Thursday, January 27, 2005

Keeping Attackers Out of the Control Channel

As a rule for writing secure code, you should always keep any potential attackers in the data channel and out of the control channel. I learned that a long time ago, but didn't pay much attention until I went to Keith Brown's talk at Applied XML Developers Conference 5 on 10/21/2004. The following is an example given in Keith's book.

// this code has a really nasty security flaw
void LogUserName(SqlConnection conn, string userName)
{
string sqlText = "insert user_names values('" + userName + "')";
SqlCommand cmd = new SqlCommand(sqlText, conn);
cmd.ExecuteNonQuery();
}

// much more secure code
void LogUserName(SqlConnection conn, string userName)
{
string sqlText = "insert user_names values(@n)";
SqlCommand cmd = new SqlCommand(sqlText, conn);
SqlParameter p = cmd.Parameters.Add("@n", SqlDbType.VarChar, userName.Length); p.Value = userName;
cmd.ExecuteNonQuery();
}

Here is another example.

string cmdToExecute = “search.exe “ + userInput;

Normal users would pass benign strings like “butterfly”, while a malicious user could pass a string that would cause you to launch another program, " net user hacker P@ssw0rd /add". There is a pipe symbol at the beginning of this malicious input.

To keeping attackers out of the control channel, you use the System.Diagnostics.Process class as follows.

Process p = new Process();
p.StartInfo.FileName = @"c:\legacy\search.exe";
p.StartInfo.Arguments = filteredUserInput;
p.Start();