Posts

Better Certificate Management in Powershell via CertificateHelper

If you’ve read my previous post here , you know powershell can do some basic certificate management via the certificate provider. However, the certificate provider has some limitations. The certificate provider can’t create,delete,copy or import/export certificates. This annoyed me so I’m creating a powershell module called CertificateHelper that will provide these missing features. So far the module implements: New-Certificate Remove-Certificate  CertHelper can be found on codeplex . You install it like this: (You must have hg installed) PS C:\>cd $home\Documents\WindowsPowerShell\Modules PS C:\Users\igord\Documents\WindowsPowerShell\Modules> hg clone https://hg01.codeplex.com/certificatehelper destination directory: certificatehelper requesting all changes adding changesets adding manifests adding file changes added 5 changesets with 8 changes to 4 files updating to branch default 4 files updated, 0 files merged, 0 files removed, 0 files unresol...

Using tshark to find the man in the middle

This post is targeted at people that understand ip addresses, default gateways and have heard of arp, but don’t play with them often enough to realize how vulnerable we are to man in the middle attacks. Back in the old days, the network hardware was often a hub, and hubs had a property that all the computers connected to a hub could see each others traffic.  This meant if my computer and tori-the-lori were on the same hub tori-the-lori could see all my network traffic. This sound like weak security.  In time the world invented switches, and now almost all networking uses switches. Switches differ from hubs in that computers only see traffic that is sent to them, not everyone's traffic.  This difference should fix the weak security right?   Well, as with most things security the devil is in the details. Lets dig in. When a computer wants to talk another computer by IP address, it needs to find the MAC address for the IP address, this is done via ARP.  Le...

The whitespace and indentation debate

Nothing annoys me more than having to argue over whitespace and indentation. Where should we stick the braces? Spaces vs Tabs? Can't we find something more useful to argue over? Long ago I read the only to end the pointless whitespace debate, is to have the compiler reject random whitespace . I thought that was a very good idea, and today I'll talk about it. In the beginning whitespace didn't matter, it was there for the human, and the program ignored it.   But that caused an annoying problem - you ended up needing tokens like '{' ';' and '(' and then you needed to argue about how you arranged the code around those tokens.  For example: ProcessIncomingDogs(List<Dog> dogs) { ... if (dogs>1) { RunAway(smallDogs,speed.Fast); Log("SmallDogs Ran Away Fast"); } Log("EveryOne Ran Away that needed to"); ... } I'm happy to say we're making progress, python gets rid of the ann...

Salting your hash, chasing rainbows and cracking passwords

Henry Ford takes 3 of his division presidents out for diner to decide which of them will be the new CEO. As soon as they start eating Mr. Ford chooses Bob, the man to his left, to be the new CEO. The other division presidents are shocked, and ask why Bob was picked over them. Henry replies: Bob was the only man who tasted his food before salting it. Unlike at dinner time, hashes should always be salted. A hash is a one way function that maps something, for this discussion a password, to a short string. The point of a hash is if you're given the hash, you can't figure out the password. A common scenario for hashes is checking users passwords. Instead of storing a users passowrd and checking the passwords match, you store the hash of the users password, and make sure a hash of the users password matches the hash you stored. The advantage of storing the hash is if someone steals your disk they don't get your user's passwords. There's a rub though. What happens if t...

How do you thumbprint a certificate?

You often use thumbprints to find certificates, but what is the thumbprint?  The thumbprint is the hash of the certificate. In the case of the CLR’s X509Certificate2 class, the thumbprint is the SHA1 hash of the certificate. If you want to compute the thumbprint of a certificate yourself it’s pretty simple: function get-CertThumbprint ($cert) { $sha = new-object System.Security.Cryptography.SHA1CNG $hashOfRawBytesOfCertificate = $sha.ComputeHash($cert.RawData) ( $hashOfRawBytesOfCertificate| % {"{0:X}" -f $_} ) -join "" } PS cert:\LocaLMachine\My> dir Directory: Microsoft.PowerShell.Security\Certificate::LocaLMachine\My Thumbprint Subject ---------- ------- 3BCA8A25A071300BD177E4C73135E54FA830039A CN=STS 08766D8B3DCDE5D633ED06AB1CB4DF4CCAECA533 CN=localhost PS cert:\LocalMachine\My> $cert = get-item 08766D8B3DCDE5D633ED06AB1CB4DF4CCAECA533 PS cert:\LocalMachine\My> $cert...

Keyboard shortcuts in Windows WYSIWG editors

I have a day job, and in that job I use Word, OneNote and Outlook.  For style I only use bold, italics, underline, headings 1-3 and lists. For some reason, I never learned the keyboard shortcuts for some of these, and thus I need the mouse to apply these styles. In case you suffer like me, here’s are the shortcuts that will set your mouse free. Style Word OneNote Heading 1 C-A-1 C-A-1 Heading N C-A-N C-A-N Bulleted List C-S-L C-. Numbered list ? C-/ Underline C-U C-U Italics C-I C-I Bold C-B C-B Strike through ? C-- High Light ? C-H List item up A-S-Up A-S-Up List item down A-S-Down ...

Powershell is dynamically scoped, and that will confuse you.

Lets start with an example, as the concept of dynamic scoping is a big string for most programmers. Python Program x = 5 def printX(): print x def setAndprintX(): x=7 printX() printX() setAndPrintX() printX() Output From Python 5 5 5 Powershell Program $x = 5 function printX() { echo $x } function setAndprintX() { $x=7 printX } printX setAndprintX printX Output From Powershell 5 7 5 What is this dynamic scoping? Most programs use static, also called lexical, scoping because it's easy to understand. You figure out what is in scope by looking at the source code. In the python example, the only value of x in scope is the global value of x. By contrast, powershell uses dynamic scoping, in this model, you lookup up variables at runtime based on a scope stack. Each time you call a function you create a new scope, and copy all values from the parent scope into it. In the powershell example, when printX is called fr...

Using wireshark to trace localhost traffic on windows.

(If you don’t care why this works and just need a recipe, switch to this post ) Capturing network packets on localhost doesn't work on windows. The reason is windows doesn't send loopback traffic far enough down the networking stack for wireshark to see it. To make sniffing work on localhost you can route your ip traffic to your default gateway. I'll walk you through this, and along the way you'll see: netcat - telnet on steroids (nc.exe) tshark - command line network sniffer from the wireshark package. powershell jobs - background jobs from the shell! Step 1 - launch the server as a background job (Woohoo powershell) PS C:\Users\igord> $server = start-job { \bin_drop\nc -L -p 8082 } Step 2 - Make client connection: PS C:\Users\igord> \bin_drop\nc.exe 127.0.0.1 8082 Hello You can see me Step 3: See if we can see anything in tshark on port 8082. C:\Program Files (x86)\Wireshark>tshark -i 4 -R "tcp.port == 8082" Capturing on M...

The Performance of Everyday Things

I've spent much time fixing code optimizations that added no business value (with often matching performance value). Please do not try to make your code faster unless you need to. The way I handle performance issues on my projects: Define acceptable performance. Write my code as simply as possible. Measure performance: against definition, if performance > acceptable - goto DONE. /*Performance not acceptable*/ Profile; Fix as simply as possible; goto Measure. DONE To be explicit: I'm comfortable using slower patterns if they are clear and simple. As soon as I've hit my acceptable performance bar - I'm done. With that out of the way, let me discuss a performance riddle I hit this week. I was wandering through some powershell code that processed slews of objects (over 200K of 'em): $interestingObjects = @() foreach ($object in $inputObjects) { if ($object.IsInteresting) { $interestingObjects += $objects ...

Using TShark

Today I realized this blog lost its google analytics (GA) tracking. Ooops, I accidentally erased the javascript that talks to Google Analytics in my blog template. I fixed the template on my blog, and wanted to verify my browser was sending data to GA. It takes the GA UI a while to show you data is coming in, so I decided to use tshark to see if my tracker code is working. Tshark is the command line version of Wireshark, an Ethernet level packet sniffer. Lets see what HTTP GETs occur when I connect to one of my posts: C:\Program Files\Wireshark>tshark.exe | findstr GET Capturing on Microsoft 1) 67.936320 192.168.1.100 -> 64.233.169.191 HTTP GET /2009/07/finding-clr-exceptions-with-visual.html HTTP/1.1 2) 68.211983 192.168.1.100 -> 64.233.169.191 HTTP GET /dyn-css/authorization.css?targetBlogID=7821316&zx=defa99ec-5585-4463-a42d-a32bf4868482 HTTP/1.1 3) 68.393167 192.168.1.100 -> 64.233.169.139 HTTP GET /__utm.gif?utmwv=4.5.8&utmn=1895005015&utmhn=ig2600....

Use cdb to see what files your application is opening.

In this post I'll show you how to use CDB to intercept CreateFile and see what files your application is opening. For this problem, Process Monitor is often a better tool, but the techniques I demonstrate work for any API you should learn them. This won't take much time, so if you've never done this before I recommend you follow along. First Load CDB against cmd: C:\Program Files\Debugging Tools for Windows (x64)>cdb.exe cmd.exe Microsoft (R) Windows Debugger Version 6.12.0000.526 AMD64 Copyright (c) Microsoft Corporation. All rights reserved. CommandLine: cmd.exe Symbol search path is: *** Invalid *** **************************************************************************** * Symbol loading may be unreliable without a symbol search path. * * Use .symfix to have the debugger choose a symbol path. * * After setting your symbol path, use .reload to refresh symbol locations. * ******************...

Finding CLR exceptions without visual studio

(If you want to understand what exception code 0xe0434352 is, read this post ) Often exceptions are thrown and caught and you don't see them. You probably know how to debug this in Visual Studio, so let me show you how to do it in cdb. Sample Code: class Program { static void Main(string[] args) { foreach (var x in Enumerable.Range(0,2000)) { Thread.Sleep(TimeSpan.FromSeconds(1)); Console.WriteLine("Hello World"); ThrowAndCatchException(); } } private static void ThrowAndCatchException() { try { throw new NotImplementedException(); } catch(Exception) { } } } Output of the application: Hello World Hello World Hello World Nothing about an exception, but you're sure it's happening behind the covers -- fire up cdb: C:\Program Files\Debugging Tools for Windows (x64)>cdb -pn consoleapplication3.exe <SNIP> ModLoad: 000007fe`f7e90000 000007fe`f7eb4000 C:\Windows\Mi...

Why write programs that don't modify variables?

Slews of bugs happen because variable have values you aren't expecting. To minimize this class of bugs I use a technique a lot of people find surprising. I try to only assign and never modify variables. In C++, I make almost all my variables const. C++ people are now saying -- Um if all your values are const how do you write a for loop? In C++ I can't help myself, I'm stuck with a variable modification eg: for (size_t x=0;x<6;x++) printf("%d",x) In python the for loop naturally iterates over a sequence so you don't need to modify a value: for x in range(6): print x In C#, you can use either the C++ syntax or a more python syntax via foreach: for (int x=0;x<6;x++) Console.WriteLine(x); or foreach (var x in Enumerable.Range(0,6)) Console.WriteLine(x) I use the foreach syntax which people initially find confusing. But its value starts to shine when using non zero starting values. Assume I need to generate 113 numbers starting at 27. Which ...

How to attach to an already running debugger target using cdb.

For the last year when I wanted to attach to a process using cdb, I'd attach by PID. This meant i'd need to the following dance: C:\Program Files\Debugging Tools for Windows (x64)>tlist |findstr firefox 9128 cmd.exe findstr firefox 276 firefox.exe Restore Session - Vimperator C:\Program Files\Debugging Tools for Windows (x64)>cdb -p 276 It turns out you can just do: C:\Program Files\Debugging Tools for Windows (x64)>cdb -pn firefox.exe Microsoft (R) Windows Debugger Version 6.11.0001.404 AMD64 Copyright (c) Microsoft Corporation. All rights reserved. If there are multiple instances of your process, you'll still need to use tlist to find the PID you're interested in.

A funny API decription

Maybe I'm weird, but I giggle when people talk about databases crying. The Flickr search api justifies a requirement as follows: Geo queries require some sort of limiting agent in order to prevent the database from crying.