Sunday, November 27, 2016

Powershell Scripting: check Exchange mail queues...



This is a guest post my Mr. Troy Collins

This script checks the Mail Queues and if they are too big it will auto e-mail.

When mail queues get big mail flow may stop working.. ​ This script can be very helpful and should be added to Schedule task to run every 15 minutes.

<#  
This script will test Exchange mail queues and e-mail if amount of message are too many.
Writen by Troy Collin
#>


$server = hostname

#$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$server/powershell/  -Authentication Kerberos
#Import-PSSession $Session
add-pssnapin Microsoft.Exchange.Management.PowerShell.SnapIn
Write-host "Exchange Snapin now eanbled."

$total_messages = get-transportserver| get-queue |  foreach -begin {$total=0} -process {$total+=$_.messageCount} -end {$total}
if ($total_messages -gt 200)
{
write-host "messages are high"
$total_messages
$message = "`n*******Automated E-mail DO NOT REPLY******`n
Exchange Message Queues test. `n

`n`nAlert Check message queue!!
current total is $total_messages`n `n
Thank you" 



$emailFrom = "Mail Queue problem! <Sender@sender.com>"
$smtpServer = "SMTPServer"
#$emailTo = "to@to.com"
$emailSubject    = "Mail Queue Status script"
$file = "$Filename"

######### End of Send email variables ###############

$mailMessageParameters = @{
From       = $emailFrom
To         = $emailTo
Subject    = $emailSubject
SmtpServer = $smtpServer
Body       = $message
# Attachment = $REPORT

}

Send-MailMessage @mailMessageParameters

} else {
Write-host "messages are not high"
$total_messages
}





Wednesday, November 23, 2016

PowerShell: ADD a local Administrator account to all windows servers from a list.

This is a guest post Mr. Troy Collins

<#  
This script will create a local user account on a remote system and added it to the Administrators group..
Writen by Troy Collin
#>

#################################
$pingerror = ".\nopingable.txt"
$already = ".\already.exists.txt"
$error = ".\error.txt"
$created = ".\created.txt"
$computers = Get-Content serverslist.txt
$Username = 'natadm'
$Password = Read-Host -Prompt "Enter password for $Username" -AsSecureString
##################################

########### Creating Report Directory #############
$FileExists = Test-Path "./Reporting"
If ($FileExists -eq $True) {
Write-Host "Reporting Directory already here moving on.. " -ForegroundColor Green
} else {
if ($FileExists -eq $false) {
Write-Host "Making Directory Called Reporting.." -ForegroundColor Red
New-Item ./reporting -Type directory
}
}
############ end of Reporting #####################

foreach ($computer in $computers) 
{


if (test-Connection -ComputerName $computer -Count 2 -Quiet ) { 
write-Host "$computer is alive and Pinging " -ForegroundColor Green
 Try { 
$checkuser = [adsi]::Exists("WinNT://$computer/$Username")
if($checkuser -NotContains $Username)
{
Write-host "creating user account and settting password on $computer"
$ADSIComp = [adsi]"WinNT://$computer" 
$NewUser = $ADSIComp.Create('User',$Username) 
#Create password 
$BSTR = [system.runtime.interopservices.marshal]::SecureStringToBSTR($Password)
$_password = [system.runtime.interopservices.marshal]::PtrToStringAuto($BSTR)
#Set password on account 
$NewUser.SetPassword(($_password))
$NewUser.SetInfo()
Write-host "Adding new Account to Local Adminitrators on $computer" 
$AdminGroup = [ADSI]"WinNT://$computer/Administrators,group"
$User = [ADSI]"WinNT://$computer/$UserName,user"
$AdminGroup.Add($User.Path)
write-Host "Account created on $computer" -foregroundcolor Green  
$computer | out-file ./reporting/$created -Append
}
else
{
      write-host "User $($username) already exists" 
$computer | out-file ./reporting/$already -Append
}
  
}
 Catch {

$computer | Out-File ./reporting/$error -Append

 }
} else
{ Write-Host "$computer does not respond adding to error.txt" -BackgroundColor White -ForegroundColor Red
  $computer | Out-File ./reporting/$pingerror -Append
}
}​




Friday, November 11, 2016

Beginning Memory Forensics - Rekall - Stuxnet

Before moving forward, I would like to shout out MichaelHale Ligh for his analysis of Stuxnet using volatility. This post was basically me trying to learn more about Rekall while trying to retrace Mike's step using Rekall to understand Stuxnet rather than reusing volatility. To get a better understanding of this post you should probably either review Mike's post first or have it opened while you go through this one.

I've done a few posts on using various tools for memory forensics. For example, in this post I used volatility, while in this post I used Mandiant's memorize. In this post we will now look at Rekall and will use a memory sample from  jonrajewski.com. The objective here is to learn a bit about Rekall and in doing so let's try to uncover some of the artifacts that Michael Hale Ligh found in his analysis of Stuxnet. Note, we are not trying to find all but hoping to learn how to use Rekall for the basics.

First let's install Rekall on Kali

Following the guidelines from the Rekall manual, let's first install "virtualenv"
"apt-get install virtualenv"



Now that "virtualenv" is installed, let's continue with the install

"virtualenv /tmp/MyEnv"
Install the "rekall-gui"
Note: If during the installation you get an error relating to “ldcurses” look at the reference section for a possible solution.

Now that we have Rekall properly installed, the first thing you may want to do is look at the help.
Simply type "rekall -h"
Rekall Modes
Rekall has an interactive mode, a non interactive mode and a web console. By providing a plugin to the command, we would use the non-interactive mode. So if you wish to use the interactive mode, only execute the "rekall" command with the file you would like to analyze.

Let's look at this in practice.
Non-interactive mode:
(rekal) root@securitynik:~/mem_forensics# rekall --filename stuxnet.vmem pslist

That's it! Just run the "rekall" command with the filename and a plugin. In the above example we use the "imageinfo" plugin to learn a little bit more about the acquired image. As a result, we were able to learn that this device image is from a Windows XP system. We can also tell this system seems to have been up for about 16 hrs (56949 seconds)

Interactive mode
Let's spend the rest of the time looking at this tool in interactive mode.
To get there all we need is
(rekal) root@securitynik:~/mem_forensics# rekall --filename stuxnet.vmem
 
Note above there is no plugin. This drops us into the interactive shell from which we can now work out of.

Let's first take a look at the processes which are running.
[1] stuxnet.vmem 22:56:55> pslist
According to Mike, we should be seeing one "lsass.exe" which has a parent of "Winlogon.exe". However, as shown above and as stated by Mike, we have three "lsass.exe" processes. One has a parent of "Winlogon.exe" and the other two have a parent of "services.exe". This means now that we should take a closer look at these 3 processes.
[1] stuxnet.vmem 22:55:58> tokens proc_regex=("lsass.exe")


From the above image, we see that the 3 "lsass.exe" processes basically have the same SIDS.

Let's move on!
Let's identify the priorities of the 3 "lsass.exe" processes. To determine this, let's run "[1] stuxnet.vmem 23:00:40> SELECT _EPROCESS.name, _EPROCESS.pid,_EPROCESS.Pcb.BasePriority FROM pslist(
                      ...: ) WHERE regex_search("lsass.exe",_EPROCESS.name)"

From above we see that the two suspicious entries have a base priority of 8 while the one we assume is legit has a higher priority of 9.
  
Continuing to learn about the processes, let's look at the DLLs they are using.
[1] stuxnet.vmem 19:05:16> dlllist [680,868,1928]
From above, we see the "lsass.exe" (PID 680) having a large number of DLLs. Note this image only represents a portion of the DLLs associated with this PID.

However, if we look at the two processes of concern PID 868 and PID 1928 we see a fewer amount with PID 868 having the fewest DLLs.


Image of PID 1928 has been truncated. However, the number of DLLs, is still less than that of PID 680.
Something interesting to note about these two PIDs also is that in both of the "Command Line" arguments, it seems the backlash (\) is being escaped (\\). This definitely differs from the legitimate entry with PID 680.

Taking a look at the handles associated with the 3 PIDs using:
[1] stuxnet.vmem 19:50:33> handles [680,868,1928]


When a look is taken at the handles, we see that PID 680 has a signiicant amount of handles while 868 and 1928 does not have as much. Note the output has been sniped.

Let's now run "malfind" against these PIDs to see if anything suspicious shows up.
[1] stuxnet.vmem 20:13:01> malfind [680,868,1928]


 
When the command was run, no results were returned for PID 680 (the process we believe to be legitimate). The same was not true for PIDs 868 and PID 1928

As we can see there seems to be an executable "MZ Signature" starting at offset 0x80000 for both of these PIDs.

Let's use the "ldrmodules" plugin to gain a bit more insight into the “lsass.exe” process with PID 1928.
[1] stuxnet.vmem 23:46:06> ldrmodules 1928               

A quick glance at the image above immediately suggest something may be wrong and worthy of investigations. Other than the obvious "red" colour, there are no path information in for these 3 entries. Also notice that the offset matches those which we identified above using the “malfind” plugin. This would suggest the dll is probably hidden as it may be unlinked from one or more lists within the Process Environment Block (PEB).       

We see the same thing for the process with PID 868
[1] stuxnet.vmem 09:35:07>ldrmodules 868


stepping back and running the dlllist command again
"[1] stuxnet.vmem 17:10:56> dlllist 1928"
We see the following:

Taking a dump of the 3 "lsass.exe" processes, we see:
[1] stuxnet.vmem 17:17:29> procdump [680,868,1928], dump_dir="./out"
 
Running "strings" and "grep" against the files which were created to look for the functions Mike mentioned we see the following:
root@securitynik:~/mem_forensics/out# strings --print-file-name --data --encoding=s executable.lsass.exe*  | grep --perl-regexp "ZwMapViewOfSection|ZwCreateSection|ZwOpenFile|ZwClose|ZwQueryAttributesFile|ZwQuerySection"


As we can see above, the strings "ZwMapViewOfSection, ZwCreateSection, ZwOpenFile, ZwClose, ZwQueryAttributesFile, ZwQuerySection" are not in the legit lsass (PID 680) but are in the other two. This can be seen from the image above.

Let's verify that "ZWClose" is at "0x7c90cfd0". To do that let's perform a "dump" of that memory location.
[1] stuxnet.vmem 22:12:31> dump 0x7c90cfd0

So we see that "ZWClose" is at that memory location. Let's switch context into PID 668 and disassemble the memory location.

Switching context to PID 668
[1] stuxnet.vmem 22:04:52> cc 668

Let's disassemble the memory location.
[1] stuxnet.vmem 22:20:29> dis 0x7c90cfd0
 
Moving along, disassemble 0x7c900050
[1] stuxnet.vmem 22:26:10> dis 0x7c900050
 
... and still moving along looking at the call "0x7c900066"
[1] stuxnet.vmem 22:35:11> dis 0x7c900066, length=1

... and yet another disassembly at "0x009400F2"

....

Filtering for object types "Mutant" in PID 668, we see the following:
[1] stuxnet.vmem 23:04:33> handles 668, object_types="Mutant"


Peeking into the registry to look for the MrxNet registry key
[1] stuxnet.vmem 23:24:33> printkey 'ControlSet001\Services\MrxNet'

And now for the MrxCls key
[1] stuxnet.vmem 23:27:08> printkey 'ControlSet001\Services\MrxCls'
 
Let's take one more run at the artifacts by looking at the loaded modules.
[1] stuxnet.vmem 23:39:35> modules                        



Ok then, if the objective was to learn to use Rekall for memory forensics, I think we have achieved that to some extent. Once again, thanks to Mike for his post on analyzing stuxnet using volatility.

              

Monday, November 7, 2016

Ways to secure your password within your PowerShell scripts

This is a guest post  Mr. Troy Collins

Resonantly I had a problem given to me by a colleague at work.


Overview of the problem:
The Citrix team has some Powershell scripts running to gather Citrix information 2 times a day via schedule task within Windows. A security issue occurred with the SMTP relay server that he was using for sending out the reports and the team that managed it forced all users to authenticate via user/pass and a mailbox to send messages.  

The problem:
The script has to run as one account that has access to the Citrix environment and the account they gave to send out the messages was different.  So who do we run the scheduled task as? The Citrix account to gather the data or send with another account and secure the password?

Solution:
I created 2 scripts one to create the secure password that you use only once and the other was updated version of the original.

Create the password hash:

#here we ask for the users input.  -AsSecureString hides the password on the screen

$pass = Read-Host "Enter Password" -AsSecureString
#Next we convert the pass and export the hash string to text file.  ( I found it easyer to copy/paste from the text file insted of the screen) 
"$pass" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | out-file ./passwd.txt
#opens the text file for you to copy the hash
invoke-item ./passwd.txt
# this part is just to delete the file to leave nothing behind.
 Write-host "would you like to delete the password file?" -ForegroundColor Yellow 
    $Readhost = Read-Host " ( y / n ) " 
    Switch ($ReadHost) 
     { 
       Y {
remove-item ./passwd.txt -force -confirm:$false

       N {Write-Host "Your Done..."} 
}

Now we take the hash we created and added it to whatever script we need to have authentication with. 

This example we are using the username / password to authenticate to e-mail server to send a message but you could use this for any command or script that can use the -Credential string.  

$username = "domain\username"
$pass = "01000000d08c9ddf0---HASH----00c04fc297eb0100000000425808144"
$passwd = ConvertTo-SecureString -String $pass
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $passwd

send-MailMessage -smtpServer smtp.someserver.com

 -Credential $cred -from 'user@somedomain.com' -to 'someone@domain.com -subject
 'Test' -attachment test.txt -body $message​

After thought:
Although this is more secure than just putting the password in the script it's not impossible to get the password, so NTFS permissions from the O/S should also be used to this script file itself. 

Enjoy

Tuesday, November 1, 2016

On recruiting and retaining talented Cyber Security professionals

I recently read the Center for Strategic (CSIS) International Studies report on Recruiting and Retaining Cyber security Ninjas and have to agree, that in this industry where cyber security professionals are in high demand, we need to find creative ways of not just recruiting but definitely retaining. It also definitely confirmed my view that money is not all when it comes to retaining talented personnel. Things such as having a challenging workplace and definitely training to keep our skillset relevant are absolutely more important.

What I did find surprising was that talented cyber security professionals don't want to have to assume management responsibilities to advance in their careers. This is understandable, as even I was not sure if I wanted to go the management route when it was proposed. However, I've embraced it and have no regrets. This is something though organizations will have to continue looking at. Maybe there will be a need to create more technical paths that runs parallel to the management path. 

Most importantly and as the report stated, most of us prefer to have a flexible work environment. I believe this becomes even more relevant when a family has to be considered. That flexibility, be it the ability to work from home or work alternate hours, etc is way more important than money.

The biggest takeaway though is that as stated "... even in organizations that pays and treat their employees well, there can be a great deal of disappointment and early turnover." This is further emphasized by "No matter how good a job may be, there are many other employers willing to pay more and promise greater responsibility ...". This definitely should come as no surprise as talented cyber security professionals are truly in great demand. I'm a witness to that on both sides of the fence. On one side being, recruited and the other watching my team members being recruited.