├── Database Scripts ├── create-database.py ├── insert-content.py └── select-content.py ├── LICENSE ├── Nmap Scripts ├── full-port-scan.py ├── host-discovery.py ├── os-detection.py ├── service-scan.py ├── ssl-certs.py ├── ssl-ciphers.py └── top-port-scan.py ├── README.md ├── Report Scripts ├── report-3des-ciphers.py ├── report-all-ciphers.py ├── report-anon-ciphers.py ├── report-cipher-risk-grades.py ├── report-des-idea-ciphers.py ├── report-export-ciphers.py ├── report-hosts-with-ports.py ├── report-hosts-without-ports.py ├── report-hosts.py ├── report-null-ciphers.py ├── report-operating-system.py ├── report-rc4-ciphers.py ├── report-ssl-certs.py ├── report-static-key-ciphers.py ├── report-sweet32-vuln-ciphers.py └── report-tls-protocols.py ├── Screenshots ├── create-database.png ├── insert-content.png ├── nmap-service-probes-2.png ├── nmap-service-probes.png ├── parse-accessible-ports.png ├── parse-live-hosts.png ├── select-content.png ├── shlex-vs-split.png ├── subprocess-stdout-stderr.png ├── timeline_ad-hoc.png └── xml-parse-sample.png └── XML Parser Scripts ├── README.md ├── parse-accesible-ports.py ├── parse-accessible-ports.py ├── parse-in-memory.py └── parse-live-hosts.py /Database Scripts/create-database.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import sqlite3 4 | 5 | def create_connection(db_file): 6 | conn = None 7 | try: 8 | conn = sqlite3.connect(db_file) 9 | except Exception as e: 10 | print(e) 11 | return conn 12 | 13 | 14 | def create_db(conn): 15 | createHostDiscoveryTable="""CREATE TABLE IF NOT EXISTS HostDiscovery ( 16 | id integer PRIMARY KEY, 17 | IP text NOT NULL, 18 | Status text NOT NULL, 19 | ICMP_Echo text NOT NULL);""" 20 | try: 21 | c = conn.cursor() 22 | c.execute(createHostDiscoveryTable) 23 | except Exception as e: 24 | print(e) 25 | 26 | 27 | def main(): 28 | db_file = 'PythonizingNmap.db' 29 | conn = create_connection(db_file) 30 | create_db(conn) 31 | 32 | 33 | if __name__ == '__main__': 34 | main() -------------------------------------------------------------------------------- /Database Scripts/insert-content.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import sqlite3 4 | import xml.etree.ElementTree as ET 5 | 6 | 7 | def create_connection(db_file): 8 | conn = None 9 | try: 10 | conn = sqlite3.connect(db_file) 11 | except Exception as e: 12 | print(e) 13 | return conn 14 | 15 | 16 | def insert_content(conn, content): 17 | sql = ''' INSERT INTO HostDiscovery(IP,Status,ICMP_Echo) 18 | VALUES(?,?,?) ''' 19 | cur = conn.cursor() 20 | cur.execute(sql, content) 21 | return cur.lastrowid 22 | 23 | 24 | def main(): 25 | # Database Connection 26 | db_file = 'PythonizingNmap.db' 27 | conn = create_connection(db_file) 28 | 29 | # Parse XML 30 | in_xml_echo = '/home/tristram/Scans/Stage_1/icmp_echo_host_discovery.xml' 31 | 32 | # Load ICMP Echo XML 33 | xml_tree_echo = ET.parse(in_xml_echo) 34 | xml_root_echo = xml_tree_echo.getroot() 35 | 36 | # Load ICMP Echo XML 37 | for host in xml_root_echo.findall('host'): 38 | echo_ip = host.find('address').get('addr') 39 | echo_state = host.find('status').get('state') 40 | echo_reason = host.find('status').get('reason') 41 | 42 | # Insert results into database 43 | insert_content(conn, (echo_ip, echo_state, echo_reason)) 44 | conn.commit() 45 | 46 | 47 | if __name__ == '__main__': 48 | main() -------------------------------------------------------------------------------- /Database Scripts/select-content.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import sqlite3 4 | 5 | def create_connection(db_file): 6 | conn = None 7 | try: 8 | conn = sqlite3.connect(db_file) 9 | except Exception as e: 10 | print(e) 11 | return conn 12 | 13 | 14 | def select_content(conn): 15 | sql = """SELECT IP 16 | FROM HostDiscovery 17 | WHERE Status = 'up' 18 | """ 19 | cur = conn.cursor() 20 | cur.execute(sql) 21 | rows = cur.fetchall() 22 | return rows 23 | 24 | 25 | def main(): 26 | db_file = 'PythonizingNmap.db' 27 | conn = create_connection(db_file) 28 | live_hosts = select_content(conn) 29 | for host in live_hosts: 30 | print(f'Live: {host[0]}') 31 | 32 | 33 | if __name__ == '__main__': 34 | main() -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Nmap Scripts/full-port-scan.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import subprocess 5 | import shlex 6 | import os 7 | import sys 8 | 9 | 10 | def parseDiscoverXml(in_xml): 11 | live_hosts = [] 12 | xml_tree = ET.parse(in_xml) 13 | xml_root = xml_tree.getroot() 14 | for host in xml_root.findall('host'): 15 | ip_state = host.find('status').get('state') 16 | if ip_state == "up": 17 | live_hosts.append(host.find('address').get('addr')) 18 | return live_hosts 19 | 20 | 21 | def convertToNmapTarget(hosts): 22 | hosts = list(dict.fromkeys(hosts)) 23 | return " ".join(hosts) 24 | 25 | 26 | def tcpSynPortScan(target, out_xml,): 27 | out_xml = os.path.join(out_xml,'65535_portscan.xml') 28 | nmap_cmd = f"/usr/bin/nmap {target} -p- -n -Pn -sS -T4 --min-parallelism 100 --min-rate 128 -vv -oX {out_xml}" 29 | sub_args = shlex.split(nmap_cmd) 30 | subprocess.Popen(sub_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 31 | makeInvokerOwner(out_xml) 32 | 33 | 34 | def makeInvokerOwner(path): 35 | uid = os.environ.get('SUDO_UID') 36 | gid = os.environ.get('SUDO_GID') 37 | if uid is not None: 38 | os.chown(path, int(uid), int(gid)) 39 | 40 | 41 | def is_root(): 42 | if os.geteuid() == 0: 43 | return True 44 | else: 45 | return False 46 | 47 | 48 | def main(): 49 | if not is_root(): 50 | print('[!] TCP/SYN scans requires root privileges') 51 | sys.exit(1) 52 | 53 | hosts = parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_echo_host_discovery.xml') 54 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_netmask_host_discovery.xml') 55 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_timestamp_host_discovery.xml') 56 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/port_host_discovery.xml') 57 | 58 | target = convertToNmapTarget(hosts) 59 | tcpSynPortScan(target, os.getcwd()) 60 | 61 | if __name__ == '__main__': 62 | main() -------------------------------------------------------------------------------- /Nmap Scripts/host-discovery.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import shlex 4 | import subprocess 5 | import os 6 | import sys 7 | 8 | 9 | def sendIcmpEcho(target, out_xml): 10 | out_xml = os.path.join(out_xml,'icmp_echo_host_discovery.xml') 11 | nmap_cmd = f"/usr/bin/nmap {target} -n -sn -PE -vv -oX {out_xml}" 12 | sub_args = shlex.split(nmap_cmd) 13 | subprocess.Popen(sub_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 14 | makeInvokerOwner(out_xml) 15 | 16 | 17 | def sendIcmpNetmask(target, out_xml): 18 | out_xml = os.path.join(out_xml,'icmp_netmask_host_discovery.xml') 19 | nmap_cmd = f"/usr/bin/nmap {target} -n -sn -PM -vv -oX {out_xml}" 20 | sub_args = shlex.split(nmap_cmd) 21 | subprocess.Popen(sub_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 22 | makeInvokerOwner(out_xml) 23 | 24 | 25 | def sendIcmpTimestamp(target, out_xml): 26 | out_xml = os.path.join(out_xml,'icmp_timestamp_host_discovery.xml') 27 | nmap_cmd = f"/usr/bin/nmap {target} -n -sn -PP -vv -oX {out_xml}" 28 | sub_args = shlex.split(nmap_cmd) 29 | subprocess.Popen(sub_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 30 | makeInvokerOwner(out_xml) 31 | 32 | 33 | def sendTcpSyn(target, out_xml): 34 | out_xml = os.path.join(out_xml,'tcp_syn_host_discovery.xml') 35 | nmap_cmd = f"/usr/bin/nmap {target} -PS21,22,23,25,80,113,443 -PA80,113,443 -n -sn -T4 -vv -oX {out_xml}" 36 | sub_args = shlex.split(nmap_cmd) 37 | subprocess.Popen(sub_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 38 | makeInvokerOwner(out_xml) 39 | 40 | 41 | def makeInvokerOwner(path): 42 | uid = os.environ.get('SUDO_UID') 43 | gid = os.environ.get('SUDO_GID') 44 | if uid is not None: 45 | os.chown(path, int(uid), int(gid)) 46 | 47 | 48 | def is_root(): 49 | if os.geteuid() == 0: 50 | return True 51 | else: 52 | return False 53 | 54 | 55 | def main(): 56 | if not is_root(): 57 | print('[!] The discovery probes in this script requires root privileges') 58 | sys.exit(1) 59 | 60 | target = '127.0.0.1' 61 | 62 | sendIcmpEcho(target, os.getcwd()) 63 | sendIcmpNetmask(target, os.getcwd()) 64 | sendIcmpTimestamp(target, os.getcwd()) 65 | sendTcpSyn(target, os.getcwd()) 66 | 67 | if __name__ == '__main__': 68 | main() -------------------------------------------------------------------------------- /Nmap Scripts/os-detection.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import subprocess 5 | import shlex 6 | import os 7 | import sys 8 | 9 | 10 | def parseDiscoverXml(in_xml): 11 | live_hosts = [] 12 | xml_tree = ET.parse(in_xml) 13 | xml_root = xml_tree.getroot() 14 | for host in xml_root.findall('host'): 15 | ip_state = host.find('status').get('state') 16 | if ip_state == "up": 17 | live_hosts.append(host.find('address').get('addr')) 18 | return live_hosts 19 | 20 | 21 | def convertToNmapTarget(hosts): 22 | hosts = list(dict.fromkeys(hosts)) 23 | return " ".join(hosts) 24 | 25 | 26 | def osScan(targets, out_xml): 27 | out_xml = os.path.join(out_xml,f'osdetection.xml') 28 | nmap_cmd = f"/usr/bin/nmap {targets} -n -Pn -O -T4 --min-parallelism 100 --min-rate 64 -vv -oX {out_xml}" 29 | sub_args = shlex.split(nmap_cmd) 30 | subprocess.Popen(sub_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 31 | makeInvokerOwner(out_xml) 32 | 33 | 34 | def makeInvokerOwner(path): 35 | uid = os.environ.get('SUDO_UID') 36 | gid = os.environ.get('SUDO_GID') 37 | if uid is not None: 38 | os.chown(path, int(uid), int(gid)) 39 | 40 | 41 | def is_root(): 42 | if os.geteuid() == 0: 43 | return True 44 | else: 45 | return False 46 | 47 | 48 | def main(): 49 | if not is_root(): 50 | print('[!] TCP/IP fingerprinting (for OS scan) requires root privileges.') 51 | sys.exit(1) 52 | 53 | hosts = parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_echo_host_discovery.xml') 54 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_netmask_host_discovery.xml') 55 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_timestamp_host_discovery.xml') 56 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/port_host_discovery.xml') 57 | 58 | target = convertToNmapTarget(hosts) 59 | 60 | osScan(target, os.getcwd()) 61 | 62 | 63 | if __name__ == '__main__': 64 | main() 65 | -------------------------------------------------------------------------------- /Nmap Scripts/service-scan.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import subprocess 5 | import shlex 6 | import os 7 | 8 | 9 | def parseDiscoverPorts(in_xml): 10 | results = [] 11 | port_list = '' 12 | xml_tree = ET.parse(in_xml) 13 | xml_root = xml_tree.getroot() 14 | for host in xml_root.findall('host'): 15 | ip = host.find('address').get('addr') 16 | ports = host.findall('ports')[0].findall('port') 17 | for port in ports: 18 | state = port.find('state').get('state') 19 | if state == 'open': 20 | port_list += port.get('portid') + ',' 21 | port_list = port_list.rstrip(',') 22 | if port_list: 23 | results.append(f"{ip} {port_list}") 24 | port_list = '' 25 | return results 26 | 27 | 28 | def serviceScan(target_ip, target_ports, out_xml): 29 | out_xml = os.path.join(out_xml,f'{target_ip}_services.xml') 30 | nmap_cmd = f"/usr/bin/nmap {target_ip} -p {target_ports} -n -Pn -sV --version-intensity 6 --script banner -T4 -vv -oX {out_xml}" 31 | sub_args = shlex.split(nmap_cmd) 32 | subprocess.Popen(sub_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 33 | 34 | 35 | def main(): 36 | in_xml = '/home/tristram/Scans/Stage_2/top_1000_portscan.xml' 37 | targets = parseDiscoverPorts(in_xml) 38 | for target in targets: 39 | element = target.split() 40 | target_ip = element[0] 41 | target_ports = element[1] 42 | print(f'Scanning: {target_ip} against ports {target_ports}') 43 | serviceScan(target_ip, target_ports, os.getcwd()) 44 | 45 | 46 | if __name__ == '__main__': 47 | main() 48 | -------------------------------------------------------------------------------- /Nmap Scripts/ssl-certs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import subprocess 5 | import shlex 6 | import os 7 | 8 | 9 | def parseDiscoverPorts(in_xml): 10 | results = [] 11 | port_list = '' 12 | xml_tree = ET.parse(in_xml) 13 | xml_root = xml_tree.getroot() 14 | for host in xml_root.findall('host'): 15 | ip = host.find('address').get('addr') 16 | ports = host.findall('ports')[0].findall('port') 17 | for port in ports: 18 | state = port.find('state').get('state') 19 | if state == 'open': 20 | port_list += port.get('portid') + ',' 21 | port_list = port_list.rstrip(',') 22 | if port_list: 23 | results.append(f"{ip} {port_list}") 24 | port_list = '' 25 | return results 26 | 27 | 28 | def sslCertScan(target_ip, target_ports, out_xml): 29 | out_xml = os.path.join(out_xml,f'{target_ip}_ssl_certs.xml') 30 | nmap_cmd = f"/usr/bin/nmap {target_ip} -p {target_ports} -n -Pn --script ssl-cert -T4 -vv -oX {out_xml}" 31 | sub_args = shlex.split(nmap_cmd) 32 | subprocess.Popen(sub_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 33 | 34 | 35 | def main(): 36 | in_xml = '/home/tristram/Scans/Stage_2/syn_port_scan.xml' 37 | targets = parseDiscoverPorts(in_xml) 38 | for target in targets: 39 | element = target.split() 40 | target_ip = element[0] 41 | target_ports = element[1] 42 | print(f'Scanning: {target_ip} against ports {target_ports}') 43 | sslCertScan(target_ip, target_ports, os.getcwd()) 44 | 45 | 46 | if __name__ == '__main__': 47 | main() 48 | -------------------------------------------------------------------------------- /Nmap Scripts/ssl-ciphers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import subprocess 5 | import shlex 6 | import os 7 | 8 | 9 | def parseDiscoverPorts(in_xml): 10 | results = [] 11 | port_list = '' 12 | xml_tree = ET.parse(in_xml) 13 | xml_root = xml_tree.getroot() 14 | for host in xml_root.findall('host'): 15 | ip = host.find('address').get('addr') 16 | ports = host.findall('ports')[0].findall('port') 17 | for port in ports: 18 | state = port.find('state').get('state') 19 | if state == 'open': 20 | port_list += port.get('portid') + ',' 21 | port_list = port_list.rstrip(',') 22 | if port_list: 23 | results.append(f"{ip} {port_list}") 24 | port_list = '' 25 | return results 26 | 27 | 28 | def sslCipherScan(target_ip, target_ports, out_xml): 29 | out_xml = os.path.join(out_xml,f'{target_ip}_ssl_ciphers.xml') 30 | nmap_cmd = f"/usr/bin/nmap {target_ip} -p {target_ports} -n -Pn --script ssl-enum-ciphers -T4 -vv -oX {out_xml}" 31 | sub_args = shlex.split(nmap_cmd) 32 | subprocess.Popen(sub_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 33 | 34 | 35 | def main(): 36 | in_xml = '/home/tristram/Scans/Stage_2/syn_port_scan.xml' 37 | targets = parseDiscoverPorts(in_xml) 38 | for target in targets: 39 | element = target.split() 40 | target_ip = element[0] 41 | target_ports = element[1] 42 | print(f'Scanning: {target_ip} against ports {target_ports}') 43 | sslCipherScan(target_ip, target_ports, os.getcwd()) 44 | 45 | 46 | if __name__ == '__main__': 47 | main() 48 | -------------------------------------------------------------------------------- /Nmap Scripts/top-port-scan.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import subprocess 5 | import shlex 6 | import os 7 | import sys 8 | 9 | 10 | def parseDiscoverXml(in_xml): 11 | live_hosts = [] 12 | xml_tree = ET.parse(in_xml) 13 | xml_root = xml_tree.getroot() 14 | for host in xml_root.findall('host'): 15 | ip_state = host.find('status').get('state') 16 | if ip_state == "up": 17 | live_hosts.append(host.find('address').get('addr')) 18 | return live_hosts 19 | 20 | 21 | def convertToNmapTarget(hosts): 22 | hosts = list(dict.fromkeys(hosts)) 23 | return " ".join(hosts) 24 | 25 | 26 | def tcpSynPortScan(target, out_xml,): 27 | out_xml = os.path.join(out_xml,'top_1000_portscan.xml') 28 | nmap_cmd = f"/usr/bin/nmap {target} --top-ports 1000 -n -Pn -sS -T4 --min-parallelism 100 --min-rate 64 -vv -oX {out_xml}" 29 | sub_args = shlex.split(nmap_cmd) 30 | subprocess.Popen(sub_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 31 | makeInvokerOwner(out_xml) 32 | 33 | 34 | def makeInvokerOwner(path): 35 | uid = os.environ.get('SUDO_UID') 36 | gid = os.environ.get('SUDO_GID') 37 | if uid is not None: 38 | os.chown(path, int(uid), int(gid)) 39 | 40 | 41 | def is_root(): 42 | if os.geteuid() == 0: 43 | return True 44 | else: 45 | return False 46 | 47 | 48 | def main(): 49 | if not is_root(): 50 | print('[!] TCP/SYN scans requires root privileges') 51 | sys.exit(1) 52 | 53 | hosts = parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_echo_host_discovery.xml') 54 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_netmask_host_discovery.xml') 55 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_timestamp_host_discovery.xml') 56 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/tcp_syn_host_discovery.xml') 57 | 58 | target = convertToNmapTarget(hosts) 59 | tcpSynPortScan(target, os.getcwd()) 60 | 61 | if __name__ == '__main__': 62 | main() -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Pythonizing Nmap 2 | When I started to get into this field, I tried my best to stick to manual workflows to get the lay of the land. As time passed by and I gained more experience the more I found that I needed to find better ways to be more efficient with my time. One place where I spent too much time was performing my initial enumeration with Nmap on larger scale assessments, staying organized as well as writing reports with the information I have collected. 3 | 4 | I believe that automation is crucial for some aspects of a penetration test and Python is a tool to help us facilitate this. Allow me to show you various ways you can enhance your workflows by incorporating Python into your Nmap processes. 5 | 6 | ## Boots on The Ground 7 | 8 | 1. Opening Remarks on Nmap Wrappers 9 | 2. Using Subprocess with Nmap 10 | 3. Parsing Nmap XML 11 | 4. Importing Nmap XML into SQLite Databases 12 | 5. Python Nmap Wrapper Scripts 13 | 6. Generating Reports from Nmap XML 14 | 7. Wrapping Up 15 | 16 | ## Opening Remarks on Nmap Wrappers 17 | 18 | Keep in mind that there is no one size fits all when it comes to Nmap scans. Before you run any sort of Nmap wrapper you should always look at the parameters that are in play and craft them to meet your needs and applicable scenarios. For your convenience here are the individual nmap commands I have incorporated in these scripts. 19 | 20 | I like to keep the structure of my nmap commands consistent in a TARGET PORT OMIT SCAN SPEED VERBOSITY OUTPUT format. 21 | 22 | | Stage | Nmap Command | Requires Root 23 | | -------------- | :--------- | :--------- | 24 | | Host Discovery - ICMP Echo | nmap TARGET -n -sn -PE -vv -oX OUTPUT | Yes 25 | | Host Discovery - ICMP Netmask | nmap TARGET -n -sn -PM -vv -oX OUTPUT | Yes 26 | | Host Discovery - ICMP Timestamp | nmap TARGET -n -sn -PP -vv -oX OUTPUT | Yes 27 | | Host Discovery - Port Scanning | nmap TARGET -PS21,22,23,25,80,113,443 -PA80,113,443 -n -sn -T4 -vv -oX OUTPUT | Yes 28 | | Port Scanning (Top 1000) | nmap TARGET --top-ports 1000 -n -Pn -sS -T4 --min-parallelism 100 --min-rate 64 -vv -oX OUTPUT | Yes 29 | | Service Detection | nmap TARGET -p PORTS -n -Pn -sV --version-intensity 6 --script banner -T4 -vv -oX OUTPUT | No 30 | | OS Detection | nmap TARGET -n -Pn -O -T4 --min-parallelism 100 --min-rate 64 -vv -oX OUTPUT | Yes 31 | | SSL Ciphers | nmap TARGET -p PORTS -n -Pn --script ssl-enum-ciphers -T4 -vv -oX OUTPUT | No 32 | | SSL Certs | nmap TARGET -p PORTS -n -Pn --script ssl-cert -T4 -vv -oX OUTPUT | No 33 | | Port Scanning (1-65535) | nmap TARGET -p- -n -Pn -sS -T4 --min-parallelism 100 --min-rate 128 -vv -oX OUTPUT | Yes 34 | 35 | ## Using Subprocess with Nmap 36 | 37 | The `subprocess` (https://docs.python.org/3/library/subprocess.html) library allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This library will make it easy for us to make calls to Nmap as well as manage the output effectively. Because we are going to use `subprocess` to call a program with parameters, we must pass our arguments as a list. What makes this tricky is each parameter will need to be its own element. However, Python makes this easy for us by using the `shlex` (https://docs.python.org/3/library/shlex.html) library. 38 | 39 | This library takes in a string and it will split each space delimiter parameter as its own element in the list. I frequently see scripts do this manually but it's not necessary. There may be some reading this and wonder why we are using a library when we can just use the built-in `split()` method from a string. These two approaches do nearly the same thing. The difference being is the `split()` method will create a list based on the delimiter and `shlex.split()` will create a delimited list intelligently based on how the shell interprets the input. 40 | 41 | What this means is if you have any parameters passed to Nmap that contains spaces within quotes, then `split()` will break your input when delimiting on spaces whereas `shlex.split()` will break it down appropriately. In a nut shell, if you do not plan on using spaces where you shouldn't, `split()` will work just fine, but out of my own habit, I incorporate `shlex.split()` to build my arguments for `subprocess`. 42 | 43 | You can see an example of what this looks like below: 44 | 45 | ![Alt text](https://github.com/gh0x0st/pythonizing_nmap/blob/main/Screenshots/shlex-vs-split.png?raw=true "shlex-vs-split") 46 | 47 | Reading STDOUT and STDERR is also relatively easy to do if you care about capturing both within your scripts. You can declare the values of the stdout/stderr arguments as `subprocess.PIPE`. Finally, you can read the data passed from stdout and stderr by using `communicate()` and declare them in variables respectively. 48 | 49 | ![Alt text](https://github.com/gh0x0st/pythonizing_nmap/blob/main/Screenshots/subprocess-stdout-stderr.png?raw=true "subprocess-stdout-stderr") 50 | 51 | I invite you to look at the man page for subprocess to see if there's any other tricks that you could find useful as it expands a lot further than what I have provided here. 52 | 53 | https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate 54 | 55 | ## Parsing Nmap XML 56 | 57 | One of my favorite features of Nmap is the ability to output our scan results to XML files. This enables us to parse through them to generate reports or use the output to generate input parameters for other Nmap operations. Let's look at an example of the XML output: 58 | 59 | ![Alt text](https://github.com/gh0x0st/pythonizing_nmap/blob/main/Screenshots/xml-parse-sample.png?raw=true "xml-parse-sample") 60 | 61 | ### Parse for Live Hosts 62 | 63 | The first case where this will be useful for us is to determine which hosts from our host discovery probes are considered up. To facilitate this task in python we'll take advantage of the `xml.etree.ElementTree` (https://docs.python.org/3/library/xml.etree.elementtree.html) library. Take a look at the note in https://github.com/gh0x0st/pythonizing_nmap/blob/main/XML%20Parser%20Scripts/README.md for an alternate library if you do not free comfortble with using ElementTree. 64 | 65 | Our helper function will take in the path of an XML file we designate and parse out the hosts that are flagged as being 'up'. 66 | 67 | Since I use all possible discovery probes I use `parseDiscoverXml()` to take in the results from all the Xml files, then I use a second helper function to remove any duplicates and output them space delimited so I can use those at the target input values for future Nmap calls. 68 | 69 | ```Python 70 | #!/usr/bin/python3 71 | 72 | import xml.etree.ElementTree as ET 73 | 74 | def parseDiscoverXml(in_xml): 75 | live_hosts = [] 76 | xml_tree = ET.parse(in_xml) 77 | xml_root = xml_tree.getroot() 78 | for host in xml_root.findall('host'): 79 | ip_state = host.find('status').get('state') 80 | if ip_state == "up": 81 | live_hosts.append(host.find('address').get('addr')) 82 | return live_hosts 83 | 84 | 85 | def convertToNmapTarget(hosts): 86 | hosts = list(dict.fromkeys(hosts)) 87 | return " ".join(hosts) 88 | 89 | 90 | def main(): 91 | hosts = parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_echo_host_discovery.xml') 92 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_netmask_host_discovery.xml') 93 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_timestamp_host_discovery.xml') 94 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/tcp_syn_host_discovery.xml') 95 | 96 | print(f"Flagged Hosts: {len(hosts)}") 97 | print(f"Unique Hosts: {len(list(dict.fromkeys(hosts)))}") 98 | print(f"Nmap Format Example: {convertToNmapTarget(hosts)}") 99 | 100 | if __name__ == '__main__': 101 | main() 102 | ``` 103 | 104 | ![Alt text](https://github.com/gh0x0st/pythonizing_nmap/blob/main/Screenshots/parse-live-hosts.png?raw=true "parse-live-hosts") 105 | 106 | ### Parse for Accessible Ports 107 | 108 | Now that we have a way to easily construct a list of available hosts, we can move onto port scanning. After this operation is finished, we'll need a way to programmatically parse the ports that considered available to our attacker machine. Our port scanning stages scripts will produce files called `top_1000_portscan.xml` / `full_portscan.xml` respectively. 109 | 110 | What we will do with this file is parse through every host in the `hosts` element and for each host we will loop through every port in the `ports` element. After it flags a port that's found to be open it'll keep all the results in a list with each element in a " ," format. When we start our service scanning, we'll split the results so we can designate our target host and target hosts respectively in future Nmap calls. This allows to programmatically generate our Nmap commands with the necessary target ip addresses and ports. 111 | 112 | ```Python 113 | #!/usr/bin/python3 114 | 115 | import xml.etree.ElementTree as ET 116 | 117 | def parseDiscoverPorts(in_xml): 118 | results = [] 119 | port_list = '' 120 | xml_tree = ET.parse(in_xml) 121 | xml_root = xml_tree.getroot() 122 | for host in xml_root.findall('host'): 123 | ip = host.find('address').get('addr') 124 | ports = host.findall('ports')[0].findall('port') 125 | for port in ports: 126 | state = port.find('state').get('state') 127 | if state == 'open': 128 | port_list += port.get('portid') + ',' 129 | port_list = port_list.rstrip(',') 130 | if port_list: 131 | results.append(f"{ip} {port_list}") 132 | port_list = '' 133 | return results 134 | 135 | 136 | def main(): 137 | targets = parseDiscoverPorts('/home/tristram/Scans/Stage_2/top_1000_portscan.xml') 138 | for target in targets: 139 | element = target.split() 140 | target_ip = element[0] 141 | target_ports = element[1] 142 | print(f'Nmap Format Example: nmap {target_ip} -p {target_ports}') 143 | 144 | if __name__ == '__main__': 145 | main() 146 | ``` 147 | 148 | ![Alt text](https://github.com/gh0x0st/pythonizing_nmap/blob/main/Screenshots/parse-accessible-ports.png?raw=true "parse-accessible-ports") 149 | 150 | ### Parsing XML in Memory 151 | 152 | The previous examples showed you how you can parse XML files that are on disk, but you are also able to parse XML without relying on XML on disk by changing a few approaches. Specifically, we'll tell Nmap to output XML to stdout and we will store that in a variable. The output itself will be stored in the first element in the `tuple` as a `bytes-like object`. We will just need to make a few changes but can borrow nearly the entire function we created before. 153 | 154 | The only changes we need to make will be to remove `ET.parse` and `xml_tree.getroot()` and replace with `ET.fromstring` which parses XML from a string directly into an Element, which is the root element of the parsed tree. 155 | 156 | Personally, I do not use this approach as much as I like to have the XML files on disk so I can use with other operations. Keep in mind that if you wanted to write your tool that works with everything in memory then you should keep an eye on your system resources. Some Nmap scans can produce quite large output files and you do not want to bog down your system or lose data in the event of a system crash. 157 | 158 | ```PYTHON 159 | #!/usr/bin/python3 160 | 161 | import xml.etree.ElementTree as ET 162 | import subprocess 163 | import shlex 164 | 165 | 166 | def nmapMemory(target): 167 | args = shlex.split(f"/usr/bin/nmap {target} -T4 -Pn -n -vv -sS -min-parallelism 100 --min-rate 64 --top-ports 1000 -oX -") 168 | return subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 169 | 170 | 171 | def parseDiscoverPortsMemory(in_xml): 172 | results = [] 173 | port_list = '' 174 | #xml_tree = ET.parse(in_xml) 175 | #xml_root = xml_tree.getroot() 176 | xml_root = ET.fromstring(in_xml.decode('utf-8')) 177 | for host in xml_root.findall('host'): 178 | ip = host.find('address').get('addr') 179 | ports = host.findall('ports')[0].findall('port') 180 | for port in ports: 181 | state = port.find('state').get('state') 182 | if state == 'open': 183 | port_list += port.get('portid') + ',' 184 | port_list = port_list.rstrip(',') 185 | if port_list: 186 | results.append(f"{ip} {port_list}") 187 | port_list = '' 188 | return results 189 | 190 | 191 | def main(): 192 | target = '127.0.0.1' 193 | xml_output = nmapMemory(target)[0] 194 | 195 | targets = parseDiscoverPortsMemory(xml_output) 196 | for target in targets: 197 | element = target.split() 198 | target_ip = element[0] 199 | target_ports = element[1] 200 | print(f'Scanning: {target_ip} against ports {target_ports}') 201 | 202 | 203 | if __name__ == '__main__': 204 | main() 205 | ``` 206 | 207 | ## Importing Nmap XML into SQLite Databases 208 | 209 | Since we have learned previously how to parse Nmap XML using Python we can also take those results and import them into SQLite Databases. From there you could use that database to build input parameters, generate reports or keep historical information from past engagements. The `sqlite3` (https://docs.python.org/3/library/sqlite3.html) library does virtually all the hard work for us. Keep in mind that this library requires us to work with `tuples` when you receive results back from the database. They work just like lists except you cannot change the element values. 210 | 211 | Let's look at how this can be done with a simple use case scenario for storing the results from a host discovery scan and whether an IP is up or not based on the results from an ICMP Echo scan. 212 | 213 | 1. Creating the Database File 214 | 2. Inserting Data into a Table 215 | 3. Selecting Content from a Table 216 | 217 | ### Creating the Database File 218 | 219 | This is where we'll create the actual database file on disk. Within the create_db function you can setup your tables and the values you want to store. If you want some ideas on what sort of tables could work for you then consider peaking at section 6 of this post before moving on as those sections produce CSV tables with various amounts of information. 220 | 221 | ```PYTHON 222 | #!/usr/bin/python3 223 | 224 | import sqlite3 225 | 226 | def create_connection(db_file): 227 | conn = None 228 | try: 229 | conn = sqlite3.connect(db_file) 230 | except Exception as e: 231 | print(e) 232 | return conn 233 | 234 | 235 | def create_db(conn): 236 | createHostDiscoveryTable="""CREATE TABLE IF NOT EXISTS HostDiscovery ( 237 | id integer PRIMARY KEY, 238 | IP text NOT NULL, 239 | Status text NOT NULL, 240 | ICMP_Echo text NOT NULL);""" 241 | try: 242 | c = conn.cursor() 243 | c.execute(createHostDiscoveryTable) 244 | except Exception as e: 245 | print(e) 246 | 247 | 248 | def main(): 249 | db_file = 'PythonizingNmap.db' 250 | conn = create_connection(db_file) 251 | create_db(conn) 252 | 253 | 254 | if __name__ == '__main__': 255 | main() 256 | ``` 257 | 258 | ![Alt text](https://github.com/gh0x0st/pythonizing_nmap/blob/main/Screenshots/create-database.png?raw=true "create-database") 259 | 260 | ### Inserting Data into a Table 261 | 262 | Now that our table is created, we can define our insert_content function to insert our parsed XML data directly into the `HostDiscovery` table. Granted I hardcoded some values here this would be a good function to parameterize to make it more dynamic. Keep note that we are inserting our data as a `tuple`. 263 | 264 | ```PYTHON 265 | #!/usr/bin/python3 266 | 267 | import sqlite3 268 | import xml.etree.ElementTree as ET 269 | 270 | 271 | def create_connection(db_file): 272 | conn = None 273 | try: 274 | conn = sqlite3.connect(db_file) 275 | except Exception as e: 276 | print(e) 277 | return conn 278 | 279 | 280 | def insert_content(conn, content): 281 | sql = ''' INSERT INTO HostDiscovery(IP,Status,ICMP_Echo) 282 | VALUES(?,?,?) ''' 283 | cur = conn.cursor() 284 | cur.execute(sql, content) 285 | return cur.lastrowid 286 | 287 | 288 | def main(): 289 | # Database Connection 290 | db_file = 'PythonizingNmap.db' 291 | conn = create_connection(db_file) 292 | 293 | # Parse XML 294 | in_xml_echo = '/home/tristram/Scans/Stage_1/icmp_echo_host_discovery.xml' 295 | 296 | # Load ICMP Echo XML 297 | xml_tree_echo = ET.parse(in_xml_echo) 298 | xml_root_echo = xml_tree_echo.getroot() 299 | 300 | # Load ICMP Echo XML 301 | for host in xml_root_echo.findall('host'): 302 | echo_ip = host.find('address').get('addr') 303 | echo_state = host.find('status').get('state') 304 | echo_reason = host.find('status').get('reason') 305 | 306 | # Insert results into database 307 | insert_content(conn, (echo_ip, echo_state, echo_reason)) 308 | conn.commit() 309 | 310 | 311 | if __name__ == '__main__': 312 | main() 313 | ``` 314 | 315 | ![Alt text](https://github.com/gh0x0st/pythonizing_nmap/blob/main/Screenshots/insert-content.png?raw=true "insert-content") 316 | 317 | ### Selecting Content from a Table 318 | 319 | After our data is inserted into the database what you can do from here is up to you! You could use this to store results from past engagements or even use it as a working database where you can build other automated workflows that utilize information selected from the database itself. In this example here we are selecting all the hosts that are considered 'up'. 320 | 321 | ```PYTHON 322 | #!/usr/bin/python3 323 | 324 | import sqlite3 325 | 326 | def create_connection(db_file): 327 | conn = None 328 | try: 329 | conn = sqlite3.connect(db_file) 330 | except Exception as e: 331 | print(e) 332 | return conn 333 | 334 | 335 | def select_content(conn): 336 | sql = """SELECT IP 337 | FROM HostDiscovery 338 | WHERE Status = 'up' 339 | """ 340 | cur = conn.cursor() 341 | cur.execute(sql) 342 | rows = cur.fetchall() 343 | return rows 344 | 345 | 346 | def main(): 347 | db_file = 'PythonizingNmap.db' 348 | conn = create_connection(db_file) 349 | live_hosts = select_content(conn) 350 | for host in live_hosts: 351 | print(f'Live: {host[0]}') 352 | 353 | 354 | if __name__ == '__main__': 355 | main() 356 | ``` 357 | 358 | ![Alt text](https://github.com/gh0x0st/pythonizing_nmap/blob/main/Screenshots/select-content.png?raw=true "select-content") 359 | 360 | ## Python Nmap Wrapper Scripts 361 | 362 | Now that we've gone through parsing the XML files from Nmap we can use this approach to programmatically generate input parameters for other Nmap operations where we need to designate target IPs and/or ports. I have included below some thoughts around a staged approach to Nmap enumeration. Keep in mind that the code snippets provided are intended to act as blueprints for you to build upon. 363 | 364 | As you read these examples you will find cases where we scan individual IPs at a time, resulting in multiple XML output files and others where I have a single scan targeting all the IPs resulting in a single XML output file. I did this intentionally for you to weight the benefits of parsing through individual XML files vs a single XML file. One option allows you to pass in a single file into your functions where the others require you use a for loop. If you use individually XML files it would be easier to review the results for a specific machine vs picking out the bits you want a in a larger file. 365 | 366 | ### Stage 1 - Host Discovery 367 | 368 | With this step the objective is to determine whether something exists at a particular IP based on the response to your probes. You'll typically encounter straight ICMP restrictions at the firewall, but there are cases where there's misconfigurations or even intended configurations where specific ICMP types are permitted. Because of this I like to take advantage of `ICMP ECHO`, `ICMP TIMESTAMP` and `ICMP NETMASK` probes by sending them individually. 369 | 370 | Outside of ICMP probes, another approach you will likely have to take is to run a port scan with a small subset of ports to solicit a response from the firewall. In these cases, a `RESET` or `SYN-ACK` from the firewall denotes a live host at that IP address. I combine both half open scans and ack scans (https://nmap.org/book/host-discovery-strategies.html) with a very small subset of ports to try. By combining all five of these probes together you can craft yourself a scripted host discovery solution to enhance your chances of discovering a live host. 371 | 372 | Granted during this stage all you want is to know is whether a host is up. However, I like to expand on this a little more by reporting how each host responds to each of the probes. You may identify hosts that allow ICMP and if the client believes they are blocking ICMP across the board from the internet it could be helpful for them to be aware. 373 | 374 | ```PYTHON 375 | #!/usr/bin/python3 376 | 377 | import shlex 378 | import subprocess 379 | import os 380 | import sys 381 | 382 | 383 | def sendIcmpEcho(target, out_xml): 384 | out_xml = os.path.join(out_xml,'icmp_echo_host_discovery.xml') 385 | nmap_cmd = f"/usr/bin/nmap {target} -n -sn -PE -vv -oX {out_xml}" 386 | sub_args = shlex.split(nmap_cmd) 387 | subprocess.Popen(sub_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 388 | makeInvokerOwner(out_xml) 389 | 390 | 391 | def sendIcmpNetmask(target, out_xml): 392 | out_xml = os.path.join(out_xml,'icmp_netmask_host_discovery.xml') 393 | nmap_cmd = f"/usr/bin/nmap {target} -n -sn -PM -vv -oX {out_xml}" 394 | sub_args = shlex.split(nmap_cmd) 395 | subprocess.Popen(sub_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 396 | makeInvokerOwner(out_xml) 397 | 398 | 399 | def sendIcmpTimestamp(target, out_xml): 400 | out_xml = os.path.join(out_xml,'icmp_timestamp_host_discovery.xml') 401 | nmap_cmd = f"/usr/bin/nmap {target} -n -sn -PP -vv -oX {out_xml}" 402 | sub_args = shlex.split(nmap_cmd) 403 | subprocess.Popen(sub_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 404 | makeInvokerOwner(out_xml) 405 | 406 | 407 | def sendTcpSyn(target, out_xml): 408 | out_xml = os.path.join(out_xml,'tcp_syn_host_discovery.xml') 409 | nmap_cmd = f"/usr/bin/nmap {target} -PS21,22,23,25,80,113,443 -PA80,113,443 -n -sn -T4 -vv -oX {out_xml}" 410 | sub_args = shlex.split(nmap_cmd) 411 | subprocess.Popen(sub_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 412 | makeInvokerOwner(out_xml) 413 | 414 | 415 | def makeInvokerOwner(path): 416 | uid = os.environ.get('SUDO_UID') 417 | gid = os.environ.get('SUDO_GID') 418 | if uid is not None: 419 | os.chown(path, int(uid), int(gid)) 420 | 421 | 422 | def is_root(): 423 | if os.geteuid() == 0: 424 | return True 425 | else: 426 | return False 427 | 428 | 429 | def main(): 430 | if not is_root(): 431 | print('[!] The discovery probes in this script requires root privileges') 432 | sys.exit(1) 433 | 434 | target = '127.0.0.1' 435 | 436 | sendIcmpEcho(target, os.getcwd()) 437 | sendIcmpNetmask(target, os.getcwd()) 438 | sendIcmpTimestamp(target, os.getcwd()) 439 | sendTcpSyn(target, os.getcwd()) 440 | 441 | if __name__ == '__main__': 442 | main() 443 | ``` 444 | 445 | ### Stage 2 - Port Scanning (Top 1000) 446 | 447 | I do not find services running on non-standard ports too often in production. Because of this I focus on the ports that have a higher ratio as defined in the nmap-services file. This will help save you time while finding the ports that are likely to be accessible. Based on the nmap author's research (https://nmap.org/book/performance-port-selection.html), scanning the top 1000 ports will catch roughly 93% of the TCP ports. The statistics here are in your favor and you'll find most of the ports within a reasonable amount of time. 448 | 449 | ```PYTHON 450 | #!/usr/bin/python3 451 | 452 | import xml.etree.ElementTree as ET 453 | import subprocess 454 | import shlex 455 | import os 456 | import sys 457 | 458 | 459 | def parseDiscoverXml(in_xml): 460 | live_hosts = [] 461 | xml_tree = ET.parse(in_xml) 462 | xml_root = xml_tree.getroot() 463 | for host in xml_root.findall('host'): 464 | ip_state = host.find('status').get('state') 465 | if ip_state == "up": 466 | live_hosts.append(host.find('address').get('addr')) 467 | return live_hosts 468 | 469 | 470 | def convertToNmapTarget(hosts): 471 | hosts = list(dict.fromkeys(hosts)) 472 | return " ".join(hosts) 473 | 474 | 475 | def tcpSynPortScan(target, out_xml,): 476 | out_xml = os.path.join(out_xml,'top_1000_portscan.xml') 477 | nmap_cmd = f"/usr/bin/nmap {target} --top-ports 1000 -n -Pn -sS -T4 --min-parallelism 100 --min-rate 64 -vv -oX {out_xml}" 478 | sub_args = shlex.split(nmap_cmd) 479 | subprocess.Popen(sub_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 480 | makeInvokerOwner(out_xml) 481 | 482 | 483 | def makeInvokerOwner(path): 484 | uid = os.environ.get('SUDO_UID') 485 | gid = os.environ.get('SUDO_GID') 486 | if uid is not None: 487 | os.chown(path, int(uid), int(gid)) 488 | 489 | 490 | def is_root(): 491 | if os.geteuid() == 0: 492 | return True 493 | else: 494 | return False 495 | 496 | 497 | def main(): 498 | if not is_root(): 499 | print('[!] TCP/SYN scans requires root privileges') 500 | sys.exit(1) 501 | 502 | hosts = parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_echo_host_discovery.xml') 503 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_netmask_host_discovery.xml') 504 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_timestamp_host_discovery.xml') 505 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/tcp_syn_host_discovery.xml') 506 | 507 | target = convertToNmapTarget(hosts) 508 | tcpSynPortScan(target, os.getcwd()) 509 | 510 | if __name__ == '__main__': 511 | main() 512 | ``` 513 | 514 | ### Stage 3 - Service Detection 515 | 516 | Service scanning is something that will catch inexperienced pen testers off guard when they discover that a simple service scan, they run all the time on CTFs just alerted a blue team to their presence an hour in on their assessment. Allow me to provide you an example of what I’m talking about and look at an example from the nmap-service-probes file: 517 | 518 | ![Alt text](https://github.com/gh0x0st/pythonizing_nmap/blob/main/Screenshots/nmap-service-probes.png?raw=true "nmap-service-probes") 519 | 520 | If you come across any server that uses ports 515,1028,1068,1503,1720,1935,2040,3388,3389 then nmap, with the default options, will eventually use the TerminalServer probes. Here's the problem. If you have a client that uses a Cisco IPS for example that sits in front of that server and it sees `\x03\0\0\x0b\x06\xe0\0\0\0\0\0|` destined to any port that isn't 3389, then it's going to flag you thinking you're trying to connect to RDP on a non-standard port. Because of this as a rule of thumb I put a hard stop on letting nmap try to service probe anything on those ports so I block those off the bat in the config file on line 29 `Exclude T:9100-9107,T:515,T:1028,T:1068,T:1503,T:1720,T:1935,T:2040,T:3388`. 521 | 522 | _NOTE: There is a `--exclude-ports` parameter but I like to show people that there are configurable options within the config files_ 523 | 524 | The problem doesn't stop there though. If you run into a port that nmap cannot figure out, it will try every possible probe up the intensity level, which by default is 7 (https://nmap.org/book/man-version-detection.html). If you look at the snippet below, there is another terminal server probe that is set to rarity 7, so those probes would be included. To prevent that from happening, I set my intensity version to 5 or 6 via `--version-intensity` depending on how paranoid I am. 525 | 526 | If you have access to lab network with some sort of IDS/IPS it would be great practice for you to see what type of scans trigger alerts and what you can do to prevent them from happening. 527 | 528 | ![Alt text](https://github.com/gh0x0st/pythonizing_nmap/blob/main/Screenshots/nmap-service-probes-2.png?raw=true "nmap-service-probes-2") 529 | 530 | ```PYTHON 531 | #!/usr/bin/python3 532 | 533 | import xml.etree.ElementTree as ET 534 | import subprocess 535 | import shlex 536 | import os 537 | 538 | 539 | def parseDiscoverPorts(in_xml): 540 | results = [] 541 | port_list = '' 542 | xml_tree = ET.parse(in_xml) 543 | xml_root = xml_tree.getroot() 544 | for host in xml_root.findall('host'): 545 | ip = host.find('address').get('addr') 546 | ports = host.findall('ports')[0].findall('port') 547 | for port in ports: 548 | state = port.find('state').get('state') 549 | if state == 'open': 550 | port_list += port.get('portid') + ',' 551 | port_list = port_list.rstrip(',') 552 | if port_list: 553 | results.append(f"{ip} {port_list}") 554 | port_list = '' 555 | return results 556 | 557 | 558 | def serviceScan(target_ip, target_ports, out_xml): 559 | out_xml = os.path.join(out_xml,f'{target_ip}_services.xml') 560 | nmap_cmd = f"/usr/bin/nmap {target_ip} -p {target_ports} -n -Pn -sV --version-intensity 6 --script banner -T4 -vv -oX {out_xml}" 561 | sub_args = shlex.split(nmap_cmd) 562 | subprocess.Popen(sub_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 563 | 564 | 565 | def main(): 566 | in_xml = '/home/tristram/Scans/Stage_2/top_1000_portscan.xml' 567 | targets = parseDiscoverPorts(in_xml) 568 | for target in targets: 569 | element = target.split() 570 | target_ip = element[0] 571 | target_ports = element[1] 572 | print(f'Scanning: {target_ip} against ports {target_ports}') 573 | serviceScan(target_ip, target_ports, os.getcwd()) 574 | 575 | 576 | if __name__ == '__main__': 577 | main() 578 | ``` 579 | 580 | ### Stage 4 - OS Detection 581 | 582 | I'm a bit torn on using the OS discovery scan over the internet. Sometimes it does not provide me anything useful and other times it provides me a gold mine with unsupported operating systems. I will run this scan just to see and will try to verify through other types of enumeration, such as identifying os requirements for the running software if I'm able. If I'm on the network probing a device, I'll typically use this all the time if I'm on the internal network but over the internet it all depends on if I have anything else to work off from first. 583 | 584 | ```PYTHON 585 | #!/usr/bin/python3 586 | 587 | import xml.etree.ElementTree as ET 588 | import subprocess 589 | import shlex 590 | import os 591 | import sys 592 | 593 | 594 | def parseDiscoverXml(in_xml): 595 | live_hosts = [] 596 | xml_tree = ET.parse(in_xml) 597 | xml_root = xml_tree.getroot() 598 | for host in xml_root.findall('host'): 599 | ip_state = host.find('status').get('state') 600 | if ip_state == "up": 601 | live_hosts.append(host.find('address').get('addr')) 602 | return live_hosts 603 | 604 | 605 | def convertToNmapTarget(hosts): 606 | hosts = list(dict.fromkeys(hosts)) 607 | return " ".join(hosts) 608 | 609 | 610 | def osScan(targets, out_xml): 611 | out_xml = os.path.join(out_xml,f'osdetection.xml') 612 | nmap_cmd = f"/usr/bin/nmap {targets} -n -Pn -O -T4 --min-parallelism 100 --min-rate 64 -vv -oX {out_xml}" 613 | sub_args = shlex.split(nmap_cmd) 614 | subprocess.Popen(sub_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 615 | makeInvokerOwner(out_xml) 616 | 617 | 618 | def makeInvokerOwner(path): 619 | uid = os.environ.get('SUDO_UID') 620 | gid = os.environ.get('SUDO_GID') 621 | if uid is not None: 622 | os.chown(path, int(uid), int(gid)) 623 | 624 | 625 | def is_root(): 626 | if os.geteuid() == 0: 627 | return True 628 | else: 629 | return False 630 | 631 | 632 | def main(): 633 | if not is_root(): 634 | print('[!] TCP/IP fingerprinting (for OS scan) requires root privileges.') 635 | sys.exit(1) 636 | 637 | hosts = parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_echo_host_discovery.xml') 638 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_netmask_host_discovery.xml') 639 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_timestamp_host_discovery.xml') 640 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/port_host_discovery.xml') 641 | 642 | target = convertToNmapTarget(hosts) 643 | 644 | osScan(target, os.getcwd()) 645 | 646 | 647 | if __name__ == '__main__': 648 | main() 649 | ``` 650 | 651 | ### Stage 5 - SSL Ciphers 652 | 653 | For the most part I try to keep NSE scripts for more targeted enumeration, apart from `ssl-enum-ciphers` and `ssl-certs`. The NSE script `ssl-enum-ciphers` is particularly useful for when your target under regulatory requirements and aren't supposed to be using unsafe TLS configurations. Some of the NSE scripts can be noisy so weigh the benefit of what you are trying to learn about a target vs the risk of being busted. 654 | 655 | The results of this NSE script exports nicely into XML and I'll show you how you can convert these results into a CSV format so you can easily move into a report further down. 656 | 657 | ```PYTHON 658 | #!/usr/bin/python3 659 | 660 | import xml.etree.ElementTree as ET 661 | import subprocess 662 | import shlex 663 | import os 664 | 665 | 666 | def parseDiscoverPorts(in_xml): 667 | results = [] 668 | port_list = '' 669 | xml_tree = ET.parse(in_xml) 670 | xml_root = xml_tree.getroot() 671 | for host in xml_root.findall('host'): 672 | ip = host.find('address').get('addr') 673 | ports = host.findall('ports')[0].findall('port') 674 | for port in ports: 675 | state = port.find('state').get('state') 676 | if state == 'open': 677 | port_list += port.get('portid') + ',' 678 | port_list = port_list.rstrip(',') 679 | if port_list: 680 | results.append(f"{ip} {port_list}") 681 | port_list = '' 682 | return results 683 | 684 | 685 | def sslCipherScan(target_ip, target_ports, out_xml): 686 | out_xml = os.path.join(out_xml,f'{target_ip}_ssl_ciphers.xml') 687 | nmap_cmd = f"/usr/bin/nmap {target_ip} -p {target_ports} -n -Pn --script ssl-enum-ciphers -T4 -vv -oX {out_xml}" 688 | sub_args = shlex.split(nmap_cmd) 689 | subprocess.Popen(sub_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 690 | 691 | 692 | def main(): 693 | in_xml = '/home/tristram/Scans/Stage_2/syn_port_scan.xml' 694 | targets = parseDiscoverPorts(in_xml) 695 | for target in targets: 696 | element = target.split() 697 | target_ip = element[0] 698 | target_ports = element[1] 699 | print(f'Scanning: {target_ip} against ports {target_ports}') 700 | sslCipherScan(target_ip, target_ports, os.getcwd()) 701 | 702 | 703 | if __name__ == '__main__': 704 | main() 705 | ``` 706 | 707 | ### Stage 6 - SSL Certs 708 | 709 | I like to include this step because from time to time misconfigured or poorly crafted SSL certificates can reveal quite a bit of information. For example, if you identify a web server that's accessible to the internet and it has a certificate signed by an internal CA then there is a good chance that web server is behind reverse proxy or a server on the private network being NAT'd to the internet which could lead to a damaging foothold if you can identify an exploitable condition. 710 | 711 | ```PYTHON 712 | #!/usr/bin/python3 713 | 714 | import xml.etree.ElementTree as ET 715 | import subprocess 716 | import shlex 717 | import os 718 | 719 | 720 | def parseDiscoverPorts(in_xml): 721 | results = [] 722 | port_list = '' 723 | xml_tree = ET.parse(in_xml) 724 | xml_root = xml_tree.getroot() 725 | for host in xml_root.findall('host'): 726 | ip = host.find('address').get('addr') 727 | ports = host.findall('ports')[0].findall('port') 728 | for port in ports: 729 | state = port.find('state').get('state') 730 | if state == 'open': 731 | port_list += port.get('portid') + ',' 732 | port_list = port_list.rstrip(',') 733 | if port_list: 734 | results.append(f"{ip} {port_list}") 735 | port_list = '' 736 | return results 737 | 738 | 739 | def sslCertScan(target_ip, target_ports, out_xml): 740 | out_xml = os.path.join(out_xml,f'{target_ip}_ssl_certs.xml') 741 | nmap_cmd = f"/usr/bin/nmap {target_ip} -p {target_ports} -n -Pn --script ssl-cert -T4 -vv -oX {out_xml}" 742 | sub_args = shlex.split(nmap_cmd) 743 | subprocess.Popen(sub_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 744 | 745 | 746 | def main(): 747 | in_xml = '/home/tristram/Scans/Stage_2/syn_port_scan.xml' 748 | targets = parseDiscoverPorts(in_xml) 749 | for target in targets: 750 | element = target.split() 751 | target_ip = element[0] 752 | target_ports = element[1] 753 | print(f'Scanning: {target_ip} against ports {target_ports}') 754 | sslCertScan(target_ip, target_ports, os.getcwd()) 755 | 756 | 757 | if __name__ == '__main__': 758 | main() 759 | ``` 760 | 761 | ### Stage 7 - Port Scanning (1-65535) 762 | 763 | I intentionally run this step last because it takes a long time if you have a lot of hosts. Based on the stats from the first port scan we'll only have a 7% chance of finding anything new so the return on investment of is particularly low. However, this stage is still something worth digging into a little bit. Obviously, we want our scans to run as fast as possible but we're too noisy we might trip an alarm, especially since we're scanning the entire TCP port range. 764 | 765 | If you have a lot of time to spare, consider the low and slow approach. If you're not concerned about alerts, then play around with the timing and performance parameters (https://nmap.org/book/man-performance.html). I've found `--min-parallelism 100 --min-rate 128` to be a good sweet spot between speed and reliably. 766 | 767 | ```PYTHON 768 | #!/usr/bin/python3 769 | 770 | import xml.etree.ElementTree as ET 771 | import subprocess 772 | import shlex 773 | import os 774 | import sys 775 | 776 | 777 | def parseDiscoverXml(in_xml): 778 | live_hosts = [] 779 | xml_tree = ET.parse(in_xml) 780 | xml_root = xml_tree.getroot() 781 | for host in xml_root.findall('host'): 782 | ip_state = host.find('status').get('state') 783 | if ip_state == "up": 784 | live_hosts.append(host.find('address').get('addr')) 785 | return live_hosts 786 | 787 | 788 | def convertToNmapTarget(hosts): 789 | hosts = list(dict.fromkeys(hosts)) 790 | return " ".join(hosts) 791 | 792 | 793 | def tcpSynPortScan(target, out_xml,): 794 | out_xml = os.path.join(out_xml,'65535_portscan.xml') 795 | nmap_cmd = f"/usr/bin/nmap {target} -p- -n -Pn -sS -T4 --min-parallelism 100 --min-rate 128 -vv -oX {out_xml}" 796 | sub_args = shlex.split(nmap_cmd) 797 | subprocess.Popen(sub_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 798 | makeInvokerOwner(out_xml) 799 | 800 | 801 | def makeInvokerOwner(path): 802 | uid = os.environ.get('SUDO_UID') 803 | gid = os.environ.get('SUDO_GID') 804 | if uid is not None: 805 | os.chown(path, int(uid), int(gid)) 806 | 807 | 808 | def is_root(): 809 | if os.geteuid() == 0: 810 | return True 811 | else: 812 | return False 813 | 814 | 815 | def main(): 816 | if not is_root(): 817 | print('[!] TCP/SYN scans requires root privileges') 818 | sys.exit(1) 819 | 820 | hosts = parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_echo_host_discovery.xml') 821 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_netmask_host_discovery.xml') 822 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_timestamp_host_discovery.xml') 823 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/port_host_discovery.xml') 824 | 825 | target = convertToNmapTarget(hosts) 826 | tcpSynPortScan(target, os.getcwd()) 827 | 828 | if __name__ == '__main__': 829 | main() 830 | ``` 831 | 832 | ## Generating Reports from Nmap XML 833 | 834 | Depending on the size of your engagement the process of transcribing your notes into a report can be quite tedious. Thankfully this is another place where Python comes to the rescue. We can take the same XML files we were working with before to generate CSV files that we can then use to import into the report format of our choosing. 835 | 836 | The scripts for this can be a little confusing with the all the loops so I added comments to help describe each step. Keep a mental note that if there are multiple tables shown in a section that means that script will create that many tables. 837 | 838 | ### Detected Hosts 839 | 840 | | IP | Status | ICMP Echo | ICMP Netmask | ICMP Timestamp | Port 841 | | :--- | :---| :---| :---| :---| :---| 842 | | 192.168.0.100|down|no-response|no-response|no-response|no-response 843 | | 192.168.0.101|up|echo-reply|no-response|timestamp-reply|reset 844 | | 192.168.0.102|up|echo-reply|no-response|no-response|syn-ack 845 | | 192.168.0.103|down|no-response|no-response|no-response|no-response 846 | 847 | ```PYTHON 848 | #!/usr/bin/python3 849 | 850 | import xml.etree.ElementTree as ET 851 | import csv 852 | 853 | def main(): 854 | # File Paths 855 | in_xml_port = '/home/tristram/Scans/Stage_1/tcp_syn_host_discovery.xml' 856 | in_xml_echo = '/home/tristram/Scans/Stage_1/icmp_echo_host_discovery.xml' 857 | in_xml_netmask = '/home/tristram/Scans/Stage_1/icmp_netmask_host_discovery.xml' 858 | in_xml_timestamp = '/home/tristram/Scans/Stage_1/icmp_timestamp_host_discovery.xml' 859 | 860 | # Load Port XML 861 | xml_tree_port = ET.parse(in_xml_port) 862 | xml_root_port = xml_tree_port.getroot() 863 | 864 | # Load ICMP Echo XML 865 | xml_tree_echo = ET.parse(in_xml_echo) 866 | xml_root_echo = xml_tree_echo.getroot() 867 | 868 | # Load ICMP Netmask XML 869 | xml_tree_netmask = ET.parse(in_xml_netmask) 870 | xml_root_netmask = xml_tree_netmask.getroot() 871 | 872 | # Load ICMP Timestamp XML 873 | xml_tree_timestamp = ET.parse(in_xml_timestamp) 874 | xml_root_timestamp = xml_tree_timestamp.getroot() 875 | 876 | # CSV File 877 | with open('detected_hosts.csv', 'w') as file: 878 | writer = csv.writer(file) 879 | # CSV Headers 880 | writer.writerow(['IP', 'Status', 'ICMP Echo', 'ICMP Netmask', 'ICMP Timestamp', 'Port']) 881 | 882 | # Load SYN Port XML 883 | for host in xml_root_port.findall('host'): 884 | host_status = 'down' 885 | master_ip = host.find('address').get('addr') 886 | port_state = host.find('status').get('state') 887 | port_reason = host.find('status').get('reason') 888 | 889 | # Load ICMP Echo XML 890 | for host in xml_root_echo.findall('host'): 891 | echo_ip = host.find('address').get('addr') 892 | echo_state = host.find('status').get('state') 893 | echo_reason = host.find('status').get('reason') 894 | 895 | # Load ICMP Netmask 896 | if master_ip == echo_ip: 897 | for host in xml_root_netmask.findall('host'): 898 | netmask_ip = host.find('address').get('addr') 899 | netmask_state = host.find('status').get('state') 900 | netmask_reason = host.find('status').get('reason') 901 | 902 | # Load ICMP Timestamp 903 | if master_ip == netmask_ip: 904 | for host in xml_root_timestamp.findall('host'): 905 | timestamp_ip = host.find('address').get('addr') 906 | timestamp_state = host.find('status').get('state') 907 | timestamp_reason = host.find('status').get('reason') 908 | if master_ip == timestamp_ip: 909 | if port_state == 'up' or echo_state == 'up' or netmask_state == 'up' or timestamp_state == 'up': 910 | host_status = 'up' 911 | 912 | # Write results to row 913 | writer.writerow([master_ip, host_status, echo_reason, netmask_reason, timestamp_reason, port_reason]) 914 | 915 | if __name__ == '__main__': 916 | main() 917 | ``` 918 | 919 | ### Detected Hosts Without Ports 920 | 921 | | IP | Port| Service 922 | | :--- | :---| :---| 923 | | 192.168.0.104|no-response|no-response|no-response 924 | | 192.168.0.105|no-response|no-response|no-response 925 | | 192.168.0.106|no-response|no-response|no-response 926 | | 192.168.0.107|no-response|no-response|no-response 927 | 928 | ```PYTHON 929 | #!/usr/bin/python3 930 | 931 | import xml.etree.ElementTree as ET 932 | import csv 933 | 934 | def main(): 935 | # Path to directory with host XML files 936 | in_xml = '/home/tristram/Scans/Stage_2/top_1000_portscan.xml' 937 | 938 | # CSV Data 939 | with open('detected_hosts_no_ports.csv', 'w') as file: 940 | writer = csv.writer(file) 941 | 942 | # CSV Headers 943 | writer.writerow(['IP', 'Port', 'Service']) 944 | 945 | # Load Top 1000 Port Scan 946 | xml_tree = ET.parse(in_xml) 947 | xml_root = xml_tree.getroot() 948 | 949 | # Cycle through each host 950 | for host in xml_root.findall('host'): 951 | ip_address = host.findall('address')[0].attrib['addr'] 952 | ports_element = host.findall('ports') 953 | port_child = ports_element[0].findall('port') 954 | open_ports = [] 955 | 956 | # Within each host cycle through the ports 957 | for port in port_child: 958 | if port.findall('state')[0].attrib['state'] == 'open': 959 | port_id = port.attrib['portid'] 960 | open_ports.append(port_id) 961 | 962 | # Write results to row 963 | if len(open_ports) == 0: 964 | writer.writerow([ip_address, 'no-response', 'no-response']) 965 | 966 | 967 | if __name__ == '__main__': 968 | main() 969 | ``` 970 | 971 | ### Detected Hosts With Ports + Services 972 | 973 | | IP | Port| Service 974 | | :--- | :---| :---| 975 | | 192.168.0.108|443|https 976 | | 192.168.0.109|443|https 977 | | 192.168.0.110|25|tcpwrapped 978 | | 192.168.0.111|443|https 979 | | 192.168.0.112|25|Microsoft Exchange smtpd 980 | | |443|https 981 | 982 | ```PYTHON 983 | #!/usr/bin/python3 984 | 985 | import xml.etree.ElementTree as ET 986 | import csv 987 | import os 988 | 989 | def main(): 990 | # Path to directory with host XML files 991 | in_path = '/home/tristram/Scans/Stage_3/' 992 | 993 | # CSV Data 994 | with open('detected_hosts_with_ports.csv', 'w') as file: 995 | writer = csv.writer(file) 996 | 997 | # CSV Headers 998 | writer.writerow(['IP', 'Port', 'Service']) 999 | for file in sorted(os.listdir(in_path)): 1000 | if file.endswith(".xml"): 1001 | if "no_ports.xml" in file: 1002 | writer.writerow([file.split('_no_ports.xml')[0], 'no-response', 'no-response']) 1003 | else: 1004 | # Load Service Scan 1005 | in_xml = os.path.join(in_path, file) 1006 | xml_tree = ET.parse(in_xml) 1007 | xml_root = xml_tree.getroot() 1008 | 1009 | # Cycle through each host 1010 | for host in xml_root.findall('host'): 1011 | ip_once = True 1012 | ip_address = host.findall('address')[0].attrib['addr'] 1013 | ports_element = host.findall('ports') 1014 | port_child = ports_element[0].findall('port') 1015 | open_ports = [] 1016 | 1017 | # Within each host cycle through the ports 1018 | for port in port_child: 1019 | if port.findall('state')[0].attrib['state'] == 'open': 1020 | port_id = port.attrib['portid'] 1021 | service_name = port.find('service').get('product') 1022 | if service_name == None: 1023 | service_name = port.find('service').get('name') 1024 | open_ports.append([port_id, service_name]) 1025 | 1026 | # Within each port cycle through the open ports 1027 | if len(open_ports): 1028 | for op in open_ports: 1029 | # Ensure we only notate the IP once to keep it clean 1030 | if ip_once == True: 1031 | # Write results to row 1032 | writer.writerow([ip_address, op[0], op[1]]) 1033 | ip_once = False 1034 | else: 1035 | # Write results to row 1036 | writer.writerow([None, op[0], op[1]]) 1037 | else: 1038 | # Write results to row if none 1039 | writer.writerow([ip_address, 'none', 'none']) 1040 | 1041 | if __name__ == '__main__': 1042 | main() 1043 | ``` 1044 | 1045 | ### Detected Hosts With Guessed Operating Systems 1046 | 1047 | | IP | Port 1048 | | :--- | :---| 1049 | | 192.168.0.113|Unknown 1050 | | 192.168.0.114|D-Link DCS-6620G webcam or Linksys BEFSR41 EtherFast router 1051 | | 192.168.0.115|Linux 4.9 1052 | | 192.168.0.116|Linux 2.6.32 1053 | | 192.168.0.117|FreeBSD 9.0-RELEASE - 10.3-RELEASE 1054 | 1055 | ```PYTHON 1056 | #!/usr/bin/python3 1057 | 1058 | import xml.etree.ElementTree as ET 1059 | import csv 1060 | 1061 | def main(): 1062 | # Path top the os scan file 1063 | in_xml = '/home/tristram/Scans/Stage_4/osdetection.xml' 1064 | 1065 | # CSV Data 1066 | with open('detected_hosts_os.csv', 'w') as file: 1067 | writer = csv.writer(file) 1068 | # CSV Headers 1069 | writer.writerow(['IP', 'OperatingSystem']) 1070 | 1071 | # Load OS Scan XML 1072 | xml_tree = ET.parse(in_xml) 1073 | xml_root = xml_tree.getroot() 1074 | 1075 | # Cycle through each host 1076 | for host in xml_root.findall('host'): 1077 | ip_address = host.findall('address')[0].attrib['addr'] 1078 | try: 1079 | os_element = host.findall('os') 1080 | os_name = os_element[0].findall('osmatch')[0].attrib['name'] 1081 | except IndexError: 1082 | os_name = 'Unknown' 1083 | 1084 | # Write results to row 1085 | writer.writerow([ip_address, os_name]) 1086 | 1087 | 1088 | if __name__ == '__main__': 1089 | main() 1090 | ``` 1091 | 1092 | ### Detected Hosts TLS Protocols 1093 | 1094 | #### TLSv1.0 1095 | 1096 | | IP | Port | Protocol 1097 | | :--- | :---| :--- | 1098 | | 192.168.0.118|443|TLSv1.0 1099 | | 192.168.0.119|25|TLSv1.0 1100 | | 192.168.0.120|443|TLSv1.0 1101 | | 192.168.0.121|443|TLSv1.0 1102 | | 192.168.0.122|5061|TLSv1.0 1103 | 1104 | #### TLSv1.1 1105 | 1106 | | IP | Port | Protocol 1107 | | :--- | :---| :--- | 1108 | | 192.168.0.123|443|TLSv1.1 1109 | | 192.168.0.124|25|TLSv1.1 1110 | | 192.168.0.125|443|TLSv1.1 1111 | | 192.168.0.126|443|TLSv1.1 1112 | | 192.168.0.127|5061|TLSv1.1 1113 | 1114 | #### SSLv3.0 1115 | 1116 | | IP | Port | Protocol 1117 | | :--- | :---| :--- | 1118 | | 192.168.0.128|443|SSLv3.0 1119 | | 192.168.0.129|25|SSLv3.0 1120 | | 192.168.0.130|443|SSLv3.0 1121 | | 192.168.0.131|443|SSLv3.0 1122 | | 192.168.0.132|5061|SSLv3.0 1123 | 1124 | ```PYTHON 1125 | #!/usr/bin/python3 1126 | 1127 | import xml.etree.ElementTree as ET 1128 | import csv 1129 | import os 1130 | 1131 | 1132 | def main(): 1133 | # Protocol Report Lists 1134 | tls_v10_report = [] 1135 | tls_v11_report = [] 1136 | ssl_v3_report = [] 1137 | 1138 | # Flagged Lists 1139 | flagged_tls_v10 = '' 1140 | flagged_tls_v11 = '' 1141 | flagged_ssl_v3 = '' 1142 | 1143 | # File Path 1144 | in_path= '/home/tristram/Scans/Stage_5/' 1145 | 1146 | # Cycle through each XML file 1147 | for file in os.listdir(in_path): 1148 | # Load each XML file 1149 | if file.endswith(".xml"): 1150 | in_xml = os.path.join(in_path, file) 1151 | xml_tree = ET.parse(in_xml) 1152 | xml_root = xml_tree.getroot() 1153 | 1154 | # Cycle through each host 1155 | for host in xml_root.findall('host'): 1156 | ip = host.find('address').get('addr') 1157 | ports_element = host.findall('ports') 1158 | port_element = ports_element[0].findall('port') 1159 | 1160 | # Cycle through each port 1161 | for scanned_port in port_element: 1162 | port_id = scanned_port.get('portid') 1163 | script_element = scanned_port.find('script') 1164 | if script_element: 1165 | # Cycle through each protocol 1166 | protocol_element = script_element.findall('table') 1167 | for tls_protocol in protocol_element: 1168 | protocol_version = tls_protocol.attrib['key'] 1169 | 1170 | # Stage data for TLSv1.0 Table 1171 | if protocol_version in 'TLSv1.0': 1172 | flagged_tls_v10 += protocol_version + ',' 1173 | 1174 | # Stage data for TLSv1.1 Table 1175 | if protocol_version in 'TLSv1.1': 1176 | flagged_tls_v11 += protocol_version + ',' 1177 | 1178 | # Stage data for SSLv3 Table 1179 | if protocol_version in 'SSLv3': 1180 | flagged_ssl_v3 += protocol_version + ',' 1181 | 1182 | # Load TLSv1.0 Data 1183 | if flagged_tls_v10: 1184 | flagged_tls_v10 = flagged_tls_v10.strip(',').split(',') 1185 | tls_v10_report.append([ip,port_id,flagged_tls_v10 ]) 1186 | flagged_tls_v10 = '' 1187 | 1188 | # Load TLSv1.1 Data 1189 | if flagged_tls_v11: 1190 | flagged_tls_v11 = flagged_tls_v11.strip(',').split(',') 1191 | tls_v11_report.append([ip,port_id,flagged_tls_v11 ]) 1192 | flagged_tls_v11 = '' 1193 | 1194 | # Load SSLv3.0 Data 1195 | if flagged_ssl_v3: 1196 | flagged_ssl_v3 = flagged_ssl_v3.strip(',').split(',') 1197 | ssl_v3_report.append([ip,port_id,flagged_ssl_v3 ]) 1198 | flagged_ssl_v3 = '' 1199 | 1200 | 1201 | # CSV Data for TLSv1.0 1202 | with open('detected_tls_v10.csv', 'w') as csvFile: 1203 | writer = csv.writer(csvFile) 1204 | 1205 | # CSV Headers 1206 | writer.writerow(["IP", "Port", "Protocol"]) 1207 | 1208 | # Cycle through each staged element in list 1209 | for server in tls_v10_report: 1210 | row_ip = server[0] 1211 | row_port = server[1] 1212 | 1213 | # Write results to row 1214 | writer.writerow([row_ip,row_port,'TLSv1.0']) 1215 | 1216 | # CSV Data for TLSv1.1 1217 | with open('detected_tls_v11.csv', 'w') as csvFile: 1218 | writer = csv.writer(csvFile) 1219 | 1220 | # CSV Headers 1221 | writer.writerow(["IP", "Port", "Protocol"]) 1222 | for server in tls_v11_report: 1223 | row_ip = server[0] 1224 | row_port = server[1] 1225 | 1226 | # Write results to row 1227 | writer.writerow([row_ip,row_port,'TLSv1.1']) 1228 | 1229 | # CSV Data for SSLv.3 1230 | with open('detected_ssl_v3.csv', 'w') as csvFile: 1231 | writer = csv.writer(csvFile) 1232 | 1233 | # CSV Headers 1234 | writer.writerow(["IP", "Port", "Protocol"]) 1235 | for server in ssl_v3_report: 1236 | row_ip = server[0] 1237 | row_port = server[1] 1238 | # Write results to row 1239 | writer.writerow([row_ip,row_port,'SSLv3.0']) 1240 | 1241 | if __name__ == '__main__': 1242 | main() 1243 | ``` 1244 | 1245 | ### Detected SSL Certificates 1246 | 1247 | | IP | Port | CommonName | IssuerCommon | CertStart | CertEnd 1248 | | :--- | :--- | :--- | :--- | :--- | :--- | 1249 | | 192.168.0.133|443|stay.example.com|DigiCert Global CA G2|2020-05-06|2021-05-06 1250 | | 192.168.0.134|443|off.example.com|DigiCert Global CA G2|2019-11-06|2020-11-05 1251 | | 192.168.0.135|443|ronins.example.com|DigiCert Global CA G2|2020-05-04|2021-05-05 1252 | | 192.168.0.136|443|lawn.example.com|DigiCert Global CA G2|2019-11-15|2020-11-14 1253 | 1254 | ```PYTHON 1255 | #!/usr/bin/python3 1256 | 1257 | import xml.etree.ElementTree as ET 1258 | import csv 1259 | import os 1260 | import re 1261 | 1262 | 1263 | def main(): 1264 | # Regular Expressions 1265 | reg_date = r'\d{4}-\d{2}-\d{2}' 1266 | 1267 | # File Path 1268 | in_path= '/home/tristram/Scans/Stage_6/' 1269 | 1270 | # Reports 1271 | cert_info_list = '' 1272 | cert_info_report = [] 1273 | 1274 | # Cycle through each XML file 1275 | for file in os.listdir(in_path): 1276 | if file.endswith(".xml"): 1277 | # Load XML 1278 | in_xml = os.path.join(in_path, file) 1279 | xml_tree = ET.parse(in_xml) 1280 | xml_root = xml_tree.getroot() 1281 | 1282 | # Cycle through each host 1283 | for host in xml_root.findall('host'): 1284 | ip = host.find('address').get('addr') 1285 | ports_element = host.findall('ports') 1286 | port_element = ports_element[0].findall('port') 1287 | 1288 | # Check Every Port 1289 | for scanned_port in port_element: 1290 | port_id = scanned_port.get('portid') 1291 | script_element = scanned_port.find('script') 1292 | 1293 | # SSL Cert Top Level 1294 | if script_element: 1295 | ssl_element = script_element.findall('table') 1296 | 1297 | # Cycle through each certificate 1298 | for ssl in ssl_element: 1299 | # Subject Field 1300 | if ssl.attrib.get('key') == 'subject': 1301 | for data in ssl: 1302 | if data.attrib.get('key') == 'commonName': 1303 | host_common_name = data.text 1304 | # Issuer Field 1305 | if ssl.attrib.get('key') == 'issuer': 1306 | for data in ssl: 1307 | if data.attrib.get('key') == 'commonName': 1308 | issuer_common_name = data.text 1309 | 1310 | # Validity Field 1311 | if ssl.attrib.get('key') == 'validity': 1312 | for data in ssl: 1313 | if data.attrib.get('key') == 'notBefore': 1314 | cert_start = data.text 1315 | cert_start = re.findall(reg_date, cert_start)[0] 1316 | if data.attrib.get('key') == 'notAfter': 1317 | cert_end = data.text 1318 | cert_end = re.findall(reg_date, cert_end)[0] 1319 | cert_info_list = f"{ip},{port_id},{host_common_name},{issuer_common_name},{cert_start},{cert_end}" 1320 | 1321 | # Load Data 1322 | cert_info_list = cert_info_list.split(',') 1323 | cert_info_report.append(cert_info_list) 1324 | 1325 | # Reset results for next host 1326 | cert_info_list = '' 1327 | 1328 | # CSV Data 1329 | with open('detected_ssl_certs.csv', 'w') as csvFile: 1330 | writer = csv.writer(csvFile) 1331 | 1332 | # CSV Headers 1333 | writer.writerow(["IP", "Port","CommonName","IssuerCommon","CertStart", "CertEnd"]) 1334 | for ci in cert_info_report: 1335 | if len(ci) == 6: 1336 | row_ip = ci[0] 1337 | row_port = ci[1] 1338 | row_cn = ci[2] 1339 | row_ion = ci[3] 1340 | row_cs = ci[4] 1341 | row_ce = ci[5] 1342 | # Write results to row 1343 | writer.writerow([row_ip,row_port,row_cn, row_ion, row_cs, row_ce]) 1344 | 1345 | 1346 | if __name__ == '__main__': 1347 | main() 1348 | ``` 1349 | 1350 | ### Detected Cipher Suites 1351 | 1352 | These reports are built to flag insecure cipher suites like that of virtually any vulnerability scanner. The risk levels were determined by the grade threshold output by Nmap's ssl-enum-ciphers NSE script (https://nmap.org/nsedoc/scripts/ssl-enum-ciphers.html). My own preference is to treat F, E and D as high risk and C as a moderate risk, but you can tweak that within the script itself. 1353 | 1354 | _NOTE: I included extra scripts for other ciphers within the repo but to keep things relatively clean I will include just a few examples below. _ 1355 | 1356 | #### Detected High Risk Ciphers 1357 | 1358 | | IP | Port| Cipher Suite 1359 | | :--- |:--- |:--- | 1360 | |192.168.0.154|443|"TLS_RSA_WITH_NULL_SHA (F) 1361 | | ||TLS_RSA_WITH_NULL_MD5 (F)" 1362 | |192.168.0.155|443|"TLS_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5 (D) 1363 | | ||TLS_RSA_WITH_NULL_SHA (F) 1364 | | ||TLS_RSA_EXPORT1024_WITH_RC4_56_SHA (D) 1365 | | ||TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 (E) 1366 | | ||TLS_RSA_EXPORT_WITH_DES40_CBC_SHA (E) 1367 | | ||TLS_RSA_WITH_NULL_MD5 (F) 1368 | | ||TLS_RSA_EXPORT_WITH_RC4_40_MD5 (E) 1369 | | ||TLS_RSA_EXPORT1024_WITH_RC4_56_MD5 (D)" 1370 | 1371 | #### Detected Moderate Risk Ciphers 1372 | 1373 | | IP | Port| Cipher Suite 1374 | | :--- |:--- |:--- | 1375 | | 192.168.0.156|443|"TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA (C) 1376 | | ||TLS_RSA_WITH_RC4_128_MD5 (C) 1377 | | ||TLS_RSA_WITH_3DES_EDE_CBC_SHA (C) 1378 | | ||TLS_RSA_WITH_RC4_128_SHA (C)" 1379 | 1380 | ```PYTHON 1381 | #!/usr/bin/python3 1382 | 1383 | import xml.etree.ElementTree as ET 1384 | import csv 1385 | import os 1386 | 1387 | 1388 | def main(): 1389 | # Cipher Risk Lists 1390 | ciphers_list = [] 1391 | flagged_ciphers = '' 1392 | 1393 | # Grade Threshold Lists 1394 | high_risk_grades = ['D','E','F'] 1395 | moderate_risk_grades = ['C'] 1396 | 1397 | high_risk_ciphers = [] 1398 | moderate_risk_ciphers = [] 1399 | 1400 | high_risk_flagged_list = '' 1401 | moderate_risk_flagged_list = '' 1402 | 1403 | # Path to directory with host XML files 1404 | in_path= '/home/tristram/Scans/Stage_5/' 1405 | for file in os.listdir(in_path): 1406 | if file.endswith(".xml"): 1407 | # Load XML 1408 | in_xml = os.path.join(in_path, file) 1409 | xml_tree = ET.parse(in_xml) 1410 | xml_root = xml_tree.getroot() 1411 | 1412 | # Cycle through each host 1413 | for host in xml_root.findall('host'): 1414 | ip = host.find('address').get('addr') 1415 | ports_element = host.findall('ports') 1416 | port_element = ports_element[0].findall('port') 1417 | 1418 | # Cycle through every port 1419 | for scanned_port in port_element: 1420 | port_id = scanned_port.get('portid') 1421 | script_element = scanned_port.find('script') 1422 | if script_element: 1423 | script_element = script_element.findall('table') 1424 | 1425 | # Cycle through script element 1426 | for tls_protocol in script_element: 1427 | 1428 | # Cycle through TLS protocol 1429 | for protocol in tls_protocol: 1430 | if protocol.attrib.get('key') == 'ciphers': 1431 | 1432 | # Cycle through each cipher 1433 | for entry in protocol: 1434 | for en in entry: 1435 | if en.attrib.get('key') == 'name': 1436 | name = en.text 1437 | if en.attrib.get('key') == 'strength': 1438 | grade = en.text 1439 | # Risk based on grade 1440 | if grade in high_risk_grades: 1441 | high_risk_flagged_list += f"{name} ({grade})" + ',' 1442 | if grade in moderate_risk_grades: 1443 | moderate_risk_flagged_list += f"{name} ({grade})" + ',' 1444 | 1445 | # Stage flagged data for current host 1446 | if high_risk_flagged_list: 1447 | high_risk_flagged_list = list(set(high_risk_flagged_list.strip(',').split(','))) 1448 | high_risk_ciphers.append([ip,port_id,high_risk_flagged_list]) 1449 | 1450 | if moderate_risk_flagged_list: 1451 | moderate_risk_flagged_list = list(set(moderate_risk_flagged_list.strip(',').split(','))) 1452 | moderate_risk_ciphers.append([ip,port_id,moderate_risk_flagged_list]) 1453 | 1454 | # Reset results for next host 1455 | high_risk_flagged_list = '' 1456 | moderate_risk_flagged_list = '' 1457 | 1458 | # Create High Risk Report 1459 | with open('high_risk_tls_ciphers.csv', 'w') as file: 1460 | writer = csv.writer(file) 1461 | 1462 | # CSV Headers 1463 | writer.writerow(["IP", "Port","Cipher Suite"]) 1464 | for hrc in high_risk_ciphers: 1465 | row_ip = hrc[0] 1466 | row_port = hrc[1] 1467 | row_cs = '\r\n'.join(hrc[2]) 1468 | 1469 | # Write results to row 1470 | writer.writerow([row_ip,row_port,row_cs]) 1471 | 1472 | # Create Moderate Risk Report 1473 | with open('moderate_risk_tls_ciphers.csv', 'w') as file: 1474 | writer = csv.writer(file) 1475 | 1476 | # CSV Headers 1477 | writer.writerow(["IP", "Port","Cipher Suite"]) 1478 | for mrc in moderate_risk_ciphers: 1479 | row_ip = mrc[0] 1480 | row_port = mrc[1] 1481 | row_cs = '\r\n'.join(mrc[2]) 1482 | 1483 | # Write results to row 1484 | writer.writerow([row_ip,row_port,row_cs]) 1485 | 1486 | 1487 | if __name__ == '__main__': 1488 | main() 1489 | ``` 1490 | 1491 | #### Detected 3DES Ciphers 1492 | 1493 | | IP | Port| Cipher Suite 1494 | | :--- |:--- |:--- | 1495 | | 192.168.0.137|443|"TLS_RSA_WITH_3DES_EDE_CBC_SHA 1496 | | ||TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA" 1497 | | 192.168.0.138|443|TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA 1498 | | 192.168.0.139|443|"TLS_RSA_WITH_3DES_EDE_CBC_SHA 1499 | | ||TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA" 1500 | 1501 | ```PYTHON 1502 | #!/usr/bin/python3 1503 | 1504 | import xml.etree.ElementTree as ET 1505 | import csv 1506 | import os 1507 | 1508 | 1509 | def main(): 1510 | # Cipher Risk Lists 1511 | ciphers_list = [] 1512 | flagged_ciphers = '' 1513 | 1514 | # Path to directory with host XML files 1515 | in_path= '/home/tristram/Scans/Stage_5/' 1516 | for file in os.listdir(in_path): 1517 | if file.endswith(".xml"): 1518 | # Load XML 1519 | in_xml = os.path.join(in_path, file) 1520 | xml_tree = ET.parse(in_xml) 1521 | xml_root = xml_tree.getroot() 1522 | 1523 | # Cycle through each host 1524 | for host in xml_root.findall('host'): 1525 | ip = host.find('address').get('addr') 1526 | ports_element = host.findall('ports') 1527 | port_element = ports_element[0].findall('port') 1528 | 1529 | # Cycle through every port 1530 | for scanned_port in port_element: 1531 | port_id = scanned_port.get('portid') 1532 | script_element = scanned_port.find('script') 1533 | if script_element: 1534 | script_element = script_element.findall('table') 1535 | 1536 | # Cycle through script element 1537 | for tls_protocol in script_element: 1538 | 1539 | # Cycle through TLS protocol 1540 | for protocol in tls_protocol: 1541 | if protocol.attrib.get('key') == 'ciphers': 1542 | 1543 | # Cycle through each cipher 1544 | for entry in protocol: 1545 | for en in entry: 1546 | if en.attrib.get('key') == 'name': 1547 | name = en.text 1548 | if en.attrib.get('key') == 'strength': 1549 | # Check for targeted cipher 1550 | if '3DES' in name: 1551 | flagged_ciphers += name + ',' 1552 | 1553 | # Stage flagged data for current host 1554 | if flagged_ciphers: 1555 | flagged_ciphers = list(set(flagged_ciphers.strip(',').split(','))) 1556 | ciphers_list.append([ip,port_id,flagged_ciphers]) 1557 | 1558 | # Reset results for next host 1559 | flagged_ciphers = '' 1560 | 1561 | # Create NULL Cipher Report 1562 | with open('detected_3des_ciphers.csv', 'w') as file: 1563 | writer = csv.writer(file) 1564 | 1565 | # CSV Headers 1566 | writer.writerow(["IP", "Port","Cipher Suite"]) 1567 | for entry in ciphers_list: 1568 | row_ip = entry[0] 1569 | row_port = entry[1] 1570 | row_cs = '\r\n'.join(entry[2]) 1571 | 1572 | # Write results to row 1573 | writer.writerow([row_ip,row_port,row_cs]) 1574 | 1575 | 1576 | if __name__ == '__main__': 1577 | main() 1578 | ``` 1579 | 1580 | #### Detected RC4 Ciphers 1581 | 1582 | | IP | Port| Cipher Suite 1583 | | :--- |:--- |:--- | 1584 | |192.168.0.148|443|"TLS_RSA_WITH_RC4_128_MD5 1585 | | ||TLS_RSA_WITH_RC4_128_SHA" 1586 | |192.168.0.149|443|"TLS_RSA_EXPORT1024_WITH_RC4_56_SHA 1587 | | ||TLS_RSA_WITH_RC4_128_MD5 1588 | | ||TLS_RSA_WITH_RC4_128_SHA 1589 | | ||TLS_RSA_EXPORT1024_WITH_RC4_56_MD5 1590 | | ||TLS_RSA_EXPORT_WITH_RC4_40_MD5" 1591 | 1592 | ```PYTHON 1593 | #!/usr/bin/python3 1594 | 1595 | import xml.etree.ElementTree as ET 1596 | import csv 1597 | import os 1598 | 1599 | 1600 | def main(): 1601 | # Cipher Risk Lists 1602 | ciphers_list = [] 1603 | flagged_ciphers = '' 1604 | 1605 | # Path to directory with host XML files 1606 | in_path= '/home/tristram/Scans/Stage_5/' 1607 | for file in os.listdir(in_path): 1608 | if file.endswith(".xml"): 1609 | # Load XML 1610 | in_xml = os.path.join(in_path, file) 1611 | xml_tree = ET.parse(in_xml) 1612 | xml_root = xml_tree.getroot() 1613 | 1614 | # Cycle through each host 1615 | for host in xml_root.findall('host'): 1616 | ip = host.find('address').get('addr') 1617 | ports_element = host.findall('ports') 1618 | port_element = ports_element[0].findall('port') 1619 | 1620 | # Cycle through every port 1621 | for scanned_port in port_element: 1622 | port_id = scanned_port.get('portid') 1623 | script_element = scanned_port.find('script') 1624 | if script_element: 1625 | script_element = script_element.findall('table') 1626 | # Cycle through script element 1627 | for tls_protocol in script_element: 1628 | 1629 | # Cycle through TLS protocol 1630 | for protocol in tls_protocol: 1631 | if protocol.attrib.get('key') == 'ciphers': 1632 | 1633 | # Cycle through each cipher 1634 | for entry in protocol: 1635 | for en in entry: 1636 | if en.attrib.get('key') == 'name': 1637 | name = en.text 1638 | if en.attrib.get('key') == 'strength': 1639 | # Check for targeted cipher 1640 | if 'RC4' in name: 1641 | flagged_ciphers += name + ',' 1642 | 1643 | # Stage flagged data for current host 1644 | if flagged_ciphers: 1645 | flagged_ciphers = list(set(flagged_ciphers.strip(',').split(','))) 1646 | ciphers_list.append([ip,port_id,flagged_ciphers]) 1647 | 1648 | # Reset results for next host 1649 | flagged_ciphers = '' 1650 | 1651 | # Create NULL Cipher Report 1652 | with open('detected_rc4_ciphers.csv', 'w') as file: 1653 | writer = csv.writer(file) 1654 | 1655 | # CSV Headers 1656 | writer.writerow(["IP", "Port","Cipher Suite"]) 1657 | for entry in ciphers_list: 1658 | row_ip = entry[0] 1659 | row_port = entry[1] 1660 | row_cs = '\r\n'.join(entry[2]) 1661 | 1662 | # Write results to row 1663 | writer.writerow([row_ip,row_port,row_cs]) 1664 | 1665 | 1666 | if __name__ == '__main__': 1667 | main() 1668 | ``` 1669 | 1670 | ## Wrapping Up 1671 | 1672 | There was a lot of information presented here as well as a lot of Python code. It is my hope that you found it useful and perhaps sparked some inspirational fires for you to think about designing your own enumeration tools or other automated workflows. I invite you to look at your own processes and see if the information you have learned here can be used to help enhance your own processes. 1673 | 1674 | Tristram 1675 | 1676 | -------------------------------------------------------------------------------- /Report Scripts/report-3des-ciphers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import csv 5 | import os 6 | 7 | 8 | def main(): 9 | # Cipher Risk Lists 10 | ciphers_list = [] 11 | flagged_ciphers = '' 12 | 13 | # Path to directory with host XML files 14 | in_path= '/home/tristram/Downloads/OffSec-master/External/Stage_5/' 15 | for file in os.listdir(in_path): 16 | if file.endswith(".xml"): 17 | # Load XML 18 | in_xml = os.path.join(in_path, file) 19 | xml_tree = ET.parse(in_xml) 20 | xml_root = xml_tree.getroot() 21 | 22 | # Cycle through each host 23 | for host in xml_root.findall('host'): 24 | ip = host.find('address').get('addr') 25 | ports_element = host.findall('ports') 26 | port_element = ports_element[0].findall('port') 27 | 28 | # Cycle through every port 29 | for scanned_port in port_element: 30 | port_id = scanned_port.get('portid') 31 | script_element = scanned_port.find('script') 32 | if script_element: 33 | script_element = script_element.findall('table') 34 | 35 | # Cycle through script element 36 | for tls_protocol in script_element: 37 | 38 | # Cycle through TLS protocol 39 | for protocol in tls_protocol: 40 | if protocol.attrib.get('key') == 'ciphers': 41 | 42 | # Cycle through each cipher 43 | for entry in protocol: 44 | for en in entry: 45 | if en.attrib.get('key') == 'name': 46 | name = en.text 47 | if en.attrib.get('key') == 'strength': 48 | # Check for targeted cipher 49 | if '3DES' in name: 50 | flagged_ciphers += name + ',' 51 | 52 | # Stage flagged data for current host 53 | if flagged_ciphers: 54 | flagged_ciphers = list(set(flagged_ciphers.strip(',').split(','))) 55 | ciphers_list.append([ip,port_id,flagged_ciphers]) 56 | 57 | # Reset results for next host 58 | flagged_ciphers = '' 59 | 60 | # Create NULL Cipher Report 61 | with open('detected_3des_ciphers.csv', 'w') as file: 62 | writer = csv.writer(file) 63 | 64 | # CSV Headers 65 | writer.writerow(["IP", "Port","Cipher Suite"]) 66 | for entry in ciphers_list: 67 | row_ip = entry[0] 68 | row_port = entry[1] 69 | row_cs = '\r\n'.join(entry[2]) 70 | 71 | # Write results to row 72 | writer.writerow([row_ip,row_port,row_cs]) 73 | 74 | 75 | if __name__ == '__main__': 76 | main() -------------------------------------------------------------------------------- /Report Scripts/report-all-ciphers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import csv 5 | import os 6 | 7 | 8 | def main(): 9 | # Cipher Risk Lists 10 | all_discovered_ciphers = [] 11 | ciphers_list = [] 12 | flagged_ciphers = '' 13 | 14 | # Path to directory with host XML files 15 | in_path= '/home/tristram/Downloads/OffSec-master/External/Stage_5/' 16 | for file in os.listdir(in_path): 17 | if file.endswith(".xml"): 18 | # Load XML 19 | in_xml = os.path.join(in_path, file) 20 | xml_tree = ET.parse(in_xml) 21 | xml_root = xml_tree.getroot() 22 | 23 | # Cycle through each host 24 | for host in xml_root.findall('host'): 25 | ip = host.find('address').get('addr') 26 | ports_element = host.findall('ports') 27 | port_element = ports_element[0].findall('port') 28 | 29 | # Cycle through every port 30 | for scanned_port in port_element: 31 | port_id = scanned_port.get('portid') 32 | script_element = scanned_port.find('script') 33 | if script_element: 34 | script_element = script_element.findall('table') 35 | 36 | # Cycle through script element 37 | for tls_protocol in script_element: 38 | protocol_version = tls_protocol.attrib['key'] 39 | 40 | # Cycle through TLS protocol 41 | for protocol in tls_protocol: 42 | if protocol.attrib.get('key') == 'ciphers': 43 | 44 | # Cycle through each cipher 45 | for entry in protocol: 46 | for en in entry: 47 | if en.attrib.get('key') == 'name': 48 | name = en.text 49 | if en.attrib.get('key') == 'strength': 50 | grade = en.text 51 | # Check for targeted cipher 52 | all_discovered_ciphers.append([ip, protocol_version, port_id, grade, name]) 53 | 54 | # Stage flagged data for current host 55 | if flagged_ciphers: 56 | flagged_ciphers = list(set(flagged_ciphers.strip(',').split(','))) 57 | ciphers_list.append([ip,port_id,flagged_ciphers]) 58 | 59 | # Reset results for next host 60 | flagged_ciphers = '' 61 | 62 | # Create All Discovered Ciphers Report 63 | with open('all_discovered_ciphers.csv', 'w') as file: 64 | writer = csv.writer(file) 65 | 66 | # CSV Headers 67 | writer.writerow(["IP", "Protocol","Port","Grade","Cipher Suite"]) 68 | for entry in all_discovered_ciphers: 69 | row_ip = entry[0] 70 | row_protocol = entry[1] 71 | row_port = entry[2] 72 | row_grade = entry[3] 73 | row_cs = entry[4] 74 | 75 | # Write results to row 76 | writer.writerow([row_ip,row_protocol,row_port,row_grade,row_cs]) 77 | 78 | if __name__ == '__main__': 79 | main() -------------------------------------------------------------------------------- /Report Scripts/report-anon-ciphers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import csv 5 | import os 6 | 7 | 8 | def main(): 9 | # Cipher Risk Lists 10 | ciphers_list = [] 11 | flagged_ciphers = '' 12 | 13 | # Path to directory with host XML files 14 | in_path= '/home/tristram/Downloads/OffSec-master/External/Stage_5/' 15 | for file in os.listdir(in_path): 16 | if file.endswith(".xml"): 17 | # Load XML 18 | in_xml = os.path.join(in_path, file) 19 | xml_tree = ET.parse(in_xml) 20 | xml_root = xml_tree.getroot() 21 | 22 | # Cycle through each host 23 | for host in xml_root.findall('host'): 24 | ip = host.find('address').get('addr') 25 | ports_element = host.findall('ports') 26 | port_element = ports_element[0].findall('port') 27 | 28 | # Cycle through every port 29 | for scanned_port in port_element: 30 | port_id = scanned_port.get('portid') 31 | script_element = scanned_port.find('script') 32 | if script_element: 33 | script_element = script_element.findall('table') 34 | 35 | # Cycle through script element 36 | for tls_protocol in script_element: 37 | 38 | # Cycle through TLS protocol 39 | for protocol in tls_protocol: 40 | if protocol.attrib.get('key') == 'ciphers': 41 | 42 | # Cycle through each cipher 43 | for entry in protocol: 44 | for en in entry: 45 | if en.attrib.get('key') == 'name': 46 | name = en.text 47 | if en.attrib.get('key') == 'strength': 48 | # Check for targeted cipher 49 | if 'anon' in name: 50 | flagged_ciphers += name + ',' 51 | 52 | # Stage flagged data for current host 53 | if flagged_ciphers: 54 | flagged_ciphers = list(set(flagged_ciphers.strip(',').split(','))) 55 | ciphers_list.append([ip,port_id,flagged_ciphers]) 56 | 57 | # Reset results for next host 58 | flagged_ciphers = '' 59 | 60 | # Create NULL Cipher Report 61 | with open('detected_anon_ciphers.csv', 'w') as file: 62 | writer = csv.writer(file) 63 | 64 | # CSV Headers 65 | writer.writerow(["IP", "Port","Cipher Suite"]) 66 | for entry in ciphers_list: 67 | row_ip = entry[0] 68 | row_port = entry[1] 69 | row_cs = '\r\n'.join(entry[2]) 70 | 71 | # Write results to row 72 | writer.writerow([row_ip,row_port,row_cs]) 73 | 74 | 75 | if __name__ == '__main__': 76 | main() -------------------------------------------------------------------------------- /Report Scripts/report-cipher-risk-grades.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import csv 5 | import os 6 | 7 | 8 | def main(): 9 | # Cipher Risk Lists 10 | ciphers_list = [] 11 | flagged_ciphers = '' 12 | 13 | # Grade Threshold Lists 14 | high_risk_grades = ['D','E','F'] 15 | moderate_risk_grades = ['C'] 16 | 17 | high_risk_ciphers = [] 18 | moderate_risk_ciphers = [] 19 | 20 | high_risk_flagged_list = '' 21 | moderate_risk_flagged_list = '' 22 | 23 | # Path to directory with host XML files 24 | in_path= '/home/tristram/Downloads/OffSec-master/External/Stage_5/' 25 | for file in os.listdir(in_path): 26 | if file.endswith(".xml"): 27 | # Load XML 28 | in_xml = os.path.join(in_path, file) 29 | xml_tree = ET.parse(in_xml) 30 | xml_root = xml_tree.getroot() 31 | 32 | # Cycle through each host 33 | for host in xml_root.findall('host'): 34 | ip = host.find('address').get('addr') 35 | ports_element = host.findall('ports') 36 | port_element = ports_element[0].findall('port') 37 | 38 | # Cycle through every port 39 | for scanned_port in port_element: 40 | port_id = scanned_port.get('portid') 41 | script_element = scanned_port.find('script') 42 | if script_element: 43 | script_element = script_element.findall('table') 44 | 45 | # Cycle through script element 46 | for tls_protocol in script_element: 47 | 48 | # Cycle through TLS protocol 49 | for protocol in tls_protocol: 50 | if protocol.attrib.get('key') == 'ciphers': 51 | 52 | # Cycle through each cipher 53 | for entry in protocol: 54 | for en in entry: 55 | if en.attrib.get('key') == 'name': 56 | name = en.text 57 | if en.attrib.get('key') == 'strength': 58 | grade = en.text 59 | # Risk based on grade 60 | if grade in high_risk_grades: 61 | high_risk_flagged_list += f"{name} ({grade})" + ',' 62 | if grade in moderate_risk_grades: 63 | moderate_risk_flagged_list += f"{name} ({grade})" + ',' 64 | 65 | # Stage flagged data for current host 66 | if high_risk_flagged_list: 67 | high_risk_flagged_list = list(set(high_risk_flagged_list.strip(',').split(','))) 68 | high_risk_ciphers.append([ip,port_id,high_risk_flagged_list]) 69 | 70 | if moderate_risk_flagged_list: 71 | moderate_risk_flagged_list = list(set(moderate_risk_flagged_list.strip(',').split(','))) 72 | moderate_risk_ciphers.append([ip,port_id,moderate_risk_flagged_list]) 73 | 74 | # Reset results for next host 75 | high_risk_flagged_list = '' 76 | moderate_risk_flagged_list = '' 77 | 78 | # Create High Risk Report 79 | with open('high_risk_tls_ciphers.csv', 'w') as file: 80 | writer = csv.writer(file) 81 | 82 | # CSV Headers 83 | writer.writerow(["IP", "Port","Cipher Suite"]) 84 | for hrc in high_risk_ciphers: 85 | row_ip = hrc[0] 86 | row_port = hrc[1] 87 | row_cs = '\r\n'.join(hrc[2]) 88 | 89 | # Write results to row 90 | writer.writerow([row_ip,row_port,row_cs]) 91 | 92 | # Create Moderate Risk Report 93 | with open('moderate_risk_tls_ciphers.csv', 'w') as file: 94 | writer = csv.writer(file) 95 | 96 | # CSV Headers 97 | writer.writerow(["IP", "Port","Cipher Suite"]) 98 | for mrc in moderate_risk_ciphers: 99 | row_ip = mrc[0] 100 | row_port = mrc[1] 101 | row_cs = '\r\n'.join(mrc[2]) 102 | 103 | # Write results to row 104 | writer.writerow([row_ip,row_port,row_cs]) 105 | 106 | 107 | if __name__ == '__main__': 108 | main() -------------------------------------------------------------------------------- /Report Scripts/report-des-idea-ciphers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import csv 5 | import os 6 | 7 | 8 | def main(): 9 | # Cipher Risk Lists 10 | ciphers_list = [] 11 | flagged_ciphers = '' 12 | 13 | # Path to directory with host XML files 14 | in_path= '/home/tristram/Downloads/OffSec-master/External/Stage_5/' 15 | for file in os.listdir(in_path): 16 | if file.endswith(".xml"): 17 | # Load XML 18 | in_xml = os.path.join(in_path, file) 19 | xml_tree = ET.parse(in_xml) 20 | xml_root = xml_tree.getroot() 21 | 22 | # Cycle through each host 23 | for host in xml_root.findall('host'): 24 | ip = host.find('address').get('addr') 25 | ports_element = host.findall('ports') 26 | port_element = ports_element[0].findall('port') 27 | 28 | # Cycle through every port 29 | for scanned_port in port_element: 30 | port_id = scanned_port.get('portid') 31 | script_element = scanned_port.find('script') 32 | if script_element: 33 | script_element = script_element.findall('table') 34 | 35 | # Cycle through script element 36 | for tls_protocol in script_element: 37 | 38 | # Cycle through TLS protocol 39 | for protocol in tls_protocol: 40 | if protocol.attrib.get('key') == 'ciphers': 41 | 42 | # Cycle through each cipher 43 | for entry in protocol: 44 | for en in entry: 45 | if en.attrib.get('key') == 'name': 46 | name = en.text 47 | if en.attrib.get('key') == 'strength': 48 | # Check for targeted cipher 49 | if ('DES' in name or 'IDEA' in name) and '3DES' not in name: 50 | flagged_ciphers += name + ',' 51 | 52 | # Stage flagged data for current host 53 | if flagged_ciphers: 54 | flagged_ciphers = list(set(flagged_ciphers.strip(',').split(','))) 55 | ciphers_list.append([ip,port_id,flagged_ciphers]) 56 | 57 | # Reset results for next host 58 | flagged_ciphers = '' 59 | 60 | # Create NULL Cipher Report 61 | with open('detected_des_idea_ciphers.csv', 'w') as file: 62 | writer = csv.writer(file) 63 | 64 | # CSV Headers 65 | writer.writerow(["IP", "Port","Cipher Suite"]) 66 | for entry in ciphers_list: 67 | row_ip = entry[0] 68 | row_port = entry[1] 69 | row_cs = '\r\n'.join(entry[2]) 70 | 71 | # Write results to row 72 | writer.writerow([row_ip,row_port,row_cs]) 73 | 74 | 75 | if __name__ == '__main__': 76 | main() -------------------------------------------------------------------------------- /Report Scripts/report-export-ciphers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import csv 5 | import os 6 | 7 | 8 | def main(): 9 | # Cipher Risk Lists 10 | ciphers_list = [] 11 | flagged_ciphers = '' 12 | 13 | # Path to directory with host XML files 14 | in_path= '/home/tristram/Downloads/OffSec-master/External/Stage_5/' 15 | for file in os.listdir(in_path): 16 | if file.endswith(".xml"): 17 | # Load XML 18 | in_xml = os.path.join(in_path, file) 19 | xml_tree = ET.parse(in_xml) 20 | xml_root = xml_tree.getroot() 21 | 22 | # Cycle through each host 23 | for host in xml_root.findall('host'): 24 | ip = host.find('address').get('addr') 25 | ports_element = host.findall('ports') 26 | port_element = ports_element[0].findall('port') 27 | 28 | # Cycle through every port 29 | for scanned_port in port_element: 30 | port_id = scanned_port.get('portid') 31 | script_element = scanned_port.find('script') 32 | if script_element: 33 | script_element = script_element.findall('table') 34 | 35 | # Cycle through script element 36 | for tls_protocol in script_element: 37 | 38 | # Cycle through TLS protocol 39 | for protocol in tls_protocol: 40 | if protocol.attrib.get('key') == 'ciphers': 41 | 42 | # Cycle through each cipher 43 | for entry in protocol: 44 | for en in entry: 45 | if en.attrib.get('key') == 'name': 46 | name = en.text 47 | if en.attrib.get('key') == 'strength': 48 | # Check for targeted cipher 49 | if 'EXPORT' in name: 50 | flagged_ciphers += name + ',' 51 | 52 | # Stage flagged data for current host 53 | if flagged_ciphers: 54 | flagged_ciphers = list(set(flagged_ciphers.strip(',').split(','))) 55 | ciphers_list.append([ip,port_id,flagged_ciphers]) 56 | 57 | # Reset results for next host 58 | flagged_ciphers = '' 59 | 60 | # Create NULL Cipher Report 61 | with open('detected_export_ciphers.csv', 'w') as file: 62 | writer = csv.writer(file) 63 | 64 | # CSV Headers 65 | writer.writerow(["IP", "Port","Cipher Suite"]) 66 | for entry in ciphers_list: 67 | row_ip = entry[0] 68 | row_port = entry[1] 69 | row_cs = '\r\n'.join(entry[2]) 70 | 71 | # Write results to row 72 | writer.writerow([row_ip,row_port,row_cs]) 73 | 74 | 75 | if __name__ == '__main__': 76 | main() -------------------------------------------------------------------------------- /Report Scripts/report-hosts-with-ports.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import csv 5 | import os 6 | 7 | def main(): 8 | # Path to directory with host XML files 9 | in_path = '/home/tristram/Downloads/OffSec-master/External/Stage_3/' 10 | 11 | # CSV Data 12 | with open('detected_hosts_with_ports.csv', 'w') as file: 13 | writer = csv.writer(file) 14 | 15 | # CSV Headers 16 | writer.writerow(['IP', 'Port', 'Service']) 17 | for file in sorted(os.listdir(in_path)): 18 | if file.endswith(".xml"): 19 | if "no_ports.xml" in file: 20 | writer.writerow([file.split('_no_ports.xml')[0], 'no-response', 'no-response']) 21 | else: 22 | # Load Service Scan 23 | in_xml = os.path.join(in_path, file) 24 | xml_tree = ET.parse(in_xml) 25 | xml_root = xml_tree.getroot() 26 | 27 | # Cycle through each host 28 | for host in xml_root.findall('host'): 29 | ip_once = True 30 | ip_address = host.findall('address')[0].attrib['addr'] 31 | ports_element = host.findall('ports') 32 | port_child = ports_element[0].findall('port') 33 | open_ports = [] 34 | 35 | # Within each host cycle through the ports 36 | for port in port_child: 37 | if port.findall('state')[0].attrib['state'] == 'open': 38 | port_id = port.attrib['portid'] 39 | service_name = port.find('service').get('product') 40 | if service_name == None: 41 | service_name = port.find('service').get('name') 42 | open_ports.append([port_id, service_name]) 43 | 44 | # Within each port cycle through the open ports 45 | if len(open_ports): 46 | for op in open_ports: 47 | # Ensure we only notate the IP once to keep it clean 48 | if ip_once == True: 49 | # Write results to row 50 | writer.writerow([ip_address, op[0], op[1]]) 51 | ip_once = False 52 | else: 53 | # Write results to row 54 | writer.writerow([None, op[0], op[1]]) 55 | else: 56 | # Write results to row if none 57 | writer.writerow([ip_address, 'none', 'none']) 58 | 59 | if __name__ == '__main__': 60 | main() -------------------------------------------------------------------------------- /Report Scripts/report-hosts-without-ports.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import csv 5 | 6 | def main(): 7 | # Path to directory with host XML files 8 | in_xml = '/home/tristram/Scans/Stage_2/top_1000_portscan.xml' 9 | 10 | # CSV Data 11 | with open('detected_hosts_no_ports.csv', 'w') as file: 12 | writer = csv.writer(file) 13 | 14 | # CSV Headers 15 | writer.writerow(['IP', 'Port', 'Service']) 16 | 17 | # Load Top 1000 Port Scan 18 | xml_tree = ET.parse(in_xml) 19 | xml_root = xml_tree.getroot() 20 | 21 | # Cycle through each host 22 | for host in xml_root.findall('host'): 23 | ip_address = host.findall('address')[0].attrib['addr'] 24 | ports_element = host.findall('ports') 25 | port_child = ports_element[0].findall('port') 26 | open_ports = [] 27 | 28 | # Within each host cycle through the ports 29 | for port in port_child: 30 | if port.findall('state')[0].attrib['state'] == 'open': 31 | port_id = port.attrib['portid'] 32 | open_ports.append(port_id) 33 | 34 | # Write results to row 35 | if len(open_ports) == 0: 36 | writer.writerow([ip_address, 'no-response', 'no-response']) 37 | 38 | 39 | if __name__ == '__main__': 40 | main() -------------------------------------------------------------------------------- /Report Scripts/report-hosts.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import csv 5 | 6 | def main(): 7 | # File Paths 8 | in_xml_port = '/home/tristram/Scans/Stage_1/tcp_syn_host_discovery.xml' 9 | in_xml_echo = '/home/tristram/Scans/Stage_1/icmp_echo_host_discovery.xml' 10 | in_xml_netmask = '/home/tristram/Scans/Stage_1/icmp_netmask_host_discovery.xml' 11 | in_xml_timestamp = '/home/tristram/Scans/Stage_1/icmp_timestamp_host_discovery.xml' 12 | 13 | # Load Port XML 14 | xml_tree_port = ET.parse(in_xml_port) 15 | xml_root_port = xml_tree_port.getroot() 16 | 17 | # Load ICMP Echo XML 18 | xml_tree_echo = ET.parse(in_xml_echo) 19 | xml_root_echo = xml_tree_echo.getroot() 20 | 21 | # Load ICMP Netmask XML 22 | xml_tree_netmask = ET.parse(in_xml_netmask) 23 | xml_root_netmask = xml_tree_netmask.getroot() 24 | 25 | # Load ICMP Timestamp XML 26 | xml_tree_timestamp = ET.parse(in_xml_timestamp) 27 | xml_root_timestamp = xml_tree_timestamp.getroot() 28 | 29 | # CSV File 30 | with open('detected_hosts.csv', 'w') as file: 31 | writer = csv.writer(file) 32 | # CSV Headers 33 | writer.writerow(['IP', 'Status', 'ICMP Echo', 'ICMP Netmask', 'ICMP Timestamp', 'Port']) 34 | 35 | # Load SYN Port XML 36 | for host in xml_root_port.findall('host'): 37 | host_status = 'down' 38 | master_ip = host.find('address').get('addr') 39 | port_state = host.find('status').get('state') 40 | port_reason = host.find('status').get('reason') 41 | 42 | # Load ICMP Echo XML 43 | for host in xml_root_echo.findall('host'): 44 | echo_ip = host.find('address').get('addr') 45 | echo_state = host.find('status').get('state') 46 | echo_reason = host.find('status').get('reason') 47 | 48 | # Load ICMP Netmask 49 | if master_ip == echo_ip: 50 | for host in xml_root_netmask.findall('host'): 51 | netmask_ip = host.find('address').get('addr') 52 | netmask_state = host.find('status').get('state') 53 | netmask_reason = host.find('status').get('reason') 54 | 55 | # Load ICMP Timestamp 56 | if master_ip == netmask_ip: 57 | for host in xml_root_timestamp.findall('host'): 58 | timestamp_ip = host.find('address').get('addr') 59 | timestamp_state = host.find('status').get('state') 60 | timestamp_reason = host.find('status').get('reason') 61 | if master_ip == timestamp_ip: 62 | if port_state == 'up' or echo_state == 'up' or netmask_state == 'up' or timestamp_state == 'up': 63 | host_status = 'up' 64 | 65 | # Write results to row 66 | writer.writerow([master_ip, host_status, echo_reason, netmask_reason, timestamp_reason, port_reason]) 67 | 68 | if __name__ == '__main__': 69 | main() -------------------------------------------------------------------------------- /Report Scripts/report-null-ciphers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import csv 5 | import os 6 | 7 | 8 | def main(): 9 | # Cipher Risk Lists 10 | ciphers_list = [] 11 | flagged_ciphers = '' 12 | 13 | # Path to directory with host XML files 14 | in_path= '/home/tristram/Downloads/OffSec-master/External/Stage_5/' 15 | for file in os.listdir(in_path): 16 | if file.endswith(".xml"): 17 | # Load XML 18 | in_xml = os.path.join(in_path, file) 19 | xml_tree = ET.parse(in_xml) 20 | xml_root = xml_tree.getroot() 21 | 22 | # Cycle through each host 23 | for host in xml_root.findall('host'): 24 | ip = host.find('address').get('addr') 25 | ports_element = host.findall('ports') 26 | port_element = ports_element[0].findall('port') 27 | 28 | # Cycle through every port 29 | for scanned_port in port_element: 30 | port_id = scanned_port.get('portid') 31 | script_element = scanned_port.find('script') 32 | if script_element: 33 | script_element = script_element.findall('table') 34 | 35 | # Cycle through script element 36 | for tls_protocol in script_element: 37 | 38 | # Cycle through TLS protocol 39 | for protocol in tls_protocol: 40 | if protocol.attrib.get('key') == 'ciphers': 41 | 42 | # Cycle through each cipher 43 | for entry in protocol: 44 | for en in entry: 45 | if en.attrib.get('key') == 'name': 46 | name = en.text 47 | if en.attrib.get('key') == 'strength': 48 | # Check for targeted cipher 49 | if 'null' in name: 50 | flagged_ciphers += name + ',' 51 | 52 | # Stage flagged data for current host 53 | if flagged_ciphers: 54 | flagged_ciphers = list(set(flagged_ciphers.strip(',').split(','))) 55 | ciphers_list.append([ip,port_id,flagged_ciphers]) 56 | 57 | # Reset results for next host 58 | flagged_ciphers = '' 59 | 60 | # Create NULL Cipher Report 61 | with open('detected_null_ciphers.csv', 'w') as file: 62 | writer = csv.writer(file) 63 | 64 | # CSV Headers 65 | writer.writerow(["IP", "Port","Cipher Suite"]) 66 | for entry in ciphers_list: 67 | row_ip = entry[0] 68 | row_port = entry[1] 69 | row_cs = '\r\n'.join(entry[2]) 70 | 71 | # Write results to row 72 | writer.writerow([row_ip,row_port,row_cs]) 73 | 74 | 75 | if __name__ == '__main__': 76 | main() -------------------------------------------------------------------------------- /Report Scripts/report-operating-system.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import csv 5 | 6 | def main(): 7 | # Path top the os scan file 8 | in_xml = '/home/tristram/Scans/Stage_4/osdetection.xml' 9 | 10 | # CSV Data 11 | with open('detected_hosts_os.csv', 'w') as file: 12 | writer = csv.writer(file) 13 | # CSV Headers 14 | writer.writerow(['IP', 'OperatingSystem']) 15 | 16 | # Load OS Scan XML 17 | xml_tree = ET.parse(in_xml) 18 | xml_root = xml_tree.getroot() 19 | 20 | # Cycle through each host 21 | for host in xml_root.findall('host'): 22 | ip_address = host.findall('address')[0].attrib['addr'] 23 | try: 24 | os_element = host.findall('os') 25 | os_name = os_element[0].findall('osmatch')[0].attrib['name'] 26 | except IndexError: 27 | os_name = 'Unknown' 28 | 29 | # Write results to row 30 | writer.writerow([ip_address, os_name]) 31 | 32 | 33 | if __name__ == '__main__': 34 | main() -------------------------------------------------------------------------------- /Report Scripts/report-rc4-ciphers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import csv 5 | import os 6 | 7 | 8 | def main(): 9 | # Cipher Risk Lists 10 | ciphers_list = [] 11 | flagged_ciphers = '' 12 | 13 | # Path to directory with host XML files 14 | in_path= '/home/tristram/Downloads/OffSec-master/External/Stage_5/' 15 | for file in os.listdir(in_path): 16 | if file.endswith(".xml"): 17 | # Load XML 18 | in_xml = os.path.join(in_path, file) 19 | xml_tree = ET.parse(in_xml) 20 | xml_root = xml_tree.getroot() 21 | 22 | # Cycle through each host 23 | for host in xml_root.findall('host'): 24 | ip = host.find('address').get('addr') 25 | ports_element = host.findall('ports') 26 | port_element = ports_element[0].findall('port') 27 | 28 | # Cycle through every port 29 | for scanned_port in port_element: 30 | port_id = scanned_port.get('portid') 31 | script_element = scanned_port.find('script') 32 | if script_element: 33 | script_element = script_element.findall('table') 34 | # Cycle through script element 35 | for tls_protocol in script_element: 36 | 37 | # Cycle through TLS protocol 38 | for protocol in tls_protocol: 39 | if protocol.attrib.get('key') == 'ciphers': 40 | 41 | # Cycle through each cipher 42 | for entry in protocol: 43 | for en in entry: 44 | if en.attrib.get('key') == 'name': 45 | name = en.text 46 | if en.attrib.get('key') == 'strength': 47 | # Check for targeted cipher 48 | if 'RC4' in name: 49 | flagged_ciphers += name + ',' 50 | 51 | # Stage flagged data for current host 52 | if flagged_ciphers: 53 | flagged_ciphers = list(set(flagged_ciphers.strip(',').split(','))) 54 | ciphers_list.append([ip,port_id,flagged_ciphers]) 55 | 56 | # Reset results for next host 57 | flagged_ciphers = '' 58 | 59 | # Create NULL Cipher Report 60 | with open('detected_rc4_ciphers.csv', 'w') as file: 61 | writer = csv.writer(file) 62 | 63 | # CSV Headers 64 | writer.writerow(["IP", "Port","Cipher Suite"]) 65 | for entry in ciphers_list: 66 | row_ip = entry[0] 67 | row_port = entry[1] 68 | row_cs = '\r\n'.join(entry[2]) 69 | 70 | # Write results to row 71 | writer.writerow([row_ip,row_port,row_cs]) 72 | 73 | 74 | if __name__ == '__main__': 75 | main() -------------------------------------------------------------------------------- /Report Scripts/report-ssl-certs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import csv 5 | import os 6 | import re 7 | 8 | 9 | def main(): 10 | # Regular Expressions 11 | reg_date = r'\d{4}-\d{2}-\d{2}' 12 | 13 | # File Path 14 | in_path= '/home/tristram/Scans/Stage_6/' 15 | 16 | # Reports 17 | cert_info_list = '' 18 | cert_info_report = [] 19 | 20 | # Cycle through each XML file 21 | for file in os.listdir(in_path): 22 | if file.endswith(".xml"): 23 | # Load XML 24 | in_xml = os.path.join(in_path, file) 25 | xml_tree = ET.parse(in_xml) 26 | xml_root = xml_tree.getroot() 27 | 28 | # Cycle through each host 29 | for host in xml_root.findall('host'): 30 | ip = host.find('address').get('addr') 31 | ports_element = host.findall('ports') 32 | port_element = ports_element[0].findall('port') 33 | 34 | # Check Every Port 35 | for scanned_port in port_element: 36 | port_id = scanned_port.get('portid') 37 | script_element = scanned_port.find('script') 38 | 39 | # SSL Cert Top Level 40 | if script_element: 41 | ssl_element = script_element.findall('table') 42 | 43 | # Cycle through each certificate 44 | for ssl in ssl_element: 45 | # Subject Field 46 | if ssl.attrib.get('key') == 'subject': 47 | for data in ssl: 48 | if data.attrib.get('key') == 'commonName': 49 | host_common_name = data.text 50 | # Issuer Field 51 | if ssl.attrib.get('key') == 'issuer': 52 | for data in ssl: 53 | if data.attrib.get('key') == 'commonName': 54 | issuer_common_name = data.text 55 | 56 | # Validity Field 57 | if ssl.attrib.get('key') == 'validity': 58 | for data in ssl: 59 | if data.attrib.get('key') == 'notBefore': 60 | cert_start = data.text 61 | cert_start = re.findall(reg_date, cert_start)[0] 62 | if data.attrib.get('key') == 'notAfter': 63 | cert_end = data.text 64 | cert_end = re.findall(reg_date, cert_end)[0] 65 | cert_info_list = f"{ip},{port_id},{host_common_name},{issuer_common_name},{cert_start},{cert_end}" 66 | 67 | # Load Data 68 | cert_info_list = cert_info_list.split(',') 69 | cert_info_report.append(cert_info_list) 70 | 71 | # Reset results for next host 72 | cert_info_list = '' 73 | 74 | # CSV Data 75 | with open('detected_ssl_certs.csv', 'w') as csvFile: 76 | writer = csv.writer(csvFile) 77 | 78 | # CSV Headers 79 | writer.writerow(["IP", "Port","CommonName","IssuerCommon","CertStart", "CertEnd"]) 80 | for ci in cert_info_report: 81 | if len(ci) == 6: 82 | row_ip = ci[0] 83 | row_port = ci[1] 84 | row_cn = ci[2] 85 | row_ion = ci[3] 86 | row_cs = ci[4] 87 | row_ce = ci[5] 88 | # Write results to row 89 | writer.writerow([row_ip,row_port,row_cn, row_ion, row_cs, row_ce]) 90 | 91 | 92 | if __name__ == '__main__': 93 | main() -------------------------------------------------------------------------------- /Report Scripts/report-static-key-ciphers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import csv 5 | import os 6 | 7 | 8 | def main(): 9 | # Cipher Risk Lists 10 | ciphers_list = [] 11 | flagged_ciphers = '' 12 | 13 | # Static Key Ciphers 14 | static_key_list = ['TLS_RSA_WITH_DES_CBC_SHA', 'TLS_DH_anon_WITH_AES_128_GCM_SHA256', 'TLS_DH_anon_WITH_AES_128_CBC_SHA', 'TLS_RSA_EXPORT_WITH_DES40_CBC_SHA', 'TLS_RSA_WITH_AES_128_CBC_SHA256', 'TLS_RSA_WITH_3DES_EDE_CBC_SHA', 'TLS_ECDH_anon_WITH_RC4_128_SHA', 'TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA', 'TLS_ECDH_anon_WITH_AES_128_CBC_SHA', 'TLS_DH_anon_WITH_DES_CBC_SHA', 'TLS_DH_anon_WITH_AES_256_CBC_SHA256', 'TLS_RSA_WITH_CAMELLIA_128_CBC_SHA', 'TLS_RSA_WITH_SEED_CBC_SHA', 'TLS_ECDH_anon_WITH_AES_256_CBC_SHA', 'TLS_RSA_WITH_AES_256_GCM_SHA384', 'TLS_DH_anon_EXPORT_WITH_RC4_40_MD5', 'TLS_RSA_WITH_NULL_MD5', 'TLS_DH_anon_WITH_RC4_128_MD5', 'TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA', 'TLS_RSA_WITH_NULL_SHA', 'TLS_DH_anon_WITH_SEED_CBC_SHA', 'TLS_DH_anon_WITH_3DES_EDE_CBC_SHA', 'TLS_DH_anon_WITH_AES_256_GCM_SHA384', 'TLS_RSA_WITH_IDEA_CBC_SHA', 'TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA', 'TLS_DH_anon_WITH_AES_128_CBC_SHA256', 'TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5', 'TLS_RSA_WITH_RC4_128_SHA', 'TLS_DH_anon_WITH_AES_256_CBC_SHA', 'TLS_RSA_WITH_AES_256_CBC_SHA', 'TLS_RSA_WITH_AES_128_CBC_SHA', 'TLS_RSA_WITH_RC4_128_MD5', 'TLS_RSA_WITH_AES_128_GCM_SHA256', 'TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA', 'TLS_RSA_EXPORT1024_WITH_RC4_56_SHA', 15 | 'TLS_RSA_WITH_AES_256_CBC_SHA256', 'TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA', 'TLS_RSA_WITH_CAMELLIA_256_CBC_SHA', 'TLS_RSA_EXPORT_WITH_RC4_40_MD5'] 16 | 17 | # Path to directory with host XML files 18 | in_path= '/home/tristram/Scans/Stage_5/' 19 | for file in os.listdir(in_path): 20 | if file.endswith(".xml"): 21 | # Load XML 22 | in_xml = os.path.join(in_path, file) 23 | xml_tree = ET.parse(in_xml) 24 | xml_root = xml_tree.getroot() 25 | 26 | # Cycle through each host 27 | for host in xml_root.findall('host'): 28 | ip = host.find('address').get('addr') 29 | ports_element = host.findall('ports') 30 | port_element = ports_element[0].findall('port') 31 | 32 | # Cycle through every port 33 | for scanned_port in port_element: 34 | port_id = scanned_port.get('portid') 35 | script_element = scanned_port.find('script') 36 | if script_element: 37 | script_element = script_element.findall('table') 38 | 39 | # Cycle through script element 40 | for tls_protocol in script_element: 41 | 42 | # Cycle through TLS protocol 43 | for protocol in tls_protocol: 44 | if protocol.attrib.get('key') == 'ciphers': 45 | 46 | # Cycle through each cipher 47 | for entry in protocol: 48 | for en in entry: 49 | if en.attrib.get('key') == 'name': 50 | name = en.text 51 | if en.attrib.get('key') == 'strength': 52 | # Check for targeted cipher 53 | if name in static_key_list: 54 | flagged_ciphers += name + ',' 55 | 56 | # Stage flagged data for current host 57 | if flagged_ciphers: 58 | flagged_ciphers = list(set(flagged_ciphers.strip(',').split(','))) 59 | ciphers_list.append([ip,port_id,flagged_ciphers]) 60 | 61 | # Reset results for next host 62 | flagged_ciphers = '' 63 | 64 | # Create NULL Cipher Report 65 | with open('detected_static_key_ciphers.csv', 'w') as file: 66 | writer = csv.writer(file) 67 | 68 | # CSV Headers 69 | writer.writerow(["IP", "Port","Cipher Suite"]) 70 | for entry in ciphers_list: 71 | row_ip = entry[0] 72 | row_port = entry[1] 73 | row_cs = '\r\n'.join(entry[2]) 74 | 75 | # Write results to row 76 | writer.writerow([row_ip,row_port,row_cs]) 77 | 78 | 79 | if __name__ == '__main__': 80 | main() -------------------------------------------------------------------------------- /Report Scripts/report-sweet32-vuln-ciphers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import csv 5 | import os 6 | 7 | 8 | def main(): 9 | # Cipher Risk Lists 10 | ciphers_list = [] 11 | flagged_ciphers = '' 12 | 13 | # Path to directory with host XML files 14 | in_path= '/home/tristram/Scans/Stage_5/' 15 | for file in os.listdir(in_path): 16 | if file.endswith(".xml"): 17 | # Load XML 18 | in_xml = os.path.join(in_path, file) 19 | xml_tree = ET.parse(in_xml) 20 | xml_root = xml_tree.getroot() 21 | 22 | # Cycle through each host 23 | for host in xml_root.findall('host'): 24 | ip = host.find('address').get('addr') 25 | ports_element = host.findall('ports') 26 | port_element = ports_element[0].findall('port') 27 | 28 | # Cycle through every port 29 | for scanned_port in port_element: 30 | port_id = scanned_port.get('portid') 31 | script_element = scanned_port.find('script') 32 | if script_element: 33 | script_element = script_element.findall('table') 34 | 35 | # Cycle through script element 36 | for tls_protocol in script_element: 37 | 38 | # Cycle through TLS protocol 39 | for protocol in tls_protocol: 40 | if protocol.attrib.get('key') == 'ciphers': 41 | 42 | # Cycle through each cipher 43 | for entry in protocol: 44 | for en in entry: 45 | if en.attrib.get('key') == 'name': 46 | name = en.text 47 | if en.attrib.get('key') == 'strength': 48 | # Check for targeted cipher 49 | if '3DES' in name or 'DES' in name or 'DES40' in name or 'RC2' in name: 50 | flagged_ciphers += name + ',' 51 | 52 | # Stage flagged data for current host 53 | if flagged_ciphers: 54 | flagged_ciphers = list(set(flagged_ciphers.strip(',').split(','))) 55 | ciphers_list.append([ip,port_id,flagged_ciphers]) 56 | 57 | # Reset results for next host 58 | flagged_ciphers = '' 59 | 60 | # Create NULL Cipher Report 61 | with open('detected_sweet32_vuln_ciphers.csv', 'w') as file: 62 | writer = csv.writer(file) 63 | 64 | # CSV Headers 65 | writer.writerow(["IP", "Port","Cipher Suite"]) 66 | for entry in ciphers_list: 67 | row_ip = entry[0] 68 | row_port = entry[1] 69 | row_cs = '\r\n'.join(entry[2]) 70 | 71 | # Write results to row 72 | writer.writerow([row_ip,row_port,row_cs]) 73 | 74 | 75 | if __name__ == '__main__': 76 | main() -------------------------------------------------------------------------------- /Report Scripts/report-tls-protocols.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import csv 5 | import os 6 | 7 | 8 | def main(): 9 | # Protocol Report Lists 10 | tls_v10_report = [] 11 | tls_v11_report = [] 12 | ssl_v3_report = [] 13 | 14 | # Flagged Lists 15 | flagged_tls_v10 = '' 16 | flagged_tls_v11 = '' 17 | flagged_ssl_v3 = '' 18 | 19 | # File Path 20 | in_path= '/home/tristram/Scans/Stage_5/' 21 | 22 | # Cycle through each XML file 23 | for file in os.listdir(in_path): 24 | # Load each XML file 25 | if file.endswith(".xml"): 26 | in_xml = os.path.join(in_path, file) 27 | xml_tree = ET.parse(in_xml) 28 | xml_root = xml_tree.getroot() 29 | 30 | # Cycle through each host 31 | for host in xml_root.findall('host'): 32 | ip = host.find('address').get('addr') 33 | ports_element = host.findall('ports') 34 | port_element = ports_element[0].findall('port') 35 | 36 | # Cycle through each port 37 | for scanned_port in port_element: 38 | port_id = scanned_port.get('portid') 39 | script_element = scanned_port.find('script') 40 | if script_element: 41 | # Cycle through each protocol 42 | protocol_element = script_element.findall('table') 43 | for tls_protocol in protocol_element: 44 | protocol_version = tls_protocol.attrib['key'] 45 | 46 | # Stage data for TLSv1.0 Table 47 | if protocol_version in 'TLSv1.0': 48 | flagged_tls_v10 += protocol_version + ',' 49 | 50 | # Stage data for TLSv1.1 Table 51 | if protocol_version in 'TLSv1.1': 52 | flagged_tls_v11 += protocol_version + ',' 53 | 54 | # Stage data for SSLv3 Table 55 | if protocol_version in 'SSLv3': 56 | flagged_ssl_v3 += protocol_version + ',' 57 | 58 | # Load TLSv1.0 Data 59 | if flagged_tls_v10: 60 | flagged_tls_v10 = flagged_tls_v10.strip(',').split(',') 61 | tls_v10_report.append([ip,port_id,flagged_tls_v10 ]) 62 | flagged_tls_v10 = '' 63 | 64 | # Load TLSv1.1 Data 65 | if flagged_tls_v11: 66 | flagged_tls_v11 = flagged_tls_v11.strip(',').split(',') 67 | tls_v11_report.append([ip,port_id,flagged_tls_v11 ]) 68 | flagged_tls_v11 = '' 69 | 70 | # Load SSLv3.0 Data 71 | if flagged_ssl_v3: 72 | flagged_ssl_v3 = flagged_ssl_v3.strip(',').split(',') 73 | ssl_v3_report.append([ip,port_id,flagged_ssl_v3 ]) 74 | flagged_ssl_v3 = '' 75 | 76 | 77 | # CSV Data for TLSv1.0 78 | with open('detected_tls_v10.csv', 'w') as csvFile: 79 | writer = csv.writer(csvFile) 80 | 81 | # CSV Headers 82 | writer.writerow(["IP", "Port", "Protocol"]) 83 | 84 | # Cycle through each staged element in list 85 | for server in tls_v10_report: 86 | row_ip = server[0] 87 | row_port = server[1] 88 | 89 | # Write results to row 90 | writer.writerow([row_ip,row_port,'TLSv1.0']) 91 | 92 | # CSV Data for TLSv1.1 93 | with open('detected_tls_v11.csv', 'w') as csvFile: 94 | writer = csv.writer(csvFile) 95 | 96 | # CSV Headers 97 | writer.writerow(["IP", "Port", "Protocol"]) 98 | for server in tls_v11_report: 99 | row_ip = server[0] 100 | row_port = server[1] 101 | 102 | # Write results to row 103 | writer.writerow([row_ip,row_port,'TLSv1.1']) 104 | 105 | # CSV Data for SSLv.3 106 | with open('detected_ssl_v3.csv', 'w') as csvFile: 107 | writer = csv.writer(csvFile) 108 | 109 | # CSV Headers 110 | writer.writerow(["IP", "Port", "Protocol"]) 111 | for server in ssl_v3_report: 112 | row_ip = server[0] 113 | row_port = server[1] 114 | # Write results to row 115 | writer.writerow([row_ip,row_port,'SSLv3.0']) 116 | 117 | if __name__ == '__main__': 118 | main() -------------------------------------------------------------------------------- /Screenshots/create-database.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gh0x0st/pythonizing_nmap/c3e6219f7c522694ab2d8883191feea40c6537e0/Screenshots/create-database.png -------------------------------------------------------------------------------- /Screenshots/insert-content.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gh0x0st/pythonizing_nmap/c3e6219f7c522694ab2d8883191feea40c6537e0/Screenshots/insert-content.png -------------------------------------------------------------------------------- /Screenshots/nmap-service-probes-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gh0x0st/pythonizing_nmap/c3e6219f7c522694ab2d8883191feea40c6537e0/Screenshots/nmap-service-probes-2.png -------------------------------------------------------------------------------- /Screenshots/nmap-service-probes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gh0x0st/pythonizing_nmap/c3e6219f7c522694ab2d8883191feea40c6537e0/Screenshots/nmap-service-probes.png -------------------------------------------------------------------------------- /Screenshots/parse-accessible-ports.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gh0x0st/pythonizing_nmap/c3e6219f7c522694ab2d8883191feea40c6537e0/Screenshots/parse-accessible-ports.png -------------------------------------------------------------------------------- /Screenshots/parse-live-hosts.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gh0x0st/pythonizing_nmap/c3e6219f7c522694ab2d8883191feea40c6537e0/Screenshots/parse-live-hosts.png -------------------------------------------------------------------------------- /Screenshots/select-content.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gh0x0st/pythonizing_nmap/c3e6219f7c522694ab2d8883191feea40c6537e0/Screenshots/select-content.png -------------------------------------------------------------------------------- /Screenshots/shlex-vs-split.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gh0x0st/pythonizing_nmap/c3e6219f7c522694ab2d8883191feea40c6537e0/Screenshots/shlex-vs-split.png -------------------------------------------------------------------------------- /Screenshots/subprocess-stdout-stderr.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gh0x0st/pythonizing_nmap/c3e6219f7c522694ab2d8883191feea40c6537e0/Screenshots/subprocess-stdout-stderr.png -------------------------------------------------------------------------------- /Screenshots/timeline_ad-hoc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gh0x0st/pythonizing_nmap/c3e6219f7c522694ab2d8883191feea40c6537e0/Screenshots/timeline_ad-hoc.png -------------------------------------------------------------------------------- /Screenshots/xml-parse-sample.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gh0x0st/pythonizing_nmap/c3e6219f7c522694ab2d8883191feea40c6537e0/Screenshots/xml-parse-sample.png -------------------------------------------------------------------------------- /XML Parser Scripts/README.md: -------------------------------------------------------------------------------- 1 | # Question of Trust 2 | 3 | The xml.etree.ElementTree module provides an easy-to-use library to parse XML data that you trust, such as the XML ouput generated from NMAP. However, when dealing with data you do not trust, there are better avenues. 4 | 5 | The below information comes from https://docs.python.org/3/library/xml.html#xml-vulnerabilities as of 11/19/2021. 6 | 7 | ## Vulnerabilities For ElementTre 8 | 9 | | Attack | Vulnerable | 10 | | :---------|------------| 11 | | billion laughs | **Yes** | 12 | | quadratic blowup | **Yes** | 13 | | external entity expansion | No | 14 | | DTD retrieval | No | 15 | | decompression bomb | No | 16 | 17 | ## Attack Descriptions 18 | 19 | The Billion Laughs attack – also known as exponential entity expansion – uses multiple levels of nested entities. Each entity refers to another entity several times, and the final entity definition contains a small string. The exponential expansion results in several gigabytes of text and consumes lots of memory and CPU time. 20 | 21 | The quadratic blowup attack is similar to a Billion Laughs attack; it abuses entity expansion, too. Instead of nested entities it repeats one large entity with a couple of thousand chars over and over again. The attack isn’t as efficient as the exponential case but it avoids triggering parser countermeasures that forbid deeply-nested entities. 22 | 23 | ## Alternative Package 24 | 25 | The defusedxml library is a pure Python package with modified subclasses of all stdlib XML parsers that prevent any potentially malicious operation. Use of this package is recommended for any server code that parses untrusted XML data. The package also ships with example exploits and extended documentation on more XML exploits such as XPath injection. 26 | 27 | ## References 28 | * https://docs.python.org/3/library/xml.html#xml-vulnerabilities 29 | * https://pypi.org/project/defusedxml/ 30 | -------------------------------------------------------------------------------- /XML Parser Scripts/parse-accesible-ports.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | 5 | def parseDiscoverPorts(in_xml): 6 | results = [] 7 | port_list = '' 8 | xml_tree = ET.parse(in_xml) 9 | xml_root = xml_tree.getroot() 10 | for host in xml_root.findall('host'): 11 | ip = host.find('address').get('addr') 12 | ports = host.findall('ports')[0].findall('port') 13 | for port in ports: 14 | state = port.find('state').get('state') 15 | if state == 'open': 16 | port_list += port.get('portid') + ',' 17 | port_list = port_list.rstrip(',') 18 | if port_list: 19 | results.append(f"{ip} {port_list}") 20 | port_list = '' 21 | return results 22 | 23 | 24 | def main(): 25 | targets = parseDiscoverPorts('/home/tristram/Downloads/OffSec-master/External/Stage_2/syn_port_scan.xml') 26 | for target in targets: 27 | element = target.split() 28 | target_ip = element[0] 29 | target_ports = element[1] 30 | print(f'Nmap Format Example: nmap {target_ip} -p {target_ports}') 31 | 32 | if __name__ == '__main__': 33 | main() 34 | -------------------------------------------------------------------------------- /XML Parser Scripts/parse-accessible-ports.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | 5 | def parseDiscoverPorts(in_xml): 6 | results = [] 7 | port_list = '' 8 | xml_tree = ET.parse(in_xml) 9 | xml_root = xml_tree.getroot() 10 | for host in xml_root.findall('host'): 11 | ip = host.find('address').get('addr') 12 | ports = host.findall('ports')[0].findall('port') 13 | for port in ports: 14 | state = port.find('state').get('state') 15 | if state == 'open': 16 | port_list += port.get('portid') + ',' 17 | port_list = port_list.rstrip(',') 18 | if port_list: 19 | results.append(f"{ip} {port_list}") 20 | port_list = '' 21 | return results 22 | 23 | 24 | def main(): 25 | targets = parseDiscoverPorts('/home/tristram/Scans/Stage_2/top_1000_portscan.xml') 26 | for target in targets: 27 | element = target.split() 28 | target_ip = element[0] 29 | target_ports = element[1] 30 | print(f'Nmap Format Example: nmap {target_ip} -p {target_ports}') 31 | 32 | if __name__ == '__main__': 33 | main() 34 | -------------------------------------------------------------------------------- /XML Parser Scripts/parse-in-memory.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | import subprocess 5 | import shlex 6 | 7 | 8 | def nmapMemory(target): 9 | args = shlex.split(f"/usr/bin/nmap {target} -T4 -Pn -n -vv -sS -min-parallelism 100 --min-rate 64 --top-ports 1000 -oX -") 10 | return subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 11 | 12 | 13 | def parseDiscoverPortsMemory(in_xml): 14 | results = [] 15 | port_list = '' 16 | #xml_tree = ET.parse(in_xml) 17 | #xml_root = xml_tree.getroot() 18 | xml_root = ET.fromstring(in_xml.decode('utf-8')) 19 | for host in xml_root.findall('host'): 20 | ip = host.find('address').get('addr') 21 | ports = host.findall('ports')[0].findall('port') 22 | for port in ports: 23 | state = port.find('state').get('state') 24 | if state == 'open': 25 | port_list += port.get('portid') + ',' 26 | port_list = port_list.rstrip(',') 27 | if port_list: 28 | results.append(f"{ip} {port_list}") 29 | port_list = '' 30 | return results 31 | 32 | 33 | def main(): 34 | target = '127.0.0.1' 35 | xml_output = nmapMemory(target)[0] 36 | 37 | targets = parseDiscoverPortsMemory(xml_output) 38 | for target in targets: 39 | element = target.split() 40 | target_ip = element[0] 41 | target_ports = element[1] 42 | print(f'Scanning: {target_ip} against ports {target_ports}') 43 | 44 | 45 | if __name__ == '__main__': 46 | main() 47 | -------------------------------------------------------------------------------- /XML Parser Scripts/parse-live-hosts.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import xml.etree.ElementTree as ET 4 | 5 | def parseDiscoverXml(in_xml): 6 | live_hosts = [] 7 | xml_tree = ET.parse(in_xml) 8 | xml_root = xml_tree.getroot() 9 | for host in xml_root.findall('host'): 10 | ip_state = host.find('status').get('state') 11 | if ip_state == "up": 12 | live_hosts.append(host.find('address').get('addr')) 13 | return live_hosts 14 | 15 | 16 | def convertToNmapTarget(hosts): 17 | hosts = list(dict.fromkeys(hosts)) 18 | return " ".join(hosts) 19 | 20 | 21 | def main(): 22 | hosts = parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_echo_host_discovery.xml') 23 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_netmask_host_discovery.xml') 24 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/icmp_timestamp_host_discovery.xml') 25 | hosts += parseDiscoverXml('/home/tristram/Scans/Stage_1/tcp_syn_host_discovery.xml') 26 | 27 | print(f"Flagged Hosts: {len(hosts)}") 28 | print(f"Unique Hosts: {len(list(dict.fromkeys(hosts)))}") 29 | print(f"Nmap Format Example: {convertToNmapTarget(hosts)}") 30 | 31 | if __name__ == '__main__': 32 | main() 33 | --------------------------------------------------------------------------------