Search code examples
sqlsql-injection3-tier

SQL Injection on Views


We are using 3-Tier Architecture in ASP.Net.

There are 3 Layers

  1. Presentation
  2. Business
  3. Data Access

The Data Access Layer contains the GetData and ExecuteQuery etc function. What I want to know is that, that want to call the View directly from the Presentation Layer. Is there any chance of SQL injection in calling a view from front-end without using stored procedure?

Presentation Layer (C#)

protected void btnView_Click(object sender, EventArgs e)
        {
            DL obj = new DL();
            DataTable tb = new DataTable();
            string query = "select * from ViewTeacher where FID = " + txtName.Text;

            tb = obj.GetData(query);

        }

DBAccess

public DataTable GetData(string query)
        {
            DataTable datatable = new DataTable();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = query;

            try
            {
                if (cmd.Connection.State != ConnectionState.Open)
                {
                    cmd.Connection.Open();
                }
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    da.Fill(datatable);
                }
            }
            catch (Exception ex)
            {

                throw new ArgumentException(ex.Message);
            }
            return datatable;
        }

Solution

  • How are you "calling a view"? If you're running an ad-hoc query of:

    SELECT <columns> FROM View WHERE ColumnX = 'Y'
    

    and if that query is being constructed using (potentially) hostile input then yes, of course that can be subject to SQL injection - the whole point of injection is that the attacker can change the nature of the query:

    SELECT <columns> FROM View WHERE ColumnX = 'Z'
    UNION ALL
    SELECT name,0,0,0,0 FROM INFORMATION_SCHEMA.TABLES --'
    

    The attacker isn't limited to just the objects that are present in the original query.


    The untrustworthy input in the two above queries was:

    Y
    

    and

    Z'
    UNION ALL
    SELECT name,0,0,0,0 FROM INFORMATION_SCHEMA.TABLES --