Sunday, July 15, 2012

Finding PowerShell's Missing Binary Operator - Rotate Right

One of my complaints about PowerShell is its lack of binary operators. As of version 2, it had the -bor, -band, and -bxor operators. Also, thankfully, version 3 will include shift left and shift right operators - -shl and -shr. Unfortunately, there is no rotate right operator. I could certainly write a function to perform a binary rotate right operation but why reinvent the wheel when it is more than likely that .NET has already implemented rotate right. Indeed it already has. System.Security.Cryptography.SHA256Managed and System.Security.Cryptography.SHA512Managed both have private, static methods that operate on unsigned 32 and 64-bit values respectively.

My function below utilizes reflection to provide a public wrapper to these private methods:


Here are some usage examples:

PS > Rotate-Right 256 1
128

PS > Rotate-Right ([UInt64] 4294967296) 32
1


To access the private methods, you call the GetMethod method. Normally, to view a type's static or instance methods, you would just pipe it to Get-Member. However, Get-Member will only return public members. The GetMethod method allows you to specify BindingFlags. In the case of RotateRight, it is a NonPublic and Static method. Also, if a method has overloaded parameter sets, you need to specify the specific parameter set in the form of a Type array to GetMethod.

Lastly, when writing a function with multiple parameter sets, a really useful tip is to use a switch statement to process each parameter set accordingly. This can be accomplished using the built-in $PsCmdlet.ParameterSetName property.

Relevant links:

PowerShell V2: ParameterSets
Type.GetMethod Method (String, BindingFlags, Binder, Type[], ParameterModifier[])

2 comments:

  1. Now that we have powershell execution directly from meterpreter sesssions, would you consider adding powersploit to MSF in the data/exploits/powershell folder? Better yet we could write modules around the functionality or adding what's needed to lib to ease post exploitation and automation thereof. Thanks for publishing the work, quite educational.
    -RLTM

    ReplyDelete
    Replies
    1. Hey RageLtMan,

      You are more than welcome take any PowerSploit script and incorporate into data/exploits/powershell. As you've probably seen, we both use the same licensing. As for developing modules, my ruby is less than optimal. I wouldn't want to make a joke of Metasploit. hehe. I suppose I could use this as an opportunity to learn. I'll keep you guys posted should I have any modules to contribute. Thanks!

      ~Matt

      Delete