Authentication in Powershell to windows server 2012 PKI - authentication

I made a script in powershell to make a .REQ from a .INF file. This file (the .REQ) must then be imported into the PKI, which then generates a .CERT.
My problem is that I do not know how to authenticate myself to the PKI from Powershell. Second question if I may ask, how do I choose the certificate Template (in the PKI online screen, I have a choice box in which I choose my template (for eg Wifi client").
Here is my code so far, of course I don't know how to authenticate, that is my main question here. I precise that I know the login and the password (I successfully connect myself using RDP).
# Generate Request File .req
Write-Host " This script generates a .REQ (step 1/3 in certificate creation)"
Write-Host " "
Write-Host " Step 1/3: create .INF file with Key length and other parameters, create a .REQ file"
Write-Host " Step 2/3: import the .REQ file into the Intermediate PKI and generate a .CER"
Write-Host " Step 3/3: from the .CER file, create a .PFX with the exportable key"
# Variables declaration
#
# UID = nom du PDA ou son numero de serie
# $Login = login sur la PKI intermediate
# $Pass = Password sur la PKI intermediate
$Date = (Get-Date).ToString('ddMMyyyy')
Write-Host " "
[string]$UID = read-host "Please enter the Device Name (or Serial Number)"
$Path = "C:\users\youcef\Desktop\Julie\"
$Login = "me"
$Pass = "pass"
# INF File content
$ReqFile = "$UID" + "_" + "$Date" + ".req"
$InfFile = #"
[NewRequest]`r
Subject = "CN=$UID"`r
KeySpec = 1
Exportable = TRUE
RequestType = PKCS10
[PolicyStatementExtension]
Policies=InternalPolicy
[InternalPolicy]
OID= 1.2.3.4.1455.67.89.5
Notice="Legal Policy Statement
[Certsrv_Server]
RenewalKeyLength=1024
RenewalValidityPeriod=Years
RenewalValidityPeriodUnits=2
CRLPeriod=weeks
CRLPeriodUnits=52
CRLDeltaPeriod=Days
CRLDeltaPeriodUnits=0
LoadDefaultTemplates=1
AlternateSignatureAlgorithm=0
"#
# Generate Request File from INF File
Write-Host "Generating Certificate Request file..." -ForegroundColor Yellow;
$MYCERTNAME = "$UID" + "_" + "$Date" + ".inf"
New-Item $MYCERTNAME -type file -value $InfFile
certreq -new $path\$MYCERTNAME $path\$ReqFile
Write-Host " "
Write-Host "Certificate request file for $UID successfully generated!" -foregroundcolor DarkGreen;
# Authentication on PKI: HERE I AM TOTALLY LOST
Connect-CertificationAuthority -ComputerName ca01.company.com
$password = ConvertTo-SecureString "password" -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential `
-argumentlist $Login, $Pass
$serverNameOrIp = "192.168.1.1"
Restart-Computer -ComputerName $serverNameOrIp `
-Authentication default `
-Credential $cred
<any other parameters relevant to you>
$cred = new-object -typename System.Management.Automation.PSCredential `
-argumentlist $username, $password
$serverNameOrIp = "https://pki.mycompany.fr/certsrv/certrqxt.asp"
Restart-Computer -ComputerName $serverNameOrIp `
-Authentication default `
-Credential $cred
<any other parameters relevant to you>
certreq -submit -config "https://pki.mycompany.fr/certsrv/certrqxt.asp" $path\$ReqFile $path\$UID.cer
#certreq -submit -config "https://pki.mycompany.fr\certsrv" $path\$ReqFile $path\$UID.cer
certreq -accept $path\$UID.cer
certutil -exportpfx -p "Welcome123" MY $UID $path\clientcerts\$UID.pfx

I solved my issue in launching my script directly on the server.
Not the best solution, but I neevr managed to use Remote Session in Powershell

Related

How to iterate through each disk associated with Azure VM and get the encryption status using PowerShell?

I want to first get the list of disks associated with a VM and then iterate through each disk properties to identify if the disk is Customer Managed Key(CMK) encrypted or not. How to perform this check using Azure PowerShell?
Generally, To get the encryption status of the virtual machine, you can use the Get-AzVMDiskEncryptionStatus cmdlet with the following syntax:
Get-AzVmDiskEncryptionStatus -ResourceGroupName $resourceGroupName -VMName $vmName
You will see the encryption status of the operating system and the data volumes.
If the above OsVolumeEncrypted or DataVolumesEncrypted displayed Encrypted, you probably have osDisk or dataDisk encrypted with CMK.
You also could capture the encryption settings from each disk by using the following PowerShell commands. For more details, you could read this article.
RGNAME="RGNAME"
VMNAME="VNAME"
$VM = Get-AzVM -Name $VMNAME -ResourceGroupName $RGNAME
$Sourcedisk = Get-AzDisk -ResourceGroupName $RGNAME -DiskName $VM.StorageProfile.OsDisk.Name
Write-Host "============================================================================================================================================================="
Write-Host " OS disk Encryption Settings:"
Write-Host "============================================================================================================================================================="
Write-Host "Enabled:" $Sourcedisk.EncryptionSettingsCollection.Enabled
Write-Host "Version:" $Sourcedisk.EncryptionSettingsCollection.EncryptionSettingsVersion
Write-Host "Source Vault:" $Sourcedisk.EncryptionSettingsCollection.EncryptionSettings.DiskEncryptionKey.SourceVault.Id
Write-Host "Secret URL:" $Sourcedisk.EncryptionSettingsCollection.EncryptionSettings.DiskEncryptionKey.SecretUrl
Write-Host "Key URL:" $Sourcedisk.EncryptionSettingsCollection.EncryptionSettings.KeyEncryptionKey.KeyUrl
Write-Host "============================================================================================================================================================="
foreach ($i in $VM.StorageProfile.DataDisks| ForEach-Object{$_.Name})
{
Write-Host "============================================================================================================================================================="
Write-Host "Data Disk Encryption Settings:"
Write-Host "============================================================================================================================================================="
Write-Host "Checking Disk:" $i
$Sourcedisk=(Get-AzDisk -ResourceGroupName $RGNAME -DiskName $i)
Write-Host "Encryption Enable: " $Sourcedisk.EncryptionSettingsCollection.Enabled
Write-Host "Encryption KeyEncryptionKey: " $Sourcedisk.EncryptionSettingsCollection.EncryptionSettings.KeyEncryptionKey.KeyUrl;
Write-Host "Encryption DiskEncryptionKey: " $Sourcedisk.EncryptionSettingsCollection.EncryptionSettings.DiskEncryptionKey.SecretUrl;
Write-Host "============================================================================================================================================================="
}

Send email Send-MailMessage - PowerShell

I have to send an email using a pre-defined account, I have all the information, smtp server name, email address, user, password. This account uses TTL.
How to create the script to send this email using VBA.
I'm having problems with the Credential parameter, I don't know how to put the username and password
"Send-MailMessage -To 'xxxx#yyy' -from 'kkk#yyyy' -subject 'Teste' -body 'Testando o envio' -stmpserver 'smtp.gmail.com' -UseSSL -Port 587 -Credential (I don't know how to make this parameter) "
See this SO post how to convert a username-password-pair into a PowerShell credential:
$userName = 'test-domain\test-login'
$password = 'test-password'
$pwdSecureString = ConvertTo-SecureString -Force -AsPlainText $password
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, $pwdSecureString
Send-MailMessage -Credential $credential ...
Note: Try to avoid putting passwords into your scripts. Store it somewhere safely, or let the user input it with Read-Host or Get-Credential.

How to execute sqlcmd in Powershell with different domain user credentials

I have a SQL script which I need to execute with credentials that I retrieve from registry.
To store them in the registry
$secureCredential = Get-Credential -Message "Enter service account credential as DOMAIN\Username format."
$credentialName = Read-Host "Enter a name for this credential"
$securePasswordString = $secureCredential.Password | ConvertFrom-SecureString
$userNameString = $secureCredential.Username
New-Item -Path HKLM:\Software\$OrgName\Credentials\$credentialName
New-ItemProperty -Path HKLM:\Software\$OrgName\Credentials\$credentialName -PropertyType String -Name UserName -Value $userNameString
New-ItemProperty -Path HKLM:\Software\$OrgName\Credentials\$credentialName -PropertyType String -Name Password -Value $securePasswordString
To Retrieve
$secureCredUserName = Get-ItemProperty -Path HKLM:\Software\MyCompany\Credentials\TfsBuildAgent -Name UserName
$secureCredPassword = Get-ItemProperty -Path HKLM:\Software\MyCompany\Credentials\TfsBuildAgent -Name Password
$dbCreatorUserName = $secureCredUserName.UserName
$dbCreatorPassword = ConvertTo-SecureString -String $secureCredPassword.Password
Due to DB permission the script has to be executed with these credentials. So
I retrieve them from the registry:
$secureCredUserName = Get-ItemProperty -Path HKLM:\Software\MyCompany\Credentials\TfsBuildAgent -Name UserName
$secureCredPassword = Get-ItemProperty -Path HKLM:\Software\MyCompany\Credentials\TfsBuildAgent -Name Password
$dbCreatorUserName = $secureCredUserName.UserName
$dbCreatorPassword = ConvertTo-SecureString -String $secureCredPassword.Password
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $using:dbCreatorUserName, $using:dbCreatorPassword
Then attempt to execute sqlcmd using Invoke-Command so that I can provide the domain credentials:
Invoke-Command -ComputerName $env:ComputerName -EnableNetworkAccess -Credential $credential -Authentication Default {sqlcmd.exe -b -S 'db-systest' -i C:\Database\Database_Package.sql -E -v }
But get Error:
Microsoft ODBC Driver 11 for SQL Server : Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'..
I have tried both -Authentication Default and -Authentication Negotiate,
the server does not support Kerberos and CredSSP is prohibited by domain policy.

Powershell BitsTransfer https basic authentication syntax

I'm new to PowerShell scripting. I'm struggling with the MS documentation and finding few examples to work with.
I'm trying to automate the weekly download of a large txt file from ntis.gov with a BitsTransfer script. I'm using .ps1 script because apparently SSIS can't do this without writing .NET code.
Access to this text file is via https: with an NTIS issued username and password. How can I specify (hard code) the password into the authentication string? I know this is bad practice. Is there a better way to do this?
My script looks like this-
$date= Get-Date -format yyMMdd
Import-Module BitsTransfer
$Job = Start-BitsTransfer `
-DisplayName DMFweeklytrans `
-ProxyUsage AutoDetect `
-Source https://dmf.ntis.gov/dmldata/weekly/WA$date `
-Destination D:\Test.txt `
-Authentication Basic `
-Credential "myIssuedUsername" `
-Asynchronous
While (($Job.JobState -eq "Transferring") -or ($Job.JobState -eq "Connecting")) {sleep 5}
Switch($Job.JobState)
{
"Transfer Completed" {Complete-BitsTransfer -BitsJobs $Jobs}
default {$Job | Format-List}
}
When you have to provide credentials in non-interactive mode, you can create a PSCredential object in the following way.
$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$yourcreds = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)
$Job = Start-BitsTransfer `
-DisplayName DMFweeklytrans `
-ProxyUsage AutoDetect `
-Source https://dmf.ntis.gov/dmldata/weekly/WA$date `
-Destination D:\Test.txt `
-Authentication Basic `
-Credential $yourcreds `
-Asynchronous

Azure database backup to blob using Powershell

We need to backup the azure database and store it on blob so that it can be restored. I've seen this blog but it uses the third party cmdlets.
http://weblogs.thinktecture.com/cweyer/2011/01/automating-backup-of-a-sql-azure-database-to-azure-blob-storage-with-the-help-of-powershell-and-task-scheduler.html
Could someone please guide/help how above can be achieved using powershell.
Backing up to WA Blob Store is not supported from Azure DB, rather the service does automatic backups for you with PITR capability. You'll find the following documentation useful:
http://msdn.microsoft.com/en-us/library/azure/hh852669.aspx
http://msdn.microsoft.com/en-us/library/azure/jj650016.aspx
Hope this helps.
Here is my powershell script
https://gist.github.com/voxon2/be29a3fd6dabbb9155ca
Here is an article describing many different approaches other than powershell
http://blogs.msdn.com/b/mast/archive/2013/03/04/different-ways-to-backup-your-windows-azure-sql-database.aspx
First get your Azure Automation Settings done (see here).
Edit the blow script and save it as .ps1 file. When you run it for
the first time, it will ask you both your azure automation account and
your database credentials. During this process, it will save your
credentials in a local file securely (see here how it is done). After this time on wards, it uses the saved credentials.
The .psl file and the encrypted credential files should be stored in one
directory
Once you are happy you can schedule it to run in task scheduler.
function Get-MyCredential
{
param(
$CredPath,
[switch]$Help
)
$HelpText = #"
Get-MyCredential
Usage:
Get-MyCredential -CredPath `$CredPath
If a credential is stored in $CredPath, it will be used.
If no credential is found, Export-Credential will start and offer to
Store a credential at the location specified.
"#
if($Help -or (!($CredPath))){write-host $Helptext; Break}
if (!(Test-Path -Path $CredPath -PathType Leaf)) {
Export-Credential (Get-Credential) $CredPath
}
$cred = Import-Clixml $CredPath
$cred.Password = $cred.Password | ConvertTo-SecureString
$Credential = New-Object System.Management.Automation.PsCredential($cred.UserName, $cred.Password)
Return $Credential
}
function Export-Credential($cred, $path) {
$cred = $cred | Select-Object *
$cred.password = $cred.Password | ConvertFrom-SecureString
$cred | Export-Clixml $path
}
#Create a directory with you azure server name to isolate configurations
$FileRootPath = "C:\PowerShellScripts\AzureServerName"
Write-Host "Getting Azure credentials"
$AzureCred = Get-MyCredential ($FileRootPath + "AzureSyncred.txt")
#Use Azure Automation Account
#(If You do not have it will not work with other accounts)
Add-AzureAccount -Credential $AzureCred
Select-AzureSubscription -SubscriptionId "myAzureSubscriptionId"
#DO NOT use tcp:myServerName.database.windows.net,1433 but only myServerName
$ServerName = "myServerName"
$Date = Get-Date -format "yyyy-MM-dd-HH-mm"
$DatabaseName = "myTargetDatabaseName"
$BlobName = $Date + "-" + $DatabaseName.bacpac"
$StorageName = "myStorageAccountName"
$ContainerName = "myContainerNameToStoreBacpacFiles"
$StorageKey = "myStorageAccountKey"
Write-Host "Getting database user credential"
#DO NOT use myDatabaseUsername#myServerName but only myDatabaseUsername
$credential = Get-MyCredential ($FileRootPath + "DbSyncred.xml")
Write-Host "Connecting to Azure database"
$SqlCtx = New-AzureSqlDatabaseServerContext -ServerName $ServerName -Credential $credential
Write-Host "Connecting to Blob storage"
$StorageCtx = New-AzureStorageContext -StorageAccountName $StorageName -StorageAccountKey $StorageKey
$Container = Get-AzureStorageContainer -Name $ContainerName -Context $StorageCtx
Write-Host "Exporting data to blob"
$exportRequest = Start-AzureSqlDatabaseExport -SqlConnectionContext $SqlCtx -StorageContainer $Container -DatabaseName $DatabaseName -BlobName $BlobName
Get-AzureSqlDatabaseImportExportStatus -Request $exportRequest
# use the below script in powershell to execute the script
# powershell -ExecutionPolicy ByPass –File C:\PowerShellScripts\AzureServerName\mySavedScript.ps1 –noexit