Using PowerShell to Compare / Diff Files

If you’ve tried to diff files in PowerShell before, you might have seen the Compare-Object cmdlet. The Compare-Object cmdlet lets you compare two sets of items, giving you a report on the differences between those two sets:

PS G:\lee\tools> cd c:\temp
PS C:\temp> $set1 = "A","B","C"
PS C:\temp> $set2 = "C","D","E"
PS C:\temp> Compare-Object $set1 $set2

InputObject SideIndicator
----------- -------------
D           =>
E           =>
A           <=
B           <=

From this output, we can see that “A” and “B” only show up in $set1, while “D” and “E” only show up in $set2. For sets of objects, this is all you need to know.

Getting Started with Guitar

If you’re interested in learning guitar, you might be running into an enormous feeling of dread. How do you get started? What kind of guitar should you get?

Here’s a short guide that can hopefully help get you started.

Buying a Guitar

Guitars can get really expensive. But higher-end guitars end up being a matter of taste (both musically and aesthetically). For your first guitar, you don’t have an opinion, so there’s no need to splurge. After all, you might find out that you don’t end up liking guitar in the end.

Who's in Your Email Social Network?

Have you ever wondered who’s in your “Email Social Network”?

I was wondering the other day how to find out who I mail the most. With a bit of PowerShell scripting, the answer is a breeze to find out:

## Connect with Outlook, and open the 'Sent Items'
$olApp = New-Object -com Outlook.Application 
$namespace = $olApp.GetNamespace("MAPI")
$sentItems = $namespace.GetDefaultFolder(5)
## Go through each item, split out names when there were multiple
## recipients, and clean them up a bit
$sentEverTo = $sentItems.Items | % { $_.To -split ";" } | % { $_.Trim(" '") }

## Group by how often you've sent mail to them
$sortedTo = $sentEverTo | group

## Explore
$sortedTo | sort Count

More Packet Hacking with PowerShell - UDP Manipulation

In the last post, I talked about how I used PowerShell to “STUN Roll” the open WiFi at DefCon. How much code was that? Was it hard?

stun_roll

It turns out that it was pretty reasonable - less than 60 lines of PowerShell.

## Convert a string in the form of hexadecimal characters into the
## equivalent bytes.
function ConvertFrom-HexString
{
    param($HexString)
    $HexString -split "(..)" | ? { $_ } | % { [Convert]::ToByte($_, 16) }
}

## Get the broadcast address for a subnet.
## Modified from
## http://powershell.com/cs/blogs/tips/archive/2013/06/03/calculate-broadcast-address.aspx
function Get-BroadcastAddress
{
    $ipConfiguration = Get-WmiObject Win32_NetworkAdapterConfiguration |
        Where-Object IPAddress | Select -First 1
    $ipAddress = @($ipConfiguration.IPAddress)[0]
    $subnetMask = @($ipConfiguration.IPSubnet)[0]

    [UInt32]$ip = [IPAddress]::Parse($IPAddress).Address
    [UInt32]$subnet = [IPAddress]::Parse($SubnetMask).Address
    [UInt32]$broadcast = $ip -band $subnet

    New-Object IPAddress ($broadcast -bor -bnot $subnet)
}

## Send the actual STUN packet for some given text
function Send-StunPacket
{
    param([string] $Text)

    ## Some header bytes that I got from reviewing the
    ## hexadecimal packet data in WireShark
    $headerContent = "000100" 
    $bytes = ConvertFrom-HexString $headerContent

    ## After the header bytes is the length of the packet
    ## Found by experimentation
    $bytes += [Byte] (4 + $Text.Length)

    ## And then some more header bytes that I didn't really know
    ## or care what they did
    $bytes += ConvertFrom-HexString "2112a4426274336f6754616876713150000600"
    $bytes += [Byte] $Text.Length

    ## Get the bytes for the message, add them to the packet.
    ## This section of the packet is usually for the user's ID.
    $messageBytes = [System.Text.Encoding]::ASCII.GetBytes($Text)
    $bytes += $messageBytes

    ## Configure the destination IP address and port
    $dstPort = 3478
    $endpoint = New-Object System.Net.IPEndPoint (Get-BroadcastAddress),$dstPort

    ## And send the packet
    $udpClient = New-Object System.Net.Sockets.UdpClient
    $null = $udpClient.Send($bytes, $bytes.Length, $endpoint)
    $udpClient.Close()
}

## The payload 🙂
$lyrics = @"
We're no strangers to love
You know the rules and so do I
A full commitment's what I'm thinking of
You wouldn't get this from any other guy
I just wanna tell you how I'm feeling
Gotta make you understand
 
CHORUS
Never gonna give you up,
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry,
Never gonna say goodbye
Never gonna tell a lie and hurt you
 
We've known each other for so long
Your heart's been aching but you're too shy to say it
Inside we both know what's been going on
We know the game and we're gonna play it
And if you ask me how I'm feeling
Don't tell me you're too blind to see (CHORUS)
 
CHORUS
(Ooh give you up)
(Ooh give you up)
(Ooh) never gonna give, never gonna give
(give you up)
(Ooh) never gonna give, never gonna give
(give you up)
 
We've known each other for so long
Your heart's been aching but you're too shy to say it
Inside we both know what's been going on
We know the game and we're gonna play it (TO FRONT)
"@

$lines = $lyrics -split "`r`n"
$lines | % { Send-StunPacket $_.Trim() }

Happy packet hacking!

Packet Hacking with PowerShell - AKA Mass Defcon Pwnage

Every year, two of the biggest hacking / security conferences take place in Las Vegas: Black Hat, and DefCon.

Both are great experiences, and both have a common theme – hackers (“Intelligent folks that like to make machines do things they weren’t originally designed for”) getting together to educate each other and have fun.

Unsurprisingly, one of the places that people get together to have fun is the free open WiFi.

Aside: Open WiFi led to the nerdiest “social networking” experience I’ve ever had. I was monitoring my hotel network to see how much malicious activity was on it. One of the prominent protocols in a network is LLMNR: a name resolution protocol that queries the local subnet for computers before trying other name resolution protocols. I saw one computer making requests for another laptop (presumably to reconnect a shared drive) – looking for a machine called “johnsmithlaptop”. It was also making LLMNR requests for a couple of servers on the Microsoft internal network. I figured that this was probably John Smith that works in security at Microsoft – who I’d been meaning to catch up with anyways. I sent him a mail asking if he was at BlackHat at my hotel – he was, and we got together for drinks :)

Redacting Sensitive Information with PowerShell

You might sometimes run into a situation where you’ve got a serialized object stream, and want to redact sensitive information out of that stream. For example, consider the following object:

$objectToSerialize = [PSCustomObject] @{
    Name = "Lee"
    SocialSecurityNumber = "SomeSecretNumber"
    Address = "1234 Something Road"
    GateCode = [PSCustomObject] @{
        Prefix = 1234
        Password = "SomeSecretPassword"
    }
}

In this, you want to remove any property value that says “SomeSecret”.

PowerShell makes this fairly easy, since the PSObject special property on every type gives you access to an object’s methods and properties. For each property value, you can check if it contains sensitive information - and if so, redact it.

What is OutputType?

If you’ve seen the OutputType attribute when writing a cmdlet or advanced function, you might wonder what we use it for.

The goal of the OutputType attribute is to provide a mechanism for tools to know what your cmdlets may output without running them. If they know that without running it, they can provide useful services – such as tab completion, data flow analysis, etc.

For example:

Get-Process | Where-Object { $_.<TAB>

Removing Insecure Wireless Connections with PowerShell

Troy Hunt recently posted a great discussion about the dangers of letting your devices automatically connect to insecure wireless networks – especially if those have a common name like ‘Starbucks’ or ‘Apple Demo’.

All devices let you “forget” a network when you are in range, and Windows 7 (and before) even had an interface that let you delete networks when they were out of range.

This dialog was removed in Windows 8, although the ’netsh’ command still lets you accomplish it from the command line.

Creating Add-ons, Plugins, and Tools for the PowerShell ISE

We frequently get questions asking if the PowerShell ISE supports a feature that it doesn’t. For example, variable watch windows, function browsers, or “find all matches in the current document”.

Or as another example, many of you are very familiar with Visual Studio and naturally wish for Visual Studio feature <x>. That <x> is usually different for each person :) The Visual Studio team is many times larger than the PowerShell team, and they’ve had a 15-year head start.

Hacking Pi with PowerShell

A Facebook friend recently posted a cool picture from the Pi chain that California Institute of Technology created on Pi Day, 2013:

image

After seeing that, you might wonder – “Where in Pi is that?” And, “What number does each colour represent?” PowerShell can help here – its support for regular expressions let you find all kinds of stuff in text. But where do you find the text of Pi? Bing, of course. After copy + pasting the first 100,000 digits of Pi from into a text file, you now have some text to work with.