simpliFiRE.IDAscope / idascope / widgets / FunctionInspectionWidget.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
#!/usr/bin/python
########################################################################
# Copyright (c) 2012
# Daniel Plohmann <daniel.plohmann<at>gmail<dot>com>
# Alexander Hanel <alexander.hanel<at>gmail<dot>com>
# All rights reserved.
########################################################################
#
#  This file is part of IDAscope
#
#  IDAscope is free software: you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful, but
#  WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#  General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see
#  <http://www.gnu.org/licenses/>.
#
########################################################################

from PySide import QtGui, QtCore
from PySide.QtGui import QIcon

from NumberQTableWidgetItem import NumberQTableWidgetItem
from idascope.core.structures.FunctionContextFilter import FunctionContextFilter


class FunctionInspectionWidget(QtGui.QMainWindow):
    """
    This widget is the front-end for the semantic inspection.
    """

    def __init__(self, parent):
        QtGui.QMainWindow.__init__(self)
        print "[|] loading FunctionInspectionWidget"
        # enable access to shared IDAscope modules
        self.parent = parent
        self.name = "Function Inspection"
        self.icon = QIcon(self.parent.config.icon_file_path + "semantics.png")
        # This widget relies on the semantic identifier and uses some functions via IDA proxy
        self.si = self.parent.semantic_identifier
        self.dh = self.parent.documentation_helper
        self.ida_proxy = self.parent.ida_proxy
        # references to Qt-specific modules
        self.QtGui = QtGui
        self.QtCore = QtCore
        self.NumberQTableWidgetItem = NumberQTableWidgetItem
        self.central_widget = self.QtGui.QWidget()
        self.setCentralWidget(self.central_widget)
        self._createGui()

    def _createGui(self):
        """
        Create the main GUI with its components.
        """
        self.funcs_label = QtGui.QLabel("Functions of Interest (0/0)")
        self.calls_label = QtGui.QLabel("Selected function contains the following API references with parameters:")

        self._createToolbar()

        self._createFunctionsTable()
        self._createCallsTable()
        self._createParameterTable()

        # layout and fill the widget
        semantics_layout = QtGui.QVBoxLayout()

        function_info_widget = QtGui.QWidget()
        function_info_layout = QtGui.QHBoxLayout()
        self.function_dummy_only_cb = QtGui.QCheckBox("Only dummy names")
        self.function_dummy_only_cb.stateChanged.connect(self.populateFunctionTable)
        self.function_tag_only_cb = QtGui.QCheckBox("Only tag function")
        self.function_tag_only_cb.setCheckState(self.QtCore.Qt.Checked)
        self.function_tag_only_cb.stateChanged.connect(self.populateFunctionTable)
        function_info_layout.addWidget(self.funcs_label)
        function_info_layout.addWidget(self.function_dummy_only_cb)
        function_info_layout.addWidget(self.function_tag_only_cb)
        function_info_widget.setLayout(function_info_layout)

        upper_table_widget = QtGui.QWidget()
        upper_table_layout = QtGui.QVBoxLayout()
        upper_table_layout.addWidget(function_info_widget)
        upper_table_layout.addWidget(self.funcs_table)
        upper_table_widget.setLayout(upper_table_layout)

        calls_params_widget = QtGui.QWidget()
        calls_params_layout = QtGui.QHBoxLayout()
        calls_params_layout.addWidget(self.calls_table)
        calls_params_layout.addWidget(self.parameter_table)
        calls_params_widget.setLayout(calls_params_layout)

        lower_tables_widget = QtGui.QWidget()
        lower_tables_layout = QtGui.QVBoxLayout()
        lower_tables_layout.addWidget(self.calls_label)
        lower_tables_layout.addWidget(calls_params_widget)
        lower_tables_widget.setLayout(lower_tables_layout)

        splitter = self.QtGui.QSplitter(self.QtCore.Qt.Vertical)
        q_clean_style = QtGui.QStyleFactory.create('Plastique')
        splitter.setStyle(q_clean_style)
        splitter.addWidget(upper_table_widget)
        splitter.addWidget(lower_tables_widget)
        semantics_layout.addWidget(splitter)

        self.central_widget.setLayout(semantics_layout)

        self.populateFunctionTable()
        self.updateFunctionsLabel()

    def _createToolbar(self):
        """
        Create the toolbar, containing some of the actions that can be performed with this widget.
        """
        self._createRefreshAction()
        self._createDeepScanAction()
        self._createRenameAction()
        self._createColoringAction()
        self._createFixUnknownCodeWithProloguesAction()
        self._createFixAllUnknownCodeAction()
        self._createRenameWrappersAction()

        self.toolbar = self.addToolBar('Function Inspection Toobar')
        self.toolbar.addAction(self.refreshAction)
        self.toolbar.addAction(self.deepScanAction)
        self.toolbar.addAction(self.annotateAction)
        self.toolbar.addAction(self.toggleColorAction)
        self.toolbar.addAction(self.fixUnknownCodeWithProloguesAction)
        self.toolbar.addAction(self.fixAllUnknownCodeAction)
        self.toolbar.addAction(self.renameWrappersAction)

    def _createRefreshAction(self):
        """
        Create the refresh action for the toolbar. On activiation, it triggers a scan of I{SemanticIdentifier} and
        updates the GUI.
        """
        self.refreshAction = QtGui.QAction(QIcon(self.parent.config.icon_file_path + "scan.png"), "Refresh the " \
            + "view by scanning all named references again.", self)
        self.refreshAction.triggered.connect(self._onRefreshButtonClicked)

    def _createDeepScanAction(self):
        """
        Create the deep scan action for the toolbar. On activiation, it triggers a deep scan of I{SemanticIdentifier}
        andupdates the GUI.
        """
        self.deepScanAction = QtGui.QAction(QIcon(self.parent.config.icon_file_path + "scandeep.png"), "Refresh the " \
            + "view by deep scanning all code.", self)
        self.deepScanAction.triggered.connect(self._onDeepScanButtonClicked)

    def _createRenameAction(self):
        """
        Create the action which performs renaming of the function names in the IDB that are covered by the scan of
        the I{SemanticIdentifier}.
        """
        self.annotateAction = QtGui.QAction(QIcon(self.parent.config.icon_file_path + "tags.png"), "Rename functions " \
            + "according to the identified tags.", self)
        self.annotateAction.triggered.connect(self._onRenameButtonClicked)

    def _createColoringAction(self):
        """
        Create the action which cycles through the semantic code coloring modes via I{DocumentationHelper}.
        """
        self.toggleColorAction = QtGui.QAction(QIcon(self.parent.config.icon_file_path + "colors.png"), \
            "Toggle semantic coloring.", self)
        self.toggleColorAction.triggered.connect(self._onColoringButtonClicked)

    def _createFixUnknownCodeWithProloguesAction(self):
        """
        Create the action which fixes unknown code to functions via I{DocumentationHelper}.
        """
        self.fixUnknownCodeWithProloguesAction = QtGui.QAction(QIcon(self.parent.config.icon_file_path + "fix.png"), \
            "Fix unknown code that has a well-known function prologue to functions.", self)
        self.fixUnknownCodeWithProloguesAction.triggered.connect(self._onFixUnknownCodeWithProloguesButtonClicked)

    def _createFixAllUnknownCodeAction(self):
        """
        Create the action which fixes unknown code to functions via I{DocumentationHelper}.
        """
        self.fixAllUnknownCodeAction = QtGui.QAction(QIcon(self.parent.config.icon_file_path + "fix_all.png"), \
            "Fix all unknown code to functions.", self)
        self.fixAllUnknownCodeAction.triggered.connect(self._onFixAllUnknownCodeButtonClicked)

    def _createFixUnknownCodeAction(self):
        """
        Create the action which fixes unknown code to functions via I{DocumentationHelper}.
        """
        self.fixUnknownCodeAction = QtGui.QAction(QIcon(self.parent.config.icon_file_path + "fix.png"), \
            "Fix unknown code to functions", self)
        self.fixUnknownCodeAction.triggered.connect(self._onFixUnknownCodeButtonClicked)

    def _createRenameWrappersAction(self):
        """
        Create the action which fixes unknown code to functions via I{DocumentationHelper}.
        """
        self.renameWrappersAction = QtGui.QAction(QIcon(self.parent.config.icon_file_path + "unwrap.png"), \
            "Rename potential wrapper functions", self)
        self.renameWrappersAction.triggered.connect(self._onRenameWrappersButtonClicked)

    def _createFunctionsTable(self):
        """
        Create the top table used for showing all functions covered by scanning for semantic information.
        """
        self.funcs_table = QtGui.QTableWidget()
        self.funcs_table.clicked.connect(self._onFunctionClicked)
        self.funcs_table.doubleClicked.connect(self._onFunctionDoubleClicked)

    def _createCallsTable(self):
        """
        Create the bottom left table used for showing all identified API calls that are contained in the function
        selected in the function table.
        """
        self.calls_table = QtGui.QTableWidget()
        self.calls_table.clicked.connect(self._onCallClicked)
        self.calls_table.doubleClicked.connect(self._onCallDoubleClicked)

    def _createParameterTable(self):
        """
        Create the bottom right table used for showing all parameters for the API call selected in the calls table.
        """
        self.parameter_table = QtGui.QTableWidget()
        self.parameter_table.doubleClicked.connect(self._onParameterDoubleClicked)

################################################################################
# Rendering and state keeping
################################################################################

    def populateFunctionTable(self):
        """
        Populate the function table with information from the last scan of I{SemanticIdentifier}.
        """
        self.funcs_table.setSortingEnabled(False)
        self.funcs_header_labels = ["Address", "Name", "Blocks"]
        for tag in sorted(self.si.getTags()):
            self.funcs_header_labels.append(tag)
        self.funcs_table.clear()
        self.funcs_table.setColumnCount(len(self.funcs_header_labels))
        self.funcs_table.setHorizontalHeaderLabels(self.funcs_header_labels)
        # Identify number of table entries and prepare addresses to display
        context_filter = self._getContextFilter()
        function_addresses = self.si.getFunctionAddresses(context_filter)
        if self.ida_proxy.BAD_ADDR in function_addresses:
            self.funcs_table.setRowCount(len(function_addresses) - 1)
        else:
            self.funcs_table.setRowCount(len(function_addresses))
        self.funcs_table.resizeRowToContents(0)

        for row, function_address in enumerate(function_addresses):
            # we don't want to render entries in the table that appear because analysis failed on broken code.
            if function_address == self.ida_proxy.BAD_ADDR:
                continue
            for column, column_name in enumerate(self.funcs_header_labels):
                tmp_item = None
                if column == 0:
                    tmp_item = self.QtGui.QTableWidgetItem("0x%x" % function_address)
                elif column == 1:
                    tmp_item = self.QtGui.QTableWidgetItem(self.ida_proxy.GetFunctionName(function_address))
                elif column == 2:
                    tmp_item = self.NumberQTableWidgetItem("%d" % \
                        self.si.getNumberOfBasicBlocksForFunctionAddress(function_address))
                else:
                    tmp_item = self.NumberQTableWidgetItem("%d" % \
                        self.si.getTagCountForFunctionAddress(column_name, function_address))
                tmp_item.setFlags(tmp_item.flags() & ~self.QtCore.Qt.ItemIsEditable)
                self.funcs_table.setItem(row, column, tmp_item)
            self.funcs_table.resizeRowToContents(row)
        self.funcs_table.setSelectionMode(self.QtGui.QAbstractItemView.SingleSelection)
        self.funcs_table.resizeColumnsToContents()
        self.funcs_table.setSortingEnabled(True)
        self.updateFunctionsLabel()

    def populateCallsTable(self, function_address):
        """
        Populate the calls table based on the selected function in the functions table.
        """
        self.calls_table.setSortingEnabled(False)
        self.calls_header_labels = ["Address", "API", "Tag"]
        self.calls_table.clear()
        self.calls_table.setColumnCount(len(self.calls_header_labels))
        self.calls_table.setHorizontalHeaderLabels(self.calls_header_labels)

        if function_address is not None:
            tagged_call_contexts = self.si.getTaggedApisForFunctionAddress(function_address)
            self.calls_table.setRowCount(len(tagged_call_contexts))
            for row, tagged_call_ctx in enumerate(tagged_call_contexts):
                for column, column_name in enumerate(self.calls_header_labels):
                    if column == 0:
                        tmp_item = self.QtGui.QTableWidgetItem("0x%x" % tagged_call_ctx.address_of_call)
                    elif column == 1:
                        tmp_item = self.QtGui.QTableWidgetItem(tagged_call_ctx.called_function_name)
                    elif column == 2:
                        tmp_item = self.QtGui.QTableWidgetItem(tagged_call_ctx.tag)
                    tmp_item.setFlags(tmp_item.flags() & ~self.QtCore.Qt.ItemIsEditable)
                    self.calls_table.setItem(row, column, tmp_item)
                self.calls_table.resizeRowToContents(row)
            self.calls_table.setSelectionMode(self.QtGui.QAbstractItemView.SingleSelection)
            self.calls_table.resizeColumnsToContents()
            self.calls_table.setSortingEnabled(True)

    def populateParameterTable(self, call_address):
        """
        Populate the parameter table based on the selected API call in the calls table.
        """
        self.parameter_table.setSortingEnabled(False)
        self.parameter_header_labels = ["Address", "Type", "Name", "Value"]
        self.parameter_table.clear()
        self.parameter_table.setColumnCount(len(self.parameter_header_labels))
        self.parameter_table.setHorizontalHeaderLabels(self.parameter_header_labels)

        if call_address is not None:
            parameter_contexts = self.si.getParametersForCallAddress(call_address)
            self.parameter_table.setRowCount(len(parameter_contexts))
            for row, parameter_ctx in enumerate(parameter_contexts):
                for column, column_name in enumerate(self.parameter_header_labels):
                    if column == 0:
                        tmp_item = self.QtGui.QTableWidgetItem(parameter_ctx.getRenderedPushAddress())
                    elif column == 1:
                        tmp_item = self.QtGui.QTableWidgetItem(parameter_ctx.parameter_type)
                    elif column == 2:
                        tmp_item = self.QtGui.QTableWidgetItem(parameter_ctx.parameter_name)
                    elif column == 3:
                        tmp_item = self.QtGui.QTableWidgetItem(parameter_ctx.getRenderedValue())
                    tmp_item.setFlags(tmp_item.flags() & ~self.QtCore.Qt.ItemIsEditable)
                    self.parameter_table.setItem(row, column, tmp_item)
                self.parameter_table.resizeRowToContents(row)
            self.parameter_table.setSelectionMode(self.QtGui.QAbstractItemView.SingleSelection)
            self.parameter_table.resizeColumnsToContents()
            self.parameter_table.setSortingEnabled(True)

    def _resetLowerTables(self):
        self.calls_table.clear()
        self.calls_table.setRowCount(0)
        self.calls_header_labels = ["Address", "API", "Tag"]
        self.calls_table.setColumnCount(len(self.calls_header_labels))
        self.calls_table.setHorizontalHeaderLabels(self.calls_header_labels)
        self.parameter_table.clear()
        self.parameter_table.setRowCount(0)
        self.parameter_header_labels = ["Address", "Type", "Name", "Value"]
        self.parameter_table.setColumnCount(len(self.parameter_header_labels))
        self.parameter_table.setHorizontalHeaderLabels(self.parameter_header_labels)

    def updateFunctionsLabel(self):
        context_filter = self._getContextFilter()
        num_displayed_functions = len(self.si.getFunctionAddresses(context_filter))
        self.funcs_label.setText("Functions of Interest (%d/%d)" %
            (num_displayed_functions, self.si.calculateNumberOfFunctions()))

    def _getContextFilter(self):
        context_filter = FunctionContextFilter()
        context_filter.display_tag_only = self.function_dummy_only_cb.isChecked()
        context_filter.display_tag_only = self.function_tag_only_cb.isChecked()
        return context_filter

################################################################################
# Button actions
################################################################################

    def _onRenameButtonClicked(self):
        """
        Action for renaming functions when the rename action from the toolbar is activated.
        """
        self.si.renameFunctions()
        self._onRefreshButtonClicked()

    def _onRefreshButtonClicked(self):
        """
        Action for refreshing the window data by performing another scan of I{SemanticIdentifier}.
        """
        self.si.scanByReferences()
        self.populateFunctionTable()
        self._resetLowerTables()

    def _onDeepScanButtonClicked(self):
        """
        Action for refreshing the window data by performing a deep scan of I{SemanticIdentifier}.
        """
        self.si.scan()
        self.populateFunctionTable()
        self._resetLowerTables()

    def _onColoringButtonClicked(self):
        """
        Action for performing semantic coloring of instructions.
        """
        self.dh.colorize(self.si.getLastScanResult())

    def _onFixUnknownCodeWithProloguesButtonClicked(self):
        """
        Action for fixing unknown parts of code (red in address bar) to functions.
        """
        self.dh.convertNonFunctionCodeWithPrologues()

    def _onFixAllUnknownCodeButtonClicked(self):
        """
        Action for fixing unknown parts of code (red in address bar) to functions.
        """
        self.dh.convertNonFunctionCode()

    def _onRenameWrappersButtonClicked(self):
        """
        Action for renaming potential wrapper functions to the wrapped API if they have a dummy name.
        """
        self.si.renamePotentialWrapperFunctions()

    def _onFunctionClicked(self, mi):
        """
        If a function in the functions table is clicked, the view of the calls and parameter table are updated.
        """
        clicked_function_address = int(self.funcs_table.item(mi.row(), \
            0).text(), 16)
        self.populateCallsTable(clicked_function_address)

    def _onFunctionDoubleClicked(self, mi):
        """
        If a function in the functions table is doubleclicked, IDA View is located to the corresponding address.
        """
        clicked_function_address = self.funcs_table.item(mi.row(), 0).text()
        self.ida_proxy.Jump(int(clicked_function_address, 16))

    def _onCallClicked(self, mi):
        """
        If an API call in the calls table is clicked, the view of the parameter table is updated.
        """
        clicked_function_address = int(self.calls_table.item(mi.row(), \
            0).text(), 16)
        self.populateParameterTable(clicked_function_address)

    def _onCallDoubleClicked(self, mi):
        """
        If an API in the calls table is doubleclicked, IDA View is located to the corresponding address.
        """
        if mi.column() == 1:
            for widget in self.parent.idascope_widgets:
                if widget.name == "WinAPI Browsing":
                    widget.navigate(self.calls_table.item(mi.row(), mi.column()).text())
                    self.parent.setTabFocus("WinAPI Browsing")
        else:
            clicked_function_address = self.calls_table.item(mi.row(), 0).text()
            self.ida_proxy.Jump(int(clicked_function_address, 16))

    def _onParameterDoubleClicked(self, mi):
        """
        If a parameter in the parameter table is doubleclicked, IDA View is located to the corresponding address.
        """
        clicked_function_address = self.parameter_table.item(mi.row(), 0).text()
        self.ida_proxy.Jump(int(clicked_function_address, 16))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.