前两天,带着学生们学习了简单的ASP.NET MVC,通过ADO.NET方式连接数据库,实现增删改查。
可能有一部分学生提前预习过,在我写登录SQL的时候,他们鄙视我说:“老师你这SQL有注入,随便都能登录了。不能这么写!”
“呦?小伙子这都知道了?那你说说看 啥是注入?注入只能拿来绕过登录么?”
好吧,竟然在老子面前装逼,看来不给你点儿颜色看看,你还真是不明白天有多高。。
于是乎。。哈哈。大清早的,轻松在班里装了一手好逼。。
呵呵。不说了,下面我把那个项目重写一下发上来吧。演示一下注入有哪些危害。怎么避免等。
(*^_^*) 大牛勿喷。
▁▃▅ 浅谈SQL注入风险 - 一个Login拿下Server ▅▃▁
目录:
本文主要就是介绍SQL注入基本手法,危害,以及如何解决。
技术有点渣渣,大牛勿喷。。。。
一、数据库。
只创建了一个Admin表,结构如下:
Admin 2 ( (1,1) not null, 4 Username nvarchar(50) not null, ) 7 go
插入三条测试数据如下:
二、Web项目
这里为了演示,所以我只搭建了一个简单的三层结构(ASP.NET MVC作为UI,DAL,BLL)以及模型Model:
1. Model模型层的AdminInfo.cs:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; Guying.BlogsDemo.Model 7 { Admin 模型 AdminInfo 12 { 编号 Id { get; set; } 账号 Username { get; set; } 密码 Password { get; set; } 27 } 28 }
AdminInfo.cs2. Web.config添加连接字符串:
3. DAL数据层的DBHelper.cs辅助类:
1 using System; 2 using System.Collections.Generic; 3 using System.Configuration; 4 using System.Linq; 5 using System.Text; Guying.BlogsDemo.DAL 8 { 数据访问辅助类 DBHelper 13 { BlogDemo 数据库链接字符串 CONNECTIONSTRING = ConfigurationManager.ConnectionStrings[].ConnectionString; 18 } 19 }
DBHelper.cs4. DAL数据层的AdminService.cs中写了一个登录的Login方法(SQL存在注入):
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Data.SqlClient; 6 using Guying.BlogsDemo.Model; Guying.BlogsDemo.DAL 9 { Admin 数据提供 AdminService 14 { Admin 登录 AdminInfo Login(AdminInfo adminInfo) 21 { 22 AdminInfo result = null; , adminInfo.Username, adminInfo.Password); 24 using (SqlConnection conn = new SqlConnection(DBHelper.CONNECTIONSTRING)) 25 { 26 conn.Open(); 27 using (SqlCommand comm = new SqlCommand(sql, conn)) 28 { 29 using (SqlDataReader reader = comm.ExecuteReader()) 30 { 31 if (reader.Read()) 32 { 33 result = new AdminInfo() 34 { ], ].ToString(), ].ToString() 38 }; 39 } 40 } 41 } 42 } 43 return result; 44 } 45 } 46 }
AdminService.cs(SQL存在注入)5. BLL业务逻辑的AdminManager.cs: