Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts

Thursday, February 5, 2015

Change Certificate on Windows Server 2012 R2 Web Application Proxy

With ADFS 3.0 and Web Application Proxy the installation of IIS is not required and necessary. The binding for certificates on the ADFS and WAP service can be done with PowerShell. In this example the same certificate will be used for ADFS and all WAP applications.
The desired certificate must have been installed into the local machines certificate store and the hash value of the certificate will be used to reference the certificate. To list all available certificates run:

dir Cert:\LocalMachine\My

example:

Thumbprint                                Subject
----------                                -------
9450B39AAAE6F203DD68AC1EA1D8D46A8C581E41  CN=certold.mydomain.com
921461C2FF106D4A50A6F3574D1CC25A7D4451B9  CN=certnew.mydomain.com

Now run the PowerShell commands to bind the new certificate:

get-WebApplicationProxyApplication DRS | set-WebApplicationProxyApplication -ExternalCertificateThumbprint 921461C2FF106D4A50A6F3574D1CC25A7D4451B9
get-WebApplicationProxyApplication Workfolders | set-WebApplicationProxyApplication -ExternalCertificateThumbprint 921461C2FF106D4A50A6F3574D1CC25A7D4451B9
Set-WebApplicationProxySslCertificate -Thumbprint 921461C2FF106D4A50A6F3574D1CC25A7D4451B9

Now restart the ADFS service

stop-service "Active Directory Federation Services"
start-service "Active Directory Federation Services"


For verification  you can run these commands and verify that the new hash is active:

get-WebApplicationProxyApplication DRS
get-WebApplicationProxyApplication Workfolders
get-WebApplicationProxySslCertificate


or 

netsh http show ssl

Tuesday, May 6, 2014

Combine ADfind and PowerShell


I really love adfind.exe (http://www.joeware.net/freetools/tools/adfind/index.htm) to search in AD and AD LDS, also if not all these machines part of AD or a different AD. Especially the CSV export is really powerful and so I was wondering how I can feed the adfind CSV output directly in a PowerShell array for further processing.


PS C:\System> $content= (tools\adfind -h dir.server.com:389 -b "o=mycompany" -u "username" -up "userpass" -maxe 25 -csv -csvdelim "|" -f "(objectclass=*)" cn | ConvertFrom-Csv -delimiter "|" )

So the command line above will run adfind to search for all entries on dir.server.com regardless what the object class is, but it will only return the first 25 entries. You can adjust the maxe option. I am working on mostly larger projects so I found the 25 entries limitation convenient and time saving.
Then all results will be available in the content array for further processing with PowerShell, e.g. counting, sorting, check for duplicates on specific attributes, ... ,you name it.




Sunday, August 18, 2013

Microsoft DNS server migration or IP address change

The IP address of a DNS server is almost a in stone written number. That is because the client DNS settings contain the IP address of the DNS server. Some clients are configured via DHCP, others manually, other clients are not known for using this DNS server. But you want catch them all.
So if you come into the situation to relocate your DNS server on the network, build a new machine but you cannot take the IP with you or if you are in the middle of a Active Directory migration project and you have already changed the DHCP settings and you need to find all manually configured machines, especially the unknowns; you can turn on debugging in the Microsoft DNS.

First of all enable the DNS debug logging. Open the DNS management console and click on properties of DNS server. Go to the Debug Logging tab.



Enable Log packets for debugging but disable Outgoing  under Packet direction.


Here the PowerShell script to process the debug files.


New-Variable -Name RegexIP -Force -Description "A regular expression object which matches and validates IP addresses." -Value ([regex]'(?<First>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Second>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Third>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Fourth>2[0-4]\d|25[0-5]|[01]?\d\d?)')
$Files = Get-Content "c:\system\DNS\log1.dns.txt" 

$RegexIP.Matches($Files)|Group value | foreach { 

$chkip=$_."Name"

try { [System.Net.Dns]::GetHostbyAddress($chkip).Hostname }

catch { write-host $chkip  }
#write-host $_.Exception.Message
}

The script does two things. First it reads all IP addresses from the log file and group them, and in a second step it tries to get from DNS the hostnames. If it cannot find a hostname for a an IP address it will just list the IP address in the output list.

output example:

PS C:\system> .\ipstat.ps1
win5010.frontoso.com
win5014.frontoso.com
win5052.frontoso.com
win5510.group.frontoso.com
10.0.1.11
10.0.1.10
win5012.frontoso.com


Now you have a list you start from the top, to change the DNS settings of those machines.
Because not every machine is connected every day you may want run the debug more often or for a longer period of time.
If you have multiple DNS servers you can process them all at once. Just append the debug log file name to $Files, seperated all files names by comma

This article targets DNS but if you get a logfile from any other service you could use the same method to identify who is accessing your server/service. e.g. with IIS log files.



Sunday, June 30, 2013

How to transfer binary files through a RDP session

This post can a) help you to transfer binary files to a server over the RDP session or b) it can help you to close a gap in your server hardening procedures.


a)
Transferring a simple text file is just open the file on your local machine and copy&paste to the file on the server. But what if you have a binary file or you need to transfer multiple files which you have packed into a zip container?
All Windows PKI users should know the certutil.exe command line utility. Besides many other functions, it can also encode and decode files from and to base64. Originally this was planned to convert certificates between the base64 format and the binary format. You can also write a powershell script an use the ToBase64String and FromBase64String method. If you are not familiar with powershell you want use certutil.exe what is pre-installed on Windows 7, 2008 R2, Windows 8, Windows 2012.

1. to get your file prepared for the transfer run:

certutil.exe -encode file.zip filezip.txt

2. next, open the filezip.txt with Notepad and mark all and copy it to the clipboard

3. Open Notepad on the server with the same file name

notepad.exe filezip.txt

and paste the content from the clipboard. Save the file.

4. Last step is to convert the file back to binary using certutil again:

certutil.exe -decode filezip.txt file.zip

Now you can extract your files from the file.zip on the server.

According to comments made to this article http://blogs.msdn.com/b/rds/archive/2006/11/20/why-does-my-shared-clipboard-not-work-part-2.aspx
you cannot transfer any size of data through the RDP session. But you can transfer files in slices you have only to split the text file. And don't worry about the ---- BEGIN CERTIFICATE ----- and ----- END CERTIFICATE ----- line in the text file.



b)
To prevent these transfers you must disable the RDP clipboard in the RDP server settings directly or over Group Policy settings. It seems that this is a server-wide setting and cannot be set on a user-base. Well, you lose a lot of convenience in working with the server console but it is more secure.

Friday, May 31, 2013

PowerShell script to enhance the Windows CA SMTP exit module

Windows CA SMTP exit module

the Windows Certification Authority has a built in feature (Windows Enterprise SKU) to send out emails to inform the PKI administrators if a new pending certificate request waiting for approval or if a new certificate has been issued. Just 2 examples.

The configuration must be done in the registry: See here for an example
http://social.technet.microsoft.com/wiki/contents/articles/2004.active-directory-certificate-services-smtp-exit-module-for-windows-server-2008-r2-example.aspx

Unfortunately you cannot configure it to send the issued certificate to the certificate requestor. For that I wrote a PowerShell script what is also working with the Windows Server 2008 R2 Standard Server.

Config file - sendcert_inc.ps1:

$sendcertpath=".\sendcert"
$msgFrom='noreply@frontoso.com'
$smtphost='127.0.0.1'
$certtmpl="1.3.6.1.4.1.311.21.8.5245527.10310595.8014498.11013764.15833798.137.13192380.4508386" #CorpWebServer
$certfileExt="txt" # fyi: extensions cer and der are blocked by Outlook
$mailbody="mailbody.txt"
$dbscanperiod="03:00" # 01:00 = 1 day, 1:15 = 1 day 15 hours; $dbscanperiod is the max time (now - $dbscanperiod) sendcert goes back in the certificate database, e.g. useful if you have already issued certs for years and you going to enable sendcert now


Mailbody.txt

Hello, attached is the requested certificate.

Please download the certificate and proceed with the SSL/TLS setup of your application.

For your convenience the certificate can be found as attachment and in the mail body.


Thank you,


----------------------------------------------------------------------------
Do not reply to this message. It was sent from an unmonitored email account.




sendcert.ps1

#
# Author: lutz.mueller-hipper@tribaldi.net
# Updates: lutz.mueller-hipper@insight.com
# Date: May 23, 2013 - v3.1
#
clear

import-module ActiveDirectory
# if not yet installed please install the ActiveDirectory PowerShell module
#dism /online /enable-feature /featurename:ActiveDirectory-PowerShell

if (-not (Test-Path .\sendcert_inc.ps1))
{
  write-host "Error: sendcert_inc.ps1 configuration file not found." >>sendcert.log
  exit;
} else {
  . .\sendcert_inc.ps1
}

if (-not (Test-Path $sendcertpath)) { mkdir $sendcertpath >$null}

$Arr_SendCert = @()

write-host "=========================="
write-host Start Send certificate via email to certificate requestor
write-host "=========================="
write-host

#Disposition Description
#20 certificate was issued
#21 certificate is revoked
#30 certificate request failed
#31 certificate request is denied

$reqid_db = @()
$reqid_db = get-content $sendcertpath\reqid_do_not_remove.txt

$reqid_db2 = @()

foreach ( $line in $reqid_db) {
 write-host "Line: "$line
 $reqid_db2 = $reqid_db2 + $line
}

certutil.exe -view -out "Request.requestid,Request.requestid" -restrict "CertificateTemplate=$certtmpl,Disposition=20,NotBefore>now-$dbscanperiod" csv > $sendcertpath\sendcert_scope.csv
$collection = @(Import-CSV $sendcertpath\sendcert_scope.csv)
write-host Issued certs during period: $collection.count

if ($collection.count -gt 0) {
  foreach($CADBentry in $collection)
  {

    $reqid = $CADBentry."request id"

    if ($reqid_db2 -notcontains $reqid) {  
    write-host 'Preparing email for request: ' $reqid

    $certview = certutil.exe -view -out "rawcertificate" -restrict "Request.requestid=$reqid"

    $certemail = @()
    $certattach = @()
    foreach($line in $certview)
     {
     #write-host "Line: " $line

     if ( $line -eq "-----BEGIN CERTIFICATE-----" ) { $certbegin="1" }
     if ( $certbegin -eq "1") {
       #write-host "next person in line pls"
       $certemail = $certemail + $line.trim() + "`n" #+ "`r`n"
       $certattach = $certattach + $line.trim() # + "`n" #+ "`r`n"
     
     }
     if ( $line -eq "-----END CERTIFICATE-----" ) { $certbegin="0" }

    }
    $cadb_requser= certutil.exe -view -out "Requester Name" -restrict "Request.requestid=$reqid" csv
    $requser = $cadb_requser[1]
    $requser = $requser.split("\")
    $user = $requser[1]
    $requser = $user.split("`"")
    $user = $requser[0]

$aduser=""

try {
 $aduser = get-aduser $user -Properties mail
  #$aduser.mail
}

catch [Exception] {
   write-host $_.Exception.Message
}

if ($aduser.mail.length -lt 1) {
  write-host "no email address found"
} else {

    $certattach > $sendcertpath\$reqid"."$certfileExt

$msg=new-object System.Net.Mail.MailMessage
$msg.From=$msgFrom
$msg.to.Add($aduser.mail)
$msg.Subject=$env:computername + ": SSL certificate " + $reqid
$msg.IsBodyHtml=$false
$mailbody = @()
$getmailbody = Get-Content mailbody.txt
foreach ($line in $getmailbody) {
  $mailbody = $mailbody + $line + "`n"
}
$msg.Body=@"

$mailbody

$certemail

-
Ref $reqid_$env:computername

"@

$att = new-object Net.Mail.Attachment($sendcertpath + "\" + $reqid + "." + $certfileExt)
$msg.Attachments.Add($att)


$smtp=new-object System.Net.Mail.SmtpClient
$smtp.host=$smtphost

try {
  $smtp.Send($msg)
  $reqid >> $sendcertpath\reqid_do_not_remove.txt
}
catch {
 write-host $_.Exception.Message
}
finally {
  $smtp.dispose
  $att.dispose()
    }
   }
  }
 }
}


Wednesday, January 9, 2013

Manipulating the Microsoft Deployment Toolkit (MDT) database using PowerShell

I am helping at the school of our children to run the Windows server and workstations. For this and also in my lab I setup MDT to deploy new physical or virtual machines.
At school we buy used/re-furbished desktop or laptop computers a lot and all of them come with a unique Windows license. And we just cannot afford to buy a additional Enterprise license for each.
So MDT helps us also to keep track of all Windows product keys and we put them one time in a spreadsheet (we get some help from students here). So end of 2012 we got 35 new machines and I thought it would be nice to import the spreadsheet into the MDT database and assign the role to install Windows 7 32bit to them as well.

So I found this post http://blogs.technet.com/b/mniehaus/archive/2009/05/15/manipulating-the-microsoft-deployment-toolkit-database-using-powershell.aspx from Michael Niehaus and I downloaded the PowerShell command lets he provided as well.

Our spreadsheet has the format:
- 1. line includes the data headers: computername, Windows product code, machine's serial number
- the other lines have the data
The spreadsheet is delimited by tabs.

And her is the PowerShell I created:

##########


# Import the CSV file into a PowerShell array
$collection = @(Import-CSV .\HPlabcomputers20121231.csv -Delimiter "`t")

# Connect to the SQL database
connect-mdtdatabase -sqlserver . -database MDTDB

# Create for each computer an entry in the MDT database
foreach($computer in $collection)
{
$PCNAME=$computer.ComputerName
$SerialNum=$computer.SerialNum
$ProdKey=$computer.WinProductKey
write-host Importing $PCNAME
new-mdtcomputer -assetTag $computer.ComputerName -serialNumber $SerialNum -settings @{OSInstall='YES'; OSDComputerName=$PCNAME; ProductKey=$ProdKey}
}

# Assign for each computer the role to install Win7 Pro 32 bit
foreach($computer in $collection)
{
$PCNAME=$computer.ComputerName
write-host Updating $PCNAME
# Search for the computername and set the computer role
get-mdtcomputer -assetTag $PCNAME | Set-MDTComputerRole -roles @('Win7_lab_computers')
}


##########

So obviously the user account you use must have SQL permissions on the MDT database to update the database.
Also note that the MDT MMC (aka Deployment Workbench) does not show the new computers if you just click refresh on the Computers view under MDT Deployment Share/Advanced Configuration/Database. Click instead on Database and hit refresh, and go back to the Computers view.