├── fcatalog_client ├── __init__.py ├── tests │ ├── __init__.py │ ├── test_utils.py │ ├── test_thread_executor.py │ ├── live_server.py │ └── test_db_endpoint.py ├── utils.py ├── thread_executor.py ├── idasync.py ├── ida_ts.py ├── db_endpoint.py └── ida_client.py ├── .gitignore ├── README.md ├── fcatalog_plugin.py └── LICENSE /fcatalog_client/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | *.pyc 3 | -------------------------------------------------------------------------------- /fcatalog_client/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /fcatalog_client/utils.py: -------------------------------------------------------------------------------- 1 | 2 | def blockify(iterator,block_size): 3 | """ 4 | Given an iterator, return blocks of size block_size, except for the last 5 | block which might be shorter. 6 | """ 7 | 8 | cur_block = [] 9 | for x in iterator: 10 | cur_block.append(x) 11 | if len(cur_block) >= block_size: 12 | yield cur_block 13 | cur_block = [] 14 | 15 | # Yield the last block: 16 | if len(cur_block) > 0: 17 | yield cur_block 18 | -------------------------------------------------------------------------------- /fcatalog_client/tests/test_utils.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from fcatalog_client.utils import blockify 4 | 5 | 6 | class TestBlockify(unittest.TestCase): 7 | def test_blockify_7_3(self): 8 | """ 9 | Make blocks of size 3 from a range of size 7. 10 | """ 11 | res = [] 12 | for b in blockify(range(7),3): 13 | res.append(b) 14 | 15 | assert res == [[0,1,2],[3,4,5],[6]] 16 | 17 | def test_blockify_9_3(self): 18 | """ 19 | Test basic operation of blockify. 20 | """ 21 | res = [] 22 | for b in blockify(range(9),3): 23 | res.append(b) 24 | 25 | assert res == [[0,1,2],[3,4,5],[6,7,8]] 26 | 27 | def test_blockify_empty(self): 28 | """ 29 | Try to blockify an empty iterator: 30 | """ 31 | res = [] 32 | for b in blockify(range(0),5): 33 | res.append(b) 34 | 35 | assert len(res) == 0 36 | -------------------------------------------------------------------------------- /fcatalog_client/thread_executor.py: -------------------------------------------------------------------------------- 1 | import threading 2 | 3 | class ThreadExecutorError(Exception): pass 4 | 5 | # Thread executor. Can run only one thread at a time. 6 | class ThreadExecutor(object): 7 | def __init__(self): 8 | # Currently not running: 9 | self._is_running = False 10 | 11 | def execute(self,func,*args,**kwargs): 12 | """ 13 | Execute function in a new thread. 14 | Returns a handle to the created thread. 15 | """ 16 | if self._is_running: 17 | raise ThreadExecutorError('Already running!') 18 | 19 | self._is_running = True 20 | 21 | def worker(): 22 | # Run the function: 23 | try: 24 | func(*args,**kwargs) 25 | finally: 26 | # Mark finished running when the execution 27 | # of the function is done. 28 | self._is_running = False 29 | 30 | # Run the worker in a new thread: 31 | t = threading.Thread(target=worker) 32 | t.start() 33 | 34 | return t 35 | 36 | 37 | -------------------------------------------------------------------------------- /fcatalog_client/tests/test_thread_executor.py: -------------------------------------------------------------------------------- 1 | 2 | import unittest 3 | import time 4 | 5 | from fcatalog_client.thread_executor import \ 6 | ThreadExecutor,ThreadExecutorError 7 | 8 | 9 | class TestThreadExecutor(unittest.TestCase): 10 | def test_basic_running(self): 11 | """ 12 | Test basic operation of ThreadExecutor by running simple functions 13 | serially. 14 | """ 15 | te = ThreadExecutor() 16 | # Run a basic function: 17 | t = te.execute(lambda :True) 18 | 19 | # Wait for thread to finish: 20 | t.join() 21 | 22 | # Run another basic function (This time with an argument): 23 | t = te.execute(lambda x:x+1,5) 24 | 25 | # Wait for thread to finish: 26 | t.join() 27 | 28 | def test_already_running(self): 29 | """ 30 | Make sure that ThreadExecutor doesn't let two threads run at the same 31 | time. 32 | """ 33 | te = ThreadExecutor() 34 | 35 | def my_func(): 36 | time.sleep(0.01) 37 | 38 | # Try to run two threds at the same time: 39 | t1 = te.execute(my_func) 40 | 41 | # The second attempt to run the function should raise an exception, 42 | # because the first one is already running: 43 | with self.assertRaises(ThreadExecutorError): 44 | t2 = te.execute(my_func) 45 | 46 | # Wait for the first thread to finish: 47 | t1.join() 48 | 49 | # After the first thread has finished, we can run another one: 50 | t3 = te.execute(lambda :True) 51 | 52 | # Wait for t3 to finish execution: 53 | t3.join() 54 | 55 | 56 | -------------------------------------------------------------------------------- /fcatalog_client/idasync.py: -------------------------------------------------------------------------------- 1 | # A module that helps with writing thread safe ida code. 2 | # Taken from: 3 | # http://www.williballenthin.com/blog/2015/09/04/idapython-synchronization-decorator/ 4 | import logging 5 | 6 | import functools 7 | import idaapi 8 | 9 | import Queue 10 | 11 | class IDASyncError(Exception): pass 12 | 13 | # Important note: Always make sure the return value from your function f is a 14 | # copy of the data you have gotten from IDA, and not the original data. 15 | # 16 | # Example: 17 | # -------- 18 | # 19 | # Do this: 20 | # 21 | # @idaread 22 | # def ts_Functions(): 23 | # return list(idautils.Functions()) 24 | # 25 | # Don't do this: 26 | # 27 | # @idaread 28 | # def ts_Functions(): 29 | # return idautils.Functions() 30 | # 31 | 32 | logger = logging.getLogger(__name__) 33 | 34 | # Enum for safety modes. Higher means safer: 35 | class IDASafety: 36 | SAFE_NONE = 0 37 | SAFE_READ = 1 38 | SAFE_WRITE = 2 39 | 40 | 41 | call_stack = Queue.LifoQueue() 42 | 43 | 44 | def sync_wrapper(ff,safety_mode): 45 | """ 46 | Call a function ff with a specific IDA safety_mode. 47 | """ 48 | logger.debug('sync_wrapper: {}, {}'.format(ff.__name__,safety_mode)) 49 | 50 | if safety_mode not in [IDASafety.SAFE_READ,IDASafety.SAFE_WRITE]: 51 | error_str = 'Invalid safety mode {} over function {}'\ 52 | .format(safety_mode,ff.__name__) 53 | logger.error(error_str) 54 | raise IDASyncError(error_str) 55 | 56 | # No safety level is set up: 57 | res_container = Queue.Queue() 58 | 59 | def runned(): 60 | logger.debug('Inside runned') 61 | 62 | # Make sure that we are not already inside a sync_wrapper: 63 | if not call_stack.empty(): 64 | last_func_name = call_stack.get() 65 | error_str = ('Call stack is not empty while calling the ' 66 | 'function {} from {}').format(ff.__name__,last_func_name) 67 | logger.error(error_str) 68 | raise IDASyncError(error_str) 69 | 70 | call_stack.put((ff.__name__)) 71 | try: 72 | res_container.put(ff()) 73 | finally: 74 | call_stack.get() 75 | logger.debug('Finished runned') 76 | 77 | ret_val = idaapi.execute_sync(runned,safety_mode) 78 | res = res_container.get() 79 | return res 80 | 81 | 82 | def idawrite(f): 83 | """ 84 | decorator for marking a function as modifying the IDB. 85 | schedules a request to be made in the main IDA loop to avoid IDB corruption. 86 | """ 87 | @functools.wraps(f) 88 | def wrapper(*args,**kwargs): 89 | ff = functools.partial(f,*args,**kwargs) 90 | ff.__name__ = f.__name__ 91 | return sync_wrapper(ff,idaapi.MFF_WRITE) 92 | return wrapper 93 | 94 | def idaread(f): 95 | """ 96 | decorator for marking a function as reading from the IDB. 97 | schedules a request to be made in the main IDA loop to avoid 98 | inconsistent results. 99 | MFF_READ constant via: http://www.openrce.org/forums/posts/1827 100 | """ 101 | @functools.wraps(f) 102 | def wrapper(*args,**kwargs): 103 | ff = functools.partial(f,*args,**kwargs) 104 | ff.__name__ = f.__name__ 105 | return sync_wrapper(ff,idaapi.MFF_READ) 106 | return wrapper 107 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | FCatalog Client (IDA Plugin) 2 | ============================ 3 | 4 | This is the FCatalog Client IDA Plugin. 5 | FCatalog is the Functions Catalog. It is a tool for quickly finding similar 6 | functions from a large database of functions. 7 | 8 | You can find the [fcatalog_server repository here](https://github.com/xorpd/fcatalog_server). 9 | 10 | Requirements: 11 | ------------- 12 | 13 | - You need IDA (Interactive Disassembler by Hex Rays) installed. I tested this 14 | only on IDA of version >= 6. 15 | 16 | - Python2.7. I think that it should come together with IDA. Note that this code 17 | will not work with Python3. Sorry about that, IDA doesn't support Python3 18 | scripting yet. 19 | 20 | - I tested this only on Windows 7. It might work on linux, but also might not. 21 | 22 | - You will need a working [fcatalog_server](https://github.com/xorpd/fcatalog_server). 23 | 24 | 25 | Installation 26 | ------------ 27 | Copy the fcatalog_client directory and fcatalog_plugin.py to the plugins 28 | directory of your IDA installation. Then restart IDA. 29 | 30 | Main Functions 31 | -------------- 32 | 33 | After the installation, when you open any file with IDA you should see new menu 34 | items under the **Edit** menu: 35 | - FCatalog: Clean IDB 36 | - FCatalog: Find Similars 37 | - FCatalog: Commit Functions 38 | - FCatalog: Configure 39 | 40 | First, configure your client by clicking on **FCatalog: Configure**. A dialog 41 | box will ask you for the host and port of your FCatalog server. You will also 42 | need to specify a database name. You can pick any database name that you want. 43 | If it does not exist, it will be created automatically. 44 | 45 | **FCatalog: Commit Functions** will save all your good "reversed" functions into 46 | the remote database. Functions are considered good and "reversed" if all of the 47 | following are true: 48 | 49 | - They have a meaningful name (Any name that doesn't contain MAYBE or RELATED) 50 | - They weren't acquired from a previous 'FCatalog: Find Similars' operation. 51 | - They are long enough (At least 0x40 bytes) 52 | - They are not fragmented (Might be implemented in the future). 53 | 54 | The IDA console should show you which functions were sent to the database. 55 | 56 | **FCatalog: Find Similars** will search for every "unreversed" function inside 57 | your IDB the most similar known function from the functions catalog database. 58 | It will then rename the function according to the name from the functions 59 | catalog database. 60 | 61 | The new name will be of the format: 62 | FCATALOG__{grade}__{function_name} 63 | grade is the similarity score, between 0 and 16. 0 means not similar at all, 16 64 | means very similar. 65 | 66 | "unreversed functions" are functions that don't have any meaningful name, or 67 | they have a name picked by the fcatalog system. 68 | 69 | **FCatalog: Clean IDB** will clean your IDB from any fcatalog function names. 70 | If you suddenly got scared from all the new function names, you can always 71 | click on this button. 72 | 73 | 74 | Tests 75 | ----- 76 | There are basic offline tests in the test directory. You can run them with 77 | unittest as follows: 78 | 79 | c:\python27\python.exe -m unittest discover 80 | 81 | 82 | There is one online test (Runs against a real server). It is 83 | tests/live_server.py. It should be run as follows: 84 | 85 | c:\python27\python.exe -m fcatalog_client.tests.live_server 86 | 87 | Website 88 | ------- 89 | Visit me at http://www.xorpd.net 90 | -------------------------------------------------------------------------------- /fcatalog_client/ida_ts.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import idautils 3 | import idaapi 4 | import idc 5 | from idasync import idaread, idawrite 6 | 7 | logger = logging.getLogger(__name__) 8 | 9 | """ 10 | This module exports thread safe ida functions. 11 | The functions that begin with underscore ('_') are not thread safe. 12 | """ 13 | 14 | def _get_func_length(func_addr): 15 | """ 16 | Return function's length. 17 | """ 18 | logger.debug('_get_func_length: {}'.format(func_addr)) 19 | # First check if this is a chunked function. 20 | # If so, we abort. 21 | if _is_func_chunked(func_addr): 22 | return None 23 | # raise FCatalogClientError('Function {:X} is chunked. Can not calculate' 24 | # ' length.'.format(func_addr)) 25 | 26 | # Get the end of the function: 27 | func_end = idc.GetFunctionAttr(func_addr,idc.FUNCATTR_END) 28 | 29 | if func_end < func_addr: 30 | return None 31 | # raise FCatalogClientError('Function {:X} has end lower than start'.\ 32 | # format(func_addr)) 33 | 34 | # Calculate length and return: 35 | return func_end - func_addr 36 | 37 | get_func_length = idaread(_get_func_length) 38 | 39 | def _get_func_data(func_addr): 40 | """ 41 | Get function's data 42 | """ 43 | logger.debug('_get_func_data: {}'.format(func_addr)) 44 | func_length = _get_func_length(func_addr) 45 | if func_length is None: 46 | return None 47 | func_data = idc.GetManyBytes(func_addr,func_length) 48 | if func_data is None: 49 | return None 50 | # raise FCatalogClientError('Failed reading function {:X} data'.\ 51 | # format(func_addr)) 52 | 53 | return str(func_data) 54 | 55 | get_func_data = idaread(_get_func_data) 56 | 57 | def _get_func_comment(func_addr): 58 | """ 59 | Get Function's comment. 60 | """ 61 | # Currently not implemented: 62 | return "" 63 | 64 | # An IDA read thread safe version: 65 | get_func_comment = idaread(_get_func_comment) 66 | 67 | def _set_func_comment(func_addr,comment): 68 | """ 69 | Set function's comment. 70 | """ 71 | # Currently not implemented: 72 | pass 73 | 74 | # An IDA write thread safe version: 75 | set_func_comment = idawrite(_set_func_comment) 76 | 77 | def _Functions(): 78 | """ 79 | Thread safe IDA iteration over all functions. 80 | """ 81 | logger.debug('_Functions') 82 | return list(idautils.Functions()) 83 | 84 | Functions = idaread(_Functions) 85 | 86 | def _first_func_addr(): 87 | """ 88 | Get addr of the first function. 89 | IDA read thread safe. 90 | """ 91 | logger.debug('_first_func_addr') 92 | if not start: start = idaapi.cvar.inf.minEA 93 | if not end: end = idaapi.cvar.inf.maxEA 94 | 95 | # find first function head chunk in the range 96 | chunk = idaapi.get_fchunk(start) 97 | if not chunk: 98 | chunk = idaapi.get_next_fchunk(start) 99 | while chunk and chunk.startEA < end and (chunk.flags & idaapi.FUNC_TAIL) != 0: 100 | chunk = idaapi.get_next_fchunk(chunk.startEA) 101 | func = chunk 102 | return int(func.startEA) 103 | 104 | first_func_addr = idaread(_first_func_addr) 105 | 106 | def _GetFunctionName(func_addr): 107 | """ 108 | Should be a thread safe version of GetFunctionName. 109 | """ 110 | logger.debug('_GetFunctionName') 111 | return str(idc.GetFunctionName(func_addr)) 112 | 113 | GetFunctionName = idaread(_GetFunctionName) 114 | 115 | def _is_func_chunked(func_addr): 116 | """ 117 | Check if a function is divided into chunks. 118 | """ 119 | logger.debug('is_func_chunked {}'.format(func_addr)) 120 | # Idea for this code is from: 121 | # http://code.google.com/p/idapython/source/browse/trunk/python/idautils.py?r=344 122 | 123 | num_chunks = 0 124 | func_iter = idaapi.func_tail_iterator_t(idaapi.get_func(func_addr)) 125 | status = func_iter.main() 126 | while status: 127 | chunk = func_iter.chunk() 128 | num_chunks += 1 129 | # yield (chunk.startEA, chunk.endEA) 130 | status = func_iter.next() 131 | 132 | return (num_chunks > 1) 133 | 134 | is_func_chunked = idaread(_is_func_chunked) 135 | 136 | def _make_name(func_addr,func_name): 137 | """ 138 | Set the name of function at address func_addr to func_name. 139 | This function is IDA write thread safe. 140 | """ 141 | logger.debug('_make_name {}, {}'.format(func_addr,func_name)) 142 | idc.MakeName(func_addr,func_name) 143 | idc.Refresh() 144 | 145 | make_name = idawrite(_make_name) 146 | 147 | 148 | -------------------------------------------------------------------------------- /fcatalog_client/tests/live_server.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import sys 3 | import string 4 | import random 5 | 6 | from fcatalog_client.db_endpoint import TCPFrameClient,DBEndpoint 7 | 8 | 9 | # Length of random part of db name: 10 | RAND_PART_LENGTH = 20 11 | 12 | # Amount of hashes used for the catalog1 signature. 13 | NUM_HASHES = 16 14 | 15 | # Address of remote server: 16 | remote = None 17 | 18 | def live_test_client(): 19 | """ 20 | Test the client against a remote server of address:port remote. 21 | """ 22 | # See 23 | # http://stackoverflow.com/questions/19087189/python-unittest-testcase-object-has-no-attribute-runtest 24 | # For more info. 25 | 26 | # suite = unittest.TestSuite() 27 | # Instantiate all tests and insert then into suite: 28 | tsuites = [] 29 | for ts in tests_list: 30 | tsuites.append(\ 31 | unittest.defaultTestLoader.loadTestsFromTestCase(ts)\ 32 | ) 33 | suite = unittest.TestSuite(tsuites) 34 | unittest.TextTestRunner().run(suite) 35 | 36 | 37 | def rand_db_name(): 38 | """ 39 | Generate a random test_db name. 40 | """ 41 | rand_part = \ 42 | ''.join(random.choice(string.ascii_lowercase) for _ in \ 43 | range(RAND_PART_LENGTH)) 44 | 45 | return 'test_db_' + rand_part 46 | 47 | ########################################################################### 48 | 49 | 50 | class TestRemoteDB(unittest.TestCase): 51 | def test_basic_db_function(self): 52 | # Get a random db name: 53 | db_name = rand_db_name() 54 | frame_endpoint = TCPFrameClient(remote) 55 | dbe = DBEndpoint(frame_endpoint,db_name) 56 | 57 | 58 | # A three somewhat similar functions: 59 | func_name1 = 'func_name1' 60 | func_comment1 = 'func_comment1' 61 | func_data1 = '230948509238459238459283409582309458230945' 62 | 63 | func_name2 = 'func_name2' 64 | func_comment2 = 'func_comment2' 65 | func_data2 = '230948509218459238459223409582309458230945' 66 | 67 | func_name3 = 'func_name3' 68 | func_comment3 = 'func_comment3' 69 | func_data3 = '230948509018459238459223409280309458030945' 70 | 71 | # A very different function: 72 | func_name4 = 'func_name4' 73 | func_comment4 = 'func_comment4' 74 | func_data4 = 'kasjflkasjfdlkasjdfoiuweoriuqwioreuwqioekaskldfjaslk' 75 | 76 | dbe.add_function(func_name1,func_comment1,func_data1) 77 | dbe.add_function(func_name2,func_comment2,func_data2) 78 | dbe.add_function(func_name3,func_comment3,func_data3) 79 | dbe.add_function(func_name4,func_comment4,func_data4) 80 | 81 | # Check if the amount of returned functions is reasonable: 82 | dbe.request_similars(func_data1,1) 83 | similars = dbe.response_similars() 84 | self.assertEqual(len(similars),1) 85 | dbe.request_similars(func_data1,2) 86 | similars = dbe.response_similars() 87 | self.assertEqual(len(similars),2) 88 | dbe.request_similars(func_data1,3) 89 | similars = dbe.response_similars() 90 | self.assertEqual(len(similars),3) 91 | dbe.request_similars(func_data1,4) 92 | similars = dbe.response_similars() 93 | self.assertEqual(len(similars),3) 94 | 95 | self.assertEqual(similars[0].name,func_name1) 96 | self.assertEqual(similars[0].comment,func_comment1) 97 | self.assertEqual(similars[0].sim_grade,NUM_HASHES) 98 | 99 | # Function 2 is second place with respect to similarity to function 1: 100 | self.assertEqual(similars[1].name,func_name2) 101 | self.assertLess(similars[1].sim_grade,NUM_HASHES) 102 | # Function 3 is third place: 103 | self.assertEqual(similars[2].name,func_name3) 104 | self.assertLess(similars[2].sim_grade,NUM_HASHES) 105 | 106 | # function 4 is the only function that looks like function 4 in this 107 | # dataset: 108 | dbe.request_similars(func_data4,3) 109 | similars = dbe.response_similars() 110 | self.assertEqual(len(similars),1) 111 | self.assertEqual(similars[0].name,func_name4) 112 | 113 | dbe.close() 114 | 115 | 116 | # Check persistency of the database by opening the same one again and 117 | # running a query: 118 | frame_endpoint = TCPFrameClient(remote) 119 | dbe = DBEndpoint(frame_endpoint,db_name) 120 | 121 | dbe.request_similars(func_data1,4) 122 | similars = dbe.response_similars() 123 | self.assertEqual(len(similars),3) 124 | 125 | self.assertEqual(similars[0].name,func_name1) 126 | self.assertEqual(similars[0].comment,func_comment1) 127 | self.assertEqual(similars[0].sim_grade,NUM_HASHES) 128 | 129 | dbe.close() 130 | 131 | tests_list = [TestRemoteDB] 132 | 133 | ############################################################################ 134 | 135 | if __name__ == '__main__': 136 | if len(sys.argv) != 3: 137 | msg = ('This program tests the correctness of fcatalog client code' 138 | ' against a live server.') 139 | print(msg) 140 | print('USAGE: {} address port'.format(sys.argv[0])) 141 | exit(2) 142 | 143 | address = sys.argv[1] 144 | port = int(sys.argv[2]) 145 | 146 | # Set address of remote server: 147 | remote = (address,port) 148 | 149 | live_test_client() 150 | 151 | 152 | 153 | 154 | 155 | 156 | -------------------------------------------------------------------------------- /fcatalog_client/db_endpoint.py: -------------------------------------------------------------------------------- 1 | # A basic fcatalog client (For IDA) 2 | # By xorpd. 3 | 4 | import logging 5 | import socket 6 | import struct 7 | import collections 8 | 9 | 10 | class FCatalogClientError(Exception): pass 11 | class DeserializeError(FCatalogClientError): pass 12 | class SerializeError(FCatalogClientError): pass 13 | class NetError(FCatalogClientError): pass 14 | class DBEndpointError(FCatalogClientError): pass 15 | 16 | logger = logging.getLogger(__name__) 17 | 18 | # The possible messages for the protocol: 19 | class MsgTypes: 20 | CHOOSE_DB = 0 21 | ADD_FUNCTION = 1 22 | REQUEST_SIMILARS = 2 23 | RESPONSE_SIMILARS = 3 24 | 25 | 26 | # A similar function struct 27 | FSimilar = collections.namedtuple('FSimilar',\ 28 | ['name','comment','sim_grade']) 29 | 30 | ############################################ 31 | 32 | def len_prefix_pack(msg): 33 | """ 34 | Add a length prefix to a message 35 | """ 36 | return struct.pack('I',len(msg)) + msg 37 | 38 | def len_prefix_unpack(data): 39 | """ 40 | Unpack a message with a length prefix. 41 | Returns msg , rest_of_data 42 | """ 43 | if len(data) < 4: 44 | raise DeserializeError('data is too short to contain a length prefix') 45 | length = struct.unpack('I',data[0:4])[0] 46 | 47 | if 4 + length > len(data): 48 | raise DeserializeError('length prefix is invalid') 49 | 50 | 51 | # Return msg, rest of data: 52 | return data[4:4+length],data[4+length:] 53 | 54 | 55 | def dword_pack(dword,msg): 56 | """ 57 | Pack a buffer with a dword (4 bytes) prefix. 58 | """ 59 | return struct.pack('I',dword) + msg 60 | 61 | def dword_unpack(data): 62 | """ 63 | Unpack a message with a length prefix. 64 | returns (dword,msg) 65 | """ 66 | if len(data) < 4: 67 | raise DeserializeError('data is too short to contain a message type') 68 | dword = struct.unpack('I',data[0:4])[0] 69 | 70 | return dword,data[4:] 71 | 72 | ############################################################ 73 | 74 | 75 | def build_msg_choose_db(db_name): 76 | """ 77 | Build a CHOOSE_DB message with the given db_name. 78 | """ 79 | inner_msg = len_prefix_pack(db_name) 80 | msg = dword_pack(MsgTypes.CHOOSE_DB,inner_msg) 81 | return msg 82 | 83 | 84 | def build_msg_add_function(func_name,func_comment,func_data): 85 | """ 86 | Build an ADD_FUNCTION message with the given arguments. 87 | """ 88 | ls = [] 89 | ls.append(len_prefix_pack(func_name)) 90 | ls.append(len_prefix_pack(func_comment)) 91 | ls.append(len_prefix_pack(func_data)) 92 | inner_msg = ''.join(ls) 93 | msg = dword_pack(MsgTypes.ADD_FUNCTION,inner_msg) 94 | return msg 95 | 96 | 97 | def build_msg_get_similars(func_data,num_similars): 98 | """ 99 | Build a REQUEST_SIMILARS message with the given arguments. 100 | """ 101 | ls = [] 102 | ls.append(len_prefix_pack(func_data)) 103 | ls.append(struct.pack('I',num_similars)) 104 | inner_msg = ''.join(ls) 105 | msg = dword_pack(MsgTypes.REQUEST_SIMILARS,inner_msg) 106 | return msg 107 | 108 | 109 | def parse_msg_response_similars(msg): 110 | """ 111 | Parse a response similars messages. Raise an exception if failed. 112 | We assume that msg does not contain the message type package. 113 | """ 114 | 115 | if len(msg) < 4: 116 | raise DeserializeError('RESPONSE_SIMILARS message is too short.') 117 | 118 | # Prepare list of results: 119 | res = [] 120 | 121 | num_sims,msg = dword_unpack(msg) 122 | 123 | for _ in range(num_sims): 124 | 125 | name,msg = len_prefix_unpack(msg) 126 | comment,msg = len_prefix_unpack(msg) 127 | sim_grade,msg = dword_unpack(msg) 128 | 129 | # Build an FSimilar namedtuple: 130 | res.append(FSimilar(\ 131 | name=name,comment=comment,sim_grade=sim_grade \ 132 | )) 133 | 134 | # Return a list of FSimilars: 135 | return res 136 | 137 | 138 | ############################################################## 139 | 140 | 141 | # An abstract class for FrameEndpoint: 142 | class FrameEndpoint(object): 143 | def send_frame(self,data): 144 | """Send a frame to remote host""" 145 | raise NotImplementedError() 146 | def recv_frame(self): 147 | """Receive a frame from remote import host""" 148 | raise NotImplementedError() 149 | def close(self): 150 | """Close connection to remote host""" 151 | raise NotImplementedError() 152 | 153 | 154 | class TCPFrameClient(FrameEndpoint): 155 | def __init__(self,remote): 156 | try: 157 | self._sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 158 | self._sock.connect(remote) 159 | except socket.error as e: 160 | raise NetError('Connection to remote host failed.') 161 | # raise NetError('Connection to remote host failed.') from e 162 | 163 | def send_frame(self,data): 164 | """ 165 | Send one frame to a socket. 166 | """ 167 | try: 168 | self._sock.sendall(len_prefix_pack(data)) 169 | except socket.error as e: 170 | raise NetError('Failed sending a frame') 171 | # raise NetError('Failed sending a frame') from e 172 | 173 | def _recv_all(self,length): 174 | """ 175 | Keep waiting for bytes until bytes were received. 176 | Then return those bytes. 177 | 178 | If connection was closed, return None. 179 | If connection was closed in the middle of receiving length bytes, raise 180 | a NetError exception. 181 | """ 182 | # A list to keep the data we have received so far: 183 | data_l = [] 184 | bytes_received = 0 185 | 186 | while bytes_received < length: 187 | try: 188 | data_received = self._sock.recv(length - bytes_received) 189 | except socket.error: 190 | raise NetError('Error receiving data') 191 | if len(data_received) == 0: 192 | # Remote host has disconnected: 193 | if bytes_received == 0: 194 | return None 195 | raise NetError('Remote host closed in a middle of recv_all') 196 | bytes_received += len(data_received) 197 | data_l.append(data_received) 198 | 199 | # Combine all chunks of data received, and return them as one buffer: 200 | return "".join(data_l) 201 | 202 | 203 | def recv_frame(self): 204 | """ 205 | Get one frame from a blocking tcp socket. 206 | Every frame is prefixed with a dword of its length. 207 | """ 208 | # Receive 4 bytes: 209 | len_data = self._recv_all(4) 210 | 211 | if len_data is None: 212 | # Remote host has closed the connection: 213 | self.close() 214 | return None 215 | 216 | len_int = struct.unpack('I',len_data)[0] 217 | 218 | 219 | if len_int < 4: 220 | raise NetError('Received invalid frame from remote host') 221 | 222 | return self._recv_all(len_int) 223 | 224 | def close(self): 225 | """ 226 | Close the FrameEndpoint. 227 | """ 228 | # Do nothing if the socket is None. (Maybe we have already closed?) 229 | if self._sock is None: 230 | return 231 | 232 | try: 233 | self._sock.close() 234 | self._sock = None 235 | except socket.error: 236 | # We don't care about errors at this point. 237 | pass 238 | 239 | 240 | 241 | class DBEndpoint(object): 242 | def __init__(self,frame_endpoint,db_name): 243 | # Initialize _sock to be None: 244 | self._sock = None 245 | 246 | # Keep remote: A tuple of address and port. 247 | self._frame_endpoint = frame_endpoint 248 | 249 | # Keep db_name: 250 | self._db_name = db_name 251 | 252 | # Send a choose_db frame: 253 | self._send_choose_db(self._db_name) 254 | 255 | def close(self): 256 | """ 257 | Close connection to remote db. 258 | """ 259 | self._frame_endpoint.close() 260 | 261 | def _send_choose_db(self,db_name): 262 | """ 263 | Send a CHOOSE_DB message 264 | """ 265 | self._frame_endpoint.send_frame(build_msg_choose_db(db_name)) 266 | 267 | 268 | def add_function(self,func_name,func_comment,func_data): 269 | """ 270 | Add a function to remote database. 271 | """ 272 | self._frame_endpoint.send_frame(\ 273 | build_msg_add_function(func_name,func_comment,func_data) \ 274 | ) 275 | 276 | def request_similars(self,func_data,num_similars): 277 | """ 278 | Send a request for similar functions to remote db. 279 | Does not return any value. Use response_similars method to get the 280 | response from the server. 281 | """ 282 | self._frame_endpoint.send_frame(\ 283 | build_msg_get_similars(func_data,num_similars) \ 284 | ) 285 | 286 | def response_similars(self): 287 | """ 288 | Get back a ResponseSimilars packet. We should have sent a 289 | RequestSimilars packet previously, or else this function might wait 290 | forever. 291 | returns a list of results, each of the form FSimilar. 292 | """ 293 | # Wait for result from RequestSimilars query: 294 | frame = self._frame_endpoint.recv_frame() 295 | if frame is None: 296 | raise DBEndpointError('Remote host has closed the connection') 297 | 298 | msg_type, msg = dword_unpack(frame) 299 | if msg_type != MsgTypes.RESPONSE_SIMILARS: 300 | raise DBEndpointError('Invalid msg_type returned from server') 301 | 302 | similars = parse_msg_response_similars(msg) 303 | # if len(similars) > num_similars: 304 | # raise DBEndpointError('Amount of results exceeded requested ' 305 | # ' num_similars') 306 | 307 | return similars 308 | 309 | 310 | -------------------------------------------------------------------------------- /fcatalog_client/tests/test_db_endpoint.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import struct 3 | import socket 4 | 5 | from fcatalog_client.db_endpoint import \ 6 | MsgTypes,\ 7 | len_prefix_pack,len_prefix_unpack,dword_pack,dword_unpack,\ 8 | build_msg_choose_db,build_msg_add_function,build_msg_get_similars,\ 9 | parse_msg_response_similars,\ 10 | TCPFrameClient,FrameEndpoint, DBEndpoint,FSimilar 11 | 12 | 13 | class TestPacking(unittest.TestCase): 14 | def test_len_prefix_pack(self): 15 | """ 16 | Test len_prefix_{pack,unpack} functions. 17 | """ 18 | # Simple packing and unpacking: 19 | msg = 'Example msg' 20 | data = len_prefix_pack(msg) 21 | self.assertEqual(len(data),len(msg) + 4) 22 | msg1,data1 = len_prefix_unpack(data) 23 | 24 | self.assertEqual(msg1,msg) 25 | self.assertEqual(len(data1),0) 26 | 27 | # Dealing with extra data: 28 | extra_data = 'some extra' 29 | longer_data = data + extra_data 30 | msg2,data2 = len_prefix_unpack(longer_data) 31 | self.assertEqual(msg2,msg) 32 | self.assertEqual(data2,extra_data) 33 | 34 | def test_dword_pack(self): 35 | """ 36 | Test dword_{pack,unpack} functions. 37 | """ 38 | msg = 'This is example msg' 39 | num = 0x1337 40 | data = dword_pack(num,msg) 41 | self.assertEqual(len(data),len(msg) + 4) 42 | num1,msg1 = dword_unpack(data) 43 | 44 | self.assertEqual(num1,num) 45 | self.assertEqual(msg1,msg) 46 | 47 | 48 | class TestBuildMessages(unittest.TestCase): 49 | def test_build_msg_choose_db(self): 50 | db_name = 'my_db_name' 51 | data = build_msg_choose_db(db_name) 52 | msg_num, data = dword_unpack(data) 53 | 54 | self.assertEqual(msg_num,MsgTypes.CHOOSE_DB) 55 | self.assertEqual(struct.unpack('I',data[0:4])[0], len(db_name)) 56 | self.assertEqual(data[4:],db_name) 57 | 58 | 59 | def test_build_msg_add_function(self): 60 | func_name = 'a_function_name' 61 | func_comment = 'A comment' 62 | func_data = 'klasdjflkasjdflkjasfkljasdfasdf' 63 | # Run build_msg_add_function on some strange arguments: 64 | data = build_msg_add_function(func_name,func_comment,func_data) 65 | 66 | # Build the data myself: 67 | res = "" 68 | for d in [func_name,func_comment,func_data]: 69 | res += struct.pack('I',len(d)) 70 | res += d 71 | 72 | # Add message type: 73 | res = dword_pack(MsgTypes.ADD_FUNCTION,res) 74 | 75 | # Compare the two results: 76 | self.assertEqual(data,res) 77 | 78 | def test_build_msg_get_similars(self): 79 | func_data = 'kalsfdjaslkjfoiweuroiweurioweuriowjsdf' 80 | num_similars = 52 81 | # Run build_msg_get_similars with some arguments: 82 | data = build_msg_get_similars(func_data,num_similars) 83 | 84 | # Build the data myself: 85 | res = "" 86 | res += struct.pack('I',len(func_data)) 87 | res += func_data 88 | res += struct.pack('I',num_similars) 89 | 90 | # Add message type: 91 | res = dword_pack(MsgTypes.REQUEST_SIMILARS,res) 92 | 93 | # Compare the two results: 94 | self.assertEqual(data,res) 95 | 96 | 97 | def test_parse_msg_response_similars(self): 98 | """ 99 | Make sure that parse_msg_response_similars manages to parse a message I 100 | create. 101 | """ 102 | # Two results: 103 | name1 = 'name1' 104 | comment1 = 'comment1' 105 | sim_grade1 = 7 106 | 107 | name2 = 'name1' 108 | comment2 = 'comment1' 109 | sim_grade2 = 7 110 | 111 | msg = "" 112 | # Two records: 113 | msg += struct.pack('I',2) 114 | 115 | # First record: 116 | msg += struct.pack('I',len(name1)) 117 | msg += name1 118 | msg += struct.pack('I',len(comment1)) 119 | msg += comment1 120 | msg += struct.pack('I',sim_grade1) 121 | 122 | # Second record: 123 | msg += struct.pack('I',len(name2)) 124 | msg += name2 125 | msg += struct.pack('I',len(comment2)) 126 | msg += comment2 127 | msg += struct.pack('I',sim_grade2) 128 | 129 | similars = parse_msg_response_similars(msg) 130 | 131 | self.assertEqual(len(similars),2) 132 | self.assertEqual(similars[0].name,name1) 133 | self.assertEqual(similars[0].comment,comment1) 134 | self.assertEqual(similars[0].sim_grade,sim_grade1) 135 | 136 | self.assertEqual(similars[1].name,name2) 137 | self.assertEqual(similars[1].comment,comment2) 138 | self.assertEqual(similars[1].sim_grade,sim_grade2) 139 | 140 | 141 | ################################################################### 142 | 143 | 144 | LOCAL_PORT = 54321 145 | 146 | class TestTCPFrameClient(unittest.TestCase): 147 | def test_basic_send_recv(self): 148 | """ 149 | Test basic send/recv methods between TCPFrameClient and a sample server 150 | socket. 151 | """ 152 | 153 | # Create a listening server socket: 154 | s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 155 | # Reuse address: 156 | s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) 157 | s.bind(('',LOCAL_PORT)) 158 | s.listen(5) 159 | 160 | # Connect FrameClient to server: 161 | tfc = TCPFrameClient(('127.0.0.1',LOCAL_PORT)) 162 | 163 | # Accept connection on the server side: 164 | sock,addr = s.accept() 165 | 166 | # Send a frame from the TCPFrameClient to the server socket: 167 | frame = 'hello' 168 | tfc.send_frame(frame) 169 | # Read 4 bytes first: 170 | length = sock.recv(4) 171 | length_int = struct.unpack('I',length)[0] 172 | self.assertEquals(length_int,len(frame)) 173 | # Receive the rest of the frame: 174 | r_frame = sock.recv(length_int) 175 | 176 | self.assertEquals(r_frame,frame) 177 | 178 | # Send a frame from the server socket to the TCPFrameClient: 179 | frame = 'How are you doing?' 180 | data = len_prefix_pack(frame) 181 | sock.send(data) 182 | r_frame = tfc.recv_frame() 183 | self.assertEquals(r_frame,frame) 184 | 185 | # Close server socket: 186 | sock.close() 187 | 188 | # We expect to get a None frame on the TCPFrameClient side: 189 | frame = tfc.recv_frame() 190 | self.assertEquals(frame,None) 191 | 192 | # Close listening socket: 193 | s.close() 194 | 195 | # Close TCPFrameClient: 196 | tfc.close() 197 | 198 | 199 | ######################################################################## 200 | 201 | 202 | class MockFrameEndpoint(FrameEndpoint): 203 | def __init__(self): 204 | self.in_list = [] 205 | self.out_list = [] 206 | 207 | def send_frame(self,data): 208 | """Send a frame to remote host""" 209 | self.out_list.append(data) 210 | 211 | def recv_frame(self): 212 | """Receive a frame from remote import host""" 213 | # Pop one frame: 214 | return self.in_list.pop(0) 215 | 216 | def close(self): 217 | """Close connection to remote host""" 218 | pass 219 | 220 | 221 | class TestDBEndpoint(unittest.TestCase): 222 | def test_add_function(self): 223 | """ 224 | Check basic operation of DBEndpoint 225 | """ 226 | mfe = MockFrameEndpoint() 227 | dbe = DBEndpoint(mfe,'my_db_name') 228 | 229 | # We expect the CHOOSE_DB message to be here: 230 | self.assertEqual(len(mfe.out_list),1) 231 | frame = mfe.out_list.pop(0) 232 | assert 'my_db_name' in frame 233 | 234 | func_name = 'my_func_name' 235 | func_comment = 'my function comment' 236 | func_data = 'kasdjflk40938523094802934829304' 237 | 238 | dbe.add_function(func_name,func_comment,func_data) 239 | self.assertEqual(len(mfe.out_list),1) 240 | frame = mfe.out_list.pop(0) 241 | for d in (func_name,func_comment,func_data): 242 | assert d in frame 243 | 244 | def test_request_similars(self): 245 | """ 246 | Check basic operation of DBEndpoint 247 | """ 248 | mfe = MockFrameEndpoint() 249 | dbe = DBEndpoint(mfe,'my_db_name') 250 | 251 | # We expect the CHOOSE_DB message to be here: 252 | self.assertEqual(len(mfe.out_list),1) 253 | frame = mfe.out_list.pop(0) 254 | assert 'my_db_name' in frame 255 | 256 | func_data = '029348509238459kldfjaklsdjflkasjdfklasdf' 257 | num_similars = 8 258 | 259 | # Prepare a response for the REQUEST_SIMILARS message ahead of time: 260 | # Two results: 261 | name1 = 'name1' 262 | comment1 = 'comment1' 263 | sim_grade1 = 7 264 | 265 | name2 = 'name1' 266 | comment2 = 'comment1' 267 | sim_grade2 = 7 268 | 269 | msg = "" 270 | # Two records: 271 | msg += struct.pack('I',2) 272 | 273 | # First record: 274 | msg += struct.pack('I',len(name1)) 275 | msg += name1 276 | msg += struct.pack('I',len(comment1)) 277 | msg += comment1 278 | msg += struct.pack('I',sim_grade1) 279 | 280 | # Second record: 281 | msg += struct.pack('I',len(name2)) 282 | msg += name2 283 | msg += struct.pack('I',len(comment2)) 284 | msg += comment2 285 | msg += struct.pack('I',sim_grade2) 286 | 287 | # Add message type: 288 | frame = dword_pack(MsgTypes.RESPONSE_SIMILARS,msg) 289 | mfe.in_list.append(frame) 290 | 291 | dbe.request_similars(func_data,num_similars) 292 | similars = dbe.response_similars() 293 | self.assertEqual(len(mfe.out_list),1) 294 | frame = mfe.out_list.pop(0) 295 | assert func_data in frame 296 | 297 | # We expect two results: 298 | self.assertEqual(len(similars),2) 299 | self.assertIsInstance(similars[0],FSimilar) 300 | 301 | dbe.close() 302 | 303 | -------------------------------------------------------------------------------- /fcatalog_plugin.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import idaapi 4 | from idaapi import Form 5 | 6 | import idautils 7 | import idc 8 | from fcatalog_client.ida_client import FCatalogClient,clean_idb,MAX_SIM_GRADE 9 | 10 | # Set up logging: 11 | LOG_FILE_NAME = 'fcatalog_plugin.log' 12 | cur_dir = os.path.dirname(os.path.abspath(__file__)) 13 | log_file_path = os.path.join(cur_dir,LOG_FILE_NAME) 14 | logging.basicConfig(filename=log_file_path,level=logging.INFO) 15 | 16 | 17 | # Client configuration: 18 | class ClientConfig(object): 19 | def __init__(self): 20 | self.db_name = None 21 | self.remote_host = None 22 | self.remote_port = None 23 | self.exclude_pattern = None 24 | 25 | 26 | ########################################################################## 27 | 28 | # Configuration stashing: 29 | 30 | def save_sstring(s): 31 | """ 32 | Save a short string inside the idb. 33 | """ 34 | min_segment_addr = min(list(idautils.Segments())) 35 | # Keep the string as a regular comment on the first instruction: 36 | idc.MakeComm(min_segment_addr,s) 37 | 38 | 39 | def load_sstring(): 40 | """ 41 | Load a short string from the idb. 42 | """ 43 | min_segment_addr = min(list(idautils.Segments())) 44 | return idc.GetCommentEx(min_segment_addr,0) 45 | 46 | def save_config(client_config): 47 | """ 48 | Save configuration (client_config instance) to IDB. 49 | """ 50 | config_str = "%%%" 51 | config_str += client_config.remote_host 52 | config_str += ":" 53 | config_str += str(client_config.remote_port) 54 | config_str += ":" 55 | config_str += client_config.db_name 56 | config_str += ":" 57 | if client_config.exclude_pattern is not None: 58 | config_str += client_config.exclude_pattern 59 | 60 | save_sstring(config_str) 61 | 62 | def load_config(): 63 | """ 64 | Load configuration (client_config instance) to IDB. 65 | """ 66 | config_str = load_sstring() 67 | if (config_str is None) or (not config_str.startswith('%%%')): 68 | # Return empty configuration: 69 | return None 70 | 71 | # Skip the percents prefix: 72 | config_str = config_str[3:] 73 | 74 | try: 75 | remote_host,remote_port_str,db_name,exclude_pattern = config_str.split(':') 76 | except ValueError: 77 | # Abort if could not unpack 4 values 78 | return None 79 | 80 | remote_port = int(remote_port_str) 81 | 82 | # Create a client config instance and fill it with the loaded 83 | # configuration: 84 | client_config = ClientConfig() 85 | client_config.remote_host = remote_host 86 | client_config.remote_port = remote_port 87 | client_config.db_name = db_name 88 | if len(exclude_pattern) == 0: 89 | client_config.exclude_pattern = None 90 | 91 | return client_config 92 | 93 | 94 | 95 | ########################################################################## 96 | 97 | 98 | class ConfForm(Form): 99 | def __init__(self): 100 | self.invert = False 101 | Form.__init__(self, r"""STARTITEM {id:host} 102 | FCatalog Client Configuration 103 | 104 | <#Host:{host}> 105 | <#Port:{port}> 106 | <#Database Name:{db_name}> 107 | <#Exclude Pattern:{exclude_pattern}> 108 | """, { 109 | 'host': Form.StringInput(tp=Form.FT_TYPE), 110 | 'port': Form.StringInput(tp=Form.FT_TYPE), 111 | 'db_name': Form.StringInput(tp=Form.FT_TYPE), 112 | 'exclude_pattern': Form.StringInput(tp=Form.FT_TYPE), 113 | }) 114 | 115 | 116 | def get_similarity_cut(): 117 | """ 118 | Get similarity cut value from the user. 119 | """ 120 | # The default similarity cut grade is just above half: 121 | default_sim_cut = (MAX_SIM_GRADE // 2) + 1 122 | # We have to make sure that default_sim_cut is not more than 123 | # MAX_SIM_GRADE: 124 | default_sim_cut = min([default_sim_cut,MAX_SIM_GRADE]) 125 | 126 | # Keep going until we get a valid sim_cut from the user, or the user picks 127 | # cancel. 128 | while True: 129 | sim_cut = idaapi.asklong(default_sim_cut,\ 130 | "Please choose a similarity grade cut (1 - {}): ".\ 131 | format(MAX_SIM_GRADE)) 132 | if sim_cut is None: 133 | # If the user has aborted, we return None: 134 | return None 135 | if (1 <= sim_cut <= MAX_SIM_GRADE): 136 | break 137 | 138 | return sim_cut 139 | 140 | 141 | class FCatalogPlugin(idaapi.plugin_t): 142 | flags = 0 143 | comment = '' 144 | help = 'The Functions Catalog client' 145 | wanted_name = 'fcatalog_client' 146 | wanted_hotkey = '' 147 | 148 | def init(self): 149 | """ 150 | Initialize plugin: 151 | """ 152 | self._client_config = load_config() 153 | self._fcc = None 154 | if self._client_config is not None: 155 | self._fcc = FCatalogClient(\ 156 | (self._client_config.remote_host,\ 157 | self._client_config.remote_port),\ 158 | self._client_config.db_name,\ 159 | self._client_config.exclude_pattern) 160 | 161 | # Make sure that self._client config is built, even if it doesn't have 162 | # any fields inside: 163 | if self._client_config is None: 164 | self._client_config = ClientConfig() 165 | 166 | # Set up menus: 167 | ui_path = "Edit/" 168 | self.menu_contexts = [] 169 | self.menu_contexts.append(idaapi.add_menu_item(ui_path, 170 | "FCatalog: Configure", 171 | "", 172 | 0, 173 | self._show_conf_form, 174 | (None,))) 175 | 176 | self.menu_contexts.append(idaapi.add_menu_item(ui_path, 177 | "FCatalog: Commit Functions", 178 | "", 179 | 0, 180 | self._commit_funcs, 181 | (None,))) 182 | self.menu_contexts.append(idaapi.add_menu_item(ui_path, 183 | "FCatalog: Find Similars", 184 | "", 185 | 0, 186 | self._find_similars, 187 | (None,))) 188 | self.menu_contexts.append(idaapi.add_menu_item(ui_path, 189 | "FCatalog: Clean IDB", 190 | "", 191 | 0, 192 | self._clean_idb, 193 | (None,))) 194 | 195 | return idaapi.PLUGIN_KEEP 196 | 197 | def run(self,arg): 198 | pass 199 | 200 | def term(self): 201 | """ 202 | Terminate plugin 203 | """ 204 | for context in self.menu_contexts: 205 | idaapi.del_menu_item(context) 206 | return None 207 | 208 | 209 | def _commit_funcs(self,arg): 210 | """ 211 | This function handles the event of clicking on "commit funcs" from the 212 | menu. 213 | """ 214 | if self._fcc is None: 215 | print('Please configure FCatalog') 216 | return 217 | self._fcc.commit_funcs() 218 | 219 | def _find_similars(self,arg): 220 | """ 221 | This function handles the event of clicking on "find similars" from the 222 | menu. 223 | """ 224 | if self._fcc is None: 225 | print('Please configure FCatalog') 226 | return 227 | # Get the similarity cut from the user: 228 | similarity_cut = get_similarity_cut() 229 | 230 | # If the user has clicked cancel, we abort: 231 | if similarity_cut is None: 232 | print('Aborting find_similars.') 233 | return 234 | 235 | self._fcc.find_similars(similarity_cut) 236 | 237 | 238 | def _clean_idb(self,arg): 239 | """ 240 | Clean the idb from fcatalog names or comments. 241 | """ 242 | clean_idb() 243 | 244 | 245 | def _show_conf_form(self,arg): 246 | """ 247 | Show the configuration form and update configuration values according 248 | to user choices. 249 | """ 250 | # Create form 251 | cf = ConfForm() 252 | 253 | # Compile (in order to populate the controls) 254 | cf.Compile() 255 | 256 | # Populate form fields with current configuration values: 257 | if self._client_config.remote_host is not None: 258 | cf.host.value = self._client_config.remote_host 259 | if self._client_config.remote_port is not None: 260 | cf.port.value = str(self._client_config.remote_port) 261 | if self._client_config.db_name is not None: 262 | cf.db_name.value = self._client_config.db_name 263 | if self._client_config.exclude_pattern is not None: 264 | cf.exclude_pattern.value = self._client_config.exclude_pattern 265 | 266 | # Execute the form 267 | res = cf.Execute() 268 | if res == 1: 269 | # User pressed OK: 270 | 271 | is_conf_good = True 272 | 273 | # Extract host: 274 | host = cf.host.value 275 | if len(host) == 0: 276 | host = None 277 | is_conf_good = False 278 | self._client_config.remote_host = host 279 | 280 | # Extract port: 281 | try: 282 | port = int(cf.port.value) 283 | except ValueError: 284 | port = None 285 | is_conf_good = False 286 | self._client_config.remote_port = port 287 | 288 | # Extract db name: 289 | db_name = cf.db_name.value 290 | if len(db_name) == 0: 291 | db_name = None 292 | is_conf_good = False 293 | self._client_config.db_name = db_name 294 | 295 | # Extract exclude_pattern 296 | exclude_pattern = cf.exclude_pattern.value 297 | if len(exclude_pattern) == 0: 298 | exclude_pattern = None 299 | self._client_config.exclude_pattern = exclude_pattern 300 | 301 | if is_conf_good: 302 | save_config(self._client_config) 303 | self._fcc = FCatalogClient(\ 304 | (self._client_config.remote_host,\ 305 | self._client_config.remote_port),\ 306 | self._client_config.db_name,\ 307 | self._client_config.exclude_pattern) 308 | print('Configuration successful.') 309 | else: 310 | print('Invalid configuration.') 311 | self._fcc = None 312 | 313 | 314 | # Dispose the form 315 | cf.Free() 316 | 317 | 318 | def PLUGIN_ENTRY(): 319 | return FCatalogPlugin() 320 | 321 | -------------------------------------------------------------------------------- /fcatalog_client/ida_client.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import logging 3 | import re 4 | 5 | from db_endpoint import DBEndpoint,TCPFrameClient 6 | from utils import blockify 7 | from thread_executor import ThreadExecutor, ThreadExecutorError 8 | from ida_ts import get_func_length, get_func_data, get_func_comment,\ 9 | set_func_comment, Functions, first_func_addr, GetFunctionName,\ 10 | is_func_chunked, make_name 11 | 12 | class FCatalogClientError(Exception): pass 13 | 14 | logger = logging.getLogger(__name__) 15 | 16 | # Minimum function size (in bytes) to be considered when trying to find 17 | # similars. 18 | MIN_FUNC_LENGTH = 0x60 19 | 20 | FCATALOG_FUNC_NAME_PREFIX = 'FCATALOG__' 21 | FCATALOG_COMMENT_PREFIX = '%%%' 22 | 23 | # The grade of similarity for each function is a number between 0 and this 24 | # constant (Inclusive): 25 | MAX_SIM_GRADE = 16 26 | 27 | # Amount of similar functions to return in every inquiry for similars function 28 | # for a specific function: 29 | NUM_SIMILARS = 1 30 | 31 | # Amount of functions to be sent together to remote server when looking for 32 | # similars: 33 | GET_SIMILARS_BATCH_SIZE = 20 34 | 35 | 36 | ######################################################################### 37 | 38 | def is_func_fcatalog(func_addr): 39 | """ 40 | Have we obtained the name for this function from fcatalog server? 41 | We know this by the name of the function. 42 | """ 43 | logger.debug('is_func_fcatalog {}'.format(func_addr)) 44 | func_name = GetFunctionName(func_addr) 45 | return func_name.startswith(FCATALOG_FUNC_NAME_PREFIX) 46 | 47 | 48 | def is_func_long_enough(func_addr): 49 | """ 50 | Check if a given function is of suitable size to be commited. 51 | """ 52 | logger.debug('is_func_long_enough {}'.format(func_addr)) 53 | func_length = get_func_length(func_addr) 54 | if func_length < MIN_FUNC_LENGTH: 55 | return False 56 | 57 | return True 58 | 59 | 60 | ########################################################################### 61 | 62 | def strip_comment_fcatalog(comment): 63 | """ 64 | Remove all fcatalog comments from a given comment. 65 | """ 66 | res_lines = [] 67 | 68 | # Get only lines that don't start with FCATALOG_COMMENT_PREFIX: 69 | lines = comment.splitlines() 70 | for ln in lines: 71 | if ln.startswith(FCATALOG_COMMENT_PREFIX): 72 | continue 73 | res_lines.append(ln) 74 | 75 | return '\n'.join(res_lines) 76 | 77 | def add_comment_fcatalog(comment,fcatalog_comment): 78 | """ 79 | Add fcatalog comment to a function. 80 | """ 81 | res_lines = [] 82 | 83 | # Add the fcatalog_comment lines with a prefix: 84 | for ln in fcatalog_comment.splitlines(): 85 | res_lines.append(FCATALOG_COMMENT_PREFIX + ' ' + ln) 86 | 87 | # Add the rest of the comment lines: 88 | for ln in comment.splitlines(): 89 | res_lines.append(ln) 90 | 91 | return '\n'.join(res_lines) 92 | 93 | def make_fcatalog_name(func_name,sim_grade,func_addr): 94 | """ 95 | Make an fcatalog function name using function name and sim_grade. 96 | """ 97 | lres = [] 98 | lres.append(FCATALOG_FUNC_NAME_PREFIX) 99 | lres.append('{:0>2}__'.format(sim_grade)) 100 | lres.append(func_name) 101 | lres.append('__{:0>8X}'.format(func_addr & 0xffffffff)) 102 | return ''.join(lres) 103 | 104 | 105 | ########################################################################### 106 | 107 | 108 | 109 | class FCatalogClient(object): 110 | def __init__(self,remote,db_name,exclude_pattern=None): 111 | # Keep remote address: 112 | self._remote = remote 113 | 114 | # Keep remote db name: 115 | self._db_name = db_name 116 | 117 | # A thread executor. Allows only one task to be run every time. 118 | self._te = ThreadExecutor() 119 | 120 | # A regexp pattern that identifies functions that are not named, and 121 | # should be ignored. 122 | self._exclude_pattern = exclude_pattern 123 | 124 | 125 | # A thread safe print function. I am not sure if this is rquired. It is 126 | # done to be one the safe side: 127 | self._print = print 128 | 129 | def _is_func_named(self,func_addr): 130 | """ 131 | Check if a function was ever named by the user. 132 | """ 133 | logger.debug('_is_func_named {}'.format(func_addr)) 134 | func_name = GetFunctionName(func_addr) 135 | 136 | # Avoid functions like sub_409f498: 137 | if func_name.startswith('sub_'): 138 | return False 139 | 140 | # If exclude_pattern was provided, make sure that the function 141 | # name does not match it: 142 | if self._exclude_pattern is not None: 143 | mt = re.match(self._exclude_pattern,func_name) 144 | if mt is not None: 145 | return False 146 | 147 | # Avoid reindexing FCATALOG functions: 148 | if is_func_fcatalog(func_addr): 149 | return False 150 | 151 | return True 152 | 153 | def _is_func_commit_candidate(self,func_addr): 154 | """ 155 | Is this function a candidate for committing? 156 | """ 157 | # Don't commit if chunked: 158 | if is_func_chunked(func_addr): 159 | return False 160 | 161 | if not self._is_func_named(func_addr): 162 | return False 163 | 164 | if not is_func_long_enough(func_addr): 165 | return False 166 | 167 | return True 168 | 169 | def _is_func_find_candidate(self,func_addr): 170 | """ 171 | Is this function a candidate for finding from database (Finding similars 172 | for this function?) 173 | """ 174 | if is_func_chunked(func_addr): 175 | return False 176 | 177 | if self._is_func_named(func_addr): 178 | return False 179 | 180 | if not is_func_long_enough(func_addr): 181 | return False 182 | 183 | return True 184 | 185 | 186 | def _iter_func_find_candidates(self): 187 | """ 188 | Iterate over all functions that are candidates for finding similars from 189 | the remote database. 190 | This function is IDA read thread safe. 191 | """ 192 | for func_addr in Functions(): 193 | if self._is_func_find_candidate(func_addr): 194 | yield func_addr 195 | 196 | 197 | def _commit_funcs_thread(self): 198 | """ 199 | Commit all the named functions from this idb to the server. 200 | This is an IDA read thread safe function. 201 | """ 202 | self._print('Commiting functions...') 203 | # Set up a connection to remote db: 204 | frame_endpoint = TCPFrameClient(self._remote) 205 | fdb = DBEndpoint(frame_endpoint,self._db_name) 206 | 207 | 208 | for func_addr in Functions(): 209 | logger.debug('Iterating over func_addr: {}'.format(func_addr)) 210 | if not self._is_func_commit_candidate(func_addr): 211 | continue 212 | 213 | func_name = GetFunctionName(func_addr) 214 | func_comment = strip_comment_fcatalog(get_func_comment(func_addr)) 215 | func_data = get_func_data(func_addr) 216 | 217 | # If we had problems reading the function data, we skip it. 218 | if func_data is None: 219 | self._print('!> Skipping {}'.format(func_name)) 220 | continue 221 | 222 | fdb.add_function(func_name,func_comment,func_data) 223 | self._print(func_name) 224 | 225 | # Close db: 226 | fdb.close() 227 | self._print('Done commiting functions.') 228 | 229 | def commit_funcs(self): 230 | """ 231 | Commit all functions from this IDB to the server. 232 | """ 233 | try: 234 | t = self._te.execute(self._commit_funcs_thread) 235 | except ThreadExecutorError: 236 | print('Another operation is currently running. Please wait.') 237 | 238 | 239 | def _batch_similars(self,fdb,l_func_addr): 240 | """ 241 | Given a list of function addresses, request similars for each of those 242 | functions. Then wait for all the responses, and return a list of tuples 243 | of the form: (func_addr,similars) 244 | This function is IDA read thread safe. 245 | """ 246 | # Send requests for similars for every function in l_func_addr list: 247 | for func_addr in l_func_addr: 248 | func_data = get_func_data(func_addr) 249 | fdb.request_similars(func_data,1) 250 | 251 | # Collect responses from remote server: 252 | lres = [] 253 | for func_addr in l_func_addr: 254 | similars = fdb.response_similars() 255 | lres.append((func_addr,similars)) 256 | 257 | return lres 258 | 259 | 260 | def _find_similars_thread(self,similarity_cut,batch_size): 261 | """ 262 | For each unnamed function in this database find a similar functions 263 | from the fcatalog remote db, and rename appropriately. 264 | This thread is IDA write thread safe. 265 | """ 266 | self._print('Finding similars...') 267 | 268 | # Set up a connection to remote db: 269 | frame_endpoint = TCPFrameClient(self._remote) 270 | fdb = DBEndpoint(frame_endpoint,self._db_name) 271 | 272 | # Iterate over blocks of candidate functions addresses: 273 | for l_func_addr in blockify(self._iter_func_find_candidates(),\ 274 | batch_size): 275 | # Send block to remote server and get results: 276 | bsimilars = self._batch_similars(fdb,l_func_addr) 277 | # Iterate over functions and results: 278 | for func_addr,similars in bsimilars: 279 | 280 | if len(similars) == 0: 281 | # No similars found. 282 | continue 283 | 284 | # Get the first entry (Highest similarity): 285 | fsim = similars[0] 286 | 287 | # Discard if doesn't pass the similarity cut: 288 | if fsim.sim_grade < similarity_cut: 289 | continue 290 | 291 | old_name = GetFunctionName(func_addr) 292 | 293 | # Generate new name: 294 | new_name = make_fcatalog_name(fsim.name,fsim.sim_grade,func_addr) 295 | 296 | # If name matches old name, skip: 297 | if new_name == old_name: 298 | continue 299 | 300 | # Set function to have the new name: 301 | make_name(func_addr,new_name) 302 | 303 | # Add the comments from the fcatalog entry: 304 | func_comment = get_func_comment(func_addr) 305 | func_comment_new = \ 306 | add_comment_fcatalog(func_comment,fsim.comment) 307 | set_func_comment(func_addr,func_comment_new) 308 | 309 | self._print('{} --> {}'.format(old_name,new_name)) 310 | 311 | # Close db: 312 | fdb.close() 313 | 314 | self._print('Done finding similars.') 315 | 316 | def find_similars(self,similarity_cut,batch_size=GET_SIMILARS_BATCH_SIZE): 317 | """ 318 | For each unnamed function in this database find a similar functions 319 | from the fcatalog remote db, and rename appropriately. 320 | """ 321 | try: 322 | t = self._te.execute(self._find_similars_thread,\ 323 | similarity_cut,batch_size) 324 | except ThreadExecutorError: 325 | print('Another operation is currently running. Please wait.') 326 | 327 | 328 | def clean_idb(): 329 | """ 330 | Clean all fcatalog marks and names from this idb. 331 | """ 332 | print('Cleaning idb...') 333 | for func_addr in Functions(): 334 | # Skip functions that are not fcatalog named: 335 | if not is_func_fcatalog(func_addr): 336 | continue 337 | 338 | print('{}'.format(GetFunctionName(func_addr))) 339 | # Clear function's name: 340 | make_name(func_addr,'') 341 | 342 | # Clean fcatalog comments from the function: 343 | func_comment = get_func_comment(func_addr) 344 | set_func_comment(func_addr,strip_comment_fcatalog(func_comment)) 345 | print('Done cleaning idb.') 346 | 347 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------