Tag Archives: powershell

Windows PowerShell vs. CMD: What’s The Difference?

powershell vs cmd hero

Back in the day, booting the then-cutting-edge IBM 8086 from the floppy brought you to a green text screen with a cursor blinking at the familiar C:\> prompt. Hacking boot.ini and config.sys to get my games to run was my first introduction to programming.

Eventually that C:\> got replaced with a pretty GUI and boot from hard disk. That command prompt (CMD) still lived on for decades. Only recently did CMD get an upgrade, or replacement, with PowerShell, the shell application Microsoft introduced with Windows 7.

CMD served us well for a good long time, but PowerShell is like going straight from steam engines to autonomous battery powered cars.

Windows Command Prompt

Windows Command Prompt – also known as CMD – is the original shell for the Microsoft DOS operating system. CMD was the default shell until Windows 10 build 14791 when Microsoft made PowerShell the default option. CMD is one of the last remnants of the original MS-DOS operating system that Microsoft replaced

Windows PowerShell

powershell cmdlets positives

Windows PowerShell is the new Microsoft shell that combines the old CMD functionality with a new scripting/cmdlet instruction set with built-in system administration functionality. PowerShell cmdlets allow users and administrators to automate complicated tasks with reusable scripts. System administrators save significant time by automating administration tasks with PowerShell.

PowerShell vs. CMD

PowerShell vs. CMD is like comparing apples to kumquats. They are completely different, despite the illusion that the ‘dir’ command works the same way in both interfaces.

PowerShell uses cmdlets, which are self-contained programming objects that expose the underlying administration options inside of Windows. Before PowerShell, sysadmins navigated the GUI to find these options, and there was no way to reuse the workflow of clicking through the menus to change options on a large scale.

PowerShell uses pipes to chain together cmdlets and share input/output data the same way as other shells, like bash in linux. Pipes allow users to create complex scripts that pass parameters and data from one cmdlet to another. Users can create reusable scripts to automate or make mass changes with variable data – a list of servers, for example.

One of the (many) neat functions of PowerShell is the ability to create aliases for different cmdlets. Aliases allow a user to configure their own names for different cmdlets or scripts, which makes it more straightforward for a user to switch back and forth between different shells: ‘ls’ is a linux bash command that displays directory objects, like the ‘dir’ command. In PowerShell, both ‘ls’ and ‘dir’ are an alias for the cmdlet ‘Get-ChildItem.’

what powershell uses

When to Use PowerShell

For systems administrators and other IT functions, PowerShell is the way to go. There isn’t any command left in CMD that isn’t in PowerShell, and PowerShell includes cmdlets for any administration function you could need. Third-party software vendors are extending PowerShell with custom cmdlets, like the NetApp PowerShell Toolkit that manages Data ONTAP.

PowerShell knowledge can be a differentiator for employment or even a job requirement, so it’s a worthwhile skill to invest in.

To get started on your PowerShell journey, check out this tutorial for the basics – and learn how to automate Active Directory tasks with our free PowerShell course by Adam Bertram, a Microsoft PowerShell MVP (pro-tip: use the code ‘blog’).

Adventures in Fileless Malware, Part III: Obfuscated VBA Scripts for Fun an...

Adventures in Fileless Malware, Part III: Obfuscated VBA Scripts for Fun and Profit

After yakking in the last two posts about malware-free or fileless attack techniques, we’re ready to handle a dangerous specimen. The Hybrid Analysis site is the resource I rely on to find these malware critters. While the information that HA provides for each sample —system calls, internet traffic, etc. — should be enough to satisfy a typical IT security pro, there is some value in diving into one of these heavily obfuscated samples to see what’s actually going on.

If you’re playing along at home, I suggest doing this in a sandbox, such as AWS, or if you’re working on your own laptop, just make sure to comment out the system calls that launch PowerShell.

Into the Obfuscated VBA Muck

The malware I eventually found in Hybrid Analysis is a VBA script that was embedded in a Word doc. As I mentioned last time, to see the actual script, you’ll need Frank Boldewin’s OfficeMalScanner.

After extracting the script, which I gave you a peek at in the last post, I decided to load the thing into the MS Word macro library. And then — gasp  —  stepped through it using the built-in debugger.

My goal was to better understand the obfuscations: to play forensic analyst and experience the frustrations involved in this job.

If you’re going into one of these obfuscated scripts for the first time in a debugger, you’ll likely be gulping espressos as you make your way through the mind numbing complex code and watch blankly as you look at the variable L_JEK being assigned the string “77767E6C797A6F6”.

It’s that much fun.

What I learned with this obfuscated VBA script is that only a very small part of it does any of the real work. Most of the rest is there to throw you off trail.

Since we’re getting into the nitty-gritty, I took a screen shot of the teeny part of the code that performs the true evil work of setting up the PowerShell command line that is ultimately launched by the VBA macro.

Tricky: just take the hex value and subtract 7 for the real ascii.

It’s very simple. The VBA code maintains a hex representation of the command line in a few variables and then translates it to a character string. The only “tricky” part is that hex values have been offset by 7.

So for example, the first part of the hex string comes from L_JEK (above). If you take 77 and subtract 7, you’ll get a hex 70. Do the same for 76 and you have obtain hex 6F. Look these up in any ascii table, and you’ll see it maps to the first two letter of “powershell”.

This ain’t a very clever obfuscation, but it doesn’t have to be!

All it has to accomplish is getting past virus scanners searching for obvious keywords or their ascii representations.  And this particular sample does this well enough.

Finally, after the code builds the command line, it then launches it through the CreateProcess function (below).

Either comment out system calls or set a breakpoint before it.

Think about it. A Word doc was sent in a phish mail to an employee. When the doc is opened, this VBA script  automatically launches a PowerShell session to start the next phase of the attack. No binaries involved, and the heavily obfuscated scripts will evade scanners.

Evil!

To further my own education, I pulled out another macro from Hybrid Analytics (below) just to see what else is out there. This second one effectively does the same thing as the code above.

Secret code embedded in VBA.

It’s a little more clever in how it builds the command line. There’s a decode function, called “d”, that filters out characters from a base string by comparing against a secondary string.

It’s a high-school level idea, but it gets the job done: it will evade scanners and fool IT folks who are quickly looking at any logs for unusual activities.

Next Stop

In my first series of post on obfuscation, I showed that Windows Event logging captures enough details of PowerShell sessions — that is, if you enable the appropriate modules — to do a deep analysis after the fact.

Of course, the brilliance of fileless attacks is that it’s hard to determine whether a PowerShell script at run-time is doing anything evil through a basic parsing of the command line by scanning event logs.

Why?

PowerShell sessions are being launched all the time, and one hacker’s PowerShell poison can be close to another IT admin’s PowerShell power tool. So if you want to alert every time a script downloads something from the Internet, you’ll be sending out too many false positives.

Of course, this leads to this blog’s favorite topic: the failure of perimeter defenses to stop phishing and FUD malware, and the power of User Behavior Analytics.

In short: it’s a losing battle trying to stop hackers from getting past perimeter defenses. The better strategy is to spot unusual file access and application behaviors, and then respond by de-activating accounts or taking another breach response measure.

That’s enough preaching for the day. In the next post, we’ll take a closer look at more advanced types of fileless attacks.

Continue reading the next post in "Fileless Malware"

Adventures in Fileless Malware, Part I

Adventures in Fileless Malware, Part I

When I first started looking into the topic of hackers living off the land by using available tools and software on the victim’s computer, little did I suspect that it would become a major attack trend. It’s now the subject of scary tech headlines, and security pros are saying it’s on the rise. It seems like a good time for a multi-part IOS blog series on this subject.

Known also as fileless or zero-footprint attacks, malware-free hacking typically uses PowerShell on Windows systems to stealthily run commands to search and exfiltrate valuable content. To IT security team monitoring for hacker activities, file-less attack are very difficult to spot, often evading virus scanners and other signature-based detection systems.

In short, legacy defense can’t really deal with this style of attack. Of course there is, ahem, security software that will spot the malware activity on file systems.

Anyway, I’ve written about  some of these ideas before in my PowerShell obfuscation series, but more from a theoretical view. Then I discovered the Hybrid Analysis site, where you can find uploaded samples of malware captured in the wild.

Wild PowerShell

I thought it would be a great place to look for some file-less malware specimens. I wasn’t disappointed. By the way, if you want to go on your own malware hunting expedition, you’ll have to be vetted by the Hybrid Analysis folks so they know you’re doing white hat work. As a blogger who writes about security, I passed with flying colors. I’m sure you will too.

Besides having samples, they also provide great insights into what the malware is doing. Hybrid Analysis runs the submitted malware in their own sandbox, and monitors for system calls, processes launched, and Internet activity, as well as pulling out suspicious text strings.

For binaries and other executables in particular, where you can’t even look at the actual high-level code, this container technique allows HA to decide whether the malware is evil or merely suspicious based on its run-time activity. And then they’ll rate the sample.

For the malware-free PowerShell and other scripting samples (Visual Basic, JavaScript, etc.) I was looking for, I could see the actual code. For example, I came across this PowerShell creature:

You too can run base64 encoded PowerShell to evade detection. Note the use of the Noninteractive parameter in this live sample from Hybrid Analysis.

If you’ve read my obfuscation posts, you’ll know that the -e parameter indicates that what follows is base64 encoded. By the way Hybrid Analysis helpfully provides the decoded PowerShell as well. If you want to try decoding base64 PS on your own, you can run this command to do the work: $DecodedText = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($EncodedText))

Getting in Deeper

I decoded the script using this technique, and you can see the resulting plaintext PowerShell malware below.

Note the time sensitivity of this PS malware, and the use of cookies to pass back more information. I modified this real-world sample in my own testing.

I was feeling a little nervous handling this live malware on my own laptop. Attention Varonis IT Security: please note that I worked with an on-line PowerShell console and also my own separate AWS environment. Got that, IT?

Anyway, we’ve seen this particular attack style before —  in the PS obfuscation series — wherein the base64 encoded PS is itself pulling more of the malware from another site, creating a .Net Framework WebClient object to do the heavy lifting.

Why this approach?

For security software that’s scanning the Windows event log, the base64 encoding prevents text-based pattern matching from doing some easy detection – matching on say the string “WebClient”. And since the real evil part of the malware is then downloaded and injected into the PS app itself, this approach completely evades detection. Or so I thought.

It turns out with more advanced Windows PowerShell logging enabled – see my post — you can effectively see the downloaded string in the event log. I commend Microsoft (as did others!) for this added level of logging.

However, hackers then responded by base64 encoding the downloaded PowerShell from the remote site, so it would then show up in the Windows event log like the encoded sample above. Makes sense, right?

Adding More Scripting Sauce

The real-world samples in Hybrid Analysis then take this idea a step further. Hackers cleverly hide this PowerShell attack in Microsoft Office macros written in Visual Basic and in other scripts. The idea is that the victim receives a phish mail from say, FedEx, with a Word doc described as an invoice. She then clicks on the doc that then launches a macro that then eventually launches the actual PowerShell.

Often times, the Visual Basic script itself is obfuscated so that it evades virus and malware scanners.

Yes, it’s complicated and evil. And I’m only doing a very shallow dive.

In the spirit of the above, I decided as a training exercise to encase the above PowerShell within some obfuscated JavaScript. You can see the results of my hacking handiwork:

Obfuscated JavaScript hiding the encoded PowerShell. Real hackers, of course, do this better than me.

There is one technique I borrowed from “in the wild” samples: the use of  Wscript.Shell to launch the actual encoded PowerShell. It’s the way you get out of the script environment to interact with the rest of the system.

By the way, JavaScript is on its own a vehicle for delivering malware. Many Windows environment have by default the Windows Script Host, which will directly run JS.  In this scenario, the encasing JS malware is attached as a file with a .doc.js suffix.  Windows will only show the first suffix, so it will appear to the victim as a Word doc.  The JS icon is rendered as a scroll-like graphic. Not surprisingly, people will click on this attachment thinking it’s a document.

Don’t click on that JS icon that resembles a scroll! It will download evil malware. You’ve been warned.

For my own encasing JavaScript malware, I modified the PowerShell sample above to download a script from a web site I control. The remote PS script merely prints out “Evil Malware”.

Not very evil.

Of course, real hackers are interested in gaining access to a laptop or server, say, through a shell..

In the next post, I’ll show how to do this by using PowerShell Empire, which I wrote about once upon a time.

We probably dove a little too deep for an introductory post, so I’ll let you catch your breath and cover some of this again next time. And then we can start grokking real-world malware-free attacks with the preliminaries out of the way.

 

Continue reading the next post in "Fileless Malware"

Our Most Underappreciated Blog Posts of 2017

Our Most Underappreciated Blog Posts of 2017

Another year, another 1293 data breaches involving over 174 million records. According to our friends at the Identity Theft Resource Center, 2017 has made history by breaking 2016’s record breaking 1091 breaches. Obviously it’s been a year that many who directly defend corporate and government systems will want to forget.

Before we completely wipe 2017 from our memory banks, I decided to take one last look at the previous 12 months worth of IOS posts.  While there are more than a few posts that did not receive the traffic we had hoped, they nevertheless contained some really valuable security ideas and practical advice.

In no particular order, here are my favorite underachieving posts of the 2017 blogging year.

Interviews

Wade Baker Speaks – We did a lot of interviews with security pros this year —researchers, front-line IT warriors, CDOs, privacy attorneys.  But I was most excited by our chat with Wade Baker. The name may not be familiar, but for years Baker produced the Verizon DBIR, this blog’s favorite source of breach stats. In this transcript, Wade shares great data-driven insights into the threat environment, data breach costs, and how to convince executives to invest in more data security.

Ann Cavoukian and GDPR – It’s hard to believe that the General Data Protection Regulation (GDPR) is only a few months away. You can draw a line from Cavoukian’s Privacy by Design ideas to the GDPR.  For companies doing business in the EU, it will soon be the case that PbD will effectively be the law. Read the Cavoukian transcript to get more inspired.

Diversity and Data Security – The more I learn about data security and privacy, the more I’m convinced that it will “take a village”.  The threat is too complex for it to be pigeon-holed into an engineering problem. A real-world approach will involve multiple disciplines — psychology, sociology, law, design, red-team thinking, along with computer smarts. In this interview with Allison Avery, Senior Organizational Development & Diversity Excellence Specialist at NYU Langone Medical Center, we learn that you shouldn’t have preconceived notions of who has the right cyber talents.

Infosec Education

PowerShell Malware –  PowerShell is a great next-generation command line shell. In the last few years, hackers have realized this as well and are using PowerShell for malware-free hacking. A few months ago I started looking into obfuscated PowerShell techniques, which allow hackers to hide the evil PowerShell and make it almost impossible for traditional scanners to detect. This is good information for IT people who need to get a first look at the new threat environment. In this two-part series, I referenced a Black Hat presentation given by Lee Holmes — yeah, that guy!  Check out Lee’s comment on the post.

Varonis and Ransomware – This was certainly the year of weaponized ransomware with WannaCry, Petya, et. al. using the NSA-discovered EternalBlue exploit to hold data hostage on a global scale. In this post, we explain how our DatAlert software can be used to detect PsExec, which is used to spread the Petya-variant of the malware. And in this other ransomware post, we also explain how to use DatAlert to detect the mass encryption of files and to limit your risks after ransomware infection.

PowerShell as a Cyber Monitoring Tool – I spent a bit of effort in this long series explaining how to use PowerShell to classify data and monitor events — kind of a roll-your-own Varonis. Alas, it didn’t get the exposure I had hoped. But there are some really great PowerShell tips, and sample code using Register-EngineEvent to monitor low-level file access events. A must read if you’re a PowerShell DIY-er.

Compliance

NIS, the Next Big EU Security Law – While we’ve all been focused on the EU GDPR, there’s more EU data security rules that go into effect in 2018. For example, The Network and Information Security (NIS) Directive.  EU countries have until July 2018 to “transpose” this directive into their own national laws. Effectively, the NIS Directive asks companies involved in critical infrastructure — energy, transportation, telecom, and Internet — to have in place data security procedures and to notify regulators when there’s a serious cyber incident. Unlike the GDPR, this directive is not just about data exposure but covers any significant cyber event, including DoS, ransomware, and data destruction.

GDPR’s 72-Hour Breach Notification – One particular GDPR requirement that’s been causing major headaches for IT is the new breach notification rules. In October, we received guidelines from the regulators. It turns out that there’s more flexibility than was first thought. For example, you can provide EU regulators partial information in the first 72-hours after discovery and more complete information as it becomes available. And there are many instances where companies will not have to additionally contact individuals if the personal data exposed is not financially harmful. It’s complicated so read this post to learn the subtleties.

By the way, we’ve been very proud of our GDPR coverage. At least one of our posts has been snippetized by Google, which means that at least Google’s algorithms think our GDPR content is the cat’s meow. Just sayin’.

Podcasts

Man vs. Machine – Each week Cindy Ng leads a discussion with a few other Varonians, including Mike Buckbee, Killian Englert, and Kris Keyser. In this fascinating podcast, Cindy and her panelists take on the question of ethics in software and data security design. We know all too well that data security is often not thought about when products are sold to consumers — maybe afterwards after a hack. We can and should do a better job in training developers and introducing better data laws, for example the EU GDPR. But what is “good enough” for algorithms that think for themselves in, say,  autonomous cars?  I don’t have the answer, but is what great fun listening to this group talk about this issue.

Cybercrime Startups – It’s strange at first to think of hackers as entrepreneurs and their criminal team as a startup. But in fact there are similarities, and hacking in 2017 starts looking like a viable career option for some. In this perfect drive-time podcast, our panelists explore the everyday world of the cybercrime startup.

Fun Security Facts

Securing S3 –  As someone who uses Amazon Web Services (AWS) to quickly test out ideas for blog posts, I’m a little in awe of Amazon’s cloud magic and also afraid to touch many of the configuration options. Apparently, I’m not the only one who gets lost in AWS since there have been major breach involving its heavily used data storage feature, known as S3. In this post, Mikes covers S3’s buckets and objects and explains how to set up security policies. Find out how to avoid being an S3 victim in 2018!

Practical PowerShell for IT Security, Part I: File Event Monitoring

Practical PowerShell for IT Security, Part I: File Event Monitoring

Back when I was writing the ultimate penetration testing series to help humankind deal with hackers, I came across some interesting PowerShell cmdlets and techniques. I made the remarkable discovery that PowerShell is a security tool in its own right. Sounds to me like it’s the right time to start another series of PowerShell posts.

We’ll take the view in these posts that while PowerShell won’t replace purpose-built security platforms — Varonis can breathe easier now — it will help IT staff monitor for threats and perform other security functions. And also give IT folks an appreciation of the miracles that are accomplished by real security platforms, like our own Metadata Framework. PowerShell can do interesting security work on a small scale, but it is in no way equipped to take on an entire infrastructure.

It’s a Big Event

To begin, let’s explore using PowerShell as a system monitoring tool to watch files, processes, and users.

Before you start cursing into your browsers, I’m well aware that any operating system command language can be used to monitor system-level happenings. A junior IT admin can quickly put together, say, a Linux shell script to poll a directory to see if a file has been updated or retrieve a list of running processes to learn if a non-standard process has popped up.

I ain’t talking about that.

PowerShell instead gives you direct event-driven monitoring based on the operating system’s access to low-level changes. It’s the equivalent of getting a push notification on a news web page alerting you to a breaking story rather than having to manually refresh the page.

In this scenario, you’re not in an endless PowerShell loop, burning up CPU cycles, but instead the script is only notified or activated when the event — a file is modified or a new user logs in — actually occurs. It’s a far more efficient way to do security monitoring than by brute-force polling.

Further down below, I’ll explain how this is accomplished.

But first, anyone who’s ever taken, as I have, a basic “Operating Systems for Poets” course knows that there’s a demarcation between user-level and system-level processes.

The operating system, whether Linux or Windows, does the low-level handling of device actions – anything from disk reads, to packets being received — and hides this from garden variety apps that we run from our desktop.

So if you launch your favorite word processing app and view the first page of a document, the whole operation appears as a smooth, synchronous activity. But in reality there are all kinds of time-sensitive actions events — disk seeks, disk blocks being read, characters sent to the screen, etc. — that are happening under the hood and deliberately hidden from us.  Thank you Bill Gates!

In the old days, only hard-core system engineers knew about this low-level event processing. But as we’ll soon see, PowerShell scripters can now share in the joy as well.

An OS Instrumentation Language

This brings us to Windows Management Instrumentation (WMI), which is a Microsoft effort to provide a consistent view of operating system objects.

Only a few years old, WMI is itself part of a broader industry effort, known as Web-based Enterprise Management (WBEM), to standardize the information pulled out of routers, switches, storage arrays, as well as operating systems.

So what does WMI actually look and feel like?

For our purposes, it’s really a query language, like SQL, but instead of accessing rows of vanilla database columns, it presents complex OS information organized as a WMI_class hierarchy. Not too surprisingly, the query language is known as, wait for it, WQL.

Windows generously provides a utility, wbemtest, that lets you play with WQL. In the graphic below, you can see the results of my querying the Win32_Process object, which holds information on the current processes running.

WQL on training wheels with wbemtest.

Effectively, it’s the programmatic equivalent of running the Windows task monitor. Impressive, no? If you want to know more about WQL, download Ravi Chaganti’s wonderous ebook on the subject.

PowerShell and the Register-WmiEvent Cmdlet

But there’s more! You can take off the training wheels provided by wbemtest, and try these queries directly in PowerShell.

Powershell’s Get-WMIObject is the appropriate cmdlet for this task, and it lets you feed in the WQL query directly as a parameter.

The graphic below shows the first few results from running select Name, ProcessId, CommandLine from Win32_Process on my AWS test environment.

gwmi is the PowerShell alias for Get-WmiObject.

The output is a bit wonky since it’s showing some hidden properties having to do with underlying class bookkeeping. The cmdlet also spews out a huge list that speeds by on my console.

For a better Win32_Process experience, I piped the output from the query into Out-GridView, a neat PS cmdlet that formats the data as a beautiful GUI-based table.

Not too shabby for a line of PowerShell code. But WMI does more than allow you to query these OS objects.

As I mentioned earlier, it gives you access to relevant events on the objects themselves. In WMI, these events are broadly broken into three types: creation, modification, and deletion.

Prior to PowerShell 2.0, you had to access these events in a clunky way: creating lots of different objects, and then you were forced to synchronously ‘hang’, so it wasn’t true asynchronous event-handling. If you want to know more, read this MS Technet post for the ugly details.

Now in PS 2.0 with the Register-WmiEvent cmdlet, we have a far prettier way to react to all kinds of events. In geek-speak, I can register a callback that fires when the event occurs.

Let’s go back to my mythical (and now famous) Acme Company, whose IT infrastructure is set up on my AWS environment.

Let’s say Bob, the sys admin, notices every so often that he’s running low on file space on the Salsa server. He suspects that Ted Bloatly, Acme’s CEO, is downloading huge files, likely audio files, into one of Bob’s directories and then moving them into Ted’s own server on Taco.

Bob wants to set a trap: when a large file is created in his home directory, he’ll be notified on his console.

To accomplish this, he’ll need to work with the CIM_DataFile class.  Instead of accessing processes, as we did above, Bob uses this class to connect with the underlying file metadata.

CIM_DataFile object can be accessed directly in PowerShell.

Playing the part of Bob, I created the following Register-WmiEvent script, which will notify the console when a very large file is created in the home directory.

Register-WmiEvent -Query "SELECT * FROM __InstanceModificationEvent WITHIN 5 WHERE TargetInstance isa 'CIM_DataFile' and TargetInstance.FileSize > 2000000 and TargetInstance.Path = '\\Users\\bob\\' and targetInstance.Drive = 'C:' "-sourceIdentifier "Accessor3" -Action  { Write-Host "Large file" $EventArgs.NewEvent.TargetInstance.Name  "was created”}

 

Running this script directly from the Salsa console launches the Register-WmiEvent command in the background, assigning it a job number, and then only interacts with the console when the event is triggered.

In the next post, I’ll go into more details about what I’ve done here. Effectively, I’m using WQL to query the CIM_DataFile object — particularly anything in the \Users\bob directory that’s over 2 million bytes — and set up a notification when a new file is created that fits this criteria —that’s where InstanceModificationEvent comes into play.

Anyway, in my Bob role  I launched the script from the PS command line, and then putting on my Ted Bloatly hat, I copied a large mp4 into Bob’s directory. You can see the results below.

We now know that Bloatly is a fan of Melody Gardot. Who would have thunk it?

You begin to see some of the exciting possibilities with PowerShell as a tool to detect threats patterns and perhaps for doing a little behavior analytics.

We’ll be exploring these ideas in the next post.

Continue reading the next post in "Practical PowerShell for IT Security"

Interview with Pen Testing Expert Ed Skoudis

Interview with Pen Testing Expert Ed Skoudis

We’re very excited to present this Q&A with Ed Skoudis. Skoudis is a very large presence in the security world. Here’s just a snippet from his lengthy bio: founder of Counter Hack, sought-after instructor at the SANS Institute, creator of NetWars CyberCity, and winner of the US Army’s Order of Thor Medal.

We focused our questions on some of the essentials of post-exploitation techniques. Skoudis set us straight on definitions and methodologies. His answers also nicely complement our own series on pentesting basics.

Inside Out Security: Let’s say you’ve entered a target system and installed an APT or RAT …

Ed Skoudis: I’m not sure APT is the proper word here.  One doesn’t install an “APT”. An APT is a threat actor, specifically a very skilled one. [See this definition of APT.]

Also, I’d prefer not to install a RAT during a penetration test.  There is no need for one in modern pen testing. RATs tend to be too heavyweight and intrusive. Traditional RATs usually provide GUI control of the machine and a bunch of splashy doodads that aren’t required by a penetration tester.

Instead, when compromising a machine, I like to use a light-weight payload, such as a Metasploit Meterpreter or related tool to get some form of shell access.

IOS: Ok, so after you’re in what would be the next four or five steps you’d take?

ES: After gaining a toe-hold on the target machine, I would:

  1.  Determine the privileges I’m running with.
  2.  Determine the machine’s location on the network and its network configuration, including looking at its network interfaces (it might be dual-homed), hostname, IP address, MAC address, ARP cache, and DNS cache.  It’s important to look for both IPv4 and IPv6 information from these sources, as many systems support IPv6 in addition to IPv4, and IPv6 tends not to get as much scrutiny from security tools as IPv4, making it a nice avenue of attack.
  3. Look for the active TCP connections this machine has with other systems, especially interesting protocols such as SMB (for Windows file sharing and domain authentication) or SSH (for secure remote shell).
  4. Check to see what security tools are installed, including anti-virus, application white listing, local firewall, etc.
  5. See if I can leverage its location on the network and active TCP connections to pivot to another host.

IOS: What are some must-have tools for post-exploitation?

ES: For Windows targets, there are plentiful PowerShell tools for privilege escalation, pillaging, and pivoting.  One of the very best suite of these tools is PowerShell Empire, which rolls together some incredible functionality from a variety of other projects.

In addition to PowerShell Empire, Metasploit itself includes dozens of post-exploitation modules useful for dumping hashes, grabbing crypto keys, getting environment information (including security defenses), and much more.

IOS: What are some techniques and tools for working out local network topology?

ES: I prefer to gain as much information from a compromised machine about the network around it as I can before resorting to intrusive (and easily discovered) scanning. That’s why I like to grab ARP cache, DNS cache, and a list of active TCP connections before moving on. That information tells me about other hosts that the currently compromised one knows about.  I’ll also grab the routing table, as it may indicate additional routers on the subnet.

After pillaging that local information from a system, I then start probing to look for other targets on the same subnet, as they will likely be more accessible than systems on separate networks. A ping sweep (IPv4) or a ping of a multi-cast address (IPv6) may turn up additional nearby hosts ripe for picking and which may have identical credentials to the system(s) I’ve currently compromised!

I then typically do small-scale port scans of very interesting ports to me, those associated with protocols where I may find more juicy attack surface, including TCP 21, 22, 23, 25, 80, 443, 445, 6000, and more.

IOS: How do you go about moving around the network?

ES: I use a variety of methods for lateral movement, including the pivoting features of Meterpreter’s msfconsole route command and portfwd commands are quite useful.

On systems where Netcat is already installed (most Linuxes), I rely on Netcat relays of various types, including listener-to-client relays, but also client-to-client and listener-to-listener relays.

On Windows targets, I really love the “netsh interface portproxy” feature to forward ports through the machine, especially its ability to listen on a given port on IPv4 and then shoot data out to another port using IPv6. As far as TCP is concerned at Layer 4, it’s a single connection.  But, we switch out the underlying Layer 3 protocol (from IPv4 to IPv6) underneath a single  TCP connection. It’s beautiful.

IOS: What are the some of the ways exfiltration of data can be accomplished without it being detected?

ES: First, encryption. In many organizations, simply sending the data across a TLS connection will get the job done.  Still, they may see the large transfer.  If I need to be more subtle, I’ll consider moving data across a command-and-control channel over DNS or related protocol.  A slow dribble is far less likely to be detected than a smash-and-grab, but will still demonstrate the business risk a professional pen tester is hired to show.

IOS: How does one search for PII and other sensitive content?

ES: Understanding the business use of a compromised machine is a vital step here.  What does the machine do, and where does it store its information to do that?  This usually gets me in the right direction.

I search using typical file system commands, such as cd, ls, find, grep, and so forth on Linux, and cd, dir, findstr, etc. on Windows.  In PowerShell on Windows, we have some additional great features for searching through the file system.

There are specific tools for finding things like social security numbers and credit cards on targets, but I find that they tend to produce a lot of disk access and noise in the target environment, another items that may get a pen tester noticed and perhaps even blocked.

IOS: Finally, any recent trends you can comment on?

ES: Yes, attacks using PowerShell are really on the rise, and there are some tremendous tools like PowerShell Empire for modeling such attacks in pen tests. Furthermore, attacks against Windows Kerberos are an increasing vector today.

IOS: Thanks Ed!

Windows PowerShell Tutorial For Beginners

Windows PowerShell Tutorial For Beginners

PowerShell Tutorial: What is it?

Windows PowerShell is an interactive object-oriented command environment developed by Microsoft to automate tasks and simplify configuration. It’s used to automate almost any area of the Windows ecosystem, including Active Directory and Exchange. After reading this post, you’ll understand why it’s become so popular amongst perpetually overworked sysadmins and other IT pros. We’ll teach you how to use cmdlets, go through a few task-based PowerShell examples and share a few resources that can help you jumpstart your PowerShell training.

So, let’s get started.

Launching PowerShell (and Run as Administrator)

In Windows 10, the search field is one of the fastest way to launch PowerShell. From the taskbar, in the search text field, type powershell. Then, click or tap the ‘Windows PowerShell’ result.

To run PowerShell as administrator, right-click (touchscreen users: tap and hold) on the Windows PowerShell search result, then click or tap ‘Run as administrator’.

Keep in mind, there are many other ways to start a PowerShell console.

PowerShell Cmdlets

As an IT pro, many command lines you’re familiar with also work in PowerShell.

Try typing: DIR, CD, IPCONFIG, and PING.

If you look closer, they do work slightly different in PowerShell, but for now, typical commands work exactly the same way as they have always worked.

By the way, PowerShell is fundamentally case insensitive. There are instances when you’ll need to pay attention to how you type them, like with Active Directory Services Interface.

What are cmdlets

Cmdlets are PowerShell commands and organized in the form of a verb-noun string. Once you understand this template, you can practically guess the meaning of any cmdlet.

Guess and then type these cmdlets:

  • Get-Command (outputs a list of all available cmdlets)
  • Get-Help (shows help information about cmdlets)
  • Get-EventLog (displays Windows event logs)
  • Get-Acl (retrieves access control lists (ACLs)

Knowing what commands you can use is great, but it doesn’t help if you don’t know how you can use them.

How to use a cmdlet

To see how to use a cmdlet, enter the cmdlet name followed by ”-?“.

Example:

1

Click here for a full list of approved verbs for Windows PowerShell Commands.

Aliases

Aliases in PowerShell are just an alternate name for the underlying cmdlet. There are two reasons for aliases. One is that they allow for more concise code on Command Prompt. Second is that they ease a user’s transition from other shells to PowerShell.

Here’s an example: dir is an alias for the get-childitem cmdlet.
To prove that the cmdlet defined in PowerShell for dir is indeed get-childitem, try this:

get-alias dir

And to go the other direction and discover all the aliases defined for the get-childitem cmdlet:

    get-alias –definition get-childitem

3

Nice! PowersShell gives Linux users a break by setting up an alias for ls.

Also set-alias allows you to map a new alias to a cmdlet. For instance, list can be an alias for get-childitem, if you type:

set-alias list get-childitem

4

The screenshot shows that if you type list or get-childitem, you get the same result! Magic!

Practical Cmdlets

In this next tutorial, you’ll learn three very useful cmdlets: get-command, get-help, and get-member. This foundational language will eventually empower us execute task-based cmdlets.

Get-Command

get-command outputs all commands available to you in your current session.

Try it! Type: get-command

get-command

But other than that, using the get-command by itself isn’t particularly helpful. You’re most likely going to use get-command to find commands you’ll want to work with.

For instance, if you want to find all the commands that begin with the letter “s”, type:
get-command s*commands that start with s

In our last post, we mentioned that PowerShell cmdlet names are based on “verb-noun” template. So to see all cmdlets that use the verb get, type:
get-command -verb get

Get-Command -Verb Get

I got excited about this function and tried a few more commands. Join me for some fun?  To see all the things you can start, type:
get-command -verb start

start

And to see all the things you can stop, type:
get-command -verb stop

stop

Let’s do the same thing with noun!  It’s very helpful because it outputs a set of commands that affect the same type of object. For example, if you want to see which commands are available for managing services, type:
get-command -noun service

noun service

Get-Help

Let’s face it, we all need a little help sometimes. For a list of all available help topics, type:
get-help *

gethelp-

Once you have this list, you can then get help on a specific cmdlet. Try this:
get-help get-service

gethelp getservice

Remember our last lesson? You can display the same output if you type -? after the cmdlet. See for yourself! Type:
get-service -?

getservice-

And now for my favorite part! If you ever need an example to see how to use a cmdlet, type:
get-help get-service – examples

get service examples

While my screenshot displays five, there are a total of eleven get-service examples.

Get-Member

get-member pulls more information about an object. To see what the get-member can do, type: get-help get-member -examples

get-member1

While my screenshot displays five, there are a total of seven get-member examples.

In the examples, you’ll notice that you’ll often need to use get-member with a pipeline. Pipelines act like a series of connected segments of pipe. Items moving along the pipeline pass through each segment. To create a pipeline in PowerShell, you connect commands together with the pipe operator “|”. The output of each command is used as input to the next command.

Let’s go over an example. If you want to know which properties and methods are available for event logs, you’d type:
get-eventlog -list | get-member

get member event log

get-eventlog cmdlet enables you to manage your event logs, and enables you to get at the events contained within those event logs.

-list is a parameter.

Simple Task-Based PowerShell Examples

After the novelty of learning something new wears off – unless you can connect the subject to your work – it’s often hard to want to continue practicing.

So, let me introduce you to a few practical, task-based PowerShell examples.

What’s the date?

Type:get-date

get-date

Simple, right?

But what if you just wanted day of the year, week, hour of day, or today’s date?

Type:

(get-date).dayofyear

(get-date).dayofweek

(get-date).hour

(get-date).day

alternative

The results tell me that today is the 320th day of the year, Monday, a little after 12pm, and is November 16th.   With all this power, who needs to look at their iPhone?

You’ve just been told you have 16 days to complete a project. What date is that?

Try this: (get-date).adddays(16)

Alternatively, we can get the same results by creating a variable:

$a = Get-Date

Then type:

"Month: " + $a.Dayofyear

"Day of the Week: " + $a.Dayofweek

"Hour: " + $a.Hour

“Day:” + $a.day

variable

Here’s a table to summarize some of the PowerShell punctuation we’ve used:

Symbol Name Function Example
$ Dollar Sign Declares a variable $a
= Equal Assigns a value to the variable $a=get-date
“” Double Quote Use double quotes to display text If $a = Monday

“Day of the Week: $a”
will output as:

Day of the Week: Monday

+ Plus Concatenates $a = November

“Day of the Week: ”
+ $a.Dayofweek

Day of the Week: Monday

( ) Parenthesis Groups to create argument  (get-date).day

To get more date and time properties, we can use a cmdlet from our previous lesson:

get-date  | get-member

get date get member

Force Stop a Service

When you have a Windows service running that will not respond to stop commands, you can use PowerShell. For instance, suppose my Lync freezes and  Lync’s process ID is 9212, then this command will stop it in its tracks:

stop-process 9212

Or

stop-process –processname lync

(And I check. Yep, my lync closed)

To get a full list of processes running, type:

get-process
lync

In the last line, you can see that Lync corresponds with the process ID 9212.

Check if a File Exists

Suppose you need to delete multiple files, you might want to first check to see if the files even exist.

test-path, as the name implies, lets you verify whether elements of the path exist. It’ll return TRUE, if all elements exist, and FALSE if any are missing.

You simply type:

test-Path (And then the file path)

I wanted to see if the article I wrote on SIEM vs. UBA exists. So I typed the file path:

test-path C:\users\cng\filesforDN\Blogs\SIEMandUBA.docx

SIEM and UBA

True! It’s exists!

PowerShell Recap

In this post, we’ve learned what a cmdlet is, how to use a cmdlet (enter the cmdlet name followed by ” -?“), and practical task-based examples.

You’ve been a witness to why PowerShell has been so helpful and we hope we’ve inspired you to want to learn more.

PowerShell Resources

Below are the latest tutorials—hmm, maybe that’s a task for PowerShell as well–and I’ve culled them down to a top ten:

Getting Started with PowerShell

  1. PowerShell for Beginners – A library of links to get started, best practices, command line syntax and more!
  2. Don Jones’ bestselling PowerShell book, Learn Windows PowerShell in a Month of Lunches is also in video! After 3-4 months of lunches with the tutorial video series, you’ll be automating admin tasks faster than you ever thought possible. By the way, the author answers questions at powershell.org. There are numerous PowerShell resources, events, and even free ebooks!
  3. If you’re taking the MCSA 70-410 Microsoft Exam, these flashcards will help: PowerShell commands.
  4. PowerShell allows you to string multiple commands together on one line using a technique called pipelining. It makes complex things much simpler, and you can learn about it here.

Configure and Manage Active Directory

Save even more time by learning how to configure and manage Active Directory using PowerShell with these resources:

  1. Use PowerShell to Search AD for High-Privileged Accounts.
  2. Use AD module cmdlets to perform various administrative, configuration, and diagnostic tasks in your AD DS and AD LDS environments.
  3. Build an AD utility from scratch in this epic 3 hour PowerShell video course (unlock for free with code:
    cmdlet)

Automate Exchange

With all that free time you have, why not learn how to automate Exchange with these resources:

  1. An excellent video on Managing Exchange Online Using PowerShell
  2. If you’re an Exchange Admin, make sure you have these 5 skills down
  3. Click here for more PowerShell tips for Exchange Admins. Then scroll down for the good stuff.