Navigation

Entries by Carlos Perez (157)

Tuesday
Jul102012

MDNSRecon

Recently I was chatting with my good friend Elliot Cutright also known in twitter as @nullthreat about the recent changes I have been doing to DNSRecon and several of the improvements. He commented that he would miss the MDNS enumeration feature I had on it originally. Do to my move of supporting Python 3.x and supporting Python 2.x and above for the tool I had to drop that feature in addition that library I used for it was abandoned by the author for quite some time. MDNS is a great way to find all sorts of information about hosts in your same subnet specially since the MDSN records act as regular DNS SRV records where we get Service name that most times include the protocol and name, Target for the service, Port and a text field with additional information. In addition to this one can resolve the hosts to their IPv4 and IPv6 addresses.

Based on the request I wrote a Ruby script that leveraged the tool avahi-browser and set as my goals for the script:

  • Detect most of the supported MDNS Records in the local subnet the attacker is connected on.
  • Do not resolve those services running on the attackers machine.
  • Make sure that the out put was useful and easy to parse and manipulate for a tester.

The resulting script I called MDNSRecon and can be downloaded from my GitHub account at https://github.com/darkoperator/MDNSRecon 

root@bt:~# ./mdnsrecon.rb -h
MDNSRecon Script by Carlos Perez (carlos_perez[at]darkoperator.com)
Version 0.1
Usage: mdnsrecon.rb [OPTION]
--help, -h:
show help
--csv <file>, -c <file>:
CSV File to save records found.
--grep, -g:
Output grepable Output with a delimiter of \
<service>\domain\host\IP\port\txt
If no option is given it will print records found to standard output.

If ran with no option we get output similar to this one if machines are available:

root@bt:~# ./mdnsrecon.rb 
[-] Records found:
[*] Host: bt.local
[*] IP: 192.168.192.128
[*] Port: 9
[*] Service:Workstation
[*] Text:''
[*]
[*] Host: ubuntu.local
[*] IP: 192.168.192.129
[*] Port: 9
[*] Service:Workstation
[*] Text:''
[*]
[*] Host: ubuntu.local
[*] IP: 192.168.192.129
[*] Port: 22
[*] Service:_udisks-ssh._tcp
[*] Text:''
[*]

If We want the output in a grepable format we use the -g options so the cut command and grep can be used to better find targets, in this example we will look for SSH services:

root@bt:~# ./mdnsrecon.rb -g | grep ssh |cut -d '\' -f4,5 --output-delimiter=" " -n
192.168.192.129 22

Now in the case we want to save the results in a format we can email someone or parse a larger set of results like those you can find on a conference floor ( or so I was told) you can select to save to a CSV file and later user a spreadsheet program or PowerShell on Windows to parse and slice:

root@bt:~# ./mdnsrecon.rb -c lab.csv
[-] Saving found records to lab.csv
[*] 3 Records saved
root@bt:~# cat lab.csv 
service,domain,host,ip,port,txt
Workstation,local,bt.local,192.168.192.128,9,''
_udisks-ssh._tcp,local,ubuntu.local,192.168.192.129,22,''
Workstation,local,ubuntu.local,192.168.192.129,9,''

So far I'm only supporting Debian, Ubuntu and Backtrack 5 as the platforms to run the script on, recommending Backtrack 5 as the preferred one. I will add other distributions of Linux depending on the amount of requests I get. I do hope you find the script useful and as with any of my projects feedback and feature request are always welcomed.

Friday
Jun152012

Parsing Nessus CSV Reports with PowerShell

Recently in the Pauldotcom Podcast Paul was mentioning how he uses Awk, cut and other bash tools to process a Nessus CSV report file and format the host output so he could use it in another tool. I saw his command and thought I would do it in PowerShell for kicks since PowerShell turns each row in to an object I can manipulate. Lets take a look at the Import-Csv cmandlet and what are the members of the object it returns:

Import-Csv C:\Users\carlos\Desktop\nessus.csv | Get-Member
   TypeName: System.Management.Automation.PSCustomObject
Name          MemberType   Definition                                                              
----          ----------   ----------                                                              
Equals        Method       bool Equals(System.Object obj)                                          
GetHashCode   Method       int GetHashCode()                                                       
GetType       Method       type GetType()                                                          
ToString      Method       string ToString()                                                       
CVE           NoteProperty System.String CVE=N/A                                                   
CVSS          NoteProperty System.String CVSS=                                                     
Description   NoteProperty System.String Description=One of several ports that were previously o...
Host          NoteProperty System.String Host=192.168.1.161                                        
Name          NoteProperty System.String Name=Open Port Re-check                                   
Plugin ID     NoteProperty System.String Plugin ID=10919                                           
Plugin Output NoteProperty System.String Plugin Output=Port 49156 was detected as being open but...
Port          NoteProperty System.String Port=0                                                    
Protocol      NoteProperty System.String Protocol=tcp                                              
Risk          NoteProperty System.String Risk=None                                                 
Solution      NoteProperty System.String Solution=- increase checks_read_timeout and/or reduce m...
Synopsis      NoteProperty System.String Synopsis=Previously open ports are now closed. 

We can see that the Nessus data for each plugin that ran is represented as NoteProperty for the object as a string. Lets see if I have some vulnerabilities found that it reports as being High for this we will use the Where-Object cmdlet to filter the objects:

 Import-Csv C:\Users\carlos\Desktop\nessus.csv | where {$_.risk -eq "high"}
Plugin ID     : 53382
CVE           : CVE-2010-3190
CVSS          : 9.3
Risk          : High
Host          : 192.168.1.161
Protocol      : tcp
Port          : 445
Name          : MS11-025: Vulnerability in Microsoft Foundation Class (MFC) Library Could Allow 
                Remote Code Execution (2500212)
Synopsis      : Arbitrary code can be executed on the remote host through the Microsoft Foundation 
                Class library.
Description   : The remote Windows host contains a version of the Microsoft Foundation Class (MFC) 
                library affected by an insecure library loading vulnerability.  The path used for 
                loading external libraries is not securely restricted. 
                
                An attacker can exploit this by tricking a user into opening an MFC application in 
                a directory that contains a malicious DLL, resulting in arbitrary code execution.
Solution      : Microsoft has released a set of patches for Visual Studio .NET 2003, 2005, and 
                2008, as well as Visual C++ 2005, 2008, and 2010 :
                
                http://technet.microsoft.com/en-us/security/bulletin/ms11-025
Plugin Output : 
                
                The following Visual C++ Redistributable Package has not
                been patched : 
                
                  Product           : Visual C++ 2008 SP1 Redistributable Package
                  Installed version : 9.0.30729.4148
                  Fixed version     : 9.0.30729.6161
                
.......
Great we found several. One advantage is that PowerShell is not case sensitive in it's operators unless you implicitly specify it, this allows me to specify the risk and “hight” and the value being capitalized . Now lets say I want to know what hosts have high vulnerabilities and only want their IP returned, for this we will use the Select-Object cmdlet and only get unique entries:
Import-Csv C:\Users\carlos\Desktop\nessus.csv | where {$_.risk -eq "high"} | select host -Unique
Host                                                                                               
----                                                                                               
192.168.1.161                                                                                      
192.168.1.160   

We could also filter by plugin if we are performing a pentest and what to come up with list of targets to feed to a tool piping it to the cmdlet out-file and giving it a file to save the IP’s to.

If we like doing all of the matching and sorting in a GUI interface we can take a look of the results in a grid view. Lets look at high, medium and low vulnerabilities and we will look at the Plugin ID, CVE, CVSS, Risk, Host, Protocol, Port and Name:

Import-Csv C:\Users\carlos\Desktop\nessus.csv | where {"high","medium","low" -contains $_.risk} | select "Plugin ID", CVE, CVSS, Risk, Host, Protocol, Port, Name | Out-GridView

This would bring up the following screen for us to filter and sort the information in a graphical manner:

image

Now what if we want to turn the data in to an HTML Report, well PowerShell also allows us to do it using the ConvertTo-Html cmdlet and turn it in to an HTML report in list format:

Import-Csv C:\Users\carlos\Desktop\nessus.csv | where {"high","medium","low" -contains $_.risk} | select "Plugin ID", CVE, CVSS, Risk, Host, Protocol, Port, Name | ConvertTo-Html -As List > report.html

This will create a report that looks like this:

image

One could go even fancier with pre-made CSS and HTML templates, but I will leave that for you to explore.

Wednesday
Apr182012

Introduction to Microsoft PowerShell – Variables

There are several types of variables this are:

  • User Created – These variables are the ones we create in the shell and in scripts. This variables are present only in the current process we are on and are lost when we close the session. We can create variables in scripts with global, script, or local scope.
  • Automatic – These variables keep the state of the PowerShell session and can not be modified directly. The values of this variables change as we execute and use the PowerShell session. This variables will save last run state of cmdlets, commands as well as other objects and information.
  • Preference – These variables store user preferences for PowerShell. These variables are created by PowerShell  when a session is started and are populated with default values. We can change the values of these variables. For example, MaximumHistoryCount that sets  the maximum number of entries in the session history.
  • Environment – These variables are the variables set by the system for Command and PowerShell environments.

Creating and Accessing Variables

In PowerShell variables behave a bit differently than from what we are used to in other shell environments. We will see that do to the the unique way that PowerShell treats everything as an object variables are treated like so. Variable in PowerShell in reality are units of memory where we store values. Variables start with the symbol $ and followed by a string of letters like:

$this_is_a_variable

The string of letters and characters must be continuous and I recommend as a best practice to use descriptive names for the variables, you can use a mix of camel case where each word is capitalized or separate each work with a underscore as the example above.

Variables in PowerShell are not case sensitive and they may contain any letter, number and special character. When special characters are used they need to be enclosed in {}:

PS C:\Users\Carlos\Desktop> ${this is an actual var of var's} = 10

PS C:\Users\Carlos\Desktop> ${this is an actual var of var's}

10

To assign a value to a variable we have 3 methods in PS. The first one is by just setting a name and using the = sign and providing any value we want to set:

$var1 = 1

We can also use the the New-Variable cmdlet:

New-Variable -Name var3 -Value "hello" -Description "Sample string variable"

As we can see the cmdlet provide us with the largest amount of options. Lets look at the the help for it:

PS C:\Users\Carlos\Desktop> help New-Variable

NAME
    New-Variable

SYNOPSIS
    Creates a new variable.


SYNTAX
    New-Variable [-Name] <string> [[-Value] <Object>] [-Description <string>] [-Force] [-Option {None | ReadOnly | Constant | Private | AllScope}] [-PassThru] [-Scope <string>] [-Visibility {Public |
     Private}] [-Confirm] [-WhatIf] [<CommonParameters>]


DESCRIPTION
    The New-Variable cmdlet creates a new variable in Windows PowerShell. You can assign a value to the variable while creating it or assign or change the value after it is created.

    You can use the parameters of New-Variable to set the properties of the variable (such as those that create read-only or constant variables), set the scope of a variable, and determine whether va
    riables are public or private.

    Typically, you create a new variable by typing the variable name and its value, such as "$var = 3", but you can use the New-Variable cmdlet to use its parameters.


RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113361
    Get-Variable
    Set-Variable
    Remove-Variable
    Clear-Variable

REMARKS
    To see the examples, type: "get-help New-Variable -examples".
    For more information, type: "get-help New-Variable -detailed".
    For technical information, type: "get-help New-Variable -full".

As we can see it provides a lot of flexibility when creating the variable. The Se-Variable cmdlet can also be used and has a similar list of options as the New-Varibale cmdlet with some slight differences, like the ability to pass the variable content with the –PassThru parameter to the pipe to be consumed by another cmdlet.

When we want to get the value of a variable we can just type the variable name in the shell and hit enter. We can also use the Get-Variable cmdlet:

PS C:\Users\Carlos\Desktop> $var1 = 1
PS C:\Users\Carlos\Desktop> $var1
1
PS C:\Users\Carlos\Desktop> Get-Variable -Name var1
Name                           Value
----                           -----
var1                           1

One thing to keep in mind is that as we covered in previous blog post variables are also available as a PSDrive so we can treat them also as a file system. If we want to get a listing of all variable we would use the Get-Variable cmdlet with no parameters we can also do a Dir of the PSDrive:

PS C:\Users\Carlos\Desktop> dir variable:

Name                           Value
----                           -----
$                              variables:
?                              False
^                              dir
_
args                           {}
ConfirmPreference              High
ConsoleFileName
DebugPreference                SilentlyContinue
Error                          {Cannot find drive. A drive with the name 'variables' does not exist., Cannot find drive. A drive with the name 'variables' does not exist., Cannot find drive. A dri...
ErrorActionPreference          Continue
ErrorView                      NormalView
ExecutionContext               System.Management.Automation.EngineIntrinsics
false                          False
FormatEnumerationLimit         4
HOME                           C:\Users\Carlos
Host                           System.Management.Automation.Internal.Host.InternalHost
input                          System.Collections.ArrayList+ArrayListEnumeratorSimple
LASTEXITCODE                   0
MaximumAliasCount              4096
MaximumDriveCount              4096
MaximumErrorCount              256
MaximumFunctionCount           4096
MaximumHistoryCount            64
MaximumVariableCount           4096
MyInvocation                   System.Management.Automation.InvocationInfo
NestedPromptLevel              0
null
OutputEncoding                 System.Text.ASCIIEncoding
PID                            6648
PROFILE                        C:\Users\Carlos\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
ProgressPreference             Continue
PSBoundParameters              {}
PSCulture                      en-US
PSEmailServer
PSHOME                         C:\Windows\System32\WindowsPowerShell\v1.0
PSSessionApplicationName       wsman
PSSessionConfigurationName     http://schemas.microsoft.com/powershell/Microsoft.PowerShell
PSSessionOption                System.Management.Automation.Remoting.PSSessionOption
PSUICulture                    en-US
PSVersionTable                 {PSVersion, PSCompatibleVersions, BuildVersion, PSRemotingProtocolVersion...}
PWD                            C:\Users\Carlos\Desktop
ReportErrorShowExceptionClass  0
ReportErrorShowInnerException  0
ReportErrorShowSource          1
ReportErrorShowStackTrace      0
ShellId                        Microsoft.PowerShell
srvs                           {System.ServiceProcess.ServiceController, System.ServiceProcess.ServiceController, System.ServiceProcess.ServiceController, System.ServiceProcess.ServiceController...}
StackTrace                        at System.Management.Automation.PropertyReferenceNode.SetValue(PSObject obj, Object property, Object value, ExecutionContext context)
test                           hello
true                           True
var1                           1.3
var2                           20
VerbosePreference              SilentlyContinue
WarningPreference              Continue
WhatIfPreference               False

To get the contents of a variable when using the PSDrive Method we would use the Get-Content cmdlet just like we would with a file:

PS C:\Users\Carlos\Desktop> Get-Content Variable:\PSHOME

C:\Windows\System32\WindowsPowerShell\v1.0

When we want to know what type of value we have in a variable we can use the the .GetType() method and we can get the property of .Name to see the name of the type or use .FullName to get the .Net type.

PS C:\Users\Carlos\Desktop> $var1.GetType().Name

Int32

As we can see in several of the examples we treat variables as object. We can even get the members of the object with the Get-Members cmdlet:

PS C:\Users\Carlos\Desktop> get-variable -name var2 | Get-Member

TypeName: System.Management.Automation.PSVariable Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() IsValidValue Method bool IsValidValue(System.Object value) ToString Method string ToString() Attributes Property System.Collections.ObjectModel.Collection`1[[System.Attribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] Attributes {get;} Description Property System.String Description {get;set;} Module Property System.Management.Automation.PSModuleInfo Module {get;} ModuleName Property System.String ModuleName {get;} Name Property System.String Name {get;} Options Property System.Management.Automation.ScopedItemOptions Options {get;set;} Value Property System.Object Value {get;set;} Visibility Property System.Management.Automation.SessionStateEntryVisibility Visibility {get;set;}

Just like objects if the property allows us to set it’s value we can change it:

PS C:\Users\Carlos\Desktop> $srvs = Get-Service

PS C:\Users\Carlos\Desktop> (get-variable srvs).Description = "This variable contains the services objects"

PS C:\Users\Carlos\Desktop> get-variable srvs | select name,description | ftAutoSize

Name Description ---- ----------- srvs This variable contains the services objects

 

Dynamic and Static Typing of Variables

PowerShell uses the .Net Framework variable types. The most common types of values we can have in a variable are shown in the table bellow:

Variable type Description
[array] An array
[bool] Yes-no value
[byte] Unsigned 8-bit integer, 0...255
[char] Individual unicode character
[datetime] Date and time indications
[decimal] Decimal number
[wmi] WMI Object
[double] Double-precision floating point decimal
[guid] Globally unambiguous 32-byte identification number
[hashtable] Hash table
[int16] 16-bit integer with characters
[int32], [int] 32-bit integers with characters
[int64], [long] 64-bit integers with characters
[nullable] Widens another data type to include the ability to contain null values.
[psobject] PowerShell object
[regex] Regular expression
[sbyte] 8-bit integers with characters
[scriptblock] PowerShell scriptblock
[single], [float] Single-precision floating point number
[string] String
[switch] PowerShell switch parameter
[timespan] Time interval
[type] Type
[uint16] Unsigned 16-bit integer
[uint32] Unsigned 32-bit integer
[uint64] Unsigned 64-bit integer

 

In PowerShell variables are dynamic. This means that we do not have to declare them and specify a type ahead of use and it can take any value type we want to give it.

PS C:\Users\Carlos\Desktop> $var1 = 1

PS C:\Users\Carlos\Desktop> $var1.GetType().Name

Int32

PS C:\Users\Carlos\Desktop> $var1 = "string"

PS C:\Users\Carlos\Desktop> $var1.GetType().Name

String

PS C:\Users\Carlos\Desktop> $var1 = 1.30

PS C:\Users\Carlos\Desktop> $var1.GetType().Name

Double

Now as mentioned before PowerShell variables can be dynamically typed, but we can also strong type variable by casting them using the variable type:

PS C:\Users\Carlos\Desktop> [int32]$var2 = 10

PS C:\Users\Carlos\Desktop> $var2.GetType().Name

Int32

PS C:\Users\Carlos\Desktop> $var2 = "hello"

Cannot convert value "hello" to type "System.Int32". Error: "Input string was not in a correct format." At line:1 char:6 + $var2 <<<< = "hello" + CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException + FullyQualifiedErrorId : RuntimeException

As we can see we got an error when we tried to save a string to the variable. The type is set in the Attribute property of the variable and if we remove the attribute it will become a dynamic variable again.

Variable Options and Attributes

We can also mark variables as read only using the SetVariable cmdlet on existing variables or when creating them with the New-Variable cmdlet:

PS C:\Users\Carlos\Desktop> Set-Variable -Name var2 -Option ReadOnly

PS C:\Users\Carlos\Desktop> $var2 = 20

Cannot overwrite variable var2 because it is read-only or constant. At line:1 char:6 + $var2 <<<< = 20 + CategoryInfo : WriteError: (var2:String) [], SessionStateUnauthorizedAccessException + FullyQualifiedErrorId : VariableNotWritable

As we can see we could not change the value on a ReadOnly variable by using assignment. But we can change it using the Set-Variable cmdlet and giving it the parameter of –Force:

PS C:\Users\Carlos\Desktop> Set-Variable -Name var2 -Value 20 -Force

PS C:\Users\Carlos\Desktop> $var2

20

If we want an immutable variable we have to create the variable as a Constant. By declaring it as one it can not be deleted, changed nor cleared during the duration of a session.

For clearing a variable we can use the Clear-Variable cmdlet or assign to it the $null value ($null is an Automatic variable created by PowerShell at startup of a session)

PS C:\Users\Carlos\Desktop> $testvar = "hello"

PS C:\Users\Carlos\Desktop> $testvar

hello

PS C:\Users\Carlos\Desktop> Clear-Variable testvar

PS C:\Users\Carlos\Desktop> $testvar

PS C:\Users\Carlos\Desktop>

We can also treat it as file (Child-Item) in a file system in the variables PSDrive:

PS C:\Users\Carlos\Desktop> $testvar = "hello"

PS C:\Users\Carlos\Desktop> Get-Content Variable:\testvar

hello

PS C:\Users\Carlos\Desktop> Set-Content -Value $null -Path Variable:\testvar

PS C:\Users\Carlos\Desktop> Get-Content Variable:\testvar

PS C:\Users\Carlos\Desktop>


We can also use assignment to clear the variable this is done by assigning $null to it:

PS C:\Users\Carlos\Desktop> $var4 = "PS Rocks!"

PS C:\Users\Carlos\Desktop> $var4 = $null

PS C:\Users\Carlos\Desktop> $var4

PS C:\Users\Carlos\Desktop>

To delete a variable we use the Remove-Variable cmdlet and it will be deleted from the current session:

PS C:\Users\Carlos\Desktop> Remove-Variable var4
PS C:\Users\Carlos\Desktop> dir variable:\var*

Name                           Value
----                           -----
var1                           1.3
var2                           20

If a Variable has an option of ReadOnly we can remove it by passing the parameter of –Force to the Remove-Variable cmdlet.

Variables in PowerShell can have several attributes that will control not only the variable type it will accept but other restrictions we might want to impose upon them. Attributes are saved as an Array in the property which allows us to have several attributes assigned to the variable object. Lets look at the attributes of $var2:

# We get the variable object first in to another variable to make it easier to manipulate

PS C:\Users\Carlos\Desktop> $avar = Get-Variable var2

# Lets get members of the variable

PS C:\Users\Carlos\Desktop> $avar | Get-Member

TypeName: System.Management.Automation.PSVariable Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() IsValidValue Method bool IsValidValue(System.Object value) ToString Method string ToString() Attributes Property System.Collections.ObjectModel.Collection`1[[System.Attribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] Attributes {get;} Description Property System.String Description {get;set;} Module Property System.Management.Automation.PSModuleInfo Module {get;} ModuleName Property System.String ModuleName {get;} Name Property System.String Name {get;} Options Property System.Management.Automation.ScopedItemOptions Options {get;set;} Value Property System.Object Value {get;set;} Visibility Property System.Management.Automation.SessionStateEntryVisibility Visibility {get;set;} #Lets get the attribute property

PS C:\Users\Carlos\Desktop> $avar.Attributes

TypeId ------ System.Management.Automation.ArgumentTypeConverterAttribute

The attributes we can set are:

  • System.Management.Automation. ValidateSetAttribute – The value may have only a given set of values.
  • System.Management.Automation. ValidateRangeAttribute – The value must match a particular number range.
  • System.Management.Automation. ValidatePatternAttribute – The value must match a Regular Expression.
  • System.Management.Automation.ValidateNotNullOrEmptyAttribute –The value may not be zero or empty ($null).
  • System.Management.Automation. ValidateNotNullAttribute – The value may not be zero.
  • System.Management.Automation. ValidateLengthAttribute – The value must be in a specified range given a minimum and maximum length.

The attributes must be objects and they are set using the method of Attribute.Add() and we pass as an argument a new object created with the New-Object cmdlet. Lets start by clearing the  attribute for Int types.

PS C:\Users\Carlos\Desktop> $avar.Attributes.Clear()

PS C:\Users\Carlos\Desktop> $avar.Attributes

PS C:\Users\Carlos\Desktop>

Let make a variable only take a Range:

PS C:\Users\Carlos\Desktop>$var2 = 5 PS C:\Users\Carlos\Desktop> $avar.Attributes.Add($(New-Object System.Management.Automation.ValidateRangeAttribute -argumentList 1,20))

PS C:\Users\Carlos\Desktop> $var2 = 1

PS C:\Users\Carlos\Desktop> $var2 = 22

The variable cannot be validated because the value 22 is not a valid value for the var2 variable.

At line:1 char:6

+ $var2 <<<< = 22

+ CategoryInfo : MetadataError: (:) [], ValidationMetadataException

+ FullyQualifiedErrorId : ValidateSetFailure

Lets look now at setting a set of approved values:

PS C:\Users\Carlos\Desktop> $var2 = "yes"

PS C:\Users\Carlos\Desktop> $avar = Get-Variable var2

PS C:\Users\Carlos\Desktop> $avar.Attributes.Add($(New-Object System.Management.Automation.ValidateSetAttribute -argumentList "yes", "no", "y", "n"))

PS C:\Users\Carlos\Desktop> $var2 = "no"

PS C:\Users\Carlos\Desktop> $var2 = "y"

PS C:\Users\Carlos\Desktop> $var2 = "n"

PS C:\Users\Carlos\Desktop> $var2 = "si"

The variable cannot be validated because the value si is not a valid value for the var2 variable. At line:1 char:6 + $var2 <<<< = "si" + CategoryInfo : MetadataError: (:) [], ValidationMetadataException + FullyQualifiedErrorId : ValidateSetFailure

Lets set a pattern to match a string starting with a specific string. The pattern should be a regular expression:

PS C:\Users\Carlos\Desktop> $pattern_var = "PS Rocks uhmmm"

PS C:\Users\Carlos\Desktop> $pvar = Get-Variable pattern_var

PS C:\Users\Carlos\Desktop> $pattern = "PS Rocks*"

PS C:\Users\Carlos\Desktop> $pvar.Attributes.Add($(New-Object System.Management.Automation.ValidatePatternAttribute -ArgumentList $pattern))

PS C:\Users\Carlos\Desktop> $pattern_var = "PS Sucks!"

The variable cannot be validated because the value PS Sucks! is not a valid value for the pattern_var variable.

At line:1 char:13

+ $pattern_var <<<< = "PS Sucks!"

+ CategoryInfo : MetadataError: (:) [], ValidationMetadataException

+ FullyQualifiedErrorId : ValidateSetFailure

Lets look at validating a length from 1 to 8:

PS C:\Users\Carlos\Desktop> $length_var = "1234"

PS C:\Users\Carlos\Desktop> $lvar = Get-Variable length_var

PS C:\Users\Carlos\Desktop> $lvar.Attributes.Add($(New-Object System.Management.Automation.ValidateLengthAttribute -ArgumentList 1,8))

PS C:\Users\Carlos\Desktop> $length_var = "Hello I'm longer than 8 chars"

The variable cannot be validated because the value Hello I'm longer than 8 chars is not a valid value for the length_var variable.

At line:1 char:12

+ $length_var <<<< = "Hello I'm longer than 8 chars"

+ CategoryInfo : MetadataError: (:) [], ValidationMetadataException

+ FullyQualifiedErrorId : ValidateSetFailure

For the other attributes of Null and Empty checking we just create the object with no arguments and pass it as an attribute.

Variable Scopes

Just like with any other shell that supports scripting and most modern scripting languages variables will have a scope. Scope is in what parts of a session or script the variable is available to us for use. In PowerShell the scopes are:

  • $global – Variables are accessible to scripts, function and to any cmdlet in the current session.
  • $script – Variables are only accessible inside the running context of the script and are discarded after the script finishes executing.
  • $private – Variables are valid only in the current scope, either a script or a function. They cannot be passed to other scopes.
  • $local – Variables are valid only in the current scope of the script or session. All scopes called with them can read, but not change, the contents of the variable and it is the default when creating a variable.

to declare a variable in an scope other than local scope we do it by appending to the beginning of the variable declaration the scope:

# Declaring the variable

PS C:\Users\Carlos\Desktop> $global:gvar = "This is a global variable"

PS C:\Users\Carlos\Desktop> $gvar

This is a global variable

# Using the New-Variable cmdlet

PS C:\Users\Carlos\Desktop> $global:gvar = "This is a global variable"

PS C:\Users\Carlos\Desktop> $gvar

This is a global variable

Automatic Variables

Automatic variables are created and populated when the session is launched. These variables will contain user information, system information, default variables, run time variables and settings for PowerShell. To get a look at the variables and what they do we can either do Get-Help about_Automatic_Variables or list the variables and select only the name and description as shown bellow:

PS C:\Users\Carlos> Get-Variable | select name,description | ft -AutoSize -Wrap

Name Description ---- ----------- $ ? Execution status of last command. ^ _ args ConfirmPreference Dictates when confirmation should be requested. Confirmation is requested when the Confir mImpact of the operation is equal to or greater than $ConfirmPreference. If $ConfirmPrefe rence is None, actions will only be confirmed when Confirm is specified. ConsoleFileName Name of the current console file. DebugPreference Dictates action taken when an Debug message is delivered. Error ErrorActionPreference Dictates action taken when an Error message is delivered. ErrorView Dictates the view mode to use when displaying errors. ExecutionContext The execution objects available to cmdlets. false Boolean False FormatEnumerationLimit Dictates the limit of enumeration on formatting IEnumerable objects. HOME Folder containing the current user's profile. Host This is a reference to the host of this Runspace. input MaximumAliasCount The maximum number of aliases allowed in a session. MaximumDriveCount The maximum number of drives allowed in a session. MaximumErrorCount The maximum number of errors to retain in a session. MaximumFunctionCount The maximum number of functions allowed in a session. MaximumHistoryCount The maximum number of history objects to retain in a session. MaximumVariableCount The maximum number of variables allowed in a session. MyInvocation NestedPromptLevel Dictates what type of prompt should be displayed for the current nesting level. null References to the null variable always return the null value. Assignments have no effect. OutputEncoding The text encoding used when piping text to a native executable. PID Current process ID. PROFILE ProgressPreference Dictates action taken when Progress Records are delivered. PSBoundParameters PSCulture Culture of the current Windows PowerShell Session. PSEmailServer Variable to hold the Email Server. This can be used instead of HostName parameter in Send -MailMessage cmdlet. PSHOME Parent folder of the host application of this Runspace. PSSessionApplicationName AppName where the remote connection will be established PSSessionConfigurationName Name of the session configuration which will be loaded on the remote computer PSSessionOption Default session options for new remote sessions. PSUICulture UI Culture of the current Windows PowerShell Session. PSVersionTable Version information for current PowerShell session. PWD ReportErrorShowExceptionClass Causes errors to be displayed with a description of the error class. ReportErrorShowInnerException Causes errors to be displayed with the inner exceptions. ReportErrorShowSource Causes errors to be displayed with the source of the error. ReportErrorShowStackTrace Causes errors to be displayed with a stack trace. ShellId The ShellID identifies the current shell. This is used by #Requires. StackTrace true Boolean True VerbosePreference Dictates the action taken when a Verbose message is delivered. WarningPreference Dictates the action taken when a Warning message is delivered. WhatIfPreference If true, WhatIf is considered to be enabled for all commands.

One of the variables you might find your self using is to check if the last cmdlet you invoked ran successfully or not, the exit state is saved in $? with a value of False if it failed and True if it was successful.

PS C:\Users\Carlos\Desktop> Get-nonexistingcmdlet

The term 'Get-nonexistingcmdlet' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path

is correct and try again.

At line:1 char:22

+ Get-nonexistingcmdlet <<<<

+ CategoryInfo : ObjectNotFound: (Get-nonexistingcmdlet:String) [], CommandNotFoundException

+ FullyQualifiedErrorId : CommandNotFoundException

PS C:\Users\Carlos\Desktop> $?

False

PS C:\Users\Carlos\Desktop> Get-Variable pshome

Name Value

---- -----

PSHOME C:\Windows\System32\WindowsPowerShell\v1.0

PS C:\Users\Carlos\Desktop> $?

True

If we are executing system executable the variable with the last exit code would be $lastexitcode returning the exit code for the error found when executing or 0 if it executed successfully.

PS C:\Users\Carlos\Desktop> wmic systemdrive

systemdrive - Alias not found.

PS C:\Users\Carlos\Desktop> $LASTEXITCODE

44135

PS C:\Users\Carlos\Desktop> hostname

infidel01

PS C:\Users\Carlos\Desktop> $LASTEXITCODE

0

Some of the automatic variables can be changed so as to customize the session, others are read only and others are modified by the session it self as it executes. Many of these variable will prove useful as you work with PowerShell so I invite you to read the help on automatic variables.

Conclusion

I only covered some of the main points of variables and how to work with them. I do invite you to read more about them in the internal documentation that Microsoft PowerShell provides using the Get-Help cmdlet:

  • about_Variables
  • about_Automatic_Variables
  • about_Environment_Variables
  • about_Preference_Variables
  • about_Scopes

As always I hope you find this blog post useful and informative.

Wednesday
Apr112012

Creating Test Accounts on a Windows 2008 R2 DC with PowerShell

Recently I had to rebuild my lab do to that I had cloned a bunch of VM’s and forgot to run sysprep on them. This caused problems do to link SID’s when I installed Exchange 2010 in my home lab so I decided to rebuild the whole AD and services in it. So I decided to share how I created 100 test accounts on an isolated part of my lab network.

After installing the Active Directory Service and making the changes to DNS so it would forward to the proper DNS and made sure I had a Reverse Lookup Zone I wanted to create 100 test domain accounts. I normally use cmd.exe with dsadd.exe command, but this time I wanted to do it using PowerShell and this is with what I came up with as a command:

  1: import-module activedirectory
  2: (1..100) | foreach {New-ADUser -SamAccountName "User$($_.tostring())" -Name "User$($_.tostring())" -DisplayName "User$($_.tostring())" -AccountPassword (ConvertTo-SecureString -AsPlainText "P@ssword$($_.tostring())" -Force) -Enabled $true -EmailAddress "user$($_.tostring())@acmelabs.com" }

The commands are broken as so:

  • On line 1 I import the Active Directory PowerShell Module on the DC. If you want to see the cmdlets available on this module you can run  Get-Command -Module activedirectory this will list all of the cmdlets available to us to manage Active Directory.
  • On line 1 I generated a range from 1 to 100 and piped it to the cmdlet ForEach-Object and gave I a code block to run the cmdlet New-ADUser. To get more info on this cmdlet I invite you to run Get-Help New-ADUser –Full this will give you the full help plus examples of the cmdlet. Since the default variable of each object processed by the pipe is $_ and in the case of a range what I’m getting are Int32 objects I need to use the method of .ToString() to convert them to string and I use $() inside a double quoted string to expand the variable. What I do for each user I created was:
    • Set a Name
    • Set a Display Name
    • Set SAM Account Name
    • Set the Password. Now the cmdlet requires a secure string as value for the parameter, for this I used the ConvertTo-SecureString cmdlet to generate one from a plaintext quoted string.
    • Enable the account and set an email address since I will be installing Exchange later in this environment.

I do hope you find this useful and informative as always.

Monday
Apr092012

Introduction to Microsoft PowerShell – Working with PSDrives and Items

PowerShell provides many ways to work with files and with other sorts of structured data it treats as files. Typically as shown before we can use the same commands as in cmd.exe but they parameters change also we can call many using he names of commands found in Unix type systems, these are aliases for PowerShell cmdlets so as to make the transition to PowerShell easier for administrators. Let have a look at the common commands used to manage files and their aliases. Do not worry to much on the manipulation commands used since I will cover those later in other blog posts but do take a look at what those aliases map to:

PS C:\> Get-Alias | where {$_.definition -match "path|item|content|location"} | Group-Object definition

Count Name                      Group
----- ----                      -----
    1 Add-Content               {ac}
    3 Get-Content               {cat, gc, type}
    3 Set-Location              {cd, chdir, sl}
    1 Clear-Content             {clc}
    1 Clear-Item                {cli}
    1 Clear-ItemProperty        {clp}
    3 Copy-Item                 {copy, cp, cpi}
    1 Copy-ItemProperty         {cpp}
    1 Convert-Path              {cvpa}
    6 Remove-Item               {del, erase, rd, ri...}
    3 Get-ChildItem             {dir, gci, ls}
    1 Get-Item                  {gi}
    2 Get-Location              {gl, pwd}
    1 Get-ItemProperty          {gp}
    1 Invoke-Item               {ii}
    3 Move-Item                 {mi, move, mv}
    1 Move-ItemProperty         {mp}
    1 New-Item                  {ni}
    1 Pop-Location              {popd}
    1 Push-Location             {pushd}
    2 Rename-Item               {ren, rni}
    1 Rename-ItemProperty       {rnp}
    1 Remove-ItemProperty       {rp}
    1 Resolve-Path              {rvpa}
    1 Set-Content               {sc}
    1 Set-Item                  {si}
    1 Set-ItemProperty          {sp}

As we can see in addition to the commands that we know from Unix type systems and those we use from cmd.exe we can find that PowerShell provides even more aliases for those cmdlets and for other actions we will discuss we will see that it has it’s own aliases and cmdlets.

PSDrives

Lets start with the concept that PowerShell treats files and folders as Items, the reason for this is that PowerShell treats other structure data as a file systems and calls the mappings to them PSDrives. To list the PSDrives on our current system we use the cmdlet Get-PSDive:

PS C:\> Get-PSDrive | ft -AutoSize

Name     Used (GB) Free (GB) Provider    Root               CurrentLocation
----     --------- --------- --------    ----               ---------------
Alias                        Alias
C            60.13    535.94 FileSystem  C:\
cert                         Certificate \
D           764.70    166.81 FileSystem  D:\
E           617.89    313.62 FileSystem  E:\
Env                          Environment
F                            FileSystem  F:\
Function                     Function
G                            FileSystem  G:\
H                            FileSystem  H:\
HKCU                         Registry    HKEY_CURRENT_USER
HKLM                         Registry    HKEY_LOCAL_MACHINE
I                            FileSystem  I:\
J                            FileSystem  J:\
Variable                     Variable
WSMan                        WSMan

As we can see in addition to the normal drives we have on the system we have others drives we can navigate to:

  • Alias – Represent all aliases valid for the current PowerShell Session.
  • Cert – Certificate store for the user represented in Current Location.
  • Env – All environment variables for the current PowerShell Session.
  • Function - All functions available for the current PowerShell Session.
  • HKLM - Registry HKey Local Machine Registry Hive.
  • HKCU - Registry HKey Current User Hive for the user the PowerShell session is running as.
  • WSMan - WinRM (Windows Remote Management) configuration and credentials.

Each of these PowerShell Drives are dependent on what is called PowerShell Providers that allow the access to the structured information. These can be listed with the Get-PSProvider cmndlet:

PS C:\> Get-PSProvider | ft -AutoSize

Name        Capabilities                Drives
----        ------------                ------
WSMan       Credentials                 {WSMan}
Alias       ShouldProcess               {Alias}
Environment ShouldProcess               {Env}
FileSystem  Filter, ShouldProcess       {C, D, E, F...}
Function    ShouldProcess               {Function}
Registry    ShouldProcess, Transactions {HKLM, HKCU}
Variable    ShouldProcess               {Variable}
Certificate ShouldProcess               {cert}

As we can see there are provider for other types other than FileSystem, this can me extended depending on PowerShell modules loaded and installed on a system for example on Windows 7 systems with the Remote Administration Tools or Windows 2008 R2 Domain Controller the can have access to an Active Directory provider, machines with the VMware PowerCLI installed will have access to providers for VMware Datastore and Virtual Infrastructures:

PowerCLI C:\> Get-PSProvider

Name                 Capabilities                  Drives
----                 ------------                  ------
WSMan                Credentials                   {WSMan}
Alias                ShouldProcess                 {Alias}
Environment          ShouldProcess                 {Env}
FileSystem           Filter, ShouldProcess         {C, A, D}
Function             ShouldProcess                 {Function}
Registry             ShouldProcess, Transactions   {HKLM, HKCU}
Variable             ShouldProcess                 {Variable}
Certificate          ShouldProcess                 {cert}
VimDatastore         ShouldProcess                 {vmstores, vmstore}
VimInventory         Filter                        {vis, vi}

Using one of this providers is quite simple, for it we use the New-PSDrive cmdlet, options for the cmdlet may change depending on the provider used so if using any external provide do look at the documentation provided by the company that made the provider. Each provider has different capabilities and this capabilities dictate what can be done on the data that is accessed, for example:

  • ShouldProcess - Cmdlets that support the -Confirm and -WhatIf parameter can be used against the PSDrive.
  • Credentials - Cmdlets that use the -Credential parameter can be used against the PSDrive
  • Transactions - Cmdlets can me executed in a transactional fashion and use the parameter -UseTransaction against the PSDrive.
  • Filter - Cmdlets can use wildcard filtering for enumerating objects using the -Filter parameter against the PSDrive.

Lets map a drive:

PS C:\Users\carlos> New-PSDrive -Name isostore -Root \\192.168.1.2\isostore -PSProvider filesystem

Name           Used (GB)     Free (GB) Provider      Root                      CurrentLocation
----           ---------     --------- --------      ----                      ---------------
isostore                               FileSystem    \\192.168.1.2\isostore

PS C:\Users\carlos> ls isostore:


    Directory: \\192.168.1.2\isostore


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
da---         1/26/2012  12:49 PM            Oracle
da---         3/27/2012   1:11 PM            Microsoft
da---         3/15/2012   7:34 PM            Linux
da---        12/30/2011   3:49 PM            FreeBSD
da---         3/15/2012   7:33 PM            Solaris
d----         12/2/2011  11:29 AM            unlock-all-v102
da---         3/15/2012   7:34 PM            VMWare
da---         2/27/2012   8:04 AM            Apple
-a---         2/24/2012   9:51 PM 3589316608 8250.0.WINMAIN_WIN8BETA.120217-1520_X64FRE_SERVER_EN-US-HB1_SSS_X64FRE_EN-
                                             US_DV5.ISO
-a---          1/4/2012   2:06 PM        403 shutdown_vms.rb
-a---         4/13/2011   3:17 AM  531705856 openfileresa-2.99.1-x86_64-disc1.iso
-a---         10/8/2007   4:06 PM  661127168 win2k3entsp2.iso
-a---        12/30/2011   7:32 PM  115838976 pfSense.iso
-a---          1/2/2012  11:16 PM  533204992 XenServer-6.0.0-install-cd.iso
-a---          1/4/2012   1:50 PM        177 shtdown.sh
-a---          5/4/2011   5:42 PM  369717248 VMware-VMvisor-Installer-4.0.0.Update01-208167.x86_64.iso

One thing that we need to keep in mind is that the drives we create are only present in the current PowerShell Session only and only can be accessed by the session so Windows Explorer and other tools on windows will not have access to the drive. Also as we can see in the example we can use a longer name for the drive than the letters we are used to use on Windows when mapping drives.

Working with Items

Listing Items

Lets look first at listing the contents of the current working folder for this we will use the Get-ChildItem cmdlet:

PS C:\> Get-ChildItem


    Directory: C:\


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----         7/13/2009  11:20 PM            PerfLogs
d-r--          4/5/2012  10:27 PM            Program Files
d-r--          4/8/2012   6:39 PM            Program Files (x86)
d----          4/5/2012   7:42 PM            Python27
d----          4/5/2012   7:41 PM            Python32
d----          4/5/2012   7:38 PM            Ruby193
d----          4/6/2012  12:27 PM            SysinternalsSuite
d-r--          4/5/2012  10:54 PM            Users
d----          4/8/2012  11:14 AM            Windows
-a---          4/5/2012  10:32 PM       1024 .rnd

As we can see we get a listing of the files and folders and basic information about them. Each item is in fact a .Net object of System.IO.FileInfo type that we can manipulate. Lets try searching in a given path for a file that matches a wild card, as we saw before when talink about PSProviders the FileSystem provider allows for filtering. Lets search for any file that starts with telnet in my install of Ruby 1.9.3:

PS C:\> Get-ChildItem -Path .\Ruby193 -Recurse -Filter telnet*


    Directory: C:\Ruby193\lib\ruby\1.9.1\net


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         5/18/2011   9:07 PM      32598 telnet.rb

Creating Files and Folders

Lets crate a directory and file for us to use to keep exploring the cmdlets, lets start by using the New-Item cmdlet to create a folder called testfolder:

PS C:\> New-Item -Path . -Name testfolder -ItemType "directory"


    Directory: C:\


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----          4/9/2012  11:45 AM            testfolder

As with all cmdlets I mention on the blog posts I do recommend that you look at full help of the command and look at the members of the objects returned as covered in the initial blogposts.

Now lets create a file, for this we will use the ItemType of "file" to indicate we want a file.

PS C:\> New-Item -Path .\testfolder -Name testfile -ItemType "file"


    Directory: C:\testfolder


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---          4/9/2012  11:53 AM          0 testfile

 

Working with Items

Now that we have a file we can work with lets look at the properties and methods available with the Get-Item cmdlet:

PS C:\> Get-Item -Path .\testfolder\testfile | Get-Member


   TypeName: System.IO.FileInfo

Name                      MemberType     Definition
----                      ----------     ----------
Mode                      CodeProperty   System.String Mode{get=Mode;}
AppendText                Method         System.IO.StreamWriter AppendText()
CopyTo                    Method         System.IO.FileInfo CopyTo(string destFileName), System.IO.FileInfo CopyTo(s...
Create                    Method         System.IO.FileStream Create()
CreateObjRef              Method         System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
CreateText                Method         System.IO.StreamWriter CreateText()
Decrypt                   Method         System.Void Decrypt()
Delete                    Method         System.Void Delete()
Encrypt                   Method         System.Void Encrypt()
Equals                    Method         bool Equals(System.Object obj)
GetAccessControl          Method         System.Security.AccessControl.FileSecurity GetAccessControl(), System.Secur...
GetHashCode               Method         int GetHashCode()
GetLifetimeService        Method         System.Object GetLifetimeService()
GetObjectData             Method         System.Void GetObjectData(System.Runtime.Serialization.SerializationInfo in...
GetType                   Method         type GetType()
InitializeLifetimeService Method         System.Object InitializeLifetimeService()
MoveTo                    Method         System.Void MoveTo(string destFileName)
Open                      Method         System.IO.FileStream Open(System.IO.FileMode mode), System.IO.FileStream Op...
OpenRead                  Method         System.IO.FileStream OpenRead()
OpenText                  Method         System.IO.StreamReader OpenText()
OpenWrite                 Method         System.IO.FileStream OpenWrite()
Refresh                   Method         System.Void Refresh()
Replace                   Method         System.IO.FileInfo Replace(string destinationFileName, string destinationBa...
SetAccessControl          Method         System.Void SetAccessControl(System.Security.AccessControl.FileSecurity fil...
ToString                  Method         string ToString()
PSChildName               NoteProperty   System.String PSChildName=testfile
PSDrive                   NoteProperty   System.Management.Automation.PSDriveInfo PSDrive=C
PSIsContainer             NoteProperty   System.Boolean PSIsContainer=False
PSParentPath              NoteProperty   System.String PSParentPath=Microsoft.PowerShell.Core\FileSystem::C:\testfolder
PSPath                    NoteProperty   System.String PSPath=Microsoft.PowerShell.Core\FileSystem::C:\testfolder\te...
PSProvider                NoteProperty   System.Management.Automation.ProviderInfo PSProvider=Microsoft.PowerShell.C...
Attributes                Property       System.IO.FileAttributes Attributes {get;set;}
CreationTime              Property       System.DateTime CreationTime {get;set;}
CreationTimeUtc           Property       System.DateTime CreationTimeUtc {get;set;}
Directory                 Property       System.IO.DirectoryInfo Directory {get;}
DirectoryName             Property       System.String DirectoryName {get;}
Exists                    Property       System.Boolean Exists {get;}
Extension                 Property       System.String Extension {get;}
FullName                  Property       System.String FullName {get;}
IsReadOnly                Property       System.Boolean IsReadOnly {get;set;}
LastAccessTime            Property       System.DateTime LastAccessTime {get;set;}
LastAccessTimeUtc         Property       System.DateTime LastAccessTimeUtc {get;set;}
LastWriteTime             Property       System.DateTime LastWriteTime {get;set;}
LastWriteTimeUtc          Property       System.DateTime LastWriteTimeUtc {get;set;}
Length                    Property       System.Int64 Length {get;}
Name                      Property       System.String Name {get;}
BaseName                  ScriptProperty System.Object BaseName {get=if ($this.Extension.Length -gt 0){$this.Name.Re...
VersionInfo               ScriptProperty System.Object VersionInfo {get=[System.Diagnostics.FileVersionInfo]::GetVer...

For getting properties for the file object we have several ways to achive this first one is using the Get-ItemProperty cmdlet by given as the name the object property:

PS C:\> Get-ItemProperty -Path .\testfolder\testfile -Name LastAccessTime

PSPath         : Microsoft.PowerShell.Core\FileSystem::C:\testfolder\testfile
PSParentPath   : Microsoft.PowerShell.Core\FileSystem::C:\testfolder
PSChildName    : testfile
PSDrive        : C
PSProvider     : Microsoft.PowerShell.Core\FileSystem
LastAccessTime : 4/9/2012 11:53:25 AM

Another Method we can use is to get the object and just request it, lets look at some properties that security professionals will find quite interesting:

PS C:\> (Get-Item -Path .\testfolder\testfile).LastWriteTime

Monday, April 09, 2012 11:53:25 AM


PS C:\> (Get-Item -Path .\testfolder\testfile).LastAccessTime

Monday, April 09, 2012 11:53:25 AM


PS C:\> (Get-Item -Path C:\Windows\System32\aaclient.dll).VersionInfo

ProductVersion   FileVersion      FileName
--------------   -----------      --------
6.1.7600.16385   6.1.7600.1638... C:\Windows\System32\aaclient.dll

Just like other shell we can redirect output of commands as text to files using > and >> symbols:

  • cmdlet > filename - Redirect command output to a file and overwrite content.
  • cmdlet >> filename - append into a file
  • cmdlet 2> filename - Redirect Errors from operation to a file and overwrite content.
  • cmdlet 2>> filename - Append errors to a file
  • cmdlet 2>&1 - Add errors to output
  • cmdlet 1>&2 - Add output to errors

Lets look also at the Add-Content cmdlet:

PS C:\> Add-Content -Path C:\testfolder\testfile -Value (get-date)
PS C:\> Get-Content -Path C:\testfolder\testfile
4/9/2012 3:39:29 PM

Lets work with the object method to modify the file, in this case we will use EFS to encrypt the file on NTFS, lets start with checking if the file is encrypted:

PS C:\> (Get-Item -Path .\testfolder\testfile).attributes
Archive

Now lets encrypt the file and see if its encrypted:

PS C:\> (Get-Item -Path .\testfolder\testfile).encrypt()
PS C:\> (Get-Item -Path .\testfolder\testfile).attributes
Archive, Encrypted

We can even confirm using the cipher.exe command:

PS C:\> cipher.exe /c .\testfolder\testfile

 Listing C:\testfolder\
 New files added to this directory will not be encrypted.

E testfile
  Compatibility Level:
    Windows XP/Server 2003

  Users who can decrypt:
    infidel01\Carlos [Carlos(Carlos@infidel01)]
    Certificate thumbprint: 45F5 3D35 94B0 3C47 B727 AB63 0198 F19A 2793 1283

  No recovery certificate found.

  Key Information:
    Algorithm: AES
    Key Length: 256
    Key Entropy: 256

Lets Rename an item with the Rename-Item cmdlet:

PS C:\> Rename-Item -Path C:\testfolder -NewName test_folder
PS C:\> ls


    Directory: C:\


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----         7/13/2009  11:20 PM            PerfLogs
d-r--          4/5/2012  10:27 PM            Program Files
d-r--          4/8/2012   6:39 PM            Program Files (x86)
d----          4/5/2012   7:42 PM            Python27
d----          4/5/2012   7:41 PM            Python32
d----          4/5/2012   7:38 PM            Ruby193
d----          4/6/2012  12:27 PM            SysinternalsSuite
d----          4/9/2012   4:44 PM            test_folder
d-r--          4/5/2012  10:54 PM            Users
d----          4/8/2012  11:14 AM            Windows
-a---          4/5/2012  10:32 PM       1024 .rnd

 

Lets delete the file we have been using for the examples:

PS C:\> Remove-Item -Path C:\test_folder\testfil
PS C:\> ls .\test_folder


    Directory: C:\test_folder


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---          4/9/2012   3:39 PM         21 testfile


PS C:\>  Remove-Item -Path C:\test_folder\testfile
PS C:\> ls .\test_folder

Working with Paths

Lets look at working with paths, we will firs start with defining the difference of Path and LiteralPath in the parameters of several commands. This is a source of confusion for many people learning PowerShell on their own by exploring the shell cmdlets. When working with a file system on a drive or share Powershell Windows restricts the characters that can be used for a file name, like *, ?, /, $ and others since they are use for variable expansion and wildcard search but since PowerShell lets us work with Active Directory, Certificate Store, Registry and others that do not have the same restrictions as the file system. This is why we use -Path when we want the special characters treated as wildcards and -LiteralPath for those cases where those special characters are part of the item names. An example of expansion:

PS C:\> Set-Location -Path Perf*
PS C:\PerfLogs>

We can see as wildcards where used to match the path. To get the current location of where we are in a provider we use the Get-Location cmdlet:

PS C:\PerfLogs> Get-Location

Path
----
C:\PerfLogs

To Change locations we use the Set-Location cmdlet:

PS C:\PerfLogs> Set-Location C:\testfolder
PS C:\testfolder> Get-Location

Path
----
C:\testfolder

We can take a path and add a child item to the path with Join-Path cmdlet:

PS C:\> Join-Path -Path C:\Windows -ChildPath system
C:\Windows\system

We can also have it join a path using wildcards:

PS C:\> Join-Path -Path C:\Win* -ChildPath tem* -Resolve
C:\Windows\Temp

We can also give it a list of path to append a child object to:

PS C:\> join-path -path c:\windows,c:\python,c:\ruby  -ChildPath temp
c:\windows\temp
c:\python\temp
c:\ruby\temp

Some time we will find our self with path that we obtained from a property of an object and we may need to extract parts of the path, for this we will use the Split-Path cmdlet and we can get different pats of the paths depending of what we want:

PS C:\> split-path c:\windows\secret.txt
c:\windows
PS C:\> split-path c:\windows\secret.txt -Qualifier
c:
PS C:\> split-path c:\windows\secret.txt -NoQualifier
\windows\secret.txt
PS C:\> split-path c:\windows\secret.txt -Parent
c:\windows
PS C:\> split-path c:\windows\secret.txt -Leaf
secret.txt

It also supports extracting parts from other types of paths:

PS C:\> Split-Path -Path /var/log/tftp.log -Leaf
tftp.log
PS C:\> Split-Path -Path /var/log/tftp.log -Parent
\var\log
PS C:\> split-path -Path http://www.darkoperator.com/index.html -Qualifier
http:
PS C:\> split-path -Path http://www.darkoperator.com/index.html -NoQualifier
//www.darkoperator.com/index.html

We can test if a path exists:

PS C:\> test-path -path HKLM:\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell
True
PS C:\> test-path -path C:\Windows
True
PS C:\> test-path -path C:\Windows\system32\aaclient.dll
True

As we can see this works with both files, folders and even other paths in other providers. Lets say we want to test is the path is for a File or a Folder, for this we will use Container for Folder and Leaf for File:

PS C:\> test-path -path C:\Windows\system32\aaclient.dll -PathType leaf
True
PS C:\> test-path -path C:\Windows\system32\aaclient.dll -PathType container
False

Conclusion

I invite you to keep exploring in the registry, variables and other psdrives available and learning what is possible and not and the differences in the parameters we can use with this providers. As always I hope this blog post is useful and informative.

Page 1 ... 6 7 8 9 10 ... 32 Next 5 Entries »