Subscribe
Search
Friday
Sep302011

Encrypting a string using certificates and PowerShell

I recently had the need to encrypt some strings using a public and private key and then store it for later use. The public key was stored as part of a certificate issued by the internal CA, the private key was to be held offline for later use. If you were using this process to exchange data with another party, you would require the other parties public certificate (and hence their public key).

The encryption process was pretty simple; however the decryption process was another story.

Encrypting a string using a key stored in a public key requires only one prerequisite component, and that is the certificate containing the key you are going to use. This certificate in my case was stored within the Windows certificate store for the local machine, in the Trusted People folder. My encryption function will need two items of input, the string to encrypt, and the certificate we will be encrypting against as System.Security.Cryptography.X509Certificates.X509Certificate2.

You may have just wondered, or swore, “How the hell do I get a System.Security.Cryptography.X509Certificates.X509Certificate2???!!!??”. Well if you remember the power of PowerShell then you will remember that it allows you to interact with the certificate store in the same way you would the registry or the file system.

To see all the Trusted Root Certification Authorities using PowerShell:

Dir cert:\localmachine\Root

Look at the output, does it look familiar? This is the equivalent to opening the MMC, adding the Certificates snap-in for the local machine and browsing to Trusted Root Certification Authorities.

What about the certificates for my AD account?

Dir cert:\currentuser\my

This is the equivalent to opening the MMC, adding the Certificates snap-in for the current user and browsing to Personal.

 

If you perform a get-member on what is returned, you will notice a the objects being returned are the right type for what my function will require.

For what I was doing, I knew that the certificate with the thumbprint of 5F507E471772839A953406A00537F609955AFCD7 which was stored the Trusted People folder for the local machine. I could get the certificate using

Gi cert:\localmachine\trustedpeople\5F507E471772839A953406A00537F609955AFCD7

 

The other thing to note, is that my encryption function actually returns a base64 encoded envelope which not only contains the message/data which was encrypted but also information regarding the certificate used to encrypt the data (and which information will be used later to decrypt the data).

The encryption function looks like this:

Function encrypt-envelope ($unprotectedcontent, $cert)

{

            [System.Reflection.Assembly]::LoadWithPartialName("System.Security") | Out-Null

            $utf8content = [Text.Encoding]::UTF8.GetBytes($unprotectedcontent)

            $content = New-Object Security.Cryptography.Pkcs.ContentInfo `

                    -argumentList (,$utf8content)

            $env = New-Object Security.Cryptography.Pkcs.EnvelopedCms $content

            $recpient = (New-Object System.Security.Cryptography.Pkcs.CmsRecipient($cert))

            $env.Encrypt($recpient)

            $base64string = [Convert]::ToBase64String($env.Encode())

            return $base64string

}

Decryption is a little more complicated, but it isn’t overly complicated when you sit down and actually think about it. To work out the reverse method, I simply worked with PowerShell and the MSDN library to reverse the process laid out in the encryption method.

For this to work, you need to have the private key for the corresponding certificate installed in either the Local Computer or User certificate stores.

function decrypt-envelope ($base64string)

{

            [System.Reflection.Assembly]::LoadWithPartialName("System.Security") | Out-Null

            $content = [Convert]::FromBase64String($base64string)

 

            $env = New-Object Security.Cryptography.Pkcs.EnvelopedCms

            $env.Decode($content)

            $env.Decrypt()

 

            $utf8content = [text.encoding]::UTF8.getstring($env.ContentInfo.Content)

            return $utf8content

}

Note this will return the string correctly formatted as it originally entered.

I will be posting some other scripts using this code in the coming days.

Thursday
Sep292011

Quest Active Directory CmdLets and Distribution Groups

All sysadmins will at soem point be required to clean up/report on Microsoft Exchange distribution groups within their organisation. Below are some notes I made as I was working on them recently.

Note: All of these use the Quest AD Cmdlets

I had a array of groups that had been passed to me ($groups), I wanted to add to that array the name of the user who manages that group, before passing the variable on to other things:

Function Get-ManagedbyName {
[cmdletbinding()]           

Param (
     [Parameter(Position=0, Mandatory=$True, ValueFromPipeline=$True, `
            HelpMessage="You must specify a QAD group object")]
     [Quest.ActiveRoles.ArsPowerShellSnapIn.Data.ArsGroupObject]$group
    )           

Begin {
    Write-Verbose "Starting function"
}           

Process {
    $managedby = $group.managedby
    $managedname = ""
    if (($managedby -eq "") -or ($managedby -eq $null)) {
        $managedname =  ""
    } else {
        $managedname = (get-qaduser $managedby).name
    }
    $group | Add-Member -MemberType NoteProperty -Name "ManagedbyName" `
          -Value $managedname -passthru
}           

End {
    Write-Verbose "Ending function"
}           

An example of using this would be

$groups= <get your group>

$groups| Get-ManagedbyName

A cmdlet to hide groups from the global address list:

Function hide-distributionlist {
[cmdletbinding()]           

Param (
     [Parameter(Position=0, Mandatory=$True, ValueFromPipeline=$True,
     HelpMessage="You must specify a list of groups")]
     [System.string[]]$groups
    )

Begin {
    Write-Verbose "Starting hide-distributionlists"
}           

Process {
    foreach ($group in $groups)
    {
       #move the group to:
       Move-QADObject $group -newparentcontainer "OU=disabled mailing groups, `
            OU=disabled users,OU=CSAU,DC=sunqld,DC=com,DC=au"
       #hide from addresslist
       set-qadgroup $group -objectattributes @{MSExchHideFromAddressLists=$true}
   }
}           
End {
    Write-Verbose "Ending hide-distributionlists"
}           

}

Tuesday
Sep272011

Powershell Scripts

Over the next few weeks I will be posting up some of my commonly used PowerShell scripts. It might be boring to some, but a lot of people have asked me for them.

For the majority of the posts, I will just post the core parts of the code that is used, I may put some of the scripts up for download later.

Tuesday
Sep272011

WiB - Web Server In A Box

Introduction

Did you realise that the website you could run a website off a server, built from scratch, soldering every separate component, with parts which cost under AU $100 from a local electronics store? Perhaps you have always wondered if you could even build a web server yourself, but not just some hardware or a virtual machine running Apache or IIS but a little tiny web server which draws almost now power and is something you have created yourself?

This whole project came about with a recent trip that I took to the local JayCar store. I usually stop by every few months whilst working on some home project (which I will leave for another day). Your local JayCar store is usually an odd little shop, filled with various electronic components combined with some very friendly and helpful staff. On this trip, I was looking for a universal remote component but stumbled upon their Web Server In A Box or WiB, this kit was created by JayCar from an article in Silicon Chip Australia.

Silicon Chip Magazine printed the original documentation for this project in their November 2009 edition. This was a great piece by Mauro Grassi and covered all of the things you need to know to get you started. Once his original 3 part article was printed JayCar created a kit quite quickly as interest grew. The Jay Car Kitincluded a slightly modified version of Grassi's Silicon Chip Article.

After buying the kit and taking it home, a friend of mine Maz and I quickly started the build, there were several issues encountered along the way, which are documented in section Silicon Chip Article. Once the build was completed, and some test content was being hosted, I decided to put some useful documentation about the project so anyone interested might not make any of the same mistakes as I did.

Many thanks goes out to the steady hands of Maz, who assisted in the original build, I doubt I could have done the surface mount ICs without his help. Everyone should go over and check out his new website located at http://maz.net.au 

Now its been a while since I have started a project like this, especially one from scratch like this. I am amazed at how well it went, and it has renewed my interested in electrical projects.


As usual, if you decided to take any of my advice, and something goes wrong. Please don't try and blame me for it blowing up in your face, I am just not that interested. Having said that if there is any feedback in regards with what is on the site, please feel free to Contact Me

Uses for the WiB

Now the WiB isn't going to be the most fancy web server out there on the Internet. Remember, this is something that cost under AU $100, and has been built at home from scratch, and only contains a very simple processor.

So what can't it do? Well, it cannot run things like PHP, ASP, .NET or Perl, it doesn't have any support for server side scripting, well that isn't quite true. The WiB has some very basic CGI interfaces which allow your pages to interact with the various inputs that are on the device's PCB.

The question really shouldn't be, can I run complex languages like PHP etc, but what can the WiB do really well? Simply put, the WiB is a very secure static page providing web server. As there is no complex operating system, nor are there any complex software languages and environments running on it, the attack surface is quite small. This small attack surface makes it a very nice, very basic and easy to use secure file web server. there is a Security Warning to go with everything I have just said. This Security Warning should be read and understood.

By now you must be thing, what the hell could I do with this thing? Well remember when the web was simple? Do you remember the time of Geocities? Back then we have very powerful sites running on basically the same environment that the WiB provides, it was fine then, why shouldn't it be fine now? Hell, if you are reading this, then the WiB is functioning correctly.

Believe itor not, there are still some very good CMS systems which you can run on the WiB, I will try and keep a list of the ones which I have tried on my WiB below (it will be a short list for now).
- TiddlyWiki
- jQuery slideViewer

If you don't like any of the static CMS systems out there, then why not fire up Dreamweaver or plain old notepad and make a custom site just for you? Not only will it run on your web, but it will be a more personalised experience for you and your visitors.

Notes about the Silicon Chip Article

First of all, many thanks to Silicon Chip Australia and Mauro Grassi for coming up with the great design and providing a very good walk through which allowed me to complete this project. I also want to point out that I was working with the documentation as provided by JayCar who, in their disclaimer mention that they may have modified things to suit their components.

The documentation provided with the kit was certainly more than enough to get the project done. Of course you need to go to the "downloads" section of the Silicon Chip website to download the code to place on your WiB's SD Card so that it properly functions.

Once again, I am not attacking those involved in the kit, just pointing out some issues with the documentation.

1. SD Card Reader and FAT
The documentation doesn't cover if you can use micro SD cards with the provided adapter. There are a few hits to the reader that this might work, but I have been unable to to get this to work.

I have also had some issues with FAT and FAT32 support. I have noticed that you need to use the default allocation unit size, if you don't use the default, the server cannot ready the files on the card.

2. Resistors Counts
There is some conflict with the number of resistors included in the kit and the number that the documentation tells you are required. The documentation states that you need 2 110Ohm resistors, however the board requires 3 110Ohm resistors. The kit does include the correct number.

3. ICMP
There is some confusion about ICMP support. The download package from the website clearly says that there is no ICMP support, as does almost all of the documentation. Having said all of that, in one of the configuration files ICMP support is set to enabled, however it doesn't work. Whilst ICMP ping support would have been handy, it would have been nice if the documentation and configuration files were in sync.

Jay Car Kit

The kit I used to build the web server came from JayCar electronics. This kit contains almost everything you need to build the project, all you will need is patience, an SD Card for storage, and a soldering iron that isn't to hot with a fine tip.

There were several things that needed to be mentioned about the JayCar kit, including:

1. The kit included 12 0 ohm Resistors to be used instead of plain wire.
There are 12 places that the documentation tells you to install some wire runs on the provided PCB, and whilst this was easily done (I had some wire in my tool kit), there was very little documentation telling you to use these resistors instead of plain wire. After spending 30 minutes cutting and soldering wire appropriately, we quickly discovered these resistors and decided to restart from scratch and unsolder everything we had done. It would have been very nice if the documentation included had pointed this out to the reader.

2. Case included wasn't complete.
Whilst I didn't use the case included with the kit, several things need stand out to me. These were issues I noticed with the kit but are probably a side effect of the original design.

a) The case included needed several extra mounting screw holes fitted nor were there any holes for the LED's to be pushed through on.
b) The case is pretty big compared with the very small PCB.
c) The case didn't have any method to push the sd card into the reader.

Conclusion

So to conclude, if you want a fun weekend, look at stopping at your local JayCar and getting a WiB kit!

Friday
Aug262011

Backtrack 5, VNC and XRDP

Just working on my project that I will be unveiling prior to Tech Ed(and will mostly be giving demonstrations of whilst there) and I discovered a rather annoying bug in Backtrack 5.

I was attempting to set up XRDP which is simply a neat little wrapper for VNC and for the life of mean, whenever I connected, either with my RDP client using XRDP or with a VNC client through any of the VNC server options, I couldn't launch any of the tools included with Backtrack 5, for example, when trying to run airodump-ng, you would get the error: "/bin/sh airodump-ng: command not found". I hacked away at various bash profiles and settings, various system settings and pulled my hair out for days; still I couldn't get anything to work.

I knew this worked on Backtrack 4, so what could the possible errors be?

  1. Backtrack 5 is based on Ubuntu 10.04, Backtrack 4 was based on 8.04
  2. Both versions I was running were 32bit
  3. Backtrack 4 came with a VNC option by default, maybe the guys had pre hacked this together to work?
  4. I was running the KDE version of Backtrack 5, and well Backtrack 4 was an older version of KDE

Out of interest sake, I tried the Gnome version Backtrack 5; and it appears to work.

So, if you want to use VNC (and XRDP) use the GNOME version of Backtrack 5!