def modularity(timestamp=None): output.important('\nCalculating graph modularity' + get_timestamp_sting(timestamp) + '...') graph_tool_graph = graph if timestamp is not None: output.normal('\nCreating a graph copy and purging filtered edges') graph_tool_graph = graph.copy() graph_tool_graph.purge_edges() graph_tool_graph.purge_vertices() output.normal('Created graph copy and purged filtered edges') output.normal('\nSaving graph as file...') filepath = get_timestamp_path(graph_path, timestamp, '.graphml') graph_tool_graph.save(filepath) output.normal('Saved graph to "' + filepath + '"') output.normal('\nLoading saved graph into igraph...') igraph_graph = igraph.Graph.Read_GraphML(filepath) igraph_graph.to_undirected() output.normal('Loaded graph into igraph') output.normal( '\nGenerating partitions with igraph using Louvain\'s algorithm...') partitions = graph_partitions(igraph_graph) output.normal('Calculated graph partitions') output.normal( '\nCalculating modularity using igraph and calculated partitions...') modularity = graph_modularity(igraph_graph, partitions) output.success('Graph modularity' + get_timestamp_sting(timestamp) + ': ' + str(modularity))
def degree(timestamp=None): output.important('\nGathering graph degree information' + get_timestamp_sting(timestamp) + '...') degree_dataframe = graph_degree(graph) output.normal('Gathered degree information.') output.normal('Sorting for in degree...') in_degree_sorted = sort_for_in_degree(degree_dataframe) output.normal('\n10 nodes with the highest in degree' + get_timestamp_sting(timestamp) + ':') output.normal(in_degree_sorted.head(10)) output.normal('\nSorting for out degree...') out_degree_sorted = sort_for_out_degree(degree_dataframe) output.normal('\n10 nodes with the highest out degree' + get_timestamp_sting(timestamp) + ':') output.normal(out_degree_sorted.head(10)) output.normal('\nSorting for degree sum...') sum_degree_sorted = sort_for_degree_sum(degree_dataframe) output.normal('\n10 nodes with the highest degree sum' + get_timestamp_sting(timestamp) + ':') output.normal(sum_degree_sorted.head(10)) output.normal('\nWriting degree information to file...') data.dataframe_to_csv(sum_degree_sorted, get_timestamp_path(degree_path, timestamp), True) output.success('Saved degree information to "' + get_timestamp_path(degree_path, timestamp) + '"')
def loadModules(): output.info("Loading Modules...") global modules for name in os.listdir('modules'): if os.path.isdir(os.path.join('modules', name)) and os.path.isfile( os.path.join('modules', name) + '/module.json'): modules.append(name) output.success("Found " + str(len(modules)) + " Modules")
def main(): global PBon global PBobj PB="" thread = Thread(target = op.thread_func, args = (t_stop,)) thread.start() while True: options = ["Choose one of the following"] options.append("Cricket Scores") options.append("Coding Contest Updates") options.append("Tweets") options.append("Custom Notification with user defined frequency") options.append("Remove any set notification") if(PB == ""): options.append("Want Notifications on Your PushBullet Devices? Enter Access Token here.") PBon = 0 else: options.append("PushBullet Device Set Up Successfully. Want to remove the Access Token?") PBon = 1 options.append("Quit") try: optionChosen = ip.getUserInput(options) except KeyboardInterrupt: exitApp() if optionChosen == len(options)-1: exitApp() if(optionChosen == len(options) -2): if(PB == ""): PB=ip.inputData("PushBullet","Enter Valid Access Token") if PB != "": try: PBobj=Pushbullet(PB) PBon = 1 op.popUp("Notify","Successfull Setup",1) except Exception as e: op.popUp("PushBullet","Wrong Access Token or Network Error\nTry Again",0) PB="" else: op.success() PB="" continue if(optionChosen == 1): cricket.main() if(optionChosen == 2): coding.main() if(optionChosen == 3): tweet.main() if(optionChosen == 4): custom.getData() if(optionChosen == 5): remove.main()
def pagerank(timestamp=None): output.important('\nCalculating graph pageranks' + get_timestamp_sting(timestamp) + '...') pagerank_dataframe = graph_pagerank(graph) output.normal('Calculated pageranks.') output.normal('\n10 nodes with the highest pagerank' + get_timestamp_sting(timestamp) + ':') output.normal(pagerank_dataframe.head(10)) output.normal('\nWriting pagerank results to file...') data.dataframe_to_csv(pagerank_dataframe, get_timestamp_path(pagerank_path, timestamp), True) output.success('Saved pagerank results to "' + get_timestamp_path(pagerank_path, timestamp) + '"')
def main_quick(): "Fast payload generation using command line arguments" init(autoreset=True) javaCheck() output.cls() output.banner() loadModules() # # format: ./PyDuck.py <module> <duck_drive> [list of attributes in format] # format of attributes: attribute=value # global loadedModule global moduleAttributes modulename = sys.argv[1] if modulename in modules: if os.path.isfile('modules/' + modulename + '/module.json'): with open('modules/' + modulename + '/module.json', 'r') as module: module_content = module.read().replace('\n', '') loadedModule = json.loads(module_content) moduleAttributes = loadedModule['attributes'] # add default attributes: lang,drive moduleAttributes['language'] = 'us' moduleAttributes['sdcard_mount'] = sys.argv[2] attr_args = [] if len(sys.argv) > 3: for i in range(3, len(sys.argv)): attr_args.append(sys.argv[i]) # check for uac bypass and add attribute if loadedModule['requirements']['has_uac_bypass'].lower( ) == "true": moduleAttributes['uac_bypass_key'] = 'y' for a in attr_args: sep = a.split('=') if sep[0] in moduleAttributes: output.success("Setting " + sep[0] + " to " + sep[1]) moduleAttributes[sep[0]] = sep[1] else: output.error("Attribute " + sep[0] + " not found..exiting") sys.exit(1) cmdUseGenerate(modulename) else: output.error("Module '" + modulename + "' does not exist") else: output.error("Module '" + modulename + "' does not exist")
def eigenvector(timestamp=None): output.important('\nCalculating graph eigenvectors' + get_timestamp_sting(timestamp) + '...') eigenvalue, eigenvector_dataframe = graph_eigenvector(graph) output.normal('Calculated eigenvectors.') output.dim('Largest eigenvalue' + get_timestamp_sting(timestamp) + ': ' + str(eigenvalue)) output.normal('\n10 nodes with the highest eigenvector' + get_timestamp_sting(timestamp) + ':') output.normal(eigenvector_dataframe.head(10)) output.normal('\nWriting eigenvector results to file...') data.dataframe_to_csv(eigenvector_dataframe, get_timestamp_path(eigenvector_path, timestamp), True) output.success('Saved eigenvector results to "' + get_timestamp_path(eigenvector_path, timestamp) + '"')
def cmdUseSet(cmd): params = cmd.split(" ") if len(params) < 3: output.error('Command Syntax => set <attribute> <value>') else: global moduleAttributes if params[1] in moduleAttributes: joined = params[2] if len(params) > 3: #add other after a space eg set text Hello World # so we add the World at the end for p in range(3, len(params)): joined += " " + params[p] moduleAttributes[params[1]] = joined output.success(params[1] + '=>' + joined) else: output.error("Attribute '" + params[1] + "' is unknown")
def betweenness_centrality(timestamp=None): output.important('\nCalculating betweenness centralities' + get_timestamp_sting(timestamp) + '...') nodes, edges = graph_betweenness_centrality(graph) output.normal( 'Calculated betweenness centralities for both edges and nodes.') output.normal('\n10 nodes with the highest betweenness centrality' + get_timestamp_sting(timestamp) + ':') output.normal(nodes.head(10)) output.normal('\n10 edges with the highest betweenness centrality' + get_timestamp_sting(timestamp) + ':') output.normal(edges.head(10)) output.normal('\nWriting betweenness centralities to file..') data.dataframe_to_csv( nodes, get_timestamp_path(nodes_betweenness_path, timestamp), True) output.success('Saved nodes betweenness centrality information to "' + get_timestamp_path(nodes_betweenness_path, timestamp) + '"') data.dataframe_to_csv( edges, get_timestamp_path(edges_betweenness_path, timestamp), True) output.success('Saved edges betweenness centrality information to "' + get_timestamp_path(edges_betweenness_path, timestamp) + '"')
def success(): unnamed_keys = sum(1 for key in _keys if len(key) == 5 or key[-1] is None) field_width = len(str(unnamed_keys)) auto_name = (f"{_default_key_name}_{c:0{field_width}}" for c in count()) for key in _keys: if not isinstance(key, (tuple, list)) or len(key) not in (5, 6): raise ValueError("Bad key '{}'".format(key)) if len(key) == 5 or key[-1] is None: key = (*key[:5], next(auto_name)) print("k:{}".format(",".join( str(x) if x is not None else "" for x in key))) for cleartext in _cleartexts: if isinstance(cleartext, int): text, textname = str(cleartext), "" elif isinstance(cleartext, tuple): text, textname = cleartext text = str(text) textname = textname if textname is not None else "" else: raise ValueError("Bad cleartext '{}'".format(cleartext)) print("c:{},{}".format(text, textname)) output.success("{} attack succeeded".format(name)) sys.exit(0)
def handleCommand(cmd): global loadedModule #output.info cmd if cmd[:4] == "info": cmdinfo(cmd) #list modules elif cmd[:7] == "modules" and len(cmd) == 7: cmdList() elif (cmd[:4] == "exit" or cmd[:4] == "quit") and len(cmd) == 4: output.success('KTHXBYE') sys.exit() elif cmd[:4] == "help" and len(cmd) == 4: cmdHelp(False) elif cmd[:3] == "cls" and len(cmd) == 3: output.cls() elif cmd[:5] == "clear" and len(cmd) == 5: output.cls() else: if cmd in modules: cmdUse(cmd) else: output.error('Unknown Command => ' + cmd) startShell()
def init(attack_name, default_key_name, *, min_keys=1, min_ciphertexts=0, deduplicate=None): global name, _default_key_name name = attack_name _default_key_name = default_key_name def excepthook(exctype, value, traceback): if exctype in (KeyboardInterrupt, RuntimeError): sys.exit(2) else: sys.__excepthook__(exctype, value, traceback) sys.excepthook = excepthook ciphertexts = [] keys = [] color = "auto" with open(sys.argv[1], "r", encoding="ascii") as f: for line in f: line = line.strip() if not line or line.isspace(): continue kind, _, line = line.partition(":") if kind == "k": n, e, keyname = line.split(",", maxsplit=2) keys.append((int(n), int(e), keyname or None)) elif kind == "c": text, textname = line.split(",", maxsplit=1) ciphertexts.append((int(text), textname)) elif kind == "C": color = line.strip() else: raise ValueError( "Unexpected input type '{}' from input file".input(kind)) output.init(color) if deduplicate: if deduplicate in ("n", "ns"): cmp_key = itemgetter(0) elif deduplicate == "keys": cmp_key = itemgetter(0, 1) else: raise ValueError( "Bad value for deduplicate argument '{}'".format(deduplicate)) keys = {cmp_key(key): key for key in reversed(keys)} keys = list(keys.values()) keys.reverse() if len(keys) < min_keys: fail( "This attack needs at least {} distinct keys".format(min_keys)) else: if len(keys) < min_keys: fail("This attack needs at least {} keys".format(min_keys)) if len(ciphertexts) < min_ciphertexts: fail("This attack needs at least {} ciphertexts".format( min_ciphertexts)) output.success("{} attack started".format(name)) return ciphertexts, keys
def cmdUseGenerate(modulename): #read the duckyscript and replace the uac key if needed global moduleAttributes ducky = moduleAttributes['sdcard_mount'] suffix = "/" if os.name == 'nt': suffix = "\\" if not ducky.endswith(suffix, len(ducky) - 1, len(ducky)): if os.name == 'nt': ducky = ducky + "\\" else: ducky = ducky + "/" lang = moduleAttributes['language'] moduleAttributes.pop('sdcard_mount', None) moduleAttributes.pop('language', None) output.info("Reading duckyscript.txt") tmpduckyscript = '' with open('modules/' + modulename + '/duckyscript.txt', 'r') as script: if loadedModule['requirements']['has_uac_bypass'].lower() == "true": #now replace the uac key output.info("Replacing <uac_bypass_key>") tmpduckyscript = script.read().replace( '<uac_bypass_key>', moduleAttributes['uac_bypass_key']) output.success("Replacing <uac_bypass_key> key... Done!") #pop uac_bypass_key moduleAttributes.pop('uac_bypass_key', None) else: output.info("No UAC Bypass needed") tmpduckyscript = script.read() for key, value in moduleAttributes.items(): output.info("Replacing <" + key + "> with " + value) tmpduckyscript = tmpduckyscript.replace('<' + key + '>', value) output.info("Writing temporary duckyscript...") with open('tmp.duckyscript', 'w') as w: w.write(tmpduckyscript) output.success("Writing temporary duckyscript...Done!") output.info("Generating inject.bin...") # Generate the inject.bin encoderPath = "encoder/encoder.jar" inputFlag = "-i tmp.duckyscript" outputFlag = "-o inject.bin" langFlag = "-l " + lang fullExecCommand = "java -jar " + encoderPath + " " + inputFlag + " " + outputFlag + " " + langFlag result = subprocess.check_output(fullExecCommand, stderr=subprocess.STDOUT, shell=True) result = result.decode("utf-8") print(result) output.success("Generating inject.bin...Done!") os.remove("tmp.duckyscript") if "folders" in loadedModule['requirements']: output.info("Creating the necessary folders...") for folder in loadedModule['requirements']['folders']: if os.path.exists(ducky + folder): shutil.rmtree(ducky + folder) time.sleep(2) os.makedirs(ducky + folder) output.success("Creating the necessary folders...Done!") else: output.info("No folder creation needed") if "files" in loadedModule['requirements']: output.info("Copying files...") for ffile in loadedModule['requirements']['files']: if os.path.isfile(ducky + ffile): os.remove(ducky + ffile) time.sleep(2) shutil.copyfile('modules/' + modulename + '/' + ffile, ducky + ffile) output.success("Copying files...Done!") else: output.info("No file copying needed") output.info("Copying inject.bin to Ducky...") shutil.copyfile('inject.bin', ducky + "inject.bin") time.sleep(2) os.remove("inject.bin") output.success("Copying inject.bin to Ducky...Done!") print('') output.success("Thanks 4 shopping with PyDuckGen") sys.exit()
def cmdList(): global modules print('\n > Loaded Modules\n--------------------------------------') for module in modules: output.success(module)
def reciprocity(timestamp=None): output.important('\nCalculating edge reciprocity' + get_timestamp_sting(timestamp) + '...') output.success('Edge reciprocity' + get_timestamp_sting(timestamp) + ': ' + str(graph_reciprocity(graph)))
# If no file was selected, exit if filename == '': output.error('No data file selected, exiting...') exit() if TEST: # Create a random graph output.important('Creating a random connected graph with 100 nodes') graph = random_graph() else: # Read the graph output.important('Reading graph data from "' + filename + '"...') graph = datafile_to_graph(filename) # Output graph info output.success('\nSuccessfully read graph. Info:') output.dim(str(graph.num_edges()) + " edges") output.dim(str(graph.num_vertices()) + " vertices") # Returns the filename for a file with a given timestamp def get_timestamp_path(path, timestamp=None, postfix='.csv'): if timestamp is None: return path + '.static' + postfix else: return path + '.' + str(timestamp) + postfix # Generates a timestamp string depending on the existence timestamp def get_timestamp_sting(timestamp=None): timestamp_string = ''