2W – Pentest & Security – with a touch of PowerShell

Yesterday I did a presentation on Pentesting & PowerShell togheter with Security MVP Hasain Alshakarti. We demonstrated how you can use use PowerShell instead of third-party applications when performing pentests. We also talked about how to secure your environment.

Click here to download the presentation: 2W-Pentest-PowerShell

(It’s in Swedish, Bork, bork, bork!)

Rating 4.00 out of 5
[?]

Fiddler using PowerShell

Fiddler is a Web Debugging Proxy which logs all HTTP(S) traffic between your computer and the Internet. It’s a freeware application and can debug traffic from any application, including Internet Explorer, Mozilla Firefox, Opera, alot more.

Click here for more information

So whats this got to do with PowerShell? Well, Fiddler (FiddlerCore) also provides a .NET class library that can be consumed by any .NET application (such as PowerShell).

Click here for more information

FiddlerCore shows a couple of examples of how you can program against FiddlerCore. Lets see how we can do it using Windows PowerShell.

First, we need to install FiddlerCore. You can download FiddlerCore here.

Next, click on FiddlerCoreAPISetup.exe to start the installation.

After the installation is completed you’ll see FiddlerCore.ddl in the folder where you installed FiddlerCore.

Time for some PowerShell. Download the Fiddler.psm1 module and start PowerShell. Use Import-Module to add the module to your current scope. In the example below the location of the module is C:\FiddlerCore\Fiddler.psm1


PS > Import-Module C:\FiddlerCore\Fiddler.psm1

When the module is added to your current scope you cab use Get-Command to display the commands (actually functions) avaialable from the module.

Note that the module currently includes three commands: Start-Fiddler, Receive-Fiddler and Stop-Fiddler. You can also use Get-Help to display information about each command. Here’s an example.


PS > Get-Help Start-Fiddler -Full

NAME
    Start-Fiddler

SYNOPSIS
    Uses FiddlerCore to listen on a specified port.

SYNTAX
    Start-Fiddler [-Path]  [-ListenPort]  [-RegisterAsSystemProxy] [-WhatIf] [-Confirm] 
    []


DESCRIPTION
    Start-Fiddler loads the FiddlerCore DLL and uses Fiddler.FiddlerApplication to listen on a specified port.
    When http(s) traffic is generated Fiddler logs the traffic. The result is exposed through a job interface.
    Start-Fiddler requires FiddlerCore which allows you to integrate HTTP/HTTPS traffic viewing and modification 
    capabilities into your .NET application.


PARAMETERS
    -Path 
        Specifies the path to the assembly DLL file that contain the types (FiddlerCore.dll).

        Required?                    true
        Position?                    1
        Default value
        Accept pipeline input?       false
        Accept wildcard characters?

    -ListenPort 
        Specifies the Port that Fiddler listens to.

        Required?                    true
        Position?                    2
        Default value
        Accept pipeline input?       false
        Accept wildcard characters?

    -RegisterAsSystemProxy []
        Registers as the system proxy, default set to False.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?       false
        Accept wildcard characters?

    -WhatIf []

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?       false
        Accept wildcard characters?

    -Confirm []

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?       false
        Accept wildcard characters?

    
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        "get-help about_commonparameters".

INPUTS

OUTPUTS

NOTES


        Start-Fiddler requires FiddlerCore which allows you to integrate HTTP/HTTPS traffic viewing and 
        modification capabilities into your .NET application.

    -------------------------- EXAMPLE 1 --------------------------

    C:\PS>Start-Fiddler -Path C:\FiddlerCoreAPI\FiddlerCore.dll -ListenPort 8877 -RegisterAsSystemProxy


    Starts Fiddler and listens to Port 8877, registers as the system proxy.





    -------------------------- EXAMPLE 2 --------------------------

    C:\PS>Start-Fiddler -Path C:\FiddlerCoreAPI\FiddlerCore.dll -ListenPort 8877 -RegisterAsSystemProxy -Whatif


    Displays what would happen if you run Start-Fiddler.






RELATED LINKS

https://www.fiddler2.com/fiddler/core/

Let’s go ahead and start Fiddler and do some monitoring. As you might have guessed, the Start-Fiddler command uses Fiddler.FiddlerApplication to listen on a specified port. In the example below the -RegisterAsSystemProxy parameter is used. Internet Explorer and many other applications use the system proxy by default and are notified when it changes. When Start-Fiddler is used with the -RegisterAsSystemProxy parameter the Proxy Server checkbox in Local Area Network (LAN) Settings is checked.


PS > Start-Fiddler -Path C:\FiddlerCoreAPI\FiddlerCore.dll -ListenPort 8877 -RegisterAsSystemProxy

Here’s what happens to the Local Area Network (LAN) Setting in Internet Explorer when the RegisterAsSystemProxy parameter is used.

In the resource monitor you’ll also notice that PowerShell is Listening to the Port you specified as input to ListenPort.

The Start-Fiddler function actually loads the FiddlerCore DLL and uses Fiddler.FiddlerApplication to listen on a specified port. When starting Fiddler.FiddlerApplication the Startup() method is used, here’s a reference post. In this version the function only allows two inputs, ListenPort and RegisterAsSystemProxy. As soon as I get some time off, i’ll update the function (and module) to support even more cool fiddler stuff. Next, the function subscribes to an event using Register-ObjectEvent. In this version the arguments are simply outputted in the Action. Finally, two script variables are created. These are used to keep track of the Event and background job.

Now we can generate some traffic. Start up Internet Explorer and surf the web for a while. In this example I’m checking out www.bing.com.

When your done, type Receive-Fiddler in powershell.

Notice how the traffic generated from Internet Explorer is returned in PowerSHell. Pretty Cool.

The Receive-Fiddler function uses Receive-Job to get the result from the background job created by the event. The function also supports the -Keep parameter which allows you to save the results so that you can receive them again.

Let’s do some more fiddling. In this example I use Internet Explorer and navigate to www.powershell.nu. Back in PowerShell, I use Receive-Fiddler, but this time i store the result in a variable


PS > $result = Receive-Fiddler

Calling the variable displays the logged traffic.


PS > $result | Select-Object -First 1


BitFlags          : None
isHTTPS           : False
isFTP             : False
LocalProcessID    : 1040
SuggestedFilename : 190.txt
bypassGateway     : False
clientPort        : 49407
state             : ReadingResponse
PathAndQuery      : /
fullUrl           : http://www.powershell.nu/
url               : www.powershell.nu/
host              : www.powershell.nu
hostname          : www.powershell.nu
port              : 80
id                : 190
clientIP          : ::ffff:127.0.0.1
responseCode      : 0
bHasResponse      : False
bBufferResponse   : False
Timers            : ClientConnected: 21:14:29.027, ClientBeginRe
                    ateway Determination: 0ms, DNS Lookup: 13ms,
                    ected: 21:14:29.074,FiddlerBeginRequest: 21:
                    esponse: 21:14:30.715,ServerDoneResponse: 21
                    neResponse: 21:14:31.199, Overall Elapsed: 0
ViewItem          :
isTunnel          : False
oResponse         : Fiddler.ServerChatter
oRequest          : Fiddler.ClientChatter
oFlags            : {x-clientport, x-responsebodytransferlength,
requestBodyBytes  : {}
responseBodyBytes :
m_clientIP        : ::ffff:127.0.0.1
m_clientPort      : 49407
m_hostIP          : 217.25.34.124

There are a couple of properties available that contain logged information such as: fullUrl, hostnam, port and so on. Some properties contain simple string values and others contain objects with even more information. As an example, let’s see what oResponse contains.


PS > $result[0].oResponse


MIMEType            : text/html
iTTFB               : 1640
iTTLB               : 2125
bWasForwarded       : False
bServerSocketReused : False
headers             : HTTP/1.1 200 OK
                      Date: Tue, 15 Mar 2011 20:14:29 GMT
                      Server: Apache
                      X-Powered-By: PHP/5.2.16
                      X-Pingback: http://www.powershell.nu/xmlrpc.php
                      Keep-Alive: timeout=5, max=100
                      Connection: Keep-Alive
                      Transfer-Encoding: chunked
                      Content-Type: text/html; charset=UTF-8

pipeServer          :

When your done, use Stop-Fiddler to proparly remove the event, background job and Shut Down Fiddler. Here’s an example:


PS > Stop-Fiddler

Remember to use Stop-Fiddler to close the Fiddler connection. This is important, if you do not use Stop-Fiddler and simply shut down PowerShell the Local Area Network (LAN) Settings will not be unchecked and Internet Explorer may not work proparly.

What if i forgot to use Stop-Fiddler and closed my PowerShell session? Start Internet Explorer, Click on Internet Options/Connections/Local Area Network (LAN) Settings and uncheck “Use a proxy server for your LAN”..

Note that the Fiddler.psm1 module is not fully tested (or fully completed) and should be used in a test-envirnment only. With that said:

Click here to download Fiddler.psm1

Rating 3.00 out of 5
[?]

Second Wednesday

The second Wednesday of each month LabCenter arranges a free Tech Meeting. The meeting starts at 5pm with some discussion, food and beverages before we go deeper into some exciting technology for the rest of the evening.

 

This week, I had the oppurtunity to do a presentation on Windows PowerShell and show some of the cool stuff that you can accomplish using Windows PowerShell in your IT-Environment.

My Demo’s included:

You can click each topic to see a description of the Demo and Code used.

Rating 4.00 out of 5
[?]

$? and $LASTEXITCODE

This post is part of the Second Wednesday Demo Session, Click here for more info about additional demo posts.

In this demo I showed some examples on Error handling in Windows PowerShell. First we took a look at the $? and $LASTEXITCODE variables.
The $? variable displays a Boolean value that represents the success or failure of the last command. as an example, we’ll first run a command that works
and examine the $? variable.


PS > cd 'C:\Program Files'
PS > $?

True

In the example we use cd (alias for Set-Location) to change working location to a specific location. Notice that $? returned True.

If we try to set the location to a non-existing folder an error occurs and $? returns False.


PS > cd C:\FolderThatDoesntExist

Set-Location : Cannot find path 'C:\FolderThatDoesntExist' because it does not exist.
At line:1 char:3
+ cd <<<<  C:\FolderThatDoesntExist
    + CategoryInfo          : ObjectNotFound: (C:\FolderThatDoesntExist:String) [Set-Location], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetLocationCommand

PS > $?

False

Next we took a look at $LASTEXITCODE. The variable returns a number that represents the exitcode of the last script or application.
In this example we used ping.exe.


PS > ping 127.0.0.1 -n 1

Pinging 127.0.0.1 with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

Ping statistics for 127.0.0.1:
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 0ms, Average = 0ms

PS > $LASTEXITCODE

0

When we tried to ping a nonexisting machine the $LASTEXITCODE variable returned 1 instead.


PS > ping NonExistingMachine -n 1

Ping request could not find host NonExistingMachine. Please check the name and try again.

PS > $LASTEXITCODE

1

Rating 3.00 out of 5
[?]

$Error

This post is part of the Second Wednesday Demo Session, Click here for more info about additional demo posts.

The $error variable contains an array of errors generated in the current session. If we want to check the latest occured error we can type:


PS > cd C:\FolderThatDoesntExist

Set-Location : Cannot find path 'C:\FolderThatDoesntExist' because it does not exist.
At line:1 char:3
+ cd <<<<  C:\FolderThatDoesntExist
    + CategoryInfo          : ObjectNotFound: (C:\FolderThatDoesntExist:String) [Set-Location], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetLocationCommand

PS > $Error[0]

Set-Location : Cannot find path 'C:\FolderThatDoesntExist' because it does not exist.
At line:1 char:3
+ cd <<<<  C:\FolderThatDoesntExist
    + CategoryInfo          : ObjectNotFound: (C:\FolderThatDoesntExist:String) [Set-
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetLocationC

We can also list detailed information about the error by pipe:ing the object to Format-List as shown below.


PS > $Error[0] | Format-List -Force


Exception             : System.Management.Automation.ItemNotFoundException: Cannot fi
                         because it does not exist.
                           at System.Management.Automation.LocationGlobber.ExpandMshG
                        NonexistingPaths, PSDriveInfo drive, ContainerCmdletProvider
                        ntext)
                           at System.Management.Automation.LocationGlobber.ResolveDri
                        tProviderContext context, Boolean allowNonexistingPaths, Cmdl
                           at System.Management.Automation.LocationGlobber.GetGlobbed
                        h, Boolean allowNonexistingPaths, CmdletProviderContext conte
                        ce)
                           at System.Management.Automation.SessionStateInternal.SetLo
                        Context context)
                           at System.Management.Automation.PathIntrinsics.SetLocation
                        t context)
                           at Microsoft.PowerShell.Commands.SetLocationCommand.Proces
TargetObject          : C:\FolderThatDoesntExist
CategoryInfo          : ObjectNotFound: (C:\FolderThatDoesntExist:String) [Set-Locati
FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo
PipelineIterationInfo : {0, 1}
PSMessageDetails      :

If we want to count the number of errors in the $error variable we use the Count property.


PS > $error.Count

1

And we can even clear the error list by using the Clear() method.


PS > $error.Clear()

The number of errors that are listed in the $error variable is determined in $MaximumErrorCount. By default the variable is set to 256, meaning that the error
list holds a maximunm of 256 errors. We can, of course change this to a higher number by typing:


PS > $MaximumErrorCount = 500

Rating 3.00 out of 5
[?]