[.NET] Crypter la section « connectionStrings » du fichier app.config (ou web.config)

Le 2 février 2010 à 19:23

Pour rappel, la section « connectionStrings » du fichier App.config contient les informations d’accès à vos bases de données comme le chemin d’accès, le login et le mot de passe. Ces informations sont donc sensibles et ne doivent pas être dévoilés aussi facilement.
Malgré qu’il soit évident qu’il ne faut pas utiliser un compte « root » de la base de données, il est tout de même plus prudent de cacher cette partie aux yeux des utilisateurs. D’autant plus qu’avec cette méthode, l’utilisateur final ne pourra pas modifier le fichier manuellement.

Voici le fichier App.config et la section “connectionStrings” sous sa forme habituelle :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="SqlCustomersDB" 
         providerName="System.Data.SqlClient" 
         connectionString="Data Source=MPE-SERV\SQLSERVER_ITESTS;
                           Initial Catalog=CustomersDB;
                           User ID=perrein;
                           Password=P@ssw0rD" />
  </connectionStrings>
</configuration>

Et voici le même fichier App.config et la section “connectionStrings” que l’on va avoir sous sa forme “protégé” :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
    <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
      xmlns="http://www.w3.org/2001/04/xmlenc#">
      <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
      <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
        <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
          <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
          <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
            <KeyName>Rsa Key</KeyName>
          </KeyInfo>
          <CipherData>
            <CipherValue>HvU+CmZBPbPfqGvhBLE8OC2QmO3V7w0gwpTr7CBkMifC15H8eQ8Z
                         AmyxCQRpP/Tz8gypkQ1PDyQdyYD26sa/I1PaJzrZpduypLD2mp9p
                         kyWXAygFRQvb0m4EL0OK8DoHDWMta1q7Q7BycVOU87ePeCQ8Z7MY
                         XGoySopx7nzvBeI=
            </CipherValue>
          </CipherData>
        </EncryptedKey>
      </KeyInfo>
      <CipherData>
        <CipherValue>vo42yCFwoVO3s4Md+Jcl9rLHQCRcVDTXr9JGFxjN4ozlGdG9TFrI16+J
                     y1CTWzgi1bXwYtFCfSUgRjMJbYm6ULLGFcFaaX7h/1O+9tfUtrLjbBuJ
                     4wO6q0xr766lrOpQ98BG9rqxm6WwEVWZfT/FesDkzWVw/N+W8FPPk1rg
                     +QTSB7ZisjqhGSkoZERgVe2MsCtl5ZJyQawFvy0DreWdj7efNT2aMs1N
                     Ieogmef0/XTB4nXYjEA8I7R9AnjekWwDnXHAcpFzYjoqgmFx8zHG+XPQ
                     xeXVhCue5QmshNDzuRg=
        </CipherValue>
      </CipherData>
    </EncryptedData>
  </connectionStrings>
</configuration>

Pour transformer le fichier, la mise en place n’est pas très compliquée, il faut utiliser la méthode SectionInformation. ProtectSection de la classe ConfigurationSection :

Configuration config = 
              ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSection section = config.GetSection("connectionStrings");

if (section != null)
{
    if (!section.IsReadOnly() && !section.SectionInformation.IsProtected)
    {
        section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
        section.SectionInformation.ForceSave = true;
        config.Save(ConfigurationSaveMode.Full);
    }
}


On peut crypter cette section avec deux providers :
- DataProtectionConfigurationProvider : utilise l’API de protection des données (DPAPI) Windows pour chiffrer et déchiffrer
- RsaProtectedConfigurationProvider : utilise le chiffrement RSA pour chiffrer et déchiffrer les données de configuration

Pour lire une connectionStrings dans le fichier de configuration, rien ne changera par rapport à nos habitudes car le décryptage est totalement transparent. Par contre, s’il faut modifier ou supprimer une valeur, il faudra décrypter la section au préalable : 

Configuration config = 
              ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSection section = config.GetSection("connectionStrings");

if (section != null)
{
    if (section.SectionInformation.IsProtected)
    {
        section.SectionInformation.UnprotectSection();
        section.SectionInformation.ForceSave = true;
        config.Save(ConfigurationSaveMode.Full);
    }
}
config.ConnectionStrings.ConnectionStrings["SqlCustomersDB"].ConnectionString = 
   @"Data Source=MPE-SERVER-02\SQLSERVER;Initial Catalog=CustomersDB;
                 Integrated Security=True;User ID=perrein;Password=P@ssw0rD";
config.Save();

// Modification du fichier de configuration
// ...
// On crypte à nouveau le fichier de configuration une fois les modifications 
// terminées et enregistrées

A bientôt :-).

Ajouter un commentaire

biuquote
  • Commentaire
  • Prévisualiser
Loading

A propos de l'auteur

Mathieu Perrein - Software Solutions Manager, Software Architect, Trainer MCT, MSP de 2010 à 2012.

 

MSP

 

MSP

MSP

 MSPD

MCT

 

Facebook

 

Ce blog est strictement personnel et les opinions exprimées ici n'engagent donc que moi, et pas mon employeur.

Tags

Vous avez désactivé JavaScript ou bien vous possédez une ancienne version d'Adobe Flash Player. Téléchargez la dernière version de Flash Player.