Jeu sécurité

Le bug du mois de mars/avril

Proposé par Pierre Lagarde

BadQuotes.aspx
<%@ Page language="c#" Codebehind="BadQuotes.aspx.cs" AutoEventWireup="false" Inherits="Inject.BadQuotes" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
   <HEAD>
    ...
   </HEAD>
   <body>
     <asp:Label id="Quote" runat="server"></asp:Label>
     <asp:Label id="Author" runat="server"></asp:Label>
   </body>
</HTML>

BadQuotes.aspx.cs
private void Page_Load(object sender, System.EventArgs e)
{
   string id = Request["ID"];
   if (id != null && id != String.Empty) {
     SqlConnection connection = new SqlConnection ("...");
     try
     {
      connection.Open ();
      SqlCommand command = new SqlCommand ("SELECT quotation, author FROM quotations WHERE id=" + id, connection);
      SqlDataReader reader = command.ExecuteReader ();
      if (reader.Read ()) {
       Quote.Text = reader["Quotation"].ToString ();
       Author.Text = reader["Author"].ToString ();
      }
     }
     finally
     {
      connection.Close ();
     }
   }
}


La bonne réponse

La bonne réponse est :
Vérifier la variable ID est bien un entier avant de l’envoyé dans le requête SQL.

Il ne faut jamais utiliser directement ce qui provient de l’URL pour un affichage ou une utilisation dans le code (Requête SQL, Insertion en base, traitement, …).


Et le code corrigé

Proposé par Pierre Lagarde

private void Page_Load(object sender, System.EventArgs e)
{
   string id = Request["ID"];

   if (id != null && id != String.Empty) {
     //
     // Make sure ID is a number and that it's in range.
     //
     int num = -1;

     try {
       num = Convert.ToInt32 (id);
     }
     catch (FormatException) {
       return;
     }

     if (num < 1 || num > 10)
       return;

     //
     // Use ID in a database query.
     //
     SqlConnection connection = new SqlConnection ("…");

     try
     {
       connection.Open ();
       SqlDataReader reader = command.ExecuteReader ();

       if (reader.Read ()) {
         Quote.Text = reader["Quotation"].ToString ();
         Author.Text = reader["Author"].ToString ();
       }
     }
     finally
     {
         connection.Close ();
     }
   }
}

Pour aller plus loin

Liste de contrôle : sécurisation d'ASP.NET

Document à télécharger : Les 10 vulnérabilités de sécurité applicatives web les plus critiques

Regardez les webcasts liés à la sécurité, et notamment ceux concernant ASP .NET 2.0 et la sécurité

Le centre de conseils sur la sécurité pour les développeurs

Writing Secure Code, l’ouvrage de référence 

Le règlement | Comment jouer ? | Liste des gagnants


**
**
**
**
**
**