├── README.md ├── .gitignore ├── normalize_ip.py ├── shelf_export.py ├── shelf_import.py ├── LICENSE ├── db_lib.py └── pcap_stats.py /README.md: -------------------------------------------------------------------------------- 1 | # pcap-stats 2 | 3 | Learn about a network from a pcap file or reading from an interface. 4 | This tool focuses on the traffic types with the largest number of packets 5 | or bytes, allowing you to identify traffic spikes, DOS or DDOS attacks, 6 | bandwidth hogs, and unwanted servers on your network. For each line of 7 | statistics we include the number of packets, the number of bytes, the 8 | associated BPF to show just this traffic, and one or more hints as to 9 | what this traffic might be (including the ports used, hostnames and 10 | netbios names, and address type details. 11 | 12 | "Traffic types" include IP and physical layers, protocol layers, TCP 13 | flags, ICMP types, TCP and UDP ports, individual IP addresses, hostnames, 14 | and netbios names. hostnames and netbios names are cached between runs. 15 | 16 | # Quickstart 17 | - If you don't have pip3 installed, install it with 18 | ```sudo apt install python3-pip``` or ```sudo yum install python3-pip``` 19 | - Install scapy with 20 | ```sudo pip3 install scapy``` 21 | - Analyze a pcap file with 22 | ```./pcap_stats.py -r pcap_file_name.pcap | less -S``` 23 | - Analyze packets coming in on a network interface with 24 | ```sudo ./pcap_stats.py -i eth0 -c 10000 | less -S``` 25 | - To create an HTML page of output 26 | ```./pcap_stats.py -r pcap_file_name.pcap -f html >pcap_stats.html``` 27 | - To see the other available options, run ```./pcap_stats.py -h``` 28 | 29 | 30 | # Tools 31 | - In the text format, to see just the lines with more than 4000 packets: 32 | ```cat output.txt | awk '$1 > 4000 {print}' | less 33 | 34 | - In the text format, to sort the output so the most common traffic is at the bottom: 35 | ```cat output.txt | sort -n | less 36 | 37 | - In the text format, to sort the output so the most common traffic is at the top: 38 | ```cat output.txt | sort -nr | less 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /normalize_ip.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """Converts ip addresses (ipv4 or ipv6) on stdin to fully exploded ip addresses.""" 3 | 4 | import ipaddress 5 | import sys 6 | 7 | 8 | Devel = False 9 | 10 | 11 | def Debug(DebugStr): 12 | """Prints a note to stderr""" 13 | if Devel != False: 14 | sys.stderr.write(DebugStr + '\n') 15 | 16 | 17 | def ip_addr_obj(raw_addr): 18 | """Returns an ip obj for the input string. The raw_addr string should already have leading and trailing whitespace removed before being handed to this function.""" 19 | 20 | try: 21 | if sys.version_info > (3, 0): 22 | raw_addr_string = str(raw_addr) 23 | else: 24 | raw_addr_string = unicode(raw_addr) 25 | except UnicodeDecodeError: 26 | raw_addr_string = '' 27 | 28 | #if Devel: 29 | # Debug('Cannot convert:' 30 | # Debug(raw_addr) 31 | # raise 32 | #else: 33 | # pass 34 | 35 | ip_obj = None 36 | 37 | if raw_addr_string != '' and not raw_addr_string.endswith(('.256', '.257', '.258', '.259', '.260')): #raw_addr_string.find('.256') == -1 38 | try: 39 | ip_obj = ipaddress.ip_address(raw_addr_string) 40 | except ValueError: 41 | #See if it's in 2.6.0.0.9.0.0.0.5.3.0.1.B.7.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1 or 260090005301B7000000000000000001 format 42 | hex_string = raw_addr_string.replace('.', '') 43 | colon_hex_string = hex_string[0:4] + ':' + hex_string[4:8] + ':' + hex_string[8:12] + ':' + hex_string[12:16] + ':' + hex_string[16:20] + ':' + hex_string[20:24] + ':' + hex_string[24:28] + ':' + hex_string[28:32] 44 | try: 45 | ip_obj = ipaddress.ip_address(colon_hex_string) 46 | except ValueError: 47 | if Devel: 48 | Debug(raw_addr_string) 49 | raise 50 | else: 51 | pass 52 | 53 | return ip_obj 54 | 55 | 56 | def explode_ip(ip_obj): 57 | """Converts the input IP object to its exploded form (type "unicode" in python2) ready for printing. If the IP/IP object is invalid, returns an empty string.""" 58 | 59 | if ip_obj is None: 60 | return '' 61 | else: 62 | return ip_obj.exploded 63 | 64 | 65 | 66 | if __name__ == "__main__": 67 | AllSucceeded = True 68 | 69 | for InLine in sys.stdin: 70 | InLine = InLine.replace('\n', '').replace('\r', '') 71 | #Debug('======== ' + InLine) 72 | user_ip_obj = ip_addr_obj(InLine) 73 | 74 | if user_ip_obj is None: 75 | AllSucceeded = False 76 | if Devel: 77 | print('Invalid: ' + InLine) 78 | else: 79 | print('') 80 | else: 81 | print(explode_ip(user_ip_obj)) 82 | 83 | #If not interested in detailed error checking, can also do: 84 | #print(explode_ip(ip_addr_obj(InLine))) 85 | 86 | 87 | if AllSucceeded: 88 | quit(0) 89 | else: 90 | Debug('One or more input lines were not recognized as cidr networks or hosts') 91 | quit(1) 92 | -------------------------------------------------------------------------------- /shelf_export.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Exports a shelf-created dictionary to stdout. Tested with DBM files.""" 3 | 4 | __version__ = '0.0.3' 5 | 6 | __author__ = 'William Stearns' 7 | __copyright__ = 'Copyright 2021, William Stearns' 8 | __credits__ = ['William Stearns'] 9 | __email__ = 'william.l.stearns@gmail.com' 10 | __license__ = 'GPL 3.0' 11 | __maintainer__ = 'William Stearns' 12 | __status__ = 'Development' #Prototype, Development or Production 13 | 14 | 15 | import os 16 | import sys 17 | import json 18 | import shelve 19 | 20 | 21 | def force_string(raw_string): 22 | """Make sure the returned object is a string.""" 23 | 24 | retval = raw_string 25 | 26 | if sys.version_info > (3, 0): #Python 3 27 | if isinstance(raw_string, bytes): 28 | retval = raw_string.decode("utf-8", 'replace') 29 | elif isinstance(raw_string, str): 30 | pass 31 | elif isinstance(raw_string, list): 32 | retval = ' '.join([force_string(listitem) for listitem in raw_string]) 33 | #print(str(type(raw_string))) 34 | #print("huh:" + str(raw_string)) 35 | #sys.exit() 36 | else: 37 | print(str(type(raw_string))) 38 | print("huh:" + str(raw_string)) 39 | sys.exit() 40 | retval = str(raw_string) 41 | else: 42 | retval = str(raw_string) 43 | 44 | return retval 45 | 46 | 47 | 48 | default_shelf_file = os.environ["HOME"] + '/.cache/ip_names' 49 | 50 | 51 | if __name__ == '__main__': 52 | import argparse 53 | 54 | parser = argparse.ArgumentParser(description='shelf_export version ' + str(__version__)) 55 | parser.add_argument('-r', '--read', help='Shelf file from which to read dictionary (default: %(default)s)', required=False, default=default_shelf_file) 56 | (parsed, unparsed) = parser.parse_known_args() 57 | cl_args = vars(parsed) 58 | 59 | active_shelf = cl_args['read'] 60 | try: 61 | persistent_dict = shelve.open(active_shelf, flag='r') 62 | except: 63 | sys.stderr.write('Unable to open ' + active_shelf + ' for reading, exiting.\n') 64 | sys.stderr.flush() 65 | sys.exit(1) 66 | 67 | print('{') 68 | is_first = True 69 | for a_key in sorted(persistent_dict): 70 | if a_key in persistent_dict: 71 | key_string = force_string(a_key) 72 | #if "'" in str(persistent_dict[a_key]): 73 | # sys.stderr.write('Quote error for ' + str(persistent_dict[a_key]) + '\n') 74 | # sys.stderr.flush() 75 | #else: 76 | if is_first: 77 | is_first = False 78 | else: 79 | print(',') 80 | #sys.stdout.write('\t"' + key_string + '": ' + str(persistent_dict[a_key]).replace("'", '"').replace('{', '[').replace('}', ']')) 81 | sys.stdout.write('\t"' + key_string + '": ' + json.dumps(list(persistent_dict[a_key]))) 82 | sys.stdout.flush() 83 | else: 84 | sys.stderr.write('Key error for ' + force_string(a_key) + '\n') 85 | sys.stderr.flush() 86 | 87 | print('\n}') 88 | -------------------------------------------------------------------------------- /shelf_import.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """imports a json dictionary from stdin and merges all items in it to a shelf. Tested with DBM files.""" 3 | 4 | __version__ = '0.0.4' 5 | 6 | __author__ = 'William Stearns' 7 | __copyright__ = 'Copyright 2021, William Stearns' 8 | __credits__ = ['William Stearns'] 9 | __email__ = 'william.l.stearns@gmail.com' 10 | __license__ = 'GPL 3.0' 11 | __maintainer__ = 'William Stearns' 12 | __status__ = 'Development' #Prototype, Development or Production 13 | 14 | 15 | import os 16 | import sys 17 | import json 18 | import shelve 19 | 20 | 21 | def debug_out(output_string): 22 | """Send debuging output to stderr.""" 23 | 24 | sys.stderr.write(output_string + '\n') 25 | sys.stderr.flush() 26 | 27 | 28 | def add_items_to_persistent(item_dict, p_shelf): 29 | """Take all the items in the item_dict and add them to p_shelf. Both are dictionaries.""" 30 | #The stdin dictionary _values_ must all be strings (string will be appended to shelf list if new) or lists (all new list items will be appended to shelf list). 31 | 32 | for one_key in item_dict: 33 | if item_dict[one_key]: 34 | if one_key in p_shelf: 35 | current_list = p_shelf[one_key] 36 | else: 37 | current_list = [] 38 | 39 | is_modified = False 40 | if isinstance(item_dict[one_key], str): 41 | if item_dict[one_key] not in current_list: 42 | current_list.append(item_dict[one_key]) 43 | is_modified = True 44 | elif isinstance(item_dict[one_key], list): 45 | for one_val in item_dict[one_key]: 46 | if one_val not in current_list: 47 | current_list.append(one_val) 48 | is_modified = True 49 | else: 50 | debug_out("value associated with " + one_key + " is not a string or list, skipping.") 51 | 52 | if is_modified: 53 | p_shelf[one_key] = current_list 54 | 55 | 56 | default_shelf_file = os.environ["HOME"] + '/.cache/ip_names_TEST' #FIXME before release 57 | 58 | if __name__ == '__main__': 59 | import argparse 60 | 61 | parser = argparse.ArgumentParser(description='shelf_import version ' + str(__version__)) 62 | parser.add_argument('-w', '--write', help='Shelf file to which to write new values (default: %(default)s)', required=False, default=default_shelf_file) 63 | (parsed, unparsed) = parser.parse_known_args() 64 | cl_args = vars(parsed) 65 | 66 | active_shelf = cl_args['write'] 67 | 68 | stdintext = sys.stdin.buffer.read().decode("utf-8", 'replace') 69 | 70 | try: 71 | import_items = json.loads(stdintext) 72 | except json.decoder.JSONDecodeError as e: 73 | debug_out("Unable to import stdin as a json object, exiting.") 74 | raise e 75 | if isinstance(import_items, dict): 76 | #Here we have a dictionary of items to add to the shelf. 77 | 78 | try: 79 | persistent_dict = shelve.open(active_shelf, writeback=True) 80 | 81 | add_items_to_persistent(import_items, persistent_dict) 82 | except: 83 | debug_out("Cannot open " + active_shelf + " for writing, exiting.") 84 | sys.exit(1) 85 | else: 86 | debug_out("Std input is not a dictionary, exiting.") 87 | print(import_items) 88 | print(type(import_items)) 89 | sys.exit(1) 90 | 91 | sys.exit(0) 92 | -------------------------------------------------------------------------------- /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 | 635 | Copyright (C) 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 | Copyright (C) 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 | -------------------------------------------------------------------------------- /db_lib.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Test library for sqlite storage.""" 3 | #All other functions call setup_db automatically if the dbfile doesn't exist, so you don't need to call that by hand. 4 | #Most functions have "dbfiles" as the first parameter. This can be a string with the database filename or a 5 | #list of string filenames, in which case dbfiles[0] is the only one that can be written and created - the rest are 6 | #read-only and will not be created if not already there. 7 | 8 | __version__ = '0.3.4' 9 | 10 | __author__ = 'David Quartarolo' 11 | __copyright__ = 'Copyright 2022, David Quartarolo' 12 | __credits__ = ['David Quartarolo', 'William Stearns'] 13 | __email__ = 'david@activecountermeasures.com' 14 | __license__ = 'WTFPL' #http://www.wtfpl.net/ 15 | __maintainer__ = 'William Stearns' 16 | __status__ = 'Development' #Prototype, Development or Production 17 | 18 | 19 | import hashlib 20 | import json 21 | import os 22 | import random 23 | import sqlite3 24 | import string 25 | import sys 26 | import time 27 | from typing import Any, Union 28 | from xmlrpc.client import Boolean 29 | 30 | sqlite_timeout = 20 #Default timeout, in seconds, can have fractions. Without it, timeout is 5. 31 | paranoid = True #Run some additional checks 32 | verbose_status = True #Show some additional status output on stderr 33 | #Note: maximum time between forced flushes is set to 600 in both buffer_merges and buffer_delete_vals 34 | 35 | def sha256_sum(raw_object) -> str: 36 | """Creates a hex format sha256 hash/checksum of the given string/bytes object.""" 37 | 38 | digest: str = '' 39 | 40 | if isinstance(raw_object, str): 41 | digest = hashlib.sha256(raw_object.encode('ascii', errors='ignore')).hexdigest() 42 | elif isinstance(raw_object, bytes): 43 | digest = hashlib.sha256(raw_object).hexdigest() 44 | else: 45 | sys.stderr.write('Unrecognized object type to be sha256 hashed: ' + str(type(raw_object))) 46 | sys.stderr.flush() 47 | 48 | return digest 49 | 50 | 51 | def is_sha256_sum(possible_hash_string: str) -> Boolean: 52 | """Check if the string is valid hex. Not that it won't correctly handle strings starting with 0x.""" 53 | 54 | return len(possible_hash_string) == 64 and all(c in string.hexdigits for c in possible_hash_string) 55 | 56 | 57 | def setup_db(dbfiles: Union[str, list]) -> Boolean: 58 | '''Create Sqlite3 DB with all required tables.''' 59 | #If dbfiles is a list, we will only create and set up dbfiles[0], the sole writeable database file. 60 | 61 | success: Boolean = True 62 | 63 | if not dbfiles: 64 | dbfile: str = '' 65 | elif isinstance(dbfiles, (list, tuple)): 66 | dbfile = dbfiles[0] 67 | else: 68 | dbfile = dbfiles 69 | 70 | if dbfile: #If dbfile is None, don't try to create it. 71 | if not os.path.exists(dbfile): 72 | try: 73 | with open(dbfile, 'x', encoding='utf8'): 74 | pass 75 | conn = sqlite3.connect(dbfile, timeout=sqlite_timeout) 76 | # Create Signatures Table 77 | conn.execute('''CREATE TABLE "main" ( 78 | "KEY_STR" TEXT UNIQUE, 79 | "JSON_STR" TEXT, 80 | PRIMARY KEY("KEY_STR") 81 | );''') 82 | db_cur = conn.cursor() 83 | db_cur.execute('PRAGMA journal_mode=wal') #https://pupli.net/2020/09/sqlite-wal-mode-in-python/ 84 | conn.close() 85 | except: 86 | success = False 87 | return success 88 | 89 | 90 | def insert_key(dbfiles: Union[str, list], key_str: str, value_obj: Any) -> Boolean: 91 | '''Inserts key_str and its associated python object into database 92 | serializing the object on the way in.''' 93 | #This will add a new row if the key isn't there, and replace the existing value if it is. 94 | 95 | if not dbfiles: 96 | dbfile: str = '' 97 | elif isinstance(dbfiles, (list, tuple)): 98 | dbfile = dbfiles[0] 99 | else: 100 | dbfile = dbfiles 101 | 102 | modified_rows = 0 103 | already_inserted = False 104 | if dbfile: #If dbfile is None, don't do anything. 105 | if not os.path.exists(dbfile): 106 | setup_db(dbfile) 107 | value_str = json.dumps(value_obj) 108 | existing_value = select_key(dbfile, key_str) #Note: no locking required around this select...replace block as we're totally replacing the existing value below. 109 | if existing_value and value_str in existing_value: 110 | already_inserted = True 111 | #if verbose_status: 112 | # sys.stderr.write(' ') 113 | # sys.stderr.flush() 114 | else: 115 | with sqlite3.connect(dbfile, timeout=sqlite_timeout) as conn: 116 | #It appears from https://www.sqlitetutorial.net/sqlite-replace-statement/ that the following will correctly insert (if not there) or replace (if there). 117 | modified_rows = conn.execute("REPLACE INTO main (KEY_STR, JSON_STR) values (?, ?)", (key_str, value_str)).rowcount 118 | conn.commit() 119 | return already_inserted or (modified_rows >= 1) 120 | 121 | 122 | def insert_key_large_value(dbfiles: Union[str, list], large_dbfiles: Union[str, list], key_str: str, value_obj: Any) -> Boolean: 123 | '''Inserts key_str and its associates python object into database 124 | serializing the object on the way in.''' 125 | #This will add a new row if the key isn't there, and replace the existing value if it is. 126 | #This places the (key: sha256sum(value)) in dbfile, and (sha256sum(value): value) in large_dbfile 127 | 128 | if not dbfiles: 129 | dbfile: str = '' 130 | elif isinstance(dbfiles, (list, tuple)): 131 | dbfile = dbfiles[0] 132 | else: 133 | dbfile = dbfiles 134 | if not large_dbfiles: 135 | large_dbfile: str = '' 136 | elif isinstance(large_dbfiles, (list, tuple)): 137 | large_dbfile = large_dbfiles[0] 138 | else: 139 | large_dbfile = large_dbfiles 140 | 141 | if dbfile and large_dbfile: #If dbfile or large_dbfile are None, don't do anything. 142 | value_sum = sha256_sum(value_obj) 143 | if paranoid: 144 | #Automatically compare the existing value_str in the database - if any - to this new value and warn if different. 145 | existing_value = select_key(large_dbfile, value_sum) 146 | if existing_value is None or existing_value == []: 147 | existing_value = [] 148 | elif value_obj not in existing_value: 149 | sys.stderr.write('db_lib.py: existing large object in database does not match new object: sha256 hash collision.\n') 150 | sys.stderr.write(large_dbfile + '\n') 151 | sys.stderr.write(value_sum + '\n') 152 | sys.stderr.write(value_obj + '\n') 153 | sys.stderr.write(str(existing_value) + '\n') 154 | sys.stderr.flush() 155 | success1 = insert_key(large_dbfile, value_sum, [value_obj]) #We don't pass down the _lists_ of dbfiles/large_dbfiles as we can only write to the first. 156 | success2 = insert_key(dbfile, key_str, [value_sum]) 157 | return success1 and success2 158 | 159 | 160 | def delete_key(dbfiles: Union[str, list], key_str: str) -> Boolean: 161 | '''Delete row with key_str and associated object from database.''' 162 | 163 | if not dbfiles: 164 | dbfile: str = '' 165 | elif isinstance(dbfiles, (list, tuple)): 166 | dbfile = dbfiles[0] 167 | else: 168 | dbfile = dbfiles 169 | 170 | modified_rows = 0 171 | if dbfile: #If dbfile is None, don't do anything. 172 | if not os.path.exists(dbfile): 173 | setup_db(dbfile) 174 | with sqlite3.connect(dbfile, timeout=sqlite_timeout) as conn: 175 | modified_rows = conn.execute("DELETE FROM main WHERE KEY_STR=?", (key_str,)).rowcount 176 | conn.commit() 177 | return modified_rows >= 1 178 | 179 | 180 | def select_key(dbfiles: Union[str, list], key_str: str): 181 | '''Searches for key_str from database. If the key_str is found, 182 | the obj is unserialized and returned as the original type of that value.''' 183 | #Note: this returns all values from all databases (both the sole read-write database 184 | #at position 0 and the remaining read-only databases.) 185 | 186 | value_obj: list = [] 187 | 188 | if not dbfiles: 189 | dbfile_list: list = [] 190 | elif isinstance(dbfiles, (list, tuple)): 191 | dbfile_list = dbfiles 192 | else: 193 | dbfile_list = [dbfiles] 194 | 195 | if dbfile_list and dbfile_list[0]: 196 | if not os.path.exists(dbfile_list[0]): 197 | setup_db(dbfile_list[0]) 198 | 199 | for dbfile in dbfile_list: 200 | if dbfile: #If dbfile is None, don't do anything. 201 | with sqlite3.connect("file:" + dbfile + "?mode=ro", uri=True, timeout=sqlite_timeout) as conn: 202 | entry_cursor = conn.execute("SELECT JSON_STR FROM main WHERE KEY_STR=?", [key_str]) 203 | entry = entry_cursor.fetchall() 204 | if len(entry) > 0: 205 | new_objects = json.loads(entry[0][0]) 206 | #First [0] is the first row returned (which should be the only row returned as keys are unique.) 207 | #Second [0] is the first column (JSON_STR, which is also the only column requested.) 208 | #The reply will generally be a list, though possibly empty or None. 209 | if new_objects: 210 | if isinstance(new_objects, (list, tuple)): 211 | for new_obj in new_objects: 212 | if new_obj not in value_obj: 213 | value_obj.append(new_obj) 214 | else: 215 | value_obj.append(new_objects) 216 | 217 | return value_obj 218 | 219 | 220 | def select_random(dbfiles: Union[str, list]) -> tuple: 221 | '''Selects a random key,value tuple from from all databases (both 222 | the sole read-write database at position 0 and the remaining 223 | read-only databases.). The return value is a single key,value 224 | tuple (unless all databases have no k,v pairs, in which case we 225 | return ('', []) .''' 226 | #Note this isn't balanced - k,v pairs from small databases will show 227 | #up more frequently than k,v pairs from large databases. 228 | 229 | kv_tuples: list = [] 230 | 231 | if not dbfiles: 232 | dbfile_list: list = [] 233 | elif isinstance(dbfiles, (list, tuple)): 234 | dbfile_list = dbfiles 235 | else: 236 | dbfile_list = [dbfiles] 237 | 238 | if dbfile_list and dbfile_list[0]: 239 | if not os.path.exists(dbfile_list[0]): 240 | setup_db(dbfile_list[0]) 241 | 242 | for dbfile in dbfile_list: 243 | if dbfile: #If dbfile is None, don't do anything. 244 | with sqlite3.connect("file:" + dbfile + "?mode=ro", uri=True, timeout=sqlite_timeout) as conn: 245 | entry_cursor = conn.execute("SELECT KEY_STR, JSON_STR FROM main ORDER BY RANDOM() LIMIT 1") #We grab a random record from each database that has entries. 246 | entry = entry_cursor.fetchall() 247 | if len(entry) > 0: 248 | new_key = entry[0][0] 249 | #First [0] is the first row returned (which should be the only row returned as keys are unique.) 250 | #Second [0] is the first column (KEY_STR) 251 | #new_key will generally be a string (possibly '' or None) 252 | if new_key: 253 | new_val = json.loads(entry[0][1]) 254 | #Second [1] is the second column (JSON_STR) 255 | #new_val will generally be a list, (possibly [] or None) 256 | kv_tuples.append( (new_key, new_val) ) 257 | 258 | if kv_tuples: 259 | return random.choice(kv_tuples) #From the N records from N databases, we pick a single line to return 260 | else: 261 | return ('', []) 262 | 263 | 264 | def select_key_large_value(dbfiles: Union[str, list], large_dbfiles: Union[str, list], key_str: str): 265 | '''Searches for key_str from database. If the key_str is found, 266 | the obj is unserialized and returned as the original type of that value.''' 267 | #This automatically gets the sha256sum from dbfile and then uses that to get the original value from large_dbfile. 268 | 269 | large_result_list = [] 270 | if dbfiles and large_dbfiles: #If dbfile or large_dbfile are None, don't do anything. 271 | sum_list = select_key(dbfiles, key_str) 272 | 273 | if sum_list: 274 | for one_sum in sum_list: 275 | one_large = select_key(large_dbfiles, one_sum) 276 | if one_large is not None: 277 | large_result_list.append(one_large[0]) 278 | 279 | return large_result_list 280 | 281 | 282 | def select_all(dbfiles: Union[str, list], return_values: Boolean = True) -> list: 283 | '''Returns all entries from database. Optional parameter return_values decides whether key, value or just key comes back in the list.''' 284 | #We store in all_entries if return_values is True, we store in all_keys if return_values is False. 285 | all_entries: dict = {} #Dictionary that holds key, value(list) pairs. Converted to a list of tuples on the way out. 286 | all_keys: list = [] #List that stores just keys. 287 | 288 | if not dbfiles: 289 | dbfile_list: list = [] 290 | elif isinstance(dbfiles, (list, tuple)): 291 | dbfile_list = dbfiles 292 | else: 293 | dbfile_list = [dbfiles] 294 | 295 | if dbfile_list and dbfile_list[0]: 296 | if not os.path.exists(dbfile_list[0]): 297 | setup_db(dbfile_list[0]) 298 | 299 | for dbfile in dbfile_list: 300 | if dbfile: #If dbfile is None, don't do anything. 301 | with sqlite3.connect("file:" + dbfile + "?mode=ro", uri=True, timeout=sqlite_timeout) as conn: 302 | if return_values: 303 | entry = conn.execute("SELECT KEY_STR, JSON_STR FROM main",) 304 | thisdb_entries = entry.fetchall() 305 | #thisdb_entries is a list of tuples, each of which is a (key, value_list). 306 | 307 | for one_entry in thisdb_entries: 308 | #one_entry is a 2 item tuple, first is the key, second is a list of all associates values 309 | if one_entry[0] in all_entries: 310 | #merge all values (one_entry[1]) into all_entries[one_entry[0]] 311 | for one_val in one_entry[1]: 312 | if one_val not in all_entries[one_entry[0]]: 313 | all_entries[one_entry[0]].append(one_val) 314 | else: 315 | all_entries[one_entry[0]] = one_entry[1] 316 | else: 317 | entry = conn.execute("SELECT KEY_STR FROM main",) 318 | thisdb_entries = entry.fetchall() 319 | #thisdb_entries is a list of tuples, each of which is a (key, ). 320 | 321 | for one_entry in thisdb_entries: 322 | #one_entry is a 1 item tuple, the only item is the key 323 | if one_entry[0] not in all_keys: 324 | all_keys.append(one_entry[0]) 325 | 326 | if return_values: 327 | return list(all_entries.items()) #Convert to a list of tuples on the way out 328 | else: 329 | return all_keys #Return a list of just keys 330 | 331 | 332 | 333 | def should_add(dbfiles: Union[str, list], key_str: str, existing_list: list, new_value: str) -> Boolean: 334 | '''Make a decision about whether we should add a new value to an existing list.''' 335 | 336 | if not dbfiles: 337 | dbfile_list: list = [] 338 | elif isinstance(dbfiles, (list, tuple)): 339 | dbfile_list = dbfiles 340 | else: 341 | dbfile_list = [dbfiles] 342 | 343 | decision = True 344 | #Don't add a country code (like "JP") to the ip_locations database if there's already an entry there that starts with that country code (like "JP;Japan/Tokyo/Tokyo") 345 | #todo: look for ip_locations and sqlite3 in the filename somewhere, not necessarily at the end 346 | #Note: this handles the case where the longer geoip string is already there 347 | #and we're considering adding the 2 character country code, but not the case where the 2 character 348 | #country code is already there and we're adding the longer string. 349 | for dbfile in dbfile_list: 350 | if dbfile.endswith( ('ip_locations.sqlite3') ) and len(existing_list) > 0 and len(new_value) == 2: 351 | for one_exist in existing_list: 352 | if one_exist.startswith(new_value + ';'): 353 | decision = False 354 | 355 | #0.0.0.0 is a valid key_str for some record types ("DO,0.0.0.0,reputation,...", ) 356 | if key_str in ('', '0000:0000:0000:0000:0000:0000:0000:0000'): 357 | decision = False 358 | elif key_str in ('127.0.0.1', '0000:0000:0000:0000:0000:0000:0000:0001') and new_value != 'localhost': 359 | decision = False 360 | elif new_value in ('', '0.0.0.0', '0000:0000:0000:0000:0000:0000:0000:0000'): 361 | decision = False 362 | elif new_value == [None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]: 363 | decision = False 364 | 365 | #Add valid character checks 366 | 367 | return decision 368 | 369 | 370 | def add_to_db_list(dbfiles: Union[str, list], key_str: str, new_value: str) -> Boolean: 371 | """Inside the given database, add the new_value to the list for key_str and write it back if changed.""" 372 | #Assumes the Value part of the database record is a list 373 | #Because we're doing a read-modify-update on dbfile[key_str], we have to put an exclusive transaction around the read-modify-write 374 | #so we don't get two writers writing to the same record (which is very likely to happen!). 375 | #This also means we have to pull in the two SQL commands (SELECT and REPLACE) under a single sqlite3.connect so we can have a transaction around both. 376 | 377 | already_inserted = False 378 | existing_list = None 379 | modified_rows = 0 380 | 381 | if not dbfiles: 382 | dbfile: str = '' 383 | elif isinstance(dbfiles, (list, tuple)): 384 | dbfile = dbfiles[0] 385 | else: 386 | dbfile = dbfiles 387 | 388 | if dbfile: #If dbfile is None, don't do anything. 389 | if not os.path.exists(dbfile): 390 | setup_db(dbfile) 391 | 392 | #todo: remove this 393 | current_val_list = select_key(dbfile, key_str) #Perform an early (read-only) check to see if the value is already in; if so, skip. THIS ASSUMES that removals are unlikely. 394 | if current_val_list and new_value in current_val_list: 395 | already_inserted = True 396 | else: 397 | with sqlite3.connect(dbfile, timeout=sqlite_timeout) as conn: 398 | 399 | conn.execute("BEGIN EXCLUSIVE TRANSACTION") 400 | entry_cursor = conn.execute("SELECT JSON_STR FROM main WHERE KEY_STR=?", [key_str]) 401 | entry = entry_cursor.fetchall() 402 | if len(entry) > 0: 403 | existing_list = json.loads(entry[0][0]) 404 | 405 | if existing_list is None: 406 | existing_list = [] 407 | if new_value not in existing_list and should_add(dbfile, key_str, existing_list, new_value): 408 | existing_list.append(new_value) 409 | modified_rows = conn.execute("REPLACE INTO main (KEY_STR, JSON_STR) values (?, ?)", (key_str, json.dumps(existing_list))).rowcount 410 | else: 411 | already_inserted = True 412 | #if verbose_status: 413 | # sys.stderr.write(' ') 414 | # sys.stderr.flush() 415 | conn.commit() 416 | 417 | return already_inserted or (modified_rows >= 1) 418 | 419 | 420 | #Deprecated - use add_to_db_dict instead 421 | def add_to_db_multiple_lists(dbfiles: Union[str, list], key_value_list: list) -> Boolean: # pylint: disable=too-many-branches 422 | """Inside the given database, process multiple key/value lists/tuples. For each value, add it to the existing list if not already there.""" 423 | #key_value_list is in this form: 424 | #[ 425 | # [key1, [value1, value2, value3...]], 426 | # [key2, [value4]], 427 | # [key3, [value5, value6]] 428 | #] 429 | #This code will also accept 430 | # (key2, value4), 431 | #instead of 432 | # (key2, [value4]), 433 | # 434 | #This approach allows us to commit a large number of writes without requiring a full database rewrite for every key-value pair (which appears to be the case for sqlite3. 435 | #The total number of tuples handed in this way should be limited; while some number greater than 1 will reduce total writes, 436 | #the more lines there are the longer the database is held with an exclusive lock, perhaps leading to locking out other users. 437 | #Perhaps some number between 10 and 1000, then sleeping a small fraction of a second and doing it again. 438 | 439 | any_changes_made: Boolean = False 440 | modified_rows: int = 0 441 | 442 | existing_cache: dict = {} #This holds key-value pairs which 1) are pulled out of the database, 2) have new values appended, and 3) are written back just before we release the lock. 443 | 444 | if not dbfiles: 445 | dbfile: str = '' 446 | elif isinstance(dbfiles, (list, tuple)): 447 | dbfile = dbfiles[0] 448 | else: 449 | dbfile = dbfiles 450 | 451 | if dbfile: #If dbfile is None, don't do anything. 452 | if not os.path.exists(dbfile): 453 | setup_db(dbfile) 454 | 455 | with sqlite3.connect(dbfile, timeout=sqlite_timeout) as conn: 456 | #We need to protect with an exclusive transaction...commit pair so that no changes can happen to the existing_lists while we pull in all these changes. 457 | conn.execute("BEGIN EXCLUSIVE TRANSACTION") 458 | 459 | #Process each key/value pair in key_value_list. 460 | for addition_tuple in key_value_list: 461 | addition_key = addition_tuple[0] 462 | #If this key is in the database, we pull its existing values back (or assign an empty list if not) 463 | if addition_key not in existing_cache: 464 | existing_cache[addition_key] = [] 465 | entry_cursor = conn.execute("SELECT JSON_STR FROM main WHERE KEY_STR=?", [addition_key]) 466 | entry = entry_cursor.fetchall() 467 | if len(entry) > 0: 468 | existing_cache[addition_key] = json.loads(entry[0][0]) 469 | 470 | #Now that we have the existing entries for that key, we add new entries provided by key_value_list. 471 | if isinstance(addition_tuple[1], (list, tuple)): 472 | for new_value in addition_tuple[1]: #addition_tuple[1] is the list/tuple of new values to add. 473 | if new_value not in existing_cache[addition_key] and should_add(dbfile, addition_key, existing_cache[addition_key], new_value): 474 | existing_cache[addition_key].append(new_value) 475 | any_changes_made = True 476 | else: #Since it's not a list or tuple, we assume it's a single value to process 477 | new_value = addition_tuple[1] #addition_tuple[1] is the sole new value to add. 478 | if new_value not in existing_cache[addition_key] and should_add(dbfile, addition_key, existing_cache[addition_key], new_value): 479 | existing_cache[addition_key].append(new_value) 480 | any_changes_made = True 481 | 482 | #Only write back existing blocks at the last moment. (Future: only write the changed ones.) 483 | if any_changes_made: 484 | for one_key in existing_cache: # pylint: disable=consider-using-dict-items 485 | #Ideally we'd use conn.executemany and feed it existing_cache.items() , but we need the existing_lists converted by json.dumps, so I don't think we can. 486 | modified_rows += conn.execute("REPLACE INTO main (KEY_STR, JSON_STR) values (?, ?)", (one_key, json.dumps(existing_cache[one_key]))).rowcount 487 | if verbose_status: 488 | sys.stderr.write('.') 489 | else: 490 | if verbose_status: 491 | sys.stderr.write(' ') 492 | 493 | conn.commit() 494 | if verbose_status: 495 | #sys.stderr.write(' Done.\n') 496 | sys.stderr.flush() 497 | 498 | return (not any_changes_made) or (modified_rows >= 1) 499 | 500 | 501 | 502 | 503 | def add_to_db_dict(dbfiles: Union[str, list], key_value_dict: dict) -> Boolean: # pylint: disable=too-many-branches 504 | """Inside the given database, process multiple key/value lists/tuples. For each value, add it to the existing list if not already there.""" 505 | #key_value_list is in this form: 506 | #{ 507 | # key1: [value1, value2, value3...], 508 | # key2: [value4], 509 | # key3: [value5, value6] 510 | #} 511 | # 512 | #This approach allows us to commit a large number of writes without requiring a full database rewrite for every key-value pair (which appears to be the case for sqlite3. 513 | #The total number of tuples handed in this way should be limited; while some number greater than 1 will reduce total writes, 514 | #the more lines there are the longer the database is held with an exclusive lock, perhaps leading to locking out other users. 515 | #Perhaps some number between 10 and 1000, then sleeping a small fraction of a second and doing it again. 516 | 517 | any_changes_made: Boolean = False 518 | modified_rows: int = 0 519 | 520 | existing_cache: dict = {} #This holds key-value pairs which 1) are pulled out of the database, 2) have new values appended, and 3) are written back just before we release the lock. 521 | 522 | if not dbfiles: 523 | dbfile: str = '' 524 | elif isinstance(dbfiles, (list, tuple)): 525 | dbfile = dbfiles[0] 526 | else: 527 | dbfile = dbfiles 528 | 529 | if dbfile: #If dbfile is None, don't do anything. 530 | if not os.path.exists(dbfile): 531 | setup_db(dbfile) 532 | 533 | with sqlite3.connect(dbfile, timeout=sqlite_timeout) as conn: 534 | #We need to protect with an exclusive transaction...commit pair so that no changes can happen to the existing_lists while we pull in all these changes. 535 | conn.execute("BEGIN EXCLUSIVE TRANSACTION") 536 | 537 | #Process each key/value pair in key_value_dict. 538 | for addition_key in key_value_dict: 539 | #If this key is in the database, we pull its existing values back (or assign an empty list if not) 540 | if addition_key not in existing_cache: 541 | existing_cache[addition_key] = [] 542 | entry_cursor = conn.execute("SELECT JSON_STR FROM main WHERE KEY_STR=?", [addition_key]) 543 | entry = entry_cursor.fetchall() 544 | if len(entry) > 0: 545 | existing_cache[addition_key] = json.loads(entry[0][0]) 546 | 547 | #Now that we have the existing entries for that key, we add new entries provided by key_value_list. 548 | if isinstance(key_value_dict[addition_key], list): 549 | for new_value in key_value_dict[addition_key]: #key_value_dict[addition_key] is the list of new values to add. 550 | if new_value not in existing_cache[addition_key] and should_add(dbfile, addition_key, existing_cache[addition_key], new_value): 551 | existing_cache[addition_key].append(new_value) 552 | any_changes_made = True 553 | else: #Since it's not a list, we assume it's a single value to process 554 | new_value = key_value_dict[addition_key] #key_value_dict[addition_key] is the sole new value to add. 555 | if new_value not in existing_cache[addition_key] and should_add(dbfile, addition_key, existing_cache[addition_key], new_value): 556 | existing_cache[addition_key].append(new_value) 557 | any_changes_made = True 558 | 559 | #Only write back existing blocks at the last moment. (Future: only write the changed ones.) 560 | if any_changes_made: 561 | for one_key in existing_cache: # pylint: disable=consider-using-dict-items 562 | #Ideally we'd use conn.executemany and feed it existing_cache.items() , but we need the existing_lists converted by json.dumps, so I don't think we can. 563 | modified_rows += conn.execute("REPLACE INTO main (KEY_STR, JSON_STR) values (?, ?)", (one_key, json.dumps(existing_cache[one_key]))).rowcount 564 | if verbose_status: 565 | sys.stderr.write('.') 566 | else: 567 | if verbose_status: 568 | sys.stderr.write(' ') 569 | 570 | conn.commit() 571 | if verbose_status: 572 | #sys.stderr.write(' Done.\n') 573 | sys.stderr.flush() 574 | 575 | return (not any_changes_made) or (modified_rows >= 1) 576 | 577 | 578 | def buffer_merges(dbfiles: Union[str, list], key_str: str, new_values: list, max_adds: int) -> Boolean: 579 | """Buffer up writes that will eventually get merged into their respective databases. 580 | You _must_ call this with buffer_merges('', '', [], 0) to flush any remaining writes before shutting down.""" 581 | 582 | if 'last_flush' not in buffer_merges.__dict__: 583 | buffer_merges.last_flush = time.time() # type: ignore 584 | #It appears we have to ignore persistent variable types as mypy doesn't recognize them. 585 | #We set "last_flush" to now when we first enter this function. Used to make sure nothing stays around forever. 586 | 587 | if 'additions' not in buffer_merges.__dict__: 588 | buffer_merges.additions = {} # type: ignore 589 | #Key is the database file, value is a list of queued writes for that database:: 590 | #{"dbfile1": 591 | # [ 592 | # [key1, [value1, value2, value3...]], 593 | # [key2, [value4]], 594 | # [key3, [value5, value6]] 595 | # ] 596 | #} 597 | 598 | success = True 599 | 600 | if not dbfiles: 601 | dbfile: str = '' 602 | elif isinstance(dbfiles, (list, tuple)): 603 | dbfile = dbfiles[0] 604 | else: 605 | dbfile = dbfiles 606 | 607 | if dbfile and new_values: #We don't check for an empty key_str as it's technically legal to have "" as a key. 608 | if not os.path.exists(dbfile): 609 | setup_db(dbfile) 610 | if isinstance(new_values, (list, tuple)): 611 | new_values_list = new_values 612 | else: 613 | new_values_list = [new_values] 614 | #First, add any new values to the "additions" structure. 615 | if dbfile not in buffer_merges.additions: # type: ignore 616 | buffer_merges.additions[dbfile] = [ [key_str, new_values_list] ] # type: ignore 617 | else: 618 | found_key = None 619 | for x in range(len(buffer_merges.additions[dbfile])): # type: ignore 620 | if buffer_merges.additions[dbfile][x][0] == key_str: # type: ignore 621 | found_key = x 622 | break 623 | if found_key is None: 624 | #Add a new line with the new values 625 | #found_key = len(buffer_merges.additions[dbfile]) #This is technically where the new entry will be appended to, but we don't need found_key to append to the list. 626 | buffer_merges.additions[dbfile].append([key_str, new_values_list]) # type: ignore 627 | else: 628 | #Merge new values into buffer_merges.additions[dbfile][found_key] 629 | for one_val in new_values_list: 630 | if one_val not in buffer_merges.additions[dbfile][found_key][1]: # type: ignore 631 | buffer_merges.additions[dbfile][found_key][1].append(one_val) # type: ignore 632 | 633 | if time.time() - buffer_merges.last_flush > 600: # type: ignore 634 | #Note; this forces a flush the _first time we're called_ more than 10 minutes since the last. This does not force writes until we get called! 635 | force_flush = True 636 | buffer_merges.last_flush = time.time() # type: ignore 637 | else: 638 | force_flush = False 639 | 640 | for one_db in buffer_merges.additions: # type: ignore 641 | # pylint: disable=consider-using-dict-items 642 | if force_flush or len(buffer_merges.additions[one_db]) >= max_adds: # type: ignore 643 | #Push out if too many items in queue for this database or it's been over 10 minutes since the last full flush 644 | success = success and add_to_db_multiple_lists(one_db, buffer_merges.additions[one_db]) # type: ignore 645 | buffer_merges.additions[one_db] = [] # type: ignore 646 | 647 | return success 648 | 649 | 650 | def remove_from_db_multiple_lists(dbfiles: Union[str, list], key_value_list: list) -> Boolean: # pylint: disable=too-many-branches 651 | """Inside the given database, process multiple key/value lists/tuples. For each value, remove it from the existing list if there.""" 652 | #key_value_list is in this form: 653 | #[ 654 | # [key1, [value1, value2, value3...]], 655 | # [key2, [value4]], 656 | # [key3, [value5, value6]] 657 | #] 658 | #This code will also accept 659 | # (key2, value4), 660 | #instead of 661 | # (key2, [value4]), 662 | # 663 | #This approach allows us to commit a large number of writes without requiring a full database rewrite for every key-value pair (which appears to be the case for sqlite3. 664 | #The total number of tuples handed in this way should be limited; while some number greater than 1 will reduce total writes, 665 | #the more lines there are the longer the database is held with an exclusive lock, perhaps leading to locking out other users. 666 | #Perhaps some number between 10 and 1000, then sleeping a small fraction of a second and doing it again. 667 | 668 | any_changes_made = False 669 | modified_rows = 0 670 | 671 | existing_cache: dict = {} #This holds key-value pairs which 1) are pulled out of the database, 2) may have values removed, and 3) are written back just before we release the lock. 672 | 673 | if not dbfiles: 674 | dbfile: str = '' 675 | elif isinstance(dbfiles, (list, tuple)): 676 | dbfile = dbfiles[0] 677 | else: 678 | dbfile = dbfiles 679 | 680 | if dbfile: #If dbfile is None, don't do anything. 681 | if not os.path.exists(dbfile): 682 | setup_db(dbfile) 683 | 684 | with sqlite3.connect(dbfile, timeout=sqlite_timeout) as conn: 685 | #We need to protect with an exclusive transaction...commit pair so that no changes can happen to the existing_lists while we pull in all these changes. 686 | conn.execute("BEGIN EXCLUSIVE TRANSACTION") 687 | 688 | #Process each key/value pair in key_value_list. 689 | for removal_tuple in key_value_list: 690 | removal_key = removal_tuple[0] 691 | #If this key is in the database, we pull its existing values back (or assign an empty list if not) 692 | if removal_key not in existing_cache: 693 | existing_cache[removal_key] = [] 694 | entry_cursor = conn.execute("SELECT JSON_STR FROM main WHERE KEY_STR=?", [removal_key]) 695 | entry = entry_cursor.fetchall() 696 | if len(entry) > 0: 697 | existing_cache[removal_key] = json.loads(entry[0][0]) 698 | 699 | #Now that we have the existing entries for that key, we remove all entries provided by key_value_list. 700 | if isinstance(removal_tuple[1], (list, tuple)): 701 | for del_value in removal_tuple[1]: #removal_tuple[1] is the list/tuple of new values to remove. 702 | while del_value in existing_cache[removal_key]: 703 | existing_cache[removal_key].remove(del_value) 704 | any_changes_made = True 705 | else: #Since it's not a list or tuple, we assume it's a single value to process 706 | del_value = removal_tuple[1] #removal_tuple[1] is the sole new value to remove. 707 | while del_value in existing_cache[removal_key]: 708 | existing_cache[removal_key].remove(del_value) 709 | any_changes_made = True 710 | 711 | #Only write back existing blocks at the last moment. (Future: only write the changed ones.) 712 | if any_changes_made: 713 | for one_key in existing_cache: # pylint: disable=consider-using-dict-items 714 | #Ideally we'd use conn.executemany and feed it existing_cache.items() , but we need the existing_lists converted by jsson.dumps, so I don't think we can. 715 | if existing_cache[one_key] == []: 716 | modified_rows += conn.execute("DELETE FROM main WHERE KEY_STR=?", (one_key,)).rowcount 717 | if verbose_status: 718 | sys.stderr.write('d') 719 | else: 720 | modified_rows += conn.execute("REPLACE INTO main (KEY_STR, JSON_STR) values (?, ?)", (one_key, json.dumps(existing_cache[one_key]))).rowcount 721 | if verbose_status: 722 | sys.stderr.write('.') 723 | else: 724 | if verbose_status: 725 | sys.stderr.write(' ') 726 | 727 | conn.commit() 728 | if verbose_status: 729 | #sys.stderr.write(' Done.\n') 730 | sys.stderr.flush() 731 | 732 | return (not any_changes_made) or (modified_rows >= 1) 733 | 734 | 735 | def buffer_delete_vals(dbfiles: Union[str, list], key_str: str, delete_values: list, max_dels: int) -> Boolean: 736 | """Buffer up values that will eventually get removed from their respective databases. 737 | You _must_ call this with buffer_delete_vals('', '', [], 0) to flush any remaining writes before shutting down.""" 738 | 739 | if 'last_flush' not in buffer_delete_vals.__dict__: 740 | buffer_delete_vals.last_flush = time.time() # type: ignore 741 | #We set "last_flush" to now when we first enter this function. Used to make sure nothing stays around forever. 742 | 743 | if 'removals' not in buffer_delete_vals.__dict__: 744 | buffer_delete_vals.removals = {} # type: ignore 745 | #Key is the database file, value is a list of queued writes for that database:: 746 | #{"dbfile1": 747 | # [ 748 | # [key1, [value1, value2, value3...]], 749 | # [key2, [value4]], 750 | # [key3, [value5, value6]] 751 | # ] 752 | #} 753 | 754 | success = True 755 | 756 | if not dbfiles: 757 | dbfile: str = '' 758 | elif isinstance(dbfiles, (list, tuple)): 759 | dbfile = dbfiles[0] 760 | else: 761 | dbfile = dbfiles 762 | 763 | if dbfile and delete_values: #We don't check for an empty key_str as it's technically legal to have "" as a key. 764 | if not os.path.exists(dbfile): 765 | setup_db(dbfile) 766 | if isinstance(delete_values, (list, tuple)): 767 | delete_values_list = delete_values 768 | else: 769 | delete_values_list = [delete_values] 770 | #First, add any deletion values to the "removals" structure. 771 | if dbfile not in buffer_delete_vals.removals: # type: ignore 772 | buffer_delete_vals.removals[dbfile] = [ [key_str, delete_values_list] ] # type: ignore 773 | else: 774 | found_key = None 775 | for x in range(len(buffer_delete_vals.removals[dbfile])): # type: ignore 776 | if buffer_delete_vals.removals[dbfile][x][0] == key_str: # type: ignore 777 | found_key = x 778 | break 779 | if found_key is None: 780 | #Add a new line with the new values 781 | #found_key = len(buffer_delete_vals.removals[dbfile]) #This is technically where the new entry will be appended to, but we don't need found_key to append to the list. 782 | buffer_delete_vals.removals[dbfile].append([key_str, delete_values_list]) # type: ignore 783 | else: 784 | #Merge new values into buffer_delete_vals.removals[dbfile][found_key] 785 | for one_val in delete_values_list: 786 | if one_val not in buffer_delete_vals.removals[dbfile][found_key][1]: # type: ignore 787 | buffer_delete_vals.removals[dbfile][found_key][1].append(one_val) # type: ignore 788 | 789 | if time.time() - buffer_delete_vals.last_flush > 600: # type: ignore 790 | #Note; this forces a flush the _first time we're called_ more than 10 minutes since the last. This does not force writes until we get called! 791 | force_flush = True 792 | buffer_delete_vals.last_flush = time.time() # type: ignore 793 | else: 794 | force_flush = False 795 | 796 | for one_db in buffer_delete_vals.removals: # type: ignore 797 | # pylint: disable=consider-using-dict-items 798 | if force_flush or len(buffer_delete_vals.removals[one_db]) >= max_dels: # type: ignore 799 | success = success and remove_from_db_multiple_lists(one_db, buffer_delete_vals.removals[one_db]) # type: ignore 800 | buffer_delete_vals.removals[one_db] = [] # type: ignore 801 | 802 | return success 803 | 804 | 805 | def add_to_db_list_large_value(dbfiles: Union[str, list], large_dbfiles: Union[str, list], key_str: str, new_value: str, max_adds: int) -> Boolean: 806 | """Inside the given database, add the new_value to the list for key_str and write it back if changed.""" 807 | #Assumes you've already initialized the dbfile. 808 | #Also assumes the Value part of the database record is a list 809 | 810 | if not dbfiles: 811 | dbfile: str = '' 812 | elif isinstance(dbfiles, (list, tuple)): 813 | dbfile = dbfiles[0] 814 | else: 815 | dbfile = dbfiles 816 | if not large_dbfiles: 817 | large_dbfile: str = '' 818 | elif isinstance(large_dbfiles, (list, tuple)): 819 | large_dbfile = large_dbfiles[0] 820 | else: 821 | large_dbfile = large_dbfiles 822 | 823 | if dbfile and large_dbfile: 824 | if not os.path.exists(dbfile): 825 | setup_db(dbfile) 826 | if not os.path.exists(large_dbfile): 827 | setup_db(large_dbfile) 828 | value_sum = sha256_sum(new_value) 829 | #Old approach that added one item at a time to 2 databases 830 | #success2 = insert_key(large_dbfile, value_sum, [new_value]) 831 | #success1 = add_to_db_list(dbfile, key_str, value_sum) 832 | #New approach that buffers up writes 833 | success2 = buffer_merges(large_dbfile, value_sum, [new_value], max_adds) 834 | success1 = buffer_merges(dbfile, key_str, [value_sum], max_adds) 835 | #We can't do the following; the writes may not yet have made it out to disk as they're being buffered. 836 | #if paranoid: 837 | # valsequal = False 838 | # retrieved_object = select_key_large_value(dbfile, large_dbfile, key_str) 839 | # for one_retrieved in retrieved_object: 840 | # if new_value == one_retrieved: 841 | # valsequal = True 842 | # if valsequal is False: 843 | # sys.stderr.write("Mismatch in add_to_db_list_large_value\n") 844 | # sys.stderr.write(str(key_str) + "\n") 845 | # sys.stderr.write(str(new_value) + "\n") 846 | # sys.stderr.write(str(value_sum) + "\n") 847 | # sys.stderr.write(str(retrieved_object) + "\n") 848 | # sys.stderr.flush() 849 | # sys.exit(1) 850 | #else: 851 | valsequal = True 852 | 853 | return valsequal and success1 and success2 854 | -------------------------------------------------------------------------------- /pcap_stats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Print statistics of a pcap file or packets arriving on an interface.""" 3 | 4 | from __future__ import annotations 5 | 6 | #Dedicated to the memory of Alan Paller, whose vision of a secure 7 | #Internet gave thousands of us a chance to learn and grow. 8 | 9 | 10 | __version__ = '0.0.63' 11 | 12 | __author__ = 'William Stearns' 13 | __copyright__ = 'Copyright 2021, William Stearns' 14 | __credits__ = ['William Stearns'] 15 | __email__ = 'william.l.stearns@gmail.com' 16 | __license__ = 'GPL 3.0' 17 | __maintainer__ = 'William Stearns' 18 | __status__ = 'Production' #Prototype, Development or Production 19 | 20 | 21 | 22 | import os 23 | import sys 24 | import time 25 | import tempfile 26 | import errno 27 | import gzip #Lets us read from gzip-compressed pcap files 28 | import bz2 #Lets us read from bzip2-compressed pcap files 29 | import re #Regex matching on UUID hostnames 30 | import binascii 31 | from typing import List, Optional, Union, cast 32 | 33 | from db_lib import add_to_db_dict, buffer_merges, select_key 34 | 35 | try: 36 | #from scapy.all import * 37 | from scapy.all import ARP, DNS, Dot3, Ether, GRE, ICMP, IP, IPv6, LLC, Loopback, NBNSQueryResponse, NBTDatagram, Scapy_Exception, STP, TCP, UDP, sniff # pylint: disable=no-name-in-module 38 | from scapy.config import conf 39 | except ImportError: 40 | sys.stderr.write('Unable to load the scapy library. Perhaps run sudo apt install python3-pip || sudo yum install python3-pip ; sudo pip3 install scapy ?\n') 41 | sys.stderr.flush() 42 | sys.exit(1) 43 | 44 | try: 45 | from scapy.contrib import erspan # pylint: disable=unused-import 46 | erspan_loaded = True 47 | except ImportError: 48 | sys.stderr.write('Unable to load the erspan module from the scapy library contrib section. Perhaps run sudo apt install python3-pip || sudo yum install python3-pip ; sudo pip3 install scapy ?\n') 49 | sys.stderr.flush() 50 | erspan_loaded = False 51 | #sys.exit(1) 52 | 53 | try: 54 | from passer_lib import DNS_extract, explode_ip, generate_meta_from_packet 55 | except ImportError: 56 | sys.stderr.write('Unable to load the passer_lib library.\n') 57 | sys.stderr.flush() 58 | sys.exit(1) 59 | 60 | 61 | def debug_out(output_string: str) -> None: 62 | """Send debuging output to stderr.""" 63 | 64 | if cl_args['devel']: 65 | sys.stderr.write(output_string + '\n') 66 | sys.stderr.flush() 67 | 68 | 69 | def mkdir_p(path: str) -> None: 70 | """Create an entire directory branch. Will not complain if the directory already exists.""" 71 | 72 | if not os.path.isdir(path): 73 | try: 74 | os.makedirs(path) 75 | except OSError as exc: 76 | if exc.errno == errno.EEXIST and os.path.isdir(path): 77 | pass 78 | elif exc.errno == errno.EEXIST: 79 | sys.stderr.write(path + ' exists, so we cannot create it as a directory. Exiting.\n') 80 | sys.stderr.flush() 81 | sys.exit(1) 82 | else: 83 | raise 84 | 85 | 86 | def force_string(raw_string: Union[bytes|str|List]) -> str: 87 | """Make sure the returned object is a string.""" 88 | 89 | 90 | if sys.version_info > (3, 0): #Python 3 91 | if isinstance(raw_string, bytes): 92 | retval = cast(str, raw_string.decode("utf-8", 'replace')) 93 | elif isinstance(raw_string, str): 94 | retval = cast(str, raw_string) 95 | elif isinstance(raw_string, list): 96 | retval = cast(str, ' '.join([force_string(listitem) for listitem in raw_string])) 97 | #print(str(type(raw_string))) 98 | #print("huh:" + str(raw_string)) 99 | #sys.exit() 100 | else: 101 | print(str(type(raw_string))) 102 | print("huh:" + str(raw_string)) 103 | sys.exit() 104 | retval = str(raw_string) 105 | else: 106 | retval = str(raw_string) 107 | 108 | return retval 109 | 110 | 111 | def open_bzip2_file_to_tmp_file(bzip2_filename: str) -> str: 112 | """Open up a bzip2 file to a temporary file and return that filename.""" 113 | 114 | tmp_fd, tmp_path = tempfile.mkstemp() 115 | try: 116 | with os.fdopen(tmp_fd, 'wb') as tmp_h, bz2.BZ2File(bzip2_filename, 'rb') as compressed_file: 117 | for data in iter(lambda: compressed_file.read(100 * 1024), b''): 118 | tmp_h.write(data) 119 | return tmp_path 120 | except: 121 | sys.stderr.write("While expanding bzip2 file, unable to write to " + str(tmp_path) + ', exiting.\n') 122 | raise 123 | 124 | 125 | def open_gzip_file_to_tmp_file(gzip_filename: str) -> str: 126 | """Open up a gzip file to a temporary file and return that filename.""" 127 | 128 | tmp_fd, tmp_path = tempfile.mkstemp() 129 | try: 130 | with os.fdopen(tmp_fd, 'wb') as tmp_h, gzip.GzipFile(gzip_filename, 'rb') as compressed_file: 131 | for data in iter(lambda: compressed_file.read(100 * 1024), b''): 132 | tmp_h.write(data) 133 | return tmp_path 134 | except: 135 | sys.stderr.write("While expanding gzip file, unable to write to " + str(tmp_path) + ', exiting.\n') 136 | raise 137 | 138 | 139 | def packet_layers(pkt) -> List: 140 | """Returns a list of packet layers.""" 141 | 142 | layers = [] 143 | counter = 0 144 | while True: 145 | layer = pkt.getlayer(counter) 146 | if layer is not None: 147 | #print(layer.name) 148 | layers.append(layer.name) 149 | else: 150 | break 151 | counter += 1 152 | 153 | return layers 154 | #Sample return ['Ethernet', 'IP', 'TCP'] 155 | 156 | 157 | def packet_len(packet, whichlayer) -> int: # pylint: disable=unused-argument 158 | """Finds the appropriate length of the packet based on user preference.""" 159 | #FIXME - only the IP/IPv6 option works at the moment. 160 | 161 | #print(str(len(p)) + " _6_ " + str(p[IPv6].plen)) 162 | 163 | if cl_args['length'] == 'ip': 164 | if packet.haslayer(IP): 165 | #p[IP].len returns the IP header onwards, but not the ethernet header above it. 166 | pack_len = packet[IP].len 167 | elif packet.haslayer(IPv6): 168 | #p[IPv6].plen returns the IP header onwards, but not the ethernet header above it. 169 | pack_len = packet[IPv6].plen 170 | elif packet.haslayer(ARP): 171 | #p[ARP].len returns the ARP header onwards, but not the ethernet header above it. 172 | pack_len = packet[ARP].plen 173 | #FIXME - add else: here to handle other types 174 | #elif cl_args['length'] == 'layer': 175 | # pack_len = 0 176 | # if packet.haslayer(IP): 177 | # #p[IP].len returns the IP header onwards, but not the ethernet header above it. 178 | # pack_len = packet[whichlayer].len 179 | # elif packet.haslayer(IPv6): 180 | # #p[IPv6].plen returns the IP header onwards, but not the ethernet header above it. 181 | # pack_len = packet[whichlayer].plen 182 | #elif cl_args['length'] == 'payload': 183 | # pack_len = 0 184 | #elif cl_args['length'] == 'ethernet': 185 | # pack_len = 0 186 | # #len(p) returns the full size of the packet including the ethernet header (and possibly 40 more bytes?) 187 | else: 188 | pack_len = 0 189 | 190 | return pack_len 191 | 192 | 193 | def inc_stats(one_label: str, length: int) -> None: 194 | """Increment the packet count and total size for this layer.""" 195 | 196 | if "p_stats" not in inc_stats.__dict__: 197 | inc_stats.p_stats = {'count': [0, 0]} # type: ignore 198 | 199 | if one_label not in inc_stats.p_stats: # type: ignore 200 | inc_stats.p_stats[one_label] = [0, 0] # type: ignore 201 | inc_stats.p_stats[one_label][0] += 1 # type: ignore 202 | inc_stats.p_stats[one_label][1] += length # type: ignore 203 | 204 | 205 | def processpacket(p): 206 | """Extract statistics from a single packet.""" 207 | 208 | if "field_filter" not in processpacket.__dict__: 209 | processpacket.field_filter = {'count': '', 'ARP': 'arp', 210 | 'DHCP6 IA Address Option (IA TA or IA NA suboption)': 'udp port 546 or udp port 547', 'DHCP6 Preference Option': 'udp port 546 or udp port 547', 'DHCP6 Server Identifier Option': 'udp port 546 or udp port 547', 'DHCP6 Status Code Option': 'udp port 546 or udp port 547', 'DHCPv6 Confirm Message': 'udp port 546 or udp port 547', 'DHCPv6 Reply Message': 'udp port 546 or udp port 547', 211 | 'DNS': 'port 53 or udp port 5353 or udp port 5355', 'ESP': 'ip proto esp', 212 | 'ICMPv6 Neighbor Discovery - Neighbor Advertisement': 'icmp6[0] == 136', 'icmp6_136.0': 'icmp6[0] == 136', 'ICMPv6 Neighbor Discovery - Neighbor Solicitation': 'icmp6[0] == 135', 'icmp6_135.0': 'icmp6[0] == 135', 'ICMPv6 Neighbor Discovery - Router Advertisement': 'icmp6[0] == 134', 'icmp6_134.0': 'icmp6[0] == 134', 'ICMPv6 Neighbor Discovery - Router Solicitation': 'icmp6[0] == 133', 'IP': 'ip', 'ICMP': 'icmp', 'IPv6': 'ip6', 'ISAKMP': 'port 500 or udp port 4500', 213 | 'Loopback': '-i lo', 214 | 'NTPHeader': 'udp port 123', 'RIP_entry': 'udp port 520', 'RIP_header': 'udp port 520', 'SNMP': 'port 161 or port 162', 'TCP': 'tcp', 'TFTP_Read_Request': 'port 69', 'TFTP_opcode': 'port 69', 'UDP': 'udp', '802.1Q': 'vlan', 215 | 'TCP_FLAGS_': 'tcp[12:2] & 0x01ff = 0x0000', 'TCP_FLAGS_F': 'tcp[12:2] & 0x01ff = 0x0001', 'TCP_FLAGS_S': 'tcp[12:2] & 0x01ff = 0x0002', 'TCP_FLAGS_R': 'tcp[12:2] & 0x01ff = 0x0004', 'TCP_FLAGS_SR': 'tcp[12:2] & 0x01ff = 0x0006', 'TCP_FLAGS_RP': 'tcp[12:2] & 0x01ff = 0x000C', 216 | 'TCP_FLAGS_A': 'tcp[12:2] & 0x01ff = 0x0010', 'TCP_FLAGS_FA': 'tcp[12:2] & 0x01ff = 0x0011', 'TCP_FLAGS_SA': 'tcp[12:2] & 0x01ff = 0x0012', 'TCP_FLAGS_RA': 'tcp[12:2] & 0x01ff = 0x0014', 'TCP_FLAGS_FRA': 'tcp[12:2] & 0x01ff = 0x0015', 'TCP_FLAGS_PA': 'tcp[12:2] & 0x01ff = 0x0018', 'TCP_FLAGS_FPA': 'tcp[12:2] & 0x01ff = 0x0019', 'TCP_FLAGS_RPA': 'tcp[12:2] & 0x01ff = 0x001C', 217 | 'TCP_FLAGS_U': 'tcp[12:2] & 0x01ff = 0x0020', 'TCP_FLAGS_SU': 'tcp[12:2] & 0x01ff = 0x0022', 'TCP_FLAGS_FPU': 'tcp[12:2] & 0x01ff = 0x0029', 'TCP_FLAGS_FSPU': 'tcp[12:2] & 0x01ff = 0x002b', 218 | 'TCP_FLAGS_SAU': 'tcp[12:2] & 0x01ff = 0x0032', 'TCP_FLAGS_FSRPAU': 'tcp[12:2] & 0x01ff = 0x003f', 219 | 'TCP_FLAGS_AE': 'tcp[12:2] & 0x01ff = 0x0050', 'TCP_FLAGS_FAE': 'tcp[12:2] & 0x01ff = 0x0051', 'TCP_FLAGS_SAE': 'tcp[12:2] & 0x01ff = 0x0052', 220 | 'TCP_FLAGS_AC': 'tcp[12:2] & 0x01ff = 0x0090', 'TCP_FLAGS_RAC': 'tcp[12:2] & 0x01ff = 0x0094', 'TCP_FLAGS_SPAC': 'tcp[12:2] & 0x01ff = 0x0095', 'TCP_FLAGS_PAC': 'tcp[12:2] & 0x01ff = 0x0098', 221 | 'TCP_FLAGS_SEC': 'tcp[12:2] & 0x01ff = 0x00c2', 'TCP_FLAGS_FSPEC': 'tcp[12:2] & 0x01ff = 0x00cb', 222 | 'TCP_FLAGS_SAEC': 'tcp[12:2] & 0x01ff = 0x00d2', 223 | 'TCP_FLAGS_AN': 'tcp[12:2] & 0x01ff = 0x0110', 'TCP_FLAGS_FAN': 'tcp[12:2] & 0x01ff = 0x0111', 'TCP_FLAGS_RAN': 'tcp[12:2] & 0x01ff = 0x0114', 224 | 'TCP_FLAGS_FSRPAUEN': 'tcp[12:2] & 0x01ff = 0x017f'} 225 | 226 | #Scapy flags 227 | #N NS 0x0100 (ECN Nonce - concealment protection. See https://en.wikipedia.org/wiki/Transmission_Control_Protocol) 228 | #C CWR 0x80 229 | #E ECN 0x40 230 | #U URG 0x20 231 | #A ACK 0x10 232 | #P PSH 0x08 233 | #R RST 0x04 234 | #S SYN 0x02 235 | #F FIN 0x01 236 | 237 | if "tcp_server_ports" not in processpacket.__dict__: 238 | processpacket.tcp_server_ports = [7, 13, 21, 22, 23, 25, 53, 79, 80, 88, 102, 110, 111, 113, 135, 139, 143, 389, 443, 445, 465, 514, 631, 902, 990, 993, 995, 1001, 1119, 1433, 1521, 1723, 2222, 2598, 3128, 3306, 3389, 3724, 5000, 5001, 5060, 5223, 5228, 5432, 5601, 5900, 7070, 7680, 8008, 8009, 8080, 8088, 8333, 8443, 9200, 9443, 13000, 49152] 239 | 240 | if "udp_server_ports" not in processpacket.__dict__: 241 | processpacket.udp_server_ports = [7, 53, 67, 123, 137, 138, 192, 443, 1900, 2190, 5002, 5353, 5355, 8200, 16384, 16385, 16386, 17500, 19305, 56833, 60682, 62988] 242 | 243 | if "local_ips" not in processpacket.__dict__: 244 | processpacket.local_ips = set([]) 245 | 246 | if "minstamp" not in processpacket.__dict__: 247 | processpacket.minstamp = None #None, or float holding the minimum timestamp (usually from the first packet) of any encountered packet 248 | if "maxstamp" not in processpacket.__dict__: 249 | processpacket.maxstamp = None #None, or float holding the maximum timestamp (usually from the last packet) of any encountered packet 250 | 251 | if "ipv4s_for_mac" not in processpacket.__dict__: 252 | processpacket.ipv4s_for_mac = {} #Key is a mac address, value is a set of IPv4 address strings 253 | if "ipv6s_for_mac" not in processpacket.__dict__: 254 | processpacket.ipv6s_for_mac = {} #Key is a mac address, value is a set of IPv4 address strings 255 | 256 | if "debug_shown" not in processpacket.__dict__: 257 | processpacket.debug_shown = [] #List of strings we've already shown 258 | 259 | #We reinstate this to hold all the writes for hostnames, to be later submitted with add_to_db_dict 260 | if 'dns_for_ip' not in processpacket.__dict__: 261 | processpacket.dns_for_ip = {} 262 | #This key_value_dict is in this form: 263 | #{ 264 | # key1: [value1, value2, value3...], 265 | # key2: [value4], 266 | # key3: [value5, value6] 267 | #} 268 | 269 | if 'ports_for_ip' not in processpacket.__dict__: #Dictionary; keys are IP addresses, values are sets of ports used by this IP (specifically, the ports at the IP's end of the connection) 270 | processpacket.ports_for_ip = {} 271 | 272 | if 'cast_type' not in processpacket.__dict__: #Dictionary; keys are IP addresses, values are one of 'broadcast', 'multicast', (or unicast, though we don't remember this as it's the default.) 273 | processpacket.cast_type = {} 274 | 275 | p_layers = packet_layers(p) 276 | 277 | prefs = {'nxdomain': False, 'devel': cl_args['devel'], 'quit': False} 278 | dests = {'unhandled': None} 279 | meta = generate_meta_from_packet(p, prefs, dests) 280 | 281 | if p.haslayer(IP): 282 | i_layer = p.getlayer(IP) 283 | p_len = packet_len(p, IP) 284 | proto = str(i_layer.proto) 285 | ttl = int(i_layer.ttl) 286 | sIP = i_layer.src 287 | dIP = i_layer.dst 288 | label = 'ip4_' + sIP 289 | inc_stats(label, p_len) 290 | processpacket.field_filter[label] = 'host ' + sIP 291 | label = 'ip4_' + dIP 292 | inc_stats(label, p_len) 293 | processpacket.field_filter[label] = 'host ' + dIP 294 | elif p.haslayer(IPv6): 295 | i_layer = p.getlayer(IPv6) 296 | p_len = packet_len(p, IPv6) 297 | proto = str(i_layer.nh) 298 | ttl = int(i_layer.hlim) 299 | sIP = i_layer.src 300 | dIP = i_layer.dst 301 | label = 'ip6_' + sIP 302 | inc_stats(label, p_len) 303 | processpacket.field_filter[label] = 'ip6 host ' + sIP 304 | label = 'ip6_' + dIP 305 | inc_stats(label, p_len) 306 | processpacket.field_filter[label] = 'ip6 host ' + dIP 307 | elif p.haslayer(ARP): 308 | i_layer = None 309 | p_len = packet_len(p, ARP) 310 | proto = None 311 | ttl = -1 312 | sIP = p.getlayer(ARP).psrc 313 | dIP = p.getlayer(ARP).pdst 314 | elif (p.haslayer(Ether) and p[Ether].type == 0x888E): #EAPOL packet; PAE=0x888E 315 | i_layer = None 316 | p_len = 0 #FIXME 317 | proto = None 318 | ttl = -1 319 | sIP = None 320 | dIP = None 321 | elif p.haslayer(LLC) or p.haslayer(STP): 322 | i_layer = None 323 | p_len = 0 #FIXME 324 | proto = None 325 | ttl = -1 326 | sIP = None 327 | dIP = None 328 | elif p_layers == ['Ethernet', 'Raw']: 329 | i_layer = None 330 | p_len = 0 #FIXME 331 | proto = None 332 | ttl = -1 333 | sIP = None 334 | dIP = None 335 | else: 336 | if p.haslayer(Ether): 337 | print("Ethernet type") 338 | print(p[Ether].type) 339 | p.show() 340 | sys.exit(99) 341 | i_layer = None 342 | p_len = 0 #FIXME 343 | proto = None 344 | ttl = -1 345 | sIP = None 346 | dIP = None 347 | 348 | inc_stats('count', p_len) 349 | 350 | if sIP and sIP not in ('0.0.0.0', '::') and not sIP.startswith(('169.254.', 'fe80:')) and p.haslayer(Ether): #We remember all the IPv4 and IPv6 addresses associated with a particular mac to decide later whether a mac address is a router. 351 | sMAC = p.getlayer(Ether).src 352 | if ':' in sIP: 353 | if sMAC not in processpacket.ipv6s_for_mac: 354 | processpacket.ipv6s_for_mac[sMAC] = set([]) 355 | processpacket.ipv6s_for_mac[sMAC].add(sIP) 356 | else: 357 | if sMAC not in processpacket.ipv4s_for_mac: 358 | processpacket.ipv4s_for_mac[sMAC] = set([]) 359 | processpacket.ipv4s_for_mac[sMAC].add(sIP) 360 | 361 | for a_layer in p_layers: 362 | if a_layer not in ignore_layers: 363 | inc_stats(a_layer, p_len) 364 | 365 | if p.haslayer(Ether): 366 | if p[Ether].dst == 'ff:ff:ff:ff:ff:ff': 367 | label = 'ethernet_broadcast' 368 | inc_stats(label, p_len) 369 | processpacket.field_filter[label] = 'ether broadcast' 370 | if dIP and (p.haslayer(IPv6) or p.haslayer(IP)): 371 | processpacket.cast_type[dIP] = 'broadcast' 372 | elif p[Ether].dst.startswith(('01:00:5e:', '33:33:', '01:80:c2:')): 373 | label = 'ethernet_multicast' 374 | inc_stats(label, p_len) 375 | processpacket.field_filter[label] = 'ether multicast' 376 | if dIP and (p.haslayer(IPv6) or p.haslayer(IP)): 377 | processpacket.cast_type[dIP] = 'multicast' 378 | else: 379 | label = 'ethernet_unicast' 380 | inc_stats(label, p_len) 381 | processpacket.field_filter[label] = 'not (ether broadcast) and not (ether multicast)' 382 | elif p.haslayer(Loopback) or p.haslayer(Dot3): 383 | pass 384 | else: 385 | #p.show() 386 | #sys.exit(34) 387 | label = 'non_ethernet' 388 | inc_stats(label, p_len) 389 | #processpacket.field_filter[label] = '...' #unsure 390 | 391 | 392 | if p.haslayer(DNS) and (isinstance(p[DNS], DNS)): 393 | dns_tuples = DNS_extract(p, meta, prefs, dests) 394 | #print(str(dns_tuples)) 395 | 396 | for one_tuple in dns_tuples: 397 | if one_tuple[0] == 'DN': 398 | if one_tuple[2] in ('A', 'AAAA', 'PTR', 'CNAME'): 399 | if one_tuple[1] and one_tuple[3]: #Check that the IP and hostname fields are not empty 400 | ip_string = force_string(one_tuple[1]) 401 | dns_hostname = force_string(one_tuple[3]) 402 | if ip_string not in processpacket.dns_for_ip: 403 | processpacket.dns_for_ip[ip_string] = [] 404 | if dns_hostname not in processpacket.dns_for_ip[ip_string]: 405 | processpacket.dns_for_ip[ip_string].append(dns_hostname) 406 | #FIXME - keep above, as below is too many calls and slows down the program 407 | #buffer_merges(ip_hostnames_db, ip_string, [dns_hostname], 50) 408 | #else: 409 | # print(str(one_tuple)) 410 | elif one_tuple[0] in ('US', 'UC', 'TS', 'IP'): 411 | pass 412 | else: 413 | debug_out(str(one_tuple)) 414 | 415 | #Now that we've added any dns entries, let's see if the source or dest IPs could be converted to hostnames so we have hostname entries too. 416 | if sIP and sIP in processpacket.dns_for_ip: 417 | for one_name in processpacket.dns_for_ip[sIP]: 418 | label = 'name_' + one_name 419 | inc_stats(label, p_len) 420 | processpacket.field_filter[label] = 'host ' + one_name 421 | #FIXME - keep above, because select_key below is pulling entries that haven't been stored yet. 422 | #if sIP and ip_hostnames_db: 423 | # all_hostnames = select_key(ip_hostnames_db[0], sIP) #We only generate these "name_..." entries for recently added hostnames, not everything in the archives 424 | # if all_hostnames: 425 | # for one_name in all_hostnames: 426 | # label = 'name_' + one_name 427 | # inc_stats(label, p_len) 428 | # processpacket.field_filter[label] = 'host ' + one_name 429 | 430 | if dIP and dIP in processpacket.dns_for_ip: 431 | for one_name in processpacket.dns_for_ip[dIP]: 432 | label = 'name_' + one_name 433 | inc_stats(label, p_len) 434 | processpacket.field_filter[label] = 'host ' + one_name 435 | #FIXME - keep above, because select_key below is pulling entries that haven't been stored yet. 436 | #if dIP and ip_hostnames_db: 437 | # all_hostnames = select_key(ip_hostnames_db[0], dIP) #We only generate these "name_..." entries for recently added hostnames, not everything in the archives 438 | # if all_hostnames: 439 | # for one_name in all_hostnames: 440 | # label = 'name_' + one_name 441 | # inc_stats(label, p_len) 442 | # processpacket.field_filter[label] = 'host ' + one_name 443 | 444 | if sIP != '::': 445 | if ttl == 255: #The system is sending a broadcast - it must be local 446 | processpacket.local_ips.add(sIP) 447 | elif ttl in (64, 128): #The ttl appears to be what it would be set to if it was on the local network. Flag as a local IP. 448 | processpacket.local_ips.add(sIP) 449 | elif ttl == 1 and p.haslayer(UDP) and p.getlayer(UDP).dport in (5353, 5355): #The ttl appears to be what it would be set to if it was on the local network. Flag as a local IP. 450 | processpacket.local_ips.add(sIP) 451 | 452 | if p.haslayer(ARP): 453 | if p.getlayer(ARP).op == 1: #1 is a request ("who-has") 454 | processpacket.local_ips.add(sIP) 455 | #Note, the destination IP is likely "broadcast" in a request 456 | elif p.getlayer(ARP).op == 2: #2 is a reply ("is-at") 457 | processpacket.local_ips.add(sIP) 458 | processpacket.local_ips.add(dIP) 459 | else: 460 | p.show() 461 | sys.exit(98) 462 | 463 | #Good for debugging 464 | #if sIP and ttl != -1: 465 | # label = 'ipttl_' + sIP + '_' + str(ttl) 466 | # inc_stats(label, p_len) 467 | # if ':' in sIP: 468 | # processpacket.field_filter[label] = 'src host ' + sIP + ' and ip6[7] = ' + str(ttl) 469 | # else: 470 | # processpacket.field_filter[label] = 'src host ' + sIP + ' and ip[8] = ' + str(ttl) 471 | 472 | p_epoch: float = p.time #Seconds and microseconds since the epoch of this packet 473 | if processpacket.minstamp is None or p_epoch < processpacket.minstamp: 474 | processpacket.minstamp = p_epoch 475 | 476 | if processpacket.maxstamp is None or p_epoch > processpacket.maxstamp: 477 | processpacket.maxstamp = p_epoch 478 | 479 | #Details: https://stackoverflow.com/questions/46276152/scapy-timestamp-measurement-for-outgoing-packets 480 | #p_gmt = time.gmtime(p_epoch) #Same timestamp, but in struct_time format for GMT 481 | #print(p_gmt) #time.struct_time(tm_year=2021, tm_mon=7, tm_mday=20, tm_hour=21, tm_min=41, tm_sec=3, tm_wday=1, tm_yday=201, tm_isdst=0) 482 | #print(time.asctime(p_gmt)) #Tue Jul 20 21:41:03 2021 483 | 484 | 485 | if p.haslayer(TCP): 486 | t_layer = p.getlayer(TCP) 487 | #p.show() 488 | #sys.exit(97) 489 | 490 | 491 | if t_layer.flags == 'S' and t_layer.dport not in processpacket.tcp_server_ports: #Following blocks try to identify which end is the "server" port. 492 | debug_out("Adding " + str(t_layer.dport) + " to tcp_server_ports") 493 | processpacket.tcp_server_ports.append(t_layer.dport) 494 | elif t_layer.flags == 'SA' and t_layer.sport not in processpacket.tcp_server_ports: 495 | debug_out("Adding " + str(t_layer.sport) + " to tcp_server_ports") 496 | processpacket.tcp_server_ports.append(t_layer.sport) 497 | 498 | if t_layer.sport in processpacket.tcp_server_ports: 499 | label = 'tcp_' + str(t_layer.sport) 500 | inc_stats(label, p_len) 501 | processpacket.field_filter[label] = 'tcp port ' + str(t_layer.sport) 502 | elif t_layer.dport in processpacket.tcp_server_ports: 503 | label = 'tcp_' + str(t_layer.dport) 504 | inc_stats(label, p_len) 505 | processpacket.field_filter[label] = 'tcp port ' + str(t_layer.dport) 506 | #elif t_layer.sport in tcp_ignore_ports and t_layer.dport in tcp_ignore_ports: #Was used for early troubleshooting, no longer needed. 507 | # pass 508 | else: 509 | warning = "No tcp server port: " + str(t_layer.sport) + " " + str(t_layer.dport) 510 | if warning not in processpacket.debug_shown: 511 | debug_out(warning) 512 | processpacket.debug_shown.append(warning) 513 | #p.show() 514 | #sys.exit(96) 515 | 516 | if sIP and sIP != '0.0.0.0': 517 | if sIP not in processpacket.ports_for_ip: 518 | processpacket.ports_for_ip[sIP] = set() 519 | processpacket.ports_for_ip[sIP].add('tcp_' + str(t_layer.sport)) 520 | 521 | if dIP and dIP != '0.0.0.0': 522 | if dIP not in processpacket.ports_for_ip: 523 | processpacket.ports_for_ip[dIP] = set() 524 | processpacket.ports_for_ip[dIP].add('tcp_' + str(t_layer.dport)) 525 | 526 | label = 'TCP_FLAGS_' + str(t_layer.flags) 527 | inc_stats(label, p_len) 528 | 529 | elif p.haslayer(UDP): 530 | u_layer = p.getlayer(UDP) 531 | if u_layer.sport in processpacket.udp_server_ports: #Following blocks try to identify which end is the "server" port. 532 | label = 'udp_' + str(u_layer.sport) 533 | inc_stats(label, p_len) 534 | processpacket.field_filter[label] = 'udp port ' + str(u_layer.sport) 535 | elif u_layer.dport in processpacket.udp_server_ports: 536 | label = 'udp_' + str(u_layer.dport) 537 | inc_stats(label, p_len) 538 | processpacket.field_filter[label] = 'udp port ' + str(u_layer.dport) 539 | elif u_layer.sport >= 33434 and u_layer.sport < 33524: #Special case traceroute if we didn't find it in the fixed ports above 540 | label = 'udp_' + str(u_layer.sport) 541 | inc_stats(label, p_len) 542 | processpacket.field_filter[label] = 'udp port ' + str(u_layer.sport) 543 | elif u_layer.dport >= 33434 and u_layer.dport < 33524: 544 | label = 'udp_' + str(u_layer.dport) 545 | inc_stats(label, p_len) 546 | processpacket.field_filter[label] = 'udp port ' + str(u_layer.dport) 547 | #elif u_layer.sport in udp_ignore_ports and u_layer.dport in udp_ignore_ports: #Was used for early troubleshooting, no longer needed. 548 | # pass 549 | else: 550 | label = 'udp_' + str(u_layer.sport) 551 | inc_stats(label, p_len) 552 | processpacket.field_filter[label] = 'udp port ' + str(u_layer.sport) 553 | label = 'udp_' + str(u_layer.dport) 554 | inc_stats(label, p_len) 555 | processpacket.field_filter[label] = 'udp port ' + str(u_layer.dport) 556 | 557 | #debug_out("No udp server port") 558 | #p.show() 559 | #sys.exit(95) 560 | 561 | if sIP and sIP != '0.0.0.0': 562 | if sIP not in processpacket.ports_for_ip: 563 | processpacket.ports_for_ip[sIP] = set() 564 | processpacket.ports_for_ip[sIP].add('udp_' + str(u_layer.sport)) 565 | 566 | if dIP and dIP != '0.0.0.0': 567 | if dIP not in processpacket.ports_for_ip: 568 | processpacket.ports_for_ip[dIP] = set() 569 | processpacket.ports_for_ip[dIP].add('udp_' + str(u_layer.dport)) 570 | 571 | #To test, run "nmblookup some_netbios_hostname" or "smbutil lookup some_netbios_hostname" 572 | if u_layer.sport == 137 and p.haslayer(NBNSQueryResponse): 573 | netbios_hostname = p[NBNSQueryResponse].RR_NAME.rstrip().rstrip(nullbyte).decode('UTF-8') 574 | netbios_address = p[NBNSQueryResponse].NB_ADDRESS.rstrip() #Apparently .decode('UTF-8') is not needed for a string 575 | buffer_merges(ip_netbios_db, netbios_address, [netbios_hostname], 50) 576 | 577 | if u_layer.sport == 138 and p.haslayer(NBTDatagram): 578 | netbios_hostname = p[NBTDatagram].SourceName.rstrip().decode('UTF-8') 579 | buffer_merges(ip_netbios_db, sIP, [netbios_hostname], 50) 580 | 581 | elif p.haslayer(ICMP): 582 | i_layer = p.getlayer(ICMP) 583 | label = 'icmp_' + str(i_layer.type) + '.' + str(i_layer.code) 584 | inc_stats(label, p_len) 585 | processpacket.field_filter[label] = 'icmptype = ' + str(i_layer.type) + ' and icmpcode = ' + str(i_layer.code) 586 | #p.show() 587 | #sys.exit(94) 588 | #IPv6 doesn't have a dedicated ICMPv6 layer, so we need to key off the IPv6 next_header value of 58 for ICMPv6 589 | elif p.haslayer(IPv6) and p.getlayer(IPv6).nh == 58: 590 | i_layer = p.getlayer('IPv6').payload 591 | label = 'icmp6_' + str(i_layer.type) + '.' + str(i_layer.code) 592 | inc_stats(label, p_len) 593 | #processpacket.field_filter[label] = 'icmptype = ' + str(i_layer.type) + ' and icmpcode = ' + str(i_layer.code) #I don't believe this works on ipv6 594 | 595 | #If we want to get down into the individual icmp types: 596 | #debug_out(label) 597 | #if i_layer.type == 1: #'ICMPv6 Destination Unreachable' 598 | # debug_out('dest_unreach') 599 | #elif i_layer.type == 3: #'ICMPv6 Time Exceeded' 600 | # debug_out('time exceeded') 601 | #elif i_layer.type == 134: #'ICMPv6 Neighbor Discovery - Router Advertisement' 602 | # debug_out('router_adv') 603 | #elif i_layer.type == 135: #'ICMPv6 Neighbor Discovery - Neighbor Solicitation' 604 | # debug_out('neighbor_sol') 605 | #elif i_layer.type == 136: #'ICMPv6 Neighbor Discovery - Neighbor Advertisement' 606 | # debug_out('neighbor_adv') 607 | #else: 608 | # p.show() 609 | # debug_out(p_layers) 610 | # sys.exit(93) 611 | elif p.haslayer(ARP) or p.haslayer(LLC): 612 | pass 613 | elif p.haslayer(IP) and p[IP].proto == 47 and p.haslayer(GRE): 614 | #FIXME - we're not parsing the _inner_ IP layer - see passer.py IPv4/UDPv4/ipencap for approach. 615 | label = 'proto_' + str(proto) + "_" + str(p[GRE].proto) 616 | inc_stats(label, p_len) 617 | processpacket.field_filter[label] = 'ip proto ' + str(proto) 618 | if p[GRE].proto == 2048: #0x800==2048==IPv4 619 | if p[GRE].payload: 620 | encap_packet = p[GRE].payload 621 | processpacket(encap_packet) 622 | #p.show() 623 | #sys.exit(31) 624 | elif p[GRE].proto == 35006: #0x88be==35006==ERSPAN_type_II 625 | #https://datatracker.ietf.org/doc/html/draft-foschiano-erspan-00 626 | pass 627 | elif p[GRE].proto == 8939: #0x22eb==8939==ERSPAN_type_III 628 | #https://datatracker.ietf.org/doc/html/draft-foschiano-erspan-00 629 | pass 630 | elif proto: 631 | label = 'proto_' + str(proto) 632 | inc_stats(label, p_len) 633 | processpacket.field_filter[label] = 'ip proto ' + str(proto) 634 | elif p.haslayer(IPv6): #use "ip6 proto" 635 | pass #FIXME 636 | elif p_layers == ['Ethernet', 'Raw']: 637 | pass 638 | elif (p.haslayer(Ether) and p[Ether].type == 0x888E): #EAPOL packet; PAE=0x888E 639 | pass 640 | else: 641 | debug_out("Non-udp-tcp") 642 | p.show() 643 | sys.exit(92) 644 | 645 | 646 | def hints_for(proto_desc: str, list_of_hints: List) -> str: 647 | """For a given protocol, return the appropriate hint information to go in field 5 of the output.""" 648 | 649 | hint_return = '' 650 | 651 | if proto_desc in hints: 652 | hint_return = hints[proto_desc] 653 | elif proto_desc.startswith(('ip4_169.254.',)): 654 | hint_return = 'link_local/unable_to_get_address' 655 | elif proto_desc.startswith(('ip6_fe80:')): 656 | hint_return = 'link_local_address' 657 | elif proto_desc.startswith(('ip4_10.', 'ip4_172.16.', 'ip4_172.17.', 'ip4_172.18.', 'ip4_172.19.', 'ip4_172.20.', 'ip4_172.21.', 'ip4_172.22.', 'ip4_172.23.', 'ip4_172.24.', 'ip4_172.25.', 'ip4_172.26.', 'ip4_172.27.', 'ip4_172.28.', 'ip4_172.29.', 'ip4_172.30.', 'ip4_172.31.', 'ip4_192.168.')): 658 | hint_return = 'rfc1918/reserved' 659 | elif proto_desc.startswith(('ip4_17.')): 660 | hint_return = 'apple' 661 | elif proto_desc.startswith(('ip4_73.')): 662 | hint_return = 'comcast' 663 | 664 | for one_hint in list_of_hints: 665 | if hint_return and one_hint: 666 | hint_return += ' ' + one_hint 667 | elif one_hint: 668 | hint_return = one_hint 669 | 670 | return hint_return 671 | 672 | 673 | def print_stats(mincount_to_show: int, minsize_to_show: int, out_format: str, source_string: str) -> None: 674 | """Show statistics""" 675 | 676 | if "p_stats" in inc_stats.__dict__: 677 | 678 | if out_format == 'html': 679 | print('') 680 | print('') 681 | print('pcap_stats for ' + source_string + '') 682 | print('') 683 | print('') 684 | print('') 685 | print('') 686 | print("") # type: ignore 687 | print('') 688 | 689 | #print(inc_stats.p_stats) 690 | #print("Local_IPs: " + str(sorted(processpacket.local_ips))) 691 | 692 | elif out_format == 'ascii': 693 | print("Begin_time: " + time.asctime(time.gmtime(int(processpacket.minstamp)))) # type: ignore 694 | print("End_time: " + time.asctime(time.gmtime(int(processpacket.maxstamp)))) # type: ignore 695 | print("Elapsed_time: " + str(processpacket.maxstamp - processpacket.minstamp)) # type: ignore 696 | 697 | for one_key in sorted(inc_stats.p_stats.keys()): # type: ignore 698 | hints_list: List = [] 699 | desc: str = one_key.replace(' ', '_') 700 | orig_ip: str = desc.replace('ip4_', '').replace('ip6_', '') 701 | full_ip = explode_ip(orig_ip, {}, {}) 702 | 703 | if desc.startswith(('ip4_', 'ip6_')) and orig_ip in processpacket.ports_for_ip: # type: ignore 704 | if len(processpacket.ports_for_ip[orig_ip]) == 1: # type: ignore 705 | for sole_port in processpacket.ports_for_ip[orig_ip]: # type: ignore 706 | break #Just retrieve the sole entry in the set 707 | hints_list.append('sole_port:' + str(sole_port)) # pylint: disable=undefined-loop-variable 708 | elif len(processpacket.ports_for_ip[orig_ip]) == 2 and 'udp_53' in processpacket.ports_for_ip[orig_ip] and 'tcp_53' in processpacket.ports_for_ip[orig_ip]: # type: ignore 709 | hints_list.append('sole_port:udp_53_and_tcp_53') 710 | else: 711 | hints_list.append(str(len(processpacket.ports_for_ip[orig_ip])) + ' ports') # type: ignore 712 | 713 | if desc.startswith(('ip4_', 'ip6_')) and orig_ip in processpacket.cast_type: # type: ignore 714 | hints_list.append('cast:' + processpacket.cast_type[orig_ip]) # type: ignore 715 | 716 | ##FIXME - break into NB: (queried) and nb: (historic) (still needed?) 717 | if ip_netbios_db: 718 | netbios_hostname_list = select_key(ip_netbios_db, full_ip) 719 | if netbios_hostname_list: 720 | hints_list.append('NB:' + str(netbios_hostname_list)) 721 | 722 | 723 | #FIXME - break into DNS: (queried) and dns: (historic) by dropping next block entirely... (still needed?) 724 | if ip_hostnames_db: 725 | all_hostnames = select_key(ip_hostnames_db[0], full_ip) 726 | else: 727 | all_hostnames = [] 728 | if all_hostnames: 729 | #Display recent hostnames. 730 | if display_uuid_hosts: 731 | orig_ip_list = all_hostnames 732 | else: 733 | orig_ip_list = [x for x in all_hostnames if not re.match(uuid_match, x)] 734 | if orig_ip_list: 735 | hints_list.append('DNS:' + str(orig_ip_list)) 736 | recent_lookup_set = set(orig_ip_list) 737 | else: 738 | recent_lookup_set = set() 739 | 740 | if len(ip_hostnames_db) > 1: #Note, this only handles case of [current, archive], not with multiple archive dbs 741 | old_hostnames = select_key(ip_hostnames_db[1], full_ip) 742 | if old_hostnames: 743 | #Display any archive hostnames. 744 | if display_uuid_hosts: 745 | orig_ip_list = old_hostnames 746 | else: 747 | orig_ip_list = [x for x in old_hostnames if not re.match(uuid_match, x)] 748 | if orig_ip_list: 749 | #Remove recent dns entries from this so we show just not-recently-looked-up hostnames after "dns:" 750 | just_old_hostnames = set(orig_ip_list) - recent_lookup_set 751 | if just_old_hostnames: 752 | hints_list.append('dns:' + str(list(just_old_hostnames))) 753 | 754 | if inc_stats.p_stats[one_key][0] >= mincount_to_show and inc_stats.p_stats[one_key][1] >= minsize_to_show: # type: ignore 755 | if orig_ip in processpacket.local_ips: # type: ignore 756 | hints_list.insert(0, 'local') 757 | 758 | for _, ipv4_set in processpacket.ipv4s_for_mac.items(): # type: ignore #_ was originally one_mac, but we don't actually use it. 759 | if orig_ip in ipv4_set and len(ipv4_set) > 10: 760 | hints_list.insert(1, 'ipv4router:' + str(list(ipv4_set)[0:10]) + '..., ' + str(len(ipv4_set)) + ' entries.') 761 | elif orig_ip in ipv4_set and len(ipv4_set) > 1: 762 | hints_list.insert(1, 'ipv4router:' + str(ipv4_set)) 763 | for _, ipv6_set in processpacket.ipv6s_for_mac.items(): # type: ignore 764 | if orig_ip in ipv6_set and len(ipv6_set) > 10: 765 | hints_list.insert(1, 'ipv6router:' + str(list(ipv6_set)[0:10]) + '..., ' + str(len(ipv6_set)) + ' entries.') 766 | elif orig_ip in ipv6_set and len(ipv6_set) > 1: 767 | hints_list.insert(1, 'ipv6router:' + str(ipv6_set)) 768 | 769 | try: 770 | if out_format == 'html': 771 | print("".format(inc_stats.p_stats[one_key][0], inc_stats.p_stats[one_key][1], desc, processpacket.field_filter.get(one_key, ''), hints_for(desc, hints_list))) # type: ignore # pylint: disable=consider-using-f-string 772 | elif out_format == 'ascii': 773 | print("{0:>10d} {1:>13d} {2:60s} {3:48s} {4:30s}".format(inc_stats.p_stats[one_key][0], inc_stats.p_stats[one_key][1], desc, processpacket.field_filter.get(one_key, ''), hints_for(desc, hints_list))) # type: ignore # pylint: disable=consider-using-f-string 774 | except BrokenPipeError: 775 | sys.exit(0) 776 | if out_format == 'html': 777 | print('
Pcap Statistics for ' + source_string + '
Begin_time: " + time.asctime(time.gmtime(int(processpacket.minstamp))) + ", End_time: " + time.asctime(time.gmtime(int(processpacket.maxstamp))) + ", Elapsed_time: " + str(processpacket.maxstamp - processpacket.minstamp) + " seconds
CountBytesDescriptionBPF expressionHint
{0:}{1}{2}{3}{4}
') 778 | print('') 779 | 780 | else: 781 | sys.stderr.write('It does not appear any packets were read. Exiting.\n') 782 | sys.stderr.flush() 783 | 784 | 785 | def process_packet_source(if_name: Optional[str], pcap_source: Optional[str], user_args: dict): 786 | """Process the packets in a single source file, interface, or stdin.""" 787 | 788 | source_file = None 789 | close_temp = False 790 | delete_temp = False 791 | 792 | #We have an interface to sniff on 793 | if if_name: 794 | debug_out('Reading packets from interface ' + if_name) 795 | try: 796 | if user_args['count']: 797 | sniff(store=0, iface=if_name, filter=user_args['bpf'], count=user_args['count'], prn=lambda x: processpacket(x)) # pylint: disable=unnecessary-lambda 798 | else: 799 | sniff(store=0, iface=if_name, filter=user_args['bpf'], prn=lambda x: processpacket(x)) # pylint: disable=unnecessary-lambda 800 | except ((Scapy_Exception, PermissionError)): 801 | sys.stderr.write("Unable to open interface " + str(if_name) + ' . Permission error? Perhaps runs as root or under sudo? Exiting.\n') 802 | raise 803 | #Read from stdin 804 | elif pcap_source in ('-', None, ''): 805 | debug_out('Reading packets from stdin.') 806 | tmp_packets = tempfile.NamedTemporaryFile(delete=True) # pylint: disable=consider-using-with 807 | tmp_packets.write(sys.stdin.buffer.read()) 808 | tmp_packets.flush() 809 | source_file = tmp_packets.name 810 | close_temp = True 811 | #Set up source packet file; next 2 sections check for and handle compressed file extensions first, then final "else" treats the source as a pcap file 812 | elif cast(str, pcap_source).endswith('.bz2'): 813 | debug_out('Reading bzip2 compressed packets from file ' + cast(str, pcap_source)) 814 | source_file = open_bzip2_file_to_tmp_file(cast(str, pcap_source)) 815 | delete_temp = True 816 | elif cast(str, pcap_source).endswith('.gz'): 817 | debug_out('Reading gzip compressed packets from file ' + cast(str, pcap_source)) 818 | source_file = open_gzip_file_to_tmp_file(cast(str, pcap_source)) 819 | delete_temp = True 820 | else: 821 | debug_out('Reading packets from file ' + cast(str, pcap_source)) 822 | source_file = pcap_source 823 | 824 | #Try to process file first 825 | if source_file: 826 | if os.path.exists(source_file) and os.access(source_file, os.R_OK): 827 | try: 828 | if user_args['count']: 829 | sniff(store=0, offline=source_file, filter=user_args['bpf'], count=user_args['count'], prn=lambda x: processpacket(x)) # pylint: disable=unnecessary-lambda 830 | else: 831 | sniff(store=0, offline=source_file, filter=user_args['bpf'], prn=lambda x: processpacket(x)) # pylint: disable=unnecessary-lambda 832 | except (FileNotFoundError, IOError): 833 | sys.stderr.write("Unable to open file " + str(pcap_source) + ', exiting.\n') 834 | raise 835 | else: 836 | sys.stderr.write("Unable to open file " + str(source_file) + ', skipping.\n') 837 | 838 | if close_temp: 839 | tmp_packets.close() 840 | 841 | if delete_temp and source_file != pcap_source and os.path.exists(cast(str, source_file)): 842 | os.remove(cast(str, source_file)) 843 | 844 | 845 | 846 | nullbyte = binascii.unhexlify('00') 847 | 848 | display_uuid_hosts = False 849 | uuid_match = r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.local\.*' 850 | 851 | hints = {'TCP_FLAGS_': 'Invalid/no_tcp_flags', 'TCP_FLAGS_SR': 'Invalid/syn_and_rst', 'TCP_FLAGS_FRA': 'Invalid/fin_and_rst', 'TCP_FLAGS_FSPEC': 'Invalid/fin_and_syn', 'TCP_FLAGS_FSPU': 'Invalid/fin_and_syn', 'TCP_FLAGS_FSRPAU': 'Invalid/fin_and_syn_and_rst', 'TCP_FLAGS_FSRPAUEN': 'Invalid/fin_and_syn_and_rst_christmas_tree', 852 | 'icmp_0.0': 'echo_reply', 853 | 'icmp_3.0': 'unreachable/net', 'icmp_3.1': 'unreachable/host', 'icmp_3.10': 'unreachable/host_admin_prohib', 'icmp_3.13': 'unreachable/communication_administratively_prohibited', 'icmp_3.2': 'unreachable/protocol', 'icmp_3.3': 'unreachable/port', 'icmp_3.4': 'unreachable/frag_needed_and_df_set', 854 | 'icmp_5.0': 'redirect/net', 'icmp_5.1': 'redirect/host', 'icmp_5.2': 'redirect/tos_and_net', 'icmp_5.3': 'redirect/tos_and_host', 855 | 'icmp_8.0': 'echo_request', 856 | 'icmp_9.0': 'router_advertisement/normal', 857 | 'icmp_11.0': 'time_exceeded/TTL', 'icmp_11.1': 'time_exceeded/frag_reassembly_time_exceeded', 858 | 'icmp_13.0': 'timestamp', 859 | 'icmp_14.0': 'timestamp_reply', 860 | 'icmp6_1.1': 'unreachable/communication_administratively_prohibited', 'icmp6_1.3': 'unreachable/address_unreachable', 'icmp6_1.4': 'unreachable/port_unreachable', 'icmp6_1.6': 'unreachable/reject_destination_route', 861 | 'icmp6_3.0': 'time_exceeded/hop_limit', 862 | 'icmp6_128.0': 'echo_request', 863 | 'icmp6_129.0': 'echo_reply', 864 | 'icmp6_133.0': 'router_solicitation/normal', 865 | 'icmp6_134.0': 'router_advertisement/normal', 866 | 'icmp6_135.0': 'neighbor_solicitation/normal', 867 | 'icmp6_136.0': 'neighbor_advertisement/normal', 868 | 'ip4_0.0.0.0': 'address_unspecified', 'ip4_1.1.1.1': 'public_dns/cloudflare', 'ip4_127.0.0.1': 'localhost', 'ip4_8.8.4.4': 'public_dns/google', 'ip4_8.8.8.8': 'public_dns/google', 'ip4_75.75.75.75': 'public_dns/cdns01.comcast.net', 'ip4_75.75.76.76': 'public_dns/cdns02.comcast.net', 'ip4_75.75.77.22': 'public_dns/doh.xfinity.com', 'ip4_75.75.77.98': 'public_dns/doh.xfinity.com', 'ip4_224.0.0.1': 'all_systems_on_this_subnet', 'ip4_224.0.0.2': 'all_routers_on_this_subnet', 'ip4_224.0.0.13': 'all_pim_routers', 'ip4_224.0.0.22': 'multicast/IGMP', 'ip4_224.0.0.251': 'multicast/mDNS', 'ip4_224.0.0.252': 'multicast/LLMNR', 'ip4_224.0.1.40': 'multicast/cisco_rp_discovery', 'ip4_224.0.1.60': 'multicast/hp_device_discovery', 'ip4_239.255.255.250': 'multicast/uPNP_or_SSDP', 'ip4_255.255.255.255': 'broadcast', 869 | 'ip6_2001:558:feed::1': 'public_dns/cdns01.comcast.net', 'ip6_2001:558:feed::2': 'public_dns/cdns02.comcast.net', 'ip6_2001:558:feed:443::98': 'public_dns/doh.xfinity.com', 870 | 'ip6_::': 'address_unspecified', 'ip6_::1': 'localhost', 'ip6_ff02::1': 'multicast/all_nodes', 'ip6_ff02::2': 'multicast/all_routers', 'ip6_ff02::c': 'multicast/ssdp', 'ip6_ff02::16': 'multicast/MLDv2_capable_routers', 'ip6_ff02::fb': 'multicast/mDNSv6', 'ip6_ff02::1:2': 'multicast/DHCP_Relay_Agents_and_Servers', 'ip6_ff02::1:3': 'multicast/LLMNR', 871 | 'proto_0': 'ip', 'proto_2': 'igmp', 'proto_47': 'gre', 'proto_47_35006': 'gre/erspan_type_II', 'proto_47_8939': 'gre/erspan_type_III', 'proto_50': 'esp', 'proto_51': 'ah', 'proto_58': 'ipv6_icmp', 'proto_103': 'pim', 872 | 'udp_7': 'echo', 'udp_17': 'qotd', 'udp_19': 'chargen', 'udp_53': 'dns', 'udp_67': 'bootp/dhcp', 'udp_69': 'tftp', 'udp_88': 'kerberos', 873 | 'udp_111': 'rpc', 'udp_123': 'ntp', 'udp_137': 'netbios/ns', 'udp_138': 'netbios/datagram', 'udp_161': 'snmp', 874 | 'udp_389': 'ldap', 875 | 'udp_443': 'https/quic', 876 | 'udp_500': 'isakmp/ike', 'udp_514': 'syslog', 'udp_520': 'rip', 'udp_546': 'dhcpv6_client', 'udp_547': 'dhcpv6', 877 | 'udp_1194': 'openvpn', 878 | 'udp_1434': 'mssql_monitor', 'udp_1853': 'videoconf/gotowebinar', 'udp_1900': 'ssdp/upnp', 879 | 'udp_1812': 'radius', 880 | 'udp_3389': 'remote_desktop_protocol', 'udp_3478': 'webrtc', 'udp_3479': 'webrtc', 'udp_3480': 'webrtc', 'udp_3481': 'webrtc', 'udp_3702': 'web_services_discovery', 881 | 'udp_4500': 'ipsec_nat_traversal', 'udp_4501': 'globalprotect_vpn', 'udp_4789': 'vxlan', 882 | 'udp_5002': 'drobo_discovery', 'udp_5060': 'sip', 'udp_5353': 'mDNS', 'udp_5355': 'LLMNR', 'udp_5938': 'teamviewer', 883 | 'udp_8200': 'videoconf/gotowebinar', 'udp_8801': 'videoconf/zoom', 'udp_8802': 'videoconf/zoom', 884 | 'udp_15509': 'videoconf/zoom', 885 | 'udp_17500': 'dropbox_lan_sync', 886 | 'udp_19305': 'google_meet', 887 | 'udp_33434': 'traceroute/udp', 'udp_33435': 'traceroute/udp', 'udp_33436': 'traceroute/udp', 'udp_33437': 'traceroute/udp', 'udp_33438': 'traceroute/udp', 'udp_33439': 'traceroute/udp', 888 | 'udp_33440': 'traceroute/udp', 'udp_33441': 'traceroute/udp', 'udp_33442': 'traceroute/udp', 'udp_33443': 'traceroute/udp', 'udp_33444': 'traceroute/udp', 'udp_33445': 'traceroute/udp', 'udp_33446': 'traceroute/udp', 'udp_33447': 'traceroute/udp', 'udp_33448': 'traceroute/udp', 'udp_33449': 'traceroute/udp', 889 | 'udp_33450': 'traceroute/udp', 'udp_33451': 'traceroute/udp', 'udp_33452': 'traceroute/udp', 'udp_33453': 'traceroute/udp', 'udp_33454': 'traceroute/udp', 'udp_33455': 'traceroute/udp', 'udp_33456': 'traceroute/udp', 'udp_33457': 'traceroute/udp', 'udp_33458': 'traceroute/udp', 'udp_33459': 'traceroute/udp', 890 | 'udp_33460': 'traceroute/udp', 'udp_33461': 'traceroute/udp', 'udp_33462': 'traceroute/udp', 'udp_33463': 'traceroute/udp', 'udp_33464': 'traceroute/udp', 'udp_33465': 'traceroute/udp', 'udp_33466': 'traceroute/udp', 'udp_33467': 'traceroute/udp', 'udp_33468': 'traceroute/udp', 'udp_33469': 'traceroute/udp', 891 | 'udp_33470': 'traceroute/udp', 'udp_33471': 'traceroute/udp', 'udp_33472': 'traceroute/udp', 'udp_33473': 'traceroute/udp', 'udp_33474': 'traceroute/udp', 'udp_33475': 'traceroute/udp', 'udp_33476': 'traceroute/udp', 'udp_33477': 'traceroute/udp', 'udp_33478': 'traceroute/udp', 'udp_33479': 'traceroute/udp', 892 | 'udp_33480': 'traceroute/udp', 'udp_33481': 'traceroute/udp', 'udp_33482': 'traceroute/udp', 'udp_33483': 'traceroute/udp', 'udp_33484': 'traceroute/udp', 'udp_33485': 'traceroute/udp', 'udp_33486': 'traceroute/udp', 'udp_33487': 'traceroute/udp', 'udp_33488': 'traceroute/udp', 'udp_33489': 'traceroute/udp', 893 | 'udp_33490': 'traceroute/udp', 'udp_33491': 'traceroute/udp', 'udp_33492': 'traceroute/udp', 'udp_33493': 'traceroute/udp', 'udp_33494': 'traceroute/udp', 'udp_33495': 'traceroute/udp', 'udp_33496': 'traceroute/udp', 'udp_33497': 'traceroute/udp', 'udp_33498': 'traceroute/udp', 'udp_33499': 'traceroute/udp', 894 | 'udp_33500': 'traceroute/udp', 'udp_33501': 'traceroute/udp', 'udp_33502': 'traceroute/udp', 'udp_33503': 'traceroute/udp', 'udp_33504': 'traceroute/udp', 'udp_33505': 'traceroute/udp', 'udp_33506': 'traceroute/udp', 'udp_33507': 'traceroute/udp', 'udp_33508': 'traceroute/udp', 'udp_33509': 'traceroute/udp', 895 | 'udp_33510': 'traceroute/udp', 'udp_33511': 'traceroute/udp', 'udp_33512': 'traceroute/udp', 'udp_33513': 'traceroute/udp', 'udp_33514': 'traceroute/udp', 'udp_33515': 'traceroute/udp', 'udp_33516': 'traceroute/udp', 'udp_33517': 'traceroute/udp', 'udp_33518': 'traceroute/udp', 'udp_33519': 'traceroute/udp', 896 | 'udp_33520': 'traceroute/udp', 'udp_33521': 'traceroute/udp', 'udp_33522': 'traceroute/udp', 'udp_33523': 'traceroute/udp', 897 | 'tcp_7': 'echo', 'tcp_11': 'systat', 'tcp_13': 'daytime', 'tcp_19': 'chargen', 'tcp_20': 'ftp-data', 'tcp_21': 'ftp', 'tcp_22': 'ssh', 'tcp_23': 'telnet', 'tcp_25': 'smtp', 'tcp_37': 'time', 'tcp_42': 'name', 'tcp_43': 'whois', 'tcp_53': 'dns', 'tcp_79': 'finger', 'tcp_80': 'http', 'tcp_88': 'kerberos', 898 | 'tcp_109': 'pop2', 'tcp_110': 'pop3', 'tcp_111': 'rpc', 'tcp_113': 'ident/auth', 'tcp_119': 'nntp', 'tcp_135': 'ms_rpc_endpoint_mapper', 'tcp_139': 'netbios/session', 'tcp_143': 'imap', 'tcp_179': 'bgp', 899 | 'tcp_389': 'ldap', 900 | 'tcp_443': 'https', 'tcp_445': 'microsoft-ds', 'tcp_465': 'smtps', 901 | 'tcp_512': 'r-commands/rexec', 'tcp_513': 'r-commands/rlogin', 'tcp_514': 'r-commands/rsh_rcp', 'tcp_587': 'smtp/msa', 902 | 'tcp_631': 'ipp', 903 | 'tcp_873': 'rsync', 904 | 'tcp_989': 'ftps-data', 'tcp_990': 'ftps', 'tcp_993': 'imaps', 905 | 'tcp_1119': 'bnetgame', 'tcp_1194': 'openvpn', 906 | 'tcp_1389': 'iclpv-dm_or_alt_jndi_ldap', 907 | 'tcp_1433': 'mssql', 'tcp_1434': 'mssql_monitor', 908 | 'tcp_1723': 'pptp', 909 | 'tcp_1935': 'rtmp', 'tcp_1984': 'bigbrother', 910 | 'tcp_3128': 'squid_proxy', 'tcp_3306': 'mysql', 'tcp_3389': 'remote_desktop_protocol', 'tcp_3478': 'webrtc', 'tcp_3724': 'blizwow', 911 | 'tcp_5001': 'drobo/nasd', 'tcp_5060': 'sip', 'tcp_5223': 'apple_push_notification', 'tcp_5228': 'google_talk', 'tcp_5555': 'monero', 'tcp_5601': 'kibana', 'tcp_5900': 'vnc/remote_framebuffer', 'tcp_5938': 'teamviewer', 912 | 'tcp_6379': 'redis', 913 | 'tcp_7680': 'windows/delivery_optimization', 914 | 'tcp_8008': 'apple_ical', 'tcp_8080': 'http-alt', 'tcp_8333': 'bitcoin', 915 | 'tcp_9200': 'elasticsearch'} 916 | 917 | #The following are _sub_layers; additional details underneath a main layer, such as SNMPBulk under SNMP. 918 | ignore_layers = ('DHCP options', 919 | 'DHCP6 Client Identifier Option', 'DHCP6 Elapsed Time Option', 'DHCP6 Identity Association for Non-temporary Addresses Option', 'DHCP6 Option - Client FQDN', 'DHCP6 Option Request Option', 'DHCP6 Vendor Class Option', 920 | 'DNS DNSKEY Resource Record', 'DNS DS Resource Record', 'DNS EDNS0 TLV', 'DNS NSEC Resource Record', 'DNS NSEC3 Resource Record', 'DNS OPT Resource Record', 'DNS Question Record', 'DNS RRSIG Resource Record', 'DNS Resource Record', 'DNS SRV Resource Record', 921 | 'Ethernet', 922 | 'ICMPv6 Neighbor Discovery Option - Prefix Information', 'ICMPv6 Neighbor Discovery Option - Recursive DNS Server Option', 'ICMPv6 Neighbor Discovery Option - Route Information Option', 'ICMPv6 Neighbor Discovery Option - Source Link-Layer Address', 923 | 'IP Option End of Options List', 'IP Option No Operation', 924 | 'ISAKMP Identification', 'ISAKMP Key Exchange', 'ISAKMP Nonce', 'ISAKMP SA', 'ISAKMP Vendor ID', 'ISAKMP payload', 925 | 'PadN', 'Padding', 926 | 'Raw', 927 | 'SCTPChunkInit', 'SCTPChunkParamCookiePreservative', 'SCTPChunkParamSupportedAddrTypes', 928 | 'SNMPbulk', 'SNMPget', 'SNMPnext', 'SNMPvarbind', 929 | 'vendor_class_data') 930 | 931 | #tcp_ignore_ports = (123, 20547, 33046, 39882) #Was used for early troubleshooting, no longer needed. 932 | #udp_ignore_ports = (10400, 10401, 16403, 38010) 933 | 934 | cache_dir = os.environ["HOME"] + '/.cache/' 935 | 936 | 937 | if __name__ == '__main__': 938 | import argparse 939 | 940 | parser = argparse.ArgumentParser(description='pcap_stats version ' + str(__version__)) 941 | parser.add_argument('-i', '--interface', help='Interface from which to read packets', required=False, default=None) 942 | parser.add_argument('-r', '--read', help='Pcap file(s) from which to read packets', required=False, default=[], nargs='*') 943 | parser.add_argument('-d', '--devel', help='Enable development/debug statements', required=False, default=False, action='store_true') 944 | parser.add_argument('-b', '--bpf', help='BPF to restrict which packets are processed', required=False, default='') 945 | parser.add_argument('-c', '--count', help='Number of packets to sniff (if not specified, sniff forever/until end of pcap file)', type=int, required=False, default=None) 946 | parser.add_argument('-m', '--mincount', help='Only show a record if we have seen it this many times (default: %(default)s)', type=int, required=False, default=0) 947 | parser.add_argument('-s', '--minsize', help='Only show a record if have this many total bytes (default: %(default)s)', type=int, required=False, default=0) 948 | parser.add_argument('-l', '--length', help='Which form of length to use (default: %(default)s)', choices=('ip',), required=False, default='ip') #Reinstate this when the length function accepts them: , choices=('ip', 'layer', 'payload') 949 | parser.add_argument('-f', '--format', help='Output format (default: %(default)s)', choices=('ascii', 'html'), required=False, default='ascii') 950 | parser.add_argument('--db_dir', help='Directory that holds sqlite databases for IP and hostname info', required=False, default=cache_dir + '/ip/') 951 | parser.add_argument('--archive_dir', help='Directory that holds read-only older sqlite databases for IP and hostname info', required=False, default=cache_dir + '/ip_archive/') 952 | (parsed, unparsed) = parser.parse_known_args() 953 | cl_args = vars(parsed) 954 | 955 | #We have to use libpcap instead of scapy's built-in code because the latter won't attach complex bpfs 956 | try: 957 | conf.use_pcap = True 958 | except: 959 | config.use_pcap = True 960 | 961 | if cl_args['db_dir']: 962 | mkdir_p(cl_args['db_dir']) 963 | if cl_args['archive_dir']: 964 | mkdir_p(cl_args['archive_dir']) 965 | 966 | if cl_args['db_dir'] and cl_args['archive_dir']: 967 | ip_netbios_db = [cl_args['db_dir'] + 'ip_names.sqlite3', cl_args['archive_dir'] + 'ip_names.sqlite3'] 968 | ip_hostnames_db = [cl_args['db_dir'] + 'ip_hostnames.sqlite3', cl_args['archive_dir'] + 'ip_hostnames.sqlite3'] 969 | elif cl_args['db_dir']: 970 | ip_netbios_db = [cl_args['db_dir'] + 'ip_names.sqlite3'] 971 | ip_hostnames_db = [cl_args['db_dir'] + 'ip_hostnames.sqlite3'] 972 | else: 973 | ip_netbios_db = [] 974 | ip_hostnames_db = [] 975 | 976 | read_from_stdin = False #If stdin requested, it needs to be processed last, so we remember it here. We also handle the case where the user enters '-' more than once by simply remembering it. 977 | if cl_args['interface'] and cl_args['read']: 978 | data_source = str(cl_args['interface']) + ' ' + str(cl_args['read']) 979 | elif cl_args['interface']: 980 | data_source = str(cl_args['interface']) 981 | elif cl_args['read']: 982 | data_source = str(cl_args['read']) 983 | else: 984 | #elif cl_args['interface'] is None and cl_args['read'] == []: 985 | debug_out('No source specified, reading from stdin.') 986 | read_from_stdin = True 987 | data_source = 'stdin' 988 | 989 | 990 | 991 | try: 992 | if cl_args['read']: 993 | #Process normal files first. 994 | for one_source in cl_args['read']: 995 | if one_source == '-': 996 | read_from_stdin = True 997 | else: 998 | process_packet_source(None, one_source, cl_args) 999 | 1000 | #Now that normal files are out of the way process stdin and/or reading from an interface, either of which could be infinite. 1001 | if read_from_stdin: 1002 | process_packet_source(None, '-', cl_args) 1003 | 1004 | if cl_args['interface']: 1005 | process_packet_source(cl_args['interface'], None, cl_args) 1006 | except KeyboardInterrupt: 1007 | buffer_merges('', '', [], 0) 1008 | 1009 | if 'dns_for_ip' in processpacket.__dict__: 1010 | add_to_db_dict(ip_hostnames_db, processpacket.dns_for_ip) # type: ignore #Save all the buffered up ip->hostname_lists in the writeable database 1011 | 1012 | 1013 | buffer_merges('', '', [], 0) 1014 | print_stats(cl_args['mincount'], cl_args['minsize'], cl_args['format'], data_source) 1015 | buffer_merges('', '', [], 0) 1016 | --------------------------------------------------------------------------------