开发者

Protect web.config section outside of web application

I want to create a msbuild task which encrypts certain sections of my web.configs. The following code works great inside a weapplication. Running the code as an msbuild causes an error saying it cannot create the config file..

System.Configuration.Configuration config = WebConfigurationManager.开发者_如何学运维OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.GetSection(sectionName);

if (section != null && !section.SectionInformation.IsProtected)
{
    section.SectionInformation.ProtectSection(provider);
    config.Save();
}

I couldn't find any classes which do the right job. Ideas anyone?


You should create your own custom MSBuild task.

The below code is a custom task.

I've made mine application(winforms) capable, but I marked the lines you can change for web based.

I've created an abstract class with 2 subclasses to handle encrypt and decryption.

Cheers!

namespace MyCompany.MSBuild.Tasks.Security
{

    using System;
    using System.Linq;
    using System.Diagnostics;
    using System.Configuration;
    //using System.Web.Configuration;

    using Microsoft.Build.Framework;
    using Microsoft.Build.Utilities;

    public abstract class ConfigurationProtectorBaseTask : Task
    {
        private static readonly string RSA_PROVIDER = "RSAProtectedConfigurationProvider";
        private static readonly string DATA_PROTECTION_PROVIDER = "DataProtectionConfigurationProvider";

        /// <summary>
        /// Gets or sets the ExePath.  This would be the name of the .exe (or .dll) which has a corresponding .config associated with it.
        /// </summary>
        /// <value>The ExePath.</value>
        [Required]
        public string ExePath { get; set; }

        /// <summary>
        /// Gets or sets the SectionName of the configuration file you are trying to encrypt.
        /// </summary>
        /// <value>The SectionName.</value>
        [Required]
        public string SectionName { get; set; }

        /// <summary>
        /// Gets or sets the Provider.
        /// </summary>
        /// <value>The Provider.</value>
        [Required]
        public string Provider { get; set; }

        /// <summary>
        /// Task Entry Point.
        /// </summary>
        /// <returns></returns>
        public override bool Execute()
        {
            if (!String.IsNullOrEmpty(this.Provider))
            {
                if (String.Equals(this.Provider, DATA_PROTECTION_PROVIDER, StringComparison.OrdinalIgnoreCase) || String.Equals(this.Provider, RSA_PROVIDER, StringComparison.OrdinalIgnoreCase))
                { }
                else
                {
                    Log.LogWarning(string.Format("Provider must be either '{0}' or '{1}'. Your value was '{2}'.", DATA_PROTECTION_PROVIDER, RSA_PROVIDER, this.Provider));
                    return false;
                }
            }

            if (!String.IsNullOrEmpty(this.ExePath))
            {
                Log.LogCommandLine(string.Format("{0}", this.ExePath));
                Console.WriteLine(this.ExePath);
            }

            InternalExecute();
            return !Log.HasLoggedErrors;
        }

        protected abstract void InternalExecute();

        protected Configuration GetConfiguration()
        {
            //WebVersion
            //Configuration config = WebConfigurationManager.OpenWebConfiguration(this.ApplicationPath);

            //NonAspNet version
            Configuration config = ConfigurationManager.OpenExeConfiguration(ExePath);

            return config;
        }

    }
}




namespace MyCompany.MSBuild.Tasks.Security
{
    using System;
    using System.Linq;
    using System.Diagnostics;
    using System.Configuration;
    using System.Web.Configuration;

    using Microsoft.Build.Framework;
    using Microsoft.Build.Utilities;

    public class ConfigurationProtectorEncrypterTask : ConfigurationProtectorBaseTask 
    {

        /// <summary>
        /// Internal Execute Wrapper.
        /// </summary>
        protected override void InternalExecute()
        {
            Configuration config = base.GetConfiguration();
            ConfigurationSection section = config.GetSection(this.SectionName);
            if (section != null && !section.SectionInformation.IsProtected)
            {
                section.SectionInformation.ProtectSection(this.Provider);
                config.Save();
            }
        }

    }
}









namespace MyCompany.MSBuild.Tasks.Security
{
    using System;
    using System.Linq;
    using System.Diagnostics;
    using System.Configuration;
    using System.Web.Configuration;

    using Microsoft.Build.Framework;
    using Microsoft.Build.Utilities;

    public class ConfigurationProtectorDecrypterTask : ConfigurationProtectorBaseTask
    {

        /// <summary>
        /// Internal Execute Wrapper.
        /// </summary>
        protected override void InternalExecute()
        {
            Configuration config = base.GetConfiguration();
            ConfigurationSection section = config.GetSection(this.SectionName);
            if (section != null && section.SectionInformation.IsProtected)
            {
                section.SectionInformation.UnprotectSection();
                config.Save();
            }
        }

    }
}









::::Save this as: ConfigurationProtectorTaskTest.msbuild 

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="AllTargetsWrapper" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

  <UsingTask AssemblyFile="MyCompany.MSBuild.dll" TaskName="ConfigurationProtectorEncrypterTask"/>
  <UsingTask AssemblyFile="MyCompany.MSBuild.dll" TaskName="ConfigurationProtectorDecrypterTask"/>


  <Target Name="AllTargetsWrapper">
    <CallTarget Targets="ConfigurationProtectorEncrypterTask1" />
    <CallTarget Targets="ConfigurationProtectorDecrypterTask2" />
  </Target>


  <PropertyGroup>
    <MyExePath>C:\SomeFolder\MyCompany.SomeExe.exe</MyExePath>
    <MySectionName>connectionStrings</MySectionName>
    <MyProvider>RSAProtectedConfigurationProvider</MyProvider>
  </PropertyGroup>



  <Target Name="ConfigurationProtectorEncrypterTask1">
    <ConfigurationProtectorEncrypterTask ExePath="$(MyExePath)" SectionName="$(MySectionName)" Provider="$(MyProvider)">
    </ConfigurationProtectorEncrypterTask>
  </Target>


  <Target Name="ConfigurationProtectorDecrypterTask2">
    <ConfigurationProtectorDecrypterTask ExePath="$(MyExePath)" SectionName="$(MySectionName)" Provider="$(MyProvider)">
    </ConfigurationProtectorDecrypterTask>

  </Target>



</Project>





:REM BAT FILE TO CALL THE ABOVE .msbuild file

call "%VS90COMNTOOLS%\vsvars32.bat"
del *.log
msbuild /target:ConfigurationProtectorEncrypterTask1 ConfigurationProtectorTaskTest.msbuild /l:FileLogger,Microsoft.Build.Engine;logfile=ConfigurationProtectorEncrypterTask1.log
msbuild /target:ConfigurationProtectorDecrypterTask2 ConfigurationProtectorTaskTest.msbuild /l:FileLogger,Microsoft.Build.Engine;logfile=ConfigurationProtectorDecrypterTask2.log

This will help as well: http://www.codeproject.com/KB/dotnet/EncryptingTheAppConfig.aspx http://www.beansoftware.com/ASP.NET-Tutorials/Encrypting-Connection-String.aspx

But the encapsulation into a MSBuild Task is my contribution.

The second URL above also mentions a command line method:

Here is that quoted material (partial quote that is):::

Encryption/Decryption using aspnet_regiis.exe command line tool

You can also encrypt and decrypt sections in the Web.config file using the aspnet_regiis.exe command-line tool, which can be found in the \Microsoft.Net\Framework\version directory. To encrypt a section of the Web.config using the DPAPI machine key with this command-line tool, use following command.

aspnet_regiis.exe -pe "connectionStrings" -app "/YourWebSiteName" –prov "DataProtectionConfigurationProvider"

To decrypt connectionStrings section using this tool, you can specify following command in aspnet_iisreg.exe tool.

aspnet_regiis.exe -pd "connectionStrings" -app "/YouWebSiteName"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜