We're sorry but this page doesn't work properly without JavaScript enabled. Please enable it to continue.
Feedback

Defending against PowerShell attacks - in theory, and in practice

00:00

Formal Metadata

Title
Defending against PowerShell attacks - in theory, and in practice
Title of Series
Number of Parts
60
Author
License
CC Attribution - ShareAlike 3.0 Unported:
You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal and non-commercial purpose as long as the work is attributed to the author in the manner specified by the author or licensor and the work or content is shared also in adapted form only under the conditions of this
Identifiers
Publisher
Release Date
Language
Producer
Production Year2018

Content Metadata

Subject Area
Genre
Abstract
Learn how attackers are using PowerShell and how to defend against those attacks.
TheoryData managementInformation securityInformation securityData managementMereologySoftware developerAuthorizationBitEmailInheritance (object-oriented programming)Computer animation
TheoryContent (media)WordRevision controlExecution unitIncidence algebraDependent and independent variablesOffice suiteEmailThread (computing)Gastropod shellCodeMalwarePhysical systemVisualization (computer graphics)WindowCore dumpMiniDiscPattern languageBootingSoftware development kitCartesian coordinate systemProcess (computing)Computer animationLecture/Conference
SummierbarkeitTheoryTwitterMereologyComputing platformRepresentation (politics)Computer wormIncidence algebraDependent and independent variablesPersonal digital assistantMacro (computer science)MalwareCodierung <Programmierung>Real numberAverageComputer animation
TheoryStatisticsDistribution (mathematics)Codierung <Programmierung>Formal grammarCountingSoftware engineeringScripting languageObject (grammar)Coma BerenicesStructural loadMacro (computer science)VisualBASICComputer configurationVirtual machineBlock (periodic table)Physical systemGateway (telecommunications)SpreadsheetExecution unitBitCodeEmailIntegrated development environmentInformation securityDifferent (Kate Ryan album)Software frameworkVulnerability (computing)Video gameSoftware testingBlock (periodic table)Virtual machineStapeldateiComputer configurationPerspective (visual)Computer animation
Information securityAddress spaceTheoryBlock (periodic table)Data managementAddress spaceInformation securityBlock (periodic table)Physical systemMalwarePoint (geometry)Cartesian coordinate systemSystem administratorTerm (mathematics)Turtle graphicsSet (mathematics)QuicksortSoftware frameworkCodeRevision controlDemo (music)Computer animation
TheoryCalculationProcess (computing)Remote procedure callDifferent (Kate Ryan album)Interpreter (computing)SoftwareVirtual machineDistribution (mathematics)MereologyPerspective (visual)Computer animationXML
Asynchronous Transfer ModeRead-only memoryCommunications protocolHierarchyMotion captureTheoryGUI widgetInformation securityAlpha (investment)File formatExecution unitMusical ensembleHierarchyInformation securityBounded variationMalwareComputer forensicsMotion captureMiniDiscBlock (periodic table)Asynchronous Transfer ModeGame controllerSemiconductor memoryMultiplication signMedical imagingGoodness of fitScripting languageVulnerability (computing)Cartesian coordinate systemComputer fileMechanism designTracing (software)Hash functionLevel (video gaming)Integrated development environmentAntivirus softwareComputer animationDiagram
TheoryBlogRevision controlInformation securityGame controllerData managementSoftware frameworkBitPhysical systemFeedbackOpticsSystem administratorAuthorizationTrailComputer animation
Run time (program lifecycle phase)Pauli exclusion principleInformation securityTheoryRevision controlScripting languageProcess (computing)1 (number)TwitterPauli exclusion principleRow (database)Self-organizationCore dumpBlock (periodic table)Information securitySoftware developerSensitivity analysisFeedbackComputer animation
Scripting languageBlock (periodic table)DisintegrationModule (mathematics)TheoryInformation securityConfiguration spaceInformation securityBitConfiguration spaceGroup actionKey (cryptography)Regulärer Ausdruck <Textverarbeitung>Physical systemUniform resource locatorMultiplication signSource codeModule (mathematics)Revision controlWeb 2.0Parameter (computer programming)Computer animation
TheoryPhysical systemView (database)Physical systemGroup actionTwitterRevision controlFile archiverReverse engineeringServer (computing)Incidence algebraData loggerDependent and independent variablesData storage deviceShared memoryComputer animation
TheoryGastropod shellLoginScripting languageBlock (periodic table)Compilation albumExecution unitRegulärer Ausdruck <Textverarbeitung>Event horizonVolumeRevision controlScripting languageSingle-precision floating-point formatTracing (software)Block (periodic table)Event horizonLoginContent (media)WindowRule of inferenceExpressionPrototypeStructural equation modelingComputer animation
Power (physics)DisintegrationTheoryWechselseitige InformationGastropod shellMalwareScripting languageBlock (periodic table)Connected spaceVirtual machinePerformance appraisalCartesian coordinate systemPoint (geometry)Core dumpMultiplication signWindowContent (media)Web 2.0Computer fileHeuristicMathematical analysisSystem callInterface (computing)10 (number)Electronic signature
TheoryEvent horizonLoginPublic-key cryptographyPhysical systemBlogContent (media)WindowInformationKey (cryptography)Tracing (software)Data managementShared memoryCryptographyPasswordScripting languageBlock (periodic table)Information securityEvent horizonVirtual machineComputer animation
MalwareEvent horizonInformation securityRevision controlScripting languageBlock (periodic table)Process (computing)DebuggerTheoryPhysical systemComputer fileKey (cryptography)Windows RegistryPower (physics)Windows PowerShellParameter (computer programming)Hash functionEvent horizonIncidence algebraPhysical systemPerspective (visual)Online helpWeightScripting languageBlock (periodic table)CircleRevision controlVirtual machineDependent and independent variablesPoint (geometry)Information securityControl flowComputer fileStapeldateiFigurate numberBlogOpen sourceSource codeMultiplication signTracing (software)Pattern languageIntrusion detection systemReverse engineeringWindowReal numberSlide ruleLatent heatComputer animation
TheoryProcess (computing)BlogEvent horizonView (database)Client (computing)Revision controlSemiconductor memoryTracing (software)Event horizonInformation securityPower (physics)Multiplication signDependent and independent variablesCore dumpComputer animation
Large eddy simulationTheoryMetropolitan area networkExecution unitProduct (business)Regulärer Ausdruck <Textverarbeitung>Fiber bundleComputer wormProjective planeGoodness of fitInformation securitySoftware frameworkLecture/ConferenceComputer animation
TheoryIntrusion detection systemComputer configurationSolid geometryScripting languageBlock (periodic table)Module (mathematics)BlogProcess (computing)Line (geometry)Motion blurGreen's functionPower (physics)Beer steinVariable (mathematics)Convex hullContent (media)Query languageInheritance (object-oriented programming)Inheritance (object-oriented programming)Integrated development environmentProcess (computing)WindowVariable (mathematics)Block (periodic table)Standard deviationDependent and independent variablesQuicksortTrailRegulärer Ausdruck <Textverarbeitung>Incidence algebraAuthenticationInformationTracing (software)Computer fileCanonical ensembleMessage passingSlide rule
TheoryPower (physics)Object (grammar)Physical systemRegulärer Ausdruck <Textverarbeitung>Client (computing)WeightUniformer RaumLink (knot theory)Element (mathematics)Block (periodic table)Scripting languageWindowComputer configurationPlastikkarteLocal GroupCountingWeb browserWordPhysical systemEscape characterString (computer science)WeightVariable (mathematics)QuicksortInternetworkingAliasingElectronic signatureWritingGame theoryUniform resource locatorOnline helpExpressionOperator (mathematics)Object (grammar)Web 2.0Scripting languageMereologyMathematical analysisShooting methodGoodness of fitCoefficient of determinationComputer-assisted translationFlagBoom (sailing)Regulärer Ausdruck <Textverarbeitung>Source code
TheoryExecution unitVariable (mathematics)Mach's principleBEEPExtension (kinesiology)Shape (magazine)String (computer science)ExpressionSpacetimeReal numberInternet forum2 (number)Information securityInternetworkingStandard deviationComputer animation
TheoryNormal (geometry)View (database)Client (computing)CodeNetwork topologyMultiplication signNeuroinformatikCodeFrequencyScripting languageMathematical analysis2 (number)MathematicsRight angleNumberElectronic mailing listSign (mathematics)Computer animation
Trigonometric functionsSimilarity (geometry)TheorySample (statistics)Genetic programmingLine (geometry)NumberFrequencySimilarity (geometry)Mathematical analysisAngleMathematicsCodeScripting languageResultantWeb pageTerm (mathematics)Group actionComputer animationDiagram
TheoryBlogCodePoint (geometry)Electronic signatureNetwork topologyScripting languageComputer fileProjective planeSoftware repositoryWord
TheoryGame theoryMereologyDigital photographyProjective planeMultiplication signScripting languageGame theoryComputer programDirectory serviceComputer fileComputer animation
Scripting languageSoftware frameworkCodeStatisticsTheorySimilarity (geometry)Negative numberPower (physics)StatisticsMetric systemScripting languageAuthorizationGroup actionMathematical analysisFrequencyDiagramComputer animation
TheoryFile formatGeneric programmingParameter (computer programming)Process (computing)Multi-agent systemPower (physics)FrequencyParameter (computer programming)Mathematical analysisToken ringComputing platformScripting languageRepresentation (politics)Loop (music)Abstract syntaxParsingComputer animation
Abstract syntax treeStatisticsTheoryContext awarenessType theoryDistribution (mathematics)Operator (mathematics)Formal languageWeightVariable (mathematics)Binary fileMedianEntropie <Informationstheorie>FrequencyPopulation densityRange (statistics)Asynchronous Transfer ModeLimit (category theory)FrequencyMathematical analysisScripting languagePattern languageNumberBinary codeOperator (mathematics)Decision theoryLinear regressionWeightStatement (computer science)Well-formed formulaComputer animation
TheoryLinear mapLinear regressionNetwork topologyLogistic distributionLimit (category theory)Linear regressionFunctional (mathematics)WeightMathematicsStatistical hypothesis testingRange (statistics)WordSlide ruleGradient descentCore dumpComputer animationDiagram
WeightExpected valueError messageTheoryStochasticGradient descentGradientSet (mathematics)WeightNeuroinformatikContent (media)BitWell-formed formulaGradient descentDifferent (Kate Ryan album)Algorithm
Negative numberTheoryContent (media)Menu (computing)Maxima and minimaDemo (music)Multiplication signPower (physics)Position operatorContent (media)Scripting languageASCIIBlock (periodic table)Decision theorySingle-precision floating-point formatEvent horizonMereologyBoolean algebraAbsolute valueMathematicsInstallation artMeasurementMathematical analysisComputer fileGraphical user interfaceWindowType theoryFocus (optics)Computer animation
TheoryCodeFlagReduction of orderBlock (periodic table)Dependent and independent variablesPhysical systemWindowRevision controlCategory of beingSurfaceIncidence algebraMereologyComputer animation
TheoryModule (mathematics)Level (video gaming)Traffic reportingMultiplication signDifferent (Kate Ryan album)TwitterPerspective (visual)Term (mathematics)ComputerRevision controlDisk read-and-write headStapeldateiComputer animation
TheoryInformation securityPhysical systemData managementExistential quantificationPower (physics)Computer animationLecture/Conference
TheoryDuality (mathematics)Physical systemBlock (periodic table)Formal languageAsynchronous Transfer ModeRevision controlProgrammschleifeScripting languageMereologyWeightCodeWindowComputer fileSign (mathematics)Variable (mathematics)Statement (computer science)Data managementInteractive televisionCartesian coordinate system
Data typeConfiguration spaceTheoryFormal languageElement (mathematics)Coma BerenicesObject (grammar)Category of beingType theoryData conversionWeightSocial classConstraint (mathematics)Formal languageComa BerenicesGaussian eliminationRevision controlScripting languageSurfaceCodeAsynchronous Transfer ModeError messageCuboid
TheorySurfaceFlagPhysical systemLatent heatConfiguration spaceReal numberRevision controlInformation securityRemote procedure callBlock (periodic table)Scripting languageDifferent (Kate Ryan album)Multiplication signNoise (electronics)BuildingLine (geometry)Point (geometry)Cartesian coordinate systemTracing (software)Event horizonWindowWordMobile appTime travelComputer animation
TheoryServer (computing)Service (economics)Web 2.0BitAuthorizationConnected spaceServer (computing)Physical systemSystem administratorComputer animation
Information securityTheoryIdentity managementGroup actionLeakVirtual machineService (economics)Virtual machineIdentity managementLeakCartesian coordinate systemMultiplication signData managementSurfaceWindowComputer animation
TheoryService (economics)Function (mathematics)Software maintenanceModul <Datentyp>Local ringHost Identity ProtocolIRIS-TSurfaceReduction of orderCloningTable (information)ExistenceFunctional (mathematics)Formal languageHydraulic jumpWindowSystem administratorTerm (mathematics)Multiplication signSurfaceReduction of orderLecture/ConferenceComputer animation
TheoryAddress spaceConstraint (mathematics)Daylight saving timeServer (computing)Process (computing)Error messagePhysical systemSurfaceConfiguration spaceSoftwareSystem administratorLecture/ConferenceComputer animation
TheoryFormal languageAsynchronous Transfer ModeDomain nameField (computer science)Scripting languageGroup actionTwitterBitNeuroinformatikVulnerability (computing)Perspective (visual)Virtual machineFunctional (mathematics)Physical systemConstraint (mathematics)Default (computer science)Fundamental theorem of algebraAsynchronous Transfer ModeControl flowFormal languageComputer animation
Process (computing)InjektivitätTheoryFunction (mathematics)SimulationSurfaceIP addressLocal ringData managementInternetworkingWeb pageoutputFunctional (mathematics)Content (media)InjektivitätFile formatRouter (computing)Physical systemVulnerability (computing)Computer animation
Regulärer Ausdruck <Textverarbeitung>InjektivitätTheoryFunction (mathematics)Process (computing)SpacetimeVulnerability (computing)outputInjektivitätAxiom of choiceCodeExpressionSocial classQuicksortWordOperator (mathematics)Form (programming)Content (media)Scripting languageParameter (computer programming)Formal languageSingle-precision floating-point formatDoubling the cubeLine (geometry)PlastikkarteDifferent (Kate Ryan album)MereologyParsingToken ringRevision controlEmailComputer animation
InjektivitätBlock (periodic table)Scripting languageTheoryFunction (mathematics)Process (computing)Power (physics)Image resolutionoutputString (computer science)Thermal expansionSummierbarkeitData typeOvalFluid staticsRaw image formatConnected spaceBlock (periodic table)Scripting languageString (computer science)outputInjektivitätExpandierender GraphSystem callWeightEscape characterType theoryEquivalence relationSocial classComputer animation
TheoryAbstract syntax treeModule (mathematics)Scripting languagePredicate (grammar)Rule of inferenceTerm (mathematics)Block (periodic table)Line (geometry)Object (grammar)ExpressionCategory of beingString (computer science)Computer animation
Scale (map)TheoryHydraulic jumpInjektivitätMereologyWritingPasswordScripting languageIntegrated development environmentModule (mathematics)Predicate (grammar)WindowSurfaceCodeBlogDirectory serviceRule of inferenceInjektivitätComputer animation
TheoryCodeDisintegrationVisual systemPresentation of a groupVisualization (computer graphics)Configuration spaceCodeEscape characterScripting languageInformation securityModule (mathematics)INTEGRALSemiconductor memoryLeakPoint (geometry)Inheritance (object-oriented programming)Computer animationLecture/Conference
TheoryInformation securitySoftware frameworkEnterprise architectureHierarchyGUI widgetHill differential equationComa BerenicesMultiplication signXML
Transcript: English(auto-generated)
Before I get talking, I'm going to be walking. So we're here for defending against PowerShell attacks. I'm Lee Holmes.
I'm the lead security architect for Azure management. And as you've 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 am an original developer on the PowerShell team. I'm an author of the PowerShell Cookbook.
But realistically, the expertise is you guys. 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 until 1045. 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, 9 AM, first day of school,
we're all pretty excited about things. All right, 10 o'clock, you're going to be like, do I have any important emails at work? Are my taxes done? Is my house burning down? By the end, you're going to be like, oh my god,
I missed my wife's anniversary twice and my parents' birthday. So I applaud your dedication to the craft. I really do. Now, as we start talking about PowerShell attacks, people talk about it in the news and stuff all the time, defending against PowerShell attacks.
But what does one actually look 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. Oh, did I hear a hoodie? No. Oh, hoodie, attacker, watch it. 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 gotta get away from 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 APIs,
any Windows APIs. I've seen shell code loaders and PE loaders fully leveraging this to take DLLs 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 certutil 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 compromise 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. All right, so what does a PowerShell attack look like? This is where it gets exciting.
Maybe not. All they did is they took some base64, but instead of calling certutil, they're calling PowerShell, and it's doing all the same stuff, but this time, rather than encoding the payload as an 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 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 doc 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 the real damage is. Now, a 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 compromise using PowerShell-encoded command, 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 XE, and they ran it, and that thing ran PowerShell,
or they got a doc, they double-clicked it, enabled a macro, and that ran PowerShell, or a DLL, or a spreadsheet. So the danger of the PowerShell attack is never the PowerShell attack, it's just that people are using it for post-compromise 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 ransomware, they're not the same people who are presenting at conferences like Black Hat and DEFCON. So the things you see here are pen testers and red teamers. Anybody making any of these toolkits 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 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. Attackers and red teamers, they have quality of life. What they've begun to realize is that compromising a machine and then writing batch files, it sucks. What you wanna be is just like any of us here, right?
Writing some PowerShell, using some cmdlets, enjoying those objects. So they're all coming from the quality of life perspective. But that's not the only option. They can run XEs like I showed you a million times, DLLs, all kinds of stuff that they can do on a system once they have access to it.
But this is what you kinda hear sometimes on the world. Let's block PowerShell. I hear about all these PowerShell attacks. Let's block it. So here's a question. How's that gonna 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 gonna change the actual problem. The problem isn't that they used the tool called PowerShell.exe. 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 gonna 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.exe, but here's the thing. PowerShell.exe is not just PowerShell.exe. Many people in this room already know that really the intelligence is behind system management automation, the automation set of DLLs and frameworks. The ISE hosts it. PowerShell.exe 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.exe, but researchers just made a new version called not PowerShell.exe, literally, NPS.exe. 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 logo, the old turtle logo. Now in terms of attack surface, this is a great example. Has anybody reviewed the MITRE attack framework?
Sweet. 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've got persistence, you've got elevation of privilege.
What are the actual techniques that attackers are using today in actual attacks on systems? So I'll save you 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 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 is 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 PowerShell 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 and 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're not protecting yourself against script kitty malware that's known to the entire industry as being bad, you've got a vulnerability. Coming up, you wanna talk about
putting application whitelisting at the very least in deny mode. Deny 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. 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 block list. So allow mode starts to let you to say, I'm only gonna 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 gonna 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, 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 forensically clean PowerShell, they're starting to worry at 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 phish 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 PowerShell's fault. The truth is it's not, but the truth is there are attacks that have leveraged PowerShell and this hurts us very deeply.
So we have invested 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 doubled down in version five and added tons and tons of PowerShell auditing and controls.
Has anybody here read the PowerShell hearts the blue team blog post? Okay, 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 gonna 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 till tomorrow. So we invested, 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. Anybody that's as good as PowerShell? I don't, I've really tried to be super open about this, like 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's 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 in Python work for Microsoft, and it turns out that some sensitive infrastructure in Microsoft runs Python. Seeing 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 into Python itself. So this is an example of doing Python,
like a Python attack. It's almost exactly the same thing that you see when people are concerned about PowerShell attacks. So this is being shepherded through the process right now is PEP 551. 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 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 551.
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 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 pipeline logging, it logs every cmdlet that's being run,
including the parameters being used for that cmdlet. So when you see people using sketchy versions of invoke web request, when you enable module and pipeline logging, you get to see exactly the URLs that were bound to that cmdlet. You get to see what was downloaded. This feature has existed since 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 PowerShell that's happening on your system. Another big one is system transcripts.
You know, the start transcript cmdlet in PowerShell. One of the mistakes we had made up until PowerShell version three, kind of four, was that it was baked into PowerShell.exe 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. As if you're behind the shoulders of an attacker or seeing what they're doing,
you can set up system transcripting to go against a share and then if anything ever happens, you can just audit 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's a Twitter account, InfoSec Taylor Swift. They've done this. They know they don't have the capability, but they went off and they deployed transcripting
and it's all dumping into a share, they're collecting it. It's really, really, they're 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 Windows event logs, you don't know what it does. Now one of the things that we added in PowerShell version five was the idea of script block logging.
So anytime anybody is 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 obfuscated techniques that I talked about where people are going off, running some PowerShell as 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 de-obfuscate this. Turns out that script block logging is the best de-obfuscator 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 was asked to evaluate it again. It did, and it went and ran this against the script block log, and you get to see very, very bare exactly what happened.
So you can dump these things into your sem or anything like that and have the ability to write much more robust rules that aren't perturbed by simple obfuscation 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 core team in Windows. Now the way that anti-malware traditionally works, you've got an application and anti-malware like defender and stuff, what it will do is it will sit on the machine and if PowerShell is trying to, for example, access a file,
it'll intercept 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, every time it's 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? 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 want to ask them, are they listening to the AMSI channel on Windows 10? Because anybody that's not is kinda stuck in the old ages. Now you start to ask yourself, okay, script block logging, I'm sold,
but I'm not really super sure on the security of all these scripts. Did somebody pack in a password? I don't really want an attacker with access to the machine to have access to passwords that were on all these things. So what we introduced was 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 key crypto. The idea there is that you have two keys. One key 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 rooftops,
deploy it 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 your 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 WEF,
Windows event forwarding. Jessica Payne has a bunch of great blog posts. If you're not already centralized in 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 FireEye linked to right here where they do talk about
here's how 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 five, we have something called automatic event logging.
So when we were developing PowerShell version five, 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 APIs, 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 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 event logging, automatic event logging, the source is on GitHub. Attackers can and will 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 around to enabling event logging, this is a chance that you're still gonna be able to extract some useful details about it. So from the perspective of the logging, my favorite story about the impact
of security transparency and visibility when it comes to PowerShell comes from FireEye. So there was a customer that they were responding to an incident response on. They were, this customer's being compromised by APT29. So this is Russian state-sponsored attacks.
You're literally going against a nearly infinitely funded government. 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 could remediate machines. So it was getting worse and it was getting worse. The problem is advanced attackers use that MITRE ATT&CK framework, not exactly it, but they just live off the land. They do whatever they can with whatever's available. So they were using Python, they were using Perl,
they were using PowerShell, batch files like WMI, WIMIC, 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 were 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 five. We also had, during that time, we had a version that was available for PowerShell version four. So they had installed the version for PowerShell version four. 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 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, any questions about some security transparency before I go on? We've 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 started off slow. Now there's, I think, five or six.
It's really starting to pick up steam, so we're getting some great responses from some vendors. Kaspersky for sure has got it. Cylance has it, so it's really starting to pick up some steam. Defender has had it since 2006, or no, 2016,
something like that. Obviously, we've worked 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 SM, you know, like Splunk or something like that,
and just do regexes 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 FireEye 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 regexes that people were using in their defense products. So this is us talking at 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 gave 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 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 gonna 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 gotta have logs. You gotta centralize them. You gotta collect them. That is absolutely the baseline. Make sure you're collecting 4688, which is the process command lines, PowerShell strip block logs. You could do this with the built-in Windows stuff. You can do this with sysinternals, sysmon.
Jeffrey is like, hey, he's not as good looking as me. I should be up there. I decided that there's just so much awesome for one slide. So the thing to remember, though, is enable your logs because attackers,
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 regexes 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 authentication talk itself.
This is an example from FIN8. 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 PowerShell'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. All it's just doing is setting a window title.
But what you can do is now launch a second process. That thing can scrape through WMI for any processes that were launched with a 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 are 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 use, 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 where you're using new object, system.net, web client, download string, whatever. This is almost canonical. You see this in the veil framework, powersploit, metasploit, it's everywhere,
almost exactly these terms. So as in a defender, you might say, all right, game's on, I'm blocking you. So let's take a look at that download cradle. What are your options? Well, invoke expression, I can tag 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. All right, 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 ya, 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 HTTPS, you can just fix that. You could do some string concatenation. Now HTTPS 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. Maybe I thought net web client was gonna be my savior. Nope, I can do the same sort of escape shenanigans there.
I can do string concatenation. I can do, put things in variables and run 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. Oh, shoot. 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 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 ya. Now the other thing to realize here is that wildcards, 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 cmdlet. So you thought you were writing a SIG 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 cmdlet name, PowerShell will think maybe you meant get if it fails to find it. So really, command. You've also got aliases, and the alias for get 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, invoke expression, boom. I'm gonna catch this. I don't know.
Invoke 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 the thing, this is the real kicker. When you do an analysis of broad use of PowerShell, you're not blocking invoke expression.
This is used in 3% 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 1%. But it's, you're not blocking invoke expression. So obviously, I sense 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, run invoke expression and 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 half of it, so whatever. So 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 PowerShell? Like, can't we just remove that obfuscation stuff? I'm like, have you seen anything in the real world? Like, together, yeah, it kinda sucks and it's kinda 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 APT32. This is like, literally stuff that they use in their attacks. If you think you're regexing 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 off the internet. Yeah. 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 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 no, like, ASCII characters, but there's not even any variable names. All the variable names are white space. If you think that's bad, what about if it was all white space? This is legit PowerShell. This works, you're proud of it. So as a defender, an attacker,
you're like, game over. 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 back ticks 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 obfuscated scripts. And you can see that these are quite different, so we might be onto something here. And there is a way to compare two lists of 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 college or high school. Cosine is the angle between 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 40, 50 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 40 numbers
that represent character frequency? This is pretty good stuff. If you take a look at most scripts, they're up in the 90% plus similarity range, where any of these obfuscated scripts, they were down here at like 0.157379.
Very, very dissimilar than the average script you might see on posh code. So it feels like we're onto 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 gray clustering above about 0.8.
They're all pretty similar to each other in terms of their character frequency. And what's left below that, that's honestly pretty reasonable to evaluate. That's maybe 30, 40 scripts out of 3,500. 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 a really promising result. It's pretty exciting. But the turn point is posh code isn't the only thing out there. We did need more data. That was based on some assumptions. We looked at the obfuscated 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 loves to do short one-liners. So we ran a little PowerShell contest a couple years ago called the Underhanded PowerShell Contest. There was one goal for this contest, which was we're gonna 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 add type and do it that way, or 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 detections.
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 was kind of identified
as being primarily PowerShell. So I did an analysis, and it was like 10 million repos. And so I 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, wait. This thing was going on. It's getting to like nine million, 9.5 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 100 million GitHub projects that I was gonna have to go against, and I did not have 11 months for this script to run. So I reached out to the kind folks at GitHub, and I was like, here's our problem. They're like, oh yeah, no problem. Some guy over lunch made a zip file of all the public projects that use PowerShell
and gave it to me, and I was like, oh man, but it was such a sweet script. Oh man. 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 one of the projects that we used. If you contributed to anything, PoshCode, GitHub, if you've ever posted anything publicly, thank you. You're on this.
I'll save some time at the end for you to find your name. Is anybody here part of this research? Put up your hands. I'm gonna take a photo for Daniel if you've ever done anything public. Awesome, he's gonna be so jazzed. What's that? Is that on Facebook? 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 their productivity, evidently,
so they pushed out a script across the whole enterprise that if they ever saw any built-in games running, they would kill them, and not only kill them, but kill them with spite. They would remove the file 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 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 four 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 were 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 obfuscated, 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 0.8 category,
there was a lot of stuff that we would've identified just with personal code review. We would've identified this as being obfuscated, but it wasn't detected as obfuscated by the character frequency analysis. So 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 of the power at our disposal. There's gotta 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 kind of an initial chopping of your script into segments.
It can recognize that something is 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 parse. But that opens up some really, really exciting opportunities when it comes to advanced analysis against any of these things.
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. 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 giving 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 simple 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, at first, you celebrate,
but then you realize, oh my god, 5,000 features, what am I gonna do with 5,000 features? I don't even wanna write them all down by hand, let alone make decisions based on them. And there's a technique out there. This is a, you can have a linear regression.
This formula represents a linear regression. And it's based on a very simple idea where you say all these 5,000 features, well, I don't know, some of them are more important than others. That's an easy statement to say. So I'm gonna assign weights that represent importance. So what I'm gonna do, every feature, multiply it by its weight or its importance.
In the end of that, I get just some number. And if it's 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 linear regression is a very common statistical technique. You can do a linear regression in Excel,
like it's just, it's everywhere. As you saw, 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 things it's between zero and one. Some things are between minus 100 and plus 200,000. So 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 it's really, really a simple concept. So look at this, another great math slide to make me look like a smart guy. It's awesome. I didn't answer the question though. You're like, Lee, 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, how important is a left paren? 250! How important is a plus operator? 512, like you just 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 our formula is wrong, 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 reduce them a little bit and you do this a lot, a lot, a lot. That's the benefit of computers is they'll just do things forever. You do 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? So we started off with 80 to 90% precision, 37% recall. So I'd be pretty happy if we got down to 90% precision, because that precision was awesome,
maybe 60% recall, 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 10 times better at this obfuscated content
with half the false positives that we did before. It's incredible. Anybody wanna see a demo? Yeah, absolutely. So revoke obfuscation, we published this work as Revoke Obfuscation. This is up on the PowerShell Gallery, Install 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 give a kid some paint and leave him 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 times and you'll see your name eventually.
And so it's all backed on cmdlets, of course. Everybody here knows it's gotta be cmdlets 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 get rvo script block cmdlet that ships as part of Revoke Obfuscation will automatically rejoin them for you. So then you can start, you can point it at an EVTX file or there is an ingestor 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 rvo obfuscation. So this is incredibly high performance going against the PowerShell ASTs,
going through all of that math and data science that we did and giving you a single boolean answer that you can run against a script block and decide whether this thing is obfuscated or not. Here you can see that it detected obfuscation here and it also shows all of the AST features that it extracted from that script
that helped it 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 whether a Revoke Obfuscation thought that the script block might have been obfuscated.
So what we did is we turned what attackers thought was like hey, I'm hiding, I'm obfuscating everything. We turned that into 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 part of Defender ATP? 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 Obfuscation has been incorporated into Defender ATP. You have Defender ATP installed on your systems and it will automatically flag
when it finds some PowerShell that it thinks is suspicious. You can have alerts 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 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 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 too, VBScript and stuff. So that's a feature that they're working on and it's influenced by some of these same techniques and some of the same approaches. Any other questions about that? Cool. So we've talked for some time about kind of the node level threats,
node level perspective in terms of logging and all this kind of stuff. I do wanna take a step back though and when we stop talking about node level stuff, it's important to step back and let's revisit what APT looks like. So Mandiant every year
does this thing called the mtrends report. So they report on trends in the environment, 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 TTPs, 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 psexec, 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 sometimes you just wanna hang your head up and cry. But here's the thing, I think this is setting up an interesting move and 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 to how can we move to starting to specialize our infrastructure and specialize 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 in 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 PowerShell play in all this?
This is the problem. I talked about the device guards, right? You block things. Well, the minute you think you're blocking everything, somebody finds like one little tweak on what you've blocked, 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 power of PowerShell and they know that if you're blocking all XEs and DLLs,
if you don't handle PowerShell somehow, then you're still providing full access to Win32 APIs and 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 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 trusted, you know, it's part of your official policy, it's allowed to run with full access to the .NET framework, everything that you're 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. 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 .NET 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, if somebody interactive on this system who is running unapproved or unseen code, well, they're allowed to run the script, but then they try to do that exact same code,
try to run some .NET, well, PowerShell's gonna block it. It says that that capability does not exist in constrained 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 constrained language mode and they're no better off than they were before. So some of the things in constrained language mode, we've blocked access to .NET, com objects,
Win32 APIs, add type, basically the things that attackers use to abuse PowerShell. You still have, you know, the funny thing about constrained language mode was when we were developing it, I enabled it and like honestly, just forget for days at a time. Using PowerShell, get process, stop processing,
all of that just day-to-day stuff just works, just cmdlets, basic scripting. And then after a couple days, I'd get this error that I can't do this thing because I'm in constrained language mode. And I was like, huh? And 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 RBAC-style sandbox. Like Jia, and I'm gonna talk about Jia in a second. It's not a sandbox. People can still run cmdlets. What it does do is prevent you from running
kind of just arbitrary code. So you're awesome, right? 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 when it comes to system configuration. We did a bunch of awesome stuff in PowerShell version five.
My regret to this day is that we didn't invent time travel. It's a problem. What we didn't do, we were not able to ship security fixes back into PowerShell version two, 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 dash version two 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 two, 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 v2 installed. You can uninstall the Windows feature, audit for it being launched. You can also use a device guard or app blocker policy
to block access to those DLLs and prevent that attack. Yeah, question. That's a good question. So the question is, what about an upgrade attack? So PowerShell six, is it the same thing as PowerShell version five? And I think the real interesting question is,
it's available on GitHub. Somebody, no matter what's in GitHub, can 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 whitelisted application protection policy.
If you didn't say that their 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 six, as we're shipping it, does have access to all these things. And so there's a couple differences when it comes to JIA,
but it's, what's there? So I've talked about JIA a couple times. Now the, oh, yeah, question. The question is, what if you're in a situation of not being able to remove version two
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 using it from a specific application,
then that thing, you can, in the PowerShell event log, see a 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 and specific systems. The important point to make, and I've realized this time and time again, is don't let the noise ruin your day. Instead of 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% 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 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 gonna go very deep into Jia. We have one that's gonna 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 gonna dig deep into it. If you really are interested in what we talk about today for Jia, 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 Delphi. He's the author of Mimikatz. He's actually a nice guy. I asked him if I could put this 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 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 they're an attacker using legitimate credentials that they stole, or maybe they're using 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.
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 says, no, use PowerShell Connect. You don't need RDP to connect to this server. So of course, he connects, enters pssetion, 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, access to knife. 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 about 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 axis. 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 nine to five, things like that. You've also got the capability restriction axis, and this is where JIA really jumps in.
So wouldn't it 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 magic. So this is the ideas behind Just Enough Administration.
Now, this isn't some newfangled thing. This is based on the stuff, 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 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're capable of restricting a PowerShell endpoint to do only what is allowed on that endpoint. You can export given known cmdlets. You can also write your own functions that export functionality that doesn't exist.
Another cool thing about Jia 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 constrain 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 Jia endpoint on that machine. Pretty sweet stuff. So this is what you get in terms of attack surface reduction with Jia. 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 razor-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 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 error messages.
My second job is in Photoshop. I'll tell you that. This was not from giphy.com. This is like 100% artisanal GIF just for you guys.
I said GIF in GIF, 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 Jia configuration ever. Look at this one. This person left open RDP. Somebody steals RDP creds.
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 Jia to configure a system, that all you've left is Jia. The other thing that sometimes comes up
is the commands that you expose can sometimes be your vulnerabilities. Now, shamefully, like this is a bit of humility here. This is an example that we gave in public documentation about how awesome Jia is. You see that we said the add computer, imagine you wanna 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 commandlet, add computer. So script junkie, I don't know if you follow him on Twitter or anything like that, but he pointed out that it turns out you didn't restrict the domain field at all.
So somebody abusing this commandlet 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 compromise that machine and then later join it back to your happy domain. So you do gotta be careful.
Like 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 of a Jia session.
So one of the things, when you create a Jia session, by default it's in no language mode. If you walk away with one thing when it comes to Jia is that is the only language mode you should allow. I talked about the benefits of constrain language mode, but it is not designed to be used at all with Jia.
The fundamental concept in Jia is it separates two things, commands coming from the user and commands coming from commands. So I told you, you could write a script that could do anything on the system and just expose that script for Jia 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 constrain language mode is write their own function and now that function has complete access to the system. So the one takeaway is don't break those defaults.
No 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 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 Jia, that's your people connecting with that function or 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's local management webpage 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 add user 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, concatenate 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, if you just took arbitrary user input and did it this way, well, the user input can be semicolon format C drive
or semicolon invoke expression, whatever. So there's an example of command injection when applied to PowerShell. Of course, PowerShell's 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 wine 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 SQL 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 to 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 commandlet parameter
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 they'll say, I know how to prevent this.
What I'm gonna do is I'm gonna 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 SQL injection
and it's sometimes you gotta do it, rarely you do, but sometimes you gotta do that. Here is the challenge. PowerShell was raised in a world of Outlook, OWA, WordPress, where all these things wanna 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 PowerShell's 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 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. Add type, kind of sucks. You know, add type, I've seen this a lot.
Add 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 SQL injection or the equivalent of PowerShell injection by doing C sharp injection, escape out of everything that you finished
and then start invoking and creating arbitrary .NET types and classes and then you're completely compromised. So that's a danger. And you might say, I 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, the PowerShell AST? I'm telling you, it's gold. If you haven't seen this one, 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 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 literally 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 the all AST nodes that invoke a member where 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 in the PowerShell gallery. So you can 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 PowerShell 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 a script analyzer. So you can just run invoke script analyzer with this module against a directory or a script or whatever, and it's gonna find out all the parts that you should be worrying about in 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, this is where it starts to get interesting. Visual Studio Code has integration with the script analyzer.
You can configure 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 got attackers into PowerShell was this promise of in memory only, this is like super legit, leak 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 Black Hat, DEFCON, Blue Hat is Microsoft's internal security conference, DerbyCon, like huge conferences where red teamers are up there and they're saying,
honestly, this stuff sketches me out, you gotta start running because your days are numbered if you're using PowerShell as an exploit technique. So 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 delivered 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 it's 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 Graeber, he's 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.