├── .github └── workflows │ └── codeql-analysis.yml ├── .travis.yml ├── CHANGELOG ├── LICENCE ├── README.md ├── fingerprintls ├── .travis.yml ├── Makefile ├── Makefile.in ├── README.md ├── configure.ac ├── fingerprintls.c ├── fingerprintls.h ├── fpdb.c ├── packet_processing.c ├── signal.c └── tlsfp.db ├── fingerprints ├── fingerprints.json └── ssllabs.json └── scripts ├── README.md ├── fingerprintout.py └── parselog.py /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | name: "CodeQL" 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | # The branches below must be a subset of the branches above 8 | branches: [master] 9 | schedule: 10 | - cron: '0 9 * * 2' 11 | 12 | jobs: 13 | analyze: 14 | name: Analyze 15 | runs-on: ubuntu-latest 16 | 17 | strategy: 18 | fail-fast: false 19 | matrix: 20 | # Override automatic language detection by changing the below list 21 | # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] 22 | language: ['cpp', 'python'] 23 | # Learn more... 24 | # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection 25 | 26 | steps: 27 | - name: Checkout repository 28 | uses: actions/checkout@v2 29 | with: 30 | # We must fetch at least the immediate parents so that if this is 31 | # a pull request then we can checkout the head. 32 | fetch-depth: 2 33 | 34 | # If this run was triggered by a pull request event, then checkout 35 | # the head of the pull request instead of the merge commit. 36 | - run: git checkout HEAD^2 37 | if: ${{ github.event_name == 'pull_request' }} 38 | 39 | # Initializes the CodeQL tools for scanning. 40 | - name: Initialize CodeQL 41 | uses: github/codeql-action/init@v1 42 | with: 43 | languages: ${{ matrix.language }} 44 | 45 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 46 | # If this step fails, then you should remove it and run the build manually (see below) 47 | - name: Autobuild 48 | uses: github/codeql-action/autobuild@v1 49 | 50 | # ℹ️ Command-line programs to run using the OS shell. 51 | # 📚 https://git.io/JvXDl 52 | 53 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 54 | # and modify them (or add more) to build your code if your project 55 | # uses a compiled language 56 | 57 | #- run: | 58 | # make bootstrap 59 | # make release 60 | 61 | - name: Perform CodeQL Analysis 62 | uses: github/codeql-action/analyze@v1 63 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: c 2 | compiler: 3 | - clang 4 | - gcc 5 | 6 | addons: 7 | apt: 8 | packages: 9 | - libpcap-dev 10 | 11 | script: cd $TEST_DIR && make 12 | 13 | env: 14 | - TEST_DIR=fingerprintls 15 | 16 | sudo: false 17 | 18 | notifications: 19 | slack: squarelemon:Reg7U43QgRTUIB8CBpWYcv2O 20 | -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 1 | ============================================== 2 | FingerPrinTLS (and associated tools) ChangeLog 3 | ============================================== 4 | 5 | A complete list of changes per commit can always be found here: 6 | 7 | https://github.com/LeeBrotherston/tls-fingerprinting/commits/master 8 | 9 | And per release, here: 10 | 11 | https://github.com/LeeBrotherston/tls-fingerprinting/releases 12 | 13 | ============================================== 14 | 15 | 1.0.1 - 2016-07-31 16 | 17 | - Added a changelog! 18 | - Multiple Fingerprint Updates 19 | - Added TLS1.3 support 20 | - Added separate licence file (as opposed to within sourcecode) 21 | - Added setgroups to the privilege dropping code 22 | - Fixed a bug regarding server name printing 23 | - Created a README.md to start trying to add documentation 24 | - Updated -u to take username instead of just a uid 25 | - Included PID in dynamically generated fingerprint names to avoid confusion on 26 | daemon restarts 27 | - Trimed duplicate fingerprints 28 | 29 | 30 | 1.0.0 - 2016-06-22 31 | 32 | Cleared up all the known bugs during initial development and marked 1.0.0 33 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TLS Fingerprinting [![Build Status](https://travis-ci.org/LeeBrotherston/tls-fingerprinting.svg?branch=master)](https://travis-ci.org/LeeBrotherston/tls-fingerprinting) 2 | 3 | These tools are to enable the matching (either on the wire or via pcap), 4 | creation, and export of TLS Fingerprints to other formats. For futher 5 | information on TLS Fingerprinting: 6 | 7 | * My [TLS Fingerprinting paper][1], 8 | * My [Derbycon Talk][2], and [slides][3] on the topic. 9 | * My [SecTorCA Talk][4], and [slides][5] on the topic. 10 | * TLS Fingerprinting Discussion on [Brakeing Down Security Podcast][6] 11 | * Quick [demo of tor detection][7] with FingerPrinTLS 12 | 13 | In summary the tools are: 14 | 15 | * **FingerprinTLS**: TLS session detection on the wire or PCAP and subsequent fingerprint detetion / creation. 16 | 17 | * **Fingerprintout**: Export to other formats such as Suricata/Snort rules, ANSI C Structs, "clean" output and xkeyscore (ok, it's regex). NOTE: Because of a lack of flexibility in the suricata/snort rules language, this is currently less accurate than using FingerprinTLS to detect fingerprints and so may require tuning. 18 | 19 | * **fingerprints.json**: The fingerprint "database" itself. 20 | 21 | Please feel free to raise issues and make pull requests to submit code changes, fingerprint submissions, etc. 22 | 23 | You can find [me on twitter][8] and [the project on twitter][9] also. 24 | 25 | 26 | [1]: https://blog.squarelemon.com/tls-fingerprinting/ 27 | [2]: https://www.youtube.com/watch?v=XX0FRAy2Mec 28 | [3]: http://www.slideshare.net/LeeBrotherston/tls-fingerprinting-stealthier-attacking-smarter-defending-derbycon 29 | [4]: http://2015.video.sector.ca/video/144175700 30 | [5]: http://www.slideshare.net/LeeBrotherston/tls-fingerprinting-sectorca-edition 31 | [6]: http://brakeingsecurity.com/2015-007-fingerprintls-profiling-application-with-lee-brotherston 32 | [7]: https://www.youtube.com/watch?v=ifODVQ3hBVs 33 | [8]: https://twitter.com/synackpse 34 | [9]: https://twitter.com/FingerprinTLS 35 | -------------------------------------------------------------------------------- /fingerprintls/.travis.yml: -------------------------------------------------------------------------------- 1 | language: c 2 | compiler: 3 | - clang 4 | - gcc 5 | install: make clean && make 6 | -------------------------------------------------------------------------------- /fingerprintls/Makefile: -------------------------------------------------------------------------------- 1 | # Commented this out for now, not sure how many use klang 2 | #CC=g++ 3 | #CFLAGS=-Wall -pedantic -Os 4 | LDFLAGS=-lpcap 5 | 6 | all: fingerprintls 7 | 8 | fingerprintls: 9 | $(CC) $(CFLAGS) fingerprintls.c -o fingerprintls $(LDFLAGS) 10 | 11 | clean: 12 | rm -rf fingerprintls fingerprintls.o 13 | 14 | .PHONY: clean 15 | -------------------------------------------------------------------------------- /fingerprintls/Makefile.in: -------------------------------------------------------------------------------- 1 | # Commented this out for now, not sure how many use klang 2 | LDFLAGS=-lpcap 3 | CXX=@CXX@ 4 | LD=@CXX@ 5 | CXXFLAGS=@CXXFLAGS@ 6 | 7 | all: fingerprintls 8 | 9 | fingerprintls: 10 | $(CC) $(CFLAGS) fingerprintls.c -o fingerprintls $(LDFLAGS) 11 | 12 | clean: 13 | rm -rf fingerprintls fingerprintls.o 14 | 15 | .PHONY: clean 16 | -------------------------------------------------------------------------------- /fingerprintls/README.md: -------------------------------------------------------------------------------- 1 | # FingerPrinTLS 2 | 3 | FingerPrinTLS is the main tool in this [tls-fingerprinting][1] collection, it is the tool which performs the actual analysis of packets which are collected either via live packet sniffing or via pcaps loaded on the commandline. 4 | 5 | FingerPrinTLS requires libpcap, which is included in most modern distributions. If they do not include this library then it will almost certainly be in the relevent package management system. 6 | 7 | This tool is tested on OS X, FreeBSD, and Linux; using GCC and Clang as compilers. Current build status is: [![Build Status](https://travis-ci.org/LeeBrotherston/tls-fingerprinting.svg?branch=master)](https://travis-ci.org/LeeBrotherston/tls-fingerprinting) 8 | 9 | The commandline switches, as ridiculous as some of them are, are: 10 | ``` 11 | -h Display help 12 | -i Operate in live packetsniffing mode, capturing traffic from 13 | -p Operate in filesystem mode, reading packets from specified pcap file 14 | -P Save client hello packets to specified pcap file for any unknown fingerprints. Useful for when creating new fingerprints and analysing unknown traffic. 15 | -j Location to save automatically generated fingerprint data (json format). This can by used my the [FingerPrintOut][2] script. 16 | -l Location to save "log" file (json format) which can be parsed by [parselog][2] 17 | -d Show reasons for discarded packets (post BPF). Typically this is because a packet is identified as malformed or not really TLS mid-processing. 18 | -f Load the (binary) FingerPrint Database from the specified location 19 | -u Drop privileges to specified UID (not username). This allows the use of this tool without running as root (although it will need to be started as root in order to obtain permissions to sniff live interfaces) 20 | ``` 21 | 22 | # Installing 23 | 24 | FingerPrinTLS is provided with a make file which I have been testing on: 25 | 26 | * Mac OS X 27 | * Linux 28 | * FreeBSD 29 | 30 | Using: 31 | 32 | * gcc 33 | * clang 34 | 35 | Other combinations may well work, just I have not tried them yet. 36 | 37 | If for some reason you cannot use makefiles to build software on your system the compiler commandline should look something like: 38 | 39 | ``` 40 | $compiler fingerprintls.c -o fingerprintls -lpcap 41 | ``` 42 | 43 | 44 | [1]: https://blog.squarelemon.com/tls-fingerprinting/ 45 | [2]: https://github.com/LeeBrotherston/tls-fingerprinting/tree/master/scripts 46 | -------------------------------------------------------------------------------- /fingerprintls/configure.ac: -------------------------------------------------------------------------------- 1 | AC_INIT(fingerprintls, 1.0) 2 | 3 | dnl Switch to a C++ compiler, and check if it works. 4 | AC_LANG(C++) 5 | AC_PROG_CXX 6 | 7 | dnl Process Makefile.in to create Makefile 8 | AC_OUTPUT(Makefile) 9 | -------------------------------------------------------------------------------- /fingerprintls/fingerprintls.c: -------------------------------------------------------------------------------- 1 | /* 2 | Exciting Licence Info..... 3 | 4 | This file is part of FingerprinTLS. 5 | 6 | FingerprinTLS is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | FingerprinTLS is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with FingerprinTLS. If not, see . 18 | 19 | Exciting Licence Info Addendum..... 20 | 21 | FingerprinTLS is additionally released under the "don't judge me" program 22 | whereby it is forbidden to rip into me too harshly for programming 23 | mistakes, kthnxbai. 24 | 25 | */ 26 | 27 | // TODO 28 | // XXX Add UDP support (not as easy as I thought, DTLS has differences... still add it though) 29 | // XXX enhance search to include sorting per list/thread/shard/thingy 30 | 31 | 32 | 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | #include 44 | #if defined(__OpenBSD__) 45 | #include 46 | #include 47 | #else 48 | #include 49 | #endif 50 | #include 51 | #include 52 | 53 | /* For TimeStamping from pcap_pkthdr */ 54 | #include 55 | 56 | /* For the signal handler stuff */ 57 | #include 58 | 59 | /* And my own signal handler functions */ 60 | #include "signal.c" 61 | 62 | /* My own header sherbizzle */ 63 | #include "fingerprintls.h" 64 | 65 | /* Stuff to process packets */ 66 | #include "packet_processing.c" 67 | 68 | /* For username to uid lookup */ 69 | #include 70 | 71 | 72 | 73 | /* 74 | * print help text 75 | */ 76 | void print_usage(char *bin_name) { 77 | fprintf(stderr, "Usage: %s \n\n", bin_name); 78 | fprintf(stderr, "Options:\n"); 79 | fprintf(stderr, " -h This message\n"); 80 | fprintf(stderr, " -i Sniff packets from specified interface\n"); 81 | fprintf(stderr, " -p Read packets from specified pcap file\n"); 82 | fprintf(stderr, " -P Save packets to specified pcap file for unknown fingerprints\n"); 83 | fprintf(stderr, " -j Output JSON fingerprints\n"); 84 | fprintf(stderr, " -l Output logfile (JSON format)\n"); 85 | fprintf(stderr, " -d Show reasons for discarded packets (post BPF)\n"); 86 | fprintf(stderr, " -f Load the (binary) FingerPrint Database\n"); 87 | fprintf(stderr, " -u Drop privileges to specified username\n"); 88 | fprintf(stderr, " -D Do not discard padding (don't do without understanding what this does)\n"); 89 | fprintf(stderr, "\n"); 90 | return; 91 | } 92 | 93 | /* Testing another way of searching the in memory database */ 94 | uint shard_fp (struct fingerprint_new *fp_lookup, uint16_t maxshard) { 95 | return (((fp_lookup->ciphersuite_length) + (fp_lookup->tls_version)) & (maxshard -1)); 96 | } 97 | 98 | int main(int argc, char **argv) { 99 | 100 | char *dev = NULL; /* capture device name */ 101 | uid_t unpriv_user = -1; /* User for dropping privs */ 102 | char errbuf[PCAP_ERRBUF_SIZE]; /* error buffer */ 103 | extern pcap_t *handle; /* packet capture handle */ 104 | extern pcap_dumper_t *output_handle; /* output to pcap handle */ 105 | struct passwd* priv_passwd; /* User id when dropping privileges */ 106 | 107 | char *filter_exp = default_filter; 108 | int arg_start = 1, i; 109 | extern struct bpf_program fp; /* compiled filter program (expression) */ 110 | 111 | extern FILE *json_fd, *fpdb_fd, *log_fd; 112 | int filesize; 113 | uint8_t *fpdb_raw = NULL; 114 | int fp_count = 0; 115 | extern int show_drops; 116 | extern int discard_pad; 117 | extern char hostname[HOST_NAME_MAX]; 118 | show_drops = 0; 119 | 120 | 121 | /* Make sure pipe sees new packets unbuffered. */ 122 | //setvbuf(stdout, (char *)NULL, _IOLBF, 0); 123 | setlinebuf(stdout); 124 | 125 | if (argc == 1) { 126 | print_usage(argv[0]); 127 | exit(-1); 128 | } 129 | /* Do the -something switches - yes this isn't very nice and doesn't support -abcd */ 130 | for (i = arg_start; i < argc && argv[i][0] == '-' ; i++) { 131 | switch (argv[i][1]) { 132 | case '?': 133 | case 'h': 134 | print_usage(argv[0]); 135 | exit(0); 136 | break; 137 | case 'p': 138 | /* Open the file */ 139 | /* Check if interface already set */ 140 | if (handle != NULL) { 141 | printf("-p and -i are mutually exclusive\n"); 142 | exit(-1); 143 | } 144 | handle = pcap_open_offline(argv[++i], errbuf); 145 | printf("Reading from file: %s\n", argv[i]); 146 | break; 147 | case 'P': 148 | /* Open the file */ 149 | output_handle = pcap_dump_open(pcap_open_dead(DLT_EN10MB, 65535), argv[++i]); 150 | if (output_handle != NULL) { 151 | printf("Writing samples to file: %s\n", argv[i]); 152 | } else { 153 | printf("Could not save samples: %s\n", errbuf); 154 | exit(-1); 155 | } 156 | break; 157 | case 'i': 158 | /* Open the interface */ 159 | /* Check if file already successfully opened, if bad filename we can fail to sniffing */ 160 | if (handle != NULL) { 161 | printf("-p and -i are mutually exclusive\n"); 162 | exit(-1); 163 | } 164 | handle = pcap_open_live(argv[++i], SNAP_LEN, 1, 1000, errbuf); 165 | printf("Using interface: \033[1;36m%s\033[1;m\n", argv[i]); 166 | break; 167 | case 'j': 168 | /* JSON output to file */ 169 | if((json_fd = fopen(argv[++i], "a")) == NULL) { 170 | printf("Cannot open JSON file for output\n"); 171 | exit(-1); 172 | } 173 | // Buffering is fine, but linebuf needed for tailers to work properly 174 | setlinebuf(json_fd); 175 | break; 176 | case 'l': 177 | /* Output to log file */ 178 | if((log_fd = fopen(argv[++i], "a")) == NULL) { 179 | printf("Cannot open log file for output\n"); 180 | exit(-1); 181 | } 182 | // Buffering is fine, but linebuf needed for tailers to work properly 183 | setlinebuf(log_fd); 184 | break; 185 | case 's': 186 | /* JSON output to stdout */ 187 | if((json_fd = fopen("/dev/stdout", "a")) == NULL) { 188 | printf("Cannot open JSON file for output\n"); 189 | fprintf(json_fd, "FD TEST\n"); 190 | exit(-1); 191 | } 192 | break; 193 | case 'd': 194 | /* Show Dropped Packet Info */ 195 | show_drops = 1; 196 | break; 197 | case 'D': 198 | /* Discard padding */ 199 | discard_pad = 0; 200 | break; 201 | case 'u': 202 | /* User for dropping privileges to */ 203 | priv_passwd = getpwnam(argv[++i]); 204 | if(priv_passwd == NULL) { 205 | printf("Cannot find user: %s\n", argv[i]); 206 | exit(-1); 207 | } 208 | unpriv_user = priv_passwd->pw_uid; 209 | break; 210 | case 'f': 211 | /* Read the *new* *sparkly* *probably broken* :) binary Fingerprint Database from file */ 212 | /* In the future this will be to override the default location as this will be the default format */ 213 | if((fpdb_fd = fopen(argv[++i], "r")) == NULL) { 214 | printf("Cannot open fingerprint database file\n"); 215 | exit(-1); 216 | } 217 | 218 | break; 219 | default : 220 | printf("Unknown option '%s'\n", argv[i]); 221 | exit(-1); 222 | break; 223 | 224 | } 225 | } 226 | 227 | /* Checks required directly after switches are set */ 228 | 229 | /* Fingerprint DB to load */ 230 | /* This needs to be before the priv drop in case the fingerprint db requires root privs to read */ 231 | if(fpdb_fd == NULL) { 232 | /* No filename set, trying the current directory */ 233 | if((fpdb_fd = fopen("tlsfp.db", "r")) == NULL) { 234 | printf("Cannot open fingerprint database file (try -f)\n"); 235 | printf("(This is a new feature, tlsfp.db should be in the source code directory)\n"); 236 | exit(-1); 237 | } 238 | 239 | } 240 | 241 | /* Interface should already be opened, and files read we can drop privs now */ 242 | /* This should stay the first action as lowering privs reduces risk from any subsequent actions */ 243 | /* being poorly implimented and running as root */ 244 | if (unpriv_user != -1) { 245 | if (setgroups(0, NULL) == -1) { 246 | fprintf(stderr, "WARNING: could not set groups to 0 prior to dropping privileges\n"); 247 | } else { 248 | fprintf(stderr, "Dropped effective group successfully\n"); 249 | } 250 | if (setgid(getgid()) == -1) { 251 | fprintf(stderr, "WARNING: could not drop group privileges\n"); 252 | } else { 253 | fprintf(stderr, "Dropped effective group successfully\n"); 254 | } 255 | if (setuid(unpriv_user) == -1) { 256 | fprintf(stderr, "WARNING: could not drop privileges to specified UID\n"); 257 | } else { 258 | fprintf(stderr, "Changed UID successfully\n"); 259 | } 260 | } 261 | 262 | // Register signal Handlers 263 | if(!(register_signals())) { 264 | printf("Could not register signal handlers\n"); 265 | exit(0); 266 | } 267 | 268 | /* If log_fd isn't set we can just print to stdout */ 269 | if(log_fd == NULL) { 270 | log_fd = stdout; 271 | } 272 | 273 | /* XXX Temporary home, but need to test as early in the cycle as possible for now */ 274 | /* Load binary rules blob and parse */ 275 | 276 | /* XXX This if can go when this is "the way" */ 277 | if(fpdb_fd != NULL) { 278 | /* Find the filesize (seek, tell, seekback) */ 279 | fseek(fpdb_fd, 0L, SEEK_END); 280 | filesize = ftell(fpdb_fd); 281 | fseek(fpdb_fd, 0L, SEEK_SET); 282 | 283 | /* Allocate memory and store the file in fpdb_raw */ 284 | fpdb_raw = malloc(filesize); 285 | if (fread(fpdb_raw, 1, filesize, fpdb_fd) == filesize) { 286 | // printf("Yay, looks like the FPDB file loaded ok\n"); 287 | fclose(fpdb_fd); 288 | } else { 289 | printf("There seems to be a problem reading the FPDB file\n"); 290 | fclose(fpdb_fd); 291 | exit(-1); 292 | } 293 | } 294 | 295 | /* Check and move past the version header (quit if it's wrong) */ 296 | if (*fpdb_raw == 0) { 297 | fpdb_raw++; 298 | } else { 299 | printf("Unknown version of FPDB file\n"); 300 | exit(-1); 301 | } 302 | 303 | int x, y; 304 | struct fingerprint_new *fp_current; 305 | extern struct fingerprint_new *search[8][5]; 306 | 307 | /* Initialise so that we know when we are on the first in any one chain */ 308 | for (x = 0 ; x < 8 ; x++) { 309 | for (y = 0 ; y < 5 ; y++) { 310 | search[x][y] = NULL; 311 | } 312 | } 313 | 314 | /* Filesize -1 because of the header, loops through the file, one loop per fingerprint */ 315 | for (x = 0 ; x < (filesize-1) ; fp_count++) { 316 | /* Allocating one my one instead of in a block, may revise this plan later */ 317 | /* This will only save time on startup as opposed to during operation though */ 318 | 319 | /* Allocate out the memory for the one signature */ 320 | fp_current = malloc(sizeof(struct fingerprint_new)); 321 | 322 | // XXX consider copied (i.e. length) values being free'd to save a little RAM here and there <-- future thing 323 | 324 | fp_current->fingerprint_id = (uint16_t) ((uint16_t)*(fpdb_raw+x) << 8) + ((uint8_t)*(fpdb_raw+x+1)); 325 | x += 2; 326 | fp_current->desc_length = (uint16_t) ((uint16_t)*(fpdb_raw+x) << 8) + ((uint8_t)*(fpdb_raw+x+1)); 327 | fp_current->desc = (char *)fpdb_raw+x+2; 328 | 329 | x += (uint16_t) ((*(fpdb_raw+x) >> 16) + (*(fpdb_raw+x+1)) + 1); // Skip the description 330 | 331 | fp_current->record_tls_version = (uint16_t) ((uint16_t)*(fpdb_raw+x+1) << 8) + ((uint8_t)*(fpdb_raw+x+2)); 332 | fp_current->tls_version = (uint16_t) ((uint16_t)*(fpdb_raw+x+3) << 8) + ((uint8_t)*(fpdb_raw+x+4)); 333 | fp_current->ciphersuite_length = (uint16_t) ((uint16_t)*(fpdb_raw+x+5) << 8) + ((uint8_t)*(fpdb_raw+x+6)); 334 | fp_current->ciphersuite = fpdb_raw+x+7; 335 | 336 | x += (uint16_t) ((*(fpdb_raw+x+5) >> 16) + (*(fpdb_raw+x+6)))+7; // Skip the ciphersuites 337 | 338 | fp_current->compression_length = *(fpdb_raw+x); 339 | fp_current->compression = fpdb_raw+x+1; 340 | 341 | x += (*(fpdb_raw+x))+1; // Skip over compression algo's 342 | 343 | fp_current->extensions_length = (uint16_t) ((uint16_t)*(fpdb_raw+x) << 8) + ((uint8_t)*(fpdb_raw+x+1)); 344 | fp_current->extensions = fpdb_raw+x+2; 345 | 346 | /* If discarding padding, strip out here. In future, if this becomes default I will remove it at the database creation time */ 347 | if(discard_pad == 1) { 348 | int counter; 349 | int debug_counter; 350 | for (counter = 0; counter < fp_current->extensions_length; counter += 2) { 351 | /* This is the two byte value for the padding extension */ 352 | if(fp_current->extensions[counter] == 0 && fp_current->extensions[counter+1] == 21) { 353 | //fprintf(stderr, "\nStripping padding from : %.*s\n", fp_current->desc_length, fp_current->desc); 354 | 355 | /* Print some debuggin material */ 356 | //for(debug_counter = 0; debug_counter < fp_current->extensions_length; debug_counter += 2) { 357 | // printf("%02X%02X ", fp_current->extensions[debug_counter], fp_current->extensions[debug_counter+1]); 358 | //} 359 | //printf(" Length: %i\n", fp_current->extensions_length); 360 | 361 | /* memmove is like memcpy, except it is save for overlapping source and dest (woo!) */ 362 | //fprintf(stderr, "src: %u dst: %u length: %i\n", fp_current->extensions+(counter+2), fp_current->extensions+(counter), (fp_current->extensions_length - (counter + 2))); 363 | memmove(fp_current->extensions+(counter), fp_current->extensions+(counter+2), (fp_current->extensions_length - (counter + 2))); 364 | fp_current->extensions_length -= 2; 365 | 366 | /* Print some debuggin material */ 367 | //for(debug_counter = 0; debug_counter < fp_current->extensions_length; debug_counter += 2) { 368 | // printf("%02X%02X ", fp_current->extensions[debug_counter], fp_current->extensions[debug_counter+1]); 369 | //} 370 | //printf(" Length: %i\n", fp_current->extensions_length); 371 | } 372 | } 373 | } 374 | 375 | x += (uint16_t)((*(fpdb_raw+x) >> 16) + *(fpdb_raw+x+1))+2; // Skip extensions list (not extensions - just the list) 376 | 377 | /* Lengths for the extensions which do not exist have already been set to 0 by fingerprintout.py */ 378 | 379 | fp_current->curves_length = (uint16_t) ((uint16_t)*(fpdb_raw+x) << 8) + ((uint8_t)*(fpdb_raw+x+1)); 380 | 381 | if(fp_current->curves_length == 0) { 382 | fp_current->curves = NULL; 383 | } else { 384 | fp_current->curves = fpdb_raw+x+2; 385 | } 386 | 387 | x += (uint16_t)((*(fpdb_raw+x) >> 16) + *(fpdb_raw+x+1))+2; // Skip past curves 388 | 389 | fp_current->sig_alg_length = (uint16_t) ((uint16_t)*(fpdb_raw+x) << 8) + ((uint8_t)*(fpdb_raw+x+1)); 390 | 391 | if(fp_current->sig_alg_length == 0) { 392 | fp_current->sig_alg = NULL; 393 | } else { 394 | fp_current->sig_alg = fpdb_raw+x+2; 395 | } 396 | 397 | x += (uint16_t)((*(fpdb_raw+x) >> 16) + *(fpdb_raw+x+1))+2; // Skip past signature algorithms 398 | 399 | fp_current->ec_point_fmt_length = (uint16_t) ((uint16_t)*(fpdb_raw+x) << 8) + ((uint8_t)*(fpdb_raw+x+1)); 400 | 401 | if(fp_current->ec_point_fmt_length == 0) { 402 | fp_current->ec_point_fmt = NULL; 403 | } else { 404 | fp_current->ec_point_fmt = fpdb_raw+x+2; 405 | } 406 | x += (uint16_t)((*(fpdb_raw+x) >> 16) + *(fpdb_raw+x+1))+2; 407 | 408 | /* Multi-array of pointers to appropriate (smaller) list */ 409 | /* XXX This should still be ordered for faster search */ 410 | fp_current->next = search[((fp_current->ciphersuite_length & 0x000F) >> 1 )][((fp_current->tls_version) & 0x00FF)]; 411 | search[((fp_current->ciphersuite_length & 0x000F) >> 1 )][((fp_current->tls_version) & 0x00FF)] = fp_current; 412 | } 413 | 414 | printf("Loaded %i signatures\n", fp_count); 415 | 416 | /* XXX END TESTING OF BINARY RULES */ 417 | 418 | /* XXX HORRIBLE HORRIBLE KLUDGE TO AVOID if's everywhere. I KNOW OK?! */ 419 | if(json_fd == NULL) { 420 | if((json_fd = fopen("/dev/null", "a")) == NULL) { 421 | printf("Cannot open JSON file (/dev/null) for output\n"); 422 | exit(-1); 423 | } 424 | } 425 | 426 | if (handle == NULL) { 427 | fprintf(stderr, "Couldn't open source %s: %s\n", dev, errbuf); 428 | exit(EXIT_FAILURE); 429 | } 430 | 431 | /* make sure we're capturing on an Ethernet device [2] */ 432 | if (pcap_datalink(handle) != DLT_EN10MB) { 433 | fprintf(stderr, "%s is not an Ethernet\n", dev); 434 | exit(EXIT_FAILURE); 435 | } 436 | 437 | /* compile the filter expression */ 438 | /* netmask is set to 0 because we don't care and it saves looking it up :) */ 439 | if (pcap_compile(handle, &fp, default_filter, 0, 0) == -1) { 440 | fprintf(stderr, "Couldn't parse filter %s: %s\n", 441 | filter_exp, pcap_geterr(handle)); 442 | exit(EXIT_FAILURE); 443 | } 444 | 445 | /* apply the compiled filter */ 446 | if (pcap_setfilter(handle, &fp) == -1) { 447 | fprintf(stderr, "Couldn't install filter %s: %s\n", 448 | filter_exp, pcap_geterr(handle)); 449 | exit(EXIT_FAILURE); 450 | } 451 | /* setup hostname variable for use in logs (incase of multiple hosts) */ 452 | if(gethostname(hostname, HOST_NAME_MAX) != 0) { 453 | snprintf(hostname, sizeof("unknown"), "unknown"); 454 | } 455 | 456 | /* now we can set our callback function */ 457 | pcap_loop(handle, -1, got_packet, NULL); 458 | 459 | fprintf(stderr, "Reached end of pcap\n"); 460 | 461 | /* cleanup */ 462 | pcap_freecode(&fp); 463 | pcap_close(handle); 464 | 465 | return 0; 466 | } 467 | -------------------------------------------------------------------------------- /fingerprintls/fingerprintls.h: -------------------------------------------------------------------------------- 1 | /* 2 | Exciting Licence Info..... 3 | 4 | This file is part of FingerprinTLS. 5 | 6 | FingerprinTLS is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | FingerprinTLS is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with FingerprinTLS. If not, see . 18 | 19 | Exciting Licence Info Addendum..... 20 | 21 | FingerprinTLS is additionally released under the "don't judge me" program 22 | whereby it is forbidden to rip into me too harshly for programming 23 | mistakes, kthnxbai. 24 | 25 | */ 26 | 27 | /* default snap length (maximum bytes per packet to capture) */ 28 | #define SNAP_LEN 1522 29 | 30 | /* ethernet headers are always exactly 14 bytes [1] */ 31 | #define SIZE_ETHERNET 14 32 | 33 | /* Max hostname length */ 34 | #define HOST_NAME_MAX 255 35 | 36 | #define FPSHARD 32 37 | 38 | /* XXX Work this out and define properly */ 39 | #define MIN_PACKET_LEN 32 40 | 41 | 42 | /* Ethernet addresses are 6 bytes */ 43 | // #define ETHER_ADDR_LEN 6 44 | 45 | /* Ethernet header */ 46 | struct sniff_ethernet { 47 | u_char ether_dhost[ETHER_ADDR_LEN]; /* destination host address */ 48 | u_char ether_shost[ETHER_ADDR_LEN]; /* source host address */ 49 | u_short ether_type; /* IP? ARP? RARP? etc */ 50 | }; 51 | 52 | /* IPv4 header */ 53 | struct ipv4_header { 54 | u_char ip_vhl; /* version << 4 | header length >> 2 */ 55 | u_char ip_tos; /* type of service */ 56 | u_short ip_len; /* total length */ 57 | u_short ip_id; /* identification */ 58 | u_short ip_off; /* fragment offset field */ 59 | #define IP_RF 0x8000 /* reserved fragment flag */ 60 | #define IP_DF 0x4000 /* dont fragment flag */ 61 | #define IP_MF 0x2000 /* more fragments flag */ 62 | #define IP_OFFMASK 0x1fff /* mask for fragmenting bits */ 63 | u_char ip_ttl; /* time to live */ 64 | u_char ip_p; /* protocol */ 65 | u_short ip_sum; /* checksum */ 66 | struct in_addr ip_src,ip_dst; /* source and dest address */ 67 | }; 68 | #define IP_HL(ip) (((ip)->ip_vhl) & 0x0f) 69 | #define IP_V(ip) (((ip)->ip_vhl) >> 4) 70 | 71 | /* TCP header */ 72 | typedef u_int tcp_seq; 73 | 74 | struct tcp_header { 75 | u_short th_sport; /* source port */ 76 | u_short th_dport; /* destination port */ 77 | tcp_seq th_seq; /* sequence number */ 78 | tcp_seq th_ack; /* acknowledgement number */ 79 | #if BYTE_ORDER == LITTLE_ENDIAN 80 | u_int th_x2:4, /* (unused) */ 81 | th_off:4; /* data offset */ 82 | #endif 83 | #if BYTE_ORDER == BIG_ENDIAN 84 | u_int th_off:4, /* data offset */ 85 | th_x2:4; /* (unused) */ 86 | #endif 87 | u_char th_flags; 88 | #define TH_FIN 0x01 89 | #define TH_SYN 0x02 90 | #define TH_RST 0x04 91 | #define TH_PUSH 0x08 92 | #define TH_ACK 0x10 93 | #define TH_URG 0x20 94 | #define TH_ECE 0x40 95 | #define TH_CWR 0x80 96 | #define TH_FLAGS (TH_FIN|TH_SYN|TH_RST|TH_ACK|TH_URG|TH_ECE|TH_CWR) 97 | u_short th_win; /* window */ 98 | u_short th_sum; /* checksum */ 99 | u_short th_urp; /* urgent pointer */ 100 | }; 101 | 102 | 103 | /* 104 | UDP Header 105 | */ 106 | struct udp_header { 107 | u_int16_t sport; 108 | u_int16_t dport; 109 | u_int16_t len; 110 | u_int16_t check; 111 | }; 112 | 113 | /* 114 | Teredo Header 115 | */ 116 | struct teredo_header { 117 | u_int16_t part_a; /* horrible partial byte items, this includes version, class and flow stuff */ 118 | u_int16_t part_b; /* In reality this is horrible and wrong, but we ignore this so yolo */ 119 | u_int16_t length; /* Payload Length */ 120 | u_int8_t nxt_header; 121 | u_int8_t hop_length; 122 | struct in6_addr ip6_src; /* Client IPv4, etc is embedded in here.... nice */ 123 | struct in6_addr ip6_dst; 124 | }; 125 | 126 | #define SSL_MIN_GOOD_VERSION 0x002 127 | #define SSL_MAX_GOOD_VERSION 0x304 128 | 129 | #define OFFSET_HELLO_VERSION 9 130 | #define OFFSET_SESSION_LENGTH 43 131 | #define OFFSET_CIPHER_LIST 44 132 | 133 | #define SSLV2_OFFSET_HELLO_VERSION 3 134 | #define SSLV2_OFFSET_SESSION_LENGTH 6 135 | #define SSLV2_OFFSET_CIPHER_LIST 44 136 | 137 | 138 | char* ssl_version(u_short version) { 139 | static char hex[7]; 140 | switch (version) { 141 | case 0x002: return "SSLv2"; 142 | case 0x300: return "SSLv3"; 143 | case 0x301: return "TLSv1.0"; 144 | case 0x302: return "TLSv1.1"; 145 | case 0x303: return "TLSv1.2"; 146 | case 0x304: return "TLSv1.3"; 147 | } 148 | snprintf(hex, sizeof(hex), "0x%04hx", version); 149 | return hex; 150 | } 151 | 152 | /* Linked list/tree struct. Used to import the binary blob file exported by fingerprintout.py */ 153 | struct fingerprint_new { 154 | uint16_t fingerprint_id; 155 | uint16_t desc_length; 156 | char *desc; 157 | uint16_t record_tls_version; 158 | uint16_t tls_version; 159 | uint16_t ciphersuite_length; 160 | uint8_t *ciphersuite; 161 | uint8_t compression_length; // Actually *IS* a uint8_t field!!! ZOMG 162 | uint8_t *compression; 163 | uint16_t extensions_length; 164 | uint8_t *extensions; 165 | uint16_t curves_length; 166 | uint8_t *curves; 167 | uint16_t sig_alg_length; 168 | uint8_t *sig_alg; 169 | uint16_t ec_point_fmt_length; 170 | uint8_t *ec_point_fmt; 171 | struct fingerprint_new *next; 172 | }; 173 | 174 | 175 | /* This works perfectly well for TLS, but does not catch horrible SSLv2 packets, soooooo.... */ 176 | //char *default_filter = "tcp[tcp[12]/16*4]=22 and (tcp[tcp[12]/16*4+5]=1) and (tcp[tcp[12]/16*4+9]=3) and (tcp[tcp[12]/16*4+1]=3) and (tcp[tcp[12]/16*4+43]=0)"; 177 | /* Filter should now catch TCP based Client Hello, all IPv6 (because BPF doesn't support v6 Payload... gah!) and Client Hellos wrapped in Teredo tunnels */ 178 | 179 | // XXX CHECK IPv6.... doesn't seem to work properly for Chrome testing time!! 180 | // Using terrible ifdefs here to avoid needing to try to figure out the root cause of the OpenBSD errors with simple filters. 181 | // Without this, execution on OpenBSD throws: Couldn't parse filter : too many registers needed to evaluate expression 182 | // Short filters sometimes work and sometimes don't, seems like some sort of weird complexity issue. 183 | #if defined(__OpenBSD__) 184 | char *default_filter = ""; 185 | #else 186 | char *default_filter = "(tcp[tcp[12]/16*4]=22 and (tcp[tcp[12]/16*4+5]=1) and (tcp[tcp[12]/16*4+9]=3) and (tcp[tcp[12]/16*4+1]=3)) or (ip6[(ip6[52]/16*4)+40]=22 and (ip6[(ip6[52]/16*4+5)+40]=1) and (ip6[(ip6[52]/16*4+9)+40]=3) and (ip6[(ip6[52]/16*4+1)+40]=3)) or ((udp[14] = 6 and udp[16] = 32 and udp[17] = 1) and ((udp[(udp[60]/16*4)+48]=22) and (udp[(udp[60]/16*4)+53]=1) and (udp[(udp[60]/16*4)+57]=3) and (udp[(udp[60]/16*4)+49]=3))) or (proto 41 and ip[26] = 6 and ip[(ip[72]/16*4)+60]=22 and (ip[(ip[72]/16*4+5)+60]=1) and (ip[(ip[72]/16*4+9)+60]=3) and (ip[(ip[72]/16*4+1)+60]=3))"; 187 | #endif 188 | 189 | //char *default_filter = ""; 190 | 191 | /* This pushes a bunch of pre-processing out to the BPF filter instead of having to deal with it too much in code */ 192 | // Disabled for now becuase it's too noisey... too many false positives 193 | //char *default_filter = "(tcp[tcp[12]/16*4]=22 and (tcp[tcp[12]/16*4+5]=1)) or ((tcp[tcp[12]/16*4+2]=1) and ((tcp[tcp[12]/16*4+3]=3) or (tcp[tcp[12]/16*4+3]=0)))"; 194 | 195 | /* 196 | Teredo BPF Notes for this dev branch 197 | */ 198 | 199 | /* 200 | "(udp[14] = 6 and udp[16] = 32 and udp[17] = 1) and ((udp[(udp[60]/16*4)+48]=22) and (udp[(udp[60]/16*4)+53]=1) and (udp[(udp[60]/16*4)+57]=3) and (udp[(udp[60]/16*4)+49]=3))" 201 | "udp[14] = 6 and udp[16] = 32 and udp[17] = 1" <-- should detect *any* teredo packet. [14] = 6 captures the next header "6" part. 32 and 1 refer to the 2001::/32 prefix on all Teredo packets. 202 | XXX BBUUUTTT it only seems to match HTTP over teredo! Weeeiiirrrdddd 203 | 204 | 205 | 48 = start of TCP header 206 | "(udp[(udp[60]/16*4)+48]=22)" <-- is the same as "tcp[tcp[12]/16*4]=22" 207 | 208 | ((udp[(udp[60]/16*4)+48]=22) and (udp[(udp[60]/16*4)+53]=1) and (udp[(udp[60]/16*4)+57]=3) and (udp[(udp[60]/16*4)+49]=3)) 209 | 210 | 211 | proto 41 <--- all of 6in4 212 | "proto 41 and ip[26] = 6" <-- tcp header set as next header 213 | 60 for tcp 214 | 215 | (ip[ip[72]/16*4]=22 and (ip[ip[72]/16*4+5]=1) and (ip[ip[72]/16*4+9]=3) and (ip[ip[72]/16*4+1]=3)) 216 | 217 | "proto 41 and ip[26] = 6 and ip[(ip[72]/16*4)+60]=22 and (ip[(ip[72]/16*4+5)+60]=1) and (ip[(ip[72]/16*4+9)+60]=3) and (ip[(ip[72]/16*4+1)+60]=3)" <--- TLS in 6in4 XXX This technique used in IPv6 filter too plz 218 | 219 | */ 220 | 221 | /* --------- */ 222 | /* Externals */ 223 | /* --------- */ 224 | int newsig_count; 225 | int show_drops; 226 | int discard_pad = 1; 227 | FILE *json_fd = NULL; 228 | FILE *fpdb_fd = NULL; 229 | FILE *log_fd = NULL; 230 | 231 | struct fingerprint_new *search[8][5]; 232 | char hostname[HOST_NAME_MAX]; /* store the hostname once to save multiple lookups */ 233 | 234 | 235 | /* These were in main, but this let's the signal handler close as needed */ 236 | pcap_t *handle = NULL; /* packet capture handle */ 237 | pcap_dumper_t *output_handle = NULL; /* output to pcap handle */ 238 | 239 | struct bpf_program fp; /* compiled filter program (expression) */ 240 | /* --------------------------------------------------------------------- */ 241 | 242 | 243 | // Declare all the functions 244 | int register_signals(); 245 | void sig_handler (int signo); 246 | int extensions_compare(uint8_t *packet, uint8_t *fingerprint, int length, int count); 247 | void print_usage(char *bin_name); 248 | void got_packet(u_char *args, const struct pcap_pkthdr *pcap_header, const u_char *packet); 249 | int print_log(char* printable_time, char *server_name, int ip_version, struct ipv4_header *ipv4, struct ip6_hdr *ipv6, struct tcp_header *tcp, struct udp_header *udp, struct teredo_header *teredo, struct fingerprint_new *fp_nav); 250 | -------------------------------------------------------------------------------- /fingerprintls/fpdb.c: -------------------------------------------------------------------------------- 1 | /* Functions, etc used in the management of the internal fingerprint database held in memory */ 2 | 3 | 4 | /* create_fpdb will allocate memory and create a skeleton structure of fingerprint structs to load data into */ 5 | /* In reality the structs are actually pointers to the binary file loaded in memory, but this still needs to */ 6 | /* be managed */ 7 | struct fingerprint_new* create_fpdb(int count) { 8 | struct fingerprint_new *fp_first, *fp_current, *fp_temp; 9 | int i; 10 | /* This malloc suitable for userland only, will need to use another variation if */ 11 | /* any of this code makes it into a kernel */ 12 | fp_temp = fp_current = fp_first = malloc(((int)count * sizeof(struct fingerprint_new))); 13 | 14 | /* Catch errors */ 15 | if (fp_first == NULL) { 16 | return NULL; 17 | } 18 | 19 | /* Initialise a chain of fingerprints */ 20 | /* Currently not sorted, tree'd, index, etc */ 21 | for(i = 1; i <= count; i++) { 22 | fp_current->next = ++fp_temp; 23 | fp_current = fp_temp; 24 | } 25 | /* Set an easy to find end */ 26 | fp_current->next = NULL; 27 | 28 | /* Return pointer to the first state in the chain */ 29 | return fp_first; 30 | 31 | } 32 | -------------------------------------------------------------------------------- /fingerprintls/packet_processing.c: -------------------------------------------------------------------------------- 1 | /* 2 | Exciting Licence Info..... 3 | 4 | This file is part of FingerprinTLS. 5 | 6 | FingerprinTLS is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | FingerprinTLS is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with FingerprinTLS. If not, see . 18 | 19 | Exciting Licence Info Addendum..... 20 | 21 | FingerprinTLS is additionally released under the "don't judge me" program 22 | whereby it is forbidden to rip into me too harshly for programming 23 | mistakes, kthnxbai. 24 | 25 | */ 26 | 27 | // XXX as expected there is a memory leak, because I've been a bit yeeehaw with malloc in doing this test 28 | // check through the code to make sure mallocs and frees are all matched up. (may be fixed?) 29 | 30 | // XXX reuse alloc'd space 31 | 32 | 33 | uint shardnum (uint16_t port1, uint16_t port2, uint16_t maxshard) { 34 | return (((port1 >> 8) + (port2 >> 8)) & (maxshard - 1)); 35 | } 36 | 37 | 38 | 39 | void got_packet(u_char *args, const struct pcap_pkthdr *pcap_header, const u_char *packet) { 40 | /* ************************************************************************* */ 41 | /* Variables, gotta have variables, and structs and pointers.... and things */ 42 | /* ************************************************************************* */ 43 | 44 | extern FILE *json_fd, *log_fd; 45 | extern int newsig_count; 46 | extern char hostname[HOST_NAME_MAX]; 47 | 48 | 49 | int size_ip = 0; 50 | int size_tcp; 51 | uint size_payload; // Check all these for appropiate variable size. Was getting signed negative value and failing tests XXX 52 | int size_vlan_offset=0; 53 | int arse; // Random counter - relocated to allow use elsewhere during testing 54 | 55 | 56 | int ip_version=0; 57 | int af_type; 58 | char src_address_buffer[64]; 59 | char dst_address_buffer[64]; 60 | 61 | struct timeval packet_time; 62 | struct tm *print_time; 63 | char printable_time[64]; 64 | 65 | struct fingerprint_new *fp_nav; /* For navigating the fingerprint database */ 66 | static struct fingerprint_new *fp_packet = NULL; /* Generated fingerprint for incoming packet */ 67 | static uint16_t extensions_malloc = 0; /* how much is currently allocated for the extensions field */ 68 | extern pcap_dumper_t *output_handle; /* output to pcap handle */ 69 | 70 | /* pointers to key places in the packet headers */ 71 | struct ether_header *ethernet; /* The ethernet header [1] */ 72 | struct ipv4_header *ipv4; /* The IPv4 header */ 73 | struct ip6_hdr *ipv6; /* The IPv6 header */ 74 | struct tcp_header *tcp; /* The TCP header */ 75 | struct udp_header *udp; /* The UDP header */ 76 | struct teredo_header *teredo; /* Teredo header */ 77 | 78 | 79 | u_char *payload; /* Packet payload */ 80 | 81 | char *server_name; /* Server name per the extension */ 82 | 83 | /* 84 | Check if this is uninitialised at this point and initialise if so. This saves us copying 85 | in the event that we need a new fingerprint, we already have a populated fingerprint structs 86 | for the most part (barring a couple of memcpy's). This should reduce the time to insert 87 | new signatures. 88 | */ 89 | if(fp_packet == NULL) { 90 | fp_packet = malloc(sizeof(struct fingerprint_new)); 91 | if(fp_packet == NULL) { 92 | printf("Malloc Error (fp_packet)\n"); 93 | exit(0); 94 | } 95 | } 96 | 97 | /* ************************************* */ 98 | /* Anything we need from the pcap_pkthdr */ 99 | /* ************************************* */ 100 | 101 | /* 102 | In theory time doesn't need to be first because it's saved in the PCAP 103 | header, however I am keeping it here incase we derive it from somewhere 104 | else in future and we want it early in the process. 105 | */ 106 | /* Copy each field separately to account for systems where these use different field sizes (OpenBSD...) */ 107 | packet_time.tv_sec = pcap_header->ts.tv_sec; 108 | packet_time.tv_usec = pcap_header->ts.tv_usec; 109 | print_time = localtime(&packet_time.tv_sec); 110 | if (print_time == NULL) { 111 | /* If we get a bad timestamp, set to X's for now, probably just drop in future..... thanks Parker!! ;) */ 112 | snprintf(printable_time, sizeof("XXXX-XX-XX XX:XX:XX"), "XXXX-XX-XX XX:XX:XX"); 113 | if (show_drops) 114 | fprintf(stderr, "[%s] Malformed timestamp from libpcap\n", printable_time); 115 | return; 116 | } else { 117 | strftime(printable_time, sizeof printable_time, "%Y-%m-%d %H:%M:%S", print_time); 118 | } 119 | if(pcap_header->len != pcap_header->caplen) { 120 | /* This is most likely something bad, and likely non-fingerprintable anyway */ 121 | if (show_drops) 122 | printf("[%s] PCAP length does not match packet header length: %u %u\n", printable_time, pcap_header->caplen, pcap_header->len); 123 | return; 124 | } 125 | 126 | /* Temporary debugging. XXX This will be removed */ 127 | if (show_drops) 128 | printf("DEBUG: pcap header length: %u %u\n", pcap_header->len, pcap_header->caplen); 129 | 130 | /* XXX Revisit which value to use - see if this can be part of BPF. Should be to *at least* payload */ 131 | /* Check that the size of the captured packet meets a minimum to even bother considering */ 132 | if (pcap_header->caplen < MIN_PACKET_LEN) { 133 | if (show_drops) 134 | printf("[%s] Packet length (%i) below minimum (%i)\n", printable_time, pcap_header->caplen, MIN_PACKET_LEN); 135 | return; 136 | } 137 | 138 | 139 | /* ******************************************** */ 140 | /* Set pointers to the main parts of the packet */ 141 | /* ******************************************** */ 142 | 143 | /* 144 | Ethernet 145 | */ 146 | 147 | /* 148 | Section to deal with random low layer stuff before we get to IP 149 | */ 150 | 151 | ethernet = (struct ether_header*)(packet); 152 | switch(ntohs(ethernet->ether_type)) { 153 | /* 154 | De-802.1Q things if needed. This isn't in the switch below so that we don't have to loop 155 | back around for IPv4 vs v6 ethertype handling. This is a special case that we just detangle 156 | upfront. Also avoids a while loop, woo! 157 | */ 158 | case ETHERTYPE_VLAN: 159 | // Using loop to account for double tagging (can you triple?!) 160 | for(size_vlan_offset=4; ethernet->ether_type == ETHERTYPE_VLAN ; size_vlan_offset+=4) { 161 | ethernet = (struct ether_header*)(packet+size_vlan_offset); 162 | } 163 | break; 164 | /* PPPoE */ 165 | case 0x8864: 166 | // XXX Need to research further but seems skipping 8 bytes is all we need? But how.... hmmmm... 167 | //ethernet = (struct ether_header*)(packet + size_vlan_offset + 8); 168 | 169 | // This is just a placeholder for now. BPF will probably need updating. 170 | printf("PPPoE\n"); 171 | break; 172 | } 173 | 174 | // Now we can deal with what the ether_type is 175 | switch(ntohs(ethernet->ether_type)){ 176 | case ETHERTYPE_IP: 177 | /* IPv4 */ 178 | ip_version=4; 179 | af_type=AF_INET; 180 | break; 181 | //case ETHERTYPE_IPV6: 182 | case 0x86dd: 183 | /* IPv6 */ 184 | ip_version=6; 185 | af_type=AF_INET6; 186 | break; 187 | default: 188 | /* Something's gone wrong... Doesn't appear to be a valid ethernet frame? */ 189 | if (show_drops) 190 | fprintf(stderr, "[%s] Malformed Ethernet frame\n", printable_time); 191 | return; 192 | } 193 | 194 | 195 | /* 196 | Sadly BPF filters are not equal between IPv4 and IPv6 so we cannot rely on them for everything, so 197 | this section attempts to cope with that. 198 | */ 199 | 200 | /* 201 | IP headers 202 | */ 203 | switch(ip_version) { 204 | case 4: 205 | /* IP Header */ 206 | if((SIZE_ETHERNET + size_vlan_offset) > pcap_header->caplen) { 207 | if(show_drops) 208 | fprintf(stderr, "[%s] Packet Drop: incomplete packet. Size: %i\n", printable_time, pcap_header->caplen); 209 | return; 210 | } 211 | ipv4 = (struct ipv4_header*)(packet + SIZE_ETHERNET + size_vlan_offset); 212 | size_ip = IP_HL(ipv4)*4; 213 | 214 | if (size_ip < 20) { 215 | /* This is just wrong, not even bothering */ 216 | if(show_drops) 217 | fprintf(stderr, "[%s] Packet Drop: Invalid IP header length: %u bytes\n", printable_time, size_ip); 218 | return; 219 | } 220 | 221 | /* Protocol */ 222 | switch(ipv4->ip_p) { 223 | case IPPROTO_TCP: 224 | break; 225 | 226 | case IPPROTO_UDP: 227 | /* 228 | As it stands currently, the BPF should ensure that the *only* UDP is Teredo with TLS IPv6 packets inside, 229 | thus I'm going to assume that is the case for now and set ip_version to 5 (4 to 6 intermediary as I will 230 | never have to support actual IPv5). 231 | */ 232 | ip_version = 7; 233 | 234 | udp = (struct udp_header*)(packet + SIZE_ETHERNET + size_vlan_offset + size_ip); 235 | teredo = (struct teredo_header*)(udp + 1); /* +1 is UDP header, not bytes ;) */ 236 | //tcp = (struct tcp_header*)(packet + SIZE_ETHERNET + size_vlan_offset + size_ip + 8 + sizeof(struct teredo_header)); 237 | 238 | /* setting offset later with size_ip manipulation... may need to ammend this */ 239 | size_ip += sizeof(struct udp_header) + sizeof(struct teredo_header); 240 | if(size_ip > pcap_header->caplen) { 241 | if(show_drops) 242 | fprintf(stderr, "[%s] Packet Drop: incomplete packet. Size: %i\n", printable_time, pcap_header->caplen); 243 | return; 244 | } 245 | break; 246 | 247 | case 0x29: 248 | /* Not using this yet, but here ready for when I impliment 6in4 de-encapsultion (per teredo) */ 249 | ip_version = 8; // No reason... YOLO 250 | ipv6 = (struct ip6_hdr*)(packet + SIZE_ETHERNET + size_vlan_offset + sizeof(struct ipv4_header)); 251 | size_ip += 40; 252 | if(size_ip > pcap_header->caplen) { 253 | if(show_drops) 254 | fprintf(stderr, "[%s] Packet Drop: incomplete packet. Size: %i\n", printable_time, pcap_header->caplen); 255 | return; 256 | } 257 | break; 258 | 259 | default: 260 | /* Not TCP, not trying.... don't care. The BPF filter should 261 | * prevent this happening, but if I remove it you can guarantee I'll have 262 | * forgotten an edge case :) */ 263 | if (show_drops) 264 | fprintf(stderr, "[%s] Packet Drop: non-TCP made it though the filter... weird\n", printable_time); 265 | return; 266 | } 267 | break; 268 | 269 | case 6: 270 | /* IP Header */ 271 | ipv6 = (struct ip6_hdr*)(packet + SIZE_ETHERNET + size_vlan_offset); 272 | size_ip = 40; 273 | 274 | if(size_ip > pcap_header->caplen) { 275 | if(show_drops) 276 | fprintf(stderr, "[%s] Packet Drop: incomplete packet. Size: %i\n", printable_time, pcap_header->caplen); 277 | return; 278 | } 279 | 280 | /* TODO: Parse 'next header(s)' */ 281 | //printf("IP Version? %i\n",ntohl(ipv6->ip6_vfc)>>28); 282 | //printf("Traffic Class? %i\n",(ntohl(ipv6->ip6_vfc)&0x0ff00000)>>24); 283 | //printf("Flow Label? %i\n",ntohl(ipv6->ip6_vfc)&0xfffff); 284 | //printf("Payload? %i\n",ntohs(ipv6->ip6_plen)); 285 | //printf("Next Header? %i\n",ipv6->ip6_nxt); 286 | 287 | // XXX These lines are duplicated, will de-dupe later this is for testing without breaking :) 288 | tcp = (struct tcp_header*)(packet + SIZE_ETHERNET + size_vlan_offset + size_ip); 289 | payload = (u_char *)(packet + SIZE_ETHERNET + size_vlan_offset + size_ip + (tcp->th_off * 4)); 290 | if((SIZE_ETHERNET + size_vlan_offset + size_ip + (tcp->th_off * 4)) > pcap_header->caplen) { 291 | if(show_drops) 292 | fprintf(stderr, "[%s] Packet Drop: incomplete packet. Size: %i\n", printable_time, pcap_header->caplen); 293 | return; 294 | } 295 | 296 | /* Sanity Check... Should be IPv6 */ 297 | if ((ntohl(ipv6->ip6_vfc)>>28)!=6){ 298 | if(show_drops) 299 | fprintf(stderr, "[%s] Packet Drop: Invalid IPv6 header\n", printable_time); 300 | return; 301 | } 302 | 303 | switch(ipv6->ip6_nxt){ 304 | case 6: /* TCP */ 305 | break; 306 | case 17: /* UDP */ 307 | case 58: /* ICMPv6 */ 308 | if(show_drops) 309 | fprintf(stderr, "[%s] Packet Drop: non-TCP made it though the filter... weird\n", printable_time); 310 | return; 311 | 312 | default: 313 | printf("[%s] Packet Drop: Unhandled IPv6 next header: %i\n",printable_time, ipv6->ip6_nxt); 314 | return; 315 | } 316 | 317 | } 318 | 319 | /* 320 | TCP/UDP/Cabbage/Jam 321 | */ 322 | /* Yay, it's TCP, let's set the pointer */ 323 | tcp = (struct tcp_header*)(packet + SIZE_ETHERNET + size_vlan_offset + size_ip); 324 | 325 | size_tcp = (tcp->th_off * 4); 326 | if (size_tcp < 20) { 327 | /* Not even trying if this is the case.... kthnxbai */ 328 | if(show_drops) 329 | printf("[%s] Packet Drop: Invalid TCP header length: %u bytes\n", printable_time, size_tcp); 330 | return; 331 | } 332 | 333 | /* 334 | Packet Payload 335 | */ 336 | 337 | /* Set the payload pointer */ 338 | payload = (u_char *)(packet + SIZE_ETHERNET + size_vlan_offset + size_ip + (tcp->th_off * 4)); 339 | 340 | /* ------------------------------------ */ 341 | 342 | /* How big is our payload, according to header info ??? */ 343 | size_payload = (pcap_header->len - SIZE_ETHERNET - size_vlan_offset - size_ip - (tcp->th_off * 4)); 344 | /* ---------------------------------------------------- */ 345 | 346 | 347 | /* ******************************************************** */ 348 | /* Some basic checks, ignore the packet if it vaguely fails */ 349 | /* ******************************************************** */ 350 | 351 | /* Check it's actually a valid TLS version - this seems to prevent most false positives */ 352 | switch ((payload[OFFSET_HELLO_VERSION]*256) + payload[OFFSET_HELLO_VERSION+1]) { 353 | /* Valid TLS Versions */ 354 | /* Yeah - SSLv2 isn't formatted this way, what a PITA! */ 355 | //case 0x002: /* SSLv2 */ 356 | case 0x300: /* SSLv3 */ 357 | case 0x301: /* TLSv1 */ 358 | case 0x302: /* TLSv1.1 */ 359 | case 0x303: /* TLSv1.2 */ 360 | case 0x304: /* TLSv1.3 */ 361 | break; 362 | default: 363 | /* Doesn't look like a valid TLS version.... probably not even a TLS packet, if it is, it's a bad one */ 364 | if(show_drops) 365 | printf("[%s] Packet Drop: Bad TLS Version %X%X\n", printable_time, payload[OFFSET_HELLO_VERSION], payload[OFFSET_HELLO_VERSION+1]); 366 | return; 367 | } 368 | 369 | /* Check the size of the sessionid */ 370 | const u_char *packet_data = &payload[OFFSET_SESSION_LENGTH]; 371 | if (size_payload < OFFSET_SESSION_LENGTH + packet_data[0] + 3) { 372 | if(show_drops) 373 | printf("[%s] Packet Drop: Session ID looks bad [%i] [%i]\n", printable_time, size_payload, (OFFSET_SESSION_LENGTH + packet_data[0] + 3) ); 374 | return; 375 | } 376 | 377 | /* Temp measure to only capture first client hello... will move to pcap */ 378 | /* if(packet_data[0] > 0) { */ 379 | /* return; */ 380 | /* } */ 381 | 382 | /* ************************************************************************ */ 383 | /* The bit that grabs the useful info from packets (or sets pointers to it) */ 384 | /* ************************************************************************ */ 385 | 386 | /* ID and Desc (with defaults for unknown fingerprints) */ 387 | fp_packet->fingerprint_id = 0; 388 | switch(ip_version) { 389 | case 7: 390 | /* Temporarily Doing this to PoC teredo. Will use outer and inner once it's working */ 391 | /* IPv4 source and IPv6 dest is sorta what the connection is, so temping with that */ 392 | inet_ntop(AF_INET,(void*)&ipv4->ip_src,src_address_buffer,sizeof(src_address_buffer)); 393 | inet_ntop(AF_INET6,(void*)&teredo->ip6_dst,dst_address_buffer,sizeof(dst_address_buffer)); 394 | break; 395 | case 4: 396 | inet_ntop(af_type,(void*)&ipv4->ip_src,src_address_buffer,sizeof(src_address_buffer)); 397 | inet_ntop(af_type,(void*)&ipv4->ip_dst,dst_address_buffer,sizeof(dst_address_buffer)); 398 | break; 399 | case 6: 400 | inet_ntop(af_type,(void*)&ipv6->ip6_src,src_address_buffer,sizeof(src_address_buffer)); 401 | inet_ntop(af_type,(void*)&ipv6->ip6_dst,dst_address_buffer,sizeof(dst_address_buffer)); 402 | break; 403 | case 8: 404 | inet_ntop(AF_INET,(void*)&ipv4->ip_src,src_address_buffer,sizeof(src_address_buffer)); 405 | inet_ntop(AF_INET6,(void*)&ipv6->ip6_dst,dst_address_buffer,sizeof(dst_address_buffer)); 406 | } 407 | 408 | 409 | /* TLS Version (Record Layer - not proper proper) */ 410 | fp_packet->record_tls_version = (payload[1]*256) + payload[2]; 411 | 412 | /* TLS Version */ 413 | fp_packet->tls_version = (payload[OFFSET_HELLO_VERSION]*256) + payload[OFFSET_HELLO_VERSION+1]; 414 | 415 | /* CipherSuite */ 416 | packet_data += 1 + packet_data[0]; 417 | u_short cs_len = packet_data[0]*256 + packet_data[1]; 418 | 419 | /* Check that the offset doesn't push the pointer off the end of the payload */ 420 | if((packet_data + cs_len) >= (payload + size_payload)) { 421 | if(show_drops == 1) { 422 | fprintf(stderr, "CipherSuite length offset Beyond end of packet %s:%i to ", src_address_buffer, ntohs(tcp->th_sport)); 423 | fprintf(stderr, "%s:%i\n", dst_address_buffer, ntohs(tcp->th_dport)); 424 | } 425 | return; 426 | } 427 | /* Length */ 428 | fp_packet->ciphersuite_length = (packet_data[0]*256) + packet_data[1]; 429 | 430 | 431 | /* 432 | CipherSuites 433 | */ 434 | packet_data += 2; // skip cipher suites length 435 | fp_packet->ciphersuite = (uint8_t *)packet_data; 436 | 437 | /* 438 | Compression 439 | */ 440 | u_short comp_len = packet_data[cs_len]; 441 | /* Check that the offset doesn't just past the end of the packet */ 442 | if((packet_data + comp_len) >= (payload + size_payload)) { 443 | if(show_drops == 1) { 444 | fprintf(stderr, "Compression length offset beyond end of packet %s:%i to ", src_address_buffer, ntohs(tcp->th_sport)); 445 | fprintf(stderr, "%s:%i\n", dst_address_buffer, ntohs(tcp->th_dport)); 446 | } 447 | return; 448 | } 449 | 450 | /* 451 | Length 452 | */ 453 | fp_packet->compression_length = comp_len; 454 | 455 | /* 456 | Compression List 457 | */ 458 | packet_data += cs_len + 1; 459 | fp_packet->compression = (uint8_t *)packet_data; 460 | 461 | /* 462 | Extensions 463 | */ 464 | u_short ext_len = packet_data[comp_len]*256 + packet_data[comp_len+1]; 465 | int ext_id, ext_count = 0; 466 | /* Check extension length doesn't run over the end of the packet */ 467 | if((packet_data + ext_len) >= (payload + size_payload)) { 468 | if(show_drops == 1) { 469 | fprintf(stderr, "Extension length offset Beyond end of packet %s:%i to ", src_address_buffer, ntohs(tcp->th_sport)); 470 | fprintf(stderr, "%s:%i\n", dst_address_buffer, ntohs(tcp->th_dport)); 471 | } 472 | return; 473 | } 474 | 475 | /* 476 | Length 477 | */ 478 | packet_data += comp_len + 2; 479 | 480 | /* 481 | Set optional data to NULL in advance 482 | */ 483 | fp_packet->curves = NULL; 484 | fp_packet->sig_alg = NULL; 485 | fp_packet->ec_point_fmt = NULL; 486 | server_name = NULL; 487 | 488 | 489 | /* 490 | So this works - so overall length seems ok 491 | */ 492 | uint8_t *extensions_tmp_ptr = (uint8_t *)packet_data; 493 | 494 | /* 495 | If we are at the end of the packet we have no extensions, without this 496 | we will just run off the end of the packet into unallocated space :/ 497 | */ 498 | if(packet_data - payload > size_payload) { 499 | ext_len = 0; 500 | } 501 | /* Loop through the extensions */ 502 | fp_packet->extensions_length = 0; 503 | for (ext_id = 0; ext_id < ext_len ; ext_id++ ) { 504 | int ext_type; 505 | 506 | /* Set the extension type */ 507 | ext_type = (packet_data[ext_id]*256) + packet_data[ext_id + 1]; 508 | ext_count++; 509 | 510 | /* Handle some special cases */ 511 | switch(ext_type) { 512 | case 0x000a: 513 | /* elliptic_curves */ 514 | fp_packet->curves = (uint8_t *)&packet_data[ext_id + 2]; 515 | /* 2 & 3, not 0 & 1 because of 2nd length field */ 516 | fp_packet->curves_length = fp_packet->curves[2]*256 + fp_packet->curves[3]; 517 | break; 518 | case 0x000b: 519 | /* ec_point formats */ 520 | fp_packet->ec_point_fmt = (uint8_t *)&packet_data[ext_id + 2]; 521 | fp_packet->ec_point_fmt_length = fp_packet->ec_point_fmt[2]; 522 | //printf("ec point length: %i\n", fp_packet->ec_point_fmt_length); 523 | break; 524 | case 0x000d: 525 | /* Signature algorithms */ 526 | fp_packet->sig_alg = (uint8_t *)&packet_data[ext_id + 2]; 527 | fp_packet->sig_alg_length = fp_packet->sig_alg[2]*256 + fp_packet->sig_alg[3]; 528 | break; 529 | case 0x0000: 530 | /* Definitely *NOT* signature-worthy 531 | * but worth noting for debugging source 532 | * of packets during signature creation. 533 | */ 534 | /* Server Name */ 535 | server_name = (char *)&packet_data[ext_id+2]; 536 | break; 537 | 538 | /* Some potential new extenstions to exploit for fingerprint material */ 539 | /* Need to be tested for consistent values before deploying though */ 540 | case 0x0015: 541 | /* Padding */ 542 | /* XXX Need to check if padding length is consistent or varies (varies is not useful to us) */ 543 | break; 544 | case 0x0010: 545 | /* application_layer_protocol_negotiation */ 546 | 547 | break; 548 | case 0x000F: 549 | /* HeartBeat (as per padding, is this consistent?) */ 550 | 551 | break; 552 | } 553 | 554 | if(ext_type == 0x0015 && discard_pad == 1) { 555 | /* Do nothing... we're ignoring padding */ 556 | /* Although there is probably a more elegant way to do this */ 557 | } else { 558 | fp_packet->extensions_length = (ext_count * 2); 559 | 560 | /* Increment past the payload of the extensions */ 561 | } 562 | ext_id += (packet_data[ext_id + 2]*256) + packet_data[ext_id + 3] + 3; 563 | 564 | 565 | if((packet_data + ext_id) >= (payload + size_payload)) { 566 | if(show_drops == 1) { 567 | fprintf(stderr, "Extension offset beyond end of packet %s:%i to ", src_address_buffer, ntohs(tcp->th_sport)); 568 | fprintf(stderr, "%s:%i\n", dst_address_buffer, ntohs(tcp->th_dport)); 569 | } 570 | return; 571 | } 572 | 573 | } 574 | 575 | /* XXX This horrible kludge to get around the 2 length fields. FIX IT! */ 576 | // XXX Check that curves are working (being matched, etc) 577 | uint8_t *realcurves = fp_packet->curves; 578 | if (fp_packet->curves != NULL) { 579 | realcurves += 4; 580 | } else { 581 | realcurves = NULL; 582 | fp_packet->curves_length = 0; 583 | } 584 | /* ******************************************************************** */ 585 | 586 | /* XXX This horrible kludge to get around the 2 length fields. FIX IT! */ 587 | uint8_t *realsig_alg = fp_packet->sig_alg; 588 | if(fp_packet->sig_alg != NULL) { 589 | realsig_alg += 4; 590 | fp_packet->sig_alg = realsig_alg; 591 | } else { 592 | realsig_alg = NULL; 593 | fp_packet->sig_alg_length = 0; 594 | } 595 | /* ******************************************************************** */ 596 | 597 | /* XXX This horrible kludge to get around the 2 length fields. FIX IT! */ 598 | uint8_t *realec_point_fmt = fp_packet->ec_point_fmt; 599 | if(fp_packet->ec_point_fmt != NULL) { 600 | realec_point_fmt += 3; 601 | } else { 602 | realec_point_fmt = NULL; 603 | fp_packet->ec_point_fmt_length = 0; 604 | } 605 | /* ******************************************************************** */ 606 | 607 | 608 | 609 | /* 610 | Extensions use offsets, etc so we can alloc those now. Others however will just have pointers 611 | and we can malloc if it becomes a signature. For this reason we have extensions_malloc to track 612 | the current size for easy reuse instead of consantly malloc and free'ing the space. 613 | */ 614 | 615 | if(extensions_malloc == 0) { 616 | fp_packet->extensions = malloc(fp_packet->extensions_length); 617 | extensions_malloc = fp_packet->extensions_length; 618 | } else{ 619 | if(fp_packet->extensions_length > extensions_malloc) { 620 | fp_packet->extensions = realloc(fp_packet->extensions, fp_packet->extensions_length); 621 | extensions_malloc = fp_packet->extensions_length; 622 | } 623 | } 624 | if(fp_packet->extensions == NULL) { 625 | printf("Malloc Error (extensions)\n"); 626 | exit(0); 627 | } 628 | 629 | // Load up the extensions 630 | int unarse = 0; 631 | for (arse = 0 ; arse < ext_len ;) { 632 | if((uint8_t) extensions_tmp_ptr[arse] == 0x00 && (uint8_t) extensions_tmp_ptr[arse+1] == 0x15 && discard_pad == 1) { 633 | arse = arse + 4 + (((uint8_t) extensions_tmp_ptr[(arse+2)])*256) + (uint8_t)(extensions_tmp_ptr[arse+3]); 634 | } else { 635 | fp_packet->extensions[unarse] = (uint8_t) extensions_tmp_ptr[arse]; 636 | fp_packet->extensions[unarse+1] = (uint8_t) extensions_tmp_ptr[arse+1]; 637 | unarse += 2; 638 | arse = arse + 4 + (((uint8_t) extensions_tmp_ptr[(arse+2)])*256) + (uint8_t)(extensions_tmp_ptr[arse+3]); 639 | } 640 | } 641 | 642 | /* ********************************************* */ 643 | /* The "compare to the fingerprint database" bit */ 644 | /* ********************************************* */ 645 | 646 | 647 | int matchcount = 0; 648 | 649 | /* ************************* */ 650 | /* New Matching thinger test */ 651 | /* ************************* */ 652 | for(fp_nav = search[((fp_packet->ciphersuite_length & 0x000F) >> 1 )][((fp_packet->tls_version) & 0x00FF)] ; 653 | fp_nav != NULL; fp_nav = fp_nav->next) { 654 | 655 | // XXX Need to optimise order and remove duplicate checks already used during indexing. 656 | if ((fp_packet->record_tls_version == fp_nav->record_tls_version) && 657 | (fp_packet->tls_version == fp_nav->tls_version) && 658 | /* XXX extensions_length is misleading! Length is variable, it is a count of 659 | uint8_t's that makes the extensions _list_. Furthermore, these values are 660 | in pairs, so the count is actually half this.... Handle much more carefully 661 | kthnxbai */ 662 | /* Note: check lengths match first, the later comparisons assume these already match */ 663 | 664 | (fp_packet->ciphersuite_length == fp_nav->ciphersuite_length) && 665 | (fp_packet->compression_length == fp_nav->compression_length) && 666 | (fp_packet->extensions_length == fp_nav->extensions_length) && 667 | (fp_packet->curves_length == fp_nav->curves_length) && 668 | (fp_packet->sig_alg_length == fp_nav->sig_alg_length) && 669 | (fp_packet->ec_point_fmt_length == fp_nav->ec_point_fmt_length) && 670 | 671 | !(bcmp(fp_packet->ciphersuite, fp_nav->ciphersuite, fp_nav->ciphersuite_length)) && 672 | !(bcmp(fp_packet->compression, fp_nav->compression, fp_nav->compression_length)) && 673 | !(bcmp(fp_packet->extensions, fp_nav->extensions, fp_nav->extensions_length)) && 674 | !(bcmp(realcurves, fp_nav->curves, fp_nav->curves_length)) && 675 | !(bcmp(realsig_alg, fp_nav->sig_alg, fp_nav->sig_alg_length)) && 676 | !(bcmp(realec_point_fmt, fp_nav->ec_point_fmt, fp_nav->ec_point_fmt_length))) { 677 | 678 | /* Whole criteria match.... woo! */ 679 | matchcount++; 680 | 681 | /* **** */ 682 | /* Now print - irrespective of new or otherwise - we'll always have something :) */ 683 | /* **** */ 684 | 685 | print_log(printable_time, server_name, ip_version, ipv4, ipv6, tcp, udp, teredo, fp_nav); 686 | 687 | /* In theory multiple matches were not possible, now with padding stripping they are. */ 688 | /* Therefore forbibly exiting the for loop here. Should also make things faster as */ 689 | /* we no longer test the remainder of the chain after a match */ 690 | break; 691 | 692 | 693 | } else { 694 | // Fuzzy Match goes here (if we ever want it) 695 | 696 | } 697 | 698 | } 699 | 700 | /* ********************************************* */ 701 | 702 | 703 | if(matchcount == 0) { 704 | 705 | /* 706 | OK, we're setting up a signature, let's actually do some memory fun 707 | */ 708 | uint8_t *temp; 709 | 710 | /* Update pointer for next to the top of list */ 711 | fp_packet->next = search[((fp_packet->ciphersuite_length & 0x000F) >> 1 )][((fp_packet->tls_version) & 0x00FF)]; 712 | 713 | /* Populate the fingerprint */ 714 | fp_packet->fingerprint_id = 0; 715 | 716 | /* Check it's not a system I've not seen with crazy long PIDs */ 717 | fp_packet->desc_length = strlen("Dynamic ") + strlen(hostname) + 7; // 7 should cover the max uint16_t + space 718 | if(getpid() < 99999) { 719 | fp_packet->desc_length += 6; /* Adding space to include PID in the temp description */ 720 | } 721 | fp_packet->desc = malloc(fp_packet->desc_length); 722 | 723 | if(fp_packet->desc == NULL) { 724 | printf("Malloc Error (desc)\n"); 725 | exit(0); 726 | } 727 | /* Makes it easier to find dynamic signatures in logs after a daemon restart */ 728 | if(getpid() < 99999) { 729 | snprintf(fp_packet->desc, fp_packet->desc_length, "Dynamic %s %d %d", hostname, getpid(), newsig_count); 730 | } else { 731 | snprintf(fp_packet->desc, fp_packet->desc_length, "Dynamic %s %d", hostname, newsig_count); 732 | } 733 | 734 | fp_packet->sig_alg = malloc(fp_packet->sig_alg_length); 735 | if(fp_packet->sig_alg == NULL) { 736 | printf("Malloc Error (sig_alg)\n"); 737 | exit(0); 738 | } 739 | 740 | fp_packet->ec_point_fmt = malloc(fp_packet->ec_point_fmt_length); 741 | if(fp_packet->ec_point_fmt == NULL) { 742 | printf("Malloc Error (ec_point_fmt)\n"); 743 | exit(0); 744 | } 745 | 746 | fp_packet->curves = malloc(fp_packet->curves_length); 747 | if(fp_packet->curves == NULL) { 748 | printf("Malloc Error (curves)\n"); 749 | exit(0); 750 | } 751 | 752 | temp = fp_packet->ciphersuite; 753 | fp_packet->ciphersuite = malloc(fp_packet->ciphersuite_length); 754 | if(fp_packet->ciphersuite == NULL) { 755 | printf("Malloc Error (ciphersuites)\n"); 756 | exit(0); 757 | } 758 | memcpy(fp_packet->ciphersuite, temp, fp_packet->ciphersuite_length); 759 | 760 | temp = fp_packet->compression; 761 | fp_packet->compression = malloc(fp_packet->compression_length); 762 | if(fp_packet->compression == NULL) { 763 | printf("Malloc Error (compression)\n"); 764 | exit(0); 765 | } 766 | memcpy(fp_packet->compression, temp, fp_packet->compression_length); 767 | 768 | memcpy(fp_packet->curves, realcurves, fp_packet->curves_length); 769 | memcpy(fp_packet->sig_alg, realsig_alg, fp_packet->sig_alg_length); 770 | memcpy(fp_packet->ec_point_fmt, realec_point_fmt, fp_packet->ec_point_fmt_length); 771 | 772 | 773 | printf("[%s] New FingerPrint [%i] Detected, dynamically adding to in-memory fingerprint database\n", printable_time, newsig_count++); 774 | fp_nav = fp_packet; // Temporarily just point one thing to another for testing. 775 | 776 | 777 | /* 778 | Insert fingerprint as first in it's "list" 779 | */ 780 | search[((fp_packet->ciphersuite_length & 0x000F) >> 1 )][((fp_packet->tls_version) & 0x00FF)] = fp_packet; 781 | 782 | 783 | /* If selected output in the normal stream */ 784 | 785 | printf("[%s] New Fingerprint \"%s\": %s connection from %s:%i to ", printable_time, fp_nav->desc, ssl_version(fp_packet->tls_version), 786 | src_address_buffer, ntohs(tcp->th_sport)); 787 | printf("%s:%i ", dst_address_buffer, ntohs(tcp->th_dport)); 788 | printf("Servername: \""); 789 | if(server_name != NULL) { 790 | for (arse = 7 ; arse <= (server_name[0]*256 + server_name[1]) + 1 ; arse++) { 791 | if (server_name[arse] > 0x20 && server_name[arse] < 0x7b) 792 | printf("%c", server_name[arse]); 793 | } 794 | } else { 795 | printf("Not Set"); 796 | } 797 | printf("\"\n"); 798 | 799 | // Should just for json_fd being /dev/null and skip .. optimisation... 800 | // or make an output function linked list XXX 801 | fprintf(json_fd, "{\"id\": %i, \"desc\": \"", fp_packet->fingerprint_id); 802 | fprintf(json_fd, "%s\", ", fp_packet->desc); 803 | fprintf(json_fd, "\"record_tls_version\": \"0x%.04X\", ", fp_packet->record_tls_version); 804 | fprintf(json_fd, "\"tls_version\": \"0x%.04X\", \"ciphersuite_length\": \"0x%.04X\", ", 805 | fp_packet->tls_version, fp_packet->ciphersuite_length); 806 | 807 | fprintf(json_fd, "\"ciphersuite\": \""); 808 | for (arse = 0; arse < fp_packet->ciphersuite_length; ) { 809 | fprintf(json_fd, "0x%.02X%.02X", (uint8_t) fp_packet->ciphersuite[arse], (uint8_t) fp_packet->ciphersuite[arse+1]); 810 | arse = arse + 2; 811 | if(arse + 1 < fp_packet->ciphersuite_length) 812 | fprintf(json_fd, " "); 813 | } 814 | fprintf(json_fd, "\", "); 815 | 816 | 817 | 818 | fprintf(json_fd, "\"compression_length\": \"%i\", ", 819 | fp_packet->compression_length); 820 | 821 | fprintf(json_fd, " \"compression\": \""); 822 | if (fp_packet->compression_length == 1) { 823 | fprintf(json_fd, "0x%.02X", (uint8_t) fp_packet->compression[0]); 824 | } else { 825 | for (arse = 0; arse < fp_packet->compression_length; ) { 826 | fprintf(json_fd, "0x%.02X", (uint8_t) fp_packet->compression[arse]); 827 | arse++; 828 | if(arse < fp_packet->compression_length) 829 | fprintf(json_fd, " "); 830 | } 831 | } 832 | 833 | fprintf(json_fd, "\", "); 834 | 835 | 836 | fprintf(json_fd, "\"extensions\": \""); 837 | for (arse = 0 ; arse < fp_packet->extensions_length ;) { 838 | fprintf(json_fd, "0x%.02X%.02X", (uint8_t) fp_packet->extensions[arse], (uint8_t) fp_packet->extensions[arse+1]); 839 | arse = arse + 2; 840 | if(arse < ext_len -1) 841 | fprintf(json_fd, " "); 842 | } 843 | fprintf(json_fd, "\""); 844 | 845 | if(fp_packet->curves != NULL) { 846 | fprintf(json_fd, ", \"e_curves\": \""); 847 | 848 | for (arse = 0 ; arse < fp_packet->curves_length && 849 | fp_packet->curves_length > 0 ; arse = arse + 2) { 850 | 851 | fprintf(json_fd, "0x%.2X%.2X", fp_packet->curves[arse], fp_packet->curves[arse+1]); 852 | if ((arse + 1) < fp_packet->curves_length) { 853 | fprintf(json_fd, " "); 854 | } 855 | } 856 | fprintf(json_fd, "\""); 857 | } 858 | 859 | if(fp_packet->sig_alg != NULL) { 860 | fprintf(json_fd, ", \"sig_alg\": \""); 861 | 862 | for (arse = 0 ; arse < (fp_packet->sig_alg_length) && 863 | fp_packet->sig_alg_length > 0 ; arse = arse + 2) { 864 | 865 | fprintf(json_fd, "0x%.2X%.2X", fp_packet->sig_alg[arse], fp_packet->sig_alg[arse+1]); 866 | if ((arse + 1) < (fp_packet->sig_alg_length)) { 867 | fprintf(json_fd, " "); 868 | } 869 | } 870 | fprintf(json_fd, "\""); 871 | } 872 | 873 | if(fp_packet->ec_point_fmt != NULL) { 874 | fprintf(json_fd, ", \"ec_point_fmt\": \""); 875 | 876 | // Jumping to "3" to get past the second length parameter... errrr... why? 877 | for (arse = 0 ; arse < fp_packet->ec_point_fmt_length; arse++) { 878 | fprintf(json_fd, "0x%.2X", fp_packet->ec_point_fmt[arse]); 879 | if ((arse + 1) < fp_packet->ec_point_fmt_length) { 880 | fprintf(json_fd, " "); 881 | } 882 | } 883 | fprintf(json_fd, "\""); 884 | } 885 | 886 | if(server_name != NULL) { 887 | fprintf(json_fd, ", \"server_name\": \""); 888 | for (arse = 7 ; arse <= (server_name[0]*256 + server_name[1]) + 1 ; arse++) { 889 | if (server_name[arse] > 0x20 && server_name[arse] < 0x7b) 890 | fprintf(json_fd, "%c", server_name[arse]); 891 | else 892 | fprintf(json_fd, "*"); 893 | } 894 | fprintf(json_fd, "\""); 895 | } 896 | 897 | fprintf(json_fd, "}\n"); 898 | 899 | 900 | /* Print the record into the normal log */ 901 | print_log(printable_time, server_name, ip_version, ipv4, ipv6, tcp, udp, teredo, fp_nav); 902 | 903 | /* **************************** */ 904 | /* END OF RECORD - OR SOMETHING */ 905 | /* **************************** */ 906 | 907 | /* Write the sample packet out */ 908 | if(output_handle != NULL) { 909 | pcap_dump((u_char *)output_handle, pcap_header, packet); 910 | } 911 | 912 | /* 913 | Setup the new fp_packet for the next incoming packet. Next call to this function will cause a malloc. 914 | */ 915 | fp_packet = NULL; 916 | extensions_malloc = 0; 917 | 918 | } else { 919 | 920 | } 921 | 922 | } 923 | 924 | int print_log(char* printable_time, char *server_name, int ip_version, struct ipv4_header *ipv4, struct ip6_hdr *ipv6, struct tcp_header *tcp, struct udp_header *udp, struct teredo_header *teredo, struct fingerprint_new *fp_nav) { 925 | /* Prints out line of JSON to the log_fd descriptor */ 926 | 927 | char src_address_buffer[64]; /* Printable address */ 928 | char dst_address_buffer[64]; /* Printable address */ 929 | int arse; /* Just a loop counter */ 930 | 931 | fprintf(log_fd, "{ "); // May need more header to define type? 932 | fprintf(log_fd, "\"timestamp\": \"%s\", ", printable_time); 933 | fprintf(log_fd, "\"event\": \"fingerprint_match\", "); 934 | 935 | fprintf(log_fd, "\"ip_version\": "); 936 | switch(ip_version) { 937 | case 4: 938 | /* IPv4 */ 939 | fprintf(log_fd, "\"ipv4\", "); 940 | inet_ntop(AF_INET,(void*)&ipv4->ip_src,src_address_buffer,sizeof(src_address_buffer)); 941 | inet_ntop(AF_INET,(void*)&ipv4->ip_dst,dst_address_buffer,sizeof(dst_address_buffer)); 942 | fprintf(log_fd, "\"ipv4_src\": \"%s\", ", src_address_buffer); 943 | fprintf(log_fd, "\"ipv4_dst\": \"%s\", ", dst_address_buffer); 944 | 945 | fprintf(log_fd, "\"src_port\": %hu, ", ntohs(tcp->th_sport)); 946 | fprintf(log_fd, "\"dst_port\": %hu, ", ntohs(tcp->th_dport)); 947 | 948 | break; 949 | case 6: 950 | /* IPv6 */ 951 | fprintf(log_fd, "\"ipv6\", "); 952 | inet_ntop(AF_INET6,(void*)&ipv6->ip6_src,src_address_buffer,sizeof(src_address_buffer)); 953 | inet_ntop(AF_INET6,(void*)&ipv6->ip6_dst,dst_address_buffer,sizeof(dst_address_buffer)); 954 | fprintf(log_fd, "\"ipv6_src\": \"%s\", ", src_address_buffer); 955 | fprintf(log_fd, "\"ipv6_dst\": \"%s\", ", dst_address_buffer); 956 | 957 | fprintf(log_fd, "\"src_port\": %hu, ", ntohs(tcp->th_sport)); 958 | fprintf(log_fd, "\"dst_port\": %hu, ", ntohs(tcp->th_dport)); 959 | break; 960 | case 7: 961 | /* 962 | * Teredo. As this is an IPv6 within IPv4 tunnel, both sets of address are logged. 963 | * The field names remain the same for ease of reporting on "all traffic from X" type 964 | * scenarios, however the "ip_version" field makes it clear that this is an encapsulted 965 | * tunnel. 966 | */ 967 | fprintf(log_fd, "\"teredo\", "); 968 | inet_ntop(AF_INET,(void*)&ipv4->ip_src,src_address_buffer,sizeof(src_address_buffer)); 969 | inet_ntop(AF_INET,(void*)&ipv4->ip_dst,dst_address_buffer,sizeof(dst_address_buffer)); 970 | fprintf(log_fd, "\"ipv4_src\": \"%s\", ", src_address_buffer); 971 | fprintf(log_fd, "\"ipv4_dst\": \"%s\", ", dst_address_buffer); 972 | inet_ntop(AF_INET6,(void*)&ipv6->ip6_src,src_address_buffer,sizeof(src_address_buffer)); 973 | inet_ntop(AF_INET6,(void*)&ipv6->ip6_dst,dst_address_buffer,sizeof(dst_address_buffer)); 974 | fprintf(log_fd, "\"ipv6_src\": \"%s\", ", src_address_buffer); 975 | fprintf(log_fd, "\"ipv6_dst\": \"%s\", ", dst_address_buffer); 976 | 977 | fprintf(log_fd, "\"src_port\": %hu, ", ntohs(tcp->th_sport)); 978 | fprintf(log_fd, "\"dst_port\": %hu, ", ntohs(tcp->th_dport)); 979 | 980 | /* Add in ports of the outer Teredo tunnel? */ 981 | 982 | break; 983 | case 8: 984 | /* 985 | * 6in4. As this is an IPv6 within IPv4 tunnel, both sets of address are logged. 986 | * The field names remain the same for ease of reporting on "all traffic from X" type 987 | * scenarios, however the "ip_version" field makes it clear that this is an encapsulted 988 | * tunnel. 989 | */ 990 | fprintf(log_fd, "\"6in4\", "); 991 | inet_ntop(AF_INET,(void*)&ipv4->ip_src,src_address_buffer,sizeof(src_address_buffer)); 992 | inet_ntop(AF_INET,(void*)&ipv4->ip_dst,dst_address_buffer,sizeof(dst_address_buffer)); 993 | fprintf(log_fd, "\"ipv4_src\": \"%s\", ", src_address_buffer); 994 | fprintf(log_fd, "\"ipv4_dst\": \"%s\", ", dst_address_buffer); 995 | inet_ntop(AF_INET6,(void*)&ipv6->ip6_src,src_address_buffer,sizeof(src_address_buffer)); 996 | inet_ntop(AF_INET6,(void*)&ipv6->ip6_dst,dst_address_buffer,sizeof(dst_address_buffer)); 997 | fprintf(log_fd, "\"ipv6_src\": \"%s\", ", src_address_buffer); 998 | fprintf(log_fd, "\"ipv6_dst\": \"%s\", ", dst_address_buffer); 999 | 1000 | fprintf(log_fd, "\"src_port\": %hu, ", ntohs(tcp->th_sport)); 1001 | fprintf(log_fd, "\"dst_port\": %hu, ", ntohs(tcp->th_dport)); 1002 | break; 1003 | } 1004 | 1005 | fprintf(log_fd, "\"tls_version\": \"%s\", ", ssl_version(fp_nav->tls_version)); 1006 | fprintf(log_fd, "\"fingerprint_desc\": \"%.*s\", ", fp_nav->desc_length, fp_nav->desc); 1007 | fprintf(log_fd, "\"server_name\": \""); 1008 | 1009 | if(server_name != NULL) { 1010 | for (arse = 7 ; arse <= (server_name[0]*256 + server_name[1]) + 1 ; arse++) { 1011 | if (server_name[arse] > 0x20 && server_name[arse] < 0x7b) 1012 | fprintf(log_fd, "%c", server_name[arse]); 1013 | } 1014 | } 1015 | 1016 | 1017 | fprintf(log_fd, "\" }\n"); 1018 | return 0; 1019 | } 1020 | -------------------------------------------------------------------------------- /fingerprintls/signal.c: -------------------------------------------------------------------------------- 1 | /* 2 | Exciting Licence Info..... 3 | 4 | This file is part of FingerprinTLS. 5 | 6 | FingerprinTLS is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | FingerprinTLS is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with FingerprinTLS. If not, see . 18 | 19 | Exciting Licence Info Addendum..... 20 | 21 | FingerprinTLS is additionally released under the "don't judge me" program 22 | whereby it is forbidden to rip into me too harshly for programming 23 | mistakes, kthnxbai. 24 | 25 | */ 26 | 27 | /* This File Is To Cope With Signal Handling Routines */ 28 | 29 | void sig_handler (int signo); 30 | 31 | 32 | /* Function registers all the signals to the sig_handler function */ 33 | int register_signals() { 34 | if (signal(SIGUSR1, sig_handler) == SIG_ERR) 35 | return 0; 36 | if (signal(SIGUSR2, sig_handler) == SIG_ERR) 37 | return 0; 38 | if (signal(SIGINT, sig_handler) == SIG_ERR) 39 | return 0; 40 | 41 | return 1; 42 | } 43 | 44 | 45 | /* Handles a variety of signals being received */ 46 | void sig_handler (int signo) { 47 | struct pcap_stat pstats; 48 | extern FILE *json_fd; 49 | extern pcap_t *handle; /* packet capture handle */ 50 | extern pcap_dumper_t *output_handle; 51 | extern struct bpf_program fp; /* compiled filter program (expression) */ 52 | 53 | switch (signo) { 54 | 55 | /* Placeholder, will use this for some debugging */ 56 | case SIGUSR1: 57 | // This is where code goes :) 58 | break; 59 | 60 | /* Someone has ctrl-c'd the process.... deal */ 61 | case SIGINT: 62 | // Get some stats on the session 63 | if(!(pcap_stats(handle, &pstats))) { 64 | printf("Processed %i%% Of Packets\n", 65 | (int) (( (float)((float)pstats.ps_recv - (float)pstats.ps_drop) / (float) pstats.ps_recv) * 100) ); 66 | printf("Received: %i\n", pstats.ps_recv); 67 | printf("Dropped: %i\n", pstats.ps_drop); 68 | } 69 | 70 | /* Stop the pcap loop */ 71 | pcap_breakloop(handle); 72 | 73 | // Close File Pointers 74 | fclose(json_fd); 75 | 76 | // No checking because accoring to the man page, they don't return anything useful o_O 77 | pcap_freecode(&fp); 78 | pcap_close(handle); 79 | if(output_handle != NULL) { 80 | pcap_dump_close(output_handle); 81 | } 82 | 83 | 84 | exit(1); 85 | break; 86 | 87 | default: 88 | printf("Caught signal: %i\n", signo); 89 | exit(0); 90 | } 91 | 92 | 93 | } 94 | -------------------------------------------------------------------------------- /fingerprintls/tlsfp.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeeBrotherston/tls-fingerprinting/4b6e8781872cdf89e892c156350152683920cf8e/fingerprintls/tlsfp.db -------------------------------------------------------------------------------- /scripts/README.md: -------------------------------------------------------------------------------- 1 | # TLS Fingerprinting additional scripts 2 | 3 | * **fingerprintout.py** - Used to convert the fingerprints.json file to various other formats. Mostly useful using "-c" to "cleanse". That is, remove servernames to protect privacy and flag up duplicate fingerprints. 4 | * **parselog.py** - A log tailer for humans reading the output from fingerprintls. Makes it pretty instead of json. 5 | -------------------------------------------------------------------------------- /scripts/fingerprintout.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2 2 | 3 | # XXX Recalculate the sizes for int's instead of char arrays 4 | # XXX Work out how to pre-populate as ints instead of char arrays 5 | 6 | import argparse 7 | import json 8 | import sys 9 | import re 10 | import binascii # Needed for the binary option 11 | 12 | # Open the JSON file 13 | def read_file(filename): 14 | jfile = [] 15 | with open(filename) as f: 16 | for line in f: 17 | jfile.append(json.loads(line)) 18 | return jfile 19 | 20 | # Take Single or multi byte strings or mixed: "0x00 0x0000 0x00" 21 | # and return entirely single byte version: "0x00 0x00 0x00 0x00" in binary format 22 | def byte_to_bin(in_string): 23 | in_string = in_string.replace(' ', '') 24 | in_string = in_string.replace('0x', '') 25 | out_string = binascii.a2b_hex(in_string) 26 | return out_string 27 | 28 | 29 | def cleanse(filename): 30 | # Reoutput the database cleaned a little... e.g. before uploading somewhere 31 | jfile = read_file(filename) 32 | objcount = len(jfile) 33 | j2file = [] 34 | with open(filename) as f: 35 | for line in f: 36 | j2file.append(json.loads(line)) 37 | # Not the smartest check ever but if the fingerprint is the same, not including 38 | # id, desc & server it'll flag as a duplicate. Will miss a 100% identical line, 39 | # but that's ok because this was for the stuff sort & unique can't handle. 40 | for i in jfile: 41 | for x in j2file: 42 | if i["record_tls_version"].strip() == x["record_tls_version"].strip() and \ 43 | i["tls_version"].strip() == x["tls_version"].strip() and \ 44 | i["ciphersuite_length"].strip() == x["ciphersuite_length"].strip() and \ 45 | i["ciphersuite"].strip() == x["ciphersuite"].strip() and \ 46 | i["compression_length"].strip() == x["compression_length"].strip() and \ 47 | i["compression"].strip() == x["compression"].strip() and \ 48 | i["extensions"].strip() == x["extensions"].strip() and \ 49 | "e_curves" in i and \ 50 | "e_curves" in x \ 51 | and i["e_curves"].strip() == x["e_curves"].strip() and \ 52 | "sig_alg" in i and \ 53 | "sig_alg" in x and \ 54 | i["sig_alg"].strip() == x["sig_alg"].strip() and \ 55 | "ec_point_fmt" in i and \ 56 | i["ec_point_fmt"].strip() == x["ec_point_fmt"].strip(): 57 | if i["desc"].strip() != x["desc"].strip(): 58 | print "# Oh no, 2 signatures match: "+str(i["desc"].strip())+" - "+str(x["desc"].strip()) 59 | #else: 60 | #print "# Oh no, duplicate copies of: "+str(i["desc"]) 61 | 62 | # Fix some minor annoyances 63 | # I hate commas in quotes in a comma delimited file... I like cut... OK? 64 | i["desc"] = i["desc"].replace(",", " ") 65 | 66 | # XXX Need to get rid of extra spaces 67 | # XXX Cleanup database if field found that is just spaces 68 | 69 | # Reprint, hopefully with nicely equally spaced and comma'd and whatever fields 70 | print "{\"id\": "+str(i["id"])+", \"desc\": \""+i["desc"].strip()+"\", ", 71 | print "\"record_tls_version\": \""+i["record_tls_version"].strip()+"\", \"tls_version\": \""+i["tls_version"].strip()+"\", ", 72 | print "\"ciphersuite_length\": \""+i["ciphersuite_length"].strip()+"\", ", 73 | print "\"ciphersuite\": \""+i["ciphersuite"].strip()+"\", ", 74 | print "\"compression_length\": \""+i["compression_length"].strip()+"\", ", 75 | print "\"compression\": \""+i["compression"].strip()+"\", ", 76 | print "\"extensions\": \""+i["extensions"].strip()+"\"", 77 | if "e_curves" in i: 78 | if len(i["e_curves"].strip()) > 0: 79 | print ", \"e_curves\": \""+i["e_curves"].strip()+"\"", 80 | if "sig_alg" in i: 81 | if len(i["sig_alg"].strip()) > 0: 82 | print ", \"sig_alg\": \""+i["sig_alg"].strip()+"\"", 83 | if "ec_point_fmt" in i: 84 | if len(i["ec_point_fmt"].strip()) > 0: 85 | print ", \"ec_point_fmt\": \""+i["ec_point_fmt"].strip()+"\"", 86 | print "}" 87 | 88 | 89 | def ids(filename, initial=False): 90 | # Creating Snort signatures from the fingerprint data 91 | # Walk through each entry outputting the appropriate snort rule 92 | jfile = read_file(filename) 93 | sid = 1000000 94 | for i in jfile: 95 | 96 | # Reformat some of the values prior to printing out rules 97 | # Different format in the JSON to how suricata/snort want it 98 | # Mostly just removing 0x and changing how bytes are grouped 99 | i["desc"] = i["desc"].replace(";", ":") 100 | i["record_tls_version"] = re.sub(r'0x([0-9A-Fa-f]{2,2})([0-9A-Fa-f]{2,2})*', r'\1 \2', i["record_tls_version"]) 101 | i["tls_version"] = re.sub(r'0x([0-9A-Fa-f]{2,2})([0-9A-Fa-f]{2,2})*', r'\1 \2', i["tls_version"]) 102 | i["ciphersuite_length"] = re.sub(r'0x([0-9A-Fa-f]{2,2})([0-9A-Fa-f]{2,2})*', r'\1 \2', i["ciphersuite_length"]) 103 | i["ciphersuite"] = re.sub(r'0x([0-9A-Fa-f]{2,2})([0-9A-Fa-f]{2,2})*', r'\1 \2', i["ciphersuite"]) 104 | i["compression_length"] = re.sub(r'0x([0-9A-Fa-f]{1,2})', r'\1', hex(int(i["compression_length"]))) 105 | i["compression_length"] = re.sub(r'^([0-9A-Fa-f])$', r'0\1', i["compression_length"]) 106 | i["compression"] = re.sub(r'0x([0-9A-Fa-f]{2,2})*', r'\1', i["compression"]) 107 | if "e_curves" in i: 108 | i["e_curves"] = re.sub(r'0x([0-9A-Fa-f]{2,2})([0-9A-Fa-f]{2,2})*', r'\1 \2', i["e_curves"]) 109 | if "sig_alg" in i: 110 | i["sig_alg"] = re.sub(r'0x([0-9A-Fa-f]{2,2})([0-9A-Fa-f]{2,2})*', r'\1 \2', i["sig_alg"]) 111 | if "ec_point_fmt" in i: 112 | i["ec_point_fmt"] = re.sub(r'0x([0-9A-Fa-f]{2,2})*', r'\1', i["ec_point_fmt"]) 113 | 114 | 115 | # Print out the rules 116 | print "alert tcp any any -> any any (", 117 | print "msg:\""+i["desc"]+"\"; ", 118 | # Checks for "handshake" and "record TLS Version" 119 | print "content: \"|16 "+i["record_tls_version"]+"|\"; offset: 0; depth: 3; rawbytes; ", 120 | # Checks this is a client hello packet 121 | print "content: \"|01|\"; distance: 1; rawbytes; ", 122 | # Checks TLS Version (not record, the real one) 123 | print "content: \"|"+i["tls_version"]+"|\"; distance: 3; rawbytes; ", 124 | # Depending on which output was selected use a 0 sessionid length and offset (as there is none) 125 | if initial: 126 | print "content: \"|00|\"; offset: 42; rawbytes; ", 127 | # Otherwise use byte_jump to jump the offset of the session_id to get to the ciphersuite section 128 | else: 129 | print "byte_jump: 1,43,align; ", 130 | # Lined back up now no matter which option was chosen 131 | print "content: \"|"+i["ciphersuite_length"]+"|\"; distance: 0; rawbytes; ", 132 | # CipherSuites 133 | print "content: \"|"+i["ciphersuite"]+"|\"; distance: 0; rawbytes; ", 134 | # Compression length and compression types concat'd 135 | print "content: \"|"+i["compression_length"]+" "+i["compression"]+"|\"; distance: 0; rawbytes; ", 136 | 137 | ### Now we get to looping through the extensions and dealing with a few special cases where we are 138 | ### looking at extension content, not just presence and order. 139 | 140 | first_ext = 0 141 | # This feels like a fudge, but YOLO, it's forget finesse friday \o/ XXX 142 | special_ext = 0 143 | if len(i["extensions"]) > 0: 144 | for x in i["extensions"].split(" "): 145 | # Reformat this extension to something snort-useful 146 | x = re.sub(r'0x([0-9A-Fa-f]{2,2})([0-9A-Fa-f]{2,2})*', r'\1 \2', x) 147 | if first_ext == 0: 148 | # First extension requires a "distance: 2;" to jump it past the "extensions length" field 149 | print "content: \"|"+x+"|\"; rawbytes; distance: 2; ", 150 | first_ext += 1 151 | else: 152 | if special_ext == 0: 153 | print "byte_jump: 2,0,relative; ", 154 | else: 155 | special_ext = 0 156 | print "content: \"|"+x+"|\"; rawbytes; distance: 0; ", 157 | 158 | # Deal with the "special" extensions 159 | # XXX Should update this to include frontloading the lengths.... next 160 | # e_curves 161 | if x == "00 0A": 162 | special_ext = 1 163 | ext_len = re.sub(r'0x([0-9A-Fa-f]{1,2})', r'\1', hex((len(i["e_curves"])+1)/3)) 164 | ext_len = re.sub(r'^([0-9A-Fa-f])$', r'0\1 ', ext_len) 165 | print "content: \"|"+ext_len+i["e_curves"]+"|\"; rawbytes; distance: 0; ", 166 | # sig_alg 167 | elif x == "00 0D": 168 | special_ext = 1 169 | ext_len = re.sub(r'0x([0-9A-Fa-f]{1,2})', r'\1', hex((len(i["sig_alg"])+1)/3)) 170 | ext_len = re.sub(r'^([0-9A-Fa-f])$', r'0\1 ', ext_len) 171 | print "content: \"|"+ext_len+i["sig_alg"]+"|\"; rawbytes; distance: 0; ", 172 | # ec_point_fmt 173 | elif x == "00 0B": 174 | special_ext = 1 175 | ext_len = re.sub(r'0x([0-9A-Fa-f]{1,2})', r'\1', hex((len(i["ec_point_fmt"])+1)/3)) 176 | ext_len = re.sub(r'^([0-9A-Fa-f])$', r'0\1 ', ext_len) 177 | print "content: \"|"+ext_len+i["ec_point_fmt"]+"|\"; rawbytes; distance: 0; ", 178 | 179 | 180 | print "sid:"+str(sid)+"; rev:1;)" 181 | sid += 1 182 | print "\n" 183 | 184 | 185 | def xkeyscore(filename): 186 | # This is my joke _joke_... ok? JOKE! xkeyscore (i.e. regex) exporter 187 | # offsets are poop in regex, don't actually use! 188 | 189 | # Oh python with your spaces!!!! 190 | jfile = read_file(filename) 191 | output = '' 192 | for i in jfile: 193 | 194 | # Reformat some of the values prior to printing out rules 195 | i["record_tls_version"] = re.sub(r'0x([0-9A-Fa-f]{2,2})([0-9A-Fa-f]{2,2})*', r'\\x\1\\x\2', i["record_tls_version"]) 196 | i["tls_version"] = re.sub(r'0x([0-9A-Fa-f]{2,2})([0-9A-Fa-f]{2,2})*', r'\\x\1\\x\2', i["tls_version"]) 197 | i["ciphersuite_length"] = re.sub(r'0x([0-9A-Fa-f]{2,2})([0-9A-Fa-f]{2,2})*', r'\\x\1\\x\2', i["ciphersuite_length"]) 198 | i["ciphersuite"] = re.sub(r'0x([0-9A-Fa-f]{2,2})([0-9A-Fa-f]{2,2})*', r'\\x\1\\x\2', i["ciphersuite"]) 199 | i["compression_length"] = re.sub(r'0x([0-9A-Fa-f]{1,2})', r'\\x\1', hex(int(i["compression_length"]))) 200 | i["compression_length"] = re.sub(r'^([0-9A-Fa-f])$', r'\\x\1', i["compression_length"]) 201 | i["compression"] = re.sub(r'0x([0-9A-Fa-f]{2,2})*', r'\\x\1', i["compression"]) 202 | if "e_curves" in i: 203 | i["e_curves"] = re.sub(r'0x([0-9A-Fa-f]{2,2})([0-9A-Fa-f]{2,2})*', r'\\x\1\\x\2', i["e_curves"]) 204 | if "sig_alg" in i: 205 | i["sig_alg"] = re.sub(r'0x([0-9A-Fa-f]{2,2})([0-9A-Fa-f]{2,2})*', r'\\x\1\\x\2', i["sig_alg"]) 206 | if "ec_point_fmt" in i: 207 | i["ec_point_fmt"] = re.sub(r'0x([0-9A-Fa-f]{2,2})*', r'\\x\1', i["ec_point_fmt"]) 208 | 209 | 210 | # Print out the rules 211 | print "# Rule for \""+i["desc"]+"\"" 212 | output = "\"\\x16"+i["record_tls_version"] 213 | output = output+".*\\x01.*"+i["tls_version"] 214 | output = output+".*"+i["ciphersuite_length"]+i["ciphersuite"] 215 | output = output+".*"+i["compression"] 216 | 217 | ### Now we get to looping through the extensions and dealing with a few special cases where we are 218 | ### looking at extension content, not just presence and order. 219 | first_ext = 0 220 | # This feels like a fudge, but YOLO, it's forget finesse friday \o/ XXX 221 | special_ext = 0 222 | if len(i["extensions"]) > 0: 223 | for x in i["extensions"].split(" "): 224 | # Reformat this extension to something regex-useful 225 | x = re.sub(r'0x([0-9A-Fa-f]{2,2})([0-9A-Fa-f]{2,2})*', r'\\x\1\\x\2', x) 226 | if first_ext == 0: 227 | # First extension requires a "distance: 2;" to jump it past the "extensions length" field 228 | output += x 229 | first_ext += 1 230 | else: 231 | if special_ext != 0: 232 | special_ext = 0 233 | output += x 234 | 235 | # Deal with the "special" extensions 236 | # XXX Should update this to include frontloading the lengths.... next 237 | # e_curves 238 | if x == "\\x00\\x0A": 239 | special_ext = 1 240 | ext_len = re.sub(r'0x([0-9A-Fa-f]{1,2})', r'\\x\1', hex((len(i["e_curves"])+1)/3)) 241 | ext_len = re.sub(r'^\\x([0-9A-Fa-f])$', r'0\1', ext_len) 242 | output = output+ext_len+i["e_curves"]+".*" 243 | # sig_alg 244 | elif x == "\\x00\\x0D": 245 | special_ext = 1 246 | ext_len = re.sub(r'0x([0-9A-Fa-f]{1,2})', r'\\x\1', hex((len(i["sig_alg"])+1)/3)) 247 | ext_len = re.sub(r'^\\x([0-9A-Fa-f])$', r'0\1', ext_len) 248 | output = output+ext_len+i["sig_alg"]+".*" 249 | # ec_point_fmt 250 | elif x == "\\x00\\x0B": 251 | special_ext = 1 252 | ext_len = re.sub(r'0x([0-9A-Fa-f]{1,2})', r'\\x\1', hex((len(i["ec_point_fmt"])+1)/3)) 253 | ext_len = re.sub(r'^\\x([0-9A-Fa-f])$', r'0\1', ext_len) 254 | output = output+ext_len+i["ec_point_fmt"]+".*" 255 | 256 | 257 | output += "\"" 258 | output = re.sub(' ', '', output) 259 | print output+"\n" 260 | 261 | 262 | def struct(filename): 263 | # Build struct array for use in peoples C 264 | # Not sorted or indexed or anything for speed, just a dump into an array... YOLO! 265 | 266 | # Work out longest length for string fields... awwwww yeah.. static struct joy 267 | desc_len = tls_version_len = ciphersuite_len = compression_len = 0 268 | extensions_len = e_curves_len = sig_alg_len = ec_point_fmt_len = server_name_len = 0 269 | record_tls_version_len = 0 270 | jfile = read_file(filename) 271 | objcount = len(jfile) 272 | 273 | for i in jfile: 274 | # This isn't very neat or nice, buuuuuuut it's not super time critical either so it stays for now. 275 | # Neatening this little mess up though is on the todo list 276 | i["ciphersuite"] = re.sub(r'0x([0-9A-Fa-f]{2,2})([0-9A-Fa-f]{2,2})*', r'0x\1,0x\2,', i["ciphersuite"]) 277 | i["ciphersuite"] = re.sub(r'.$', r'', i["ciphersuite"]) 278 | i["ciphersuite"] = re.sub(r' ', r'', i["ciphersuite"]) 279 | i["extensions"] = re.sub(r'0x([0-9A-Fa-f]{2,2})([0-9A-Fa-f]{2,2})*', r'0x\1,0x\2,', i["extensions"]) 280 | i["extensions"] = re.sub(r'.$', r'', i["extensions"]) 281 | i["extensions"] = re.sub(r' ', r'', i["extensions"]) 282 | if "compression" in i: 283 | i["compression"] = re.sub(r'0x([0-9A-Fa-f]{2,2})*', r'0x\1,', i["compression"]) 284 | i["compression"] = re.sub(r'.$', r'', i["compression"]) 285 | i["compression"] = re.sub(r' ', r'', i["compression"]) 286 | if "e_curves" in i: 287 | i["e_curves"] = re.sub(r'0x([0-9A-Fa-f]{2,2})([0-9A-Fa-f]{2,2})*', r'0x\1,0x\2,', i["e_curves"]) 288 | i["e_curves"] = re.sub(r'.$', r'', i["e_curves"]) 289 | i["e_curves"] = re.sub(r' ', r'', i["e_curves"]) 290 | # XXX Need more of this checking, didn't realise how badly python would barf 291 | if "sig_alg" in i: 292 | i["sig_alg"] = re.sub(r'0x([0-9A-Fa-f]{2,2})([0-9A-Fa-f]{2,2})*', r'0x\1,0x\2,', i["sig_alg"]) 293 | i["sig_alg"] = re.sub(r'.$', r'', i["sig_alg"]) 294 | i["sig_alg"] = re.sub(r' ', r'', i["sig_alg"]) 295 | 296 | if "ec_point_fmt" in i: 297 | i["ec_point_fmt"] = re.sub(r'0x([0-9A-Fa-f]{2,2})*', r'0x\1,', i["ec_point_fmt"]) 298 | i["ec_point_fmt"] = re.sub(r'.$', r'', i["ec_point_fmt"]) 299 | i["ec_point_fmt"] = re.sub(r' ', r'', i["ec_point_fmt"]) 300 | 301 | 302 | if desc_len < len(i["desc"]): 303 | desc_len = len(i["desc"]) + 1 304 | if record_tls_version_len < len(i["record_tls_version"]): 305 | record_tls_version_len = len(i["record_tls_version"]) + 1 306 | if tls_version_len < len(i["tls_version"]): 307 | tls_version_len = len(i["tls_version"]) + 1 308 | if ciphersuite_len < ((len(i["ciphersuite"])/7) * 2): 309 | ciphersuite_len = ((len(i["ciphersuite"])/7) * 2) 310 | if compression_len < len(i["compression"]): 311 | compression_len = len(i["compression"]) + 1 312 | if extensions_len < len(i["extensions"]): 313 | extensions_len = len(i["extensions"]) + 1 314 | if "e_curves" in i: 315 | if e_curves_len < len(i["e_curves"]): 316 | e_curves_len = len(i["e_curves"]) + 1 317 | if "sig_alg" in i: 318 | if sig_alg_len < len(i["sig_alg"]): 319 | sig_alg_len = len(i["sig_alg"]) + 1 320 | if "ec_point_fmt" in i: 321 | if ec_point_fmt_len < len(i["ec_point_fmt"]): 322 | ec_point_fmt_len = len(i["ec_point_fmt"]) + 1 323 | # if server_name_len < len(i["server_name"]): 324 | # server_name_len = len(i["server_name"]) + 1 325 | 326 | # Print the struct layout so this can be one .c or something 327 | # Need to set more accurate size than "int" for the sizes 328 | print "struct fingerprint {" 329 | print "\tint id;" 330 | print "\tu_char desc["+str(desc_len)+"];" 331 | print "\tuint16_t record_tls_version;" 332 | print "\tuint16_t tls_version;" 333 | print "\tint ciphersuite_length;" 334 | print "\tuint8_t ciphersuite["+str(ciphersuite_len)+"];" 335 | print "\tint compression_length;" 336 | print "\tuint8_t compression["+str(compression_len)+"];" 337 | print "\tint extensions_length;" 338 | print "\tuint8_t extensions["+str(extensions_len)+"];" 339 | print "\tint e_curves_length;" 340 | print "\tuint8_t e_curves["+str(e_curves_len)+"];" 341 | print "\tint sig_alg_length;" 342 | print "\tuint8_t sig_alg["+str(sig_alg_len)+"];" 343 | print "\tint ec_point_fmt_length;" 344 | print "\tuint8_t ec_point_fmt["+str(ec_point_fmt_len)+"];" 345 | print "} fpdb["+str(objcount)+"] = {" 346 | 347 | # Pre-populate a bunch of C structs for people to use in their own Code 348 | # note: not ordered, indexed or in pretty trees; just at static struct array 349 | # enjoi the blazing performance ;) 350 | fp_count = 0 351 | for i in jfile: 352 | print "\t{"+str(i["id"])+", \""+i["desc"]+"\", "+i["record_tls_version"]+", "+i["tls_version"]+", ", 353 | print re.sub(r'0x([0-9A-Fa-f]{2,2})([0-9A-Fa-f]{2,2})$', r'0x\1\2', i["ciphersuite_length"])+", ", 354 | print "{"+i["ciphersuite"]+"}, "+str(i["compression_length"])+", {"+i["compression"]+"}, ", 355 | print str(i["extensions"].count('x'))+",", 356 | print "{"+i["extensions"]+"}", 357 | 358 | if "e_curves" in i: 359 | print ", "+str(i["e_curves"].count('x')), 360 | print ", {"+i["e_curves"]+"}", 361 | else: 362 | print ",0 , {}", 363 | if "sig_alg" in i: 364 | print ", "+str(i["sig_alg"].count('x')), 365 | print ", {"+i["sig_alg"]+"}", 366 | else: 367 | print ",0 , {}", 368 | if "ec_point_fmt" in i: 369 | print ", "+str(i["ec_point_fmt"].count('x')), 370 | print ", {"+i["ec_point_fmt"]+"}", 371 | else: 372 | print ",0 , {}", 373 | 374 | fp_count += 1 375 | 376 | if fp_count < objcount: 377 | print "}," 378 | else: 379 | print "}" 380 | 381 | 382 | print "\t};" 383 | 384 | def binary(filename): 385 | 386 | # XXX accounted for 0x00 where 0x0000 is needed, have not looked at 0x0 yet... check this!! 387 | 388 | # XXX Check the mutt signature with the oddly formed compression len to compression thing 389 | 390 | # Build a binary "database", which is actually a pre-compiled'ish struct linked list for use in peoples code 391 | # Much like the "struct" option but allows more room for indexing/searching and growing as there is no need 392 | # to parse strings from some flatfile which C is soooooo good at. Yes yes, this is still file parsing.... 393 | # but (from a C perspective) it's easier file parsing, and this isn't so hard in python to output either. 394 | 395 | # Documenting the file format here, in lieu of proper documentation 396 | 397 | # Byte 0 : binary format version 398 | # Per fingerprint..... 399 | # uint16_t : Fingerprint ID 400 | # uint16_t : Desc Length 401 | # Bytes : Desc 402 | # uint16_t : record_tls_version; 403 | # uint16_t : tls_version; 404 | # etc etc etc 405 | # uint16_t ciphersuite_length 406 | # uint8_t ciphersuite.... 407 | # uint8_t compression_length 408 | # uint8_t compression.... 409 | # uint16_t extensions_length 410 | # uint8_t extensions.... 411 | # uint16_t e_curves_length 412 | # uint8_t e_curves..... 413 | # uint16_t sig_alg_length 414 | # uint8_t sig_alg..... 415 | # uint16_t ec_point_fmt_length 416 | # uint8_t ec_point_fmt.... 417 | 418 | 419 | # Write the version before we itterate through the fingerprints 420 | outfile = open("tlsfp.db","w+") 421 | outfile.write(byte_to_bin("0x00")) 422 | 423 | # Open the JSON file and process each entry (line) 424 | jfile = read_file(filename) 425 | objcount = len(jfile) 426 | 427 | for i in jfile: 428 | # Need to add the ID once this is working XXX 429 | print "Processing: "+i["desc"] 430 | # Initialise all the lengths to stop things complaining later. Oh and other random 431 | # weirdness. 432 | desc_len = tls_version_len = ciphersuite_len = compression_len = 0 433 | extensions_len = e_curves_len = sig_alg_len = ec_point_fmt_len = server_name_len = 0 434 | record_tls_version_len = 0 435 | 436 | # Start correctly encoding things and writing them to outfile 437 | temp_data = format(i["id"], '#06x') 438 | outfile.write(byte_to_bin(temp_data)) 439 | 440 | temp_data = len(i["desc"]) 441 | temp_data = format(temp_data, '#06x') 442 | outfile.write(byte_to_bin(temp_data)) 443 | 444 | outfile.write(i["desc"]) 445 | outfile.write(byte_to_bin(i["record_tls_version"])) 446 | outfile.write(byte_to_bin(i["tls_version"])) 447 | outfile.write(byte_to_bin(i["ciphersuite_length"])) 448 | outfile.write(byte_to_bin(i["ciphersuite"])) 449 | 450 | # Compression Length is stored as decimal for some reason (go team) 451 | # But it's only a one byte value... ccccoooonnnnvvveeeerrrrttttt 452 | temp_data = len(byte_to_bin(i["compression"].zfill(2))) 453 | temp_data = format(temp_data, '#04x') 454 | outfile.write(byte_to_bin(temp_data)) 455 | 456 | # OK, carry on as we were... 457 | outfile.write(byte_to_bin(i["compression"])) 458 | 459 | # We need to calculate extensions_length, because it's not in the JSON file 460 | # so switcharoo, encode extensions first, then length it, then write... *BOOM* 461 | temp_data = len(byte_to_bin(i["extensions"])) 462 | temp_data = format(temp_data, '#06x') 463 | outfile.write(byte_to_bin(temp_data)) 464 | outfile.write(byte_to_bin(i["extensions"])) 465 | 466 | # And again for the optionals 467 | if "e_curves" in i: 468 | temp_data = len(byte_to_bin(i["e_curves"])) 469 | temp_data = format(temp_data, '#06x') 470 | outfile.write(byte_to_bin(temp_data)) 471 | outfile.write(byte_to_bin(i["e_curves"])) 472 | else: 473 | # Still need to set zero length 474 | outfile.write(byte_to_bin("0x0000")) 475 | 476 | if "sig_alg" in i: 477 | temp_data = len(byte_to_bin(i["sig_alg"])) 478 | temp_data = format(temp_data, '#06x') 479 | outfile.write(byte_to_bin(temp_data)) 480 | outfile.write(byte_to_bin(i["sig_alg"])) 481 | else: 482 | # Still need to set zero length 483 | outfile.write(byte_to_bin("0x0000")) 484 | 485 | if "ec_point_fmt" in i: 486 | temp_data = len(byte_to_bin(i["ec_point_fmt"])) 487 | temp_data = format(temp_data, '#06x') 488 | outfile.write(byte_to_bin(temp_data)) 489 | outfile.write(byte_to_bin(i["ec_point_fmt"])) 490 | else: 491 | # Still need to set zero length 492 | outfile.write(byte_to_bin("0x0000")) 493 | 494 | # Close the file before the script terminates 495 | outfile.close() 496 | 497 | 498 | if __name__ == '__main__': 499 | parser = argparse.ArgumentParser() 500 | 501 | action_group = parser.add_mutually_exclusive_group(required=True) 502 | action_group.add_argument("-c", "--cleanse", action="store_true", 503 | help="Re-output as JSON with some format un-breaking (beta)") 504 | action_group.add_argument("-s", "--struct", action="store_true", 505 | help="Output C Structure") 506 | action_group.add_argument("-b", "--binary", action="store_true", 507 | help="Output binary fingerprint DB") 508 | action_group.add_argument("-i", "--ids", action="store_true", 509 | help="Output Suricata/Snort Signatures") 510 | action_group.add_argument("-I", "--idsinit", action="store_true", 511 | help="Output Suricata/Snort Signatures matching only initial handshake (sessionid 0)") 512 | action_group.add_argument("-x", "--xkeyscore", action="store_true", 513 | help="OK, it's regex, and not that great, probably best not to use this!") 514 | 515 | parser.add_argument('filename', nargs='?', help="Specify the fingerprint file to use") 516 | parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), default=sys.stdout, 517 | help="You may optionally supply an output file, otherwise output to stdout") 518 | 519 | args = parser.parse_args() 520 | 521 | sys.stdout = args.outfile 522 | 523 | if args.cleanse: 524 | cleanse(args.filename) 525 | elif args.struct: 526 | struct(args.filename) 527 | elif args.binary: 528 | binary(args.filename) 529 | elif args.ids: 530 | ids(args.filename) 531 | elif args.idsinit: 532 | ids(args.filename, initial=True) 533 | elif args.xkeyscore: 534 | xkeyscore(args.filename) 535 | else: 536 | parser.print_usage() 537 | -------------------------------------------------------------------------------- /scripts/parselog.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2 2 | 3 | import time, os, json, sys 4 | 5 | inputfile = sys.argv[1] 6 | print "Tailing: "+inputfile 7 | # Set the filename and open the file 8 | filename = inputfile 9 | file = open(filename,'r') 10 | 11 | #Find the size of the file and move to the end 12 | st_results = os.stat(filename) 13 | st_size = st_results[6] 14 | file.seek(st_size) 15 | 16 | while 1: 17 | where = file.tell() 18 | line = file.readline() 19 | if not line: 20 | time.sleep(0.1) 21 | file.seek(where) 22 | else: 23 | jline = json.loads(line) 24 | 25 | # Actually outputting things here.... 26 | if(jline["event"] == 'fingerprint_match'): 27 | print jline["timestamp"]+" \"\033[1;36m"+jline["fingerprint_desc"]+"\033[1;m\" "+jline["tls_version"]+" connection to \""\ 28 | +"\033[1;33m"+jline["server_name"]+"\033[1;m\" ", 29 | 30 | if(jline["ip_version"] == "ipv4"): 31 | print jline["ipv4_src"]+":"+str(jline["src_port"])+" -> "+jline["ipv4_dst"]+" "+str(jline["dst_port"])+" ", 32 | print "(ipv4)" 33 | if(jline["ip_version"] == "ipv6"): 34 | print jline["ipv6_src"]+" "+str(jline["src_port"])+" -> "+jline["ipv6_dst"]+" "+str(jline["dst_port"])+" ", 35 | print "(ipv6)" 36 | if(jline["ip_version"] == "6in4"): 37 | print jline["ipv4_src"]+"("+jline["ipv6_src"]+" "+str(jline["src_port"])+") -> "+jline["ipv4_dst"]+"("+jline["ipv6_dst"]+" "+str(jline["dst_port"])+") ", 38 | print "(6in4)" 39 | if(jline["ip_version"] == "teredo"): 40 | print jline["ipv4_src"]+"("+jline["ipv6_src"]+" "+str(jline["src_port"])+") -> "+jline["ipv4_dst"]+"("+jline["ipv6_dst"]+" "+str(jline["dst_port"])+") ", 41 | print "(teredo)" 42 | 43 | 44 | 45 | 46 | 47 | #print '\033[1;30mGray like Ghost\033[1;m' 48 | #print '\033[1;31mRed like Radish\033[1;m' 49 | #print '\033[1;32mGreen like Grass\033[1;m' 50 | #print '\033[1;33mYellow like Yolk\033[1;m' 51 | #print '\033[1;34mBlue like Blood\033[1;m' 52 | #print '\033[1;35mMagenta like Mimosa\033[1;m' 53 | #print '\033[1;36mCyan like Caribbean\033[1;m' 54 | #print '\033[1;37mWhite like Whipped Cream\033[1;m' 55 | #print '\033[1;38mCrimson like Chianti\033[1;m' 56 | #print '\033[1;41mHighlighted Red like Radish\033[1;m' 57 | #print '\033[1;42mHighlighted Green like Grass\033[1;m' 58 | #print '\033[1;43mHighlighted Brown like Bear\033[1;m' 59 | #print '\033[1;44mHighlighted Blue like Blood\033[1;m' 60 | #print '\033[1;45mHighlighted Magenta like Mimosa\033[1;m' 61 | #print '\033[1;46mHighlighted Cyan like Caribbean\033[1;m' 62 | #print '\033[1;47mHighlighted Gray like Ghost\033[1;m' 63 | #print '\033[1;48mHighlighted Crimson like Chianti\033[1;m' 64 | --------------------------------------------------------------------------------