【问题标题】:Read encrypted connection string in Machine.config from Powershell从 Powershell 读取 Machine.config 中的加密连接字符串
【发布时间】:2018-07-08 20:50:54
【问题描述】:

是否可以从 Powershell 脚本中读取 Machine.config 中的加密连接字符串?

出于安全原因,我们正在尝试将硬编码的连接字符串从 PowerShell 脚本移动到 Machine.config

更新:Powershell 脚本应该从 Machine.config 读取连接字符串(通过 aspnet_regiis 加密)并连接到数据库。

【问题讨论】:

    标签: powershell powershell-3.0 machine.config


    【解决方案1】:

    我不确定 PowerShell 在您的问题中的位置。如果您使用 aspnet_regiis.exe 之类的内置命令来加密配置部分,那么您的 IIS 站点不知道该部分已加密。

    我不确定在 machine.config 中添加内容如何使应用程序更安全,因为任何透明读取它的内容都适用于该机器上的任何应用程序。

    .net 配置的工作方式是你有一个 some.exe,它有一个 some.exe.config 文件。当您部署 some.exe 时,您可以(应该?)包括一个加密敏感部分的步骤。该应用程序仍将只是读取数据,而不知道它已被加密。

    但同样是应用程序,而不是读取加密值的 powershell。

    这是我用来加密/解密部分的脚本的一部分。谨慎使用,因为加密的数据只能在同一台机器(并且可能是同一台操作系统)上解密。 YMMV

    $appConfig = "your.exe"
    $sectionName = "appSettings"
    $dataProtectionProvider = "DataProtectionConfigurationProvider"
    
    if (-not (Test-Path $path) ) { throw "Unable to find $($appConfig) $($path)" }
    
    $configuration = [System.Configuration.ConfigurationManager]::OpenExeConfiguration($path)
    $section = $configuration.GetSection($sectionName)
    if (-not $section.SectionInformation.IsProtected) {
        $section.SectionInformation.ProtectSection($dataProtectionProvider)
        $section.SectionInformation.ForceSave = $true
        $configuration.Save([System.Configuration.ConfigurationSaveMode]::Full)
        Write-Information -Message "$($sectionName) in $($appConfig) has been protected from casual users"
    }
    else {
        Write-Information -Message "$($sectionName) in $($appConfig) is already protected"
        $section.SectionInformation.UnprotectSection()
        $section.SectionInformation.ForceSave = $true
        $configuration.Save([System.Configuration.ConfigurationSaveMode]::Full)
        Write-Information -Message "$($sectionName) in $($appConfig) protection removed"
    }
    

    这是加密/解密配置部分的完整脚本的 sn-p。

    【讨论】:

    • 由于连接字符串存储为纯文本,我们将其移动到 machine.config 并通过 aspnet_regiis.exe 实用程序进行加密。我们希望 Powershell 脚本从 Machine.config 读取加密的连接字符串并连接到 SQL DB 服务器以执行业务逻辑。我不确定我们是否需要显式解密连接,或者 Powershell 是否会像 .net 应用程序一样默认处理它,如果它是用 aspnet_regiis.exe 加密的,我们不必指定逻辑。谢谢
    • 只要您使用 .net ConfigurationManager 方法访问配置部分,加密设置对调用者是透明的。有很多其他方法会导致加密设置失败,因此请务必将实际值存储在 .config 文件之外的安全位置。如果你有 Azure,那么 Azure Keyvault 是一个安全存储机密的好工具。 (如果这个答案有帮助,请投票)
    猜你喜欢
    • 1970-01-01
    • 2011-04-16
    • 2012-10-10
    • 2016-01-21
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多