Archive

Posts Tagged ‘2W’

Fiddler using PowerShell

March 14th, 2011 4 comments

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
[?]
Categories: 2W, Fiddler Tags: ,

Second Wednesday

March 14th, 2011 No comments

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 3.00 out of 5
[?]
Categories: 2W, Demo Tags: ,

$? and $LASTEXITCODE

March 14th, 2011 No comments

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
[?]
Categories: 2W, Error Tags: ,

$Error

March 14th, 2011 No comments

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 4.00 out of 5
[?]
Categories: 2W, Error Tags: ,

Remoting

March 14th, 2011 No comments

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

Here’s a quick introduction to Windows PowerShell remoting. First, we need to Enable remoting on the computers that we want to manage. This is done by using the Enable-PSRemoting cmdlet. Here’s an example.


PS > Enable-PSRemoting


WinRM Quick Configuration
Running command "Set-WSManQuickConfig" to enable this machine for remote management through
 This includes:
    1. Starting or restarting (if already started) the WinRM service
    2. Setting the WinRM service type to auto start
    3. Creating a listener to accept requests on any IP address
    4. Enabling firewall exception for WS-Management traffic (for http only).

Do you want to continue?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
WinRM already is set up to receive requests on this machine.
WinRM has been updated for remote management.
Created a WinRM listener on HTTP://* to accept WS-Man requests to any IP on this machine.
WinRM firewall exception enabled.

Confirm
Are you sure you want to perform this action?
Performing operation "Registering session configuration" on Target "Session configuration "M
not found. Running command "Register-PSSessionConfiguration Microsoft.PowerShell32 -processo
to create "Microsoft.PowerShell32" session configuration. This will restart WinRM service.".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

When remoting is enabled on both the client and target computers you can run commands remote using WinRM. PowerShell includes a couple of CmdLets we can use. If we want to start an interactive session against a computer we can use Enter-PSSession.


PS > Enter-PSSession Client01 -Credential powershell\administrator

[client01]: PS C:\Users\Administrator\Documents>

Notice how we use the Credential parameter to specify different credentials.

When we are finished we call the Exit-PSSession CmdLet to end the Remote Session.


[client01]: PS C:\Users\Administrator\Documents> Exit-PSSession

PS >

If we want to run a set of commands against one or more remote computers without starting an interactive session we use the Invoke-Command cmdlet. Here’s an example.


PS > Invoke-Command -ComputerName Client01,Client02 -ScriptBlock {
>> Get-Process
>> } -Cred powershell\administrator
>>

In the example above we run Get-Process against Client01 and Client02. If you study the output from the example above you’ll notice that an additional property PSComputerName
is added. Also note that the object returned to your session are Deserialized “property bags”. These are not live objects, they are snapshots that have properties, but no methods.

When using the ComputerName parameter, each remote connection is opened when the command executes and closed after execution. It’s possible to keep a session open to perform additional actions using the
New-PSSession CmdLet. Here’s an example.


PS > $sessions = New-PSSession -ComputerName DC01,SP01 -Credential powershell\administrator

Now we can use the Session parameter when executing commands remote. Notice that we do not have to specify any Credentials since they are stored in the PSSession opened earlier.


PS > Invoke-Command -Session $sessions -ScriptBlock { Get-Process }

Finally, let’s take a look at CredSSP. CredSSP is used when we want our remote session to have full access to network resources. This is where CredSSP comes into play. You’ll also want to use
CredSSP in double-hop scenarios such as SharePoint remoting. To enable CredSSP you use the Enable-WSManCredSSP CmdLet both on the Client and Target computer. On the target machine, type:


PS > Enable-WSManCredSSP -Role Server


CredSSP Authentication Configuration for WS-Management
CredSSP authentication allows the server to accept user credentials
authentication on the server, the server will have access to the us
client computer sends them. For more information, see the Enable-WS
Do you want to enable CredSSP authentication?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): Y

cfg               : http://schemas.microsoft.com/wbem/wsman/1/confi
lang              : en-US
Basic             : false
Kerberos          : true
Negotiate         : true
Certificate       : false
CredSSP           : true
CbtHardeningLevel : Relaxed

On the Client computer we use the same command but change the Role to Client. We also specify the Server in the DelegateComputer parameter as shown below.


PS > Enable-WSManCredSSP -role client -delegatecomputer SP01.powershell.nu

Now we can run remote commands using CredSSP.


PS > Enter-PSSession -ComputerName SP01.powershell.nu -Authentication CredSSP -Credential powershell\spAdmin

Note that if you are running within a workgroup you have to enable CredSSP over NTLM.

Rating 3.00 out of 5
[?]
Categories: 2W, Remote Tags: ,