Scripting for Penetration TestingTable of ContentsScripting for Penetration Testing . 2Scripting for Penetration Testing . 3Recon & Enumeration Scripting Example -1 . 5Recon & Enumeration Scripting Example -2 . 7Exploit Checking -1 . 10Exploit Checking -2 . 12Data Exfiltration Scripts -1 . 15Data Exfiltration Scripts -2 . 17Notices . 20Page 1 of 20

Scripting for Penetration TestingScripting for Penetration Testing62**062 Next section will be a little bitabout how you can use this, being apen tester myself, some of the waysthat you can use scripting to helpyourself through a vulnerableassessment or a pen test.Page 2 of 20

Scripting for Penetration TestingScripting for Penetration TestingUsing scripts just make “sense”.Usually several tasks can be automated.Reconnaissance Enumeration Exploit checking Pivoting Data ExfiltrationIf it is a manual process going to be done a lot of times, it is aprime candidate for automation. 63**063 For pen testing, there's a lotof repetitive things. You're checkingout a network so you're trying toreach out to multiple hosts. Soscripting just makes a lot of sense.Once you figure out what it is youwant to try, you can make yourself areally good script, similar to whatChris made, and you can use itconsistently. The general stepsduring a pen test is you go out andyou do a reconnaissance. That'swhere you go out and find whathosts are alive out there, and thenyou do an enumeration of servicesand ports that are open. So you goout, check out what it is they haveavailable for you to actually possiblyPage 3 of 20

exploit, and then you use something,a tool, to go out and check anyexploits for the versions of theservices or the protocols that you'retrying to take advantage of.Pivoting is where you try to movefrom host to host, also known aslateral movement. So sometimes youcan do that in a scripted way as wellto make it a little easier. Sometimesthe pivoting involves cleaning upafter yourself. If you're not backtracking out and you're actuallymoving, kind of like leapfrogging to alily pad, if you will, and you want toclean up the box behind you, itmakes sense to use a script. As youmove to another box, you can wipeclean the box that you were onbefore.And of course the crown jewels ofwhatever it is that you're trying toget, data exfiltration-- try to get thatstuff out of their network so you canget it home and take a look at it. Alot of this can be done and is donefairly frequently, actually, in a manualway sometimes because, again, thatlaw of diminishing returns. If you'reonly hopping to one box or you'reonly doing something to one or twoboxes, sometimes trying to figure outhow to get it right in a script takes awhile, so. But for the most part, a lotof these, especially when you'redoing an assessment on a largenetwork, it makes a lot of sense touse batch scripting.Page 4 of 20

Recon & Enumeration Scripting Example -1Recon & Enumeration Scripting Example -1You “own” 20 Windows boxes and want to collect as muchinformation from them as possible. You could do it all by hand,individually OR, you could write a script. Inputs: List of IP addresses to run script on Outputs: Text file containing enumeration dataProcess Connect to each IP address (batch, net use). Copy and run enumeration utilities (net, sc, tasklist, enum,netdom, global, and anything else in the Windows ResourceKits). Output results to a text file (batch, redirection). Copy file to “dropbox” and delete all other traces of activity(batch).64**064 During the recon andenumeration stage, if you own orhave already compromised 20Windows boxes and you want to dosome data gathering, obviously itmakes sense to go ahead and writeyourself up a script. So this is writtenin such a way that the input is whatyou'll need-- a list of IP addresses torun your script on-- and then youroutput is what you're going to receiveat the end of it. It'll be a text file ortext files containing the enumerationdata that you're looking for.The process, kind of the step-bystep, is connecting to each IPaddress using net use and your batchPage 5 of 20

file, similar to the one that I justdemonstrated. You can copy and runenumeration utilities like the Net orSC or Enum. There's quite a few ofthem. Obviously the WindowsResource Kit has lots and lots of toolsthat are meant for good that can besubverted to do things that aren't sogood.For outputting the results to a textfile, you can use your redirection thatwe talked about in your batch script,and then copy your file to what wecall a drop box, but essentially it's ahost somewhere on the networkthat's usually in a quiet part of thenetwork that doesn't get used, andmaybe no one's even logged on sono one's going to catch you on thathost, so we use a drop box, and thenyou delete all traces of where you'vebeen. You can do that with a batchscript as well. Questions?Page 6 of 20

Recon & Enumeration Scripting Example -2Recon & Enumeration Scripting Example -2You are wandering around a facility and find an open workstation –quick – what do you do? You could try to remember what to do OR, you could put in your USB drive or CD and run a script. Inputs: None Outputs: Text file of enumeration data, user accounts created,“malware” installedProcess Run the enumeration from the last slide. Create a new user and try to add it to the local admins group(batch). Install your remote access program and set it to run (batch).65**065 So another way with reconand enumeration. This one's a littlemore, how shall I say, targetedopportunity. I used to also be part ofa red team organization, sosometimes we were told to checksomewhat physical security, andphysical security of course is if youwalk up to a machine and, "Oh, it'slogged in," and no one's there-- youdon't want to sit there and try tofigure out what it is you want to do.It would be very nice if you had ascript already built and put on a USBdrive that you could slap in and run,or perhaps even if they have a USBpolicy and you're not sure if theyhave a CD policy, you can put yourPage 7 of 20

script on a CD and you can run yourscript that way. No real inputs tospeak of because you should haveeverything on your drive or your CD,and then you can also get all yourenumeration data and perhaps someother things; if you're on thatmachine and it happens to be anadmin account, you might want to tryto set yourself up with an accountthat you can use later during theassessment. So you could end upwith user accounts created, andshould you have a Trojan orsomething that you want to use, youcan go ahead and install that.Very similar to the last slide, run thatenumeration to get the data, andthen, like I said, you want to goahead and try to create a user. Youmight be able to do that, and if youcan do that, go ahead and try to addthem to the local admin's group.That would be very nice. You can dothat in your batch script as well. Andthen the remote access program, orRemote Access Trojan, or RemoteAccess Tool-- the RAT-- you can goahead and set that in and get thatrunning so it can call back to yourhome machine or whatever you haveset up for that. Any questions?Chris, you have something to add?Instructor 2: I just have anexample of this. We used to do atraining scenario for all the pentesters, and we would sit them downat a computer and say, "Go." Andwhat we would ask them to do-what they were presented with onthe screen was a countdown timer.Page 8 of 20

"This box is rebooting in twominutes," but you've got completeaccess to it. You have a commandprompt, it's logged in, whatever-- dosomething. Whatever it is that youwant to do, you've got completeadministrator access. What wouldyou do? And we ran through thisparticular scenario, because out on apen test I actually had this happen. Iwent up to a box, moved the mouse,the window came up, I celebrated,and then panicked because uppopped the "You've received patches.This box will be rebooting in tenminutes." And I went, "Oh great.Well, what am I going to do?"So I'm sitting there scratching myhead trying to think through all thepossible things that I can dowatching this countdown clock gofrom ten minutes down to zero, andit struck me that, "Wow, I really wishI had a batch file with me," that Ihad a USB stick or something that Icould just plug in and run all myenumeration piece. I could add mylocal administrator account. I coulddo all this stuff, and instead here Iam trying to hand-jam it at thecommand prompt trying to do thingsquickly while this clock, thisdoomsday clock basically, is tickingdown until it's going to boot me offthe system. So just from a pentesting perspective, this was a reallygood case to run and it shows howbatch scripting-- you can take thatmoment of panic out of it. You onlyhave to know, "Plug in my USB stick,run my batch file," and the computerdoes the work for you. You don'tPage 9 of 20

even have to think about it. So,again, another really good usage of ascript.Instructor: Thank you.Exploit Checking -1Exploit Checking -1May be a little too “loud” for a pen test. Inputs: Metasploit exploit module to run, list of IP addresses Outputs: List of IP address exploit was successful onProcess Control loop (bash) Exploit checking (msfconsole) Output parsing (bash with redirects)66**066 Exploit checking. This maybe a little bit-- with the amount oftraffic and the type of traffic that'll betraversing a network, not unlike whatRyan said with Nessus doing itsthing, this may not be the best way,unless you get permission to run thiswith a pen test. But the implicit thingthat you will need is the Metasploitframework and the exploit module.I'm not sure if people are familiarPage 10 of 20

with Metasploit, but it is a pen testingframework that essentially makestesting exploits for a particular typeof-- if it's a Windows host, a Linuxhost, and a particular type of systemor software that's running-- you canput in all the required pieces of it andjust hit Exploit, and it'll actually sendeverything to the appropriate ports orwhatever it is. So it makesexploiting, or testing exploits, very,very easy. It's a very niceframework. It's very common.Now that it's so common, many ofthe attacks are blocked because theykind of know that people useMetasploit, not just for pen testingbut to try to hack other people.So you would Metasploit and a list ofIPs, and then you would-- youroutput-- you would end up with a listof IP addresses where the exploitswere successful. And the process ispretty simple. You set up a controlloop using bash because Metasploitruns on Linux. Specifically it runs onsomething called Kali Linux, which isa Debian-based Linux, and you goahead and do the exploit checkingwith-- the MSF is the MetasploitFramework console-- and then yououtput, or you parse the output, andyou can do your redirects and youcan send it to grep or to some ofthose other text parsing type of tools.That'd be helpful. Any questions onthis one?Page 11 of 20

Exploit Checking -2Exploit Checking -2Fuzzing is nothing more than a glorified script. Inputs: Target application or service Outputs: “User” input sent to the application or serviceProcess Generate list of “inputs” to send to the application (perl). Loop on each “input” (bash).– Transmit “input” to application (python).– Interpret output from application (bash).– Test to see if application has crashed (bash).– If crashed, store the “input” in a file (bash).67**067 Fuzzing is checking to see ifyou can bring down a particular pieceof software by sending either atremendous amount of data at it tosee if you can bring it to its knees, asit were, or if you send it input that it'snot expecting, that software couldfail, possibly will fail, and the key tothe fuzzing piece is if you can get itto fail and you can get control of theprogram in such a way that yourcode now starts to run in place ofwhat that old software was running.But fuzzing is essentially a script thatsits there and generates either a tonof output to send to it, or it createsthe specific type of input data. So forthis input, you just need a targetPage 12 of 20

application or a service that you pointthe fuzzing script at, and then youroutput is user input sent to theapplication or service. This is justcreating the actual-- what you'regoing to send it, is what you're usingthe script for.And the process. Generate a list ofinputs to send to the application, andthey recommend using Perl since Perlis good with manipulating text. Andthen loop on each input with bash,input meaning the data that you'regoing to send, mind you, to attackthe application. Then interpret theoutput, should you get some error orsomething like that, to figure outwhat's going on using your script,and then test to see if the applicationhas actually crashed. You could kindof look for some error levels, thatsort of thing, and if it has crashedyou can store the input that causedit, meaning the data that you actuallycreated-- the three million A's thatyou sent it, or whatever it is that youcreated that caused it. You want toput that in a file so you can save thatoff to the side. You could do thatmultiple times with that script, andthen once you figure out the types ofinput data that you sent it that youwant to use, you can do a little bitmore analysis on what that is andwhat you need to change in that tobe able to gain access to the programthat actually is vulnerable. Chris?Instructor 2: So I'll just add thecomment here that this is a Windowsscripting class. Why do you not seebatch or Windows script for any ofPage 13 of 20

those actions that are up there? Whyis it all bash, Python and Perl?Student: Command promptsisn't basically powerfulenough to run it and most of thesetools are UNIX tools anyways.Instructor 2: Because trying to dothese types of activities withWindows batch would be morefrustrating than useful, I think. Soback to what was said at-- whatWayne said at the beginning of themodule, pick the scripting languagethat's most applicable or most usefulfor what you're doing. It may not beWindows batch all the time. There'sprobably a better tool out there,depending on what you're doing. Sopick that, and don't try to kluge asolution into batch just because it'sthere.Instructor: Good point. Thankyou.Page 14 of 20

Data Exfiltration Scripts -1Data Exfiltration Scripts -1Want to prove data can be taken out of a network? Write a scriptthat does something like this: Input: List of files for any IP address, credentials Output: E-Mails of all the files in your gmail accountProcess Running on an internal host, copy files to a “dropbox” (net use). Compress and encrypt all the files (cabarc, encrypting tool) Break file archive into 5MB chunks (cabarc). Create email with 5MB data attachments (echo) Send emails to a gmail account (bmail).Another script will be needed on the receiving side to piece it allback together, decrypt it, and save off the individual files.68**068 For the data exfiltrationpiece, if you want to prove that datacan be taken out of a network, youcould write a script that deals withemail, and you would just need a listof files that you're trying for any IPaddress and credentials, and thenyou'd end up with some emails withall the files in your Gmail account orwhatever account that you end upsending it to.So the process is running on aninternal host, so this assumes thatyou're already inside. You copy filesto your drop box using the net usecommand, and then you compressand encrypt-- and this is kind of thePage 15 of 20

sneaker, more hacker-ish-- notnecessarily for vulnerabilityassessment or pen testing-- butdoing it this way is a sneakier way-compressing it first and thenencrypting it-- so when it does leavethe network it's not as easily read, orread at all, actually. You can usecabarc, an encrypting tool, and thenyou break the files, archive, into 5megabyte chunks. Again, trying togo low and slow and smaller sopeople can't see what you're doing.You create email with theseattachments that are 5 megabytes,and you can do that with echo, andthen you can send the emails towhatever account-- this says Gmailaccount-- to whatever accountoutside using bmail as your tool.So on the flipside of this, you do haveto have the receiving end of it. Soyou'll have to have another script onthe far side that'll piece it backtogether, decrypt it and then unzip itall that, so you'll have the individualfiles saved off that way. But this isjust kind of a sneaky way to try toprove that you can get informationout from a network. Any questions?Page 16 of 20

Data Exfiltration Scripts -2Data Exfiltration Scripts -2Want to test data leakage protection and see what it triggers on?Write a script for it.Input: Destination URL Output: HTTP posts & E-Mails of sensitive informationProcess Create junk files of various sizes containing “naughty” words(echo) – e.g., 1 SSN, 2 SSN, 10 SSN, 50 SSN, 1 HIPAA, 2 HIPAA, etc. Create random files of various sizes (VBS).– e.g., 5MB, 25MB, 50MB, 100MB, 250MB, etc. Post files to destination URL (VBS & Windows API).Create E-Mail with “naughty” words (echo).Send E-Mail (bmail).69**069 All righty. This next piecewith data exfiltration deals with-- thisis data leakage protection, but I'veheard it also called data lossprevention, DLP. If you're trying totest, this is a system that checks forimportant company information ordata leaving their network. Sothey're triggered based on a coupleof different things. Some of themhave kind of like dirty word searches,like if it says "proprietary" or whateverthe sensitivity or sensitive-- whateveryour important documents are markedwith. Sometimes it's looking for thosedirty words. If it's the government, if it'ssecret, top secret, it's looking for thosekind of words.Page 17 of 20

And then another piece of data lossprevention deals with the size of thefile flowing out. If you have some 5gigabyte file flowing out of yournetwork, it's kind of an obvious,"Why do we have such a thinghappening?" So that should trigger.So this is meant to be kind of a testfor that, whether to try to be sneakyand not be seen or, in most cases,this is actually to see at what levelwill your alarms go off, do youralarms go off, and at what level doyour alarms go off.So you'll need a destination URL.You'll want to set up basically a webserver on the far end on the outsidesomeplace that you can use to putyour information. The output, orwhat you'll end up having, is theHTTP posts and the email, so we'll bedoing it a couple different ways here.We'll be posting and we'll be sendingout emails.The process is you create junk filesthat have these dirty words. You talkto your customer and you find outwhat it is. Is it "top secret"? What isit? "Proprietary"-- that sort of thing-and you put those words into thefiles. Some of them could also be-- ifyou're a HIPAA-regulated source, youmight need to pay attention to yourprotected health information, yourPHI, your EPHI, the electronic versionof that. If certain words that yourcompany uses should trigger, youcheck that.Some basic stuff for PII, or personallyidentifiable information, as thePage 18 of 20

government calls it, are socialsecurity numbers. So you can justgen up a script that creates 50 fakesocial security numbers. You can justrun through them and see if puttingthose in files-- and then you can alsocreate random files of different sizes.Again, this is to test to see where thealarm-- if the alarm goes off, andwhere approximately the alarm goesoff when you're trying to send a giantfile outside. You can create thoseusing VB Script, and then you canpost the files to the destination URLusing VB Script and the WindowsAnd then also, in the same way thatwe just did the emails before, we cancreate the emails using echo, andyou just make sure you put in thekeywords that they're supposed to belooking for in the DLP system, andthen you send the email using bmail.Any questions?Page 19 of 20

NoticesNotices 2015 Carnegie Mellon UniversityThis material is distributed by the Software Engineering Institute (SEI) only to course attendees for theirown individual study.Except for the U.S. government purposes described below, this material SHALL NOT be reproduced orused in any other manner without requesting formal permission from the Software Engineering Institute [email protected] material was created in the performance of Federal Government Contract Number FA8721-05-C0003 with Carnegie Mellon University for the operation of the Software Engineering Institute, a federallyfunded research and development center. The U.S. government's rights to use, modify, reproduce,release, perform, display, or disclose this material are restricted by the Rights in Technical DataNoncommercial Items clauses (DFAR 252-227.7013 and DFAR 252-227.7013 Alternate I) contained inthe above identified contract. Any reproduction of this material or portions thereof marked with thislegend must also reproduce the disclaimers contained on this slide.Although the rights granted by contract do not require course attendance to use this material for U.S.government purposes, the SEI recommends attendance to ensure proper understanding.THE MATERIAL IS PROVIDED ON AN “AS IS” BASIS, AND CARNEGIE MELLON DISCLAIMS ANYAND ALL WARRANTIES, IMPLIED OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO,WARRANTY OF FITNESS FOR A PARTICULAR PURPOSE, RESULTS OBTAINED FROM USE OFTHE MATERIAL, MERCHANTABILITY, AND/OR NON-INFRINGEMENT).CERT is a registered mark owned by Carnegie Mellon University.6Page 20 of 20

Scripting for Penetration Testing 63 Scripting for Penetration Testing Using scripts just make “sense”. Usually several tasks can be automated. Reconnaissance Enumeration Exploit checking Pivoting Data Exfiltration If it is a manual process going to be done a lot of