常见Web攻击

一、SQL注入

  1. sql注入的危害 

  • 非法读取、篡改、删除数据库中的数据
  • 盗取用户的各类敏感信息,获取利益
  • 通过修改数据库来修改网页上的内容
  • 注入木马等

2. 实例

MYSQLDB
	# 通过在用户名里面构建一个sql语句,达到了我们在执行sql语句的时候永远为真的情况
	# username = '~ OR 1=1'
	username = request.POST.get('username')
	password = request.POST.get('password')
	import MySQLdb
	conn = MySQLdb.connect(host='127.0.0.1', user='root', db='mxonline', password='0000')
	cursor = conn.cursor()
	sql_select = "select * from users_userprofile where email='{0}' and password='{1}'".format(username, password)

	result = cursor.execute(sql_select)
	for row in cursor.fetchall():
		# 查询到所有用户

  3. 防范

mysqldb
	c=db.cursor()
	max_price=5
	c.execute("""SELECT spam, eggs, sausage FROM breakfast
			  WHERE price < %s""", [max_price])
			  
sqlalchemy
	from sqlalchemy.orm import sessionmaker
	from sqlalchemy import create_engine
	from sqlalchemy.orm import scoped_session
	from models import Student,Course,Student2Course

	engine = create_engine(
			"mysql+pymysql://root:123456@127.0.0.1:3306/s9day120?charset=utf8",
			max_overflow=0,  # 超过连接池大小外最多创建的连接
			pool_size=5,  # 连接池大小
			pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
			pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
		)
	SessionFactory = sessionmaker(bind=engine)
	session = scoped_session(SessionFactory)
	
	cursor = session.execute('INSERT INTO users(name) VALUES(:value)', params={"value": 'zhangyafei'})
	session.commit()
	print(cursor.lastrowid)
	
	from sqlalchemy.sql import text
	t = text("select * from test where id= :tid")
	conn.execute(t, tid=1).fetchall()
	
flask-sqlalchemy
	db = SQLAlchemy(app)
	conn = db.session.connection()

	@app.route('/')
	def index():
		rv = conn.execute('select * from test where id = %s', [1])
		return jsonify(rv)
		
pymysql
	def fetchall(sql, arg=list(), type=pymysql.cursors.DictCursor):
		conn, cursor = connect(type)
		cursor.execute(sql, arg)
		data = cursor.fetchall()
		connect_close(conn, cursor)
		return data

二、xss攻击

  1.xss跨站脚本攻击(Cross Site Scripting)的危害

  • 盗取各类用户的账号,如用户网银账号、各类管理员账号
  • 盗窃企业重要的具有商业价值的资料
  • 非法转账
  • 控制受害者机器向其他网站发起攻击、注入木马等等

  2.xss攻击防范

  • 首先在代码里对用户输入的地方和变量都需要仔细检查长度和对"<",">",",","'"等字符进行过滤
  • 避免直接在cookie中泄露用户隐私,例如email、密码等等通过使cookie和系统ip绑定来降低cookie泄露后的危险
  • 尽量使用POST而非GET提交表单

  3. xssf防范代码

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from bs4 import BeautifulSoup


class XSSFilter(object):
    __instance = None

    def __init__(self):
        # XSS白名单
        self.valid_tags = {
            "font": ['color', 'size', 'face', 'style'],
            'b': [],
            'div': [],
            "span": [],
            "table": [
                'border', 'cellspacing', 'cellpadding'
            ],
            'th': [
                'colspan', 'rowspan'
            ],
            'td': [
                'colspan', 'rowspan'
            ],
            "a": ['href', 'target', 'name'],
            "img": ['src', 'alt', 'title'],
            'p': [
                'align'
            ],
            "pre": ['class'],
            "hr": ['class'],
            'strong': []
        }

    def __new__(cls, *args, **kwargs):
        """
        单例模式
        :param cls:
        :param args:
        :param kwargs:
        :return:
        """
        if not cls.__instance:
            obj = object.__new__(cls, *args, **kwargs)
            cls.__instance = obj
        return cls.__instance

    def process(self, content):
        soup = BeautifulSoup(content, 'html.parser')
        # 遍历所有HTML标签
        for tag in soup.find_all(recursive=True):
            # 判断标签名是否在白名单中
            if tag.name not in self.valid_tags:
                tag.hidden = True
                if tag.name not in ['html', 'body']:
                    tag.hidden = True
                    tag.clear()
                continue
            # 当前标签的所有属性白名单
            attr_rules = self.valid_tags[tag.name]
            keys = list(tag.attrs.keys())
            for key in keys:
                if key not in attr_rules:
                    del tag[key]

        return soup.decode()


if __name__ == '__main__':
    html = """<p class="title">
                        <b>The Dormouse's story</b>
                    </p>
                    <p class="story">
                        <div name='root'>
                            Once upon a time there were three little sisters; and their names were
                            <a href="http://example.com/elsie" class="sister c1" style='color:red;background-color:green;' id="link1"><!-- Elsie --></a>
                            <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
                            <a href="http://example.com/tillie" class="sister" id="link3">Tilffffffffffffflie</a>;
                            and they lived at the bottom of a well.
                            <script>alert(123)</script>
                        </div>
                    </p>
                    <p class="story">...</p>"""

    obj = XSSFilter()
    v = obj.process(html)
    print(v)
xss.py

三、CSRF攻击

  1. csrf跨站请求伪造(Cross-site request forgery)的危害

  • 以你名义发送邮件
  • 盗取你的账号
  • 购买商品
  • 虚拟货币转账

  2. 防范

  • 加上csrf token

 

posted @ 2019-03-10 10:34  DreamBoy_张亚飞  阅读(387)  评论(0编辑  收藏  举报