Defending against PowerShell attacks - in theory, and in practice by Lee holmes

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
you before I get talking I'm gonna be walking so so we're here for defending against PowerShell attacks I'm Lea Holmes I'm the lead security architect for Azure management and as you probably seen through a bunch of the sessions and stuff so far that PowerShell is a huge part of azure and a huge part of Azure management I'm an original developer on the PowerShell team I'm an author of the PowerShell cookbook but realistically the expertise is you guys you know I've been a guy along for the ride what's really defined PowerShell is the PowerShell community and the expertise in this room is just super humbling so defending against PowerShell attacks if you didn't notice this goes from 9:00 until 10:45 now I've never been in a session this long before but I kind of expect it might be something a little bit like all right Early's 9:00 a.m. first day of school we're all pretty excited about things all right 10 o'clock you're gonna be like do I have any important emails at work my taxes done it's my house burning down by the end you could be like oh my god I missed my wife's anniversary twice and my Paris birthday so I applaud your dedication to the craft I really do now as we started getting talking about PowerShell attacks people talk about it in the news and stuff all the time defending against PowerShell attacks now what does one actually look like like I don't have a hoodie no one here has a hoodie so maybe we're not qualified to be attackers but let's take a look at how they actually start did I hear a hoodie no oh hoodie attacker watch it huh two attackers out all right this is the way it starts you've got almost entirely commonly frequently you've got a malicious office document being used as a phishing attack now smug IT people will say only fools fall for phishing attacks but we've got to get away from blaming blaming the victims here I've been involved in incident responses where what happened was an attacker compromised one company they went and started responding to active email threads with contextual documents related to that thread like oh please see attached it describes everything in this thread I don't care who you are you're falling for that you're clicking you're enabling macros now you enable macros and what happens when do you enable macros that runs VBA Visual Basic for applications now you might think you look at this code and you might be a little bit disgusted but the truth is it's just as powerful as any executable at the top there it's invoking Windows ap is any windows API is I've seen shell code loaders and PE loaders fully leveraging this to take dll's off disk and make them executable so in this simple example what they're doing is they're calling a Windows API to download a file run that file and there you go you got more malware under the system usually these things are stagers where they're not the full attack they just enable further attacks so this is a basic one here's an example of one that might be more complicated so it's still using VBA it still has full access to the powershell language to the vba language to Windows all that kind of stuff what they've decided to do here is rather than download the executable they've packaged it up in base64 and in the bottom here you can see that what they've done is they've used cert util to decode the base64 dump that onto disk as an executable and then run the executable so you're starting to see a pattern here where they they compromised a victim run something to download more things and then they usually just shovel in a well-known exploit kit that can get them their job done right so what does a power shell attack look like this is where it gets exciting maybe not all they did is they took some base64 but instead of calling cert util they're calling PowerShell and it's doing all the same stuff but this time rather than encoding the payload isn't executable which always works they're encoding it as a PowerShell command and realistically this PowerShell command more often than not just downloads an executable and runs it but this is what a PowerShell attack looks like I'm serious this is what they look like these things come from John Lambert on Twitter he is part of the the mystic team in Microsoft so they do a lot of threat intelligence so these come from he does a lot of scraping against virustotal which is kind of an information sharing platform so these examples come from here and you might ask well if no good attackers are getting caught on virustotal maybe this isn't representative so this is an example of apt so mandiant they're a really really high class Incident Response Company they assist lots and lots of companies here's an example of an apt that was doing targeted attacks against banks in the Middle East I'll save you the pain you look at this they ended up doing a phishing attack to break in initially and unfortunately it's about the same thing as they always are it's a simple dock with a macro that runs some stuff so apt and average malware is all about the same from the initial point of entry but what you do here is a lot of people talking still about the PowerShell attacks and how encoded command and obfuscation techniques like that that's where like the real damage is now the great deep dive into this was from Palo Alto so they have a unit 42 and they have a great visibility they do an endpoint protection but it also is backed by email protection gateways they were actually able to say when they saw a compromised using PowerShell - encoded commands so a PowerShell attack how did that start it never started with PowerShell it always started they traced it back they traced it back and they found out well originally this person got an X e and they ran it and that thing ran PowerShell where they got a doc they they double clicked it enabled a macro and that run PowerShell or a DLL or a spreadsheet so the danger of the PowerShell attack is never the PowerShell attack is just that people are using it for post compromised activities they've already got code execution on a system that can do anything that you can do in Windows and then they decide to use PowerShell for a little bit of excitement where we have seen and this is where we start to talk about PowerShell for post exploitation where we have seen a lot of use and uptick in PowerShell is in the security research community I'll tell you one thing the people who are compromising companies and stealing secrets stealing IP doing around somewhere they're not the same people who are presenting at conferences like black hat and DEF CON so the things you see here are pen testers and red teamers anybody making any of these tool kits that they release publicly you should applaud them for their efforts because what they're doing is they're showing things that actually exist and they're coming from people who have their hearts in it of everybody wanting to secure the environments together there's different ways to get there but you should never feel bad about these frameworks because they're a demonstration of existing skill and vulnerabilities so there's a bunch of them anybody experimented with any of them if you haven't this is like one of the things you should do is experiment with one of these frameworks take a look at your own infrastructure and see what kind of danger you have going on there but one of the things that's really interesting to realize is that PowerShell is just one example of the things that you can do on a system once you've compromised it different ackers and red teamers they have quality of life where they've begun to realize is that compromising a machine and then writing batch files sucks what you want to be is like just like any of us here right writing some PowerShell using some command it's enjoying those objects so they're all coming from the quality of life perspective but that's not the only option they can run exes like I showed you a million times dll's all kinds of stuff that they can do on a system once they have access to it but this is what you kind of hear sometimes on the on the world right let's block PowerShell I hear about all these PowerShell attacks let's block it so here's the question how is that going to work out for you probably not I showed you how people are able to do so many things on a system PowerShell is just one of them you're not going to change the actual problem the problem isn't that they used the tool called PowerShell DXE the problem is that you're allowing any application to run and that there isn't efficient malware scanning happening on your systems so it doesn't address the underlying problem but what we're going to talk about a lot today is that it doesn't address your underlying security vulnerabilities but it also removes your most powerful tool at your disposal as a defender this is a very very important point people will do it anyways they'll block PowerShell taxi but here's the thing parish LXE is not just PowerShell taxi many people in this room already know that really the intelligence is behind system management automation the automation set of dll's and frameworks the ISE hosts it Parishad XE hosts it vs code hosts it everything that has PowerShell support is hosting the PowerShell engine now there's great examples out there of people blocking PowerShell XE but researchers just made a new version called not PowerShell XE literally NPS XE that thing gets past any sort of blocks like that so it's a short-sighted approach to take this is an example of a hosting demo that I did in like 2006 of kind of hosting the the logo you know the old turtle logo now in terms of attacks this is a great example has anybody reviewed The MITRE attack framework suite it's they've done a great job of digging into once an attacker gets onto a system what are the different techniques that they use today so yeah you've got persistence and I hope you can all read this right yeah you bet persistence you've got elevation of privilege what are the actual techniques that our attackers are using today in actual attacks on systems so I'll save you the the hard work there is PowerShell and there's PowerShell remoting so remember that person who blocked PowerShell how are they doing yeah exactly does not make a difference here's another example again intentionally ridiculous to read one of the things that sits on almost every network is the Lua interpreter Lua is a very popular embedded scripting language it's embedded in a bunch of different environments a bunch of different applications AutoCAD all kinds of stuff it's very powerful here's an example of Lua being used as part of nmap almost every linux distribution and unix distribution most Windows machines have nmap installed this lets you go off and kind of port probe ports and all that kind of stuff around your network it has an embedded Lua interpreter here's an example of it doing the usual like pop and calc right this thing has full access to a machine people don't realize it exists they block PowerShell Lua who's just as capable from that perspective now a way I like to think about this is Maslow's hierarchy of security controls you hear about people blocking PowerShell and being worried that pirate shell is like forensically clean and all this kind of stuff but you take a look it's important to think through the right levels of securing your environment and securing your infrastructure obviously patching an antivirus are very very important what these things do is they protect you against the things that are known to the whole industry of being bad if you don't if you're not protecting yourself against script kiddie malware that's known to the entire industry as being bad you've got a vulnerability coming up you want to talk about putting application whitelisting at the very least in deny mode did i mode lets you say i personally know that this is bad maybe I know this hash is bad or this executable is bad or this file name is bad like you've got way more intelligence than the industry this gives you the mechanics to start blocking this stuff against your infrastructure moving on to allow mode obviously the problem with the deny mode is that it usually only takes a small variation on evil to get out of that sort of block list so allow mode starts to let you to say I'm only going to allow things that are vetted and trusted to run in my infrastructure so that way somebody does a minor variation on evil it's not going to get me because I didn't go through an explicit vetting process once you start getting past those controls we talk about auditing the protections you know how are you making sure that people aren't clearing the event logs and things like that disabling your controls you start to talk about forensics against disk images you start to talk about forensics against memory images so when you hear people who are really really concerned about forensic ly clean PowerShell they're starting to worry yet like this apex of the Maslow's hierarchy of security controls yet a lot of times they're proponents of disable AV or proponents they don't even have the capability of blocking known malware somebody says I'm gonna fish you tomorrow with a document with the following hash good luck if you don't have the ability to block that known attack you really shouldn't be worrying about forensic capture of memory artifacts now I might sound like a bit of a PowerShell apologist coming up like hey it's never power shells fault the truth is it's not but the truth is there are PowerShell there are attacks that have leveraged PowerShell and this hurts us very deeply so we have in very heavily in PowerShell since the very first version we've invested very heavily in security and this is an example of we really really double down in version 5 and added tons and tons of PowerShell auditing and controls has anybody here read the PowerShell Hartz the blue team blog post ok sweet so a couple this will be new so one of the things we've done is very deeply invested in when it comes down to it attackers are just unauthorized system administrators we're never going to get away from system administration but what we can do is make sure that unauthorized use of PowerShell is as transparent as it can possibly be this thing should leave a slime trail from here it'll tomorrow so we invested it and this is a great blog post that we put up where we compared the security optics and the security controls and popular management frameworks see anybody that's good as PowerShell I don't I've really tried to be super open about this like you know take feedback where it exists I haven't met a single person in the security community or otherwise who can say oh yeah you're missing about four or five features that this other thing has that makes it more secure now here's another thing I talked about us listening about PowerShell apologists this is kind of a dirty little secret that no one's talking about Python there is one new row since we first started doing the PowerShell version five work where we have now turns out that a lot of the core developers and Python work for Microsoft and it turns out that some sensitive infrastructure in Microsoft runs Python seeing how how good the PowerShell script block logging and auditing and transparency and all that kind of stuff is actually stopping attackers we've been working very closely with the Python community about bringing some of these security transparency features and to Python itself so this is an example of doing PowerShell or Python like a Python attack it's almost exactly the same thing that you see when people are concerned about parish shell attacks so this is being shepherded through the process right now is pepp five five one Python has a community driven improvement process these things are based on community feedback one of the things that there's a misconception in the Python community is that that detection of attacks is kind of a PowerShell only thing and so if you're running any Python and you probably want to make sure that the Python world is aware of your concerns and support publicly support pep five five one so tweet about it all that kind of stuff that will really help the Python organization realize that people like you are concerned about Python being abused on your infrastructures so I've talked about PowerShell security transparency so let's take a little bit of a dive into some of the things that we've done in PowerShell to make it incredibly transparent to how it's being used now the first question is like how do I do all this stuff well configuration is pretty easy we have some group policies that you can go off and set deploy them they're backed by very simple Reg keys you can go off and set those reg keys directly through DSC or PowerShell or whatever you're using so all these things are incredibly easy to set up now the first one is module and pipeline logging so module and pipe LAN line logging it logs every command lit that's being run including the parameters being used for that command lit so when you see people using sketchy versions of invoke web requests when you enable module and pipeline logging you get to see exactly the URLs that were bound to that command lit you get to see what was downloaded this feature has existed so this PowerShell version one in version three what we did is we turned it on so that you could enable it for everything and not just specific modules so this has been around for some time and it's a really really useful source of insight on the power show that's happening on your system another big one is system transcripts you know the start transcript command late in PowerShell one of the mistakes we had made up until PowerShell version three kind of four was that it was baked into PowerShell XE itself the idea of transcripting so what we did is we instead migrated this into the engine itself so now start transcript works from PowerShell from the ISE from vs code anything that uses PowerShell but the important thing this also gave us the ability to set up system-wide policies for transcripts so this is kind of an over-the-shoulder view of what's happening on your system you can as if you're behind the shoulders of an attacker seeing what they're doing you can set up system transcripts in transcripting to go against a share and then if anything ever happens you can just add it the stuff in that share you're good you know exactly what happened now one of the things that I've heard is people saying well you know I don't necessarily have the skills to do reverse engineering or Incident Response but I tell you everybody here has the skills to set up an SMB server deploy a group policy to have all your transcripts dumping into the SMB server everybody has that skill you might not know what to do with it but if an incident response happens absolutely anybody that you call in to help will praise you to the day they die that you had a flight data recorder of everything that happened on your systems a great example of this there there's a Twitter account InfoSec Taylor Swift they've done this read they they know they don't have the capability but they went off and they deployed transcripting as all dumping into a share they're collecting it it's really really if their text files you zip them it uses almost nothing for archival storage now there's another big one so I talked about over-the-shoulder transcripting but script block logging is where things really start to get crazy the problem is see this command here powershell - encoded command well you see it you don't know what it does you see this in the in the Windows Event log so you don't know what it does now one of the things that we added in PowerShell version 5 was the idea of script block logging so anytime anybody has asked PowerShell invoke this thing evaluate this string invoke this script anything anytime it goes into the PowerShell parser we log it to the event log so those those obfuscated techniques that I talked about where people are going off running some PowerShell is a stager going off and downloading more content and running invoke expression on that each one of those stages PowerShell is being asked to evaluate it it dumps it into the event log and you get to see every single thing that happened this is an example of what that looks like so this is obfuscated PowerShell script that is kind of prototypical of the kind of stuff you might see in an attack and you might say that sucks I'm gonna spend like two three hours to do this gate this turns out that script block logging is the best D office cater that money can buy when you look at the next event log this is what it is that first stage went through invoke expression and PowerShell ask was asked to evaluate it again it did and it went and ran this against the script block login you get to see very very bare exactly what happened so you can dump these things into your sim or anything like that and have the ability to write much more robust rules that aren't perturbed by a simple alpha station that happens in pretty much everything else now where this really takes an interesting twist is the anti-malware scan interface so this is a feature that we worked with the defender team and the the core team in Windows now the way that that anti-malware traditionally works you've got an application and anti-malware like defender and stuff what it will do as it will sit on the machine and if PowerShell is trying to for example access a file it'll intercept that that call and it will do some heuristics on the file that PowerShell is trying to access run it against some signatures all that kind of stuff it'll also do this against web connections and some other things it'll make an evaluation based on that initial point of entry and then decide whether PowerShell should be allowed to run it or not the problem is that this is all malware trying to anti-malware trying to do stuff on behalf of the applications but what happens if applications can become active participants in their own defense what happens if PowerShell everytime is asked to evaluate a script block like you saw with the script block logging what happens if it says Windows Defender is this still safe to run like I know you said it was safe to run the script that downloaded content from the internet but this is the content that it just downloaded is this still safe to run that has absolutely become a turning point for AV on Windows we're seeing tens of thousands of people every month being protected by signatures that the defender team was able to write against the anti-malware scan interface that would have otherwise passed through this basic file and network based analysis so it's an incredible improvement in the AV industry defender was the first to adopt it but we're seeing a bunch of other EDRs and AV engines adopt this as well so if you have an AV engine you for sure when I ask them are they listening to the amp C Channel on Windows 10 because anybody that's not is kind of stuck in the old ages now you start to ask yourself like okay script lock logging like I'm sold but I'm not really super sure on the security of all these scripts like did somebody pack in a password I don't really want an attacker with access to machine to have access to passwords that were on all these things so what we introduced with something called protected event logging now what you can do with protected event logging it's based on the magic of something called public and private private key crypto the idea there is that you have two keys one key use is used to encrypt content this is it's a public key this is something that you can put on blog posts you can scream it from the from the rooftops deploy to every machine you're fine because the magic is you forward all of your event logs into your event management system or something like a your UN UNC shares and from there you have the private key and you're the only one with that private key so you can decrypt all the content but that's the magic right since that was a private key that's the only thing that can decrypt content an attacker on the machine they don't have the ability to decrypt the event logs and see what was logged so this is an incredibly useful feature if you're concerned about the information disclosure that might happen from windows event logging so in the topic of event logging there's a bunch of useful PowerShell events now I'll point out that this slide only talks about PowerShell specifically there is a great post that Microsoft has put up which talks about just broadly system-wide what events you should be looking at there's a bunch of great white papers on wefts windows event forwarding jessica pane has a bunch of great blog posts if you're not already centralizing and collecting these things absolutely that's the first thing you should do there's a couple events that are really really useful to start monitoring if you're not there's a great white paper from fire I linked to right here where they do talk about here's how we're we've used these events and real incidents to understand how PowerShell was being used in a system one thing that you might not know which is pretty cool if you have PowerShell version 5 we have something called automatic event logging so when we were developing PowerShell version 5 the approach we took is we went through and looked at all the attack frameworks out there and we took a look at what are some common techniques that they're using in terms of common net api's common invocation patterns we baked those into the PowerShell engine itself so if we see that a script being run is kind of like using some of those same techniques we're gonna log it anyways the important point to realize that this is like a hey we we got you if you've forgotten to enable the full script block logging don't think about it as a intrusion detection system the source code for this protected event or this this event logging automatic event logging the sources on github attackers cannon well we'll reverse engineer how it's done so don't treat it like it's a panache or it's gonna save you all the time but what it does help is if the system has been compromised and you haven't had the chance to get it get around to enabling event logging this is a chance that you're still going to be able to extract some useful details about it so from the perspective of the the logging my favorite story about the impact of security transparency and visibility when it comes to PowerShell comes from fire I so there was a customer that they were responding to an incident response on they were this customer is being compromised by a PT 29 so this is Russian state-sponsored attacks you're literally going against a nearly infinitely funded government they were they were trying to remediate this customer and this customer was getting machines compromised faster than they could kind of circle around the wagons and figure out what was going on before they can remediate machines so it was getting worse and it was getting worse the problem is advanced attackers use that mitre attack framework not exactly it but they just live off the land they do whatever they can with whatever is available so they were using Python they were using Perl they're using PowerShell batch files like WMI women just everything right it doesn't really matter once they have credentials and the ability to compromise a system so they were starting to really wonder how they're gonna remediate this customer they took one critical step that critical step was to install the security transparency enhancements that we did to PowerShell version 5 we also had a during that time we had a version that was available for PowerShell version 4 so they hadn't installed the version 4 PowerShell version 4 and immediately this thing became an open source engagement they could see when the attackers were using PowerShell they could see exactly what systems they were connecting to they could see exactly what source code they were using exactly what creds they were using everything it's like the attacker was saying hey we're about to do this or we just did this these are the machines that we connected to they did that one thing and that became the linchpin of the entire investigation they were able to start finally unfurling what was happening and that became the break that they were able to use to finally remediate and and help this customer that's from one thing that's from enabling PowerShell script block logging when nothing else had that security transparency it's a strength another thing that many questions about some security transparency before I go on we got about three days for this presentation so I'm happy to take questions at any point Ashley I had it in a version of the slide and I don't have it in my short-term memory it's it started off slow now there's I think five or six it's really starting to pick up pick up steam so we're getting some great responses from some vendors kaspersky for sure has got it silence has it so it's just really starting to pick up some steam defender has had it since 2006 or no no 2016 something like that obviously we work with them now when you start recording all these event logs one of the things that I think there's a huge opportunity for in the industry is around post-processing event logs we're kind of in this world of dump them into a SEM you know like Splunk or something like that and just do regex is against it we have so much more opportunity than that so we're gonna take a little deep dive here I showed you some of that obfuscated stuff before and how scary that can be it's a scary scary time seeing that in your event logs so what can we do about this using the power of event logging and post-processing event logs so this is some research Daniel Bohannon he is a investigator at fire I mandiant he's responded to a lot of breaches and one of the things he was seeing was more and more breaches using obfuscation techniques to bypass really trivial reg X's that people were using in their defense products so this is us talking at a black hat and Def Con this year it's a small little security conference I promise I've changed in the meantime but he's a great guy so what he did was he started writing this obfuscation framework to demonstrate the kind of techniques he was actually seeing in the wild now people get frustrated that he released this tool but all he did is shine light on a problem that existed in spades I did guilt-trip him I give him a good old guilt trip and we worked together and we worked on this project called revoke obfuscation so this is the ability of using the the massive benefits of PowerShell logging PowerShell and all this kind of stuff to find a way to start to unfurl some of this problem that we have with obfuscated payloads now what we're first going to talk about is the problem that exists in the industry now the first step obviously like the first step in any Incident Response is you've got to have logs you got to centralized and you got to collect them that is absolutely the baseline make sure you're collecting 46 88 which is the process command lines PowerShell script block logs you could do this with the built-in Windows stuff you can do this with sysinternals sis Mon Jeffrey is like hey he's not as good-looking as me I should be up there and I decided that there's just so much awesome for one slide so the thing to remember though is enable your logs because attacker is as nice as they are aren't in the habit of doing it for you so might as well do it before they get there so let's pretend this is honestly the canonical detection challenge is how do you take something like CMD calling PowerShell to run a payload what do you do to detect that people do all kinds of stuff like reg X is against CMD and the parent process command line and all this kind of stuff to see what they can do the reality of the problem by the way this is like 15 20 minutes we go into so much more detail in the revoke obfuscation talk itself this is an example from thin eight so this is a financially motivated attacker who uses all kinds of stuff against the financial sector this is the kind of thing that they do to obfuscate this sort of parent process command line tracking you see at the top there they're setting some environment variables and then they're finally kind of chaining these environment variables together piping it into PI Rachelle's standard input and then running that thing so when you take a look at your event logs for what happened here based on process command line logging alone all you're gonna see is a command line running with some environment variables piped into environment variables and you have no idea what's happening another trick that people will try to do is they'll try to say well word launching CMD launching PowerShell well that's for sure bad so they'll try to do some intelligence based on command like parent process lineage that helps but it's also not the be-all and end-all here's an example where you have one process that just launches basically a dummy process with a kind of interesting command line always just doing is setting a window title but what you can do is now launched a second process that thing can scrape through WMI for any processes that were launched with the given command line extract out the latter half of that and then run that invoke expression so now these things aren't shared by any sort of parent process command chain but you're still able to bypass and start to do message passing between two processes without it going through the parent process at all obviously things like files and other things or other opportunities for information passing between two processes this breaks all kinds of detection but this isn't where it gets bad you think that's kind of complicated there's one thing that almost all attackers and this is called the powershell download cradle when they're using PowerShell there's almost I talked about those word Docs where they were just got there but what they really did is download more stuff and run that so this is an example of a PowerShell download cradle we're using new object system net web client download string whatever like this is almost canonical you see this in the veil framework powersploit Metasploit is everywhere almost exactly these terms so as an it defender you might say all right games on I'm blocking you so let's take a look at that download cradle what are your options well invoke expression I can take off that I've got new object system net web client maybe I'm looking for the method of download string where this thing is joined with a URL alright so maybe this is a good thing I can start to use my SEM start to do some stuff to try to write signatures against this I see some eyebrows going like this anybody with experience with PowerShell I tell you this stuff blows people's minds they're like but who would use my baby for such evil I tell ya so let's talk about why some of these assumptions are dangerous well obviously new object you don't need the system prefix so blow that net web client works download string well that HTTP you can just fix that you could do some string concatenation now HTTP will never show up so ixnay on that turns out download string isn't the only way to get stuff from the internet you can download files you can download data you can download data async so scratch that what about starting to use some escape characters on that method name doesn't matter what method you thought you were gonna protect against escape characters are gonna screw you you can also do the same thing on new object right maybe I thought net web client was going to be my Savior no I can do the same sort of escape shenanigans there I can do string concatenation I can do put things in variables and them again starting to lose some faith new object good thing is that new object doesn't have any aliases so new object is safe anyone here use get command yeah if I don't see all hands I know you're lying okay get command yeah everyone uses it it's great turns out I can use invoke expression on the result so you know whatever you're still using new object but of course we've got the invocation operators you're like no one uses invoke expression that's for noobs I use the ampersand operator yep that's gonna get you now the other thing to realize here is that wildcards right get command is a search utility what if I say new object right obviously I can now search for the new object command that's what get command is for I can do this this this this this this all of these work to return the new object command lit so you thought you're writing a stake against new object I'm sorry to tell you you're not don't forget get command new object didn't have aliases but get command does so you can do this against GCM but PowerShell is super helpful when you drop the getter on any command Lynnae m-- powershell will think maybe you meant get if it fails to find it so really command you've also got aliases and their alias forget alias which is alias so i don't know what are you gonna do here you can't block new object do you like regex all the things like honestly at this point you're like ready to throw it in maybe maybe flag on this hill and VOC expression boom I'm gonna catch this I know a VOC expression has all the same issues that new object had all the same issues that get command had aside from the fact that it kills dogs and puppies and cats but here's a thing this is the real kicker when you do an analysis of broad use of PowerShell you know blocking invoke expression this is used in three percent or more of scripts in the wild you're like I never use it so maybe in your part of the world it's down to one percent but it's you're not blocking invoke expression so obviously I said it's a little bit of shock things are in bad shape kind of that's the extent of PowerShell obfuscate no just kidding you can reverse strings how about you split them based on an operator maybe you're gonna replace things in a string bring it back when invoke expression in that maybe you're gonna do some string concatenation maybe you're gonna do a tool that does all this stuff for you yeah this is bad bad news like I can't even keep up with this and I wrote a half of it so whatever so here's here's where some of that crazy stuff comes from and I've had countless people at security conferences ask me like dude why did you guys have to write all that stuff in pyroshow like can't we just remove that obfuscation stuff I'm like have you seen anything in the real world like together yeah it kind of sucks it's kind of crazy but any one of these things like remove get command from the system I don't think so right this is a real problem this is an example of a PT 32 this is like literally stuff that they use in there and their attacks if you think your regex in this not gonna happen that was all everything I was just talking about was against a standard download cradle but what happens if you start using different approaches to download content so there's another tool invoke cradle crafter that generates new styles of download cradles and shows some of the massive ways that you can download stuff of the Internet here's an example from 2010 I'll give you four seconds and I'll ask you what it does I don't know it's something like hello world this is this was somebody just doing like PowerShell golf having some fun in a forum in 2010 this one didn't contain malicious content but it could've here's an example where somebody has used not only know like ASCII characters but there's not even any variable names all the variable names are whitespace if you think that's bad what about if it was always spaced this is legit PowerShell this works you're proud of it so as a defender an attack her you're like game over I'm I don't know I'm gonna get into something more simple like cutting down trees or something like that but I will warn you we are not done yet so what we decided to do obviously there is something we can do we wouldn't be here today if it was like huh this sucks time to get into a new career take a look at this none of this is normal anybody here is like doesn't know what it does but can say absolutely this is sketchy like I don't know what it does but I would like to take a second look thank you very much the only question is I can't be asking you guys is this sketchy is there any way that we can have a computer saying yes this is sketchy or not so one of the ways that we first investigated was character frequency analysis when you take a look at it you're like one of the major signs that I saw was like a lot of backticks or a lot of curly braces and stuff so here's an analysis of character frequency across all of posh code yeah on the right hand side it looks kind of like English a lot of stuff based on variable names and comments on the left hand side you can see some character frequency analysis of both of these office cated scripts and you can see that these are quite different so we might be onto something here the and there is a way to compare to list some numbers to figure out how similar they are and I apologize I'm gonna math right now cosine similarity so this is a thing that most of us learned in you know college or high school cosine is the angle between two two lines now that is represented by two numbers so there's a technique to figure out how close two lines are by doing some math here it's up here because it makes me look smart now you can extend the same technique to not just two numbers three numbers four numbers or you know 4050 numbers like I showed before from character frequency analysis so what happens when we take cosine similarity which is a similarity metric and apply it to something like forty numbers that represent character frequency this is pretty good stuff if you take a look at most scripts they're up in the like 90% plus similarity range where any of these obfuscated scripts they were down here at like 0.15 7 3 7 9 very very dissimilar than the average script you might see on posh code so it feels like we're on to something right if you take a look where you actually take a look at the grouping of these similarities this is an analysis of all of posh code and you see there's a great clustering above about 0.8 they're all pretty similar to each other in terms of their character frequency and what's left you know below that that's honestly pretty reasonable to evaluate that's maybe 30 40 scripts out of 3,500 yeah that's like maybe an hour's work if that to just page through decide whether they're doing anything sketchy or not so that's that's a really promising result that's pretty exciting but the turn point is like posh code isn't the only thing out there we did need more data that was based on some assumptions we looked at the office gated stuff yeah most of it was things like people trying to figure out how short they could make the powershell for doing a Christmas tree and stuff so our community love to do like short one-liners so we ran a little PowerShell contest a couple years ago called the underhanded PowerShell contest there is one goal for this contest which was we're going to give you a simple task try to find ways to evaluate some static signatures that we wrote and we got amazing amounts of creative things people just doing all kinds of things like well I'm gonna use ad type and do it that way I'm gonna do it this way so we got a lot of scripts out of the underhanded PowerShell contest of people intentionally trying to evade static detection so gold right we also did more we reached out to github so a little background story here github has an API that lets you enumerate projects public projects and we wanted to enumerate every public project that used that was kind of identified as being primarily PowerShell so I did a analysis and it was like 10 million repos and so I was they had this script going github of course has a throttling policy where they say be nice don't hit us too hard so I had this PowerShell script literally for a month waiting for its throttle policy download a bunch more weight this was thing what's going on it's getting to like nine million nine point five million I'm like the end is almost near it gets to 10 million 11 million I'm like what what's going on here i double-checked my numbers there was a hundred million github projects that i was gonna have to go against and I did not have eleven months for this script to run so I reached out to the kind folks at github and I was like here's our problem like oh yeah the problem some guy over lunch made a zip file of all the public projects that use PowerShell and gave it to me it was like oh but it was such a sweet script so anyway sometimes diplomacy works so we went against github TechNet basically everything that exists so first a word of thanks this is everybody that was involved in a one of the projects that we used if you contributed to anything posh code github if you've ever posted things anything publicly thank you you have your on this I'll save some time at the end for you to find your name is anybody here part of this research poop your hands I want to take a photo for Daniel if you've ever done anything public awesome he's gonna be so jazzed what's that this isn't no so thank you you absolutely made this research possible so guess what we found there's some scary stuff out there I'll tell you here's an example of just the depths of depravity that humanity has this is a script somebody really likes there their productivity evidently so they pushed out a script across the whole enterprise that if they ever saw any built-in games running it would kill him and not only kill him but kill him with spite they would remove the file from from the Program Files directory afterwards so thank you captain buzzkill you're a part of this research so some statistics about what this ended up being nearly half a million scripts downloaded some of them from here 30,000 authors were involved in this and to give you like some idea of the scope of the humanity I added up all the scripts that I've ever written PowerShell cookbook every tool I've done everything I've saved in my tools directory like everything that I could find that I ever wrote two megabytes about two megabytes that's a lot of scripts but when it comes down to it this thing was for gigs just the amount of distributed around the world and shared publicly never ceases to amaze me it does it's an amazing community if we go back and take a look at that similarity metric that we were we're really happy about this right this is like some great grouping this is the way that data scientists measure the value of an algorithm there's two parts you've got precision and you've got recall so precision this is when something says that for example this is obfuscated how often is it correct so this is where we were great if you take a look here 89% of the time that based on character frequency analysis alone if it said it was office cated it was correct and because we had done all that manual labeling of like 7,000 powershell scripts we now have a ground truth of what is obfuscated and what is not the real kicker is recall so recall the definition of recall is of all the obfuscated stuff out there how much of it did you detect so this is the problem what happened it's great at finding stuff that's obfuscated but up in that zero point eight category there was a lot of stuff that we would have identified just with personal code review we would have identified this as being obfuscated but it wasn't detected as obfuscated by the character frequency analysis so a very very promising and it's something that's useful to have in your arsenal but it's not the be-all and end-all we can do better right this is PowerShell we had all the power at our disposal there's got to be something better than character frequency analysis yes you know I'm surprised this year at the summit I didn't see any sessions talking about the ast or anything based on the tokenizer but it is one of the things that makes PowerShell a crazy crazy platform for doing deep deep analysis so the first stage that PowerShell goes through when it evaluates any of your scripts is the tokenizer that's the kind of an initial chopping of your script into segments it can recognize that something as a command or a parameter or a string the second step after tokenizing that PowerShell does is it makes an AST so this is the abstract syntax tree and this is a tree like representation of your PowerShell script so you can now start to see things like relationships like this for loop has this variable in it or this sub expression has some of the things here so this is an example of the ast for that same purse but that opens up some really really exciting opportunities when it comes to advanced analysis against any of these things so let's take a look at this now we don't have to just go against character frequency analysis what we can do is to start look for patterns so for example this script uses a lot of binary operators or this thing uses concatenation operators a lot or this thing has a lot of parentheses or this thing as a ratio to other scripts does a bunch of things any of those ast nodes we can now start to do analysis against them their frequency their deviation all this stuff and out of that we can get 5,000 features to kind of thumbprint a script imagine given a script and then I'm gonna pull out 5,000 numbers that you can now decide whether this thing is obfuscated or not this is more than just character frequency analysis this is based on the syntax and patterns of the script itself does it have a lot of comments or not that kind of thing now first you celebrate then you realize like oh my god 5,000 features what am I gonna do with 5,000 features I don't even want to write them all down by hand let alone make decisions based on them and there's a technique out there this is a you could have a linear regression this this formula represents a linear regression and it's based on a very simple idea where you say all these 5000 features well some of them are more important than others yeah that's an easy statement to say so I'm gonna assign weights that represent importance that's what I'm going to do every feature multiply it by its weight or its importance and the end of that I get is just some number and it is above some threshold then it's obfuscated if it's below that threshold then it's not so that's a pretty simple concept and what you get here that that linear regression is a very common statistical technique you can do a linear regression in Excel like it's just it's everywhere it's as you saw it the math is relatively simple one of the things that happens is you'll start to add in new features so that there's this thing called a logit function one of the issues when you run a linear regression is that those weights and those features tend to be kind of rangy right some thing is between 0 & 1 some things are between minus 100 and plus 200,000 so this this logit function is a way to compress the range of some of these things back into kind of a standard range so you combine a linear regression plus a logit function and that's where you get this fancy new word called a logistic regression and is really really a simple simple concept so look at this another great math slide to make me look like a smart guy so awesome I didn't answer the question though you're likely you just talked more math at me how do we figure out the importance of these weights that is really the core of all of this is how do I take a bunch of features and a bunch of weights and decide the importance of the weights the answer here is called the gradient descent it's another fancy word but honestly it's a simple concept and the approach you take here is I assume just basically random weights like hey was how important is a left paren you know 250 how important is a + operator 512 like you randomly make stuff up but the benefit of all that work we did to label data now what we can say is I'm gonna run this algorithm with those randomized weights and I'm gonna see how it compares to actual values that somebody labeled by hand and said this is obfuscated or it's not now the magic of this gradient descent is when when our formula is wrong you know it gives you some degree of error then you can take that error and feed it back through all those weights and so the weights that were big and really contributed to that error well you've reduced them a little bit and you do this a lot a lot a lot that's the benefit of computers that they'll just do things forever you this a lot and then you get a set of weights that can accurately predict the difference between obfuscated and non obfuscated content based on that relatively simple formula so how did this do right so we started off with 98 and nine percent precision 37 percent recall so I'd be pretty happy if we got down to like ninety percent precision because that precision was awesome maybe 60 percent recall like I'd be pretty happy check this out stunning with the power of powershell AST analysis we're able to detect 94% of obfuscated scripts so detecting ten times better at this obfuscated content with half the false positives that we did before it's incredible anybody want to see a demo yeah absolutely so revoke confiscation we published this work as revoke confiscation this is up on the PowerShell gallery import or install a module revoke obfuscation so it breaks into a couple parts now Daniel he's a sucker for ASCII art when you start it revoke obfuscation is the tool that you can run this is basically his outlet like you you give a kid some paint and like leave them alone in a padded room like you're sure that you've kind of constrained their creativity so he went crazy on this basically GUI for revoke obfuscation but by the way in here you see there's credits that's gonna generate a random credit out of the contributors so install this module type credits enough time then you'll see you name eventually and so it's all backed on commandlets of course everybody here knows it's got to be Commandments and objects no killing puppies many puppies were killed in the creation of this GUI but not in the other one now one of the big things about script block logging is that they get broken up into a couple pieces in the Windows Event log so this this get our vo script block command lit that ships as part of revoke obfuscation will automatically rejoin them for you so then you can start you can point it at an Eevee TX file or there is a gesture for Splunk and it will recreate these bring them back together so then you can start to do some analysis against full script blocks so that's pretty cool but where it really matters is when you pipe this into measure R vo alpha station so this is incredibly high performance going against the powershell AST s going through all of that that math and data science that we did and giving you a single boolean answer that you can run against the script block and decide whether this thing is obfuscated or not here you can see that it detected alpha station here and it also shows all of the ast features that it extracted from that script that helped to make that decision now that's pretty awesome you could put this on any of your endpoints that are doing log ingestion and enrich all your data for example with weather revoke obfuscation thought that the script block might have been obfuscated so we did is we turned what attackers thought was like hey I'm hiding I'm office gating everything we turned that into a a laser sharp focus on hey I'm an attacker come get me this is an amazing turn of the tides when it comes from the attacker defender mindset but one of the great things that I'm really really excited about when it comes to industry is that you can start to do things like leverage awesome research like this at scale so anybody here a part of defender ATP a couple people so fireEye mandiant fireEye they've been using revoke obfuscation as part of incident responses for quite a while and they've been really excited by it this has also been invoked not like literally exactly the code but a version of revoke confiscation has been incorporated into defender ATP you have defender ATP installed in your systems and it will automatically flag when it finds some powershell that it thinks is suspicious you can have let's go on for this or you can use this to enrich existing alerts so it becomes a really great signal that as we start to move to cloud driven intelligence that defenders can start to leverage this stuff centrally and not have to do it off on every system so we've been focusing for for some time any questions about revoke obfuscation yeah question over there yeah so the question was how does this relate to the attack surface reduction they're working on some of the same same concepts they do now have a category attack surface reduction is a new feature in an experiment in Windows 10 that lets you either block or audit potentially obfuscated use of PowerShell and other things to BB script and stuff so that's a feature that they're working on and it's influenced by some of these same techniques and some same approaches any other questions with that cool so we've talked for some time about kind of it the note level threats node level perspective in terms of logging and all this kind of stuff I do want to take a step back though and we when we stop talking about node level stuff it's important to step back and and let's revisit what apt looks like so mandiant every year does this thing called the EM trends report so they report on trends in in the environment you know any new apts that they found one that they found and it was broadly impacting enough to really make a difference to make it into this report here are their TTP's tools techniques and practices if you're not heartbroken right now that an apt was able to be massively successful with a batch file a slightly modified version of an attack tool and PS exec my heart's broken anybody who talks about anything advanced to see that a massively successful attack campaign can be really enabled by this like hook sometimes you just want to hang your head up and cry but here's a thing I think this is setting up an interesting move from it's a demonstration of the dangers of general-purpose architectures general-purpose computers and we can start to move our thoughts away from a bunch of nodes that can do anything - how can we move - starting to specialize her infrastructure and specialize our our architecture specialize the purposes of our device so if anybody saw Jeffrey's talk before we've been talking about Azure stack and this has been an amazing example of where we've been able to take a very very important security critical system and go through a system thinking approach of really really locking it down locking down management access to it locking down what it can do take an assumed breach an approach that says when something's in the system we know what's supposed to be there and what's not so we can take really really aggressive approaches on the inside of the fabric so the question is how does powerful play in all this this is the problem I talked about the device guards just right you block things well the minute you think you're blocking everything somebody finds like one little tweak on what you've blocked hmm they're through when you change your approach to say instead I'm gonna be explicit on what I allow well yeah that's great that's great security if you can do that now the thing that might be a challenge is you're like I use PowerShell anybody in this room knows the PowerShell power of PowerShell and they know that if you're blocking all X's and dll's if you don't handle PowerShell somehow then you're still providing full access to win32 api is an incredible amount of power not news to us one of the things that we introduced in PowerShell is called constrained language mode so this started and as part of Windows RT does anybody remember that Windows 8.1 this was the precursor to Windows 10 s so this is a version of Windows that only runs approved software all that kind of stuff and as part of that we worked very very closely with the device guard team to create a version of PowerShell that is great I just I love how it works if a script is trust did you know as part of your official policy it's allowed to run with full access to the dotnet framework every everything that you used to today in PowerShell now if it's not so if somebody just using your system or malware trying to abuse PowerShell it's gonna get restricted to a constrained version of the PowerShell language so what might not surprise you is this still has simple things like loops and switch statements and variables and all that functions like it's still it's still a nice language the one thing that we did though is we took away the things that tend to be used to make applications or the things that tend to be used to exploit the system via PowerShell so here's an example of a system with device guard you see an example script up there it's running dotnet code whatever this is part of your device guard policy you see that first line it was able to run the script just fine so as a management technique you can do anything that you ever could possibly do now somebody interactive on this system who is running unapproved or unseen code well they're allowed to run the script but that they try to do that exact same code try to run some net well PowerShell is gonna block it it says that that capability does not exist in constrain language mode and maybe they try to be tricky right they try to change the file itself and put their own code into the file and run that file well every well-written device guard policy uses code signing or file hashing as a way to figure out what's allowed onto that system and so by somebody changing the file that file now backs down into constrain language mode and they're no better off than they were before so some of the things in constrain language mode we've blocked access to dotnet comm objects win32 api is add type basically the thing is that attackers use to abuse powershell you still have you know the funny thing about constraint language mode was when we were developing it I enable it and like honestly just forget for days time using powershell get processed stop processing all that just database stuff just works just commandlets basic scripting and then after a couple days I get this error that I can't do this thing because I'm in constrained language mode I was like two days ago I changed this how did I just realize this now it is a very very useful version of PowerShell as a way to remove and eliminate attack surface the one thing I will point out it's not an hour back style sandbox like Gaea and I'm gonna talk about Gaea in a second it's not a sandbox people can still run commandlets what it does do is prevent you from running kind of just arbitrary code so you're awesome right you've you've done things like enabled logging all the stuff checked all the boxes are you done just about there's one thing to be careful about and when it comes to system configuration we did a bunch of awesome stuff in PowerShell version 5 my regret to this day is that we didn't invent time travel that's a problem well we didn't do we were not able to ship security fixes back from into PowerShell version 2 which we did in 2008 now attackers and red teamers are starting to realize that this is an issue and so what they've done is attacks rather than just using PowerShell they might use PowerShell bash version 2 and all their stuff all that fancy stuff that you brought in for script block logging and all this kind of stuff that might not be lit up in version 2 and you might be blind to what's happening there's ways to detect this at the top here it shows the event logs show PowerShell loading the v2 engine but the best thing to do is to remove v2 once you've got v5 there's really no reason to have the two installed you can uninstall the windows feature audit for it being launched you can also use a device guard or app lock or policy to block access to those dll's and prevent prevent that attack yeah question that's a good question so the question is what about an upgrade attack right so PowerShell 6 is it the same thing as PowerShell version 5 and I think the real interesting question is it's available on github somebody no matter what's in github can like just remove the lines they don't like as an attacker and then bring that in but that comes down to the question of well hey no problem you've got a whitelist of application protection policy if you didn't say that there custom-build of PowerShell that hacked out all that stuff can run then it's not gonna run so that's really the way to think about it PowerShell version 6 as we're shipping it does have access to all these things and so there's a couple differences when it comes to gyah but but it's there so I've talked about jiya a couple times now the yeah question the question is what if you're in a situation of not being able to remove version 2 because of dependencies and at that point you start to get into mitigation policies so for example you can decide which systems need those dependencies and roll out something broadly and leave those systems enabled or you can do something like audit the use of PowerShell if you're if you're using it from a specific application then that thing you can in the PowerShell Event log C word launched PowerShell with this that might raise red flags versus something else that didn't you could also with AppLocker you can deploy user specific policies so really really you can get rich when it comes to blocking specific issues in specific systems the important point to make and I've realized this time and time again is don't let the the noise ruin your day set a broad policy like we are blocking it if people say well I need it say sure have it you're still way better off than you were before you said we're gonna block it because now you have 98 percent of the systems where you've been able to block it so just enough administration this is another great example of being able to take what some people consider a liability which is you know PowerShell PowerShell remoting they get really scared about all the news they hear but instead flipping it to absolutely a strength we have three sessions I'm not going to go very deep into Gaea we have one that's going to be talking about some of the tool sets we've got a bit of a lab on it and then we've got another one based on web technologies so I'm not going to dig deep into it if you really are interested in what we talked about today for Gaea any of these sessions are gonna be down your alley but the idea is here's an attacker here's a server this guy is Benjamin Delfy he's the author of mimic cats he's actually a nice guy I asked him if I could put this on on my slide and so he's a cool guy he's fun and he's also really respectful he's a researcher that is absolutely moving the ball forward when it comes to helping people realize the the dangers in their actual systems no I asked him to take it off for his mug shot so let's say what happens here you got an attacker you got a server so the attacker tries to RDP and the problem is they're not always attackers right sometimes their an attacker using legitimate credentials that they stole or maybe they're using the literally an attacker maybe it's an insider threat so this person tries to attack a server tries to RDP into there doesn't work they know the guy to talk to you Jeffrey Jeffrey can I be an admin on this server please Jeffrey he's a guy he was not born yesterday I'll tell you that he Oh use PowerShell Connect you don't need RDP to connect to this server so of course he connects enters PS session restarts DNS does whatever he needs to do good days Jeffrey looks away for one minute goes for coffee something he tries to steal some secrets accessed tonight this would be a wonderful world if only this world existed right it does exist this is the way to think about management on Windows this is the way to think of what your attack surface it's kind of two axes you've got your time axis so how long somebody has management access and then you've got your capability access so this is what can somebody do when they have access for most people it's this whole block that all the admin all the time do everything as an industry we've been getting better with the idea of limiting time so this is the privileged Identity Management concept where I can say you're only admin when you've got a ticket or you're only admin 9:00 to 5:00 things like that you've also got the capability restriction axis and this is where Gaea really jumps in so it wouldn't be great if people only had the permission they needed to do exactly their job what if when a machine was popped it didn't leak all these high value creds and what if logging was enabled everywhere that would be B magic so this is the ideas behind just enough administration now this isn't some newfangled thing this is based on the stuff that excuse me that we've been doing with exchange online since 2008 this is battle-hardened Exchange Online has been offering remote PowerShell to the world for 10 years now it's based on some simple concepts you have roles you have endpoints where they're connecting to and then you've got identity so what identity does do the commands run to when they actually get connected so this is an example of a role capability anybody here I guarantee it can write a hash table anybody or JSON if you prefer anybody can write this if you're capable of writing this you are capable of restricting a powershell endpoint to do only what is allowed on that endpoint you can export given known commandlets you can also write your own functions that export functionality that doesn't exist another cool thing about gia is that you can use it for local sandboxing so you can set up whatever powershell launches you can set it up to now launch those local sessions when I said that constrained language wasn't a sandbox well if you want to constrain local access like a jump box for example you can allow them every PowerShell window that launches that all they get access to is a gia endpoint on that machine pretty sweet stuff so this is what you get in terms of attack surface reduction with Gia I can limit the time window that I'm vulnerable to attack I can limit the capability window of what a compromised administrator can do and you're able to get this freezer threat thin attack surface based on free stuff that exists in Windows today now you go down and you're like this is amazing I've secured my infrastructure I've got like Fort Knox yay me this is what an attacker says he's like these people know nothing I'm gonna get in anyways yeah with errormsgs my second job is in Photoshop I'll tell you that this was not from gif EECOM this is like 100 cent artisanal jiff just for you guys I said Jeff and gifts so I didn't offend anybody so this is the first thing they're gonna do when they look at a system they're gonna use nmap or something do a port sweep see what ports you have open doesn't matter if you've got the best Gaea configuration ever look at this one this person left open RDP somebody steals RDP CREZ doesn't matter what you've done to that system they're logging in as a full local administrator that system is theirs so really really really think about your network attack surface that when you're using Gaea to configure a system that all you've left is Gaea the other thing that sometimes comes up is the commands that you expose can sometimes be your vulnerabilities now shamefully like this has a bit of humility here this is an example that we gave in public documentation about how awesome Gaea is you see that we said the add computer imagine you want to give somebody some administrative access but not domain admin but what you're gonna let them do is add a computer to the domain so you expose one command let add computer so script junkie I don't know if you follow on Twitter or anything like that but he pointed out that turns out you didn't restrict the domain field at all so somebody abusing this command lit could add the computer to a malicious domain which will then can possibly send down all kinds of malicious group policies do whatever it wants to fully compromised that machine and then later join it back to your happy domain so you do got to be careful I think about it from the perspective of an attacker how can you abuse given functionality to potentially break out of what you thought were handcuffs another thing that I see sometimes is people trying to improve the user experience about of a gia session so one of the things when you create a gia session by default it to no language mode if you walk away with one thing when it comes to gia is that is the only language melody should allow I talked about the benefits of constrain language mode but it is not designed to be used at all with gia the fundamental concept in gia is it separates two things commands coming from the user and commands coming from commands right so I told you you could write a script that could do anything on this system and just expose that script for Gia and you're happy constrain language mode lets you write your own functions it's not meant to be a sandbox like this so all an attacker has to do with this no leg or constraint language mode is write their own function and now that function has complete access to the system so the one takeaway is like don't do don't break those default sit low language is our default be very aware of the danger of constrain language or anybody that you see using it now when it comes down to functions let's talk about functions this is one of the things that I think is is yet to be discovered by people as they're exposing things to a malicious attacker there is one thing to remember when you're writing a function that you're exposing on an attack surface so that you're exposing to gia that's your you know your people connecting with that function are your attack surface or when you're downloading content from the internet to run it there's one thing to think about is never trust your inputs absolutely the main thing so here's an example command injection it's just a perennial problem in systems management pretty much every router out there has been pwned by command injection vulnerabilities you go to your router as local management page and it says hey ping a IP address so that you can figure out if it's router to the internet or you to router you go to that router and instead of that IP address being one two three four you enter one two three four and and you know adduser me right so what happened there is almost all systems that do this kind of thing initially stumble on this issue where they just take arbitrary input and then run it concatenated with ping or something like that they just run it on that router so this literally almost every IOT device gets popped by this exact same thing this can happen also when you're writing a PowerShell function that you're exposing to users so if you're saying PowerShell - command user input hmm if you just took arbitrary user input and it it this way well the user input can be semicolon format C Drive or a semicolon and invoke expression whatever so there's an example of a command injection when applied to powershell of course powershell is not unique in this you could do command injection with CMD itself although I don't tend to see that once people have sipped the fine line of PowerShell there's another whole class of vulnerability here which is script injection so script injection every language has it people are very very comfortable with the word sequel injection but the idea behind anything injection is I take arbitrary content from a user and then I run it I ask the engine of choice so rerun it on my behalf so I took some user input here run it through invoke expression similar to the way that command injection works the user can just do semicolon add type whatever and just run whatever code they want this is extremely common I see this all the time invoke expression is almost never needed in PowerShell there's so many different ways with the invocation operator and splatting and all this kind of stuff to marshal user input very very safely into a commandant parameter with ever without ever going to invoke expression there's some obscure forms of this as well you see here but it all comes down to some sort of script injection now there are a lot of smart people out there that realize the danger of script injection and what they'll do is it'll say I know how to prevent this what I'm gonna do is I'm going to take the user input put it in single quotes and then if there's any single quotes that are part of the user input then I'm gonna escape them with more single quotes and kind of like constrain them to this single quote jail that's kind of the technique that people use to prevent sequel injection and it's sometimes you got to do it rarely you do but sometimes you got to do that here is the challenge para shell was raised in a world of outlook oh wow WordPress where all these things want to make your emails look beautiful right so you put a straight quote it makes it a curly quote you put in a straight single quote it makes it a curly single quote so PowerShell was raised in this world and power shells tokenizer and parser has three different quotes for each there are three different single quotes there are three different double quotes so somebody who is just escaping the kind of straight ASCII version is still vulnerable because somebody can pack in their payload with like the lower left hanging German double quote you know this this stuff is absolutely possible so unsafe escaping is a super danger you've also got some things a script block injection is kind of like script injection where you're creating script blocks out of raw strings this is sometimes you sometimes see this when you're making further remoting connections based on user input you've got expand string some people use expand string as the way to figure out the value of a variable it's kind of like invoke expression you can still do pipelines and some things within an expand string call you've got Method injection so user input this is a way to make it invoke arbitrary methods ad type kena sucks you know ad type I've seen this a lot ad type runs arbitrary C sharp if you're taking user input and packing it into a C sharp statement then the attacker can just do the equivalent of sequel injection or the equivalent of PowerShell injection by doing C sharp injection escape a lot of everything that you've finished and then start invoking and creating arbitrary net types and classes and and then you're completely compromised so that's a danger and you might say see some sad people I am NOT here as the death and doomsayer I do not have a sickle or a scythe there are ways that you can defend yourself against all these things recognize this word PowerShell ast I'm telling you is gold if you haven't seen this one I look download the show PS ast module from the PowerShell gallery you can just explore what PowerShell sees and the way that it understands your PowerShell scripts is awesome so here's an example that we enabled in PowerShell this last line here every ast object has this method called find all it takes a predicate and basically a predicate is just a fancy term for a script block so what it'll do is a script block that you give it it'll run it that script block against every node in the ast the idea behind a predicate is kind of like where object where it returns true or false on whether something is interesting to you or not so with this predicate you can do things like here's an example where based on the incoming ast I'm gonna return true if it's an invoke member expression AST so you're invoking a method invoking a property and the member value itself the member name if that thing isn't a constant so if it's not just like they written in there if it's a string with a variable or if it's a late bound variable any of that stuff this is kind of like a really complicated where object to find me all ast nodes that invoke a member or that member was not known at compile time so that's pretty awesome stuff like that's a really complicated rule to run against an entire AST this isn't something that you have to do by yourself though because we have this kind of capability this is exactly the foundation of the PowerShell script analyzer this is part of PowerShell part of Windows we're continually updating it on github and the PowerShell gallery so you could take the PowerShell script analyzer and write modules with predicates like the one that I showed to start to find things that you might be worried about in your scripts maybe there's some things that you know that are specific to your environment where if I ever see like this exact string then I know things are bad you can write ast things to find out did you ever have a script with a password in it for example now all the stuff that I talked about we have encoded this into a module on the PowerShell gallery called power shell injection hunter so you could install this module from the PowerShell gallery I will admit there's no docs on it yet there's no blog post on it yet the only reason I'm talking to you about it is because I know that you're capable of figuring it out so the injection hunter is a module that encodes all of the stuff that I just told you to worry about into ast based rules that run against the script analyzer so you can just run invoke script analyzer with this module against a directory or a stripped or whatever and it's gonna find out all the parts that you should be worrying about and those scripts that might be part of your attack surface so consider it like a buddy code reviewer it's not necessarily that they're like exact pwnage but it will help you say oh I should take a look at this a little bit deeper now when you do that at scale we're starts to get interesting visual studio code has integration with the script analyzer you can configure a Visual Studio code to look into your module path add new script analyzer commands to it so this is an example of as you're just writing a PowerShell script like it says don't use aliases or like it says you have a variable that's never been assigned to it can now tell you you're just about to use unsafe escaping this is a security vulnerability and it even gives you the remediation of what you should do instead so I think you know if we think back to last week when this presentation started we're at a point now where we've had what God attackers into PowerShell was this promise of in memory only this is like super legit leap attacks all this kind of stuff this is a way to escape any defenders what we've seen over the last years you know it was really eye-opening at a bunch of security conferences this year at blackhat Def Con blue hat is Microsoft's internal security conference Derby con like huge conferences where red teamers are up there and they're saying honestly this stuff sketches me out you got to start running because your days are numbered if you're using PowerShell as an exploit technique so Chris Chris Thompson gave a great presentation this year about talking about some of this stuff and he was like you promised us as red teamers you promised us freedom with PowerShell you deliver slavery instead the amount of insight that a defender can bring to any attacker that uses PowerShell is phenomenal it is far beyond anything that you can get with anything else out there and is absolutely in your best interest to funnel everything you can into your strengths button up lock up and let him at it this is a great paraphrasing so Matt Graber he is a powershell MVP he's an extremely advanced powershell user just a great demonstration of what every researcher should be and he started saying you know what honestly with all this stuff I am moving away and I think it makes sense to move away from PowerShell because there are so many things out there so we got your back you got your back thank you appreciate your time [Applause]
Info
Channel: PowerShell.org
Views: 6,268
Rating: 5 out of 5
Keywords: powershell, windows powershell, techsession, powershell summit
Id: M5bkHUQy-JA
Channel Id: undefined
Length: 100min 15sec (6015 seconds)
Published: Wed May 02 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.