def execute(self, api: Api): want_to_continue = api.ask_user( "Warning", "This plugin may replace some of your comments, continue?") if not want_to_continue: return trace_data = api.get_trace_data() trace = api.get_visible_trace() for i, t in enumerate(trace): if 'mem' in t and t['mem']: comment = "" for mem in t['mem']: addr = hex(mem['addr']) value = mem['value'] if mem['access'] == "READ": comment += f"[{ addr }] -> { hex(value) } " elif mem['access'] == "WRITE": comment += f"[{ addr }] <- { hex(value) } " if 0x20 <= value <= 0x7e: comment += f"'{ chr(value) }' " # Add comment to full trace row = t["id"] trace_data.trace[row]['comment'] = comment # Add comment to visible trace too because it could be filtered_trace trace[i]['comment'] = comment api.update_trace_table()
def execute(self, api: Api): self.api = api max_distance = api.get_string_from_user( "Max distance", f"Give a max distance between addresses, leave empty for default ({DEFAULT_MAX_DISTANCE})", ) try: max_distance = int(max_distance) except ValueError: max_distance = DEFAULT_MAX_DISTANCE self.init_gui() trace = api.get_visible_trace() row_id_min = sys.maxsize row_id_max = 0 data_reads = [] data_writes = [] addresses = set() # get all memory accesses from trace for t in trace: if t["mem"]: if t["id"] > row_id_max: row_id_max = t["id"] if t["id"] < row_id_min: row_id_min = t["id"] for mem in t["mem"]: if mem["access"] == "READ": data_reads.append({"x": t["id"], "y": mem["addr"]}) elif mem["access"] == "WRITE": data_writes.append({"x": t["id"], "y": mem["addr"]}) addresses.add(mem["addr"]) # convert a set to sorted list addresses = sorted(addresses) # convert mem addresses to indexes (0..x) new_index = 0 addr_indexes = {} i = 0 for (i, addr) in enumerate(addresses): if i > 0: if abs(addr - addresses[i - 1]) > max_distance: new_index += max_distance addr_indexes[addr] = new_index + i addr_max = new_index + i # replace addresses with indexes for d in data_reads: d["y"] = addr_indexes[d["y"]] for d in data_writes: d["y"] = addr_indexes[d["y"]] self.plot_item.setXRange(row_id_min, row_id_max, padding=0) self.plot_item.setYRange(1, addr_max, padding=0) self.scatter_plot_reads.setData(data_reads) self.scatter_plot_writes.setData(data_writes)
def execute(self, api: Api): api.print('') bookmarks = api.get_selected_bookmarks() for b in bookmarks: rows = "{:<13}".format(f"{b.startrow} - {b.endrow}") addr = "{:<12}".format(b.addr) disasm = "{:<20}".format(b.disasm) api.print(f"{rows} {addr} {disasm} ; {b.comment}")
def execute(self, api: Api): input_dlg_data = [ { "label": "Memory address", "data": "0x0" }, { "label": "Size", "data": 2000 }, { "label": "Access types", "data": ["Reads and writes", "Reads", "Writes"] }, { "label": "Source trace", "data": ["Full trace", "Filtered trace"] }, ] options = api.get_values_from_user("Filter by memory address", input_dlg_data) if not options: return addr, size, access_types, trace_id = options addr = self.str_to_int(addr) print( f"Filtering by mem address: from {hex(addr)} to {hex(addr+size)}") if trace_id == 0: trace = api.get_full_trace() else: trace = api.get_filtered_trace() result_trace = [] for t in trace: for mem in t["mem"]: if mem["access"].upper() == "READ" and access_types == 2: continue elif mem["access"].upper() == "WRITE" and access_types == 1: continue if addr <= mem["addr"] <= (addr + size): result_trace.append(t.copy()) break # avoid adding the same row more than once if len(result_trace) > 0: print(f"Length of filtered trace: {len(result_trace)}") api.set_filtered_trace(result_trace) api.show_filtered_trace() else: api.show_messagebox( "Error", "Could not find any rows accessing given memory area")
def execute(self, api: Api): api.print("") bookmarks = api.get_selected_bookmarks() for b in bookmarks: if b.startrow is not b.endrow: rows = "{:<13}".format(f"{b.startrow} - {b.endrow}") else: rows = "{:<13}".format(f"{b.startrow}") addr = "{:<16}".format(b.addr) disasm = "{:<33}".format(b.disasm) api.print(f"{rows} {addr} {disasm} ; {b.comment}")
def __init__(self, config): Api.__init__(self, config) self.functions = { 'add': self.addSubDomain, 'delete': self.deleteSubDomain, 'get': self.getSubDomain, 'list': self.listSubDomain, 'verify': self.verifySubDomain, 'update': self.updateSubDomain, 'addRecord': self.addRecord, 'deleteRecord': self.deleteRecord, 'updateRecord': self.updateRecord, 'verifyRecord': self.verifyRecord }
def execute(self, api: Api): self.api = api input_dlg_data = [ {"label": "Memory address", "data": "0x0"}, {"label": "Size", "data": 2000}, {"label": "Source trace", "data": ["Full trace", "Filtered trace"]}, {"label": "Memory operations", "data": ["Reads", "Writes"]}, {"label": "Byte order", "data": ["Little endian", "Big endian"]}, ] options = api.get_values_from_user("Data visualizer", input_dlg_data) if not options: return self.address, self.mem_size, trace_id, mem_op, byte_order = options self.address = self.str_to_int(self.address) if trace_id == 0: trace = api.get_full_trace() else: trace = api.get_filtered_trace() if not trace: print("Plugin error: empty trace.") return if mem_op == 0: self.mem_op = "READ" else: self.mem_op = "WRITE" if byte_order == 0: self.byteorder = "little" else: self.byteorder = "big" self.color_counter = 0 self.address_colors = {} self.show_first_mem_access = True data = self.prepare_data(trace) self.show_hex_window(data)
def __init__(self, parent=None): """Inits MainWindow, UI and plugins""" super(MainWindow, self).__init__(parent) self.api = Api(self) self.trace_data = TraceData() self.filtered_trace = [] self.init_plugins() self.init_ui() if len(sys.argv) > 1: self.open_trace(sys.argv[1])
def home(request): api = Api(request) categories = ( {'name':_('Last Releases'), 'api':local.API_URL_LAST, 'link':'last_releases'}, {'name':_('Upcoming'), 'api':local.API_URL_UPCOMING, 'link':'upcomming'}, {'name':_('Popular'), 'api':local.API_URL_POPULAR, 'link':'popular'}, {'name':_('Top Rated'), 'api':local.API_URL_TOPRATED, 'link':'top_rated'}, ) params = { 'api_key' : local.API_KEY, 'language': request.LANGUAGE_CODE } featured = None for category in categories: result = api.get(category['api'], params) items = result.get('results', []) for item in items: try: item['year'] = datetime.strptime(item.get('release_date'), '%Y-%m-%d').year except Exception as e: # pass raise Exception(e) category['items'] = items if category['link'] == 'popular': featured = items[:5] context = { 'app': 'home', 'featured' : featured, 'categories': categories, } return render(request, 'home.html', context)
def detail(request, id): api = Api(request) params = { 'api_key' : local.API_KEY, 'language' : request.LANGUAGE_CODE, 'append_to_response': 'videos,images,similar' } item = api.get(local.API_URL_MOVIE % id, params) if item: # Passar o release_date para datetime try: item['release_date_dt'] = datetime.strptime(item.get('release_date'), '%Y-%m-%d').date() except Exception as e: pass # Passar o runtime para datetime runtime = item.get('runtime') if type(runtime) == int: ttime = runtime / 60, runtime % 60 item['runtime_dt'] = time(ttime[0], ttime[1]) # Passar o release_date dos sililares para datetime similars = item.get('similar', {}).get('results', []) for similar in similars: try: similar['year'] = datetime.strptime(similar.get('release_date'), '%Y-%m-%d').year except Exception as e: #pass raise Exception(e) context = { 'app' : 'detail', 'item': item, } return render(request, 'detail.html', context)
def search(request, query): api = Api(request) try: page = int(request.GET.get('p', 1)) safe = int(request.GET.get('safe', 1)) except Exception as e: raise Exception(e) params = { 'api_key' : local.API_KEY, 'language' : request.LANGUAGE_CODE, 'page' : page, 'include_adult': False if safe else True, 'query' : query, } result = api.get(local.API_URL_SEARCH, params) items = result.get('results', []) # Converte a data para datetime e retorna o ano for item in items: try: item['year'] = datetime.strptime(item.get('release_date'), '%Y-%m-%d').year except Exception as e: pass #raise Exception(e) context = { 'app' : 'search', 'search': query, 'page' : page, 'safe' : safe, 'items' : result.get('results'), 'total_items': result.get('total_results'), 'total_pages': result.get('total_pages'), } return render(request, 'search.html', context)
def execute(self, api: Api): trace_data = api.get_trace_data() trace = api.get_selected_trace() if not trace: print('PluginPrintRows error: Nothing selected.') return api.print('') row_id_digits = len(str(trace[-1]['id'])) for t in trace: ip = hex(trace_data.get_instruction_pointer(t['id'])) api.print('{:<{}} '.format(t['id'], row_id_digits) + ' %s ' % ip + ' {:<42}'.format(t['disasm']) + '; %s' % t['comment'])
def execute(self, api: Api): trace_data = api.get_trace_data() trace = api.get_selected_trace() if not trace: print("PluginPrintRows error: Nothing selected.") return api.print("") row_id_digits = len(str(trace[-1]["id"])) for t in trace: ip = hex(trace_data.get_instruction_pointer(t["id"])) api.print("{:<{}} ".format(t["id"], row_id_digits) + " %s " % ip + " {:<42}".format(t["disasm"]) + "; %s" % t.get("comment", ""))
from flask import Flask from flask_redis import FlaskRedis from core.api import Api from core.config import runtime_config from core.resources.smoke import SmokeResource from core.resources.resources import Login, SessionDetails app = Flask(__name__) app.config.from_object(runtime_config()) api = Api(app, prefix='/auth') api.add_resource(Login, '/login') api.add_resource(SessionDetails, '/sid') api.add_resource(SmokeResource, '/smoke') redis_client = FlaskRedis() redis_client.init_app(app)
from core.services.connection import get_connection app = Flask(__name__) app.config.from_object(runtime_config()) @app.before_request def open_session(): g.conn = get_connection() session = sessionmaker() session.configure(bind=g.conn) g.session = session() @app.teardown_request def close_session(e): if 'session' in g: if e is None: g.session.commit() else: g.session.rollback() g.session.close() g.session = None api = Api(app, prefix='/mono-statistics') api.add_resource(SmokeResource, '/smoke') api.add_resource(UsersResource, '/users') api.add_resource(UserResource, '/users/<uuid:user_id>')
def execute(self, api: Api): addr_and_size = api.get_values_from_user( "Filter by memory address", "Give me memory address and size, separated by comma:" ) if not addr_and_size or len(addr_and_size) != 2: print('Error. Wrong values given') return addr, size = addr_and_size api.print(f"Filtering by mem access addr: from {hex(addr)} to {hex(addr+size)}") trace = api.get_visible_trace() filtered_trace = [] for t in trace: for mem in t['mem']: if addr <= mem['addr'] <= (addr + size): filtered_trace.append(t.copy()) continue trace_len = len(filtered_trace) if trace_len > 0: api.print(f"Length of filtered trace: {trace_len}") api.set_filtered_trace(filtered_trace) api.show_filtered_trace() else: api.print("Filter plugin resulted in empty trace")
from core.api import Api from modules.projects.api import ProjectResource from modules.profiles.api import ProfileResource from modules.memberships.api import MembershipResource v1_api = Api(api_name='1.0') v1_api.register(ProjectResource()) v1_api.register(ProfileResource()) v1_api.register(MembershipResource())
def test_simple_get2(): response = Api.send_get() assert response.status_code == 200
def execute(self, api: Api): api.print('----------------------------------') bookmarks = api.get_bookmarks() if not bookmarks: api.print('No bookmarks found.') return for b in bookmarks: row = '{:<8}'.format(b.startrow) api.print(row + '{:<20}'.format(b.disasm) + '; %s' % b.comment) api.print('') addresses = {} for b in bookmarks: if b.addr in addresses: addresses[b.addr] += 1 else: addresses[b.addr] = 1 addresses = sorted(addresses.items(), key=itemgetter(1), reverse=True) api.print('Duplicate bookmarks:') api.print('Address | count | start row') for address, count in addresses: # [:15] b_rows = [] for b in bookmarks: if address == b.addr: b_rows.append(b.startrow) b_rows_str = ' '.join(map(str, b_rows)) api.print('%s | %d | %s' % (address, count, b_rows_str)) api.print('') api.print('%d bookmarks total.' % len(bookmarks)) api.print('%d unique bookmarks.' % len(addresses)) lengths = [] for b in bookmarks: lengths.append(b.endrow - b.startrow + 1) avg_len = sum(lengths) / len(bookmarks) shortest = min(lengths) longtest = max(lengths) api.print('Average length of bookmark: %d' % avg_len) api.print('Longest: %d Shortest: %d' % (longtest, shortest))
import argparse import logging from core.api import Api from core.scraper import Scraper if __name__ == '__main__': logging.basicConfig(level=logging.INFO) ap = argparse.ArgumentParser() ap.add_argument('-t', '--token', required=True, help='A valid application token') ap.add_argument('-o', '--output-directory', default='./workouts', help='A directory where the downloaded workouts will be stored') args = vars(ap.parse_args()) api = Api(args['token']) scraper = Scraper(api, args['output_directory']) scraper.run()
def execute(self, api: Api): trace = api.get_visible_trace() if not trace: return api.print('') trace_data = api.get_trace_data() ip_name = trace_data.get_instruction_pointer_name() if ip_name not in trace_data.regs: api.print('Error. Unknown instruction pointer name.') return ip_index = trace_data.regs[ip_name] counts = {} for t in trace: addr = t['regs'][ip_index] if addr in counts: counts[addr] += 1 else: counts[addr] = 1 api.print('%d unique addresses executed.' % len(counts)) api.print('Top 30 executed addresses:') counts = sorted(counts.items(), key=itemgetter(1), reverse=True) for address, count in counts[:30]: api.print('%s %d ' % (hex(address), count))