How to spoof a hostname for Invoke-WebRequest (without messing around in the HOSTS file)

Despite moving on to Docker/Kubernetes and therefore Linux, I still get PowerShell questions from colleagues. This particular case was a colleague who wanted to test that each of several webservers behind a load balancer was properly processing a SAML request, without having to change his HOSTS file every time. As a Texas girl, I can’t resist a dare, so here we go: how to [mock | spoof | fake | manipulate] the IP address of a hostname for a web request. We’ve tried this with Invoke-WebRequest; it might also work for Invoke-RestMethod.

Since the site my colleague was testing was HTTPS-only, you first have to tell PowerShell to not worry about SSL certificates. There’s a TechNet Forum answer that refers to a now-disappeared Connect article that has one part of the script we’re using, as well as the oldest post (on a blog that hasn’t been updated in 2.5 years) with another part of the script, so for the sake of everyone’s sanity, a copy of that script as my colleague and I use it:

$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
Add-Type -AssemblyName System.Web
Add-Type -AssemblyName system.Security
Add-Type -AssemblyName System

Add-Type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

… as for the actual spoofing, a moderate amount of Googling later yielded a Reddit thread, with the right answer buried in the middle of, well, a Reddit thread (“fix your network so you don’t need to edit host files”):

Invoke-WebRequest https://192.168.65.2 -Headers @{ host="awesome.mandie.net" }

Remember that the PowerShell session will uncritically accept all HTTPS answers, so close it and start a new one when you need to say, use the AzureRM modules!

Advertisement

Is that Skype for Business (Lync) Number Free?

Get-CsAdPrincipal is a tragically underused cmdlet. Absent a fully generic Get-CsEndpointObject, it’s the next best thing to Get-ADObject, and is killer when you have no idea what you’re looking for – a User, a Common Area Phone, Conference Dialin Number, Response Group or some crazy custom endpoint used in a Skype-enabled application, especially if all you care about is seeing if a number is available. If you see “485 Ambiguous” in a SIP trace, this will help you figure out who (and/or what) all has this number, and why Skype isn’t quite sure which one the caller wanted to reach.

There are several scripts for testing each of the Skype for Business object types one by one, and I give some of my favorites at the end of the post; the Get-CsAdPrincipal approach is faster in automation if you’re mostly interested in whether a number is consumed at all, and aren’t concerned with *what* exactly is consuming it.

Get-CsAdPrincipal -LDAPFilter '|(msrtcsip-line=tel:+499112224000*)(msrtcsip-privateline=tel:+499112224000*)'

The LDAP query is checking both the MsRTCSIP-Line and MsRTCSIP-PrivateLine attributes, and there is an asterisk at the end in case the extension was specified separately: tel:+499112224000 and tel:+499112224000;ext=4000 are functionally the same number, but do not look the same to Skype for Business! This is common in places where each line can be directly dialed from outside – that is, much of Europe. I used the attribute names in all lowercase because the mixed-case versions did not work.

If all you wanted was a quick way to check if a number is free or not, you can quit reading now and get back to writing your provisioning script 🙂 If you want to know a bit more about Skype for Business objects, as well as see some really nice stuff for viewing your number pool, stay with me…

Continue reading

ActiveRoles Performance Tip: Use Distinguished Name instead of Canonical Name in OrganizationalUnit Parameters

When making over 100 accounts today for some hard core Skype for Business monitoring, I (re-)discovered that the form of New-QADUser‘s -ParentContainer parameter makes a huge performance difference. I didn’t time it, but noticed that it took about as long to make five accounts using the Canonical Name (mandie.net/Region/State/City/Purpose) as it did to make the rest of the batch using DN, or Distinguished Name (OU=Purpose,OU=City,OU=State,OU=Region,DC=mandie,DC=net).

This was with Quest ActiveRoles Management Shell for AD 1.7, which goes with ARS 6.9. It was an issue back in the QARMS 1.6/ARS 6.8 days, so hopefully Dell has fixed it for recently-released ARS 7.0. I say “hopefully,” because I can’t find QARMS 1.8(?) anywhere in the ARS 7.0 installation download, much less the Release Notes. Anyhow, it is something to do with how ActiveRoles checks your permissions on the Organizational Unit you are attempting to write to.

You might leave the team responsible for ActiveRoles Server at your company, but ActiveRoles Server never really leaves you…

Hyper-V Switch from Internal to External While VMs Running… No Internets for you!

It’s not every day that you get taught new admin concepts using PowerShell by Jeffrey Snover  himself (the guy who invented PowerShell), but I had the privilege of taking part in the TechDays NL 2015 pre-conference workshop on OneGet PowerShell Package Manager and Desired State Configuration (DSC) that Jeff Wouters (PowerShell MVP) organized, and then led along with Mr. Snover. Both Jeffs patiently answered our (sometimes) silly questions and worked hard to make sure we got as much as possible out of the day.

However, no one was able to save me from myself when I learned that enabling External access for your Internal-only Hyper-V virtual switch while the VMs attached to it are running is apparently a bad idea – at least when your host OS is Windows 10 Technical Preview, Build 10122. This warning didn’t put me off:

Warning schmarning...

… and it appeared to work, but not really: it took out my Internet connection completely. Annoyingly enough, the WiFi claimed that it was connected, along with being bridged. Hyper-V added a nifty new generic Ethernet adapter that was supposed to act as a bridge between the virtual switch and my real WiFi. Note the missing vEthernet (External01) Hyper-V Virtual Ethernet Adapter.

A bridge too far...

Another hint was that Get-NetIPAddress only showed the loopback addresses for both IPv4 and IPv6, and nothing else.

There was no reverse – when I tried switching that virtual switch back to Internal, I got “Error applying Virtual Switch Properties changes”:

FixVirtSwitch11

Disabling and re-enabling the WiFi connection also did no good; the WiFi was always connected, but traffic was not being passed from applications. Deleting and reinstalling the WiFi adapter was also not an option.

Note the grey text for the

Note the grey text for the “Delete” option.

However, I was able to delete the generic Ethernet adapter.

FixVirtSwitch13

As soon as that finished, Get-NetIPAddress showed addresses for the WiFi adapter and the virtual switch I hadn’t meddled with. Voila, I had Internet again!

The virtual switch in question was left as a Private Network, and was easily switched back to being Internal. After that, IP addresses (IPv4 and IPv6) showed up for it, too, on Get-NetIPAddress.

FixVirtSwitch14

The goofy-looking font is a special feature of the 10122 build of Windows 10 for Arial font in various contexts, and can be remedied by some simple method I have completely forgotten.

Wish I’d thought of trying this during the workshop, because package management is kind of hard to work with when you don’t have any way to get to a repository, but here it is for you, dear reader. And for Mr. Snover and Mr. Wouters the next time they teach OneGet… er, PowerShell Package Manager.

Quickly turn SkypeUI on and off without opening Regedit – Skype for Business Preview

The Skype for Business Technical Preview has been pretty great so far, and if I had my choice, I’d use it 100% of the time (get it here). However, I occasionally need to take screenshots for our end users, most of whom have recently been upgraded to Lync 2013 from Office Communicator 2007 R2! Several people have posted the proper registry key to add and change in order to switch UIs (great example here), but frankly, opening Regedit always makes me a tiny bit nervous, even if I am running as a non-admin user. If you are not running as a non-admin user for regular email/Lync/internetting, please think very hard about why!

Here are some little PowerShell functions I’ve written to quickly make this change and restart the Lync/Skype for Business client (can also be downloaded from TechNet Gallery)


# QuickSkypeUISwitch.ps1, Version 1.01
# Amanda Debler, http://mandie.net
# now with no-so-new Provider hotness - thanks, Kevin Bird (http://kb-kb.com), for reminding me that providers exist 🙂


# See if the key exists, and if so, what its current value is
 
function Test-SkypeUIRegKey {
    # old cmd-style registry query
    # reg query "HKCU\Software\Microsoft\Office\Lync" /v EnableSkypeUI
    try {
        get-ItemProperty HKCU:\Software\Microsoft\Office\Lync -Name EnableSkypeUI
        }
    catch [System.Exception] {
    "Registry Key does not exist or cannot be accessed - if Skype for Business UI isn't coming up, try Enable-SkypeUI"
    }
}
 
# Lazy assumption that you have Lync set to autostart, plus
# trickery to find, kill and restart your Lync/Skype4B client,
# because I have no idea where you installed it
 
function Restart-SkypeForBusiness {
    $lyncProcess = Get-Process -Name Lync
    $lyncProcess |  Stop-Process
    Start-Process -FilePath $lyncProcess.Path
}
 
# The /f means force - don't care if you have a key there already or not
 
function Enable-SkypeUI {
    # old but not busted cmd-style registry key insert
    # reg add "HKCU\Software\Microsoft\Office\Lync" /v EnableSkypeUI /t REG_BINARY /d 00000001 /f

    # Note the commas in the Value - Binary registry keys are treated as 4 bytes
    New-ItemProperty HKCU:\Software\Microsoft\Office\Lync -Name EnableSkypeUI -Value 00,00,00,01 -PropertyType Binary -Force
    Restart-SkypeForBusiness
}
 
function Disable-SkypeUI {
    # reg add "HKCU\Software\Microsoft\Office\Lync" /v EnableSkypeUI /t REG_BINARY /d 00000000 /f
    New-ItemProperty HKCU:\Software\Microsoft\Office\Lync -Name EnableSkypeUI -Value 00,00,00,00 -PropertyType Binary -Force
    Restart-SkypeForBusiness
}

Get-CsTopologyFixed Loves Your Simple URLs!

Yes, I know there is no such thing as a tbxml tag. That doesn't mean that there shouldn't be.Remember how I was complaining last week about how Get-CsTopology -AsXml drops the whole SimpleUrlConfiguration node, which makes Topology Builder sad?

Fixed it!

You, too, can enjoy what I do in the evenings on my ridiculous lab machine and get your own readable (though read-only) .tbxml files right from PowerShell:

Get-CsTopologyFixed (hosted on TechNet Gallery)

It works for View-Only Administrators (CsViewOnlyAdministrator), as well as full CsAdministrator (or equivalent), so your telephone gal or Exchange guy can grab a copy whenever they need to check something or a consultant wants a copy so that they understand what’s going on with Lync in your environment. I have not tested it with an account that only has, for example, CsUserAdministrator or CsServerAdministrator.

For people who are not (yet) hard-core PowerShellers: this script is a function, not a standalone script. Running it “dot-sourced” will add the Get-CsTopologyFixed cmdlet to your current PowerShell session, or you can add the function to your Lync Server connection script. You need to either be on a computer with Lync Management Shell (part of the Lync management tools on the Lync Server installer image) or implicitly remoted to one that has it in order to access the native Lync Server cmdlets.

Here is the function to take the output of Get-CsSimpleUrlConfiguration and put it into an XML node, which my full script then drops into the rest of the Topology XML:

    function Convert-CsSimpleUrlConfigurationToXMLText { 
        $GetCsSimpleUrlConfiguration = Get-CsSimpleUrlConfiguration 
        $SimpleUrlConfigurationOut = "" 
        $simpleUrlConfigurationOut += '<SimpleUrlConfiguration xmlns="urn:schema:Microsoft.Rtc.Management.Settings.SimpleUrl.2008" UseBackendDatabase="false">' 
     
        foreach ($simpleUrl in $GetCsSimpleUrlConfiguration.SimpleUrl) { 
            $SimpleUrlConfigurationOut += "<SimpleUrl Component=`"$($simpleUrl.Component)`" Domain=`"$($simpleUrl.Domain)`" ActiveUrl=`"$($simpleUrl.ActiveUrl)`">" 
            foreach ($simpleUrlEntry in $simpleUrl.SimpleUrlEntry) { 
                $SimpleUrlConfigurationOut += "<SimpleUrlEntry Url=`"$($simpleUrlEntry.Url)`" />" 
            } 
            $SimpleUrlConfigurationOut += "</SimpleUrl>" 
        } 
 
        $SimpleUrlConfigurationOut += '</SimpleUrlConfiguration>' 
 
        $SimpleUrlConfigurationOut 
    }

I have no idea if it works (or is even necessary) on Lync Server 2010. If Microsoft will let me have a preview copy, I’d be willing to find out if it works (or is even necessary) on Skype for Business 😉

If you find something wrong with my script, or come up with an improvement, let me know!

PowerShell Heart Logo

PowerShell logo in a heart

I love PowerShell, and so should you!

The #PowerShellChicks group was initiated by the foremost lady of PowerShell, June Blender:

I think we need a logo! A PowerShell symbol hatching from an egg would have been awesome, but my graphic design skills are pretty much limited to PowerPoint. To celebrate having my session on Lync admin basics selected for the 2015 PowerShell Summit Europe, here’s a little something I knocked together. If someone wants to do the curved gradient and motion lines that are on the real logo (and perhaps improve the overall proportions), knock yourself out and let me know about it!

 

 

Comparing Lync Policies – or How to Flip Just About Any Array of Hashtables in PowerShell

If you are reading this blog and can read German, I don’t need to tell you about msxfaq.de, former Exchange and now Lync MVP Frank Carius’ online (but not very alphabetical) encyclopedia of Exchange and Lync – it probably gets more page views in a day than this blog ever has. Even if you cannot read German, you have still probably run into it when searching for Exchange or Lync topics and then seriously wished you could read German – machine translation only goes so far.

Anyhow, one of the most helpful things he’s put out there and that I use all the time is a Swap-Table script. I wasn’t able to turn it up with “flip table in PowerShell” or “pivot PowerShell table” or any of several variations, so this is a little attempt to make that wonderful file findable for the English-speaking world. Scroll to the bottom and look for the “Code” section. You can make it a function in your PowerShell profile by putting the contents of that text file inside the curly braces {} of the following (code not posted here because plagiarism is evil):

function Swap-Table {
# contents of swap-table.1.0.ps1 go here

}

It has been particularly useful for comparing ClientPolicies and ConferencingPolicies in Lync, as ClientPolicy has over 70 attributes! Once you have the function in your session and you’re connected to Lync Management Shell, it works like this:

Get-CsClientPolicy | Swap-Table | Out-GridView

PowerShell Summit Europe 2014 – Registration Ends September 10!

PowerShell, in my not quite humble opinion, is the best thing Microsoft has done in the past decade, with the second best being Lync. It is mere coincidence that my professional life currently revolves around both.

So, if you are a cheap flight away from Amsterdam, you have until September 10 to join several PowerShell legends like Jeffrey Snover, Don Jones, Richard Siddaway, Tobias Weltner and Steve Murawski, as well as about 60 regular PowerShell enthusiasts like me for three intense days at a price far lower than a regular Microsoft course at some random training center.

The summit starts September 29 (Monday) and goes through October 1, with most people arriving (and hanging out) Sunday evening.

Registration and more summit info: http://powershell.org/wp/community-events/summit/

 

NetLogon.log: Control what goes in, and get what you want out

Or, when you want some, but not all, of what Netlogon.log has to offer – especially when trying to track down the source of a user account’s lockouts or find subnets that haven’t been put into an Active Directory site yet.

At one point, we had Netlogon turned up to 11 on all our domain controllers – that is, DBFlag is set to 0x2080ffff, just like this TechNet article and everything else you see at first glance on the Internet has it. That quick looks makes it look like your options are EVERYTHING!!1!1 or nothing. Since that one Knowledge Base article literally IS the only place on the Internet where these flags are listed in detail, and Microsoft has recently started featuring the automated “Fix It” solution, here is the info for posterity (and convenience),
nicely formatted into tables.

Data Source: http://support.microsoft.com/kb/109626
Formatting into tables: Amanda Debler (me)
All descriptions as-is from Microsoft.

Basic Netlogon Flags

Flag Name Value Description
NL_INIT 0x00000001 Initialization
NL_MISC 0x00000002 Misc debug
NL_LOGON 0x00000004 Logon processing
NL_SYNC 0x00000008 Synchronization and replication
NL_MAILSLOT 0x00000010 Mailslot messages
NL_SITE 0x00000020 Sites
NL_CRITICAL 0x00000100 Only real important errors
NL_SESSION_SETUP 0x00000200 Trusted Domain maintenance
NL_DOMAIN 0x00000400 Hosted Domain maintenance
NL_2 0x00000800
NL_SERVER_SESS 0x00001000 Server session maintenance
NL_CHANGELOG 0x00002000 Change Log references
NL_DNS 0x00004000 DNS name registration

Verbose Netlogon Flags

Flag Name Value Description
NL_WORKER 0x00010000 Debug worker thread
NL_DNS_MORE 0x00020000 Verbose DNS name registration
NL_PULSE_MORE 0x00040000 Verbose pulse processing
NL_SESSION_MORE 0x00080000 Verbose session management
NL_REPL_TIME 0x00100000 replication timing output
NL_REPL_OBJ_TIME 0x00200000 replication objects get/set timing output
NL_ENCRYPT 0x00400000 debug encrypt and decrypt across net
NL_SYNC_MORE 0x00800000 additional replication dbgprint
NL_PACK_VERBOSE 0x01000000 Verbose Pack/Unpack
NL_MAILSLOT_TEXT 0x02000000 Verbose Mailslot messages
NL_CHALLENGE_RES 0x04000000 challenge response debug
NL_SITE_MORE 0x08000000 Verbose sites

Netlogon Control Flags

Flag Name Value Description
NL_INHIBIT_CANCEL 0x10000000 Don’t cancel API calls
NL_TIMESTAMP 0x20000000 TimeStamp each output line
NL_ONECHANGE_REPL 0x40000000 Only replicate one change per call
NL_BREAKPOINT 0x80000000 Enter debugger on startup

Right now, I just want a clear look at account lockouts and subnetless IPs, even on our busiest DCs. A very busy DC can blow through a 100MB log file allowance in a few hours, and even with Netlogon.bak, collection and filtering would have to happen several times a day to make sure we see all the bad logons.

“But why would you want to capture LESS diagnostic information?!?” Because heavy logging can cause its own problems – read and think about this article from the Directory Services team before you implement “All Logging, All The Time”. It explains how to enable (and disable) logging for all facets of Directory Services.

As a compromise, I’m just going to turn off all those ‘[SITE]’ messages, since they are most of the entries in netlogon.log, and don’t provide any information I need right now. So, 0x2080ffff - 0x00000020 = 0x2080ffdf. I tried the nice .NET/PowerShell way, but it failed against a 2003 server. Back to the old-fashioned way – still possible from within a PowerShell script:

(all one line) reg add "\\$computerName\HKLM\SYSTEM\CurrentControlSet\Services\NetLogon\Parameters" /v DBFlag /t REG_DWORD /d 0x2080ffdf /f

Make sure that your log file is the size you want it to be (in this case, 100 megabytes):

(all one line)reg add "\\$computerName\HKLM\SYSTEM\CurrentControlSet\Services\NetLogon\Parameters" /v MaximumLogFileSize /t REG_DWORD /d 100000000 /f

And to check our work…

(all one line) reg query "\\$computerName\HKLM\SYSTEM\CurrentControlSet\Services\NetLogon\Parameters" /v DBFlag

(all one line) reg query "\\$computerName\HKLM\SYSTEM\CurrentControlSet\Services\NetLogon\Parameters" /v MaximumLogFileSize

Finish up by stopping and starting the Netlogon service, again, the old-fashioned way with NT Service Controller. You need to use sc.exe in PowerShell, because sc is an alias for Set-Content:

sc.exe \\$computerName stop netlogon

sc.exe \\$computerName start netlogon

Here’s a table of the result codes to interpret the [LOGON] entries (from Section “Netlogon Log File Error Codes” http://technet.microsoft.com/en-us/library/cc776964.aspx, copied in case that particular link goes away):

Log Code Description
0x0 Successful login
0xC0000064 The specified user does not exist
0xC000006A The value provided as the current password is not correct
0xC000006C Password policy not met
0xC000006D The attempted logon is invalid due to a bad user name
0xC000006E User account restriction has prevented successful login
0xC000006F The user account has time restrictions and may not be logged onto at this time
0xC0000070 The user is restricted and may not log on from the source workstation
0xC0000071 The user account’s password has expired
0xC0000072 The user account is currently disabled
0xC000009A Insufficient system resources
0xC0000193 The user’s account has expired
0xC0000224 User must change his password before he logs on the first time
0xC0000234 The user account has been automatically locked

The most important ones to distinguish between are 0xC000006A (bad password was entered this time – these ARE the droids you’re looking for) and 0xC0000234 (a logon attempt has been made with a user account that has been locked out, but this says nothing about whether this current attempt used a good or bad password)

Continue reading