2

Hacker reached my database User list and other tables.

First of all, I use parameterized command in all of the transactions by using

command.Parameters.Add("@Parameter1", SqlDbType.NVarChar).Value

All transactions are stored procedures.

I am inserting every single site navigation into database. Particular database table as follows;

ID int (PK)
UserID int (null)
URL nvarchar(500)
IPAddress nvarchar(25)
CreatedAt datetime

Project gets UserID information from the code is session opened or not.

CreatedAt is DateTime.UtcNow.

IPAddress code as follows:

public static string GetIPAddress(HttpContext context)
{
    string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

    if (!string.IsNullOrEmpty(ipAddress))
    {
        string[] addresses = ipAddress.Split(',');
        if (addresses.Length != 0)
            return addresses[0];
    }

    return context.Request.ServerVariables["HTTP_CLIENT_IP"] ?? context.Request.ServerVariables["REMOTE_ADDR"];
}

However URL is filled from Website Current URL with all query string. (Request.RawUrl)

Normally, when the user visits the site, Log is inserted into database as I stated above. Following records are inserted normally. Example data looks like this:

ID      UserID    URL                        IPAddress      CreatedAt
1        NULL     /User                      1.22.33.444    2019-12-12 16:22:33.441
2        NULL     /User/MyOrders             1.22.33.444    2019-12-12 16:24:33.441
3        NULL     /User?utm_source=email     1.22.33.444    2019-12-12 16:29:33.441

The hacker somehow inserted a record into database as follows:

ID      UserID    URL                        IPAddress                     CreatedAt
4        NULL     /User                      (select(0)from(select(sle     2019-12-12 17:22:33.441
5        NULL     /User/MyOrders             -1; waitfor delay '0:0:9'     2019-12-12 17:24:33.441
6        NULL     /User?utm_source=email     prvNA0R6'; waitfor delay      2019-12-12 17:29:33.441
7        NULL     /User?utm_source=email     -1' OR 2+198-198-1=0+0+0+     2019-12-12 17:29:33.441

As you can see IPAddress column is the SQL Query attack. IPAddress field is restricted to 25 character length. Following SQL query text is truncated by the SQL.

In my opinion, hacker gets database records by using SQL Injection by changing URL or IPAddress as SQL scripts.

Any idea how hacker reached my database and how to avoid attack from now on?

EDIT

Stored procedure is as follows:

create procedure SP_InsertLogNavigation
    @URL nvarchar(150),
    @UserID int,
    @IPAddress nvarchar(25),
    @CreatedAt datetime
as
    insert into LogNavigation (URL, UserID, IPAddress, CreatedAt)
    values (@URL, @UserID, @IPAddress, @CreatedAt)

Usage of the stored procedure is as follows:

public bool Save(LogNavigation logNavigation)
{
    int affectedRows = 0;

    InitializeSqlFields("SP_InsertLogNavigation");

    command.Parameters.Add("@URL", SqlDbType.NVarChar).Value = logNavigation.URL;
    command.Parameters.Add("@UserID", SqlDbType.Int).Value = Validation.IsNull(logNavigation.UserID);
    command.Parameters.Add("@IPAddress", SqlDbType.NVarChar).Value = logNavigation.IPAddress;
    command.Parameters.Add("@CreatedAt", SqlDbType.DateTime).Value = logNavigation.CreatedAt;

    try
    {
        Connect();

        affectedRows = command.ExecuteNonQuery();
    }
    catch (SqlException)
    {
    }
    finally
    {
        Disconnect();
    }

    return affectedRows != 0;
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
codeblock
  • 31
  • 5
  • You are using store procedure or plan query? – jishan siddique Dec 17 '19 at 08:54
  • I am using StoredProcedure – codeblock Dec 17 '19 at 08:55
  • You told us that you use parameters, so what are the effects of these attempts to do sql injection? – Steve Dec 17 '19 at 08:57
  • @Steve I am pretty sure she/he got an information about my database data. Also she/he passes the SQL script into IPAddress column. – codeblock Dec 17 '19 at 08:59
  • Can you show your stored procedure, and how/when it is called? – GarethD Dec 17 '19 at 09:00
  • 1
    he is only trying to take access , but the things you are using can't hacked easily. and from my point of view try to write code in n tier. so that the things can't easily injected to the code. – Ravi Kant Singh Dec 17 '19 at 09:13
  • Any idea @GarethD – codeblock Dec 17 '19 at 09:25
  • This is not a successful Sql Injection. This is an _attempt_ to do Sql Injection. The attacker tries to reach your db using headers, but you have used parameters, so its script is just written to your log table but not executed. Also, the truncation to 25 chars makes the attempt to write any successful script (from the attacker point of view) very difficult if not impossible. Now if you are sure about the information leak then you should search elsewhere. For example, do you provide some log reading functionality? – Steve Dec 17 '19 at 09:33
  • @Steve I logged user visit information just like mentioned in the question. Not furthermore log. I am %100 sure my informations leaked because I see the screenshot which is the same in my db table. – codeblock Dec 17 '19 at 09:40
  • She/he also attack the by using form (Contact, Update Profile). – codeblock Dec 17 '19 at 09:41
  • 2
    @codeblock Your code and procedures are 100% fine (well, there is [a case against using the sp_ prefix for your stored procedure](https://sqlperformance.com/2012/10/t-sql-queries/sp_prefix), but in terms of SQL Injection and things relevant to the question they are fine). It appears, as Martin has pointed out in his answer that the attempt was unsuccessful. There is nothing in any of the code you have posted that would have executed the SQL that was injected. – GarethD Dec 17 '19 at 09:42
  • Allright. I will ask another question about the contact and update profile form. Maybe these two forms are the main reason because attacker tried to reach with the form – codeblock Dec 17 '19 at 09:54

1 Answers1

8

So I would assert that you actually have not succumbed to the SQL injection attack. If you are using only parameterised queries then the attacker has tried to gain access but failed.

However, the reason why your table has their attack attempts lodged is to do with these lines of code:

string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

return context.Request.ServerVariables["HTTP_CLIENT_IP"] ?? context.Request.ServerVariables["REMOTE_ADDR"];

You must understand that the client has almost total control over the headers submitted to your website. The attacker can modify the headers to be whichever values they desire.

These parameters are supplied by the client in their request:

HTTP_X_FORWARDED_FOR
REMOTE_ADDR
HTTP_CLIENT_IP

In your case, the attacker has provided spoofed headers that contain SQL Injection code, which you have faithfully placed into your database in the IP Address column.

Edit following OP query in comments

OP asked:

Excellent, but I have only one question. How she/he passed more than 25 characters to the my server side

The request headers have no specified size limit, although their are practical limits applied by various implementations (i.e. 8Kb in Apache). The client can send a request header of any length up to what is allowed by your website host software.

However, as your SP is configured with a parameter whose maximum length is 25 characters, the overflowing text is being truncated when persisted to the database.

Martin
  • 16,093
  • 1
  • 29
  • 48
  • Excellent, but I have only one question. How she/he passed more than 25 characters to the my server side. – codeblock Dec 17 '19 at 09:09
  • @codeblock I've added an edit to my question to explain the reason for this – Martin Dec 17 '19 at 09:15
  • I understand the limitation of the RequestHeader. User can set anything for the header. The only thing that I don't understand; I don't execute Request Header in the code except IPAddress. IPAddress is returned by the function `GetIPAddress()`. How she/he is passed SQL Query more than 25 length and execute it. – codeblock Dec 17 '19 at 09:24
  • 1
    @codeblock If the attacker has compromised your SQL Server it is not through the code you have shown us. The SQL supplied via the IP Address header is not executed against the server (unless there is more code you haven't shown us) – Martin Dec 17 '19 at 09:26
  • You're right. Is it possible to use `URL` because if user can use any `URL` project handled URL data and insert it. – codeblock Dec 17 '19 at 09:30
  • @codeblock How would you intend to use it? I think that may be a different question as it has a lengthy answer of it's own! – Martin Dec 17 '19 at 09:42
  • I will ask another question about contact and update profile form. – codeblock Dec 17 '19 at 10:07
  • Can you check [this question](https://stackoverflow.com/questions/59373828/my-asp-net-website-is-attacked-with-sql-injection-using-post-form) – codeblock Dec 17 '19 at 12:06