After Deploying mywebsite to server can I encrypt the web.config file? - encryption

I am trying to encrypt the web.config file after deploying automatically.
As per the Link :https://blogs.iis.net/msdeploy/archive/2013/07/09/webdeploy-3-5-rtw.aspx
I am using below command:
msdeploy.exe –verb:sync –source:iisapp=”sourceTestSite” –dest:iisapp=”destinationTestSite” –EnableRule:EncryptWebConfig
But then I am getting error:
Error Code: ERROR_FAILED_TO_ENCRYPT_WEB_CONFIG
I do not want to first encrypt and then deploy. I am thinking to run deployment script and after deployment it should encrypt automatically probably using MSDEploy command.
I tried below threads but did not get any help:
Failed to encrypt destination web.config when using MS build plugin in Jenkins
Also I wanted to keep my secret file in separate location but I found encryption process will not work for that
How to encrypt a file linked to a web.config
This time I am trying to run command on remote server to encrypt the web.config file by using below code. I am running below code in my machine and trying to encrypt the web.config file present on my myRemoteServer.
$currentDirectory = (Get-Location)
$user = "domain1\username1"
$section = "appSettings"
$app= "/MyWeb"
$version="v4.0.30319"
$computername ="myRemoteServer"
$pwd = ConvertTo-SecureString -String "mysecret#11" -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user,$pwd
$encryptcmd1= Set-Location "C:\windows\Microsoft.Net\Framework\$version"
$encryptCmd2 = ".\aspnet_regiis.exe -pe ""appSettings"" -app ""/MyWeb"""
$encryptCmd = "$encryptcmd1 $encryptcmd2"
try
{
invoke-command -ComputerName $computername -Credential $credential -ScriptBlock {$encryptCmd}
}
catch
{
Log-Message $_
}
Set-Location $currentDirectory
It doesn't throw any exception. However it is not working and not encrypting web.config file on that server.
I want to know where / what is wrong here.

his function will encrypt a sections of a web.config file.
function Encrypt-ConfigurationSection([int] $id, [string] $app, [string] $section, [string] $version){
$currentDirectory = (Get-Location)
Set-Location "C:\windows\Microsoft.Net\Framework\$version\"
.\aspnet_regiis.exe -pe $section -app $app -site $id -prov "RsaProtectedConfigurationProvider"
Set-Location $currentDirectory
}
Example call
Encrypt-ConfigurationSection 1 ‘/WebApplication1’ ‘connectionStrings’ ‘v4.0.30319’
This function will decrypt a sections of a web.config file.
function Decrypt-ConfigurationSection([int] $id, [string] $app, [string] $section, [string] $version){
$currentDirectory = (Get-Location)
Set-Location "C:\windows\Microsoft.Net\Framework\$version\"
.\aspnet_regiis.exe -pd $section -app $app -site $id
Set-Location $currentDirectory
}
Example Call
Decrypt-ConfigurationSection 1 ‘/WebApplication1’ ‘connectionStrings’ ‘v4.0.30319’
I got help from this website:
https://joshjoubert.wordpress.com/2013/03/28/encrypting-and-decrypting-sections-of-a-web-config-with-powershell/

Related

PGP encryption with multiple keys in mule

Given that PGP supports encryption using multiple public keys, how it can be achieved in mulesoft?
adding two keys in Public Key Ring File Name field on encryption config window for pgp encrypter tab results in error as org.mule.module.pgp.exception.MissingPGPKeyException: No key file found in: abc.gpg,test.pgp
Is it possible to add multiple public keys from this encrypt module or else how it can be done? mule runtime : 3.8.5
much appreciate any help. Thank you!
I solved this by using java component- invoking terminal and running gpg encrypt command from java runtime. I am just checking for OS first to build a command string to run its respective terminal
boolean isWindows = System.getProperty("os.name")
.toLowerCase().startsWith("windows");
/*gpg command options may vary as per your requirement. multiple --recipient option here is the way to encrypt with multiple public keys.
Using StringBuilder helps to build this string from input/dynamic values.
*/
String command = "gpg --pgp6 --armor --batch --output encryptedHelloWorld.pgp --trust-model always --recipient "<part of UserID1 (either name or emailId)>" --recipient "<part of UserID2>" --encrypt helloWorld.txt"
/*in case you need to change directory to where your file is to encrypt it from one command, you could append this
`"cd"+ <your path to file> "&" + command` ----> for windows
`"cd"+ <your path to file> ";" + command` ----> for linux
*/
public int executeCommand(String command) throws IOException, InterruptedException {
Process pr;
if (isWindows) {
String[] cmd = { "cmd.exe", "/c", command };
pr = Runtime.getRuntime().exec(cmd);
}
else {
String[] cmd = { "/bin/sh", "-c", command };
pr = Runtime.getRuntime().exec(cmd);
}
int exitStatus = pr.waitFor(); // this gives you value 0 if success or other than 0 which ties to error message
errorInputStream = pr.getErrorStream(); //streaming error message
return exitStatus;
}

No results while applying Export-Csv command in PowerShell script

The following script execute a query against a database with the command $con.ConnectionString = "Data Source=$DB_PATH" and export all the results to a CSV file. Firstly, when I createad it, the file was working fine with no issue.
$DB_PATH = "C:\ProgramData\PROISER\ISASPSUS\datastore\dsfile.db"
Add-Type -Path "C:\Program Files\System.Data.SQLite\2010\bin\System.Data.SQLite.dll"
$con = New-Object -TypeName System.Data.SQLite.SQLiteConnection
$con.ConnectionString = "Data Source=$DB_PATH"
$con.Open()
$sql = $con.CreateCommand()
$sql.CommandText = "SELECT * FROM analysis"
$adapter = New-Object -TypeName System.Data.SQLite.SQLiteDataAdapter $sql
$data = New-Object System.Data.DataSet
[void]$adapter.Fill($data)
$table = $data.Tables
foreach ($t in $table) {
$CurrentDate = Get-Date
$CurrentDate = $CurrentDate.ToString('MM-dd-yyyy')
$t | Export-Csv -Path "C:\Users\santiago.corso\analisis_$CurrentDate" -NoTypeInformation -Append
}
$sql.Dispose()
$con.Close()
From one point to another, the execution of the ps1 file stored in a task scheduled inside Task Scheduler in Windows started showing the "how to open this file" window and no file was created from that point onwards.
Executing the ps1 file on its own works fine, but inside a scheduled task is when the problem occurs.

MSB4018 Error Visual Studio 2015 ASP.Net and Error Publish Web App to Azure

I am working with Visual Studio 2015 Community with Azure 2.9 For the first time. I tried creating a brand new ASP.Net Web Application. The default template build and viewed in the Browser with no issues.
I tried publishing the site using Azure. When doing so I get this error
The "InvokePowerShell" task failed unexpectedly.
System.Management.Automation.CommandNotFoundException: The term '[cmdletbinding(SupportsShouldProcess=$true)]
param($publishProperties, $packOutput, $nugetUrl)
# to learn more about this file visit http://go.microsoft.com/fwlink/?LinkId=524327
$publishModuleVersion = '1.0.1'
function Get-VisualStudio2015InstallPath{
[cmdletbinding()]
param()
process{
$keysToCheck = #('hklm:\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0',
'hklm:\SOFTWARE\Microsoft\VisualStudio\14.0',
'hklm:\SOFTWARE\Wow6432Node\Microsoft\VWDExpress\14.0',
'hklm:\SOFTWARE\Microsoft\VWDExpress\14.0'
)
[string]$vsInstallPath=$null
foreach($keyToCheck in $keysToCheck){
if(Test-Path $keyToCheck){
$vsInstallPath = (Get-itemproperty $keyToCheck -Name InstallDir -ErrorAction SilentlyContinue | select -ExpandProperty InstallDir -ErrorAction SilentlyContinue)
}
if($vsInstallPath){
break;
}
}
$vsInstallPath
}
}
$vsInstallPath = Get-VisualStudio2015InstallPath
$publishModulePath = "{0}Extensions\Microsoft\Web Tools\Publish\Scripts\{1}\" -f $vsInstallPath, $publishModuleVersion
if(!(Test-Path $publishModulePath)){
$publishModulePath = "{0}VWDExpressExtensions\Microsoft\Web Tools\Publish\Scripts\{1}\" -f $vsInstallPath, $publishModuleVersion
}
$defaultPublishSettings = New-Object psobject -Property #{
LocalInstallDir = $publishModulePath
}
function Enable-PackageDownloader{
[cmdletbinding()]
param(
$toolsDir = "$env:LOCALAPPDATA\Microsoft\Web Tools\Publish\package-downloader-$publishModuleVersion\",
$pkgDownloaderDownloadUrl = 'http://go.microsoft.com/fwlink/?LinkId=524325') # package-downloader.psm1
process{
if(get-module package-downloader){
remove-module package-downloader | Out-Null
}
if(!(get-module package-downloader)){
if(!(Test-Path $toolsDir)){ New-Item -Path $toolsDir -ItemType Directory -WhatIf:$false }
$expectedPath = (Join-Path ($toolsDir) 'package-downloader.psm1')
if(!(Test-Path $expectedPath)){
'Downloading [{0}] to [{1}]' -f $pkgDownloaderDownloadUrl,$expectedPath | Write-Verbose
(New-Object System.Net.WebClient).DownloadFile($pkgDownloaderDownloadUrl, $expectedPath)
}
if(!$expectedPath){throw ('Unable to download package-downloader.psm1')}
'importing module [{0}]' -f $expectedPath | Write-Output
Import-Module $expectedPath -DisableNameChecking -Force
}
}
}
function Enable-PublishModule{
[cmdletbinding()]
param()
process{
if(get-module publish-module){
remove-module publish-module | Out-Null
}
if(!(get-module publish-module)){
$localpublishmodulepath = Join-Path $defaultPublishSettings.LocalInstallDir 'publish-module.psm1'
if(Test-Path $localpublishmodulepath){
'importing module [publish-module="{0}"] from local install dir' -f $localpublishmodulepath | Write-Verbose
Import-Module $localpublishmodulepath -DisableNameChecking -Force
$true
}
}
}
}
try{
if (!(Enable-PublishModule)){
Enable-PackageDownloader
Enable-NuGetModule -name 'publish-module' -version $publishModuleVersion -nugetUrl $nugetUrl
}
'Calling Publish-AspNet' | Write-Verbose
# call Publish-AspNet to perform the publish operation
Publish-AspNet -publishProperties $publishProperties -packOutput $packOutput
}
catch{
"An error occurred during publish.`n{0}" -f $_.Exception.Message | Write-Error
}' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
at System.Management.Automation.Runspaces.AsyncResult.EndInvoke()
at System.Management.Automation.PowerShell.EndInvoke(IAsyncResult asyncResult)
at Microsoft.Web.Publishing.Tasks.InvokePowerShell.Execute()
at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() WebApplication1 0
I am assuming I missed something in my install? Anyone know what this error is or how to get passed it?
I upvoted this in the past, then apparently found the answer somewhere else, then forgot the answer again and ended up here again.
Adding <AutoParameterizationWebConfigConnectionStrings>False</AutoParameterizationWebConfigConnectionStrings>
in the csproj on the right PropertyGroup fixed the problem for me.

How can I download a basic authentication-protected file in a Chocolatey install script?

The Install-ChocolateyZipPackage commandlet does not seem to support basic authentication when it comes to downloading files, i.e. via an URL such as https://user:password#example.com/file.zip. How can I work around this in my Chocolatey install script, i.e. download the file in question (e.g. https://user:password#example.com/file.zip) before I install it via Install-ChocolateyZipPackage?
Thomas put up a good answer in the group forum - https://groups.google.com/forum/#!msg/chocolatey/e4lcPIrLhis/vfSUVe0SZcIJ
As far as I know, authentication is not supported. But you could
specify wget as dependency and use that to download the file.
I use it in one of my packages for authentication and it works fine:
https://chocolatey.org/packages/rukerneltool#files (look at chocolateyInstall.ps1)
On Linux, wget would be the first choice to handle such things in a
Bash script.
But if the software you want to make a package of is Open Source, you
could integrate it directly into the package. That makes it easier.
Code for this is (in case it is later changed:
$webClient = New-Object System.Net.WebClient
$webClient.Credentials = New-Object System.Net.Networkcredential($username, $password)
Write-Output $('Downloading' + $url + '…')
$webClient.DownloadFile($url, $zipFilePath)
I use a similar way without wget, to fetch artifacts from our company's buildserver
$packageName = 'mycompanypackage'
$installerType = 'exe'
$username = 'chocolatey'
$password = '************'
$url = 'http://bamboo.mycompany.com/browse/DP-RS/latestSuccessful/artifact/JOB1/Setup/setup.exe'
$downloadFile = $url.Substring($url.LastIndexOf("/") + 1)
$url = $url+'?os_authType=basic'
$url64 = $url
$silentArgs = '/VERYSILENT /NORESTART /SUPPRESSMSGBOXES'
if (Test-Path "$downloadFile") {Remove-Item "$downloadFile"}
$webclient = new-object System.Net.WebClient
$credCache = new-object System.Net.CredentialCache
$creds = new-object System.Net.NetworkCredential($username, $password)
$credCache.Add($url, "Basic", $creds)
$webclient.Credentials = $credCache
$webclient.DownloadFile($url, $downloadFile)
Install-ChocolateyInstallPackage "$packageName" "$installerType" "$silentArgs" "$downloadFile"

How can I have a Windows Service, installed using OctopusDeploy, use an app.config?

So far, I've been able to create a Windows Service, which I can then get TeamCity to build and pack up and make available for Octopus Deploy.
What I can't seem to do, is have an app.config which has a connection string in it and use that connection string.
The following is my Deploy.ps1:
# These variables should be set via the Octopus web portal:
#
# ServiceName - Name of the Windows service
#
# sc.exe is the Service Control utility in Windows
# Default the service name
if (! $ServiceName)
{
$ServiceName = "OctoService"
}
Write-Host "Service Name:" $ServiceName
# Get the exe name based ont the directory
$contentPath = (Join-Path $OctopusPackageDirectoryPath "content")
$configName = (Get-ChildItem $contentPath\*.config -Name | Select-Object -First 1)
$binPath = (Join-Path $OctopusPackageDirectoryPath "lib\net40")
$exeName = (Get-ChildItem $binPath\*.exe -Name | Select-Object -First 1)
$fullPath = (Join-Path $binPath $exeName)
Write-Host "Service Path:" $fullPath
Write-Host "Config Path:" (Join-Path $contentPath $configName)
Copy-Item (Join-Path $contentPath $configName) $binPath
$service = Get-Service $ServiceName -ErrorAction SilentlyContinue
if (! $service)
{
Write-Host "The service will be installed"
New-Service -Name $ServiceName -BinaryPathName $fullPath -StartupType Automatic
}
else
{
Stop-Service $ServiceName -Force
$fullPath = Resolve-Path $fullPath
& "sc.exe" config "$ServiceName" binPath= $fullPath start= auto | Write-Host
Start-Service $ServiceName
}
Here's my .nuspec file:
<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<metadata>
<id>$id$</id>
<version>$version$</version>
<title>$title$</title>
<authors>$author$</authors>
<owners>$author$</owners>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>$description$</description>
<copyright>Copyright 2012</copyright>
</metadata>
<files>
<file src="app.config" target="content" />
<file src="Deploy.ps1" />
</files>
</package>
If I try to access ConfigurationManager.ConnectionStrings["MyConnectionString"], I'll get a null reference.
Any suggestions?
my money is on you needing to name your app.config to exename.exe.config so it is picked up by your service.
App.config is the 'temporary' name used in the ide, it gets renamed as part of the build to whatever the exe name is

Resources