Automation of Web Application Creation in Managed Environments (Part VII: Edit registry and host file)

This is the seventh and last article of this series. It is related to another article I already posted on the subject. This article tries to automate what was achieved in that article, i.e. edit the registry entry for BackConnectionHostNames to contain all hosted Hostnames as well as update the Local Host-File. Why would you do that? Because if you don’t then you will have a problem with calls from the server calling resources on the same server running into the loopback issue.

In essence the loopback issue is caused by a (valid!) security measure where the server should not call any resources on the system as this can mean a security loop hole. Webservers and especially webservers hosting webservices are a special case, thus you need to configure for this case and that is what you do by registering the allowed host names in the host-file and the registry.

So let’s get into the BackConnectionHostNames Registry Edit.

$path = "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0\BackConnectionHostNames"
$root_path = "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0"
$name = "BackConnectionHostNames"

$value = @"

if (Test-Path $path) {  
    Write ($path + " exists!")  
} else {  
    Write ($path + " needs to be created!") 
    New-ItemProperty -Path $root_path -Name $name -PropertyType MultiString -Value $value

So this one is pretty easy. You can improve it by getting the multi-string content from a text file or something silly like that. So I have 3 variables at the top and these were the early days, you can see that because I omitted the semi-colon at the end of the line, which I usually do these days (except for function calls). Also the two last variables could be used to create the first, so it’s redundant, but that’s not even going to change the semantics of the script. The variable ‘value’ basically contains lines where each line represents a hostname.

Next the script checks if the path to the item property exists. It makes sure not to overwrite it, when a value exists. You could easily change this by adding the following line

Set-ItemProperty -Path $root_path -Name $name -Value $value -confirm:$false


Write ($path + " exists!")

The only time you will get a problem is when there already is a property with this name and this property does not have the type of a multi-valued string.

If the property does not exist it gets created with the path, name, type and value given. It’s almost as if you create a directory with PowerShell which makes sense because you can also walk through the registry the same way you do a directory of files and folders.

Now that we have set up the registry we can choose to hit “Windows + R” for “Run” and type ‘regedit’ then you navigate through the registry editor to the right place…hklm\system\CurrentControlSet\Control\Lsa\MSV1_0\ and then check the backconnectionhostnames value. It should be fine with the values given above.

Okay, the next step is getting the host file in order. You can do this manually. Honestly this is basically nothing but an ip address and a hostname separated by a tab or two at the most. Find the script below.

$inpath = ([string] (Split-Path -parent $MyInvocation.MyCommand.Definition) + "\hosts.txt")
$definitions = ([string] (Split-Path -parent $MyInvocation.MyCommand.Definition) + "\hosts_definitions.txt")

$outpath = ([string] (Split-Path -parent $MyInvocation.MyCommand.Definition) + "\hosts")

$content = get-content $inpath;

$content > $outpath 

import-csv $definitions -delimiter ';' | % {
    Write ("    " + $_.IP + "    " + $_.HostName) >> $outpath;
    Write ("    " + $_.IP + "    " + $_.HostName);
if (Test-Path $outpath) {
    copy-item $outpath "C:\windows\system32\drivers\etc\hosts" -confirm:$false -force
    Write ("Copied host-file");
    remove-item $outpath

The hosts.txt and the hosts_definitions.txt need to be in the directory the script is run in ($MyInvocation.MyCommand.Definition). The hosts file (without the .txt) will be copied to the same directoy and then later on moved to the correct directory. For each of the lines in the input file you can add the IP and the hostname with 4 spaces in between. Bam! Finito! Your host file is finished and ready to be sent to the correct folder. The correct folder in this case is the drivers\etc folder of the system directory. You move it and you delete the source. There you go. That’s it.

This is what the input file looks like:


and just for completeness, here is what the host file looks like when delivered with a fresh windows installation:

# Copyright (c) 1993-2009 Microsoft Corp.
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
# For example:
#          # source server
#              # x client host

# localhost name resolution is handled within DNS itself.
#       localhost
#	::1             localhost

So now you have your registry and host files set up to allow the loopback check done in the right way! The only thing is that you need to make this re-runnable in some fashion or at least be able to add new host names in the future as we will see can be done with the scripts in all other parts. So using the set-propertyitem command might be a really good idea.

Additionally I want to touch on the topic of disallowing SSL 2.0 for IIS on Windows Server and automating that as well. This topic is described in another very detailed knowledge base article, so I will only briefly give you an overview of why you would want to do this. It fits well with editing the registry for the backconnectionhostname entry, because that uses the same mechanics but isn’t quite as long/ complex.

Basically this belongs into the context of security and server hardening. You will want to disallow the use of certain certificates that IIS may allow but you do not. At one of my customers a security department basically made this a requirement for our servers. So doing this on every server (because any SharePoint Prerequisite Install configures the WebServer role) of the farm is quite tedious.

The problem with these certificate types (cryptos) is that they have names containing slashes (‘/’) in them, e.g. RC2 128/128. The slash is used as a path separator in the context of powershell, so all the blogs tell you: you need to use the C# API. Okay so in my first version of the script I actually just added the first part (“RC2 128”) and manually edited the entries later (add “/128”). Yuck! So today I finally made this work in a sensible fashion. Finally I as the administrator no longer care about which cryptos are actually disabled and can only run the script and be done with this. As it’s actually fast as scripting should be it’s a couple of script executions and less than a minute for a farm. Nice!

So how did I go about this? I found this RegistryKey Class on msdn but I didn’t know how to get an object of the type [Microsoft.Win32.RegistryKey], because when do you actually have a Handle (basically what I was trying to get in the first place, so trying to find a handle is the same problem as before or an IntPtr (Int Pointer)) so I had to scan through multiple google results before finding something about RegistryKey Object and OpenSubKey. That’s where I found the constructor, which is basically a special form of the path (…prefixed “Registry::”), so that was the last missing piece to script the below:

function Get-LocalMachineRegistryKeyForEdit([string] $registryPath, [string] $SubKey) {
    $fullParentPath = "Registry::HKLM\" + $registryPath;
    if ( Test-Path $fullParentPath ) {
        $reg = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($registryPath);
        $reg.OpenSubKey($SubKey, $true);

function New-SubKey([Microsoft.Win32.RegistryKey] $key, [string] $subkey) {
    $fullParentPath = "Registry::" + $key.Name;
    if ( Test-Path $fullParentPath ) {
        $fullChildPath = $fullParentPath + "\" + $subkey;
        if ( -not (Test-Path $fullChildPath) ) {
            $newsubkey = $key.CreateSubKey($subkey);

function New-PathDWORD([Microsoft.Win32.RegistryKey] $key, [string] $subkey, [string] $valueType, [string] $valueName, [string] $value) {
    $fullParentPath = "Registry::" + $key.Name;
    if ( Test-Path $fullParentPath ) {
        $fullChildPath = $fullParentPath + "\" + $subkey;
        if ( -not (Test-Path $fullChildPath) ) {
            $newsubkey = $key.CreateSubKey($subkey);
        $k = Get-Item -Path ($fullChildPath)  

        if($k -ne $null) {
            $kProp = Get-ItemProperty -Path $fullChildPath -Name $valueName -erroraction silentlycontinue
            if($kProp -eq $null) {
                New-ItemProperty -Path $fullChildPath -Name $valueName -PropertyType $valueType -Value $value

# Registry::HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL
$schannelPath = "SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL";

# Registry::HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers
$ciphers = "Ciphers";

$cip = Get-LocalMachineRegistryKeyForEdit $schannelPath $ciphers

#enabled == 0
Write "SCHANNEL SECTION - Enabled=0";

New-SubKey $cip "NULL" "DWORD" "Enabled" "0"

New-PathDWORD $cip "RC2 40/128" "DWORD" "Enabled" "0"
New-PathDWORD $cip "RC2 56/128" "DWORD" "Enabled" "0"
New-PathDWORD $cip "RC4 40/128" "DWORD" "Enabled" "0"
New-PathDWORD $cip "RC4 56/128" "DWORD" "Enabled" "0"
New-PathDWORD $cip "RC4 64/128" "DWORD" "Enabled" "0"
New-PathDWORD $cip "RC2 128/128" "DWORD" "Enabled" "0"
New-PathDWORD $cip "RC4 128/128" "DWORD" "Enabled" "0"

#enabled == 1
Write "SCHANNEL SECTION - Enabled=1";

New-PathDWORD $cip "DES 56/56" "DWORD" "Enabled" "0xffffffff";
New-PathDWORD $cip "Triple DES 168/168" "DWORD" "Enabled" "0xffffffff"; # Triple DES 168/168

# ------
# Hashes

$hashes = "Hashes";
$hash = Get-LocalMachineRegistryKeyForEdit $schannelPath $hashes

Write "HASHES SECTION - Enabled=0";

#enabled == 0
New-PathDWORD $hash "MD5" "DWORD" "Enabled" "0"; # MD5

Write "HASHES SECTION - Enabled=1";

#enabled == 1
New-PathDWORD $hash "SHA" "DWORD" "Enabled" "0xffffffff"; # SHA


$keyexchalgo = "KeyExchangeAlgorithms";
$algo = Get-LocalMachineRegistryKeyForEdit $schannelPath $keyexchalgo

New-PathDWORD $algo "PKCS" "DWORD" "Enabled" "0xffffffff"; # PKCS


$protocolsPath = "SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols";
$protocols = "Protocols";

$prot = Get-LocalMachineRegistryKeyForEdit $schannelPath $protocols

$pct10 = "PCT 1.0";
New-SubKey $prot $pct10;  #PCT 1.0

$ssl20 = "SSL 2.0";
New-SubKey $prot $ssl20;  #PCT 1.0

$pct = Get-LocalMachineRegistryKeyForEdit $protocolsPath $pct10
New-PathDWORD $pct "Server" "DWORD" "Enabled" "0"; 

$ssl = Get-LocalMachineRegistryKeyForEdit $protocolsPath $ssl20
New-PathDWORD $ssl "Server" "DWORD" "Enabled" "0";

When all is run, this is what the registry looks like:

We basically have three methods that I will need to implement for the different use-cases I have.
I have the “give me a registry key for editing” use-case. So I get me that .NET object if it exists. Watch out that I am doing this in the HKLM (HKey Local Machine) context. I you want to do something outside of HKLM you need to change it accordingly.

So then I have my object I want to create DWORDs and Keys for. Well I need a method that does exactly that, because the first 15 or so steps will be “get me the key for editing and check if a key exists and add a DWORD enabling it or disabling it. Then I have a special case starting with the protocols section. There are actually sub-subkeys (or grandchildren keys if you so will). So we also need to be able to just create a path and then be able to perform or Path+DWORD operation again.

So the Path+DWORD is the heart of our script. Let’s look at it then. We make sure we don’t try to create something that already exists. So we have a parallel identification variable for the Test-Path method and the RegistryKey.OpenSubKey method. The subsequent OpenSubKey then opens the key for editing. I could have of course also implemented it, so that it directly opens the key I want in the first call of opensubkey and then use the flag for editing there. Might have been more slick, but how do I find my scripts on other blogs later if I don’t have any sillyness in them, right? 😉

So that’s a wrap.

I am sure you can optimize these things or maybe find easier solutions to these challenges I drew up here, but I think it was well worth writing this down as it took quite some time to find the solutions and the way I work I get inspiration for other problems I come across from reading these types of blogs.

I hope reading this article or all of them was worth your time and I would appreciate any feedback from your side if you are reading this.
I enjoyed writing this, so hopefully reading it was fun, too. My SharePoint journey isn’t over by far, so stay tuned for the next articles to come.

Back To Part VI
Back To Overview



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: